diff --git a/.docker/Dockerfile b/.docker/Dockerfile new file mode 100644 index 0000000000..3968e76834 --- /dev/null +++ b/.docker/Dockerfile @@ -0,0 +1,14 @@ +FROM gitpod/workspace-full:latest + +USER root + +# Add here the instruction who needs root user + + +USER gitpod + +# Install dotnet core +ENV PATH=$HOME/.dotnet:$PATH +RUN wget https://dotnetwebsite.azurewebsites.net/download/dotnet-core/scripts/v1/dotnet-install.sh && \ + bash dotnet-install.sh -v 3.1.201 && \ + rm -rf dotnet-install.sh; diff --git a/.gitignore b/.gitignore index 3a1270b1d0..4cff1e6170 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ -.vscode/ .idea/ +.ionide/ node_modules/ temp/ diff --git a/.gitpod.yml b/.gitpod.yml new file mode 100644 index 0000000000..4875b1f773 --- /dev/null +++ b/.gitpod.yml @@ -0,0 +1,36 @@ +image: + file: .docker/Dockerfile + +tasks: + - before: dotnet restore + - init: npm install && npm run build compiler + +github: + prebuilds: + # enable for the master/default branch (defaults to true) + master: true + # enable for all branches in this repo (defaults to false) + branches: false + # enable for pull requests coming from this repo (defaults to true) + pullRequests: true + # enable for pull requests coming from forks (defaults to false) + pullRequestsFromForks: true + # add a check to pull requests (defaults to true) + addCheck: true + # add a "Review in Gitpod" button as a comment to pull requests (defaults to false) + addComment: true + # add a "Review in Gitpod" button to the pull request's description (defaults to false) + addBadge: false + # add a label once the prebuild is ready to pull requests (defaults to false) + addLabel: false + +vscode: + extensions: + - christian-kohler.path-intellisense@1.4.2:QnOrf5fk6KiVaQs4cNEP+w== + - wayou.vscode-todo-highlight@1.0.4:8IqxuxCVol2WnScJc5xVzg== + - mrmlnc.vscode-scss@0.9.0:/wXbNRm+2kunH5HbQqfnXA== + - PKief.material-icon-theme@3.9.2:xeHlNzPEF04yFqz/xKCD5w== + - Ionide.Ionide-fsharp@4.5.0:0qxXuhq6eO066etkNQrKCQ== + - zhuangtongfa.material-theme@3.2.2:jGTZwg0ChZg3eEKHC+UO+w== + - mhutchie.git-graph@1.21.0:zoSeoEOMfrwN0BMBC8VvqQ== + - eamodio.gitlens@10.2.0:GNDO73Cmp0fYDiLNxVkbsQ== diff --git a/.travis.yml b/.travis.yml index 22303cc2a2..030df1ebad 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,18 +1,27 @@ language: csharp os: linux -dist: trusty -sudo: false -dotnet: 2.1.403 +dist: xenial +sudo: required +# dotnet: 3.1.201 mono: none # cache: # yarn: true +addons: + snaps: + - name: dotnet-sdk + classic: true + channel: latest/stable + before_script: - - nvm install 10.15.0 - - nvm use 10.15.0 + - sudo snap alias dotnet-sdk.dotnet dotnet + - nvm install node + - nvm use node # # Update npm # - npm install -g npm script: + - dotnet --version + - node --version - npm install && npm test diff --git a/.vscode/launch.json b/.vscode/launch.json index 0655ad163b..8938cbee50 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -31,9 +31,9 @@ "type": "node", "request": "launch", "name": "Launch Quicktest.js", - "program": "${workspaceRoot}/src/tools/temp/QuickTest.js", + "program": "${workspaceRoot}/src/quicktest/bin/QuickTest.js", "args": ["--help"], - "cwd": "${workspaceRoot}/src/tools/temp", + "cwd": "${workspaceRoot}/src/quicktest", "stopOnEntry": true }, { @@ -48,19 +48,19 @@ { "type": "node", "request": "launch", - "name": "bench-compile tests (Node)", + "name": "bench-compile (Node)", "program": "${workspaceRoot}/src/fable-standalone/test/bench-compiler/out-node/app.js", - "args": ["${workspaceRoot}/tests/Main/Fable.Tests.fsproj", "out-tests", "--commonjs"], - // "args": ["${workspaceRoot}/../fable-test/fable-test.fsproj", "out-test", "--commonjs", "--optimize-fcs"], + // "args": ["${workspaceRoot}/tests/Main/Fable.Tests.fsproj", "out-tests", "--commonjs"], + "args": ["${workspaceRoot}/../fable-test/fable-test.fsproj", "out-test", "--commonjs", "--optimize-fcs"], "cwd": "${workspaceRoot}/src/fable-standalone/test/bench-compiler" }, { "type": "coreclr", "request": "launch", - "name": "bench-compile tests (.NET)", + "name": "bench-compile (.NET)", "program": "${workspaceFolder}/src/fable-standalone/test/bench-compiler/bin/Debug/netcoreapp2.1/bench-compiler.dll", - "args": ["${workspaceRoot}/tests/Main/Fable.Tests.fsproj", "out-tests", "--commonjs"], - // "args": ["${workspaceRoot}/../fable-test/fable-test.fsproj", "out-test", "--commonjs", "--optimize-fcs"], + // "args": ["${workspaceRoot}/tests/Main/Fable.Tests.fsproj", "out-tests", "--commonjs"], + "args": ["${workspaceRoot}/../fable-test/fable-test.fsproj", "out-test", "--commonjs", "--optimize-fcs"], "cwd": "${workspaceFolder}/src/fable-standalone/test/bench-compiler" }, { @@ -82,6 +82,7 @@ "request": "launch", "name": "Run Mocha Tests", "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha", + "sourceMaps": false, "args": [ "--no-timeouts", "--colors", diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000000..370ef698e9 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,18 @@ +{ + "files.exclude": { + "**/.git": true, + "**/.svn": true, + "**/.hg": true, + "**/CVS": true, + "**/.DS_Store": true, + "**/bin": true, + "**/obj": true, + "**/.fake": true, + "**/packages": true, + "**/node_modules": true, + "**/bower_components": true + }, + "files.trimTrailingWhitespace": true, + "files.trimFinalNewlines": true, + "gitlens.codeLens.enabled": false +} diff --git a/Fable.sln b/Fable.sln index 6dd7f8698d..debcb11e5e 100644 --- a/Fable.sln +++ b/Fable.sln @@ -1,9 +1,9 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 +# Visual Studio 15 VisualStudioVersion = 15.0.26124.0 MinimumVisualStudioVersion = 15.0.26124.0 -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Quicktest", "src\quicktest\Quicktest.fsproj", "{661A1972-0D06-46E8-958C-55325E5D520C}" +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Quicktest", "src\quicktest\QuickTest.fsproj", "{661A1972-0D06-46E8-958C-55325E5D520C}" EndProject Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Fable.Transforms", "src\Fable.Transforms\Fable.Transforms.fsproj", "{E55F3DA2-86B7-4E73-9700-EC6490043268}" EndProject @@ -30,9 +30,6 @@ Global Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {661A1972-0D06-46E8-958C-55325E5D520C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {661A1972-0D06-46E8-958C-55325E5D520C}.Debug|Any CPU.Build.0 = Debug|Any CPU @@ -143,4 +140,10 @@ Global {D8C8FBCB-54AF-49C3-93B1-5460668E32EC}.Release|x86.ActiveCfg = Release|Any CPU {D8C8FBCB-54AF-49C3-93B1-5460668E32EC}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {204581E6-42C5-4EE2-A4A9-713C32A17CF2} + EndGlobalSection EndGlobal diff --git a/README.md b/README.md index c50dc8e29c..e9cc03a380 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,16 @@ # F# |> BABEL -### The compiler that emits JavaScript you can be proud of! - [![Mono Build Status](https://travis-ci.org/fable-compiler/Fable.svg?branch=master "Mono Build Status")](https://travis-ci.org/fable-compiler/Fable) [![.NET Build Status](https://ci.appveyor.com/api/projects/status/vlmyxg64my74sik5/branch/master?svg=true ".NET Build Status")](https://ci.appveyor.com/project/alfonsogarciacaro/fable) [![npm version](https://badge.fury.io/js/fable-compiler.svg)](https://www.npmjs.com/package/fable-compiler) [![Join the chat at https://gitter.im/fable-compiler/Fable](https://badges.gitter.im/fable-compiler/Fable.svg)](https://gitter.im/fable-compiler/Fable?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/fable-compiler/Fable/) + [Follow us on Twitter!](https://twitter.com/FableCompiler) -Fable is an F# to JavaScript compiler powered by [Babel](https://babeljs.io/), designed to produce readable and standard code. [Check the website](http://fable.io) for more information and if you find the project useful, don't forget to give us a star! +Fable is an F# to JavaScript compiler powered by [Babel](https://babeljs.io/), designed to make F# a first-class citizen of the JavaScript ecosystem. [Check the website](http://fable.io) for more information and if you find the project useful, don't forget to give us a star! ## Getting started -Check [this page](https://fable.io/docs/getting_started.html). +Check [this page](https://fable.io/docs/2-steps/setup.html). ## Building @@ -19,8 +19,7 @@ Make sure the following **requirements** are installed in your system: - [dotnet SDK](https://www.microsoft.com/net/download/core) - [node.js](https://nodejs.org) with npm -Then run `npm install` to install dependencies and `npm run build` to start the build. Check [build.fsx](https://github.com/fable-compiler/Fable/blob/4839311afe4cfc3fd0849915c7cdf831ca1ab74c/build.fsx#L218) for other build targets. -For example: `npm run build compiler`. +Then run `npm install` to install dependencies and `npm run build` at the root folder to start the build. Check [build.fsx](https://github.com/fable-compiler/Fable/blob/4839311afe4cfc3fd0849915c7cdf831ca1ab74c/build.fsx#L218) for other build targets. For example: `npm run build compiler`. After that, if you want to quickly try changes to Fable source, please check `src/quicktest/QuickTest.fs`. @@ -47,7 +46,6 @@ Many of you are making really useful contributions that you also need for your o } ``` - **ATTENTION**: Remember to **build fable-library files beforehand**. This can be done just by building the whole project (see "Building" above) or running the `FableLibrary` FAKE target (after this, if you edit one of the src/js/fable-library JS or TS files, you can run the `FableLibraryTypescriptOnly` which is faster). ## Contributing diff --git a/appveyor.yml b/appveyor.yml index f28fac3744..69b95a8af0 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -4,22 +4,24 @@ init: build: verbosity: detailed -environment: - nodejs_version: "10.15.0" +# environment: +# nodejs_version: "10.16.3" # cache: # - "%LOCALAPPDATA%\\Yarn" # Install scripts. (runs after repo cloning) install: + # Get the latest stable version of .NET Core + - cmd: choco install dotnetcore-sdk --no-progress # Get the latest stable version of Node.js - - ps: Install-Product node $env:nodejs_version + - ps: choco install nodejs --no-progress # # Update npm # # There seems to be issues with npm 5.4 in Windows # # See https://github.com/npm/npm/issues/18380 # - npm install -g npm@6.1.0 -os: Visual Studio 2015 +os: Visual Studio 2019 # before_build: # - cmd: set PATH=C:\Program Files (x86)\MSBuild\14.0\Bin;%PATH% build_script: diff --git a/build.fsx b/build.fsx index e6dd36accb..bad9a3b5ba 100644 --- a/build.fsx +++ b/build.fsx @@ -8,18 +8,18 @@ open PublishUtils open System open System.Text.RegularExpressions open Fable.Core -open Fable.Import +open Fable.Core.JsInterop // Appveyor artifact let FABLE_BRANCH = "master" -let APPVEYOR_REPL_ARTIFACT_URL_PARAMS = "?branch=" + FABLE_BRANCH + "&pr=false" +let APPVEYOR_REPL_ARTIFACT_URL_PARAMS = "?branch=" + FABLE_BRANCH //+ "&pr=false" let APPVEYOR_REPL_ARTIFACT_URL = "https://ci.appveyor.com/api/projects/fable-compiler/Fable/artifacts/src/fable-standalone/fable-standalone.zip" + APPVEYOR_REPL_ARTIFACT_URL_PARAMS // ncave FCS fork -let FCS_REPO = "https://github.com/ncave/FSharp.Compiler.Service" -let FCS_REPO_LOCAL = "../FSharp.Compiler.Service_fable" +let FCS_REPO = "https://github.com/ncave/fsharp" +let FCS_REPO_LOCAL = "../fsharp_fable" let FCS_REPO_FABLE_BRANCH = "fable" let FCS_REPO_SERVICE_SLIM_BRANCH = "service_slim" @@ -29,6 +29,8 @@ type GhRealeases = err != null ? fail(err) : succeed(res)))""")>] abstract create: user: string * token: string * owner: string * repo: string * name: string * msg: string -> JS.Promise +let concurrently(commands: string[]): unit = importDefault "concurrently" + let cleanDirs dirs = for dir in dirs do removeDirRecursive dir @@ -64,39 +66,62 @@ let buildLibrary() = buildTypescript "src/fable-library" buildSplitter "src/fable-library" +let quicktest additionalCommands = + cleanDirs ["build/fable-library"] + concurrently [| + // Watch fable-library + yield "npx tsc --project src/fable-library --watch" + // Restart splitter on changes so latest fable-library and compiler are picked + yield "npx nodemon --watch src/quicktest -e \"fs\" --exec \"fable-splitter -c src/quicktest/splitter.config.js --run\"" + yield! additionalCommands + |] + let buildCompiler() = let projectDir = "src/fable-compiler" let libraryDir = "build/fable-library" cleanDirs [projectDir "dist"; projectDir "bin"] buildTypescript projectDir updateVersionInCliUtil() - run "dotnet publish -c Release -o ../fable-compiler/bin/fable-cli src/Fable.Cli/Fable.Cli.fsproj" + run "dotnet publish -c Release -o src/fable-compiler/bin/fable-cli src/Fable.Cli/Fable.Cli.fsproj" buildLibrary() copyDirRecursive libraryDir (projectDir "bin/fable-library") -let buildCompilerJs testLocal = +let buildCompilerJs() = let projectDir = "src/fable-compiler-js" - cleanDirs [projectDir "dist"] - if testLocal then - buildSplitterWithArgs projectDir "--test-local" - else - buildSplitter projectDir + let buildDir = "build/fable-compiler-js" + cleanDirs [buildDir; projectDir "dist"] + buildSplitterWithArgs projectDir ("--outDir " + buildDir + "/out") + run (sprintf "npx rollup %s/out/app.js --file %s/dist/app.js --format umd --name Fable" buildDir projectDir) + run (sprintf "npx terser %s/dist/app.js -o %s/dist/app.min.js --mangle --compress" projectDir projectDir) let buildStandalone() = - let projectDir = "src/fable-standalone" + let buildDir = "build/fable-standalone" let libraryDir = "build/fable-library" - cleanDirs [projectDir "dist"] - buildLibrary() + let projectDir = "src/fable-standalone" + let distDir = "src/fable-standalone/dist" + if pathExists libraryDir |> not then + buildLibrary() - // bundle.min.js - buildWebpack projectDir - fileSizeInBytes (projectDir "dist/bundle.min.js") / 1000 - |> printfn "Bundle size: %iKB" - // worker.min.js - buildWebpack "src/fable-standalone/src/Worker" + // cleanup + cleanDirs [buildDir; distDir] + mkDirRecursive distDir + // build + buildSplitterWithArgs projectDir ("--outDir " + buildDir + "/out-bundle") + buildSplitterWithArgs (projectDir + "/src/Worker") ("--outDir " + buildDir + "/out-worker") + // bundle + run (sprintf "npx rollup %s/out-bundle/Main.js --file %s/bundle.js --format umd --name __FABLE_STANDALONE__" buildDir buildDir) + run (sprintf "npx rollup %s/out-worker/Worker.js --file %s/worker.js --format esm" buildDir buildDir) + // minimize + run (sprintf "npx terser %s/bundle.js -o %s/bundle.min.js --mangle --compress" buildDir distDir) + // run (sprintf "npx terser %s/worker.js -o %s/worker.min.js --mangle --compress" buildDir distDir) + run (sprintf "npx webpack --entry ./%s/worker.js --output ./%s/worker.min.js --config ./%s/worker.config.js" buildDir distDir projectDir) + + // print bundle size + fileSizeInBytes (distDir "bundle.min.js") / 1000 |> printfn "Bundle size: %iKB" + fileSizeInBytes (distDir "worker.min.js") / 1000 |> printfn "Worker size: %iKB" // Put fable-library files next to bundle - let libraryTarget = projectDir "dist/fable-library" + let libraryTarget = distDir "fable-library" copyDirRecursive libraryDir libraryTarget // These files will be used in the browser, so make sure the import paths include .js extension let reg = Regex(@"^import (.*"".*)("".*)$", RegexOptions.Multiline) @@ -118,6 +143,31 @@ let buildStandalone() = // (if comMajor > staMajor || comMinor > staMinor then compilerVersion // else sprintf "%i.%i.%i%s" staMajor staMinor (staPatch + 1) comPrerelease) +let testJs() = + let projectDir = "src/fable-compiler-js" + let buildDir = "build/tests-js" + if not (pathExists "build/fable-standalone") then + buildStandalone() + if not (pathExists "build/fable-compiler-js") then + buildCompilerJs() + + cleanDirs [buildDir] + + // Link fable-compiler-js to local packages + runInDir projectDir "npm link ../fable-metadata" + runInDir projectDir "npm link ../fable-standalone" + + // Test fable-compiler-js locally + run ("node " + projectDir + " tests/Main/Fable.Tests.fsproj " + buildDir + " --commonjs") + run ("npx mocha " + buildDir + " --reporter dot -t 10000") + // and another test + runInDir "src/fable-compiler-js/test" "node .. test_script.fsx --commonjs" + runInDir "src/fable-compiler-js/test" "node bin/test_script.js" + + // Unlink local packages after test + runInDir projectDir "npm unlink ../fable-metadata && cd ../fable-metadata && npm unlink" + runInDir projectDir "npm unlink ../fable-standalone && cd ../fable-standalone && npm unlink" + let test() = if pathExists "build/fable-library" |> not then buildLibrary() @@ -128,13 +178,32 @@ let test() = runInDir "tests/Main" "dotnet run" if envVarOrNone "APPVEYOR" |> Option.isSome then - buildStandalone() - // Test fable-compiler-js locally - buildCompilerJs true - run "node src/fable-compiler-js tests/Main/Fable.Tests.fsproj build/tests-js --commonjs" - run "npx mocha build/tests-js --reporter dot -t 10000" - // runInDir "src/fable-compiler-js/test" "node .. test_script.fsx --commonjs" - // runInDir "src/fable-compiler-js/test" "node bin/test_script.js" + testJs() + +let coverage() = + // report converter + // https://github.com/danielpalme/ReportGenerator + // dotnet tool install dotnet-reportgenerator-globaltool --tool-path tools + if not (pathExists "./bin/tools/reportgenerator") && not (pathExists "./bin/tools/reportgenerator.exe") then + runInDir "." "dotnet tool install dotnet-reportgenerator-globaltool --tool-path bin/tools" + let reportGen = + if pathExists "./bin/tools/reportgenerator" then "bin/tools/reportgenerator" + else "bin\\tools\\reportgenerator.exe" + + if pathExists "build/fable-library" |> not then + buildLibrary() + + cleanDirs ["build/tests"] + buildSplitter "tests" + + // JS + run "npx nyc mocha build/tests --require source-map-support/register --reporter dot -t 10000" + runInDir "." (reportGen + " \"-reports:build/coverage/nyc/lcov.info\" -reporttypes:Html \"-targetdir:build/coverage/nyc/html\" ") + + // .NET + //runInDir "tests/Main" "dotnet build /t:Collect_Coverage" + cleanDirs ["build/coverage/netcoreapp2.0/out"] + runInDir "." (reportGen + " \"-reports:build/coverage/netcoreapp2.0/coverage.xml\" -reporttypes:Html \"-targetdir:build/coverage/netcoreapp2.0/html\" ") let downloadStandalone() = let targetDir = "src/fable-standalone/dist" @@ -177,8 +246,8 @@ let syncFcsRepo() = runInDir FCS_REPO_LOCAL "git pull" cheatWithDotnetSdkVersion (FCS_REPO_LOCAL "fcs") (fun () -> runBashOrCmd (FCS_REPO_LOCAL "fcs") "build" "") - copyFile (FCS_REPO_LOCAL "artifacts/bin/fcs/netstandard2.0/FSharp.Compiler.Service.dll") "../fable/lib/fcs/" - copyFile (FCS_REPO_LOCAL "artifacts/bin/fcs/netstandard2.0/FSharp.Compiler.Service.xml") "../fable/lib/fcs/" + copyFile (FCS_REPO_LOCAL "artifacts/bin/fcs/Release/netstandard2.0/FSharp.Compiler.Service.dll") "../fable/lib/fcs/" + copyFile (FCS_REPO_LOCAL "artifacts/bin/fcs/Release/netstandard2.0/FSharp.Compiler.Service.xml") "../fable/lib/fcs/" // fcs-fable runInDir FCS_REPO_LOCAL ("git checkout " + FCS_REPO_FABLE_BRANCH) @@ -186,7 +255,12 @@ let syncFcsRepo() = cheatWithDotnetSdkVersion (FCS_REPO_LOCAL "fcs") (fun () -> runBashOrCmd (FCS_REPO_LOCAL "fcs") "build" "CodeGen.Fable") copyDirRecursive (FCS_REPO_LOCAL "fcs/fcs-fable") "src/fcs-fable" - copyDirRecursive (FCS_REPO_LOCAL "src") "src/fcs-fable/src" + copyDirNonRecursive (FCS_REPO_LOCAL "src/absil") "src/fcs-fable/src/absil" + copyDirNonRecursive (FCS_REPO_LOCAL "src/fsharp") "src/fcs-fable/src/fsharp" + copyDirNonRecursive (FCS_REPO_LOCAL "src/fsharp/service") "src/fcs-fable/src/fsharp/service" + copyDirNonRecursive (FCS_REPO_LOCAL "src/fsharp/symbols") "src/fcs-fable/src/fsharp/symbols" + copyDirNonRecursive (FCS_REPO_LOCAL "src/ilx") "src/fcs-fable/src/ilx" + copyDirNonRecursive (FCS_REPO_LOCAL "src/utils") "src/fcs-fable/src/utils" removeFile "src/fcs-fable/.gitignore" let fcsFableProj = "src/fcs-fable/fcs-fable.fsproj" Regex.Replace( @@ -199,7 +273,7 @@ let packages = ["Fable.Core", doNothing "fable-babel-plugins", doNothing "fable-compiler", buildCompiler - "fable-compiler-js", (fun () -> buildCompilerJs false) + "fable-compiler-js", buildCompilerJs "fable-loader", doNothing "fable-metadata", doNothing "fable-publish-utils", doNothing @@ -220,9 +294,17 @@ let publishPackages restArgs = match argsLower with | "test"::_ -> test() +| "test-js"::_ -> testJs() +| "coverage"::_ -> coverage() +| "quicktest-fast"::_ -> run "npx fable-splitter -c src/quicktest/splitter.config.js --watch --run" +| "quicktest"::_ -> quicktest [] +| "check-sourcemaps"::_ -> + ("src/quicktest/Quicktest.fs", "src/quicktest/bin/Quicktest.js", "src/quicktest/bin/Quicktest.js.map") + |||> sprintf "nodemon --watch src/quicktest/bin/Quicktest.js --exec 'source-map-visualization --sm=\"%s;%s;%s\"'" + |> List.singleton |> quicktest | ("fable-library"|"library")::_ -> buildLibrary() | ("fable-compiler"|"compiler")::_ -> buildCompiler() -| ("fable-compiler-js"|"compiler-js")::_ -> buildCompilerJs false +| ("fable-compiler-js"|"compiler-js")::_ -> buildCompilerJs() | ("fable-splitter"|"splitter")::_ -> buildFableSplitter() | ("fable-standalone"|"standalone")::_ -> buildStandalone() | "download-standalone"::_ -> downloadStandalone() diff --git a/docs/FAQ.md b/docs/FAQ.md deleted file mode 100644 index 45bdf429df..0000000000 --- a/docs/FAQ.md +++ /dev/null @@ -1,233 +0,0 @@ -# FAQ - -This is the section for quick questions or to miss the holes in the documentation. Check the first question below to learn how you can help make the FAQ a great resource for Fable users. - -## General - -#### How can I add a new question? - -Make sure the question is not answered already either here or in the documentation. Then just [click here to edit this page in Github](https://github.com/fable-compiler/Fable/blob/master/docs/FAQ.md), add your question to the bottom and create a PR. Maintainers will write an answer and ask you if that solves the issue. If it does, the PR will be merged and the question will be added to the page so it can be referenced by other users. - -## Compiler - -#### How does Fable work? - -Fable has two "hearts" or sides: the .NET side is a daemon (a lightweight TCP server listening by default on port 61225) that waits for messages containing the F# source (.fs) or project (.fsproj) file to parse together with other options, and returns its contents in the form of a [Babel compliant AST](https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md). - -On the other side, there is a JS client that takes care of watching the files, communicating with the Fable daemon, resolving npm dependencies and outputting the actual JS code. At the time of writing there are three JS clients for Fable available: - -* [fable-loader](https://www.npmjs.com/package/fable-loader) is a plugin for [Webpack](https://webpack.js.org/), a powerful JS bundler with many handy features for development, like live reloading. -* [rollup-plugin-fable](https://www.npmjs.com/package/rollup-plugin-fable) for [Rollup](https://rollupjs.org/), another bundler focused on tree shaking. -* [fable-splitter](https://www.npmjs.com/package/fable-splitter) is a standalone tool which, unlike the previous ones, outputs separated files instead of a single bundle. - -> All the clients need a configuration file, click the links above for more details. - -The usual way to run a JS tool is a [package.json script](https://docs.npmjs.com/misc/scripts), so when you type `npm run build` this will invoke a command named "build" within the "scripts" property of the package.json file. For convenience, you can tell Fable to automatically start the package.json script and stop whenever it finishes: - -```shell -dotnet fable npm-run build -``` - -The Fable daemon must be invoked in a directory with an .fsproj including a [dotnet CLI tool reference](https://docs.microsoft.com/en-us/dotnet/core/tools/extensibility#per-project-based-extensibility) to the `dotnet-fable` Nuget package ([how to manage CLI tools with Paket](https://fsprojects.github.io/Paket/nuget-dependencies.html#Special-case-CLI-tools)). Run `dotnet fable --help` to know more about the Fable daemon specific options. - -It is also possible to run the Fable daemon and the JS clients separately if necessary: - -```shell -dotnet fable start - -# In a different shell -npm run build -``` - -#### Can I use Type Providers with Fable? - -Erasure Type Providers compatible with netstandard should be compatible with Fable, however they must generate code that doesn't call .NET APIs unsupported by Fable. At the time of writing there are no Type Providers designed for Fable available. - -#### How can I run a certain piece of code only in my production build? - -Using a [Compiler Directive](https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/compiler-directives). - -```fsharp -#if !DEBUG -printfn "only printing in production bundle" -#endif -``` - -You can define compilation directives using the `define` option in your Fable client. Latest [fable-loader](https://www.npmjs.com/package/fable-loader) will automatically define `DEBUG` when running Webpack in development mode. - -#### How can I make the compilation fail on incomplete pattern matches? - -Fable emits a warning on incomplete pattern matching expressions by default. To turn this particular warning into an error, add the following block to your project file: - -```xml - - - - - - 25 - - - - -``` - -This setting will not only make your compilation process fail on the command line, but will also make your IDE show an error at the location in the source code. - -To turn more warnings into errors, separate them with commas or semicolons. - -#### How are numbers compiled to JS? - -All numeric types including decimal become `JS number` (64-bit floating type), except for longs and big integers. Tom Clarke has documented in much more detail the differences in numeric types between .NET and JS, [check it out](../docs/numbers.md). - -## Fable.Core - -#### Which operators are used in Fable.Core? - -The `Fable.Core.JsInterop` module provides three main operators to interact with JS (all of them erased in generated JS code): `?` to dynamically access a property of an object, `!!` for unsafe casting (equivalent to `unbox`) and `!^` to pass arguments to a method accepting [Erased Unions](../docs/interacting.md#erase-attribute). - -```fsharp -open Fable.Core.JsInterop - -let jqElement = Browser.window?jQuery -let result: float = !!myObj?bar(5) -myObject?aProperty <- 30 - -let myMethod (arg: U3) = ... -myMethod !^5 // Same as: myMethod (U3.Case2 5) -``` - -#### How can I create a JS object? - -The `Fable.Core.JsInterop` module provides three helpers to create JS object. The first one, `createObj`, is used to dynamically create a JS object with string keys: - -```fsharp -open Fable.Core.JsInterop - -// { a: 5, b: aValue } -createObj [ - "a" ==> 5 - "b" ==> aValue -] -``` - -If you have an interface definition for the JS object you can just use an [F# Object Expression](https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/object-expressions). However, in many cases you only want to set a few fields, as when you pass options to a JS library, in those cases you can use `jsOptions` and a lambda to declare your object and have the compiler type-check the fields: - -```fsharp -type IFoo = - abstract foo: string with get, set - abstract bar: int with get, set - abstract optionalField: obj with get, set - -let myJsApi (options: IFoo) = importMember "foo-module" - -// JS: { foo: "foo", bar: 5 } -myJsApi (jsOptions(fun (o: IFoo) -> - o.foo <- "foo" - o.bar <- 5 -)) -``` - -If you use these helpers multiple times, you may want to define custom prefix operators for a terser syntax. For example: - -```fsharp -let inline (~%) x = createObj x -let inline (~%%) x = jsOptions x - -anotherJsApi %["bar" ==> 10] -myJsApi %%(fun o -> o.foo <- "foo") -``` - -Finally, some libraries (like React bindings) use F# unions to represent fields of JS objects. In those cases you can use `keyValueList` to transform a list of union cases to a JS object. - -```fsharp -type MyOptions = - | Foo of string - | Bar of int - -// JS: { foo: "foo", bar: 5 } -// Note we use the caseRules argument to change the first letter -keyValueList CaseRules.LowerFirst [ - Foo "foo" - Bar 5 -] -``` - -## Library authors - -#### Which files need to be included in the nuget package? - -The F# source code and the F# project file have to be included in the Nuget Package in a folder named `fable` within the package. This may sound complicated but it's only a matter of adding a couple of lines to your project file and let the `dotnet pack` command do all the rest. - -```xml - - - - -``` - -Possible cryptic error message when you don't include the project file and/or source files is `Cannot find root module`. - -## Unit tests - -#### How do I add unit tests to an existing project? - -Writing unit tests in Fable requires that the F# files are compiled to a format that can be processed by a nodejs test runner (f.ex Jest or Mocha). -In general you don't really need one bundle with all your test files, so the easiest way is to have every test file compiled as individual file. - -[fable-splitter](https://github.com/fable-compiler/Fable/tree/master/src/js/fable-splitter) can be used to achieve this. To run tests in nodejs you typically don't need ES5 code, the only real requirement is that ES6 modules are transpiled to commonjs (as this is the format nodejs uses). This can be achieve with the [@babel/plugin-transform-modules-commonjs](https://babeljs.io/docs/en/next/babel-plugin-transform-modules-commonjs.html) babel plugin. - -Example configuration for the fable splitter: - -```js -const path = require("path"); - -function resolve(relativePath) { - return path.join(__dirname, relativePath); -} - -module.exports = { - entry: resolve("test/test.fsproj"), - outDir: resolve("test/output"), - babel: { - "plugins": ["@babel/plugin-transform-modules-commonjs"] - }, - allFiles: true -} -``` - -Following F# test file `App.test.fs` -```fsharp -module MyApp.Test -open Fable.Import.Jest // See https://github.com/jgrund/fable-jest - -test "Demo test" <| fun () -> - expect.Invoke(sprintf "%d" 42).toEqual("42") -``` - -gets compiled to `test/output/App.test.js` -```js -"use strict"; -var _String = require("./fable-core.2.0.10/String"); - -test("Demo test", function () { - expect((0, _String.toText)((0, _String.printf)("%d"))(42)).toEqual("42"); -}); -``` - -which can be ran as normal JavaScript would run with our test runner (Jest in this example). - -Compile the test with an npm script to trigger the splitter when the Fable daemon runs: - -```json -{ - "scripts" : { - "test" : "jest", - "compile" : "fable-splitter --config splitter.config.js" - } -} -``` - -> npm run compile - -Once the compilation is complete: `npm test`. diff --git a/docs/compatibility.md b/docs/compatibility.md deleted file mode 100644 index 79bbd55656..0000000000 --- a/docs/compatibility.md +++ /dev/null @@ -1,120 +0,0 @@ -# .NET and F# Compatibility - -> This document applies to Fable 1. It will be updated soon with Fable 2 information. - -Fable provides support for some classes of .NET BCL (Base Class Library) and most of FSharp.Core library. When possible, Fable translates .NET types and methods to native JavaScript APIs for minimum overhead. - -## .NET Base Class Library - -The following classes are translated to JS and most of their methods (static and instance) should be available in Fable. - -.NET | JavaScript ---------------------------------------|---------------------------- -Numeric Types | number -Arrays | Array / Typed Arrays -Events | fable-core/Event -System.Boolean | boolean -System.Char | string -System.String | string -System.Guid | string -System.TimeSpan | number -System.DateTime | Date -System.DateTimeOffset | Date -System.Timers.Timer | fable-core/Timer -System.Collections.Generic.List | Array -System.Collections.Generic.HashSet | Set -System.Collections.Generic.Dictionary | Map -System.Text.RegularExpressions.Regex | RegExp -System.Lazy | fable-core/Lazy -System.Random | {} -System.Math | (native JS functions) - -The following static methods are also available: - -- `System.Console.WriteLine` (also with formatting) -- `System.Diagnostics.Debug.WriteLine` (also with formatting) -- `System.Diagnostics.Debug.Assert(condition: bool)` -- `System.Diagnostics.Debugger.Break()` -- `System.Activator.CreateInstance<'T>()` - -There is also support to convert between numeric types and to parse strings, check [the convert tests](https://github.com/fable-compiler/Fable/blob/master/tests/Main/ConvertTests.fs). - -### Caveats - -- All numeric types including `decimal` become JS `number` (64-bit floating type), except for `int64`, `uint64` and `bigint`. Check [this document](numbers.md) to learn more about the differences in numeric types between .NET and JS. -- Numeric arrays are compiled to [Typed Arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) when possible. -- No bound checks for numeric types (unless you do explicit conversions like `byte 500`) nor for array indices. -- `Regex` will always behave as if passed `RegexOptions.ECMAScript` flag (e.g., no negative look-behind or named groups). - -## FSharp.Core - -Most of FSharp.Core operators are supported, as well as formatting with `sprintf`, `printfn` or `failwithf` (`String.Format` is also available). -The following types and/or corresponding modules from FSharp.Core lib will likewise translate to JS: - -.NET | JavaScript -------------------|---------------------------------------------------------- -Tuples | Array -Option | (erased) -Choice | fable-core/Choice -Result | fable-core/Result -String | fable-core/String (module) -Seq | [Iterable](http://babeljs.io/docs/learn-es2015/#iterators-for-of) -List | fable-core/List -Map | fable-core/Map -Set | fable-core/Set -Async | fable-core/Async -Event | fable-core/Event (module) -Observable | fable-core/Observable (module) -Arrays | Array / Typed Arrays -Events | fable-core/Event -MailboxProcessor | fable-core/MailboxProcessor (limited support) - -The following F# semantic and syntactic features are also available: - -- Records and Unions -- Structural Equality/Comparison -- Comprehensions (seq, array, list) -- Computation Expressions -- Pattern Matching -- Active Patterns -- Object Expressions -- Units of measure - -### Caveats - -- Options are **erased** in JS (`Some 5` becomes just `5` in JS and `None` translates to `null`). This is needed for example, to represent TypeScript [optional properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#optional-properties). However in a few cases (like nested options) there is an actual representation of the option in the runtime. -- `Async.RunSynchronously` is not supported. -- `MailboxProcessor` is single-threaded in JS and currently only `Start`, `Receive`, `Post` and `PostAndAsyncReply` are implemented (`cancellationToken` or `timeout` optional arguments are not supported). - -## Object Oriented Programming - -**Classes** translate to [ES6 classes](https://github.com/lukehoban/es6features#classes) and most of their .NET/F# characteristics are available: properties, overloads, secondary constructors, custom operators, etc. - -**Inheritance** is possible and conforms to [ES2015 inheritance](https://github.com/lukehoban/es6features#classes) but must be done by calling the _primary constructor_ of the base class. Methods can be overridden and call the base implementation. Just note it won't be possible to access the base implementation from outside by casting the object. Example: - -```fsharp -type A() = - member x.Foo() = "Hello" - -type B() = - inherit A() - member x.Foo() = base.Foo() + " World!" - -// This prints "Hello World!" both in .NET and JS -B().Foo() |> printfn "%s" - -// This prints "Hello" in .NET and "Hello World!" in JS -(B() :> A).Foo() |> printfn "%s" -``` - -**Interface** methods are compiled as normal object methods and it's possible to test against an interface (e.g. `x :? IComparable`) for types defined in F# code. - -## Generics - -Generics are erased by default in generated code. However, it is still possible to access generic information in _inline_ functions (like `typeof<'T>`) or methods decorated with `PassGenerics` attribute. - -> **Caveat**: Functions decorated with `PassGenericsAttribute` may work unexpectedly if called from external JS code. - -## Reflection - -Fable keeps metadata information in the declared types to allow limited support for .NET/F# reflection. Please check the [Fable reflection tests](https://github.com/fable-compiler/Fable/blob/master/tests/Main/ReflectionTests.fs) to see which methods are available in latest versions. diff --git a/docs/getting_started.md b/docs/getting_started.md deleted file mode 100644 index 77829e4895..0000000000 --- a/docs/getting_started.md +++ /dev/null @@ -1,10 +0,0 @@ -# Getting started - -There are several starting points for Fable depending on your background: - -- If you want to upgrade an existing Fable 1 project to Fable 2, [check the migration guide](/blog/Migration-to-Fable2.html). -- If you want have a quick taste without installing anything, [try the online REPL](/repl). -- If you're interested in F# both on client and server sides, check the [SAFE stack](https://safe-stack.github.io/). -- If you're new to F#, you may want to learn the basics of the language first. There are [many resources for that](https://fsharp.org/): a nice overview of the language is provided by [the tour of F#](https://docs.microsoft.com/en-us/dotnet/fsharp/tour) and for a more extensive guide you can check the enjoyable [tutorials by Scott Wlaschin](https://fsharpforfunandprofit.com/). -- When you're ready to start a Fable project in your computer you can clone the [Fable 2 minimal sample](https://github.com/fable-compiler/fable2-samples/tree/master/minimal) and check its README for more detailed instructions. For a more complex sample, check the [Fulma demo](https://github.com/MangelMaxime/fulma-demo). -- For more Fable examples, videos... check the [awesome-fable](https://github.com/kunjee17/awesome-fable) list of Fable resources. \ No newline at end of file diff --git a/docs/img/fable_logo.png b/docs/img/fable_logo.png deleted file mode 100755 index e932591315..0000000000 Binary files a/docs/img/fable_logo.png and /dev/null differ diff --git a/docs/interacting.md b/docs/interacting.md deleted file mode 100644 index 304c114b42..0000000000 --- a/docs/interacting.md +++ /dev/null @@ -1,324 +0,0 @@ -# Interacting with JavaScript - -> This document applies to Fable 1. It will be updated soon with Fable 2 information. - -This page is structured as a reference document. For a more practical approach to Fable and JavaScript interop, please check [this great guide by Zaid Ajaj](https://medium.com/@zaid.naom/f-interop-with-javascript-in-fable-the-complete-guide-ccc5b896a59f). - -## Importing JavaScript code - -To use code from JS libraries first you need to import it into F#. For this Fables uses [ES2015 imports](https://developer.mozilla.org/en/docs/web/javascript/reference/statements/import), which can be later transformed to other JS module systems like `commonjs` or `amd` by Babel. - -There are two ways to declare ES2015 imports in the Fable: by using either the **Import attribute** or the **import expressions**. The `ImportAttribute` can decorate members, types or modules and works as follows: - -```fsharp -// Namespace imports -[] -// import * from "my-module" - -// Member imports -[] -// import { myFunction } from "my-module" - -// Default imports -[] -// import Express from "express" -``` - -> If the value is globally accessible in JS, you can use the `Global` attribute with an optional name parameter instead. - -Unless you are decorating an abstract member, you can use `jsNative` as a placeholder for the body: - -```fsharp -open Fable.Core.JsInterop - -[] -let Express: obj = jsNative -``` - -By opening `Fable.Core.JsInterop`, you will also have access to **import expressions**. These expressions are generic so be sure to make the type of the imported value explicit. - -```fsharp -open Fable.Core.JsInterop - -let buttons: obj = importAll "my-lib/buttons" -// import * as buttons from "my-lib/buttons" - -// It works for function declarations too -let getTheme(x: int): IInterface = importDefault "my-lib" -// import getTheme from "my-lib" - -let myString: string = importMember "my-lib" -// import { myString } from "my-lib" - -// Use just `import` to make the member name explicit -// as with the ImportAttribute -let aDifferentName: string = import "myString" "my-lib" -// import { myString } from "my-lib" -``` - -## Dynamic typing - -[Fable.Core.JsInterop](https://github.com/fable-compiler/Fable/blob/master/src/fable/Fable.Core/Fable.Core.fs) implements the F# dynamic operators so you can easily access an object property by name (without static check) -as follows: - -```fsharp -open Fable.Core.JsInterop - -printfn "Value: %O" jsObject?myProperty - -let pname = "myProperty" - -printfn "Value: %O" jsObject?(pname) // Access with a string reference - -jsObject?myProperty <- 5 // Assignment is also possible -``` - -When you combine the dynamic operator with application, Fable will destructure tuple arguments as with normal method calls. These operations can also be chained to replicate JS fluent APIs. - -```fsharp -let result = jsObject?myMethod(1, 2) -// var result = jsObject.myMethod(1, 2) - -chart - ?width(768.) - ?height(480.) - ?group(speedSumGroup) - ?on("renderlet", fun chart -> - chart?selectAll("rect")?on("click", fun sender args -> - Browser.console.log("click!", args)) -// chart -// .width(768) -// .height(480) -// .group(speedSumGroup) -// .on("renderlet", function (chart) { -// return chart.selectAll("rect").on("click", function (sender, args) { -// return console.log("click!", args); -// }); -// }); -``` - -> Note that in order to make this possible, the output of the `?` is an applicable value. If you don't want this behaviour, `unbox` or the `!!` dynamic cast operator: `let myValue: int = !!myObj?otherMethod("foo", "bar")` - -When you have to call a function with the `new` keyword in JS, use `createNew`. - -```fsharp -open Fable.Core.JsInterop - -let instance = createNew jsObject?myMethod(1, 2) -// var instance = new jsObject.myMethod(1, 2) -``` - -If you prefer member extensions rather than operators for dynamic typing, you can open `Fable.Core.DynamicExtensions` (Fable.Core 1.3.8 or higher) to have the methods `.Item` and `.Invoke` available on any object. - -```fsharp -open Fable.Core.DynamicExtensions - -let foo = obj() -let bar1 = foo.["b"] // Same as foo.Item("b") -foo.["c"] <- 14 -let bar2 = foo.Invoke(4, "a") -``` - -## Plain Old JavaScript Objects - -To create a plain JS object (aka POJO), use `createObj`: - -```fsharp -open Fable.Core.JsInterop - -let data = - createObj [ - "todos" ==> Storage.fetch() - "editedTodo" ==> None - "visibility" ==> "all" - ] -``` - -You can also create a JS object from an interface by using `createEmpty` and then assigning manually: - -```fsharp -type IMyInterface = - abstract foo: string with get, set - abstract bar: float with get, set - -let x = createEmpty // var x = {} -x.foo <- "abc" // x.foo = "abc" -x.bar <- 8.5 // val.bar = 8.5 -``` - -It is also possible to instantiate a plain JS object in a type-safe manner by declaring an F# record with the `Pojo` attribute: - -```fsharp -open Fable.Core - -type [] MyRecord = - { aNumber: int; aString: string } - -let foo = { aNumber = 5; aString = "bar" } -// var foo = { aNumber: 5, aString: "bar" } -``` - -This is mainly useful to interact with JS libraries that expect a plain object (e.g., for configuration) instead of a class instance. But do not abuse this solution because records with `Pojo` attribute will miss features like members or reflection. - -## Foreign interfaces - -Defining a foreign interface is trivial: just create an F# interface and the compiler will call its properties or methods by name. However doing this may be a bit tedious for JS libraries with large APIs, so we better take advantage of [Typescript definition files](http://definitelytyped.org) using [ts2fable](https://www.npmjs.com/package/ts2fable), a tool to translate `.d.ts` files into F# sources with Fable metadata. Check the [README file](https://www.npmjs.com/package/ts2fable) for installation and usage instructions. - -> Please note ts2fable is currently being updated and you may need to do some manual fixes after the automatic translation. - -You can find common definitions already parsed [here](https://github.com/fable-compiler/fable-import). These are already published in Nuget, where you can find more packages maintained by other contributors, usually [prefixed by Fable.Import](https://www.nuget.org/packages?q=Fable.Import). You can also find some other bindings and helpers in the [fable-awesome list](https://github.com/kunjee17/awesome-fable#libraries). - -## Special attributes - -There are some attributes available in the `Fable.Core` namespace to ease the interaction with JS. - -### Emit attribute - -You can use the `Emit` attribute to decorate a function. Every call to the function will then be replaced **inline** by the content of the attribute with the placeholders `$0`, `$1`, `$2`... replaced by the arguments. For example, the following code will generate JavaScript as seen below. - -```fsharp -open Fable.Core - -[] -let add (x: int) (y: string): float = jsNative - -let result = add 1 "2" -``` - -```js -var result = 1 + "2" -``` - -When you don't know the exact number of arguments you can use the following syntax: - -```fsharp -type Test() = - [] - member __.Invoke([] args: int[]): obj = jsNative -``` - -It's also possible to pass syntax conditioned to optional parameters. - -```fsharp -type Test() = - [] - member __.Item with get(): float = jsNative and set(v: float): unit = jsNative - - // This syntax means: if second arg evals to true in JS print 'i' and nothing otherwise - [] - member __.ParseRegex(pattern: string, ?ignoreCase: bool): Regex = jsNative -``` - -The content of `Emit` will actually be parsed by Babel so it will still be validated somehow. However, it's not advised to abuse this method, as the code in the template will remain obscure to Fable and may prevent some optimizations. - -### Erase attribute - -In TypeScript there's a concept of [Union Types](https://www.typescriptlang.org/docs/handbook/advanced-types.html#union-types) which differs from union types in F#. The former are just used to statically check a function argument accepting different types. In Fable, they're translated as **Erased Union Types** whose cases must have one and only one single data field. After compilation, the wrapping will be erased and only the data field will remain. To define an erased union type, just attach the `Erase` attribute to the type. Example: - -```fsharp -open Fable.Core - -[] -type MyErasedType = - | String of string - | Number of int - -myLib.myMethod(String "test") -``` - -```js -myLib.myMethod("test") -``` - -`Fable.Core` already includes predefined erased types which can be used as follows: - -```fsharp -open Fable.Core - -type Test() = - member x.Value = "Test" - -let myMethod (arg: U3) = - match arg with - | U3.Case1 s -> s - | U3.Case2 i -> string i - | U3.Case3 t -> t.Value -``` - -When passing arguments to a method accepting `U2`, `U3`... you can use the `!^` as syntax sugar so you don't need to type the exact case (the argument will still be type checked): - -```fsharp -open Fable.Core.JsInterop - -let myMethod (arg: U3) = ... - -// This is equivalent to: myMethod (U3.Case2 5) -myMethod !^5 - -// This doesn't compile, myMethod doesn't accept floats -myMethod !^2.3 -``` - -### StringEnum attribute - -Similarly, in TypeScript it's possible to define [String Literal Types](https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types) which are similar to enumerations with an underlying string value. Fable allows the same feature by using union types and the `StringEnum` attribute. These union types must not have any data fields as they will be compiled to a string matching the name of the union case. - -By default, the compiled string will have the first letter lowered. If you want to prevent this or use a different text than the union case name, use the `CompiledName` attribute: - -```fsharp -open Fable.Core - -[] -type MyStrings = - | Vertical - | [] Horizontal - -myLib.myMethod(Vertical, Horizontal) -``` - -```js -myLib.myMethod("vertical", "Horizontal") -``` - -## JSON serialization - -To make it easier to share types when you are also using F# on the server side, the functions `toJson` and `ofJson` are available in `Fable.Core.JsInterop` module. Unlike native JSON parsing in JavaScript, `ofJson` will _inflate_ a proper instance of the target type if the string is well formed, that is, if it is the result of serializing the same type with `toJson` or `Fable.JsonConverter` (see below). - -```fsharp -open Fable.Core.JsInterop - -type Tree = - | Leaf of int - | Branch of Tree list - member this.Sum() = - match this with - | Leaf i -> i - | Branch trees -> - trees |> Seq.map (fun x -> x.Sum()) |> Seq.sum - -let tree = Branch [Leaf 1; Leaf 2; Branch [Leaf 3; Leaf 4]] - -let json = toJson tree -let tree2 = ofJson json - -let typeTest = (box tree2) :? Tree // Type is kept -let sum = tree2.Sum() // Prototype members can be accessed -``` - -On the server side, you can use [Newtonsoft.Json](https://www.newtonsoft.com/json) + [Fable.JsonConverter](https://www.nuget.org/packages/Fable.JsonConverter/), as follows: - -```fsharp -open Newtonsoft.Json - -// Always use the same instance of the converter -// as it will create a cache to improve performance -let jsonConverter = Fable.JsonConverter() :> JsonConverter - -// Serialization -JsonConvert.SerializeObject(value, [|jsonConverter|]) - -// Deserialization -JsonConvert.DeserializeObject(json, [|jsonConverter|]) -``` - -If you need more fine-grained control over the JSON serialization, please use the [Thoth library](https://mangelmaxime.github.io/Thoth/json/decode.html). diff --git a/docs/numbers.md b/docs/numbers.md deleted file mode 100644 index d8b46b9415..0000000000 --- a/docs/numbers.md +++ /dev/null @@ -1,70 +0,0 @@ - -# Numbers in Fable - - - -Fable numbers are very nearly compatible with .NET semantics, but translating into Javascript types has consequences: - -* (non-standard) All floating point numbers are implemented as 64 bit (`double`). This makes `float` numbers more accurate than expected. -* (non-standard) Arithmetic integers of 32 bits or less are implemented with different truncation from that expected, as whole numbers embedded within `double`. -* (OK) Conversions between types are correctly truncated. -* (OK) Bitwise operations for 64 bit and 32 bit integers are correct and truncated to the appropriate number of bits. -* (non-standard) Bitwise operations for 16 bit and 8 bit integers use the underlying JavaScript 32 bit bitwise semantics. Results are not truncated as expected, and shift operands are not masked to fit the data type. -* (OK) Longs have a custom implementation which is identical in semantics to .NET and truncates in 64 bits: although it is quite slow. - -32 bit integers thus differ from .NET in two ways: - -* Underlying 52 bit precision, without expected truncation to 32 bits on overflow. Truncation can be forced if needed by `>>> 0`. -* On exceeding 52 bits absolute value floating point loses precision. So overflow will result in unexpected lower order 0 bits. - -The loss of precision can be seen in a single multiplication: - -``` -((1 <<< 28) + 1) * ((1 <<< 28) + 1) >>> 0 - -``` - -The multiply product will have internal double representation rounded to `0x0100_0000_2000_0000`. When it is truncated to 32 bits by -`>>> 0` the result will be `0x2000_0000` not the .NET exact lower order bits value of `0x2000_0001`. - -The same problem can be seen where repeated arithmetic operations make the internal (non-truncated) value large. For example a linear -congruence random number generator: - -``` -let rng (s:int32) = 10001*s + 12345 -``` - -The numbers generated by repeated application of this to its result will all be even after the 4th pseudo-random number, when `s` value exceeds 2^53: - -``` -let rec randLst n s = - match n with - | 0 -> [s] - | n -> s :: randLst (n-1) (rng s) - -List.iter (printfn "%x") (randLst 7 1) -``` - -The resulting printed list of pseudo-random numbers does not work in Fable: - -| Fable | .Net | -|-------:|------:| -|1|1| -|574a|574a -|d524223|d524223| -|6a89e98c|6a89e98c| -|15bd0684|15bd0685| -|3d8b8000|3d8be20e| -|50000000|65ba5527| -|0|2458c8d0| - -## Workarounds - -* When accurate low-order bit arithmetic is needed and overflow can result in numbers larger than 2^53 use `int64`, `uint64`, which use exact 64 bits, instead of `int32`, `uint32`. -* Alternately, truncate all arithmetic with `>>> 0` or `>>> 0u` as appropriate before numbers can get larger than 2^53:
`let rng (s:int32) = 10001*s + 12345 >>> 0` - - -## Printing - -One small change from .NET in `printf`, `sprintf`, `ToString`. Negative signed integers are printed in hexadecimal format as sign + magnitude, -in .Net they are printed as two's complement bit patterns. diff --git a/global.json b/global.json index 55e448dfe0..05d0ae3d21 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "2.1.403" + "version": "3.1.201" } } diff --git a/lib/fcs/FSharp.Compiler.Service.dll b/lib/fcs/FSharp.Compiler.Service.dll index 1654a1c4b4..04d6794292 100644 Binary files a/lib/fcs/FSharp.Compiler.Service.dll and b/lib/fcs/FSharp.Compiler.Service.dll differ diff --git a/lib/fcs/FSharp.Compiler.Service.xml b/lib/fcs/FSharp.Compiler.Service.xml index 558d8334c3..75bc92af30 100644 --- a/lib/fcs/FSharp.Compiler.Service.xml +++ b/lib/fcs/FSharp.Compiler.Service.xml @@ -5,3277 +5,3361 @@ Consider using 'yield!' instead of 'yield'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:31) + (Originally from src/fsharp/FSComp.txt:32) The byref pointer is readonly, so this write is not permitted. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1435) + (Originally from src/fsharp/FSComp.txt:1458) The value '%s' is not accessible from this code location - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:943) + (Originally from src/fsharp/FSComp.txt:960) + + + + + Use reference assemblies for .NET framework references when available (Enabled by default). + (Originally from src/fsharp/FSComp.txt:1492) The union cases or fields of the type '%s' are not accessible from this code location - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:942) + (Originally from src/fsharp/FSComp.txt:959) The union case '%s' is not accessible from this code location - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:944) + (Originally from src/fsharp/FSComp.txt:961) The value or constructor '%s' is not defined. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:8) + (Originally from src/fsharp/FSComp.txt:9) The value, namespace, type or module '%s' is not defined. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:9) + (Originally from src/fsharp/FSComp.txt:10) The value, constructor, namespace or type '%s' is not defined. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:7) + (Originally from src/fsharp/FSComp.txt:8) The type parameter %s is not defined. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:16) + (Originally from src/fsharp/FSComp.txt:17) The type '%s' is not defined in '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:12) + (Originally from src/fsharp/FSComp.txt:13) The type '%s' is not defined. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:11) + (Originally from src/fsharp/FSComp.txt:12) Maybe you want one of the following: - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:15) + (Originally from src/fsharp/FSComp.txt:16) The record label or namespace '%s' is not defined. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:13) + (Originally from src/fsharp/FSComp.txt:14) The record label '%s' is not defined. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:14) + (Originally from src/fsharp/FSComp.txt:15) The pattern discriminator '%s' is not defined. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:17) + (Originally from src/fsharp/FSComp.txt:18) The namespace or module '%s' is not defined. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:5) + (Originally from src/fsharp/FSComp.txt:5) The namespace '%s' is not defined. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:4) + (Originally from src/fsharp/FSComp.txt:4) + + + + + The type '%s' does not define the field, constructor or member '%s'. + (Originally from src/fsharp/FSComp.txt:7) The field, constructor or member '%s' is not defined. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:6) + (Originally from src/fsharp/FSComp.txt:6) The constructor, module or namespace '%s' is not defined. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:10) + (Originally from src/fsharp/FSComp.txt:11) The type '%s' implements 'System.IComparable'. Consider also adding an explicit override for 'Object.Equals' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:171) + (Originally from src/fsharp/FSComp.txt:172) The type '%s' implements 'System.IComparable' explicitly but provides no corresponding override for 'Object.Equals'. An implementation of 'Object.Equals' has been automatically provided, implemented via 'System.IComparable'. Consider implementing the override 'Object.Equals' explicitly - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:172) + (Originally from src/fsharp/FSComp.txt:173) The signature and implementation are not compatible because the respective type parameter counts differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:167) + (Originally from src/fsharp/FSComp.txt:168) The signature and implementation are not compatible because the type parameter '%s' has a constraint of the form %s but the implementation does not. Either remove this constraint from the signature or add it to the implementation. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:170) + (Originally from src/fsharp/FSComp.txt:171) The signature and implementation are not compatible because the declaration of the type parameter '%s' requires a constraint of the form %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:169) + (Originally from src/fsharp/FSComp.txt:170) The signature and implementation are not compatible because the type parameter in the class/signature has a different compile-time requirement to the one in the member/implementation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:168) + (Originally from src/fsharp/FSComp.txt:169) The override for '%s' was ambiguous - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:187) + (Originally from src/fsharp/FSComp.txt:188) The override '%s' implements more than one abstract slot, e.g. '%s' and '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:190) + (Originally from src/fsharp/FSComp.txt:191) No implementations of '%s' had the correct number of arguments and type parameters. The required signature is '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:186) + (Originally from src/fsharp/FSComp.txt:187) No implementation was given for '%s'. Note that all interface members must be implemented and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:195) + (Originally from src/fsharp/FSComp.txt:196) + + + + + No implementation was given for those members: %sNote that all interface members must be implemented and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'. + (Originally from src/fsharp/FSComp.txt:198) + + + + + No implementation was given for those members (some results omitted): %sNote that all interface members must be implemented and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'. + (Originally from src/fsharp/FSComp.txt:200) + + + + + No implementation was given for those members (some results omitted): %s + (Originally from src/fsharp/FSComp.txt:199) + + + + + No implementation was given for those members: %s + (Originally from src/fsharp/FSComp.txt:197) No implementation was given for '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:194) + (Originally from src/fsharp/FSComp.txt:195) The interface '%s' is included in multiple explicitly implemented interface types. Add an explicit implementation of this interface. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:192) + (Originally from src/fsharp/FSComp.txt:193) A named argument has been assigned more than one value - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:193) + (Originally from src/fsharp/FSComp.txt:194) More than one override implements '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:188) + (Originally from src/fsharp/FSComp.txt:189) The namespace or module attributes differ between signature and implementation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:184) + (Originally from src/fsharp/FSComp.txt:185) The method '%s' is sealed and cannot be overridden - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:189) + (Originally from src/fsharp/FSComp.txt:190) This method is over-constrained in its type parameters - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:185) + (Originally from src/fsharp/FSComp.txt:186) The member '%s' matches multiple overloads of the same method.\nPlease restrict it to one of the following:%s. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1342) + (Originally from src/fsharp/FSComp.txt:1360) The member '%s' does not have the correct number of method type parameters. The required signature is '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:197) + (Originally from src/fsharp/FSComp.txt:202) The member '%s' does not have the correct number of arguments. The required signature is '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:196) + (Originally from src/fsharp/FSComp.txt:201) The member '%s' does not have the correct kinds of generic parameters. The required signature is '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:198) + (Originally from src/fsharp/FSComp.txt:203) The member '%s' cannot be used to implement '%s'. The required signature is '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:199) + (Originally from src/fsharp/FSComp.txt:204) Invalid value - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:166) + (Originally from src/fsharp/FSComp.txt:167) + + + + + Interface member '%s' does not have a most specific implementation. + (Originally from src/fsharp/FSComp.txt:1491) The struct, record or union type '%s' has an explicit implementation of 'Object.GetHashCode' or 'Object.Equals'. You must apply the 'CustomEquality' attribute to the type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:173) + (Originally from src/fsharp/FSComp.txt:174) The struct, record or union type '%s' has an explicit implementation of 'Object.GetHashCode'. Consider implementing a matching override for 'Object.Equals(obj)' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:174) + (Originally from src/fsharp/FSComp.txt:175) The struct, record or union type '%s' has an explicit implementation of 'Object.Equals'. Consider implementing a matching override for 'Object.GetHashCode()' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:175) + (Originally from src/fsharp/FSComp.txt:176) Duplicate or redundant interface - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:191) + (Originally from src/fsharp/FSComp.txt:192) The implicit instantiation of a generic construct at or near this point could not be resolved because it could resolve to multiple unrelated types, e.g. '%s' and '%s'. Consider using type annotations to resolve the ambiguity - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:162) + (Originally from src/fsharp/FSComp.txt:163) Could not resolve the ambiguity in the use of a generic construct with an 'unmanaged' constraint at or near this position - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1057) + (Originally from src/fsharp/FSComp.txt:1074) Could not resolve the ambiguity inherent in the use of a 'printf'-style format string - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:163) + (Originally from src/fsharp/FSComp.txt:164) Could not resolve the ambiguity in the use of a generic construct with an 'enum' constraint at or near this position - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:164) + (Originally from src/fsharp/FSComp.txt:165) Could not resolve the ambiguity in the use of a generic construct with a 'delegate' constraint at or near this position - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:165) + (Originally from src/fsharp/FSComp.txt:166) The type '%s' is not accessible from this code location - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:941) + (Originally from src/fsharp/FSComp.txt:958) union case - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:916) + (Originally from src/fsharp/FSComp.txt:933) property - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:921) + (Originally from src/fsharp/FSComp.txt:938) patvar - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:926) + (Originally from src/fsharp/FSComp.txt:943) and %d other overloads - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:915) + (Originally from src/fsharp/FSComp.txt:932) namespace/module - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:929) + (Originally from src/fsharp/FSComp.txt:946) namespace - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:927) + (Originally from src/fsharp/FSComp.txt:944) module - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:928) + (Originally from src/fsharp/FSComp.txt:945) generated type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:933) + (Originally from src/fsharp/FSComp.txt:950) generated property - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:932) + (Originally from src/fsharp/FSComp.txt:949) Full name - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:911) + (Originally from src/fsharp/FSComp.txt:928) also from %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:931) + (Originally from src/fsharp/FSComp.txt:948) from %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:930) + (Originally from src/fsharp/FSComp.txt:947) field - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:919) + (Originally from src/fsharp/FSComp.txt:936) extension - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:922) + (Originally from src/fsharp/FSComp.txt:939) event - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:920) + (Originally from src/fsharp/FSComp.txt:937) custom operation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:923) + (Originally from src/fsharp/FSComp.txt:940) Calls - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1246) + (Originally from src/fsharp/FSComp.txt:1264) argument - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:924) + (Originally from src/fsharp/FSComp.txt:941) anonymous record field - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:925) + (Originally from src/fsharp/FSComp.txt:942) active recognizer - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:918) + (Originally from src/fsharp/FSComp.txt:935) active pattern result - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:917) + (Originally from src/fsharp/FSComp.txt:934) \nA tuple type is required for one or more arguments. Consider wrapping the given arguments in additional parentheses or review the definition of the interface. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:32) + (Originally from src/fsharp/FSComp.txt:33) The specified .NET Framework version '%s' is not supported. Please specify a value from the enumeration Microsoft.Build.Utilities.TargetDotNetFrameworkVersion. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1099) + (Originally from src/fsharp/FSComp.txt:1115) Unexpected Expr.TyChoose - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:951) + (Originally from src/fsharp/FSComp.txt:968) Note: Lambda-lifting optimizations have not been applied because of the use of this local constrained generic function as a first class value. Adding type constraints may resolve this condition. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:952) + (Originally from src/fsharp/FSComp.txt:969) The 'VolatileField' attribute may only be used on 'let' bindings in classes - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:656) + (Originally from src/fsharp/FSComp.txt:669) Volatile fields must be marked 'mutable' and cannot be thread-static - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:711) + (Originally from src/fsharp/FSComp.txt:724) A declaration may only be given a value in a signature if the declaration has the [<Literal>] attribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:709) + (Originally from src/fsharp/FSComp.txt:722) In sequence expressions, multiple results are generated using 'yield!' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:631) + (Originally from src/fsharp/FSComp.txt:644) Character range matches have been removed in F#. Consider using a 'when' pattern guard instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:564) + (Originally from src/fsharp/FSComp.txt:577) 'use' expressions may not be used in queries - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1263) + (Originally from src/fsharp/FSComp.txt:1281) The use of 'let! x = coll' in sequence expressions is not permitted. Use 'for x in coll' instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:629) + (Originally from src/fsharp/FSComp.txt:642) This declaration is not supported in recursive declaration groups - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1332) + (Originally from src/fsharp/FSComp.txt:1350) This attribute cannot be used in this version of F# - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:683) + (Originally from src/fsharp/FSComp.txt:696) 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. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1266) + (Originally from src/fsharp/FSComp.txt:1284) Arguments to query operators may require parentheses, e.g. 'where (x > y)' or 'groupBy (x.Length / 10)' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1274) + (Originally from src/fsharp/FSComp.txt:1292) Unrecognized attribute target. Valid attribute targets are 'assembly', 'module', 'type', 'method', 'property', 'return', 'param', 'field', 'event', 'constructor'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:673) + (Originally from src/fsharp/FSComp.txt:686) The unnamed arguments do not form a prefix of the arguments of the method called - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:650) + (Originally from src/fsharp/FSComp.txt:663) Unknown union case - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:503) + (Originally from src/fsharp/FSComp.txt:516) Unit-of-measure cannot be used in type constructor application - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:540) + (Originally from src/fsharp/FSComp.txt:553) This union case takes one argument - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:558) + (Originally from src/fsharp/FSComp.txt:571) The union case named '%s' conflicts with the generated type '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1078) + (Originally from src/fsharp/FSComp.txt:1095) Union case/exception field '%s' cannot be used more than once. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1301) + (Originally from src/fsharp/FSComp.txt:1319) This union case expects %d arguments in tupled form - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:559) + (Originally from src/fsharp/FSComp.txt:572) This union case does not take arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:557) + (Originally from src/fsharp/FSComp.txt:570) The union case '%s' does not have a field named '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1297) + (Originally from src/fsharp/FSComp.txt:1315) Uninitialized 'val' fields must be mutable and marked with the '[<DefaultValue>]' attribute. Consider using a 'let' binding instead of a 'val' field. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:712) + (Originally from src/fsharp/FSComp.txt:725) Unexpected type arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:549) + (Originally from src/fsharp/FSComp.txt:562) Unexpected %s in type expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:543) + (Originally from src/fsharp/FSComp.txt:556) Unexpected / in type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:548) + (Originally from src/fsharp/FSComp.txt:561) Unexpected source-level property specification - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:514) + (Originally from src/fsharp/FSComp.txt:527) Unexpected source-level property specification in syntax tree - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:508) + (Originally from src/fsharp/FSComp.txt:521) Unexpected SynMeasure.Anon - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:464) + (Originally from src/fsharp/FSComp.txt:477) Unexpected expression at recursive inference point - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:493) + (Originally from src/fsharp/FSComp.txt:506) Unexpected Const_uint16array - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:469) + (Originally from src/fsharp/FSComp.txt:482) Unexpected Const_bytearray - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:470) + (Originally from src/fsharp/FSComp.txt:483) Unexpected condition in imported assembly: failed to decode AttributeUsage attribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:672) + (Originally from src/fsharp/FSComp.txt:685) Unexpected big rational constant - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:467) + (Originally from src/fsharp/FSComp.txt:480) The field '%s' has been given a value, but is not present in the type '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:596) + (Originally from src/fsharp/FSComp.txt:609) Unable to parse format string '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:574) + (Originally from src/fsharp/FSComp.txt:587) Types cannot inherit from multiple concrete types - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:762) + (Originally from src/fsharp/FSComp.txt:775) Types cannot contain nested type definitions - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:742) + (Originally from src/fsharp/FSComp.txt:755) Struct types are always sealed - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:774) + (Originally from src/fsharp/FSComp.txt:787) Record types are always sealed - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:772) + (Originally from src/fsharp/FSComp.txt:785) Enum types are always sealed - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:776) + (Originally from src/fsharp/FSComp.txt:789) Delegate types are always sealed - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:775) + (Originally from src/fsharp/FSComp.txt:788) Discriminated union types are always sealed - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:771) + (Originally from src/fsharp/FSComp.txt:784) Assembly code types are always sealed - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:773) + (Originally from src/fsharp/FSComp.txt:786) The type '%s' is used in an invalid way. A value prior to '%s' has an inferred type involving '%s', which is an invalid forward reference. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:799) + (Originally from src/fsharp/FSComp.txt:812) This type test or downcast will erase the provided type '%s' to the type '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1185) + (Originally from src/fsharp/FSComp.txt:1203) This type test or downcast will ignore the unit-of-measure '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1090) + (Originally from src/fsharp/FSComp.txt:1106) This type test with a provided type '%s' is not allowed because this provided type will be erased to '%s' at runtime. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1187) + (Originally from src/fsharp/FSComp.txt:1205) This type requires a definition - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:759) + (Originally from src/fsharp/FSComp.txt:772) The type parameters inferred for this value are not stable under the erasure of type abbreviations. This is due to the use of type abbreviations which drop or reorder type parameters, e.g. \n\ttype taggedInt<'a> = int or\n\ttype swap<'a,'b> = 'b * 'a.\nConsider declaring the type parameters for this value explicitly, e.g.\n\tlet f<'a,'b> ((x,y) : swap<'b,'a>) : swap<'a,'b> = (y,x). - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:498) + (Originally from src/fsharp/FSComp.txt:511) Type parameter cannot be used as type constructor - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:544) + (Originally from src/fsharp/FSComp.txt:557) This type parameter has been used in a way that constrains it to always be '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:497) + (Originally from src/fsharp/FSComp.txt:510) This value, type or method expects %d type parameter(s) but was given %d - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:520) + (Originally from src/fsharp/FSComp.txt:533) type or module - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:744) + (Originally from src/fsharp/FSComp.txt:757) The type '%s' is not an interface type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:719) + (Originally from src/fsharp/FSComp.txt:732) This type is not an interface type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:737) + (Originally from src/fsharp/FSComp.txt:750) This type is not a record type. Values of class and struct types must be created using calls to object constructors. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:624) + (Originally from src/fsharp/FSComp.txt:637) This type is not a record type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:625) + (Originally from src/fsharp/FSComp.txt:638) This type is not accessible from this code location - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:671) + (Originally from src/fsharp/FSComp.txt:684) This type has no nested types - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:542) + (Originally from src/fsharp/FSComp.txt:555) This type has no accessible object constructors - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:634) + (Originally from src/fsharp/FSComp.txt:647) type, exception or module - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:743) + (Originally from src/fsharp/FSComp.txt:756) This type does not inherit Attribute, it will not work correctly with other .NET languages. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1451) + (Originally from src/fsharp/FSComp.txt:1474) Type definitions may only have one 'inherit' specification and it must be the first declaration - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:792) + (Originally from src/fsharp/FSComp.txt:805) 'let' and 'do' bindings must come before member and interface definitions in type definitions - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:793) + (Originally from src/fsharp/FSComp.txt:806) This type definition involves an immediate cyclic reference through a struct field or inheritance relation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:788) + (Originally from src/fsharp/FSComp.txt:801) This type definition involves an immediate cyclic reference through an abbreviation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:787) + (Originally from src/fsharp/FSComp.txt:800) This downcast will erase the provided type '%s' to the type '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1186) + (Originally from src/fsharp/FSComp.txt:1204) The type '%s' is not a type whose values can be enumerated with this syntax, i.e. is not compatible with either seq<_>, IEnumerable<_> or IEnumerable and does not have a GetEnumerator method - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:527) + (Originally from src/fsharp/FSComp.txt:540) Type abbreviations cannot have members - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:726) + (Originally from src/fsharp/FSComp.txt:739) As of F# 4.1, the accessibility of type abbreviations is checked at compile-time. Consider changing the accessibility of the type abbreviation. Ignoring this warning might lead to runtime errors. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:727) + (Originally from src/fsharp/FSComp.txt:740) Type abbreviations cannot have interface declarations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:735) + (Originally from src/fsharp/FSComp.txt:748) Type abbreviations cannot have augmentations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:797) + (Originally from src/fsharp/FSComp.txt:810) This type abbreviation has one or more declared type parameters that do not appear in the type being abbreviated. Type abbreviations must use all declared type parameters in the type being abbreviated. Consider removing one or more type parameters, or use a concrete type definition that wraps an underlying type, such as 'type C<'a> = C of ...'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:760) + (Originally from src/fsharp/FSComp.txt:773) One tuple type is a struct tuple, the other is a reference tuple - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1325) + (Originally from src/fsharp/FSComp.txt:1343) This method or property is not normally used from F# code, use an explicit tuple pattern for deconstruction instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1431) + (Originally from src/fsharp/FSComp.txt:1454) 'try/with' expressions may not be used in queries - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1267) + (Originally from src/fsharp/FSComp.txt:1285) 'try'/'with' cannot be used within sequence expressions - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:630) + (Originally from src/fsharp/FSComp.txt:643) Thread-static and context-static variables must be static and given the [<DefaultValue>] attribute to indicate that the value is initialized to the default value on each new thread - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:710) + (Originally from src/fsharp/FSComp.txt:723) This member, function or value declaration may not be declared 'inline' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1272) + (Originally from src/fsharp/FSComp.txt:1290) This type definition may not have the 'CLIMutable' attribute. Only record types may have this attribute. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1254) + (Originally from src/fsharp/FSComp.txt:1272) Invalid provided field. Provided fields of erased provided types must be literals. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1283) + (Originally from src/fsharp/FSComp.txt:1301) The syntax 'expr.id' may only be used with record labels, properties and fields - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:645) + (Originally from src/fsharp/FSComp.txt:658) Syntax error - unexpected '?' symbol - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:566) + (Originally from src/fsharp/FSComp.txt:579) '%s' may only be used to construct object types - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:594) + (Originally from src/fsharp/FSComp.txt:607) The struct, record or union type '%s' has the 'StructuralEquality' attribute but the component type '%s' does not satisfy the 'equality' constraint - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1035) + (Originally from src/fsharp/FSComp.txt:1052) The struct, record or union type '%s' has the 'StructuralEquality' attribute but the type parameter '%s' does not satisfy the 'equality' constraint. Consider adding the 'equality' constraint to the type parameter - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1034) + (Originally from src/fsharp/FSComp.txt:1051) The struct, record or union type '%s' has the 'StructuralComparison' attribute but the component type '%s' does not satisfy the 'comparison' constraint - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1029) + (Originally from src/fsharp/FSComp.txt:1046) The struct, record or union type '%s' has the 'StructuralComparison' attribute but the type parameter '%s' does not satisfy the 'comparison' constraint. Consider adding the 'comparison' constraint to the type parameter - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1028) + (Originally from src/fsharp/FSComp.txt:1045) Each argument of the primary constructor for a struct must be given a type, for example 'type S(x1:int, x2: int) = ...'. These arguments determine the fields of the struct. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1036) + (Originally from src/fsharp/FSComp.txt:1053) Structs cannot contain value definitions because the default constructor for structs will not execute these bindings. Consider adding additional arguments to the primary constructor for the type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:731) + (Originally from src/fsharp/FSComp.txt:744) Structs cannot contain 'do' bindings because the default constructor for structs would not execute these bindings - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:730) + (Originally from src/fsharp/FSComp.txt:743) Structs, interfaces, enums and delegates cannot inherit from other types - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:761) + (Originally from src/fsharp/FSComp.txt:774) Structs cannot have an object constructor with no arguments. This is a restriction imposed on all CLI languages as structs automatically support a default constructor. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:702) + (Originally from src/fsharp/FSComp.txt:715) Structs may only bind a 'this' parameter at member declarations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:492) + (Originally from src/fsharp/FSComp.txt:505) If a union type has more than one case and is a struct, then all fields within the union type must be given unique names. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1334) + (Originally from src/fsharp/FSComp.txt:1352) Struct types cannot contain abstract members - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:781) + (Originally from src/fsharp/FSComp.txt:794) Static 'val' fields in types must be mutable, private and marked with the '[<DefaultValue>]' attribute. They are initialized to the 'null' or 'zero' value for their type. Consider also using a 'static let mutable' binding in a class type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:713) + (Originally from src/fsharp/FSComp.txt:726) Static optimization conditionals are only for use within the F# library - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:651) + (Originally from src/fsharp/FSComp.txt:664) This static member should not have a 'this' parameter. Consider using the notation 'member Member(args) = ...'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:511) + (Originally from src/fsharp/FSComp.txt:524) Static value definitions may only be used in types with a primary constructor. Consider adding arguments to the type definition, e.g. 'type X(args) = ...'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:732) + (Originally from src/fsharp/FSComp.txt:745) Interfaces cannot contain definitions of static initializers - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:697) + (Originally from src/fsharp/FSComp.txt:710) A static initializer requires an argument - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:509) + (Originally from src/fsharp/FSComp.txt:522) A static field was used where an instance field is expected - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:460) + (Originally from src/fsharp/FSComp.txt:473) A simple method name is required here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:604) + (Originally from src/fsharp/FSComp.txt:617) In sequence expressions, results are generated using 'yield' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:466) + (Originally from src/fsharp/FSComp.txt:479) Array method '%s' is supplied by the runtime and cannot be directly used in code. For operations with array elements consider using family of GetArray/SetArray functions from LanguagePrimitives.IntrinsicFunctions module. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1296) + (Originally from src/fsharp/FSComp.txt:1314) Return values cannot have names - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:472) + (Originally from src/fsharp/FSComp.txt:485) Return types of union cases must be identical to the type being defined, up to abbreviations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:717) + (Originally from src/fsharp/FSComp.txt:730) 'return' and 'return!' may not be used in queries - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1265) + (Originally from src/fsharp/FSComp.txt:1283) The syntax 'type X with ...' is reserved for augmentations. Types whose representations are hidden but which have members are now declared in signatures using 'type X = ...'. You may also need to add the '[<Sealed>] attribute to the type definition in the signature - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:789) + (Originally from src/fsharp/FSComp.txt:802) This is not a variable, constant, active recognizer or literal - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:562) + (Originally from src/fsharp/FSComp.txt:575) + + + + + The 'let! ... and! ...' construct may only be used if the computation expression builder defines either a '%s' method or appropriate 'MergeSource' and 'Bind' methods + (Originally from src/fsharp/FSComp.txt:1486) This control construct may only be used if the computation expression builder defines a '%s' method - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:541) + (Originally from src/fsharp/FSComp.txt:554) Only active patterns returning exactly one result may accept arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:554) + (Originally from src/fsharp/FSComp.txt:567) The representation of this type is hidden by the signature. It must be given an attribute such as [<Sealed>], [<Class>] or [<Interface>] to indicate the characteristics of the type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:767) + (Originally from src/fsharp/FSComp.txt:780) Recursive bindings that include member specifications can only occur as a direct augmentation of a type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:704) + (Originally from src/fsharp/FSComp.txt:717) Records, union, abbreviations and struct types cannot have the 'AllowNullLiteral' attribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:763) + (Originally from src/fsharp/FSComp.txt:776) This record contains fields from inconsistent types - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:490) + (Originally from src/fsharp/FSComp.txt:503) The 'rec' on this module is implied by an outer 'rec' declaration and is being ignored - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1329) + (Originally from src/fsharp/FSComp.txt:1347) A property cannot have explicit type parameters. Consider using a method instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:505) + (Originally from src/fsharp/FSComp.txt:518) This property or field was not found on this custom attribute type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:678) + (Originally from src/fsharp/FSComp.txt:691) Property '%s' is static - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:642) + (Originally from src/fsharp/FSComp.txt:655) Property '%s' is not static - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:639) + (Originally from src/fsharp/FSComp.txt:652) Property '%s' is not readable - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:640) + (Originally from src/fsharp/FSComp.txt:653) Property '%s' cannot be set - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:643) + (Originally from src/fsharp/FSComp.txt:656) This property cannot be set - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:677) + (Originally from src/fsharp/FSComp.txt:690) The types System.ValueType, System.Enum, System.Delegate, System.MulticastDelegate and System.Array cannot be used as super types in an object expression or class - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:605) + (Originally from src/fsharp/FSComp.txt:618) A parameter with attributes must also be given a name, e.g. '[<Attribute>] Name : Type' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:471) + (Originally from src/fsharp/FSComp.txt:484) The parameter '%s' was inferred to have byref type. Parameters of byref type must be given an explicit type annotation, e.g. 'x1: byref<int>'. When used, a byref parameter is implicitly dereferenced. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1053) + (Originally from src/fsharp/FSComp.txt:1070) You must explicitly declare either all or no type parameters when overriding a generic abstract method - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:500) + (Originally from src/fsharp/FSComp.txt:513) Accessibility modifiers are not permitted on overrides or interface implementations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:770) + (Originally from src/fsharp/FSComp.txt:783) This override takes a different number of arguments to the corresponding abstract member. The following abstract members were found:%s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:689) + (Originally from src/fsharp/FSComp.txt:702) One or more of the overloads of this method has curried arguments. Consider redesigning these members to take arguments in tupled form. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:649) + (Originally from src/fsharp/FSComp.txt:662) Optional arguments cannot be used in custom attributes - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:676) + (Originally from src/fsharp/FSComp.txt:689) Optional arguments are only permitted on type members - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:550) + (Originally from src/fsharp/FSComp.txt:563) Optional arguments must come at the end of the argument list, after any non-optional arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1071) + (Originally from src/fsharp/FSComp.txt:1088) '%s' must be followed by 'in'. Usage: %s. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1290) + (Originally from src/fsharp/FSComp.txt:1308) Incorrect syntax for '%s'. Usage: %s. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1218) + (Originally from src/fsharp/FSComp.txt:1236) The operator '%s' does not accept the use of 'into' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1252) + (Originally from src/fsharp/FSComp.txt:1270) This declaration opens the namespace or module '%s' through a partially qualified path. Adjust this code to use the full path of the namespace. This change will make your code more robust as new constructs are added to the F# and CLI libraries. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:724) + (Originally from src/fsharp/FSComp.txt:737) In a recursive declaration group, 'open' declarations must come first in each module - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1330) + (Originally from src/fsharp/FSComp.txt:1348) Only types representing units-of-measure may be given the 'Measure' attribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:769) + (Originally from src/fsharp/FSComp.txt:782) Only structs and classes without primary constructors may be given the 'StructLayout' attribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:766) + (Originally from src/fsharp/FSComp.txt:779) Only simple variable patterns can be bound in 'let rec' constructs - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:705) + (Originally from src/fsharp/FSComp.txt:718) Only simple bindings of the form 'id = expr' can be used in construction expressions - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:611) + (Originally from src/fsharp/FSComp.txt:624) Only record fields and simple, non-recursive 'let' bindings may be marked mutable - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:706) + (Originally from src/fsharp/FSComp.txt:719) Only functions may be marked 'inline' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:665) + (Originally from src/fsharp/FSComp.txt:678) Only classes may be given the 'AbstractClass' attribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:768) + (Originally from src/fsharp/FSComp.txt:781) Objects must be initialized by an object construction expression that calls an inherited object constructor and assigns a value to each field - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:612) + (Originally from src/fsharp/FSComp.txt:625) The operator 'expr.[idx]' has been used on an object of indeterminate type based on information prior to this program point. Consider adding further type constraints - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:585) + (Originally from src/fsharp/FSComp.txt:598) Only overrides of abstract and virtual members may be specified in object expressions - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:599) + (Originally from src/fsharp/FSComp.txt:612) This form of object expression is not used in F#. Use 'member this.MemberName ... = ...' to define member implementations in object expressions. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:515) + (Originally from src/fsharp/FSComp.txt:528) Calls to object constructors on type parameters cannot be given arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:587) + (Originally from src/fsharp/FSComp.txt:600) Interfaces cannot contain definitions of object constructors - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:698) + (Originally from src/fsharp/FSComp.txt:711) An object constructor requires an argument - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:510) + (Originally from src/fsharp/FSComp.txt:523) Object construction expressions (i.e. record expressions with inheritance specifications) may only be used to implement constructors in object model types. Use 'new ObjectType(args)' to construct instances of object model types outside of constructors - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:622) + (Originally from src/fsharp/FSComp.txt:635) Object construction expressions may only be used to implement constructors in class types - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:610) + (Originally from src/fsharp/FSComp.txt:623) This numeric literal requires that a module '%s' defining functions FromZero, FromOne, FromInt32, FromInt64 and FromString be in scope - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:618) + (Originally from src/fsharp/FSComp.txt:631) This is not a valid name for an enumeration case - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:578) + (Originally from src/fsharp/FSComp.txt:591) This code is not sufficiently generic. The type variable %s could not be generalized because it would escape its scope. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:504) + (Originally from src/fsharp/FSComp.txt:517) Not an exception - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:752) + (Originally from src/fsharp/FSComp.txt:765) Non-zero constants cannot have generic units. For generic zero, write 0.0<_>. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:465) + (Originally from src/fsharp/FSComp.txt:478) The generic member '%s' has been used at a non-uniform instantiation prior to this program point. Consider reordering the members so this member occurs first. Alternatively, specify the full type of the member explicitly, including argument types, return type and any additional generic parameters and constraints. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1054) + (Originally from src/fsharp/FSComp.txt:1071) This 'let' definition may not be used in a query. Only simple value definitions may be used in queries. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1268) + (Originally from src/fsharp/FSComp.txt:1286) This value is not a literal and cannot be used in a pattern - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:523) + (Originally from src/fsharp/FSComp.txt:536) 'while' expressions may not be used in queries - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1261) + (Originally from src/fsharp/FSComp.txt:1279) 'try/finally' expressions may not be used in queries - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1262) + (Originally from src/fsharp/FSComp.txt:1280) No abstract property was found that corresponds to this override - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:692) + (Originally from src/fsharp/FSComp.txt:705) No abstract or interface member was found that corresponds to this override - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:688) + (Originally from src/fsharp/FSComp.txt:701) Interface implementations cannot be given on construction expressions - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:609) + (Originally from src/fsharp/FSComp.txt:622) In queries, use the form 'for x in n .. m do ...' for ranging over integers - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1260) + (Originally from src/fsharp/FSComp.txt:1278) The struct, record or union type '%s' does not support structural equality because the type '%s' does not satisfy the 'equality' constraint. Consider adding the 'NoEquality' attribute to the type '%s' to clarify that the type does not support structural equality - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1033) + (Originally from src/fsharp/FSComp.txt:1050) The struct, record or union type '%s' does not support structural equality because the type parameter %s does not satisfy the 'equality' constraint. Consider adding the 'NoEquality' attribute to the type '%s' to clarify that the type does not support structural equality - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1032) + (Originally from src/fsharp/FSComp.txt:1049) The struct, record or union type '%s' is not structurally comparable because the type '%s' does not satisfy the 'comparison' constraint. Consider adding the 'NoComparison' attribute to the type '%s' to clarify that the type is not comparable - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1031) + (Originally from src/fsharp/FSComp.txt:1048) The struct, record or union type '%s' is not structurally comparable because the type parameter %s does not satisfy the 'comparison' constraint. Consider adding the 'NoComparison' attribute to the type '%s' to clarify that the type is not comparable - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1030) + (Originally from src/fsharp/FSComp.txt:1047) No arguments may be given when constructing a record value - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:608) + (Originally from src/fsharp/FSComp.txt:621) The member '%s' does not correspond to any abstract or virtual method available to override or implement. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:600) + (Originally from src/fsharp/FSComp.txt:613) 'new' may only be used with object constructors - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:616) + (Originally from src/fsharp/FSComp.txt:629) 'new' must be used with a named type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:606) + (Originally from src/fsharp/FSComp.txt:619) This new member hides the abstract member '%s' once tuples, functions, units of measure and/or provided types are erased. Rename the member or use 'override' instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:696) + (Originally from src/fsharp/FSComp.txt:709) This new member hides the abstract member '%s'. Rename the member or use 'override' instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:695) + (Originally from src/fsharp/FSComp.txt:708) 'new' cannot be used on interface types. Consider using an object expression '{ new ... with ... }' instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:591) + (Originally from src/fsharp/FSComp.txt:604) Namespaces cannot contain values. Consider using a module to hold your value declarations. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:474) + (Originally from src/fsharp/FSComp.txt:487) Namespaces cannot contain extension members except in the same file and namespace declaration group where the type is defined. Consider using a module to hold declarations of extension members. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:475) + (Originally from src/fsharp/FSComp.txt:488) '%s' may only be used with named types - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:589) + (Originally from src/fsharp/FSComp.txt:602) Named arguments cannot be given to member trait calls - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:577) + (Originally from src/fsharp/FSComp.txt:590) The named argument '%s' did not match any argument or mutable property - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:648) + (Originally from src/fsharp/FSComp.txt:661) %s is an active pattern and cannot be treated as a discriminated union case with named fields. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1339) + (Originally from src/fsharp/FSComp.txt:1357) Name '%s' not bound in pattern context - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:551) + (Originally from src/fsharp/FSComp.txt:564) Named arguments must appear after all other arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:525) + (Originally from src/fsharp/FSComp.txt:538) Mutable function values should be written 'let mutable f = (fun args -> ...)' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:664) + (Originally from src/fsharp/FSComp.txt:677) Mutable values cannot have generic parameters - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:663) + (Originally from src/fsharp/FSComp.txt:676) Mutable values cannot be marked 'inline' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:662) + (Originally from src/fsharp/FSComp.txt:675) Multiple visibility attributes have been specified for this identifier. 'let' bindings in classes are always private, as are any 'let' bindings inside expressions. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:477) + (Originally from src/fsharp/FSComp.txt:490) Multiple visibility attributes have been specified for this identifier - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:476) + (Originally from src/fsharp/FSComp.txt:489) This declaration opens the module '%s', which is marked as 'RequireQualifiedAccess'. Adjust your code to use qualified references to the elements of the module instead, e.g. 'List.map' instead of 'map'. This change will ensure that your code is robust as new constructs are added to libraries. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:723) + (Originally from src/fsharp/FSComp.txt:736) The path '%s' is a namespace. A module abbreviation may not abbreviate a namespace. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:798) + (Originally from src/fsharp/FSComp.txt:811) In a recursive declaration group, module abbreviations must come after all 'open' declarations and before other declarations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1331) + (Originally from src/fsharp/FSComp.txt:1349) A custom query operation for '%s' is required but not specified - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1199) + (Originally from src/fsharp/FSComp.txt:1217) Method overrides and interface implementations are not permitted here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:687) + (Originally from src/fsharp/FSComp.txt:700) Method '%s' is not accessible from this code location - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:461) + (Originally from src/fsharp/FSComp.txt:474) Members that extend interface, delegate or enum types must be placed in a module separate to the definition of the type. This module must either have the AutoOpen attribute or be opened explicitly by client code to bring the extension members into scope. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:790) + (Originally from src/fsharp/FSComp.txt:803) The member '%s' is used in an invalid way. A use of '%s' has been inferred prior to the definition of '%s', which is an invalid forward reference. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:800) + (Originally from src/fsharp/FSComp.txt:813) Interfaces cannot contain definitions of member overrides - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:699) + (Originally from src/fsharp/FSComp.txt:712) Extension members cannot provide operator overloads. Consider defining the operator as part of the type definition instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1074) + (Originally from src/fsharp/FSComp.txt:1091) This member is not permitted in an interface implementation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:740) + (Originally from src/fsharp/FSComp.txt:753) MemberKind.PropertyGetSet only expected in parse trees - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:473) + (Originally from src/fsharp/FSComp.txt:486) This member is not sufficiently generic - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:707) + (Originally from src/fsharp/FSComp.txt:720) The type %s contains the member '%s' but it is not a virtual or abstract method that is available to override or implement. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:601) + (Originally from src/fsharp/FSComp.txt:614) A member and a local class binding both have the name '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:734) + (Originally from src/fsharp/FSComp.txt:747) Measure definitions cannot have type parameters - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:758) + (Originally from src/fsharp/FSComp.txt:771) Measure declarations may have only static members: constructors are not available - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:733) + (Originally from src/fsharp/FSComp.txt:746) Measure declarations may have only static members - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:729) + (Originally from src/fsharp/FSComp.txt:742) 'match' expressions may not be used in queries - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1287) + (Originally from src/fsharp/FSComp.txt:1305) This lookup cannot be used here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:641) + (Originally from src/fsharp/FSComp.txt:654) Local class bindings cannot be marked inline. Consider lifting the definition out of the class or else do not mark it as inline. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:725) + (Originally from src/fsharp/FSComp.txt:738) This literal pattern does not take arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1319) + (Originally from src/fsharp/FSComp.txt:1337) Literal values cannot have generic parameters - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:669) + (Originally from src/fsharp/FSComp.txt:682) A literal value cannot be marked 'mutable' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:667) + (Originally from src/fsharp/FSComp.txt:680) A literal value cannot be marked 'inline' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:668) + (Originally from src/fsharp/FSComp.txt:681) A declaration may only be the [<Literal>] attribute if a constant value is also given, e.g. 'val x : int = 1' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:708) + (Originally from src/fsharp/FSComp.txt:721) This list expression exceeds the maximum size for list literals. Use an array for larger literals and call Array.ToList. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:575) + (Originally from src/fsharp/FSComp.txt:588) This definition may only be used in a type with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:796) + (Originally from src/fsharp/FSComp.txt:809) This code is less generic than required by its annotations because the explicit type variable '%s' could not be generalized. It was constrained to be '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:494) + (Originally from src/fsharp/FSComp.txt:507) The kind of the type specified by its attributes does not match the kind implied by its definition - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:757) + (Originally from src/fsharp/FSComp.txt:770) In queries, '%s' must use a simple pattern - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1198) + (Originally from src/fsharp/FSComp.txt:1216) A type annotated with IsReadOnly must also be a struct. Consider adding the [<Struct>] attribute to the type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1442) + (Originally from src/fsharp/FSComp.txt:1465) Invalid use of a type name - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:633) + (Originally from src/fsharp/FSComp.txt:646) Invalid use of an interface type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:637) + (Originally from src/fsharp/FSComp.txt:650) Invalid use of a delegate constructor. Use the syntax 'new Type(args)' or just 'Type(args)'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:638) + (Originally from src/fsharp/FSComp.txt:651) The 'UseNullAsTrueValue' attribute flag may only be used with union types that have one nullary case and at least one non-nullary case - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1052) + (Originally from src/fsharp/FSComp.txt:1069) 'use' bindings must be of the form 'use <var> = <expr>' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:685) + (Originally from src/fsharp/FSComp.txt:698) + + + + + use! may not be combined with and! + (Originally from src/fsharp/FSComp.txt:1488) 'use!' bindings must be of the form 'use! <var> = <expr>' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1085) + (Originally from src/fsharp/FSComp.txt:1101) Units-of-measure cannot be used as prefix arguments to a type. Rewrite as postfix arguments in angle brackets. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:539) + (Originally from src/fsharp/FSComp.txt:552) Units-of-measure supported only on float, float32, decimal and signed integer types - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:468) + (Originally from src/fsharp/FSComp.txt:481) Literal enumerations must have type int, uint, int16, uint16, int64, uint64, byte, sbyte or char - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:785) + (Originally from src/fsharp/FSComp.txt:798) Invalid type extension - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:755) + (Originally from src/fsharp/FSComp.txt:768) Type arguments cannot be specified here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:553) + (Originally from src/fsharp/FSComp.txt:566) The number of type arguments did not match: '%d' given, '%d' expected. This may be related to a previously reported error. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1192) + (Originally from src/fsharp/FSComp.txt:1210) Invalid signature for set member - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:694) + (Originally from src/fsharp/FSComp.txt:707) Invalid record, sequence or computation expression. Sequence expressions should be of the form 'seq { ... }' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:572) + (Originally from src/fsharp/FSComp.txt:585) Invalid join relation in '%s'. Expected 'expr <op> expr', where <op> is =, =?, ?= or ?=?. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1245) + (Originally from src/fsharp/FSComp.txt:1263) Invalid record construction - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:619) + (Originally from src/fsharp/FSComp.txt:632) This property has an invalid type. Properties taking multiple indexer arguments should have types of the form 'ty1 * ty2 -> ty3'. Properties returning functions should have types of the form '(ty1 -> ty2)'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:534) + (Originally from src/fsharp/FSComp.txt:547) This is not a valid pattern - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:563) + (Originally from src/fsharp/FSComp.txt:576) Invalid optional assignment to a property or field - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:653) + (Originally from src/fsharp/FSComp.txt:666) The '%s' operator should not normally be redefined. To define overloaded comparison semantics for a particular type, implement the 'System.IComparable' interface in the definition of that type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:482) + (Originally from src/fsharp/FSComp.txt:495) The '%s' operator should not normally be redefined. To define equality semantics for a type, override the 'Object.Equals' member in the definition of that type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:483) + (Originally from src/fsharp/FSComp.txt:496) The '%s' operator should not normally be redefined. Consider using a different operator name - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:484) + (Originally from src/fsharp/FSComp.txt:497) Invalid object, sequence or record expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:571) + (Originally from src/fsharp/FSComp.txt:584) Invalid object expression. Objects without overrides or interfaces should use the expression form 'new Type(args)' without braces. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:570) + (Originally from src/fsharp/FSComp.txt:583) This is not a valid object construction expression. Explicit object constructors must either call an alternate constructor or initialize all fields of the object and specify a call to a super class constructor. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:529) + (Originally from src/fsharp/FSComp.txt:542) Non-primitive numeric literal constants cannot be used in pattern matches because they can be mapped to multiple different types through the use of a NumericLiteral module. Consider using replacing with a variable, and use 'when <variable> = <constant>' at the end of the match clause. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:552) + (Originally from src/fsharp/FSComp.txt:565) 'new' constraints must take one argument of type 'unit' and return the constructed type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:533) + (Originally from src/fsharp/FSComp.txt:546) Invalid namespace, module, type or union case name - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:715) + (Originally from src/fsharp/FSComp.txt:728) Invalid module name - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:754) + (Originally from src/fsharp/FSComp.txt:767) This recursive binding uses an invalid mixture of recursive forms - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:528) + (Originally from src/fsharp/FSComp.txt:541) The name '(%s)' should not be used as a member name. To define comparison semantics for a type, implement the 'System.IComparable' interface. If defining a static member for use from other CLI languages then use the name '%s' instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:478) + (Originally from src/fsharp/FSComp.txt:491) The name '(%s)' should not be used as a member name. To define equality semantics for a type, override the 'Object.Equals' member. If defining a static member for use from other CLI languages then use the name '%s' instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:479) + (Originally from src/fsharp/FSComp.txt:492) The name '(%s)' should not be used as a member name because it is given a standard definition in the F# library over fixed types - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:481) + (Originally from src/fsharp/FSComp.txt:494) Invalid member name. Members may not have name '.ctor' or '.cctor' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1190) + (Originally from src/fsharp/FSComp.txt:1208) The name '(%s)' should not be used as a member name. If defining a static member for use from other CLI languages then use the name '%s' instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:480) + (Originally from src/fsharp/FSComp.txt:493) Invalid inline specification - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:684) + (Originally from src/fsharp/FSComp.txt:697) Invalid indexer expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:584) + (Originally from src/fsharp/FSComp.txt:597) The '%s' operator cannot be redefined. Consider using a different operator name - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:485) + (Originally from src/fsharp/FSComp.txt:498) Internal error. Invalid index into active pattern array - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:556) + (Originally from src/fsharp/FSComp.txt:569) This is not a valid value for an enumeration literal - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:718) + (Originally from src/fsharp/FSComp.txt:731) An 'enum' constraint must be of the form 'enum<type>' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:532) + (Originally from src/fsharp/FSComp.txt:545) Delegate specifications must be of the form 'typ -> typ' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:783) + (Originally from src/fsharp/FSComp.txt:796) Invalid declaration - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:516) + (Originally from src/fsharp/FSComp.txt:529) Invalid constraint: the type used for the constraint is sealed, which means the constraint could only be satisfied by at most one solution - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:531) + (Originally from src/fsharp/FSComp.txt:544) Invalid constraint - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:530) + (Originally from src/fsharp/FSComp.txt:543) This is not a valid constant expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:670) + (Originally from src/fsharp/FSComp.txt:683) Invalid assignment - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:632) + (Originally from src/fsharp/FSComp.txt:645) Invalid argument to parameterized pattern label - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:555) + (Originally from src/fsharp/FSComp.txt:568) This is not a valid name for an active pattern - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:660) + (Originally from src/fsharp/FSComp.txt:673) A use of 'into' must be followed by the remainder of the computation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1251) + (Originally from src/fsharp/FSComp.txt:1269) Interfaces inherited by other interfaces should be declared using 'inherit ...' instead of 'interface ...' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1063) + (Originally from src/fsharp/FSComp.txt:1080) Interface types cannot be sealed - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:782) + (Originally from src/fsharp/FSComp.txt:795) Interface types and delegate types cannot contain fields - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:777) + (Originally from src/fsharp/FSComp.txt:790) This instance member needs a parameter to represent the object being invoked. Make the member static or use the notation 'member x.Member(args) = ...'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:507) + (Originally from src/fsharp/FSComp.txt:520) The inherited type is not an object model type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:621) + (Originally from src/fsharp/FSComp.txt:634) A inheritance declaration is not permitted here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:722) + (Originally from src/fsharp/FSComp.txt:735) This 'inherit' declaration specifies the inherited type but no arguments. Consider supplying arguments, e.g. 'inherit BaseType(args)'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:794) + (Originally from src/fsharp/FSComp.txt:807) This 'inherit' declaration has arguments, but is not in a type with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:795) + (Originally from src/fsharp/FSComp.txt:808) 'inherit' cannot be used on interface types. Consider implementing the interface by using 'interface ... with ... end' instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:590) + (Originally from src/fsharp/FSComp.txt:603) The function or member '%s' is used in a way that requires further type annotations at its definition to ensure consistency of inferred types. The inferred signature is '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1191) + (Originally from src/fsharp/FSComp.txt:1209) Implicit product of measures following / - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:463) + (Originally from src/fsharp/FSComp.txt:476) The struct, record or union type '%s' implements the interface 'System.IStructuralEquatable' explicitly. Apply the 'CustomEquality' attribute to the type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:745) + (Originally from src/fsharp/FSComp.txt:758) The struct, record or union type '%s' implements the interface 'System.IStructuralComparable' explicitly. Apply the 'CustomComparison' attribute to the type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:489) + (Originally from src/fsharp/FSComp.txt:502) The struct, record or union type '%s' implements the interface 'System.IEquatable<_>' explicitly. Apply the 'CustomEquality' attribute to the type and provide a consistent implementation of the non-generic override 'System.Object.Equals(obj)'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:746) + (Originally from src/fsharp/FSComp.txt:759) The struct, record or union type '%s' implements the interface 'System.IComparable' explicitly. You must apply the 'CustomComparison' attribute to the type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:487) + (Originally from src/fsharp/FSComp.txt:500) The struct, record or union type '%s' implements the interface 'System.IComparable<_>' explicitly. You must apply the 'CustomComparison' attribute to the type, and should also provide a consistent implementation of the non-generic interface System.IComparable. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:488) + (Originally from src/fsharp/FSComp.txt:501) Illegal syntax in type expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:545) + (Originally from src/fsharp/FSComp.txt:558) This is not valid literal expression. The [<Literal>] attribute will be ignored. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1305) + (Originally from src/fsharp/FSComp.txt:1323) Illegal pattern - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:565) + (Originally from src/fsharp/FSComp.txt:578) Explicit type declarations for constructors must be of the form 'ty1 * ... * tyN -> resTy'. Parentheses may be required around 'resTy' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:716) + (Originally from src/fsharp/FSComp.txt:729) A literal value cannot be given the [<ThreadStatic>] or [<ContextStatic>] attributes - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:666) + (Originally from src/fsharp/FSComp.txt:679) An if/then/else expression may not be used within queries. Consider using either an if/then expression, or use a sequence expression instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1208) + (Originally from src/fsharp/FSComp.txt:1226) It is recommended that objects supporting the IDisposable interface are created using the syntax 'new Type(args)', rather than 'Type(args)' or 'Type' as a function value representing the constructor, to indicate that resources may be owned by the generated value - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:593) + (Originally from src/fsharp/FSComp.txt:606) The system type '%s' was required but no referenced system DLL contained this type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1341) + (Originally from src/fsharp/FSComp.txt:1359) Generic types cannot be given the 'StructLayout' attribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:765) + (Originally from src/fsharp/FSComp.txt:778) A generic type parameter has been used in a way that constrains it to always be '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:496) + (Originally from src/fsharp/FSComp.txt:509) The provided types generated by this use of a type provider may not be used from other F# assemblies and should be marked internal or private. Consider using 'type internal TypeName = ...' or 'type private TypeName = ...'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1294) + (Originally from src/fsharp/FSComp.txt:1312) The generic function '%s' must be given explicit type argument(s) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:518) + (Originally from src/fsharp/FSComp.txt:531) This function value is being used to construct a delegate type whose signature includes a byref argument. You must use an explicit lambda expression taking %d arguments. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:526) + (Originally from src/fsharp/FSComp.txt:539) The corresponding formal argument is not optional - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:652) + (Originally from src/fsharp/FSComp.txt:665) Invalid use of 'fixed'. 'fixed' may only be used in a declaration of the form 'use x = fixed expr' where the expression is an array, the address of a field, the address of an array element or a string' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1336) + (Originally from src/fsharp/FSComp.txt:1354) The field labels and expected type of this record expression or pattern do not uniquely determine a corresponding record type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:501) + (Originally from src/fsharp/FSComp.txt:514) A field/val declaration is not permitted here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:721) + (Originally from src/fsharp/FSComp.txt:734) This field requires a name - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:714) + (Originally from src/fsharp/FSComp.txt:727) No assignment given for field '%s' of type '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:597) + (Originally from src/fsharp/FSComp.txt:610) This field is not a literal and cannot be used in a pattern - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:561) + (Originally from src/fsharp/FSComp.txt:574) Named field '%s' is used more than once. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1302) + (Originally from src/fsharp/FSComp.txt:1320) Named field '%s' conflicts with autogenerated name for anonymous field. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1303) + (Originally from src/fsharp/FSComp.txt:1321) This field is readonly - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:524) + (Originally from src/fsharp/FSComp.txt:537) Field '%s' is not static - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:560) + (Originally from src/fsharp/FSComp.txt:573) This field is not mutable - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:579) + (Originally from src/fsharp/FSComp.txt:592) The field '%s' appears twice in this record expression or pattern - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:502) + (Originally from src/fsharp/FSComp.txt:515) All record, union and struct types in FSharp.Core.dll must be explicitly labelled with 'StructuralComparison' or 'NoComparison' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1027) + (Originally from src/fsharp/FSComp.txt:1044) Extraneous fields have been given values - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:598) + (Originally from src/fsharp/FSComp.txt:611) This list or array expression includes an element of the form 'if ... then ... else'. Parenthesize this expression to indicate it is an individual element of the list or array, to disambiguate this from a list generated using a sequence expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:573) + (Originally from src/fsharp/FSComp.txt:586) This expression form may only be used in sequence and computation expressions - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:569) + (Originally from src/fsharp/FSComp.txt:582) The expression form { expr with ... } may only be used with record types. To build object types use { new Type(...) with ... } - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:620) + (Originally from src/fsharp/FSComp.txt:633) The expression form 'expr then expr' may only be used as part of an explicit object constructor - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:576) + (Originally from src/fsharp/FSComp.txt:589) Expected %d expressions, got %d - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:567) + (Originally from src/fsharp/FSComp.txt:580) TcExprUndelayed: delayed - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:568) + (Originally from src/fsharp/FSComp.txt:581) Explicit type specifications cannot be used for exception constructors - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:747) + (Originally from src/fsharp/FSComp.txt:760) Explicit type parameters may only be used on module or member bindings - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:499) + (Originally from src/fsharp/FSComp.txt:512) An explicit static initializer should use the syntax 'static new(args) = expr' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:512) + (Originally from src/fsharp/FSComp.txt:525) An explicit object constructor should use the syntax 'new(args) = expr' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:513) + (Originally from src/fsharp/FSComp.txt:526) Expected unit-of-measure, not type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:538) + (Originally from src/fsharp/FSComp.txt:551) Expected unit-of-measure parameter, not type parameter. Explicit unit-of-measure parameters must be marked with the [<Measure>] attribute. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:535) + (Originally from src/fsharp/FSComp.txt:548) Expected type parameter, not unit-of-measure parameter - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:536) + (Originally from src/fsharp/FSComp.txt:549) Expected type, not unit-of-measure - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:537) + (Originally from src/fsharp/FSComp.txt:550) Expected an interface type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:613) + (Originally from src/fsharp/FSComp.txt:626) Expected module or namespace parent %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:486) + (Originally from src/fsharp/FSComp.txt:499) The exception '%s' does not have a field named '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1298) + (Originally from src/fsharp/FSComp.txt:1316) Exception abbreviations should not have argument lists - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:748) + (Originally from src/fsharp/FSComp.txt:761) Exception abbreviations must refer to existing exceptions or F# types deriving from System.Exception - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:750) + (Originally from src/fsharp/FSComp.txt:763) Event '%s' is static - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:646) + (Originally from src/fsharp/FSComp.txt:659) Event '%s' is not static - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:647) + (Originally from src/fsharp/FSComp.txt:660) Enumerations cannot have members - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:728) + (Originally from src/fsharp/FSComp.txt:741) Enumerations cannot have interface declarations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:736) + (Originally from src/fsharp/FSComp.txt:749) The type '%s' is not a valid enumerator type , i.e. does not have a 'MoveNext()' method returning a bool, and a 'Current' property - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1087) + (Originally from src/fsharp/FSComp.txt:1103) The 'EntryPointAttribute' attribute may only be used on function definitions in modules - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:661) + (Originally from src/fsharp/FSComp.txt:674) '{ }' is not a valid expression. Records must include at least one field. Empty sequences are specified by using Seq.empty or an empty list '[]'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:623) + (Originally from src/fsharp/FSComp.txt:636) Copy-and-update record expressions must include at least one field. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1292) + (Originally from src/fsharp/FSComp.txt:1310) Duplicate specification of an interface - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:720) + (Originally from src/fsharp/FSComp.txt:733) The method or function '%s' should not be given explicit type argument(s) because it does not declare its type parameters explicitly - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:519) + (Originally from src/fsharp/FSComp.txt:532) 'do!' cannot be used within sequence expressions - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:628) + (Originally from src/fsharp/FSComp.txt:641) DLLImport stubs cannot be inlined - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:491) + (Originally from src/fsharp/FSComp.txt:504) DLLImport bindings must be static members in a class or function definitions in a module - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1080) + (Originally from src/fsharp/FSComp.txt:1097) Delegate specifications must not be curried types. Use 'typ * ... * typ -> typ' for multi-argument delegates, and 'typ -> (typ -> typ)' for delegates returning function values. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:784) + (Originally from src/fsharp/FSComp.txt:797) A delegate constructor must be passed a single function value - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:654) + (Originally from src/fsharp/FSComp.txt:667) The 'DefaultValue' attribute may only be used on 'val' declarations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:658) + (Originally from src/fsharp/FSComp.txt:671) The default, zero-initializing constructor of a struct type may only be used if all the fields of the struct type admit default initialization - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:521) + (Originally from src/fsharp/FSComp.txt:534) A default implementation of this interface has already been added because the explicit implementation of the interface was not specified at the definition of the type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:739) + (Originally from src/fsharp/FSComp.txt:752) This method already has a default implementation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:690) + (Originally from src/fsharp/FSComp.txt:703) The method implemented by this default is ambiguous - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:691) + (Originally from src/fsharp/FSComp.txt:704) One or more of the declared type parameters for this type extension have a missing or wrong type constraint not matching the original type constraints on '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:791) + (Originally from src/fsharp/FSComp.txt:804) This declaration element is not permitted in an augmentation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:741) + (Originally from src/fsharp/FSComp.txt:754) '%s' is not used correctly. Usage: %s. This is a custom operation in this query or computation expression. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1213) + (Originally from src/fsharp/FSComp.txt:1231) '%s' is not used correctly. This is a custom operation in this query or computation expression. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1212) + (Originally from src/fsharp/FSComp.txt:1230) A custom operation may not be used in conjunction with a non-value or recursive 'let' binding in another part of this computation expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1205) + (Originally from src/fsharp/FSComp.txt:1223) A custom operation may not be used in conjunction with 'use', 'try/with', 'try/finally', 'if/then/else' or 'match' operators within this computation expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1206) + (Originally from src/fsharp/FSComp.txt:1224) The custom operation '%s' refers to a method which is overloaded. The implementations of custom operations may not be overloaded. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1207) + (Originally from src/fsharp/FSComp.txt:1225) The definition of the custom operator '%s' does not use a valid combination of attribute flags - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1253) + (Originally from src/fsharp/FSComp.txt:1271) '%s' is used with an incorrect number of arguments. This is a custom operation in this query or computation expression. Expected %d argument(s), but given %d. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1220) + (Originally from src/fsharp/FSComp.txt:1238) A custom attribute must invoke an object constructor - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:681) + (Originally from src/fsharp/FSComp.txt:694) A custom attribute must be a reference type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:679) + (Originally from src/fsharp/FSComp.txt:692) The number of args for a custom attribute does not match the expected number of args for the attribute constructor - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:680) + (Originally from src/fsharp/FSComp.txt:693) Could not find method System.Runtime.CompilerServices.OffsetToStringData in references when building 'fixed' expression. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1337) + (Originally from src/fsharp/FSComp.txt:1355) Couldn't find Dispose on IDisposable, or it was overloaded - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:522) + (Originally from src/fsharp/FSComp.txt:535) The input to a copy-and-update expression that creates an anonymous record must be either an anonymous record or a record - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1454) + (Originally from src/fsharp/FSComp.txt:1477) Constructors are not permitted as extension members - they must be defined as part of the original definition of the type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1320) + (Originally from src/fsharp/FSComp.txt:1338) Constructors cannot be defined for this type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:703) + (Originally from src/fsharp/FSComp.txt:716) Constructors cannot be specified in exception augmentations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:701) + (Originally from src/fsharp/FSComp.txt:714) Constructors must be applied to arguments and cannot be used as first-class values. If necessary use an anonymous function '(fun arg1 ... argN -> new Type(arg1,...,argN))'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:644) + (Originally from src/fsharp/FSComp.txt:657) Constructors for the type '%s' must directly or indirectly call its implicit object constructor. Use a call to the implicit object constructor instead of a record expression. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:595) + (Originally from src/fsharp/FSComp.txt:608) This object constructor requires arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:615) + (Originally from src/fsharp/FSComp.txt:628) Constructor expressions for interfaces do not take arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:614) + (Originally from src/fsharp/FSComp.txt:627) The constructor does not have a field named '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1300) + (Originally from src/fsharp/FSComp.txt:1318) A constructor cannot have explicit type parameters. Consider using a static construction method instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:506) + (Originally from src/fsharp/FSComp.txt:519) This construct may only be used within sequence or computation expressions - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:582) + (Originally from src/fsharp/FSComp.txt:595) This construct may only be used within list, array and sequence expressions, e.g. expressions of the form 'seq { ... }', '[ ... ]' or '[| ... |]'. These use the syntax 'for ... in ... do ... yield...' to generate elements - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:580) + (Originally from src/fsharp/FSComp.txt:593) This construct may only be used within computation expressions. To return a value from an ordinary function simply write the expression without 'return'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:581) + (Originally from src/fsharp/FSComp.txt:594) This construct may only be used within computation expressions - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:583) + (Originally from src/fsharp/FSComp.txt:596) This construct is ambiguous as part of a sequence expression. Nested expressions may be written using 'let _ = (...)' and nested sequences using 'yield! seq {... }'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:627) + (Originally from src/fsharp/FSComp.txt:640) This construct is ambiguous as part of a computation expression. Nested expressions may be written using 'let _ = (...)' and nested computations using 'let! res = builder { ... }'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:626) + (Originally from src/fsharp/FSComp.txt:639) One or more of the explicit class or function type variables for this binding could not be generalized, because they were constrained to other types - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:495) + (Originally from src/fsharp/FSComp.txt:508) Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1072) + (Originally from src/fsharp/FSComp.txt:1089) The 'ConditionalAttribute' attribute may only be used on members - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:659) + (Originally from src/fsharp/FSComp.txt:672) Interfaces cannot contain definitions of concrete members. You may need to define a constructor on your type to indicate that the type is a class. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:700) + (Originally from src/fsharp/FSComp.txt:713) The 'CompiledName' attribute cannot be used with this language element - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:588) + (Originally from src/fsharp/FSComp.txt:601) Cannot partially apply the extension method '%s' because the first parameter is a byref type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1450) + (Originally from src/fsharp/FSComp.txt:1473) Cannot override inherited member '%s' because it is sealed - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1193) + (Originally from src/fsharp/FSComp.txt:1211) Cannot inherit from a variable type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:586) + (Originally from src/fsharp/FSComp.txt:599) Cannot inherit a sealed type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:779) + (Originally from src/fsharp/FSComp.txt:792) Cannot inherit from interface type. Use interface ... with instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:780) + (Originally from src/fsharp/FSComp.txt:793) Cannot inherit from erased provided type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1188) + (Originally from src/fsharp/FSComp.txt:1206) Cannot create an extension of a sealed type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:607) + (Originally from src/fsharp/FSComp.txt:620) Cannot call the byref extension method '%s. The first parameter requires the value to be mutable or a non-readonly byref type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1448) + (Originally from src/fsharp/FSComp.txt:1471) Cannot call an abstract base member: '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1056) + (Originally from src/fsharp/FSComp.txt:1073) '%s' must be applied to an argument of type '%s', but has been applied to an argument of type '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1096) + (Originally from src/fsharp/FSComp.txt:1112) '%s' can only be applied to optional arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1097) + (Originally from src/fsharp/FSComp.txt:1113) Byref types are not allowed to have optional type extensions. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1449) + (Originally from src/fsharp/FSComp.txt:1472) A byref pointer returned by a function or method is implicitly dereferenced as of F# 4.5. To acquire the return value as a pointer, use the address-of operator, e.g. '&f(x)' or '&obj.Method(arg1, arg2)'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1437) + (Originally from src/fsharp/FSComp.txt:1460) A type annotated with IsByRefLike must also be a struct. Consider adding the [<Struct>] attribute to the type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1438) + (Originally from src/fsharp/FSComp.txt:1461) A binding cannot be marked both 'use' and 'rec' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:655) + (Originally from src/fsharp/FSComp.txt:668) 'let!', 'use!' and 'do!' expressions may not be used in queries - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1264) + (Originally from src/fsharp/FSComp.txt:1282) '%s' must be followed by a variable name. Usage: %s. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1217) + (Originally from src/fsharp/FSComp.txt:1235) '%s' must come after a 'for' selection clause and be followed by the rest of the query. Syntax: ... %s ... - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1219) + (Originally from src/fsharp/FSComp.txt:1237) 'member val' definitions are only permitted in types with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1255) + (Originally from src/fsharp/FSComp.txt:1273) + + + + + Attributes cannot be applied to type extensions. + (Originally from src/fsharp/FSComp.txt:1478) The attributes of this type specify multiple kinds for the type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:756) + (Originally from src/fsharp/FSComp.txt:769) Attributes are not allowed within patterns - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:517) + (Originally from src/fsharp/FSComp.txt:530) Attributes are not permitted on 'let' bindings in expressions - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:657) + (Originally from src/fsharp/FSComp.txt:670) This attribute is not valid for use on this language element. Assembly attributes should be attached to a 'do ()' declaration, if necessary within an F# module. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:674) + (Originally from src/fsharp/FSComp.txt:687) This attribute is not valid for use on this language element - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:675) + (Originally from src/fsharp/FSComp.txt:688) Attribute expressions must be calls to object constructors - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:682) + (Originally from src/fsharp/FSComp.txt:695) The attribute 'AutoOpen(\"%s\")' in the assembly '%s' did not refer to a valid module or namespace in that assembly and has been ignored - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:803) + (Originally from src/fsharp/FSComp.txt:816) The attribute '%s' appears in both the implementation and the signature, but the attribute arguments differ. Only the attribute from the signature will be included in the compiled code. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1055) + (Originally from src/fsharp/FSComp.txt:1072) At least one override did not correctly implement its corresponding abstract member - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:617) + (Originally from src/fsharp/FSComp.txt:630) The member '%s' does not accept the correct number of arguments. One overload accepts %d arguments, but %d were given. The required signature is '%s'.%s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:603) + (Originally from src/fsharp/FSComp.txt:616) The member '%s' does not accept the correct number of arguments. %d argument(s) are expected, but %d were given. The required signature is '%s'.%s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:602) + (Originally from src/fsharp/FSComp.txt:615) Anonymous unit-of-measure cannot be nested inside another unit-of-measure expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:546) + (Originally from src/fsharp/FSComp.txt:559) Anonymous type variables are not permitted in this declaration - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:547) + (Originally from src/fsharp/FSComp.txt:560) + + + + + This anonymous record has too many fields. Remove the extra fields %s. + (Originally from src/fsharp/FSComp.txt:1368) + + + + + This anonymous record does not have enough fields. Add the missing fields %s. + (Originally from src/fsharp/FSComp.txt:1367) - Two anonymous record types have mismatched sets of field names '%s' and '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1346) + This anonymous record does not exactly match the expected shape. Add the missing fields %s and remove the extra fields %s. + (Originally from src/fsharp/FSComp.txt:1366) + + + + + This is the wrong anonymous record. It should have the fields %s. + (Originally from src/fsharp/FSComp.txt:1369) Two anonymous record types are from different assemblies '%s' and '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1345) + (Originally from src/fsharp/FSComp.txt:1365) + + + + + This feature is not supported in this version of F#. You may need to add /langversion:preview to use this feature. + (Originally from src/fsharp/FSComp.txt:1487) Types with the 'AllowNullLiteral' attribute may only inherit from or implement types which also allow the use of the null literal - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:764) + (Originally from src/fsharp/FSComp.txt:777) All implemented interfaces should be declared on the initial declaration of the type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:738) + (Originally from src/fsharp/FSComp.txt:751) Active patterns do not have fields. This syntax is invalid. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1299) + (Originally from src/fsharp/FSComp.txt:1317) 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. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:592) + (Originally from src/fsharp/FSComp.txt:605) This property overrides or implements an abstract property but the abstract property doesn't have a corresponding %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:693) + (Originally from src/fsharp/FSComp.txt:706) Abstract members are not permitted in an augmentation - they must be defined as part of the type itself - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:686) + (Originally from src/fsharp/FSComp.txt:699) Abbreviations for Common IL exception types must have a matching object constructor - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:751) + (Originally from src/fsharp/FSComp.txt:764) Abbreviations for Common IL exceptions cannot take arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:749) + (Originally from src/fsharp/FSComp.txt:762) Abbreviated types cannot be given the 'Sealed' attribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:778) + (Originally from src/fsharp/FSComp.txt:791) F# supports array ranks between 1 and 32. The value %d is not allowed. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1259) + (Originally from src/fsharp/FSComp.txt:1277) A value must be mutable in order to mutate the contents or take the address of a value type, e.g. 'let mutable x = ...' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:85) + (Originally from src/fsharp/FSComp.txt:86) A value defined in a module must be mutable in order to take its address, e.g. 'let mutable x = ...' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1441) + (Originally from src/fsharp/FSComp.txt:1464) The value has been copied to ensure the original is not mutated by this operation or because the copy is implicit when returning a struct from a member and another member is then accessed - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:87) + (Originally from src/fsharp/FSComp.txt:88) This value does not have a valid property setter type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:81) + (Originally from src/fsharp/FSComp.txt:82) Unexpected decode of InternalsVisibleToAttribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:92) + (Originally from src/fsharp/FSComp.txt:93) Unexpected decode of InterfaceDataVersionAttribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:93) + (Originally from src/fsharp/FSComp.txt:94) Unexpected decode of AutoOpenAttribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:91) + (Originally from src/fsharp/FSComp.txt:92) Unexpected use of a byref-typed variable - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:84) + (Originally from src/fsharp/FSComp.txt:85) The module/namespace '%s' from compilation unit '%s' did not contain the val '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1050) + (Originally from src/fsharp/FSComp.txt:1067) The module/namespace '%s' from compilation unit '%s' did not contain the namespace, module or type '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1051) + (Originally from src/fsharp/FSComp.txt:1068) The module/namespace '%s' from compilation unit '%s' did not contain the module/namespace '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1049) + (Originally from src/fsharp/FSComp.txt:1066) The type/module '%s' is not a concrete module or type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:74) + (Originally from src/fsharp/FSComp.txt:74) The type '%s' has an inline assembly code representation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:75) + (Originally from src/fsharp/FSComp.txt:75) Two modules named '%s' occur in two parts of this assembly - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:77) + (Originally from src/fsharp/FSComp.txt:78) Recursively defined values cannot appear directly as part of the construction of a tuple value within a recursive binding - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:88) + (Originally from src/fsharp/FSComp.txt:89) Recursive values cannot be directly assigned to the non-mutable field '%s' of the type '%s' within a recursive binding. Consider using a mutable field instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:90) + (Originally from src/fsharp/FSComp.txt:91) Recursive values cannot appear directly as a construction of the type '%s' within a recursive binding. This feature has been removed from the F# language. Consider using a record instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:89) + (Originally from src/fsharp/FSComp.txt:90) This is not a valid constant expression or custom attribute value - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:95) + (Originally from src/fsharp/FSComp.txt:96) A namespace and a module named '%s' both occur in two parts of this assembly - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:76) + (Originally from src/fsharp/FSComp.txt:77) Invalid mutation of a constant expression. Consider copying the expression to a mutable local, e.g. 'let mutable x = ...'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:86) + (Originally from src/fsharp/FSComp.txt:87) Invalid member signature encountered because of an earlier error - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:80) + (Originally from src/fsharp/FSComp.txt:81) Invalid form for a property setter. At least one argument is required. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:83) + (Originally from src/fsharp/FSComp.txt:84) Invalid form for a property getter. At least one '()' argument is required when using the explicit syntax. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:82) + (Originally from src/fsharp/FSComp.txt:83) This operation accesses a mutable top-level value defined in another assembly in an unsupported way. The value cannot be accessed through its address. Consider copying the expression to a mutable local, e.g. 'let mutable x = ...', and if necessary assigning the value back after the completion of the operation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1043) + (Originally from src/fsharp/FSComp.txt:1060) Two type definitions named '%s' occur in namespace '%s' in two parts of this assembly - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:78) + (Originally from src/fsharp/FSComp.txt:79) This literal expression or attribute argument results in an arithmetic overflow. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1304) + (Originally from src/fsharp/FSComp.txt:1322) A module and a type definition named '%s' occur in namespace '%s' in two parts of this assembly - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:79) + (Originally from src/fsharp/FSComp.txt:80) Cannot take the address of the value returned from the expression. Assign the returned value to a let-bound value before taking the address. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1447) + (Originally from src/fsharp/FSComp.txt:1470) Active patterns cannot return more than 7 possibilities - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:94) + (Originally from src/fsharp/FSComp.txt:95) The struct or class field '%s' is not accessible from this code location - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:946) + (Originally from src/fsharp/FSComp.txt:963) Source file is too large to embed in a portable PDB - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:851) + (Originally from src/fsharp/FSComp.txt:865) @@ -3286,2766 +3370,2850 @@ Consider using 'return!' instead of 'return'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:30) + (Originally from src/fsharp/FSComp.txt:31) Replace with '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:18) + (Originally from src/fsharp/FSComp.txt:19) Recursive class hierarchy in type '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:938) + (Originally from src/fsharp/FSComp.txt:955) A ReadOnly attribute has been applied to a struct type with a mutable field. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1436) + (Originally from src/fsharp/FSComp.txt:1459) Unexpected token '%s' in preprocessor expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1311) + (Originally from src/fsharp/FSComp.txt:1329) Missing token '%s' in preprocessor expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1313) + (Originally from src/fsharp/FSComp.txt:1331) Incomplete preprocessor expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1312) + (Originally from src/fsharp/FSComp.txt:1330) Unexpected character '%s' in preprocessor expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1310) + (Originally from src/fsharp/FSComp.txt:1328) Expected single line comment or end of line - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1023) + (Originally from src/fsharp/FSComp.txt:1040) An error occurred while reading the F# metadata of assembly '%s'. A reserved construct was utilized. You may need to upgrade your F# compiler or use an earlier version of the assembly that doesn't make use of a specific construct. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1430) + (Originally from src/fsharp/FSComp.txt:1453) An error occurred while reading the F# metadata node at position %d in table '%s' of assembly '%s'. The node had no matching declaration. Please report this warning. You may need to recompile the F# assembly you are using. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1314) + (Originally from src/fsharp/FSComp.txt:1332) Error reading/writing metadata for the F# compiled DLL '%s'. Was the DLL compiled with an earlier version of the F# compiler? (error: '%s'). - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:73) + (Originally from src/fsharp/FSComp.txt:73) A pattern match guard must be of type 'bool', but this 'when' expression is of type '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:26) + (Originally from src/fsharp/FSComp.txt:27) Problem with filename '%s': Illegal characters in path. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1135) + (Originally from src/fsharp/FSComp.txt:1151) Partial active patterns may only generate one result - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:956) + (Originally from src/fsharp/FSComp.txt:973) Missing variable '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:955) + (Originally from src/fsharp/FSComp.txt:972) Missing 'do' in 'while' expression. Expected 'while <expr> do <expr>'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1243) + (Originally from src/fsharp/FSComp.txt:1261) Accessibility modifiers are not permitted on an 'inherits' declaration - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:411) + (Originally from src/fsharp/FSComp.txt:423) Accessibility modifiers should come immediately prior to the identifier naming a construct - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:382) + (Originally from src/fsharp/FSComp.txt:394) 'use' bindings are not permitted in modules and are treated as 'let' bindings - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:375) + (Originally from src/fsharp/FSComp.txt:387) 'use' bindings are not permitted in primary constructors - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:374) + (Originally from src/fsharp/FSComp.txt:386) Unmatched 'with' or badly formatted 'with' block - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:398) + (Originally from src/fsharp/FSComp.txt:410) Incomplete value definition. If this is in an expression, the body of the expression must be indented to the same column as the 'use!' keyword. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1241) + (Originally from src/fsharp/FSComp.txt:1259) Incomplete value definition. If this is in an expression, the body of the expression must be indented to the same column as the 'use' keyword. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1242) + (Originally from src/fsharp/FSComp.txt:1260) Unmatched '(' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:424) + (Originally from src/fsharp/FSComp.txt:437) Incomplete value definition. If this is in an expression, the body of the expression must be indented to the same column as the 'let!' keyword. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1240) + (Originally from src/fsharp/FSComp.txt:1258) Incomplete value or function definition. If this is in an expression, the body of the expression must be indented to the same column as the 'let' keyword. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1239) + (Originally from src/fsharp/FSComp.txt:1257) Unmatched '[<'. Expected closing '>]' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1223) + (Originally from src/fsharp/FSComp.txt:1241) Unmatched 'class', 'interface' or 'struct' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:396) + (Originally from src/fsharp/FSComp.txt:408) Unmatched '[|' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:440) + (Originally from src/fsharp/FSComp.txt:453) Unmatched '[' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:435) + (Originally from src/fsharp/FSComp.txt:448) Unmatched '{|' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:442) + (Originally from src/fsharp/FSComp.txt:455) Unmatched '{' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:441) + (Originally from src/fsharp/FSComp.txt:454) Unmatched 'begin' or 'struct' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:389) + (Originally from src/fsharp/FSComp.txt:401) Unmatched 'begin' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:401) + (Originally from src/fsharp/FSComp.txt:413) Unmatched '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:439) + (Originally from src/fsharp/FSComp.txt:452) Accessibility modifiers are not permitted on union cases. Use 'type U = internal ...' or 'type U = private ...' to give an accessibility to the whole representation. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:419) + (Originally from src/fsharp/FSComp.txt:432) Unexpected token '%s' or incomplete expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1279) + (Originally from src/fsharp/FSComp.txt:1297) Accessibility modifiers are not permitted here, but '%s' was given. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:380) + (Originally from src/fsharp/FSComp.txt:392) Syntax error: unexpected type parameter specification - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:452) + (Originally from src/fsharp/FSComp.txt:465) Unexpected symbol '=' in expression. Did you intend to use 'for x in y .. z do' instead? - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1344) + (Originally from src/fsharp/FSComp.txt:1362) + + + + + Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + (Originally from src/fsharp/FSComp.txt:431) A semicolon is not expected at this point - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:378) + (Originally from src/fsharp/FSComp.txt:390) Unexpected quotation operator '<@' in type definition. If you intend to pass a verbatim string as a static argument to a type provider, put a space between the '<' and '@' characters. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1093) + (Originally from src/fsharp/FSComp.txt:1109) Unexpected infix operator in unit-of-measure expression. Legal operators are '*', '/' and '^'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:450) + (Originally from src/fsharp/FSComp.txt:463) Unexpected integer literal in unit-of-measure expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:451) + (Originally from src/fsharp/FSComp.txt:464) Unexpected infix operator in type expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:447) + (Originally from src/fsharp/FSComp.txt:460) Unexpected identifier: '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:418) + (Originally from src/fsharp/FSComp.txt:430) Unexpected end of input in 'match' or 'try' expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1228) + (Originally from src/fsharp/FSComp.txt:1246) Unexpected end of input in 'while' expression. Expected 'while <expr> do <expr>'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1226) + (Originally from src/fsharp/FSComp.txt:1244) Unexpected end of input in type signature - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1233) + (Originally from src/fsharp/FSComp.txt:1251) Unexpected end of input in type definition - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1234) + (Originally from src/fsharp/FSComp.txt:1252) Unexpected end of input in type arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1232) + (Originally from src/fsharp/FSComp.txt:1250) Unexpected end of input in 'try' expression. Expected 'try <expr> with <rules>' or 'try <expr> finally <expr>'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1225) + (Originally from src/fsharp/FSComp.txt:1243) Unexpected end of input in 'then' branch of conditional expression. Expected 'if <expr> then <expr>' or 'if <expr> then <expr> else <expr>'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1229) + (Originally from src/fsharp/FSComp.txt:1247) Unexpected end of input in object members - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1235) + (Originally from src/fsharp/FSComp.txt:1253) Unexpected end of input in 'match' expression. Expected 'match <expr> with | <pat> -> <expr> | <pat> -> <expr> ...'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1224) + (Originally from src/fsharp/FSComp.txt:1242) Unexpected end of input in body of lambda expression. Expected 'fun <pat> ... <pat> -> <expr>'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1231) + (Originally from src/fsharp/FSComp.txt:1249) Unexpected end of input in 'for' expression. Expected 'for <pat> in <expr> do <expr>'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1227) + (Originally from src/fsharp/FSComp.txt:1245) Unexpected end of input in expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1237) + (Originally from src/fsharp/FSComp.txt:1255) Unexpected end of input in 'else' branch of conditional expression. Expected 'if <expr> then <expr>' or 'if <expr> then <expr> else <expr>'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1230) + (Originally from src/fsharp/FSComp.txt:1248) Unexpected end of input in value, function or member definition - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1236) + (Originally from src/fsharp/FSComp.txt:1254) Unexpected end of input - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:379) + (Originally from src/fsharp/FSComp.txt:391) Unexpected empty type moduleDefn list - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:391) + (Originally from src/fsharp/FSComp.txt:403) '_' cannot be used as field name - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1293) + (Originally from src/fsharp/FSComp.txt:1311) Unclosed block - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:388) + (Originally from src/fsharp/FSComp.txt:400) Type name cannot be empty. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1281) + (Originally from src/fsharp/FSComp.txt:1299) Type annotations on property getters and setters must be given after the 'get()' or 'set(v)', e.g. 'with get() : string = ...' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:404) + (Originally from src/fsharp/FSComp.txt:416) Accessibility modifiers are not permitted in this position for type abbreviations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:414) + (Originally from src/fsharp/FSComp.txt:426) The syntax 'module ... = struct .. end' is not used in F# code. Consider using 'module ... = begin .. end' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:458) + (Originally from src/fsharp/FSComp.txt:471) The syntax 'module ... : sig .. end' is not used in F# code. Consider using 'module ... = begin .. end' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:459) + (Originally from src/fsharp/FSComp.txt:472) Syntax error in labelled type argument - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:446) + (Originally from src/fsharp/FSComp.txt:459) Syntax error - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:394) + (Originally from src/fsharp/FSComp.txt:406) Successive patterns should be separated by spaces or tupled - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:425) + (Originally from src/fsharp/FSComp.txt:438) Successive arguments should be separated by spaces or tupled, and arguments involving function or method applications should be parenthesized - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:434) + (Originally from src/fsharp/FSComp.txt:447) A setter property may have at most two argument groups - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1040) + (Originally from src/fsharp/FSComp.txt:1057) Property setters must be defined using 'set value = ', 'set idx value = ' or 'set (idx1,...,idxN) value = ... ' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:407) + (Originally from src/fsharp/FSComp.txt:419) Accessibility modifiers are not permitted on record fields. Use 'type R = internal ...' or 'type R = private ...' to give an accessibility to the whole representation. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:422) + (Originally from src/fsharp/FSComp.txt:435) In F# code you may use 'expr.[expr]'. A type annotation may be required to indicate the first expression is an array - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:437) + (Originally from src/fsharp/FSComp.txt:450) At most one 'with' augmentation is permitted - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:377) + (Originally from src/fsharp/FSComp.txt:389) Only '#' compiler directives may occur prior to the first 'namespace' declaration - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:381) + (Originally from src/fsharp/FSComp.txt:393) Only class types may take value arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:400) + (Originally from src/fsharp/FSComp.txt:412) The use of the type syntax 'int C' and 'C <int>' is not permitted here. Consider adjusting this type to be written in the form 'C<int>' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1046) + (Originally from src/fsharp/FSComp.txt:1063) Remove spaces between the type name and type parameter, e.g. \"type C<'T>\", not type \"C <'T>\". Type parameters must be placed directly adjacent to the type name. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1044) + (Originally from src/fsharp/FSComp.txt:1061) Remove spaces between the type name and type parameter, e.g. \"C<'T>\", not \"C <'T>\". Type parameters must be placed directly adjacent to the type name. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1045) + (Originally from src/fsharp/FSComp.txt:1062) No matching 'in' found for this 'let' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:426) + (Originally from src/fsharp/FSComp.txt:439) No #endif found for #if or #else - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:372) + (Originally from src/fsharp/FSComp.txt:384) No '=' symbol should follow a 'namespace' declaration - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:457) + (Originally from src/fsharp/FSComp.txt:470) Files should begin with either a namespace or module declaration, e.g. 'namespace SomeNamespace.SubNamespace' or 'module SomeNamespace.SomeModule', but not both. To define a module within a namespace use 'module SomeModule = ...' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:383) + (Originally from src/fsharp/FSComp.txt:395) To indicate that this property can be set, use 'member val PropertyName = expr with get,set'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1257) + (Originally from src/fsharp/FSComp.txt:1275) Property definitions may not be declared mutable. To indicate that this property can be set, use 'member val PropertyName = expr with get,set'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1256) + (Originally from src/fsharp/FSComp.txt:1274) Multiple accessibilities given for property getter or setter - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:406) + (Originally from src/fsharp/FSComp.txt:418) The syntax '(typ,...,typ) ident' is not used in F# code. Consider using 'ident<typ,...,typ>' instead - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:448) + (Originally from src/fsharp/FSComp.txt:461) A module name must be a simple name, not a path - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:390) + (Originally from src/fsharp/FSComp.txt:402) A module abbreviation must be a simple name, not a path - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:384) + (Originally from src/fsharp/FSComp.txt:396) Expected type argument or static argument - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1091) + (Originally from src/fsharp/FSComp.txt:1107) Missing qualification after '.' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:436) + (Originally from src/fsharp/FSComp.txt:449) Unmatched '<'. Expected closing '>' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1092) + (Originally from src/fsharp/FSComp.txt:1108) Missing function body - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:445) + (Originally from src/fsharp/FSComp.txt:458) Mismatched quotation, beginning with '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:438) + (Originally from src/fsharp/FSComp.txt:451) Mismatched quotation operator name, beginning with '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:453) + (Originally from src/fsharp/FSComp.txt:466) This member is not permitted in an object implementation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:444) + (Originally from src/fsharp/FSComp.txt:457) The declaration form 'let ... and ...' for non-recursive bindings is not used in F# code. Consider using a sequence of 'let' bindings - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:423) + (Originally from src/fsharp/FSComp.txt:436) Invalid use of 'rec' keyword - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1333) + (Originally from src/fsharp/FSComp.txt:1351) Invalid property getter or setter - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1041) + (Originally from src/fsharp/FSComp.txt:1058) Invalid operator definition. Prefix operator definitions must use a valid prefix operator name. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1065) + (Originally from src/fsharp/FSComp.txt:1082) Invalid prefix operator - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1064) + (Originally from src/fsharp/FSComp.txt:1081) Invalid literal in type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:449) + (Originally from src/fsharp/FSComp.txt:462) Invalid declaration syntax - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:402) + (Originally from src/fsharp/FSComp.txt:414) Invalid anonymous record type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1453) + (Originally from src/fsharp/FSComp.txt:1476) Invalid anonymous record expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1452) + (Originally from src/fsharp/FSComp.txt:1475) Interfaces always have the same visibility as the enclosing type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:408) + (Originally from src/fsharp/FSComp.txt:420) An integer for loop must use a simple identifier - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:376) + (Originally from src/fsharp/FSComp.txt:388) Accessibility modifiers are not permitted on inline assembly code types - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:417) + (Originally from src/fsharp/FSComp.txt:429) 'inherit' declarations cannot have 'as' bindings. To access members of the base class when overriding a method, the syntax 'base.SomeMember' may be used; 'base' is a keyword. Remove this 'as' binding. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:412) + (Originally from src/fsharp/FSComp.txt:424) An indexer property must be given at least one argument - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1042) + (Originally from src/fsharp/FSComp.txt:1059) Incomplete conditional. Expected 'if <expr> then <expr>' or 'if <expr> then <expr> else <expr>'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:429) + (Originally from src/fsharp/FSComp.txt:442) 'in' or '=' expected - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:432) + (Originally from src/fsharp/FSComp.txt:445) Neither 'member val' nor 'override val' definitions are permitted in object expressions. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1291) + (Originally from src/fsharp/FSComp.txt:1309) Denominator must not be 0 in unit-of-measure exponent - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:456) + (Originally from src/fsharp/FSComp.txt:469) The '%s' visibility attribute is not allowed on module abbreviation. Module abbreviations are always private. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:387) + (Originally from src/fsharp/FSComp.txt:399) The '%s' accessibility attribute is not allowed on module abbreviation. Module abbreviations are always private. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:386) + (Originally from src/fsharp/FSComp.txt:398) Ignoring attributes on module abbreviation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:385) + (Originally from src/fsharp/FSComp.txt:397) Identifier expected - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:431) + (Originally from src/fsharp/FSComp.txt:444) A getter property is expected to be a function, e.g. 'get() = ...' or 'get(index) = ...' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:405) + (Originally from src/fsharp/FSComp.txt:417) A getter property may have at most one argument group - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1039) + (Originally from src/fsharp/FSComp.txt:1056) 'get', 'set' or 'get,set' required - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:399) + (Originally from src/fsharp/FSComp.txt:411) 'get' and/or 'set' required - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:403) + (Originally from src/fsharp/FSComp.txt:415) Missing 'do' in 'for' expression. Expected 'for <pat> in <expr> do <expr>'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1244) + (Originally from src/fsharp/FSComp.txt:1262) Field bindings must have the form 'id = expr;' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:443) + (Originally from src/fsharp/FSComp.txt:456) Expected a type after this point - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1222) + (Originally from src/fsharp/FSComp.txt:1240) Unexpected end of type. Expected a name after this point. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1238) + (Originally from src/fsharp/FSComp.txt:1256) Expected an expression after this point - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1221) + (Originally from src/fsharp/FSComp.txt:1239) The block following this '%s' is unfinished. Every code block is an expression and must have a result. '%s' cannot be the final code element in a block. Consider giving this block an explicit result. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:428) + (Originally from src/fsharp/FSComp.txt:441) Attempted to parse this as an operator name, but failed - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1094) + (Originally from src/fsharp/FSComp.txt:1110) Error in the return expression for this 'let'. Possible incorrect indentation. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:427) + (Originally from src/fsharp/FSComp.txt:440) End of file in verbatim string embedded in comment begun at or before here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:369) + (Originally from src/fsharp/FSComp.txt:381) End of file in verbatim string begun at or before here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:366) + (Originally from src/fsharp/FSComp.txt:378) End of file in triple-quote string embedded in comment begun at or before here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1089) + (Originally from src/fsharp/FSComp.txt:1105) End of file in triple-quote string begun at or before here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1088) + (Originally from src/fsharp/FSComp.txt:1104) End of file in string embedded in comment begun at or before here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:368) + (Originally from src/fsharp/FSComp.txt:380) End of file in string begun at or before here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:365) + (Originally from src/fsharp/FSComp.txt:377) End of file in IF-OCAML section begun at or before here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:370) + (Originally from src/fsharp/FSComp.txt:382) End of file in #if section begun at or after here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:364) + (Originally from src/fsharp/FSComp.txt:376) End of file in directive begun at or before here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:371) + (Originally from src/fsharp/FSComp.txt:383) End of file in comment begun at or before here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:367) + (Originally from src/fsharp/FSComp.txt:379) Accessibility modifiers are not permitted in this position for enum types - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:415) + (Originally from src/fsharp/FSComp.txt:427) Accessibility modifiers are not permitted on enumeration fields - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:420) + (Originally from src/fsharp/FSComp.txt:433) A type definition requires one or more members or other declarations. If you intend to define an empty class, struct or interface, then use 'type ... = class end', 'interface end' or 'struct end'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:397) + (Originally from src/fsharp/FSComp.txt:409) Accessibility modifiers are not permitted on 'do' bindings, but '%s' was given. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:363) + (Originally from src/fsharp/FSComp.txt:375) Consider using a separate record type instead - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:421) + (Originally from src/fsharp/FSComp.txt:434) Augmentations are not permitted on delegate type moduleDefns - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:395) + (Originally from src/fsharp/FSComp.txt:407) Attributes should be placed before 'val' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:392) + (Originally from src/fsharp/FSComp.txt:404) Attributes are not permitted on 'inherit' declarations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:410) + (Originally from src/fsharp/FSComp.txt:422) Attributes are not allowed here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:413) + (Originally from src/fsharp/FSComp.txt:425) Attributes have been ignored in this construct - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:373) + (Originally from src/fsharp/FSComp.txt:385) Attributes are not permitted on interface implementations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:393) + (Originally from src/fsharp/FSComp.txt:405) Cannot find code target for this attribute, possibly because the code after the attribute is incomplete. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1280) + (Originally from src/fsharp/FSComp.txt:1298) 'assert' may not be used as a first class value. Use 'assert <expr>' instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:430) + (Originally from src/fsharp/FSComp.txt:443) The use of '->' in sequence and computation expressions is limited to the form 'for pat in expr -> expr'. Use the syntax 'for ... in ... do ... yield...' to generate elements in more complex sequence expressions. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:433) + (Originally from src/fsharp/FSComp.txt:446) All enum fields must be given values - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:416) + (Originally from src/fsharp/FSComp.txt:428) Active pattern case identifiers must begin with an uppercase letter - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:454) + (Originally from src/fsharp/FSComp.txt:467) The '|' character is not permitted in active pattern case identifiers - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:455) + (Originally from src/fsharp/FSComp.txt:468) Accessibility modifiers are not allowed on this member. Abstract slots always have the same visibility as the enclosing type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:409) + (Originally from src/fsharp/FSComp.txt:421) + + + + + Package manager key '%s' was not registered in %s. Currently registered: %s + (Originally from src/fsharp/FSComp.txt:1363) + + + + + %s + (Originally from src/fsharp/FSComp.txt:1364) + + + + + The package management feature requires language version 5.0 use /langversion:preview + (Originally from src/fsharp/FSComp.txt:1484) Write the xmldoc of the assembly to the given file - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:835) + (Originally from src/fsharp/FSComp.txt:848) Specify a Win32 resource file (.res) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:843) + (Originally from src/fsharp/FSComp.txt:857) Specify a Win32 manifest file - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:844) + (Originally from src/fsharp/FSComp.txt:858) Report all warnings as errors - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:860) + (Originally from src/fsharp/FSComp.txt:875) Report specific warnings as errors - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:861) + (Originally from src/fsharp/FSComp.txt:876) Enable specific warnings that may be off by default - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:864) + (Originally from src/fsharp/FSComp.txt:879) Set a warning level (0-5) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:862) + (Originally from src/fsharp/FSComp.txt:877) Output messages in UTF-8 encoding - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:872) + (Originally from src/fsharp/FSComp.txt:887) Enable high-entropy ASLR - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:903) + (Originally from src/fsharp/FSComp.txt:920) Unrecognized target '%s', expected 'exe', 'winexe', 'library' or 'module' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:882) + (Originally from src/fsharp/FSComp.txt:898) + + + + + Unrecognized value '%s' for --langversion use --langversion:? for complete list + (Originally from src/fsharp/FSComp.txt:76) Unrecognized debug type '%s', expected 'pdbonly' or 'full' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:883) + (Originally from src/fsharp/FSComp.txt:899) Unrecognized platform '%s', valid values are 'x86', 'x64', 'Itanium', 'anycpu32bitpreferred', and 'anycpu' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:897) + (Originally from src/fsharp/FSComp.txt:913) + + + + + Algorithm '%s' is not supported + (Originally from src/fsharp/FSComp.txt:914) Unknown --test argument: '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:896) + (Originally from src/fsharp/FSComp.txt:912) Specify target framework profile of this assembly. Valid values are mscorlib, netcore or netstandard. Default - mscorlib - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:905) + (Originally from src/fsharp/FSComp.txt:922) Enable or disable tailcalls - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:857) + (Originally from src/fsharp/FSComp.txt:871) + + + + + Supported language versions: + (Originally from src/fsharp/FSComp.txt:1495) Specify subsystem version of this assembly - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:904) + (Originally from src/fsharp/FSComp.txt:921) Specify a strong name key file - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:836) + (Originally from src/fsharp/FSComp.txt:849) Specify a strong name key container - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:837) + (Originally from src/fsharp/FSComp.txt:850) Statically link the given assembly and all referenced DLLs that depend on this assembly. Use an assembly name e.g. mylib, not a DLL name. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:878) + (Originally from src/fsharp/FSComp.txt:894) Statically link the F# library and all referenced DLLs that depend on it into the assembly being generated - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:877) + (Originally from src/fsharp/FSComp.txt:893) --sourcelink switch only supported when emitting a Portable PDB (--debug:portable or --debug:embedded) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:850) + (Originally from src/fsharp/FSComp.txt:864) Source link information file to embed in the portable PDB file - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:848) + (Originally from src/fsharp/FSComp.txt:862) Resolve assembly references using directory-based rules rather than MSBuild resolution - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:881) + (Originally from src/fsharp/FSComp.txt:897) Print the inferred interface of the assembly to a file - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:841) + (Originally from src/fsharp/FSComp.txt:854) Short form of '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:885) + (Originally from src/fsharp/FSComp.txt:901) Response file '%s' not found in '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1322) + (Originally from src/fsharp/FSComp.txt:1340) Response file name '%s' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1323) + (Originally from src/fsharp/FSComp.txt:1341) Read response file for more options - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:870) + (Originally from src/fsharp/FSComp.txt:885) Embed the specified managed resource - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:852) + (Originally from src/fsharp/FSComp.txt:866) Use a resident background compilation service to improve compiler startup times. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:879) + (Originally from src/fsharp/FSComp.txt:895) Reference an assembly (Short form: -r) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:842) + (Originally from src/fsharp/FSComp.txt:855) Public-sign the assembly using only the public portion of the strong name key, and mark the assembly as signed - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:834) + (Originally from src/fsharp/FSComp.txt:847) Problem with codepage '%d': %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:825) + (Originally from src/fsharp/FSComp.txt:838) Specify the preferred output language culture name (e.g. es-ES, ja-JP) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:907) + (Originally from src/fsharp/FSComp.txt:924) Limit which platforms this code can run on: x86, Itanium, x64, anycpu32bitpreferred, or anycpu. The default is anycpu. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:838) + (Originally from src/fsharp/FSComp.txt:851) Name the output debug file - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:880) + (Originally from src/fsharp/FSComp.txt:896) + + + + + Maps physical paths to source path names output by the compiler + (Originally from src/fsharp/FSComp.txt:873) Enable optimizations (Short form: -O) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:856) + (Originally from src/fsharp/FSComp.txt:870) Do not include the default Win32 manifest - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:845) + (Originally from src/fsharp/FSComp.txt:859) Disable specific warning messages - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:863) + (Originally from src/fsharp/FSComp.txt:878) Suppress compiler copyright message - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:868) + (Originally from src/fsharp/FSComp.txt:883) Do not reference the default CLI assemblies by default - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:876) + (Originally from src/fsharp/FSComp.txt:892) Only include optimization information essential for implementing inlined constructs. Inhibits cross-module inlining but improves binary compatibility. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:839) + (Originally from src/fsharp/FSComp.txt:852) Don't add a resource to the generated assembly containing F#-specific metadata - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:840) + (Originally from src/fsharp/FSComp.txt:853) Don't copy FSharp.Core.dll along the produced binaries - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:908) + (Originally from src/fsharp/FSComp.txt:925) Name of the output file (Short form: -o) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:828) + (Originally from src/fsharp/FSComp.txt:841) Ignore ML compatibility warnings - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:867) + (Originally from src/fsharp/FSComp.txt:882) Link the specified resource to this assembly where the resinfo format is <file>[,<string name>[,public|private]] - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:853) + (Originally from src/fsharp/FSComp.txt:867) Specify a directory for the include path which is used to resolve source files and assemblies (Short form: -I) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:874) + (Originally from src/fsharp/FSComp.txt:889) + + + + + Display the allowed values for language version, specify language version such as 'latest' or 'preview' + (Originally from src/fsharp/FSComp.txt:1494) Invalid warning level '%d' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:884) + (Originally from src/fsharp/FSComp.txt:900) Invalid value '%s' for '--targetprofile', valid values are 'mscorlib', 'netcore' or 'netstandard'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:910) + (Originally from src/fsharp/FSComp.txt:927) Invalid version '%s' for '--subsystemversion'. The version must be 4.00 or greater. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:909) + (Originally from src/fsharp/FSComp.txt:926) Invalid response file '%s' ( '%s' ) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1321) + (Originally from src/fsharp/FSComp.txt:1339) + + + + + Invalid path map. Mappings must be comma separated and of the format 'path=sourcePath' + (Originally from src/fsharp/FSComp.txt:1157) The command-line option '%s' is for test purposes only - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:898) + (Originally from src/fsharp/FSComp.txt:915) - RESOURCES - - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:890) + (Originally from src/fsharp/FSComp.txt:906) - OUTPUT FILES - - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:888) + (Originally from src/fsharp/FSComp.txt:904) - MISCELLANEOUS - - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:893) + (Originally from src/fsharp/FSComp.txt:909) - LANGUAGE - - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:894) + (Originally from src/fsharp/FSComp.txt:910) - INPUT FILES - - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:889) + (Originally from src/fsharp/FSComp.txt:905) - ERRORS AND WARNINGS - - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:895) + (Originally from src/fsharp/FSComp.txt:911) - CODE GENERATION - - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:891) + (Originally from src/fsharp/FSComp.txt:907) - ADVANCED - - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:892) + (Originally from src/fsharp/FSComp.txt:908) Display this usage message (Short form: -?) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:869) + (Originally from src/fsharp/FSComp.txt:884) Output messages with fully qualified paths - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:873) + (Originally from src/fsharp/FSComp.txt:888) Emit debug information in quotations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:906) + (Originally from src/fsharp/FSComp.txt:923) --embed switch only supported when emitting a Portable PDB (--debug:portable or --debug:embedded) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:849) + (Originally from src/fsharp/FSComp.txt:863) Embed specific source files in the portable PDB file - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:847) + (Originally from src/fsharp/FSComp.txt:861) Embed all source files in the portable PDB file - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:846) + (Originally from src/fsharp/FSComp.txt:860) Produce a deterministic assembly (including module version GUID and timestamp) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:858) + (Originally from src/fsharp/FSComp.txt:872) Delay-sign the assembly using only the public portion of the strong name key - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:833) + (Originally from src/fsharp/FSComp.txt:846) Define conditional compilation symbols (Short form: -d) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:866) + (Originally from src/fsharp/FSComp.txt:881) Emit debug information (Short form: -g) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:854) + (Originally from src/fsharp/FSComp.txt:868) Specify debugging type: full, portable, embedded, pdbonly. ('%s' is the default if no debuggging type specified and enables attaching a debugger to a running program, 'portable' is a cross-platform format, 'embedded' is a cross-platform format embedded into the output file). - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:855) + (Originally from src/fsharp/FSComp.txt:869) The command-line option '%s' has been deprecated - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:899) + (Originally from src/fsharp/FSComp.txt:916) The command-line option '%s' has been deprecated. HTML document generation is now part of the F# Power Pack, via the tool FsHtmlDoc.exe. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:901) + (Originally from src/fsharp/FSComp.txt:918) The command-line option '%s' has been deprecated. Use '%s' instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:900) + (Originally from src/fsharp/FSComp.txt:917) Enable or disable cross-module optimizations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:859) + (Originally from src/fsharp/FSComp.txt:874) Freely distributed under the MIT Open Source License. https://github.com/Microsoft/visualfsharp/blob/master/License.txt - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:827) + (Originally from src/fsharp/FSComp.txt:840) Copyright (c) Microsoft Corporation. All Rights Reserved. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:826) + (Originally from src/fsharp/FSComp.txt:839) Output warning and error messages in color - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:902) + (Originally from src/fsharp/FSComp.txt:919) + + + + + Reference an assembly or directory containing a design time tool (Short form: -t) + (Originally from src/fsharp/FSComp.txt:856) Specify the codepage used to read source files - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:871) + (Originally from src/fsharp/FSComp.txt:886) Use to override where the compiler looks for mscorlib.dll and framework components - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:887) + (Originally from src/fsharp/FSComp.txt:903) The command-line option '--cliroot' has been deprecated. Use an explicit reference to a specific copy of mscorlib.dll instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:886) + (Originally from src/fsharp/FSComp.txt:902) + + + + + Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) + (Originally from src/fsharp/FSComp.txt:891) Generate overflow checks - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:865) + (Originally from src/fsharp/FSComp.txt:880) Build a Windows executable - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:830) + (Originally from src/fsharp/FSComp.txt:843) Build a module that can be added to another assembly - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:832) + (Originally from src/fsharp/FSComp.txt:845) Build a library (Short form: -a) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:831) + (Originally from src/fsharp/FSComp.txt:844) Build a console executable - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:829) + (Originally from src/fsharp/FSComp.txt:842) Base address for the library to be built - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:875) + (Originally from src/fsharp/FSComp.txt:890) A value marked as 'inline' has an unexpected value - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:965) + (Originally from src/fsharp/FSComp.txt:982) A value marked as 'inline' could not be inlined - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:966) + (Originally from src/fsharp/FSComp.txt:983) The value '%s' was marked inline but was not bound in the optimization environment - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:963) + (Originally from src/fsharp/FSComp.txt:980) The value '%s' was marked inline but its implementation makes use of an internal or private function which is not sufficiently accessible - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:962) + (Originally from src/fsharp/FSComp.txt:979) Recursive ValValue %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:968) + (Originally from src/fsharp/FSComp.txt:985) Local value %s not found during optimization - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:964) + (Originally from src/fsharp/FSComp.txt:981) Failed to inline the value '%s' marked 'inline', perhaps because a recursive value was marked 'inline' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:967) + (Originally from src/fsharp/FSComp.txt:984) The union type for union case '%s' was defined with the RequireQualifiedAccessAttribute. Include the name of the union type ('%s') in the name you are using. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:982) + (Originally from src/fsharp/FSComp.txt:999) Unexpected empty long identifier - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:977) + (Originally from src/fsharp/FSComp.txt:994) Multiple types exist called '%s', taking different numbers of generic parameters. Provide a type instantiation to disambiguate the type resolution, e.g. '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:973) + (Originally from src/fsharp/FSComp.txt:990) The instantiation of the generic type '%s' is missing and can't be inferred from the arguments or return type of this member. Consider providing a type instantiation when accessing this type, e.g. '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:974) + (Originally from src/fsharp/FSComp.txt:991) The record type for the record field '%s' was defined with the RequireQualifiedAccessAttribute. Include the name of the record type ('%s') in the name you are using. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:983) + (Originally from src/fsharp/FSComp.txt:1000) The record type '%s' does not contain a label '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:978) + (Originally from src/fsharp/FSComp.txt:995) No constructors are available for the type '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:981) + (Originally from src/fsharp/FSComp.txt:998) This is not a constructor or literal, or a constructor is being used incorrectly - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:976) + (Originally from src/fsharp/FSComp.txt:993) Invalid module/expression/type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:972) + (Originally from src/fsharp/FSComp.txt:989) Invalid field label - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:979) + (Originally from src/fsharp/FSComp.txt:996) Invalid expression '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:980) + (Originally from src/fsharp/FSComp.txt:997) 'global' may only be used as the first name in a qualified path - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:975) + (Originally from src/fsharp/FSComp.txt:992) This value is not a function and cannot be applied. Did you intend to access the indexer via %s.[index] instead? - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1425) + (Originally from src/fsharp/FSComp.txt:1448) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1427) + (Originally from src/fsharp/FSComp.txt:1450) This expression is not a function and cannot be applied. Did you intend to access the indexer via expr.[index] instead? - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1426) + (Originally from src/fsharp/FSComp.txt:1449) This value is not a function and cannot be applied. Did you forget to terminate a declaration? - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1428) + (Originally from src/fsharp/FSComp.txt:1451) This value is not a function and cannot be applied. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1424) + (Originally from src/fsharp/FSComp.txt:1447) No Invoke methods found for delegate type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:948) + (Originally from src/fsharp/FSComp.txt:965) Files in libraries or multiple-file applications must begin with a namespace or module declaration. When using a module declaration at the start of a file the '=' sign is not allowed. If this is a top-level module, consider removing the = to resolve this error. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:51) + (Originally from src/fsharp/FSComp.txt:51) + %d overloads - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1277) + (Originally from src/fsharp/FSComp.txt:1295) + 1 overload - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1276) + (Originally from src/fsharp/FSComp.txt:1294) + + + + + Resource header beginning at offset %s is malformed. + (Originally from src/fsharp/FSComp.txt:1497) + + + + + Stream does not begin with a null resource and is not in '.RES' format. + (Originally from src/fsharp/FSComp.txt:1496) More than one Invoke method found for delegate type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:949) + (Originally from src/fsharp/FSComp.txt:966) This construct is for ML compatibility. %s. You can disable this warning by using '--mlcompatibility' or '--nowarn:62'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1060) + (Originally from src/fsharp/FSComp.txt:1077) This 'if' expression is missing an 'else' branch. Because 'if' is an expression, and not a statement, add an 'else' branch which also returns a value of type '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:22) + (Originally from src/fsharp/FSComp.txt:23) Method or object constructor '%s' is not static - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1343) + (Originally from src/fsharp/FSComp.txt:1361) Infix operator member '%s' has %d initial argument(s). Expected a tuple of 3 arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1288) + (Originally from src/fsharp/FSComp.txt:1306) Infix operator member '%s' has %d initial argument(s). Expected a tuple of 2 arguments, e.g. static member (+) (x,y) = ... - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1025) + (Originally from src/fsharp/FSComp.txt:1042) Infix operator member '%s' has no arguments. Expected a tuple of 2 arguments, e.g. static member (+) (x,y) = ... - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1024) + (Originally from src/fsharp/FSComp.txt:1041) Infix operator member '%s' has extra curried arguments. Expected a tuple of 2 arguments, e.g. static member (+) (x,y) = ... - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1026) + (Originally from src/fsharp/FSComp.txt:1043) (loading description...) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1284) + (Originally from src/fsharp/FSComp.txt:1302) All elements of a list must be of the same type as the first element, which here is '%s'. This element has type '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:20) + (Originally from src/fsharp/FSComp.txt:21) Identifiers containing '@' are reserved for use in F# code generation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:953) + (Originally from src/fsharp/FSComp.txt:970) The identifier '%s' is reserved for future use by F# - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:954) + (Originally from src/fsharp/FSComp.txt:971) Possible incorrect indentation: this token is offside of context started at position %s. Try indenting this token further or using standard formatting conventions. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:970) + (Originally from src/fsharp/FSComp.txt:987) The '|' tokens separating rules of this pattern match are misaligned by one column. Consider realigning your code or using further indentation. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:971) + (Originally from src/fsharp/FSComp.txt:988) The indentation of this 'in' token is incorrect with respect to the corresponding 'let' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:969) + (Originally from src/fsharp/FSComp.txt:986) Syntax error. Wrong nested #endif, unexpected tokens before it. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1021) + (Originally from src/fsharp/FSComp.txt:1038) Unexpected character '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:990) + (Originally from src/fsharp/FSComp.txt:1007) This token is reserved for future use - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1011) + (Originally from src/fsharp/FSComp.txt:1028) This Unicode encoding is only valid in string literals - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1010) + (Originally from src/fsharp/FSComp.txt:1027) TABs are not allowed in F# code unless the #indent \"off\" option is used - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1012) + (Originally from src/fsharp/FSComp.txt:1029) This number is outside the allowable range for 32-bit unsigned integers - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:999) + (Originally from src/fsharp/FSComp.txt:1016) This number is outside the allowable range for 32-bit signed integers - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:998) + (Originally from src/fsharp/FSComp.txt:1015) This number is outside the allowable range for 64-bit unsigned integers - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1001) + (Originally from src/fsharp/FSComp.txt:1018) This number is outside the allowable range for 64-bit signed integers - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1000) + (Originally from src/fsharp/FSComp.txt:1017) This number is outside the allowable range for 16-bit unsigned integers - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:997) + (Originally from src/fsharp/FSComp.txt:1014) This number is outside the allowable range for 16-bit signed integers - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:996) + (Originally from src/fsharp/FSComp.txt:1013) This number is outside the allowable range for unsigned native integers - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1003) + (Originally from src/fsharp/FSComp.txt:1020) This number is outside the allowable range for signed native integers - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1002) + (Originally from src/fsharp/FSComp.txt:1019) This number is outside the allowable range for this integer type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:985) + (Originally from src/fsharp/FSComp.txt:1002) This number is outside the allowable range for 8-bit unsigned integers - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:995) + (Originally from src/fsharp/FSComp.txt:1012) This number is outside the allowable range for hexadecimal 8-bit signed integers - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:994) + (Originally from src/fsharp/FSComp.txt:1011) This number is outside the allowable range for 8-bit signed integers - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:993) + (Originally from src/fsharp/FSComp.txt:1010) This number is outside the allowable range for 32-bit floats - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1006) + (Originally from src/fsharp/FSComp.txt:1023) This number is outside the allowable range for decimal literals - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1005) + (Originally from src/fsharp/FSComp.txt:1022) \U%s is not a valid Unicode character escape sequence - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1095) + (Originally from src/fsharp/FSComp.txt:1111) - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0b0001 (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1007) + This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). + (Originally from src/fsharp/FSComp.txt:1024) Invalid line number: '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1013) + (Originally from src/fsharp/FSComp.txt:1030) Invalid floating point number - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1004) + (Originally from src/fsharp/FSComp.txt:1021) This is not a valid character literal - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1009) + (Originally from src/fsharp/FSComp.txt:1026) This is not a valid byte literal - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1008) + (Originally from src/fsharp/FSComp.txt:1025) Consider using a file with extension '.ml' or '.mli' instead - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1067) + (Originally from src/fsharp/FSComp.txt:1084) Identifiers followed by '%s' are reserved for future use - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:992) + (Originally from src/fsharp/FSComp.txt:1009) #if directive should be immediately followed by an identifier - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1020) + (Originally from src/fsharp/FSComp.txt:1037) #if directive must appear as the first non-whitespace character on a line - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1014) + (Originally from src/fsharp/FSComp.txt:1031) #endif has no matching #if - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1018) + (Originally from src/fsharp/FSComp.txt:1035) #endif required for #else - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1016) + (Originally from src/fsharp/FSComp.txt:1033) #endif directive must appear as the first non-whitespace character on a line - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1019) + (Originally from src/fsharp/FSComp.txt:1036) #else has no matching #if - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1015) + (Originally from src/fsharp/FSComp.txt:1032) #else directive must appear as the first non-whitespace character on a line - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1017) + (Originally from src/fsharp/FSComp.txt:1034) #! may only appear as the first line at the start of a file. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1022) + (Originally from src/fsharp/FSComp.txt:1039) '%s' is not permitted as a character in operator names and is reserved for future use - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:989) + (Originally from src/fsharp/FSComp.txt:1006) This byte array literal contains characters that do not encode as a single byte - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:991) + (Originally from src/fsharp/FSComp.txt:1008) Used in mutually recursive bindings, in property declarations, and with multiple constraints on generic parameters. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1348) + (Originally from src/fsharp/FSComp.txt:1371) Used in a computation expression to append the result of a given computation expression to a collection of results for the containing computation expression. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1414) + (Originally from src/fsharp/FSComp.txt:1437) Used in a sequence expression to produce a value for a sequence. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1413) + (Originally from src/fsharp/FSComp.txt:1436) Used together with the match keyword in pattern matching expressions. Also used in object expressions, record copying expressions, and type extensions to introduce member definitions, and to introduce exception handlers. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1412) + (Originally from src/fsharp/FSComp.txt:1435) Introduces a looping construct. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1411) + (Originally from src/fsharp/FSComp.txt:1434) Used for Boolean conditions (when guards) on pattern matches and to introduce a constraint clause for a generic type parameter. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1410) + (Originally from src/fsharp/FSComp.txt:1433) Indicates the .NET void type. Used when interoperating with other .NET languages. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1409) + (Originally from src/fsharp/FSComp.txt:1432) Used in a signature to indicate a value, or in a type to declare a member, in limited situations. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1408) + (Originally from src/fsharp/FSComp.txt:1431) Used instead of let! in computation expressions for computation expression results that implement IDisposable. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1407) + (Originally from src/fsharp/FSComp.txt:1430) Used instead of let for values that implement IDisposable - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1406) + (Originally from src/fsharp/FSComp.txt:1429) Used to convert to a type that is higher in the inheritance chain. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1405) + (Originally from src/fsharp/FSComp.txt:1428) Delimits a untyped code quotation. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1420) + (Originally from src/fsharp/FSComp.txt:1443) Delimits a typed code quotation. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1419) + (Originally from src/fsharp/FSComp.txt:1442) Used to declare a class, record, structure, discriminated union, enumeration type, unit of measure, or type abbreviation. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1404) + (Originally from src/fsharp/FSComp.txt:1427) Used to introduce a block of code that might generate an exception. Used together with with or finally. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1403) + (Originally from src/fsharp/FSComp.txt:1426) Used as a Boolean literal. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1365) + (Originally from src/fsharp/FSComp.txt:1388) Used in for loops to indicate a range. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1402) + (Originally from src/fsharp/FSComp.txt:1425) Used in conditional expressions. Also used to perform side effects after object construction. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1401) + (Originally from src/fsharp/FSComp.txt:1424) Used to declare a structure type. Also used in generic parameter constraints. Used for OCaml compatibility in module definitions. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1400) + (Originally from src/fsharp/FSComp.txt:1423) Used to indicate a method or property that can be called without an instance of a type, or a value member that is shared among all instances of a type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1399) + (Originally from src/fsharp/FSComp.txt:1422) Used in query expressions to specify what fields or columns to extract. Note that this is a contextual keyword, which means that it is not actually a reserved word and it only acts like a keyword in appropriate context. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1398) + (Originally from src/fsharp/FSComp.txt:1421) In function types, delimits arguments and return values. Yields an expression (in sequence expressions); equivalent to the yield keyword. Used in match expressions - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1415) + (Originally from src/fsharp/FSComp.txt:1438) Used to provide a value for the result of the containing computation expression, where that value itself comes from the result another computation expression. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1397) + (Originally from src/fsharp/FSComp.txt:1420) Used to provide a value for the result of the containing computation expression. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1396) + (Originally from src/fsharp/FSComp.txt:1419) Used to indicate that a function is recursive. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1395) + (Originally from src/fsharp/FSComp.txt:1418) Allows access to a member from outside the type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1394) + (Originally from src/fsharp/FSComp.txt:1417) Restricts access to a member to code in the same type or module. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1393) + (Originally from src/fsharp/FSComp.txt:1416) Used to implement a version of an abstract or virtual method that differs from the base version. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1392) + (Originally from src/fsharp/FSComp.txt:1415) Used with Boolean conditions as a Boolean or operator. Equivalent to ||. Also used in member constraints. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1391) + (Originally from src/fsharp/FSComp.txt:1414) Used to make the contents of a namespace or module available without qualification. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1390) + (Originally from src/fsharp/FSComp.txt:1413) Used in discriminated unions to indicate the type of categories of values, and in delegate and exception declarations. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1389) + (Originally from src/fsharp/FSComp.txt:1412) Indicates the absence of an object. Also used in generic parameter constraints. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1388) + (Originally from src/fsharp/FSComp.txt:1411) Not actually a keyword. However, not struct in combination is used as a generic parameter constraint. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1387) + (Originally from src/fsharp/FSComp.txt:1410) Used to declare, define, or invoke a constructor that creates or that can create an object. Also used in generic parameter constraints to indicate that a type must have a certain constructor. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1386) + (Originally from src/fsharp/FSComp.txt:1409) Used to associate a name with a group of related types and modules, to logically separate it from other code. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1385) + (Originally from src/fsharp/FSComp.txt:1408) Used to declare a variable, that is, a value that can be changed. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1384) + (Originally from src/fsharp/FSComp.txt:1407) Used to associate a name with a group of related types, values, and functions, to logically separate it from other code. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1383) + (Originally from src/fsharp/FSComp.txt:1406) Used to declare a property or method in an object type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1382) + (Originally from src/fsharp/FSComp.txt:1405) Used in computation expressions to pattern match directly over the result of another computation expression. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1381) + (Originally from src/fsharp/FSComp.txt:1404) Used to branch by comparing a value to a pattern. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1380) + (Originally from src/fsharp/FSComp.txt:1403) Used in computation expressions to bind a name to the result of another computation expression. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1379) + (Originally from src/fsharp/FSComp.txt:1402) Used to associate, or bind, a name to a value or function. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1378) + (Originally from src/fsharp/FSComp.txt:1401) Assigns a value to a variable. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1416) + (Originally from src/fsharp/FSComp.txt:1439) Used to specify a computation that is to be performed only when a result is needed. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1377) + (Originally from src/fsharp/FSComp.txt:1400) Used to specify that a member is visible inside an assembly but not outside it. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1376) + (Originally from src/fsharp/FSComp.txt:1399) Used to declare and implement interfaces. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1375) + (Originally from src/fsharp/FSComp.txt:1398) Used to indicate a function that should be integrated directly into the caller's code. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1374) + (Originally from src/fsharp/FSComp.txt:1397) Used to specify a base class or base interface. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1373) + (Originally from src/fsharp/FSComp.txt:1396) Used for sequence expressions and, in verbose syntax, to separate expressions from bindings. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1372) + (Originally from src/fsharp/FSComp.txt:1395) Used in conditional branching constructs. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1371) + (Originally from src/fsharp/FSComp.txt:1394) Used to reference the top-level .NET namespace. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1370) + (Originally from src/fsharp/FSComp.txt:1393) Used as a shorter alternative to the fun keyword and a match expression in a lambda expression that has pattern matching on a single argument. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1369) + (Originally from src/fsharp/FSComp.txt:1392) Used in lambda expressions, also known as anonymous functions. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1368) + (Originally from src/fsharp/FSComp.txt:1391) Used in looping constructs. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1367) + (Originally from src/fsharp/FSComp.txt:1390) Used together with try to introduce a block of code that executes regardless of whether an exception occurs. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1366) + (Originally from src/fsharp/FSComp.txt:1389) Indicates that a declared program element is defined in another binary or assembly. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1364) + (Originally from src/fsharp/FSComp.txt:1387) Used to declare an exception type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1363) + (Originally from src/fsharp/FSComp.txt:1386) In type definitions and type extensions, indicates the end of a section of member definitions. In verbose syntax, used to specify the end of a code block that starts with the begin keyword. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1362) + (Originally from src/fsharp/FSComp.txt:1385) Used in conditional branching. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1361) + (Originally from src/fsharp/FSComp.txt:1384) Used in conditional branching. A short form of else if. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1360) + (Originally from src/fsharp/FSComp.txt:1383) Converts a type to a type that is lower in the hierarchy. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1418) + (Originally from src/fsharp/FSComp.txt:1441) In a for expression, used when counting in reverse. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1359) + (Originally from src/fsharp/FSComp.txt:1382) Used to convert to a type that is lower in the inheritance chain. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1358) + (Originally from src/fsharp/FSComp.txt:1381) In verbose syntax, indicates the end of a block of code in a looping expression. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1357) + (Originally from src/fsharp/FSComp.txt:1380) Used in looping constructs or to execute imperative code. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1356) + (Originally from src/fsharp/FSComp.txt:1379) Used to declare a delegate. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1355) + (Originally from src/fsharp/FSComp.txt:1378) Indicates an implementation of an abstract method; used together with an abstract method declaration to create a virtual method. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1354) + (Originally from src/fsharp/FSComp.txt:1377) In verbose syntax, indicates the start of a class definition. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1353) + (Originally from src/fsharp/FSComp.txt:1376) Converts a type to type that is higher in the hierarchy. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1417) + (Originally from src/fsharp/FSComp.txt:1440) In verbose syntax, indicates the start of a code block. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1352) + (Originally from src/fsharp/FSComp.txt:1375) Used as the name of the base class object. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1351) + (Originally from src/fsharp/FSComp.txt:1374) Used to verify code during debugging. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1350) + (Originally from src/fsharp/FSComp.txt:1373) Used to give the current class object an object name. Also used to give a name to a whole pattern within a pattern match. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1349) + (Originally from src/fsharp/FSComp.txt:1372) Indicates a method that either has no implementation in the type in which it is declared or that is virtual and has a default implementation. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1347) + (Originally from src/fsharp/FSComp.txt:1370) %s '%s' not found in type '%s' from assembly '%s'. A possible cause may be a version incompatibility. You may need to explicitly reference the correct version of this assembly to allow all referenced components to use the correct version. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1422) + (Originally from src/fsharp/FSComp.txt:1445) %s '%s' not found in assembly '%s'. A possible cause may be a version incompatibility. You may need to explicitly reference the correct version of this assembly to allow all referenced components to use the correct version. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1421) + (Originally from src/fsharp/FSComp.txt:1444) The 'anycpu32bitpreferred' platform can only be used with EXE targets. You must use 'anycpu' instead. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1271) + (Originally from src/fsharp/FSComp.txt:1289) invalid namespace for provided type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1177) + (Originally from src/fsharp/FSComp.txt:1195) invalid full name for provided type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1178) + (Originally from src/fsharp/FSComp.txt:1196) Invalid provided literal value '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1270) + (Originally from src/fsharp/FSComp.txt:1288) This expression returns a value of type '%s' but is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to use the expression as a value in the sequence then use an explicit 'yield!'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1433) + (Originally from src/fsharp/FSComp.txt:1456) This expression returns a value of type '%s' but is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to use the expression as a value in the sequence then use an explicit 'yield'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1432) + (Originally from src/fsharp/FSComp.txt:1455) The type '%s' is required here and is unavailable. You must add a reference to assembly '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:957) + (Originally from src/fsharp/FSComp.txt:974) A reference to the type '%s' in assembly '%s' was found, but the type could not be found in that assembly - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:958) + (Originally from src/fsharp/FSComp.txt:975) A reference to the DLL %s is required by assembly %s. The imported type %s is located in the first assembly and could not be resolved. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:960) + (Originally from src/fsharp/FSComp.txt:977) Internal error or badly formed metadata: not enough type parameters were in scope while importing - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:959) + (Originally from src/fsharp/FSComp.txt:976) Invalid number of generic arguments to type '%s' in provided type. Expected '%d' arguments, given '%d'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1247) + (Originally from src/fsharp/FSComp.txt:1265) Invalid value unit-of-measure parameter '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1249) + (Originally from src/fsharp/FSComp.txt:1267) Invalid value '%s' for unit-of-measure parameter '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1248) + (Originally from src/fsharp/FSComp.txt:1266) An imported assembly uses the type '%s' but that type is not public - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:961) + (Originally from src/fsharp/FSComp.txt:978) Invalid argument to 'methodhandleof' during codegen - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1209) + (Originally from src/fsharp/FSComp.txt:1227) MDB generation failed. Could not find compatible member %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1076) + (Originally from src/fsharp/FSComp.txt:1093) The name of the MDB file must be <assembly-file-name>.mdb. The --pdb option will be ignored. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1075) + (Originally from src/fsharp/FSComp.txt:1092) Unexpected error creating debug information file '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:984) + (Originally from src/fsharp/FSComp.txt:1001) Cannot generate MDB debug information. Failed to load the 'MonoSymbolWriter' type from the 'Mono.CompilerServices.SymbolWriter.dll' assembly. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1077) + (Originally from src/fsharp/FSComp.txt:1094) The file '%s' changed on disk unexpectedly, please reload. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1434) + (Originally from src/fsharp/FSComp.txt:1457) Compiler error: unexpected unrealized value - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:817) + (Originally from src/fsharp/FSComp.txt:830) Unexpected GetSet annotation on a property - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:820) + (Originally from src/fsharp/FSComp.txt:833) Undefined value '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:804) + (Originally from src/fsharp/FSComp.txt:817) This type cannot be used for a literal field - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:819) + (Originally from src/fsharp/FSComp.txt:832) The StructLayout attribute could not be decoded - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:822) + (Originally from src/fsharp/FSComp.txt:835) GenSetStorage: %s was represented as a static method but was not an appropriate lambda expression - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:815) + (Originally from src/fsharp/FSComp.txt:828) The signature for this external function contains type parameters. Constrain the argument and return types to indicate the types of the corresponding C function. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:812) + (Originally from src/fsharp/FSComp.txt:825) RSA key expected - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1106) + (Originally from src/fsharp/FSComp.txt:1122) Private key expected - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1105) + (Originally from src/fsharp/FSComp.txt:1121) No signature directory - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1111) + (Originally from src/fsharp/FSComp.txt:1127) Invalid signature size - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1110) + (Originally from src/fsharp/FSComp.txt:1126) Invalid RSAParameters structure - '{0}' expected - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1108) + (Originally from src/fsharp/FSComp.txt:1124) Invalid Public Key blob - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1112) + (Originally from src/fsharp/FSComp.txt:1128) Invalid Magic value in CLR Header - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1103) + (Originally from src/fsharp/FSComp.txt:1119) Invalid bit Length - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1107) + (Originally from src/fsharp/FSComp.txt:1123) Invalid algId - 'Exponent' expected - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1109) + (Originally from src/fsharp/FSComp.txt:1125) Bad image format - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1104) + (Originally from src/fsharp/FSComp.txt:1120) Reflected definitions cannot contain uses of the prefix splice operator '%%' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:824) + (Originally from src/fsharp/FSComp.txt:837) Mutable variables cannot escape their method - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:816) + (Originally from src/fsharp/FSComp.txt:829) The MarshalAs attribute could not be decoded - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:811) + (Originally from src/fsharp/FSComp.txt:824) Main module of program is empty: nothing will happen when it is run - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:818) + (Originally from src/fsharp/FSComp.txt:831) Literal fields cannot be set - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:814) + (Originally from src/fsharp/FSComp.txt:827) Label %s not found - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:805) + (Originally from src/fsharp/FSComp.txt:818) Incorrect number of type arguments to local call - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:806) + (Originally from src/fsharp/FSComp.txt:819) The FieldOffset attribute could not be decoded - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:821) + (Originally from src/fsharp/FSComp.txt:834) The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1070) + (Originally from src/fsharp/FSComp.txt:1087) The type '%s' has been marked as having an Explicit layout, but the field '%s' has not been marked with the 'FieldOffset' attribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1062) + (Originally from src/fsharp/FSComp.txt:1079) Dynamic invocation of %s is not supported - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:807) + (Originally from src/fsharp/FSComp.txt:820) The DllImport attribute could not be decoded - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:813) + (Originally from src/fsharp/FSComp.txt:826) The DefaultAugmentation attribute could not be decoded - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:823) + (Originally from src/fsharp/FSComp.txt:836) Custom marshallers cannot be specified in F# code. Consider using a C# helper function. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:810) + (Originally from src/fsharp/FSComp.txt:823) This operation involves taking the address of a value '%s' represented using a local variable or other special representation. This is invalid. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:809) + (Originally from src/fsharp/FSComp.txt:822) Taking the address of a literal field is invalid - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:808) + (Originally from src/fsharp/FSComp.txt:821) The 'if' expression needs to have type '%s' to satisfy context type requirements. It currently has type '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:23) + (Originally from src/fsharp/FSComp.txt:24) @@ -6056,2197 +6224,2359 @@ Cannot find FSharp.Core.dll in compiler's directory - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1324) + (Originally from src/fsharp/FSComp.txt:1342) Conflicting options specified: 'win32manifest' and 'win32res'. Only one of these can be used. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1118) + (Originally from src/fsharp/FSComp.txt:1134) Exiting - too many errors - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1114) + (Originally from src/fsharp/FSComp.txt:1130) System.Runtime.InteropServices assembly is required to use UnknownWrapper\DispatchWrapper classes. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1306) + (Originally from src/fsharp/FSComp.txt:1324) Static linking may not be used on an assembly referencing mscorlib (e.g. a .NET Framework assembly) when generating an assembly that references System.Runtime (e.g. a .NET Core or Portable assembly). - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1137) + (Originally from src/fsharp/FSComp.txt:1153) Static linking may not include a mixed managed/unmanaged DLL - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1122) + (Originally from src/fsharp/FSComp.txt:1138) Static linking may not include a .EXE - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1121) + (Originally from src/fsharp/FSComp.txt:1137) Passing a .resx file (%s) as a source file to the compiler is deprecated. Use resgen.exe to transform the .resx file into a .resources file to pass as a --resource option. If you are using MSBuild, this can be done via an <EmbeddedResource> item in the .fsproj project file. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1136) + (Originally from src/fsharp/FSComp.txt:1152) The resident compilation service was not used because a problem occured in communicating with the server. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1134) + (Originally from src/fsharp/FSComp.txt:1150) The assembly '%s' is listed on the command line. Assemblies should be referenced using a command line flag such as '-r'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1133) + (Originally from src/fsharp/FSComp.txt:1149) Code in this assembly makes uses of quotation literals. Static linking may not include components that make use of quotation literals unless all assemblies are compiled with at least F# 4.0. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1120) + (Originally from src/fsharp/FSComp.txt:1136) The code in assembly '%s' makes uses of quotation literals. Static linking may not include components that make use of quotation literals unless all assemblies are compiled with at least F# 4.0. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1119) + (Originally from src/fsharp/FSComp.txt:1135) A problem occurred writing the binary '%s': %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1127) + (Originally from src/fsharp/FSComp.txt:1143) + + + + + --pathmap can only be used with portable PDBs (--debug:portable or --debug:embedded) + (Originally from src/fsharp/FSComp.txt:1156) No implementation files specified - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1116) + (Originally from src/fsharp/FSComp.txt:1132) Option '--keycontainer' overrides attribute 'System.Reflection.AssemblyNameAttribute' given in a source file or added module - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1132) + (Originally from src/fsharp/FSComp.txt:1148) Option '--keyfile' overrides attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file or added module - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1131) + (Originally from src/fsharp/FSComp.txt:1147) The key file '%s' could not be opened - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1126) + (Originally from src/fsharp/FSComp.txt:1142) Ignoring mixed managed/unmanaged assembly '%s' during static linking - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1123) + (Originally from src/fsharp/FSComp.txt:1139) - Determinstic builds only support portable PDBs (--debug:portable or --debug:embedded) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1139) + Deterministic builds only support portable PDBs (--debug:portable or --debug:embedded) + (Originally from src/fsharp/FSComp.txt:1155) Option '--delaysign' overrides attribute 'System.Reflection.AssemblyDelaySignAttribute' given in a source file or added module - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1130) + (Originally from src/fsharp/FSComp.txt:1146) The attribute %s specified version '%s', but this value is invalid and has been ignored - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1117) + (Originally from src/fsharp/FSComp.txt:1133) Assembly '%s' was referenced transitively and the assembly could not be resolved automatically. Static linking will assume this DLL has no dependencies on the F# library or other statically linked DLLs. Consider adding an explicit reference to this DLL. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1124) + (Originally from src/fsharp/FSComp.txt:1140) An %s specified version '%s', but this value is a wildcard, and you have requested a deterministic build, these are in conflict. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1138) + (Originally from src/fsharp/FSComp.txt:1154) The 'AssemblyVersionAttribute' has been ignored because a version was given using a command line option - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1128) + (Originally from src/fsharp/FSComp.txt:1144) Assembly '%s' not found in dependency set of target binary. Statically linked roots should be specified using an assembly name, without a DLL or EXE extension. If this assembly was referenced explicitly then it is possible the assembly was not actually required by the generated binary, in which case it should not be statically linked. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1125) + (Originally from src/fsharp/FSComp.txt:1141) Error emitting 'System.Reflection.AssemblyCultureAttribute' attribute -- 'Executables cannot be satellite assemblies, Culture should always be empty' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1129) + (Originally from src/fsharp/FSComp.txt:1145) + + + + + From the end slicing with requires language version 5.0, use /langversion:preview. + (Originally from src/fsharp/FSComp.txt:1485) + + + + + - %s + (Originally from src/fsharp/FSComp.txt:1498) Prefix flag (' ' or '+') set twice - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:220) + (Originally from src/fsharp/FSComp.txt:225) Precision missing after the '.' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:225) + (Originally from src/fsharp/FSComp.txt:230) Positional specifiers are not permitted in format strings - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:217) + (Originally from src/fsharp/FSComp.txt:222) Missing format specifier - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:218) + (Originally from src/fsharp/FSComp.txt:223) The 'l' or 'L' in this format specifier is unnecessary. In F# code you can use %%d, %%x, %%o or %%u instead, which are overloaded to work with all basic integer types. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:228) + (Originally from src/fsharp/FSComp.txt:233) The # formatting modifier is invalid in F# - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:221) + (Originally from src/fsharp/FSComp.txt:226) The 'h' or 'H' in this format specifier is unnecessary. You can use %%d, %%x, %%o or %%u instead, which are overloaded to work with all basic integer types. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:229) + (Originally from src/fsharp/FSComp.txt:234) '%s' format does not support precision - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:226) + (Originally from src/fsharp/FSComp.txt:231) '%s' flag set twice - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:219) + (Originally from src/fsharp/FSComp.txt:224) '%s' format does not support '0' flag - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:224) + (Originally from src/fsharp/FSComp.txt:229) '%s' does not support prefix '%s' flag - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:230) + (Originally from src/fsharp/FSComp.txt:235) Bad width in format specifier - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:223) + (Originally from src/fsharp/FSComp.txt:228) Bad precision in format specifier - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:222) + (Originally from src/fsharp/FSComp.txt:227) Bad format specifier: '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:231) + (Originally from src/fsharp/FSComp.txt:236) Bad format specifier (after l or L): Expected ld,li,lo,lu,lx or lX. In F# code you can use %%d, %%x, %%o or %%u instead, which are overloaded to work with all basic integer types. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:227) + (Originally from src/fsharp/FSComp.txt:232) All branches of a pattern match expression must return values of the same type as the first branch, which here is '%s'. This branch returns a value of type '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:25) + (Originally from src/fsharp/FSComp.txt:26) The record, struct or class field '%s' is not accessible from this code location - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:945) + (Originally from src/fsharp/FSComp.txt:962) + + + + + wild card in for loop + (Originally from src/fsharp/FSComp.txt:1500) + + + + + single underscore pattern + (Originally from src/fsharp/FSComp.txt:1499) + + + + + whitespace relexation + (Originally from src/fsharp/FSComp.txt:1501) + + + + + package management + (Originally from src/fsharp/FSComp.txt:1506) + + + + + open static classes + (Originally from src/fsharp/FSComp.txt:1504) + + + + + nullable optional interop + (Originally from src/fsharp/FSComp.txt:1510) + + + + + nameof + (Originally from src/fsharp/FSComp.txt:1502) + + + + + implicit yield + (Originally from src/fsharp/FSComp.txt:1503) + + + + + from-end slicing + (Originally from src/fsharp/FSComp.txt:1507) + + + + + fixed-index slice 3d/4d + (Originally from src/fsharp/FSComp.txt:1508) + + + + + dotless float32 literal + (Originally from src/fsharp/FSComp.txt:1505) + + + + + default interface member consumption + (Originally from src/fsharp/FSComp.txt:1511) + + + + + applicative computation expressions + (Originally from src/fsharp/FSComp.txt:1509) + + + + + %s for F# %s + (Originally from src/fsharp/FSComp.txt:1493) + + + + + Expression does not have a name. + (Originally from src/fsharp/FSComp.txt:1480) This construct is experimental - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:947) + (Originally from src/fsharp/FSComp.txt:964) The event '%s' has a non-standard type. If this event is declared in another CLI language, you may need to access this event using the explicit %s and %s methods for the event. If this event is declared in F#, make the type of the event an instantiation of either 'IDelegateEvent<_>' or 'IEvent<_,_>'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:940) + (Originally from src/fsharp/FSComp.txt:957) Unsupported expression '%s' from type provider. If you are the author of this type provider, consider adjusting it to provide a different provided expression. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1159) + (Originally from src/fsharp/FSComp.txt:1177) Invalid member '%s' on provided type '%s'. Only properties, methods and constructors are allowed - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1151) + (Originally from src/fsharp/FSComp.txt:1169) Unsupported constant type '%s'. Quotations provided by type providers can only contain simple constants. The implementation of the type provider may need to be adjusted by moving a value declared outside a provided quotation literal to be a 'let' binding inside the quotation literal. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1158) + (Originally from src/fsharp/FSComp.txt:1176) Unknown static argument kind '%s' when resolving a reference to a provided type or method '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1176) + (Originally from src/fsharp/FSComp.txt:1194) Unexpected 'null' return value from provided type '%s' member '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1171) + (Originally from src/fsharp/FSComp.txt:1189) Unexpected exception from provided type '%s' member '%s': %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1157) + (Originally from src/fsharp/FSComp.txt:1175) Unexpected exception from member '%s' of provided type '%s' member '%s': %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1172) + (Originally from src/fsharp/FSComp.txt:1190) The type provider constructor has thrown an exception: %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1181) + (Originally from src/fsharp/FSComp.txt:1199) Too many static parameters. Expected at most %d parameters, but got %d unnamed and %d named parameters. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1269) + (Originally from src/fsharp/FSComp.txt:1287) The static parameter '%s' of the provided type or method '%s' requires a value. Static parameters to type providers may be optionally specified using named arguments, e.g. '%s<%s=...>'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1201) + (Originally from src/fsharp/FSComp.txt:1219) The static parameter '%s' has already been given a value - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1203) + (Originally from src/fsharp/FSComp.txt:1221) The type provider returned 'null', which is not a valid return value from '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1180) + (Originally from src/fsharp/FSComp.txt:1198) Assembly attribute '%s' refers to a designer assembly '%s' which cannot be loaded or doesn't exist. %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1163) + (Originally from src/fsharp/FSComp.txt:1181) The type provider '%s' reported an error in the context of provided type '%s', member '%s'. The error: %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1194) + (Originally from src/fsharp/FSComp.txt:1212) The type provider '%s' reported an error: %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1165) + (Originally from src/fsharp/FSComp.txt:1183) The type provider does not have a valid constructor. A constructor taking either no arguments or one argument of type 'TypeProviderConfig' was expected. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1164) + (Originally from src/fsharp/FSComp.txt:1182) The '%s' of a provided type was null or empty. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1196) + (Originally from src/fsharp/FSComp.txt:1214) An exception occurred when accessing the '%s' of a provided type: %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1195) + (Originally from src/fsharp/FSComp.txt:1213) A reference to a provided type was missing a value for the static parameter '%s'. You may need to recompile one or more referenced assemblies. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1210) + (Originally from src/fsharp/FSComp.txt:1228) A reference to a provided type had an invalid value '%s' for a static parameter. You may need to recompile one or more referenced assemblies. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1211) + (Originally from src/fsharp/FSComp.txt:1229) Expected provided type with path '%s' but provided type has path '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1170) + (Originally from src/fsharp/FSComp.txt:1188) Expected provided type named '%s' but provided type has 'Name' with value '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1160) + (Originally from src/fsharp/FSComp.txt:1178) The type provider '%s' returned an invalid type from 'ApplyStaticArguments'. A type with name '%s' was expected, but a type with name '%s' was returned. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1183) + (Originally from src/fsharp/FSComp.txt:1201) The type provider '%s' returned an invalid method from 'ApplyStaticArgumentsForMethod'. A method with name '%s' was expected, but a method with name '%s' was returned. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1184) + (Originally from src/fsharp/FSComp.txt:1202) Property '%s' on provided type '%s' is neither readable nor writable as it has CanRead=false and CanWrite=false - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1250) + (Originally from src/fsharp/FSComp.txt:1268) Property '%s' on provided type '%s' has CanWrite=false but GetSetMethod() returned a method - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1155) + (Originally from src/fsharp/FSComp.txt:1173) Property '%s' on provided type '%s' has CanRead=false but GetGetMethod() returned a method - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1153) + (Originally from src/fsharp/FSComp.txt:1171) Property '%s' on provided type '%s' has CanWrite=true but there was no value from GetSetMethod() - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1154) + (Originally from src/fsharp/FSComp.txt:1172) Property '%s' on provided type '%s' has CanRead=true but there was no value from GetGetMethod() - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1152) + (Originally from src/fsharp/FSComp.txt:1170) One or more errors seen during provided type setup - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1156) + (Originally from src/fsharp/FSComp.txt:1174) Type provider '%s' returned null from GetInvokerExpression. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1182) + (Originally from src/fsharp/FSComp.txt:1200) The provided type '%s' returned a member with a null or empty member name - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1141) + (Originally from src/fsharp/FSComp.txt:1159) The provided type '%s' has member '%s' which has declaring type '%s'. Expected declaring type to be the same as provided type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1144) + (Originally from src/fsharp/FSComp.txt:1162) The provided type '%s' member info '%s' has null declaring type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1143) + (Originally from src/fsharp/FSComp.txt:1161) The provided type '%s' returned a null member - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1142) + (Originally from src/fsharp/FSComp.txt:1160) No static parameter exists with name '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1202) + (Originally from src/fsharp/FSComp.txt:1220) Nested provided types do not take static arguments or generic parameters - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1173) + (Originally from src/fsharp/FSComp.txt:1191) Provided type '%s' has 'IsGenericType' as true, but generic types are not supported. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1148) + (Originally from src/fsharp/FSComp.txt:1166) Provided type '%s' has 'IsArray' as true, but array types are not supported. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1149) + (Originally from src/fsharp/FSComp.txt:1167) Multiple static parameters exist with name '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1204) + (Originally from src/fsharp/FSComp.txt:1222) This provided method requires static parameters - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1326) + (Originally from src/fsharp/FSComp.txt:1344) Invalid member '%s' on provided type '%s'. Provided type members must be public, and not be generic, virtual, or abstract. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1150) + (Originally from src/fsharp/FSComp.txt:1168) Assembly '%s' hase TypeProviderAssembly attribute with invalid value '%s'. The value should be a valid assembly name - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1189) + (Originally from src/fsharp/FSComp.txt:1207) Invalid static argument to provided type. Expected an argument of kind '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1174) + (Originally from src/fsharp/FSComp.txt:1192) The type provider '%s' provided a method with a name '%s' and metadata token '%d', which is not reported among its methods of its declaring type '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1167) + (Originally from src/fsharp/FSComp.txt:1185) The type provider '%s' provided a constructor which is not reported among the constructors of its declaring type '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1168) + (Originally from src/fsharp/FSComp.txt:1186) The type provider '%s' used an invalid parameter in the ParameterExpression: %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1166) + (Originally from src/fsharp/FSComp.txt:1184) Character '%s' is not allowed in provided type name '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1197) + (Originally from src/fsharp/FSComp.txt:1215) Character '%s' is not allowed in provided namespace name '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1140) + (Originally from src/fsharp/FSComp.txt:1158) Referenced assembly '%s' has assembly level attribute '%s' but no public type provider classes were found - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1145) + (Originally from src/fsharp/FSComp.txt:1163) Event '%s' on provided type '%s' has no value from GetRemoveMethod() - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1162) + (Originally from src/fsharp/FSComp.txt:1180) Event '%s' on provided type '%s' has no value from GetAddMethod() - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1161) + (Originally from src/fsharp/FSComp.txt:1179) An error occured applying the static arguments to a provided type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1175) + (Originally from src/fsharp/FSComp.txt:1193) An error occured applying the static arguments to a provided method - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1309) + (Originally from src/fsharp/FSComp.txt:1327) The provider '%s' returned a non-generated type '%s' in the context of a set of generated types. Consider adjusting the type provider to only return generated types. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1273) + (Originally from src/fsharp/FSComp.txt:1291) Type '%s' from type provider '%s' has an empty namespace. Use 'null' for the global namespace. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1146) + (Originally from src/fsharp/FSComp.txt:1164) Empty namespace found from the type provider '%s'. Use 'null' for the global namespace. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1147) + (Originally from src/fsharp/FSComp.txt:1165) A direct reference to the generated type '%s' is not permitted. Instead, use a type definition, e.g. 'type TypeAlias = <path>'. This indicates that a type provider adds generated types to your assembly. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1169) + (Originally from src/fsharp/FSComp.txt:1187) Named static arguments must come after all unnamed static arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1200) + (Originally from src/fsharp/FSComp.txt:1218) A type provider implemented GetStaticParametersForMethod, but ApplyStaticArgumentsForMethod was not implemented or invalid - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1308) + (Originally from src/fsharp/FSComp.txt:1326) Erased to - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1278) + (Originally from src/fsharp/FSComp.txt:1296) All branches of an 'if' expression must return values of the same type as the first branch, which here is '%s'. This branch returns a value of type '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:24) + (Originally from src/fsharp/FSComp.txt:25) System.Environment.Exit did not exit - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:232) + (Originally from src/fsharp/FSComp.txt:237) The treatment of this operator is now handled directly by the F# compiler and its meaning cannot be redefined - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:233) + (Originally from src/fsharp/FSComp.txt:238) The documentation file has no .xml suffix - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1115) + (Originally from src/fsharp/FSComp.txt:1131) is - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1423) + (Originally from src/fsharp/FSComp.txt:1446) (description unavailable...) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1285) + (Originally from src/fsharp/FSComp.txt:1303) The '!' operator is used to dereference a ref cell. Consider using 'not expr' here. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:28) + (Originally from src/fsharp/FSComp.txt:29) Delegates are not allowed to have curried signatures - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:950) + (Originally from src/fsharp/FSComp.txt:967) %s var in collection - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1216) + (Originally from src/fsharp/FSComp.txt:1234) %s var in collection %s (outerKey = innerKey). Note that parentheses are required after '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1214) + (Originally from src/fsharp/FSComp.txt:1232) %s var in collection %s (outerKey = innerKey) into group. Note that parentheses are required after '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1215) + (Originally from src/fsharp/FSComp.txt:1233) None of the types '%s' support the operator '%s'. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:305) + (Originally from src/fsharp/FSComp.txt:310) None of the types '%s' support the operator '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:303) + (Originally from src/fsharp/FSComp.txt:308) This type parameter cannot be instantiated to 'Nullable'. This is a restriction imposed in order to ensure the meaning of 'null' in some CLI languages is not confusing when used in conjunction with 'Nullable' values. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:322) + (Originally from src/fsharp/FSComp.txt:327) The type '%s' is not compatible with any of the types %s, arising from the use of a printf-style format string - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:325) + (Originally from src/fsharp/FSComp.txt:330) The type '%s' is not a CLI enum type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:319) + (Originally from src/fsharp/FSComp.txt:324) The type '%s' is not a CLI delegate type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:321) + (Originally from src/fsharp/FSComp.txt:326) Type instantiation length mismatch - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:329) + (Originally from src/fsharp/FSComp.txt:334) Type inference problem too complicated (maximum iteration depth reached). Consider adding further type annotations. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:298) + (Originally from src/fsharp/FSComp.txt:303) The type '%s' has a non-standard delegate type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:320) + (Originally from src/fsharp/FSComp.txt:325) The type '%s' does not support the operator '%s'. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:306) + (Originally from src/fsharp/FSComp.txt:311) The type '%s' does not support the operator '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:304) + (Originally from src/fsharp/FSComp.txt:309) The type '%s' does not support the 'equality' constraint because it is a record, union or struct with one or more structural element types which do not support the 'equality' constraint. Either avoid the use of equality with this type, or add the 'StructuralEquality' attribute to the type to determine which field type does not support equality - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:318) + (Originally from src/fsharp/FSComp.txt:323) The type '%s' does not support the 'equality' constraint because it is a function type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:317) + (Originally from src/fsharp/FSComp.txt:322) The type '%s' does not support the 'equality' constraint because it has the 'NoEquality' attribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:316) + (Originally from src/fsharp/FSComp.txt:321) The type '%s' does not support a conversion to the type '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:307) + (Originally from src/fsharp/FSComp.txt:312) The type '%s' does not support the 'comparison' constraint because it is a record, union or struct with one or more structural element types which do not support the 'comparison' constraint. Either avoid the use of comparison with this type, or add the 'StructuralComparison' attribute to the type to determine which field type does not support comparison - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:315) + (Originally from src/fsharp/FSComp.txt:320) The type '%s' does not support the 'comparison' constraint. For example, it does not support the 'System.IComparable' interface - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:314) + (Originally from src/fsharp/FSComp.txt:319) The type '%s' does not support the 'comparison' constraint because it has the 'NoComparison' attribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:313) + (Originally from src/fsharp/FSComp.txt:318) The type '%s' does not have 'null' as a proper value - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:311) + (Originally from src/fsharp/FSComp.txt:316) The declared type parameter '%s' cannot be used here since the type parameter cannot be resolved at compile time - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:296) + (Originally from src/fsharp/FSComp.txt:301) The constraints 'struct' and 'not struct' are inconsistent - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:310) + (Originally from src/fsharp/FSComp.txt:315) - + - The available overloads are shown below. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:362) + The required signature is %s + (Originally from src/fsharp/FSComp.txt:347) - + - The required signature is %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:342) + Argument '%s' doesn't match + (Originally from src/fsharp/FSComp.txt:373) + + + + + Argument at index %d doesn't match + (Originally from src/fsharp/FSComp.txt:374) Optional arguments not permitted here - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:330) + (Originally from src/fsharp/FSComp.txt:335) The type '%s' does not have 'null' as a proper value. To create a null value for a Nullable type use 'System.Nullable()'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:312) + (Originally from src/fsharp/FSComp.txt:317) + + + + + Known type parameter: %s + (Originally from src/fsharp/FSComp.txt:367) + + + + + Known type parameters: %s + (Originally from src/fsharp/FSComp.txt:368) + + + + + Known return type: %s + (Originally from src/fsharp/FSComp.txt:369) + + + + + Known type of argument: %s + (Originally from src/fsharp/FSComp.txt:365) + + + + + Known types of arguments: %s + (Originally from src/fsharp/FSComp.txt:366) No overloads match for method '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:359) + (Originally from src/fsharp/FSComp.txt:364) No %s member or object constructor named '%s' takes %d arguments. The named argument '%s' doesn't correspond to any argument or settable return property for any overload. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:357) + (Originally from src/fsharp/FSComp.txt:362) No %s member or object constructor named '%s' takes %d arguments. Note the call to this member also provides %d named arguments. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:356) + (Originally from src/fsharp/FSComp.txt:361) No %s member or object constructor named '%s' takes %d arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:355) + (Originally from src/fsharp/FSComp.txt:360) Method or object constructor '%s' not found - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:358) + (Originally from src/fsharp/FSComp.txt:363) A unique overload for method '%s' could not be determined based on type information prior to this program point. A type annotation may be needed. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:360) + (Originally from src/fsharp/FSComp.txt:370) %s is not an instance method - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:339) + (Originally from src/fsharp/FSComp.txt:344) %s is not a static method - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:338) + (Originally from src/fsharp/FSComp.txt:343) The type '%s' has a method '%s' (full name '%s'), but the method is static - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:308) + (Originally from src/fsharp/FSComp.txt:313) The type '%s' has a method '%s' (full name '%s'), but the method is not static - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:309) + (Originally from src/fsharp/FSComp.txt:314) This method expects a CLI 'params' parameter in this position. 'params' is a way of passing a variable number of arguments to a method in languages such as C#. Consider passing an array for this argument - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:335) + (Originally from src/fsharp/FSComp.txt:340) The member or object constructor '%s' takes %d type argument(s) but is here given %d. The required signature is '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:351) + (Originally from src/fsharp/FSComp.txt:356) The member or object constructor '%s' requires %d argument(s) but is here given %d unnamed and %d named argument(s). The required signature is '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:347) + (Originally from src/fsharp/FSComp.txt:352) The member or object constructor '%s' takes %d argument(s) but is here given %d. The required signature is '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:348) + (Originally from src/fsharp/FSComp.txt:353) The member or object constructor '%s' requires %d additional argument(s). The required signature is '%s'. Some names for missing arguments are %s. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:346) + (Originally from src/fsharp/FSComp.txt:351) The member or object constructor '%s' requires %d argument(s). The required signature is '%s'. Some names for missing arguments are %s. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:345) + (Originally from src/fsharp/FSComp.txt:350) The member or object constructor '%s' requires %d additional argument(s). The required signature is '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:344) + (Originally from src/fsharp/FSComp.txt:349) The member or object constructor '%s' requires %d argument(s). The required signature is '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:343) + (Originally from src/fsharp/FSComp.txt:348) The member or object constructor '%s' does not take %d argument(s). An overload was found taking %d arguments. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:354) + (Originally from src/fsharp/FSComp.txt:359) A member or object constructor '%s' taking %d arguments is not accessible from this code location. All accessible versions of method '%s' take %d arguments. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:352) + (Originally from src/fsharp/FSComp.txt:357) %s is not a static member - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:331) + (Originally from src/fsharp/FSComp.txt:336) %s is not an instance member - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:332) + (Originally from src/fsharp/FSComp.txt:337) The member or object constructor '%s' is not %s. Private members may only be accessed from within the declaring type. Protected members may only be accessed from an extending type and cannot be accessed from inner lambda expressions. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:337) + (Originally from src/fsharp/FSComp.txt:342) The member or object constructor '%s' is not %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:336) + (Originally from src/fsharp/FSComp.txt:341) The member or object constructor '%s' has no argument or settable return property '%s'. %s. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:340) + (Originally from src/fsharp/FSComp.txt:345) This indexer expects %d arguments but is here given %d - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:300) + (Originally from src/fsharp/FSComp.txt:305) Incorrect generic instantiation. No %s member named '%s' takes %d generic arguments. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:353) + (Originally from src/fsharp/FSComp.txt:358) A generic construct requires that the type '%s' is an unmanaged type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:324) + (Originally from src/fsharp/FSComp.txt:329) A generic construct requires that the type '%s' is a CLI or F# struct type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:323) + (Originally from src/fsharp/FSComp.txt:328) A generic construct requires that the type '%s' have reference semantics, but it does not, i.e. it is a struct - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:326) + (Originally from src/fsharp/FSComp.txt:331) A generic construct requires that the type '%s' have a public default constructor - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:328) + (Originally from src/fsharp/FSComp.txt:333) A generic construct requires that the type '%s' be non-abstract - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:327) + (Originally from src/fsharp/FSComp.txt:332) Expected arguments to an instance member - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:299) + (Originally from src/fsharp/FSComp.txt:304) Expecting a type supporting the operator '%s' but given a tuple type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:302) + (Originally from src/fsharp/FSComp.txt:307) Expecting a type supporting the operator '%s' but given a function type. You may be missing an argument to a function. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:301) + (Originally from src/fsharp/FSComp.txt:306) The object constructor '%s' takes %d argument(s) but is here given %d. The required signature is '%s'. If some of the arguments are meant to assign values to properties, consider separating those arguments with a comma (','). - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:350) + (Originally from src/fsharp/FSComp.txt:355) The object constructor '%s' takes %d argument(s) but is here given %d. The required signature is '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:349) + (Originally from src/fsharp/FSComp.txt:354) The object constructor '%s' has no argument or settable return property '%s'. %s. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:341) + (Originally from src/fsharp/FSComp.txt:346) This code is less generic than indicated by its annotations. A unit-of-measure specified using '_' has been determined to be '1', i.e. dimensionless. Consider making the code generic, or removing the use of '_'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:297) + (Originally from src/fsharp/FSComp.txt:302) - Candidates: %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:361) + Candidates:\n%s + (Originally from src/fsharp/FSComp.txt:371) + + + + + Available overloads:\n%s + (Originally from src/fsharp/FSComp.txt:372) The argument types don't match - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:334) + (Originally from src/fsharp/FSComp.txt:339) Argument length mismatch - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:333) + (Originally from src/fsharp/FSComp.txt:338) Quotations cannot contain expressions that set union case fields - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:288) + (Originally from src/fsharp/FSComp.txt:293) Quotations cannot contain expressions that set fields in exception values - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:289) + (Originally from src/fsharp/FSComp.txt:294) Quotations cannot contain expressions that require byref pointers - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:290) + (Originally from src/fsharp/FSComp.txt:295) Quotations cannot contain expressions that fetch union case indexes - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:287) + (Originally from src/fsharp/FSComp.txt:292) Quotations cannot contain this kind of type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:295) + (Originally from src/fsharp/FSComp.txt:300) Quotations cannot contain this kind of pattern match - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:293) + (Originally from src/fsharp/FSComp.txt:298) Quotations cannot contain this kind of constant - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:292) + (Originally from src/fsharp/FSComp.txt:297) Quotations cannot contain expressions that fetch static fields - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:284) + (Originally from src/fsharp/FSComp.txt:289) Quotations cannot contain object expressions - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:282) + (Originally from src/fsharp/FSComp.txt:287) Quotations cannot contain inline assembly code or pattern matching on arrays - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:285) + (Originally from src/fsharp/FSComp.txt:290) Quotations cannot contain function definitions that are inferred or declared to be generic. Consider adding some type constraints to make this a valid quoted expression. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:281) + (Originally from src/fsharp/FSComp.txt:286) Quotations cannot contain uses of generic expressions - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:280) + (Originally from src/fsharp/FSComp.txt:285) Quotations cannot contain descending for loops - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:286) + (Originally from src/fsharp/FSComp.txt:291) Quotations cannot contain array pattern matching - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:294) + (Originally from src/fsharp/FSComp.txt:299) Quotations cannot contain expressions that take the address of a field - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:283) + (Originally from src/fsharp/FSComp.txt:288) Quotations cannot contain expressions that make member constraint calls, or uses of operators that implicitly resolve to a member constraint call - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:291) + (Originally from src/fsharp/FSComp.txt:296) A quotation may not involve an assignment to or taking the address of a captured local variable - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1275) + (Originally from src/fsharp/FSComp.txt:1293) Inner generic functions are not permitted in quoted expressions. Consider adding some type constraints until this function is no longer generic. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1086) + (Originally from src/fsharp/FSComp.txt:1102) The variable '%s' is bound in a quotation but is used as part of a spliced expression. This is not permitted since it may escape its scope. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:279) + (Originally from src/fsharp/FSComp.txt:284) + + + + + The dependency manager extension %s could not be loaded. Message: %s + (Originally from src/fsharp/FSComp.txt:1479) The conversion from %s to %s is a compile-time safe upcast, not a downcast. Consider using the :> (upcast) operator instead of the :?> (downcast) operator. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1328) + (Originally from src/fsharp/FSComp.txt:1346) The conversion from %s to %s is a compile-time safe upcast, not a downcast. Consider using 'upcast' instead of 'downcast'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1327) + (Originally from src/fsharp/FSComp.txt:1345) A ';' is used to separate field values in records. Consider replacing ',' with ';'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:27) + (Originally from src/fsharp/FSComp.txt:28) The variable '%s' is used in an invalid way - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:237) + (Originally from src/fsharp/FSComp.txt:242) The type of a field using the 'DefaultValue' attribute must admit default initialization, i.e. have 'null' as a proper value or be a struct type whose fields all admit default initialization. You can use 'DefaultValue(false)' to disable this check - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:277) + (Originally from src/fsharp/FSComp.txt:282) The value '%s' is unused - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1037) + (Originally from src/fsharp/FSComp.txt:1054) The recursive object reference '%s' is unused. The presence of a recursive object reference adds runtime initialization checks to members in this and derived types. Consider removing this recursive object reference. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1038) + (Originally from src/fsharp/FSComp.txt:1055) default augmentation of the union case - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:262) + (Originally from src/fsharp/FSComp.txt:267) compiled form of the union case - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:261) + (Originally from src/fsharp/FSComp.txt:266) The type '%s' is less accessible than the value, member or type '%s' it is used in. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:238) + (Originally from src/fsharp/FSComp.txt:243) A type variable has been constrained by multiple different class types. A type variable may only have one class constraint. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1286) + (Originally from src/fsharp/FSComp.txt:1304) 'System.Void' can only be used as 'typeof<System.Void>' in F# - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:239) + (Originally from src/fsharp/FSComp.txt:244) Struct members cannot return the address of fields of the struct by reference - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1443) + (Originally from src/fsharp/FSComp.txt:1466) Expression-splicing operators may only be used within quotations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:242) + (Originally from src/fsharp/FSComp.txt:247) A method return type would contain byrefs which is not permitted - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:254) + (Originally from src/fsharp/FSComp.txt:259) [<ReflectedDefinition>] terms cannot contain uses of the prefix splice operator '%%' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:259) + (Originally from src/fsharp/FSComp.txt:264) A protected member is called or 'base' is being used. This is only allowed in the direct implementation of members since they could escape their object scope. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:234) + (Originally from src/fsharp/FSComp.txt:239) The property '%s' has the same name as a method in type '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:263) + (Originally from src/fsharp/FSComp.txt:268) The property '%s' has the same name as another property in type '%s', but one takes indexer arguments and the other does not. You may be missing an indexer argument to one of your properties. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:265) + (Originally from src/fsharp/FSComp.txt:270) Object constructors cannot directly use try/with and try/finally prior to the initialization of the object. This includes constructs such as 'for x in ...' that may elaborate to uses of these constructs. This is a limitation imposed by Common IL. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:248) + (Originally from src/fsharp/FSComp.txt:253) This value can't be assigned because the target '%s' may refer to non-stack-local memory, while the expression being assigned is assessed to potentially refer to stack-local memory. This is to help prevent pointers to stack-bound memory escaping their scope. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1440) + (Originally from src/fsharp/FSComp.txt:1463) The Span or IsByRefLike variable '%s' cannot be used at this point. This is to ensure the address of the local value does not escape its scope. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1445) + (Originally from src/fsharp/FSComp.txt:1468) A Span or IsByRefLike value returned from the expression cannot be used at ths point. This is to ensure the address of the local value does not escape its scope. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1446) + (Originally from src/fsharp/FSComp.txt:1469) ReflectedDefinitionAttribute may not be applied to an instance member on a struct type, because the instance member takes an implicit 'this' byref parameter - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1079) + (Originally from src/fsharp/FSComp.txt:1096) First-class uses of the expression-splicing operator are not permitted - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:243) + (Originally from src/fsharp/FSComp.txt:248) First-class uses of the 'reraise' function is not permitted - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:245) + (Originally from src/fsharp/FSComp.txt:250) + + + + + Using the 'nameof' operator as a first-class function value is not permitted. + (Originally from src/fsharp/FSComp.txt:1481) First-class uses of the address-of operators are not permitted - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:244) + (Originally from src/fsharp/FSComp.txt:249) Type '%s' is illegal because in byref<T>, T cannot contain byref types. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1258) + (Originally from src/fsharp/FSComp.txt:1276) The function or method call cannot be used at this point, because one argument that is a byref of a non-stack-local Span or IsByRefLike type is used with another argument that is a stack-local Span or IsByRefLike type. This is to ensure the address of the local value does not escape its scope. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1444) + (Originally from src/fsharp/FSComp.txt:1467) The type abbreviation contains byrefs. This is not permitted by F#. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:278) + (Originally from src/fsharp/FSComp.txt:283) The byref typed value '%s' cannot be used at this point - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:246) + (Originally from src/fsharp/FSComp.txt:251) A byref typed value would be stored here. Top-level let-bound byref values are not permitted. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:258) + (Originally from src/fsharp/FSComp.txt:263) The address of a value returned from the expression cannot be used at this point. This is to ensure the address of the local value does not escape its scope. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1439) + (Originally from src/fsharp/FSComp.txt:1462) The address of the variable '%s' or a related expression cannot be used at this point. This is to ensure the address of the local value does not escape its scope. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1338) + (Originally from src/fsharp/FSComp.txt:1356) The address of the static field '%s' cannot be used at this point - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:250) + (Originally from src/fsharp/FSComp.txt:255) The address of the variable '%s' cannot be used at this point - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:249) + (Originally from src/fsharp/FSComp.txt:254) The address of an array element cannot be used at this point - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:252) + (Originally from src/fsharp/FSComp.txt:257) The address of the field '%s' cannot be used at this point - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:251) + (Originally from src/fsharp/FSComp.txt:256) This type implements the same interface at different generic instantiations '%s' and '%s'. This is not permitted in this version of F#. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:276) + (Originally from src/fsharp/FSComp.txt:281) The member '%s' is used in an invalid way. A use of '%s' has been inferred prior to its definition at or near '%s'. This is an invalid forward reference. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:257) + (Originally from src/fsharp/FSComp.txt:262) 'base' values may only be used to make direct calls to the base implementations of overridden members - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:247) + (Originally from src/fsharp/FSComp.txt:252) The function or method has an invalid return type '%s'. This is not permitted by the rules of Common IL. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1456) + (Originally from src/fsharp/FSComp.txt:1483) The parameter '%s' has an invalid type '%s'. This is not permitted by the rules of Common IL. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1455) + (Originally from src/fsharp/FSComp.txt:1482) Invalid custom attribute value (not a constant or literal) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:255) + (Originally from src/fsharp/FSComp.txt:260) The property '%s' of type '%s' has a getter and a setter that do not match. If one is abstract then the other must be as well. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:264) + (Originally from src/fsharp/FSComp.txt:269) A property's getter and setter must have the same type. Property '%s' has getter of type '%s' but setter of type '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1295) + (Originally from src/fsharp/FSComp.txt:1313) The type of a first-class function cannot contain byrefs - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:253) + (Originally from src/fsharp/FSComp.txt:258) + + + + + Feature '%s' is not supported by target runtime. + (Originally from src/fsharp/FSComp.txt:1490) + + + + + Feature '%s' is not available in F# %s. Please use language version %s or greater. + (Originally from src/fsharp/FSComp.txt:1489) A type instantiation involves a byref type. This is not permitted by the rules of Common IL. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:240) + (Originally from src/fsharp/FSComp.txt:245) Calls to 'reraise' may only occur directly in a handler of a try-with - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:241) + (Originally from src/fsharp/FSComp.txt:246) A function labeled with the 'EntryPointAttribute' attribute must be the last declaration in the last file in the compilation sequence. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:260) + (Originally from src/fsharp/FSComp.txt:265) Duplicate property. The property '%s' has the same name and signature as another property in type '%s' once tuples, functions, units of measure and/or provided types are erased. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:273) + (Originally from src/fsharp/FSComp.txt:278) Duplicate property. The property '%s' has the same name and signature as another property in type '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:272) + (Originally from src/fsharp/FSComp.txt:277) Duplicate method. The method '%s' has the same name and signature as another method in type '%s' once tuples, functions, units of measure and/or provided types are erased. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:269) + (Originally from src/fsharp/FSComp.txt:274) Duplicate method. The abstract method '%s' has the same name and signature as an abstract method in an inherited type once tuples, functions, units of measure and/or provided types are erased. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:275) + (Originally from src/fsharp/FSComp.txt:280) Duplicate method. The abstract method '%s' has the same name and signature as an abstract method in an inherited type. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:274) + (Originally from src/fsharp/FSComp.txt:279) The method '%s' has curried arguments but has the same name as another method in type '%s'. Methods with curried arguments cannot be overloaded. Consider using a method taking tupled arguments. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:270) + (Originally from src/fsharp/FSComp.txt:275) Duplicate method. The method '%s' has the same name and signature as another method in type '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:268) + (Originally from src/fsharp/FSComp.txt:273) Methods with curried arguments cannot declare 'out', 'ParamArray', 'optional', 'ReflectedDefinition', 'byref', 'CallerLineNumber', 'CallerMemberName', or 'CallerFilePath' arguments - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:271) + (Originally from src/fsharp/FSComp.txt:276) A type would store a byref typed value. This is not permitted by Common IL. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:266) + (Originally from src/fsharp/FSComp.txt:271) The byref-typed variable '%s' is used in an invalid way. Byrefs cannot be captured by closures or passed to inner functions. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:235) + (Originally from src/fsharp/FSComp.txt:240) The 'base' keyword is used in an invalid way. Base calls cannot be used in closures. Consider using a private member to make base calls. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:236) + (Originally from src/fsharp/FSComp.txt:241) The attribute type '%s' has 'AllowMultiple=false'. Multiple instances of this attribute cannot be attached to a single language element. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:256) + (Originally from src/fsharp/FSComp.txt:261) Redundant arguments are being ignored in function '%s'. Expected %d but got %d arguments. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1317) + (Originally from src/fsharp/FSComp.txt:1335) Type inference caused an inference type variable to escape its scope. Consider adding type annotations to make your code less generic. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1316) + (Originally from src/fsharp/FSComp.txt:1334) Type inference caused the type variable %s to escape its scope. Consider adding an explicit type parameter declaration or adjusting your code to be less generic. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1315) + (Originally from src/fsharp/FSComp.txt:1333) Lowercase literal '%s' is being shadowed by a new pattern with the same name. Only uppercase and module-prefixed literals can be used as named patterns. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1318) + (Originally from src/fsharp/FSComp.txt:1336) The operator '%s' cannot be resolved. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1289) + (Originally from src/fsharp/FSComp.txt:1307) Unrecognized option: '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:71) + (Originally from src/fsharp/FSComp.txt:71) The non-generic type '%s' does not expect any type arguments, but here is given %d type argument(s) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:29) + (Originally from src/fsharp/FSComp.txt:30) Filename '%s' contains invalid character '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1084) + (Originally from src/fsharp/FSComp.txt:1100) The signature file '%s' does not have a corresponding implementation file. If an implementation file exists then check the 'module' and 'namespace' declarations in the signature and implementation files match. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:68) + (Originally from src/fsharp/FSComp.txt:68) A signature for the file or module '%s' has already been specified - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:65) + (Originally from src/fsharp/FSComp.txt:65) The search directory '%s' could not be found - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:42) + (Originally from src/fsharp/FSComp.txt:43) F# Compiler for F# %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:37) + (Originally from src/fsharp/FSComp.txt:38) Microsoft (R) F# Compiler version %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:36) + (Originally from src/fsharp/FSComp.txt:37) Problem with filename '%s': %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:38) + (Originally from src/fsharp/FSComp.txt:39) Problem reading assembly '%s': %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1282) + (Originally from src/fsharp/FSComp.txt:1300) The '--pdb' option requires the '--debug' option to be used - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:40) + (Originally from src/fsharp/FSComp.txt:41) Option requires parameter: %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:53) + (Originally from src/fsharp/FSComp.txt:53) No inputs specified - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:39) + (Originally from src/fsharp/FSComp.txt:40) This file contains multiple declarations of the form 'module SomeNamespace.SomeModule'. Only one declaration of this form is permitted in a file. Change your file to use an initial namespace declaration and/or use 'module ModuleName = ...' to define your modules. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:52) - - - - - Multiple references to '%s.dll' are not permitted - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:46) + (Originally from src/fsharp/FSComp.txt:52) Files in libraries or multiple-file applications must begin with a namespace or module declaration, e.g. 'namespace SomeNamespace.SubNamespace' or 'module SomeNamespace.SomeModule'. Only the last source file of an application may omit such a declaration. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:50) + (Originally from src/fsharp/FSComp.txt:50) Invalid warning number '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:33) + (Originally from src/fsharp/FSComp.txt:34) Invalid version string '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:34) + (Originally from src/fsharp/FSComp.txt:35) Invalid version file '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:35) + (Originally from src/fsharp/FSComp.txt:36) The file extension of '%s' is not recognized. Source files must have extension .fs, .fsi, .fsx, .fsscript, .ml or .mli. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:55) + (Originally from src/fsharp/FSComp.txt:55) The search directory '%s' is invalid - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:41) + (Originally from src/fsharp/FSComp.txt:42) Unrecognized privacy setting '%s' for managed resource, valid options are 'public' and 'private' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:45) + (Originally from src/fsharp/FSComp.txt:46) Invalid module or namespace name - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:72) + (Originally from src/fsharp/FSComp.txt:72) Invalid directive. Expected '#time', '#time \"on\"' or '#time \"off\"'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:63) + (Originally from src/fsharp/FSComp.txt:63) Invalid directive. Expected '#r \"<file-or-assembly>\"'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:61) + (Originally from src/fsharp/FSComp.txt:61) Invalid directive. Expected '#load \"<file>\" ... \"<file>\"'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:62) + (Originally from src/fsharp/FSComp.txt:62) Invalid directive. Expected '#I \"<path>\"'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:60) + (Originally from src/fsharp/FSComp.txt:60) '%s' is not a valid filename - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:43) + (Originally from src/fsharp/FSComp.txt:44) '%s' is not a valid assembly name - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:44) + (Originally from src/fsharp/FSComp.txt:45) The declarations in this file will be placed in an implicit module '%s' based on the file name '%s'. However this is not a valid F# identifier, so the contents will not be accessible from other files. Consider renaming the file or adding a 'module' or 'namespace' declaration at the top of the file. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:49) + (Originally from src/fsharp/FSComp.txt:49) An implementation of file or module '%s' has already been given. Compilation order is significant in F# because of type inference. You may need to adjust the order of your files to place the signature file before the implementation. In Visual Studio files are type-checked in the order they appear in the project file, which can be edited manually or adjusted using the solution explorer. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:66) + (Originally from src/fsharp/FSComp.txt:66) An implementation of the file or module '%s' has already been given - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:67) - - - - - When mscorlib.dll or FSharp.Core.dll is explicitly referenced the %s option must also be passed - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1081) + (Originally from src/fsharp/FSComp.txt:67) FSharp.Core.sigdata not found alongside FSharp.Core. File expected in %s. Consider upgrading to a more recent version of FSharp.Core, where this file is no longer be required. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1082) + (Originally from src/fsharp/FSComp.txt:1098) File '%s' not found alongside FSharp.Core. File expected in %s. Consider upgrading to a more recent version of FSharp.Core, where this file is no longer be required. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1083) + (Originally from src/fsharp/FSComp.txt:1099) Error opening binary file '%s': %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:58) + (Originally from src/fsharp/FSComp.txt:58) Directives inside modules are ignored - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:64) + (Originally from src/fsharp/FSComp.txt:64) The F#-compiled DLL '%s' needs to be recompiled to be used with this version of F# - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:59) + (Originally from src/fsharp/FSComp.txt:59) Could not resolve assembly '%s' required by '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:57) + (Originally from src/fsharp/FSComp.txt:57) Could not resolve assembly '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:56) + (Originally from src/fsharp/FSComp.txt:56) Source file '%s' could not be found - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:54) + (Originally from src/fsharp/FSComp.txt:54) The file extensions '.ml' and '.mli' are for ML compatibility - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1066) + (Originally from src/fsharp/FSComp.txt:1083) Unable to read assembly '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:47) + (Originally from src/fsharp/FSComp.txt:47) Assembly resolution failure at or near this location - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:48) + (Originally from src/fsharp/FSComp.txt:48) '%s' is not a valid integer argument - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:69) + (Originally from src/fsharp/FSComp.txt:69) '%s' is not a valid floating point argument - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:70) + (Originally from src/fsharp/FSComp.txt:70) A type cannot have both the 'ReferenceEquality' and 'StructuralEquality' or 'StructuralComparison' attributes - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:209) + (Originally from src/fsharp/FSComp.txt:214) The 'StructuralEquality' attribute must be used in conjunction with the 'NoComparison' or 'StructuralComparison' attributes - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:208) + (Originally from src/fsharp/FSComp.txt:213) The 'StructuralComparison' attribute must be used in conjunction with the 'StructuralEquality' attribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:207) + (Originally from src/fsharp/FSComp.txt:212) A type with attribute 'ReferenceEquality' cannot have an explicit implementation of 'Object.Equals(obj)', 'System.IEquatable<_>' or 'System.Collections.IStructuralEquatable' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:211) + (Originally from src/fsharp/FSComp.txt:216) Only record, union, exception and struct types may be augmented with the 'ReferenceEquality', 'StructuralEquality' and 'StructuralComparison' attributes - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:210) + (Originally from src/fsharp/FSComp.txt:215) The 'ReferenceEquality' attribute cannot be used on structs. Consider using the 'StructuralEquality' attribute instead, or implement an override for 'System.Object.Equals(obj)'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:204) + (Originally from src/fsharp/FSComp.txt:209) The 'NoEquality' attribute must be used in conjunction with the 'NoComparison' attribute - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:206) + (Originally from src/fsharp/FSComp.txt:211) A type with attribute 'NoEquality' should not usually have an explicit implementation of 'Object.Equals(obj)'. Disable this warning if this is intentional for interoperability purposes - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:214) + (Originally from src/fsharp/FSComp.txt:219) A type with attribute 'NoComparison' should not usually have an explicit implementation of 'System.IComparable', 'System.IComparable<_>' or 'System.Collections.IStructuralComparable'. Disable this warning if this is intentional for interoperability purposes - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:215) + (Originally from src/fsharp/FSComp.txt:220) This type uses an invalid mix of the attributes 'NoEquality', 'ReferenceEquality', 'StructuralEquality', 'NoComparison' and 'StructuralComparison' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:205) + (Originally from src/fsharp/FSComp.txt:210) A type with attribute 'CustomEquality' must have an explicit implementation of at least one of 'Object.Equals(obj)', 'System.IEquatable<_>' or 'System.Collections.IStructuralEquatable' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:212) + (Originally from src/fsharp/FSComp.txt:217) The 'CustomEquality' attribute must be used in conjunction with the 'NoComparison' or 'CustomComparison' attributes - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:216) + (Originally from src/fsharp/FSComp.txt:221) A type with attribute 'CustomComparison' must have an explicit implementation of at least one of 'System.IComparable' or 'System.Collections.IStructuralComparable' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:213) + (Originally from src/fsharp/FSComp.txt:218) Error while parsing embedded IL type - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:201) + (Originally from src/fsharp/FSComp.txt:206) Error while parsing embedded IL - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:200) + (Originally from src/fsharp/FSComp.txt:205) Invalid expression on left of assignment - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:203) + (Originally from src/fsharp/FSComp.txt:208) This indexer notation has been removed from the F# language - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:202) + (Originally from src/fsharp/FSComp.txt:207) .NET Framework - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:936) + (Originally from src/fsharp/FSComp.txt:953) Global Assembly Cache - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:937) + (Originally from src/fsharp/FSComp.txt:954) Found by AssemblyFolders registry key - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:934) + (Originally from src/fsharp/FSComp.txt:951) Found by AssemblyFoldersEx registry key - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:935) + (Originally from src/fsharp/FSComp.txt:952) All elements of an array must be of the same type as the first element, which here is '%s'. This element has type '%s'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:21) + (Originally from src/fsharp/FSComp.txt:22) Add . for indexer access. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:19) + (Originally from src/fsharp/FSComp.txt:20) Active pattern '%s' is not a function - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1068) + (Originally from src/fsharp/FSComp.txt:1085) Active pattern '%s' has a result type containing type variables that are not determined by the input. The common cause is a when a result case is not mentioned, e.g. 'let (|A|B|) (x:int) = A x'. This can be fixed with a type constraint, e.g. 'let (|A|B|) (x:int) : Choice<int,unit> = A x' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1069) + (Originally from src/fsharp/FSComp.txt:1086) The mutable local '%s' is implicitly allocated as a reference cell because it has been captured by a closure. This warning is for informational purposes only to indicate where implicit allocations are performed. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1307) + (Originally from src/fsharp/FSComp.txt:1325) Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is virtual and the other isn't - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:113) + (Originally from src/fsharp/FSComp.txt:114) Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe types differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:105) + (Originally from src/fsharp/FSComp.txt:106) Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is static and the other isn't - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:112) + (Originally from src/fsharp/FSComp.txt:113) Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe compiled representation of this method is as a static member but the signature indicates its compiled representation is as an instance member - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:118) + (Originally from src/fsharp/FSComp.txt:119) Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe respective type parameter counts differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:104) + (Originally from src/fsharp/FSComp.txt:105) Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is marked as an override and the other isn't - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:116) + (Originally from src/fsharp/FSComp.txt:117) Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is a type function and the other is not. The signature requires explicit type parameters if they are present in the implementation. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:103) + (Originally from src/fsharp/FSComp.txt:104) Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is a constructor/property and the other is not - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:117) + (Originally from src/fsharp/FSComp.txt:118) Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe names differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:97) + (Originally from src/fsharp/FSComp.txt:98) Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe literal constant values and/or attributes differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:102) + (Originally from src/fsharp/FSComp.txt:103) Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe compiled representation of this method is as an instance member, but the signature indicates its compiled representation is as a static member - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:119) + (Originally from src/fsharp/FSComp.txt:120) Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe inline flags differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:101) + (Originally from src/fsharp/FSComp.txt:102) Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe number of generic parameters in the signature and implementation differ (the signature declares %s but the implementation declares %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:108) + (Originally from src/fsharp/FSComp.txt:109) Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe generic parameters in the signature and implementation have different kinds. Perhaps there is a missing [<Measure>] attribute. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:109) + (Originally from src/fsharp/FSComp.txt:110) Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is final and the other isn't - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:115) + (Originally from src/fsharp/FSComp.txt:116) Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is an extension member and the other is not - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:106) + (Originally from src/fsharp/FSComp.txt:107) Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe CLI member names differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:111) + (Originally from src/fsharp/FSComp.txt:112) Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe display names differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:99) + (Originally from src/fsharp/FSComp.txt:100) Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe compiled names differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:98) + (Originally from src/fsharp/FSComp.txt:99) Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe mutability attributes differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:96) + (Originally from src/fsharp/FSComp.txt:97) Module '%s' contains\n %s \nbut its signature specifies\n %s \nAn arity was not inferred for this value - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:107) + (Originally from src/fsharp/FSComp.txt:108) Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe arities in the signature and implementation differ. The signature specifies that '%s' is function definition or lambda expression accepting at least %s argument(s), but the implementation is a computed function value. To declare that a computed function value is a permitted implementation simply parenthesize its type in the signature, e.g.\n\tval %s: int -> (int -> int)\ninstead of\n\tval %s: int -> int -> int. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:110) + (Originally from src/fsharp/FSComp.txt:111) Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe accessibility specified in the signature is more than that specified in the implementation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:100) + (Originally from src/fsharp/FSComp.txt:101) Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is abstract and the other isn't - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:114) + (Originally from src/fsharp/FSComp.txt:115) @@ -8257,337 +8587,370 @@ The module contains the constructor\n %s \nbut its signature specifies\n %s \nThe types of the fields differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:154) + (Originally from src/fsharp/FSComp.txt:155) The module contains the constructor\n %s \nbut its signature specifies\n %s \nThe names differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:152) + (Originally from src/fsharp/FSComp.txt:153) The module contains the constructor\n %s \nbut its signature specifies\n %s \nThe respective number of data fields differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:153) + (Originally from src/fsharp/FSComp.txt:154) The module contains the constructor\n %s \nbut its signature specifies\n %s \nthe accessibility specified in the signature is more than that specified in the implementation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:155) + (Originally from src/fsharp/FSComp.txt:156) Invalid recursive reference to an abstract slot - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:939) + (Originally from src/fsharp/FSComp.txt:956) The module contains the field\n %s \nbut its signature specifies\n %s \nThe types differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:161) + (Originally from src/fsharp/FSComp.txt:162) The module contains the field\n %s \nbut its signature specifies\n %s \nThe 'static' modifiers differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:158) + (Originally from src/fsharp/FSComp.txt:159) The module contains the field\n %s \nbut its signature specifies\n %s \nThe names differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:156) + (Originally from src/fsharp/FSComp.txt:157) The module contains the field\n %s \nbut its signature specifies\n %s \nThe 'mutable' modifiers differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:159) + (Originally from src/fsharp/FSComp.txt:160) The module contains the field\n %s \nbut its signature specifies\n %s \nThe 'literal' modifiers differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:160) + (Originally from src/fsharp/FSComp.txt:161) The module contains the field\n %s \nbut its signature specifies\n %s \nthe accessibility specified in the signature is more than that specified in the implementation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:157) + (Originally from src/fsharp/FSComp.txt:158) The exception definitions are not compatible because the exception abbreviations in the signature and implementation differ. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:179) + (Originally from src/fsharp/FSComp.txt:180) The exception definitions are not compatible because a CLI exception mapping is being hidden by a signature. The exception mapping must be visible to other modules. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:176) + (Originally from src/fsharp/FSComp.txt:177) The exception definitions are not compatible because the order of the fields is different in the signature and implementation. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:183) + (Originally from src/fsharp/FSComp.txt:184) The exception definitions are not compatible because the field '%s' was required by the signature but was not specified by the implementation. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:181) + (Originally from src/fsharp/FSComp.txt:182) The exception definitions are not compatible because the field '%s' was present in the implementation but not in the signature. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:182) + (Originally from src/fsharp/FSComp.txt:183) The exception definitions are not compatible because the exception declarations differ. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:180) + (Originally from src/fsharp/FSComp.txt:181) The exception definitions are not compatible because the CLI representations differ. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:177) + (Originally from src/fsharp/FSComp.txt:178) The exception definitions are not compatible because the exception abbreviation is being hidden by the signature. The abbreviation must be visible to other CLI languages. Consider making the abbreviation visible in the signature. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:178) + (Originally from src/fsharp/FSComp.txt:179) The %s definitions for type '%s' in the signature and implementation are not compatible because the types have different base types - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:132) + (Originally from src/fsharp/FSComp.txt:133) The %s definitions for type '%s' in the signature and implementation are not compatible because a type representation is being hidden by a signature - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:138) + (Originally from src/fsharp/FSComp.txt:139) The %s definitions for type '%s' in the signature and implementation are not compatible because the types are of different kinds - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:139) + (Originally from src/fsharp/FSComp.txt:140) The %s definitions for type '%s' in the signature and implementation are not compatible because the signature says this type may use nulls as an extra value but the implementation does not - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:127) + (Originally from src/fsharp/FSComp.txt:128) The %s definitions for type '%s' in the signature and implementation are not compatible because the signature says this type may use nulls as a representation but the implementation does not - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:126) + (Originally from src/fsharp/FSComp.txt:127) The %s definitions for type '%s' in the signature and implementation are not compatible because the signature is an abstract class but the implementation is not. Consider adding the [<AbstractClass>] attribute to the implementation. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:131) + (Originally from src/fsharp/FSComp.txt:132) The %s definitions for type '%s' in the signature and implementation are not compatible because the signature defines the %s '%s' but the implementation does not (or does, but not in the same order) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:134) + (Originally from src/fsharp/FSComp.txt:135) The %s definitions for type '%s' in the signature and implementation are not compatible because the signature declares a %s while the implementation declares a %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:148) + (Originally from src/fsharp/FSComp.txt:149) The %s definitions for type '%s' in the signature and implementation are not compatible because the signature has an abbreviation while the implementation does not - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:151) + (Originally from src/fsharp/FSComp.txt:152) The %s definitions for type '%s' in the signature and implementation are not compatible because the representations differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:141) + (Originally from src/fsharp/FSComp.txt:142) The %s definitions for type '%s' in the signature and implementation are not compatible because the respective type parameter counts differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:121) + (Originally from src/fsharp/FSComp.txt:122) The %s definitions for type '%s' in the signature and implementation are not compatible because the number of %ss differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:133) + (Originally from src/fsharp/FSComp.txt:134) The %s definitions in the signature and implementation are not compatible because the names differ. The type is called '%s' in the signature file but '%s' in implementation. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:120) + (Originally from src/fsharp/FSComp.txt:121) The %s definitions for type '%s' in the signature and implementation are not compatible because the signature requires that the type supports the interface %s but the interface has not been implemented - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:123) + (Originally from src/fsharp/FSComp.txt:124) The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation type is sealed but the signature implies it is not. Consider adding the [<Sealed>] attribute to the signature. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:128) + (Originally from src/fsharp/FSComp.txt:129) The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation says this type may use nulls as an extra value but the signature does not - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:125) + (Originally from src/fsharp/FSComp.txt:126) The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation says this type may use nulls as a representation but the signature does not - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:124) + (Originally from src/fsharp/FSComp.txt:125) The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation type is not sealed but signature implies it is. Consider adding the [<Sealed>] attribute to the implementation. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:129) + (Originally from src/fsharp/FSComp.txt:130) The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation is an abstract class but the signature is not. Consider adding the [<AbstractClass>] attribute to the signature. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:130) + (Originally from src/fsharp/FSComp.txt:131) The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation defines a struct but the signature defines a type with a hidden representation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:136) + (Originally from src/fsharp/FSComp.txt:137) The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation defines the %s '%s' but the signature does not (or does, but not in the same order) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:135) + (Originally from src/fsharp/FSComp.txt:136) The %s definitions for type '%s' in the signature and implementation are not compatible because the IL representations differ - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:140) + (Originally from src/fsharp/FSComp.txt:141) The %s definitions for type '%s' in the signature and implementation are not compatible because the field %s was present in the implementation but not in the signature - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:142) + (Originally from src/fsharp/FSComp.txt:143) The %s definitions for type '%s' in the signature and implementation are not compatible because the field %s was required by the signature but was not specified by the implementation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:144) + (Originally from src/fsharp/FSComp.txt:145) The %s definitions for type '%s' in the signature and implementation are not compatible because the order of the fields is different in the signature and implementation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:143) + (Originally from src/fsharp/FSComp.txt:144) The %s definitions for type '%s' in the signature and implementation are not compatible because the field '%s' was present in the implementation but not in the signature. Struct types must now reveal their fields in the signature for the type, though the fields may still be labelled 'private' or 'internal'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:145) + (Originally from src/fsharp/FSComp.txt:146) The %s definitions for type '%s' in the signature and implementation are not compatible because a CLI type representation is being hidden by a signature - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:137) + (Originally from src/fsharp/FSComp.txt:138) The %s definitions for type '%s' in the signature and implementation are not compatible because the accessibility specified in the signature is more than that specified in the implementation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:122) + (Originally from src/fsharp/FSComp.txt:123) The %s definitions for type '%s' in the signature and implementation are not compatible because the abstract member '%s' was present in the implementation but not in the signature - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:147) + (Originally from src/fsharp/FSComp.txt:148) The %s definitions for type '%s' in the signature and implementation are not compatible because the abstract member '%s' was required by the signature but was not specified by the implementation - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:146) + (Originally from src/fsharp/FSComp.txt:147) The %s definitions for type '%s' in the signature and implementation are not compatible because the abbreviations differ: %s versus %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:149) + (Originally from src/fsharp/FSComp.txt:150) The %s definitions for type '%s' in the signature and implementation are not compatible because an abbreviation is being hidden by a signature. The abbreviation must be visible to other CLI languages. Consider making the abbreviation visible in the signature. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:150) + (Originally from src/fsharp/FSComp.txt:151) The default value does not have the same type as the argument. The DefaultParameterValue attribute and any Optional attribute will be ignored. Note: 'null' needs to be annotated with the correct type, e.g. 'DefaultParameterValue(null:obj)'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1340) + (Originally from src/fsharp/FSComp.txt:1358) The CallerMemberNameAttribute applied to parameter '%s' will have no effect. It is overridden by the CallerFilePathAttribute. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1335) + (Originally from src/fsharp/FSComp.txt:1353) The argument names in the signature '%s' and implementation '%s' do not match. The argument name from the signature file will be used. This may cause problems when debugging or profiling. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/FSComp.txt:1429) + (Originally from src/fsharp/FSComp.txt:1452) + + + + + If set to true, then all error messages will just return the filled 'holes' delimited by ',,,'s - this is for language-neutral testing (e.g. localization-invariant baselines). + + + + + Package manager key '%s' was not registered in %s. Currently registered: %s + (Originally from src/fsharp/Interactive.DependencyManager\InteractiveDependencyManager.txt:2) + + + + + %s + (Originally from src/fsharp/Interactive.DependencyManager\InteractiveDependencyManager.txt:3) + + + + + If set to true, then all error messages will just return the filled 'holes' delimited by ',,,'s - this is for language-neutral testing (e.g. localization-invariant baselines). + + + + + The dependency manager extension %s could not be loaded. Message: %s + (Originally from src/fsharp/Interactive.DependencyManager\InteractiveDependencyManager.txt:4) + + + + + Call this method once to validate that all known resources are valid; throws if not Stopped due to error\n - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:2) + (Originally from src/fsharp/fsi\FSIstrings.txt:2) Prevents references from being locked by the F# Interactive process - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:54) + (Originally from src/fsharp/fsi\FSIstrings.txt:54) @@ -8603,307 +8966,319 @@ Use the given file on startup as initial input - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:11) + (Originally from src/fsharp/fsi\FSIstrings.txt:11) Usage: %s <options> [script.fsx [<arguments>]] - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:3) + (Originally from src/fsharp/fsi\FSIstrings.txt:3) - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:49) + (Originally from src/fsharp/fsi\FSIstrings.txt:49) --> Timing now on - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:47) + (Originally from src/fsharp/fsi\FSIstrings.txt:47) --> Timing now off - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:48) + (Originally from src/fsharp/fsi\FSIstrings.txt:48) Real: %s, CPU: %s, GC %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:26) + (Originally from src/fsharp/fsi\FSIstrings.txt:26) gen - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:27) + (Originally from src/fsharp/fsi\FSIstrings.txt:27) Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:13) + (Originally from src/fsharp/fsi\FSIstrings.txt:13) Support TAB completion in console (on by default) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:18) + (Originally from src/fsharp/fsi\FSIstrings.txt:18) Suppress fsi writing to stdout - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:17) + (Originally from src/fsharp/fsi\FSIstrings.txt:17) F# Interactive for F# %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:53) + (Originally from src/fsharp/fsi\FSIstrings.txt:53) Microsoft (R) F# Interactive version %s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:52) + (Originally from src/fsharp/fsi\FSIstrings.txt:52) + + + + + Operation failed. The error text has been printed in the error stream. To return the corresponding FSharpErrorInfo use the EvalInteractionNonThrowing, EvalScriptNonThrowing or EvalExpressionNonThrowing + (Originally from src/fsharp/fsi\FSIstrings.txt:56) + + + + + Operation could not be completed due to earlier error + (Originally from src/fsharp/fsi\FSIstrings.txt:55) - MISCELLANEOUS - - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:8) + (Originally from src/fsharp/fsi\FSIstrings.txt:8) Loading - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:38) + (Originally from src/fsharp/fsi\FSIstrings.txt:38) #load the given file on startup - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:12) + (Originally from src/fsharp/fsi\FSIstrings.txt:12) Warning: line too long, ignoring some characters\n - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:25) + (Originally from src/fsharp/fsi\FSIstrings.txt:25) - LANGUAGE - - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:7) + (Originally from src/fsharp/fsi\FSIstrings.txt:7) Invalid directive '#%s %s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:24) + (Originally from src/fsharp/fsi\FSIstrings.txt:24) '%s' is not a valid assembly name - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:22) + (Originally from src/fsharp/fsi\FSIstrings.txt:22) See '%s' for options - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:37) + (Originally from src/fsharp/fsi\FSIstrings.txt:37) F# Interactive command line options: - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:36) + (Originally from src/fsharp/fsi\FSIstrings.txt:36) F# Interactive directives: - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:29) + (Originally from src/fsharp/fsi\FSIstrings.txt:29) Toggle timing on/off - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:33) + (Originally from src/fsharp/fsi\FSIstrings.txt:33) Reference (dynamically load) the given DLL - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:30) + (Originally from src/fsharp/fsi\FSIstrings.txt:30) Exit - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:35) + (Originally from src/fsharp/fsi\FSIstrings.txt:35) Load the given file(s) as if compiled and referenced - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:32) + (Originally from src/fsharp/fsi\FSIstrings.txt:32) Display help - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:34) + (Originally from src/fsharp/fsi\FSIstrings.txt:34) Add the given search path for referenced DLLs - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:31) + (Originally from src/fsharp/fsi\FSIstrings.txt:31) \n- Interrupt\n - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:39) + (Originally from src/fsharp/fsi\FSIstrings.txt:39) - INPUT FILES - - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:4) + (Originally from src/fsharp/fsi\FSIstrings.txt:4) Display this usage message (Short form: -?) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:14) + (Originally from src/fsharp/fsi\FSIstrings.txt:14) Execute interactions on a Windows Forms event loop (on by default) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:16) + (Originally from src/fsharp/fsi\FSIstrings.txt:16) Failed to resolve assembly '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:50) + (Originally from src/fsharp/fsi\FSIstrings.txt:50) \n- Exit...\n - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:40) + (Originally from src/fsharp/fsi\FSIstrings.txt:40) Exit fsi after loading the files or running the .fsx script given on the command line - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:15) + (Originally from src/fsharp/fsi\FSIstrings.txt:15) Exception raised when starting remoting server.\n%s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:10) + (Originally from src/fsharp/fsi\FSIstrings.txt:10) \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: %s\n - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:28) + (Originally from src/fsharp/fsi\FSIstrings.txt:28) - ERRORS AND WARNINGS - - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:6) + (Originally from src/fsharp/fsi\FSIstrings.txt:6) Emit debug information in quotations - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:19) + (Originally from src/fsharp/fsi\FSIstrings.txt:19) Directory '%s' doesn't exist - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:23) + (Originally from src/fsharp/fsi\FSIstrings.txt:23) --> Referenced '%s' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:45) + (Originally from src/fsharp/fsi\FSIstrings.txt:45) --> Referenced '%s' (file may be locked by F# Interactive process) - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:44) + (Originally from src/fsharp/fsi\FSIstrings.txt:44) --> Referenced '%s' - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:43) + (Originally from src/fsharp/fsi\FSIstrings.txt:43) --> Added '%s' to library include path - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:46) + (Originally from src/fsharp/fsi\FSIstrings.txt:46) Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t%s - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:42) + (Originally from src/fsharp/fsi\FSIstrings.txt:42) A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:21) + (Originally from src/fsharp/fsi\FSIstrings.txt:21) - CODE GENERATION - - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:5) + (Originally from src/fsharp/fsi\FSIstrings.txt:5) Binding session to '%s'... - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:51) + (Originally from src/fsharp/fsi\FSIstrings.txt:51) For help type #help;; - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:20) + (Originally from src/fsharp/fsi\FSIstrings.txt:20) - ADVANCED - - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:9) + (Originally from src/fsharp/fsi\FSIstrings.txt:9) - Aborting main thread... - (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/fcs/FSharp.Compiler.Service/../../src/fsharp/fsi/FSIstrings.txt:41) + (Originally from src/fsharp/fsi\FSIstrings.txt:41) @@ -8924,7 +9299,7 @@ Iterable functional collection with O(1) append-1 time. Useful for data structures where elements get added at the - end but the collection must occasionally be iterated. Iteration is slower and may allocate because + end but the collection must occasionally be iterated. Iteration is slower and may allocate because a suffix of elements is stored in reverse order. The type doesn't support structural hashing or comparison. @@ -8935,19 +9310,19 @@ A record of options to control structural formatting. For F# Interactive properties matching those of this value can be accessed via the 'fsi' value. - + Floating Point format given in the same format accepted by System.Double.ToString, e.g. f6 or g15. If ShowProperties is set the printing process will evaluate properties of the values being - displayed. This may cause additional computation. + displayed. This may cause additional computation. The ShowIEnumerable is set the printing process will force the evaluation of IEnumerable objects to a small, finite depth, as determined by the printing parameters. This may lead to additional computation being performed during printing. <example> - From F# Interactive the default settings can be adjusted using, for example, + From F# Interactive the default settings can be adjusted using, for example, <pre> open FSharp.Compiler.Interactive.Settings;; setPrintWidth 120;; @@ -8957,20 +9332,20 @@ - The maximum number of rows for which to generate layout for table-like + The maximum number of rows for which to generate layout for table-like structures. -1 if no maximum. - The maximum number of elements for which to generate layout for - list-like structures, or columns in table-like + The maximum number of elements for which to generate layout for + list-like structures, or columns in table-like structures. -1 if no maximum. - Return to the layout-generation + Return to the layout-generation environment to layout any otherwise uninterpreted object @@ -9030,7 +9405,7 @@ - Layout like an F# list. + Layout like an F# list. @@ -9040,7 +9415,7 @@ - Layout list vertically. + Layout list vertically. @@ -9050,17 +9425,17 @@ - Form tuple of layouts. + Form tuple of layouts. - Wrap braces around layout. + Wrap braces around layout. - Wrap square brackets around layout. + Wrap square brackets around layout. @@ -9080,7 +9455,7 @@ - Join layouts into a space separated list. + Join layouts into a space separated list. @@ -9090,12 +9465,12 @@ - Join broken with ident=2 + Join broken with ident=2 - Join broken with ident=1 + Join broken with ident=1 @@ -9105,7 +9480,7 @@ - Join, possible break with indent=2 + Join, possible break with indent=2 @@ -9120,7 +9495,7 @@ - Join, unbreakable. + Join, unbreakable. @@ -9140,7 +9515,7 @@ - An string leaf + An string leaf @@ -9172,7 +9547,7 @@ - Interpret tables for a unicode lexer generated by <c>fslex.exe</c>. + Interpret tables for a unicode lexer generated by <c>fslex.exe</c>. @@ -9182,7 +9557,7 @@ - The type of tables for an unicode lexer generated by <c>fslex.exe</c>. + The type of tables for an unicode lexer generated by <c>fslex.exe</c>. @@ -9225,17 +9600,27 @@ Dynamically typed, non-lexically scoped parameter table. + + + True if the refill of the buffer ever failed , or if explicitly set to True. + + Fast helper to turn the matched characters into a string, avoiding an intermediate array. - + + + Create a lex buffer backed by source text. + + + Create a lex buffer that reads character or byte inputs by using the given function. - + Create a lex buffer suitable for Unicode lexing that reads characters from the given array. Important: does take ownership of the array. @@ -9260,13 +9645,13 @@ - The line number for the position in the input stream, assuming fresh positions have been updated + The line number for the position in the input stream, assuming fresh positions have been updated using for the new line. - The line number in the input stream, assuming fresh positions have been updated + The line number in the input stream, assuming fresh positions have been updated for the new line by modifying the EndPos property of the LexBuffer. @@ -9282,7 +9667,7 @@ - Get an arbitrary position, with the empty string as filename. + Get an arbitrary position, with the empty string as filename. @@ -9292,7 +9677,7 @@ - Return the column number marked by the position, + Return the column number marked by the position, i.e. the difference between the <c>AbsoluteOffset</c> and the <c>StartOfLineAbsoluteOffset</c> @@ -9518,6 +9903,23 @@ Helpers used by generated parsers. + + + Map a directory name with its replacement. + Prefixes are compared case sensitively. + + + + + Map a file path with its replacement. + Prefixes are compared case sensitively. + + + + + Add a path mapping to the map. + + Split an array of pairs into two arrays. @@ -9567,7 +9969,7 @@ Apply 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, + also passing the index of the elements. The two arrays must have the same lengths, otherwise an <c>ArgumentException</c> is raised. @@ -9584,7 +9986,7 @@ - Apply a function to pairs of elements drawn from the two collections, right-to-left, + 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 arrays must have the same lengths, otherwise an <c>ArgumentException</c> is raised. @@ -9592,7 +9994,7 @@ - Apply a function to pairs of elements drawn from the two collections, + Apply a function to pairs of elements drawn from the two collections, left-to-right, threading an accumulator argument through the computation. The two input arrays must have the same lengths, otherwise an <c>ArgumentException</c> is @@ -9602,28 +10004,28 @@ Apply a function to each element of the array, threading an accumulator argument - through the computation. If the input function is <c>f</c> and the elements are <c>i0...iN</c> then + through the computation. If the input function is <c>f</c> and the elements are <c>i0...iN</c> then computes <c>f i0 (...(f iN-1 iN))</c>. Raises ArgumentException if the array has size zero. Apply a function to each element of the array, threading an accumulator argument - through the computation. If the input function is <c>f</c> and the elements are <c>i0...iN</c> + through the computation. If the input function is <c>f</c> and the elements are <c>i0...iN</c> then computes <c>f (... (f i0 i1)...) iN</c>. Raises ArgumentException if the array has size zero. Return the index of the first element in the array - that satisfies the given predicate. Raise <c>KeyNotFoundException</c> if + that satisfies the given predicate. Raise <c>KeyNotFoundException</c> if none of the elements satisfy the predicate. Return the index of the first element in the array - that satisfies the given predicate. Raise <c>KeyNotFoundException</c> if + that satisfies the given predicate. Raise <c>KeyNotFoundException</c> if none of the elements satisfy the predicate. @@ -9690,7 +10092,7 @@ - Split the collection into two collections, containing the + Split the collection into two collections, containing the elements for which the given predicate returns True and False respectively. @@ -9711,7 +10113,7 @@ Test if any element of the array satisfies the given predicate. - If the input function is <c>f</c> and the elements are <c>i0...iN</c> + If the input function is <c>f</c> and the elements are <c>i0...iN</c> then computes <c>p i0 or ... or p iN</c>. @@ -9750,20 +10152,20 @@ - Apply the given function to each element of the array. + Apply the given function to each element of the array. Apply a function to each element of the array, threading an accumulator argument - through the computation. If the input function is <c>f</c> and the elements are <c>i0...iN</c> then + through the computation. If the input function is <c>f</c> and the elements are <c>i0...iN</c> then computes <c>f i0 (...(f iN s))</c>. Apply a function to each element of the collection, threading an accumulator argument - through the computation. If the input function is <c>f</c> and the elements are <c>i0...iN</c> + through the computation. If the input function is <c>f</c> and the elements are <c>i0...iN</c> then computes <c>f (... (f s i0)...) iN</c> @@ -9841,7 +10243,7 @@ Calculates the edit distance between two strings. - The edit distance is a metric that allows to measure the amount of difference between two strings + The edit distance is a metric that allows to measure the amount of difference between two strings and shows how many edit operations (insert, delete, substitution) are needed to transform one string into the other. @@ -9904,7 +10306,7 @@ - Some filename operations. + Some filename operations. @@ -9993,7 +10395,7 @@ - Hash tables, by default based on F# structural "hash" and (=) functions. + Hash tables, by default based on F# structural "hash" and (=) functions. The table may map a single key to multiple bindings. @@ -10009,7 +10411,7 @@ - Set the given key. + Set the given key. @@ -10036,8 +10438,8 @@ Simple priority caching for a small number of key/value associations. This cache may age-out results that have been Set by the caller. - Because of this, the caller must be able to tolerate values - that aren't what was originally passed to the Set function. + Because of this, the caller must be able to tolerate values + that aren't what was originally passed to the Set function. Concurrency: This collection is thread-safe, though concurrent use may result in different threads seeing different live sets of cached items, and may result in the onDiscard action @@ -10090,7 +10492,7 @@ Simple aging lookup table. When a member is accessed it's moved to the top of the list and when there are too many elements - the least-recently-accessed element falls of the end. + the least-recently-accessed element falls of the end. - areSimilar: Keep at most once association for two similar keys (as given by areSimilar) @@ -10113,7 +10515,7 @@ - Lookup an element in the map, returning a Some value if the element is in the domain + Lookup an element in the map, returning a Some value if the element is in the domain of the map and None if not. @@ -10171,12 +10573,12 @@ - Fold over the bindings in the map. + Fold over the bindings in the map. - Fold over the bindings in the map. + Fold over the bindings in the map. @@ -10219,7 +10621,7 @@ - Immutable maps. A constraint tag carries information about the class of key-comparers being used. + Immutable maps. A constraint tag carries information about the class of key-comparers being used. @@ -10313,7 +10715,7 @@ Test if all elements of the collection satisfy the given predicate. - If the input function is f and the elements are i0...iN and j0...jN then + If the input function is f and the elements are i0...iN and j0...jN then computes p i0 && ... && p iN. @@ -10331,7 +10733,7 @@ Test if any element of the collection satisfies the given predicate. - If the input function is f and the elements are i0...iN then computes + If the input function is f and the elements are i0...iN then computes p i0 or ... or p iN. @@ -10362,7 +10764,7 @@ - Compares a and b and returns 1 if a > b, -1 if b < a and 0 if a = b. + Compares a and b and returns 1 if a > b, -1 if b < a and 0 if a = b. @@ -10374,7 +10776,7 @@ - Immutable sets where a constraint tag carries information about the class of key-comparer being used. + Immutable sets where a constraint tag carries information about the class of key-comparer being used. @@ -10387,83 +10789,214 @@ Convert string into Option string where null and String.Empty result in None - + - Test to report for the name of the type provider that produced the value + Construct a new DependencyProvider - + - The ILScopeRef of the runtime assembly reference for type provider that produced the value + Handle Assembly resolution - + - A type provider that produced the value + Signature for ResolutionProbe callback + host implements this, it's job is to return a list of assembly paths to probe. - + - Apply an operation and 'untaint' the result. This can be used if the return type - is guaranteed not to be implemented by a type provider + Construct a new DependencyProvider - + - Apply an operation and 'untaint' the result. The result must be marshallable. Any exception will be attributed to the type provider with an error located at the given range + Signature for Native library resolution probe callback + host implements this, it's job is to return a list of package roots to probe. - + - Apply an operation. Any exception will be attributed to the type provider with an error located at the given range + TryFindDependencyManagerInPath - given a #r "key:sometext" go and find a DependencyManager that satisfies the key - + - Apply an operation that returns an option. Unwrap option. Any exception will be attributed to the type provider with an error located at the given range + Fetch a dependencymanager that supports a specific key - + - Apply an operation. No exception may be raised by 'f' + Resolve reference for a list of package manager lines - + - Apply an operation that returns an array. Unwrap array. Any exception will be attributed to the type provider with an error located at the given range. String is method name of thing-returning-array, to diagnostically attribute if it is null + Remove the dependency mager with the specified key - + - Apply an operation. Any exception will be attributed to the type provider with an error located at the given range + Returns a formatted error message for the host to present - + - Apply an operation. Any exception will be attributed to the type provider with an error located at the given range + Construct a new DependencyProvider - + - Apply an operation. Any exception will be attributed to the type provider with an error located at the given range + Construct a new DependencyProvider - + - Apply an operation. Any exception will be attributed to the type provider with an error located at the given range + Provides DependencyManagement functions. + Class is IDisposable - + - Conditionally coerce the value + Todo describe this API - + - Create an initial tainted value + Name of the dependency manager - + + + Key that identifies the types of dependencies that this DependencyManager operates on + E.g + nuget: indicates that this DM is for nuget packages + paket: indicates that this DM is for paket scripts, which manage nuget packages, github source dependencies etc ... + + + + + Resolve the dependencies, for the given set of arguments, go find the .dll references, scripts and additional include values. + + + + + Wraps access to a DependencyManager implementation + + + + + Succeded? + + + + + The resolution output log + + + + + The resolution error log (process stderr) + + + + + The source code file paths + + + + + The roots to package directories + + + + + The resolution paths + + + + + The results of ResolveDependencies + + + + + Test to report for the name of the type provider that produced the value + + + + + The ILScopeRef of the runtime assembly reference for type provider that produced the value + + + + + A type provider that produced the value + + + + + Apply an operation and 'untaint' the result. This can be used if the return type + is guaranteed not to be implemented by a type provider + + + + + Apply an operation and 'untaint' the result. The result must be marshallable. Any exception will be attributed to the type provider with an error located at the given range + + + + + Apply an operation. Any exception will be attributed to the type provider with an error located at the given range + + + + + Apply an operation that returns an option. Unwrap option. Any exception will be attributed to the type provider with an error located at the given range + + + + + Apply an operation. No exception may be raised by 'f' + + + + + Apply an operation that returns an array. Unwrap array. Any exception will be attributed to the type provider with an error located at the given range. String is method name of thing-returning-array, to diagnostically attribute if it is null + + + + + Apply an operation. Any exception will be attributed to the type provider with an error located at the given range + + + + + Apply an operation. Any exception will be attributed to the type provider with an error located at the given range + + + + + Apply an operation. Any exception will be attributed to the type provider with an error located at the given range + + + + + Apply an operation. Any exception will be attributed to the type provider with an error located at the given range + + + + + Conditionally coerce the value + + + + + Create an initial tainted value + + + Assert that the value is of 'U and coerce the value. If coercion fails, the failure will be blamed on a type provider @@ -10504,11 +11037,6 @@ Stores and transports aggregated list of errors reported by the type provider - - - Whether there are any 'live' type providers that may need a refresh when a project is Cleaned - - The TcConfig passed in to the builder creation. @@ -10525,12 +11053,7 @@ overall analysis results for the project will be quick. - - - Check if the builder is not disposed - - - + Raised when a type provider invalidates the build. @@ -10549,7 +11072,7 @@ Raised just before a file is type-checked, to invalidate the state of the file in VS and force VS to request a new direct typecheck of the file. The incremental builder also typechecks the file (error and intellisense results from the background builder are not - used by VS). + used by VS). @@ -10557,16 +11080,14 @@ The list of files the build depends on - + - Perform one step in the F# build. Return true if the background work is finished. + Tries to get the current successful TcImports. This is only used in testing. Do not use it for other stuff. - + - Increment the usage count on the IncrementalBuilder by 1. This initial usage count is 0 so immediately after creation - a call to KeepBuilderAlive should be made. The returns an IDisposable which will - decrement the usage count and dispose if the usage count goes to zero + Perform one step in the F# build. Return true if the background work is finished. @@ -10632,7 +11153,17 @@ Manages an incremental build graph for the build of an F# project - + + + If enabled, holds semantic classification information for Item(symbol)s in a file. + + + + + If enabled, stores a linear list of ranges and strings that identify an Item(symbol) in a file. Used for background find all references. + + + Represents latest inferred signature contents. @@ -10645,7 +11176,7 @@ - Represents the collected attributes to apply to the module of assuembly generates + Represents the collected attributes to apply to the module of assembly generates @@ -10715,7 +11246,7 @@ - Empty patial long name. + Empty partial long name. @@ -10723,9 +11254,74 @@ Qualified long name. + + + Get the list of valid versions + + + + + Get the list of valid options + + + + + Get the specified LanguageVersion as a string + + + + + Get the specified LanguageVersion + + + + + Has preview been explicitly specified + + + + + Does the selected LanguageVersion support the specified feature + + + + + Get a version string associated with the given feature. + + + + + Get a string name for the given feature. + + + + + Get the list of valid versions + + + + + Create a LanguageVersion management object + + + + + LanguageVersion management + + + + + LanguageFeature enumeration + + + + + Coordinating compiler operations - configuration, loading initial context, reporting errors etc. + + - is this the developer-debug build? + is this the developer-debug build? @@ -10889,7 +11485,7 @@ - The maximum number of bits needed to store an encoded position + The maximum number of bits needed to store an encoded position @@ -11004,7 +11600,7 @@ - not a total order, but enough to sort on ranges + not a total order, but enough to sort on ranges @@ -11014,12 +11610,12 @@ - This view hides the use of file indexes and just uses filenames + This view hides the use of file indexes and just uses filenames - This view of range marks uses file indexes explicitly + This view of range marks uses file indexes explicitly @@ -11042,6 +11638,11 @@ Convert a file path to an index + + + Equality comparer for range. + + Convert a range from one-based line counting (used internally in the F# compiler and in F# error messages) to zero-based line counting (used by Visual Studio) @@ -11059,7 +11660,7 @@ - Convert a position from zero-based line counting (used by Visual Studio) to one-based line counting (used internally in the F# compiler and in F# error messages) + Convert a position from zero-based line counting (used by Visual Studio) to one-based line counting (used internally in the F# compiler and in F# error messages) @@ -11069,7 +11670,7 @@ - Convert a line number from zero-based line counting (used by Visual Studio) to one-based line counting (used internally in the F# compiler and in F# error messages) + Convert a line number from zero-based line counting (used by Visual Studio) to one-based line counting (used internally in the F# compiler and in F# error messages) @@ -11088,12 +11689,12 @@ Return true if the textual phase given is from the compile part of the build process. - This set needs to be equal to the set of subcategories that the language service can produce. + This set needs to be equal to the set of subcategories that the language service can produce. - the language service knows about. + the language service knows about. @@ -11114,7 +11715,7 @@ fixes given string by replacing all control chars with spaces. - NOTE: newlines are recognized and replaced with stringThatIsAProxyForANewlineInFlatErrors (ASCII 29, the 'group separator'), + NOTE: newlines are recognized and replaced with stringThatIsAProxyForANewlineInFlatErrors (ASCII 29, the 'group separator'), which is decoded by the IDE with 'NewlineifyErrorString' back into newlines, so that multi-line errors can be displayed in QuickInfo @@ -11125,27 +11726,27 @@ - Stop on first error. Accumulate warnings and continue. + Stop on first error. Accumulate warnings and continue. - Stop on first error. Report index + Stop on first error. Report index - Stop on first error. Accumulate warnings and continue. + Stop on first error. Accumulate warnings and continue. - Stop on first error. Accumulate warnings and continue. + Stop on first error. Accumulate warnings and continue. - The bind in the monad. Stop on first error. Accumulate warnings and continue. + The bind in the monad. Stop on first error. Accumulate warnings and continue. @@ -11214,14 +11815,9 @@ Literal build phase subcategory strings. - - - Formats the given predictions according to the error style. - - - + - Filters predictions based on edit distance to the given unknown identifier. + Demangles a suggestion @@ -11238,7 +11834,7 @@ Get the Reference Assemblies directory for the .NET Framework (on Windows) - This is added to the default resolution path for + This is added to the default resolution path for design-time compilations. @@ -11259,7 +11855,7 @@ - Round-tripped baggage + Round-tripped baggage @@ -11282,6 +11878,21 @@ Indicates a script or source being edited or compiled. Uses reference assemblies (not implementation assemblies). + + + The prefix of the names used for the fake namespace path added to all dynamic code entries in FSI.EXE + + + + + Reuses generated exception field name objects for common field numbers + + + + + Reuses generated union case field name objects for common field numbers + + Mangle the static parameters for a provided type or method @@ -11311,7 +11922,7 @@ Return a string array delimited by the given separator. - Note that a quoted string is not going to be mangled into pieces. + Note that a quoted string is not going to be mangled into pieces. @@ -11395,12 +12006,13 @@ - Anything to do with special names of identifiers and other lexical rules + Some general F# utilities for mangling / unmangling / manipulating names. + Anything to do with special names of identifiers and other lexical rules - Diagnostics from the AbsIL toolkit. You can reset the diagnostics + Diagnostics from the AbsIL toolkit. You can reset the diagnostics stream to point elsewhere, or turn it off altogether by setting it to 'None'. The logging channel initially points to stderr. All functions call flush() automatically. @@ -11428,11 +12040,23 @@ Helpers for codegen: scopes for allocating new temporary variables. + + + Is the given assembly possibly a primary assembly? + In practice, a primary assembly is an assembly that contains the System.Object type definition + and has no referenced assemblies. + However, we must consider assemblies that forward the System.Object type definition + to be possible primary assemblies. + Therefore, this will return true if the given assembly is the real primary assembly or an assembly that forwards + the System.Object type definition. + Assembly equivalency ignores the version here. + + A table of common references to items in primary assembly (System.Runtime or mscorlib). - If a particular version of System.Runtime.dll has been loaded then you should - reference items from it via an ILGlobals for that specific version built using mkILGlobals. + If a particular version of System.Runtime.dll has been loaded then you should + reference items from it via an ILGlobals for that specific version built using mkILGlobals. @@ -11445,8 +12069,8 @@ One module in the "current" assembly, either a main-module or an auxiliary module. The main module will have a manifest. - An assembly is built by joining together a "main" module plus - several auxiliary modules. + An assembly is built by joining together a "main" module plus + several auxiliary modules. @@ -11461,31 +12085,31 @@ - Records whether the entrypoint resides in another module. + Records whether the entrypoint resides in another module. - Records the types implemented by this assembly in auxiliary - modules. + Records the types implemented by this assembly in auxiliary + modules. - This is the public key used to sign this - assembly (the signature itself is stored elsewhere: see the - binary format, and may not have been written if delay signing - is used). (member Name, member PublicKey) forms the full - public name of the assembly. + This is the public key used to sign this + assembly (the signature itself is stored elsewhere: see the + binary format, and may not have been written if delay signing + is used). (member Name, member PublicKey) forms the full + public name of the assembly. - This is the ID of the algorithm used for the hashes of auxiliary - files in the assembly. These hashes are stored in the - <c>ILModuleRef.Hash</c> fields of this assembly. These are not - cryptographic hashes: they are simple file hashes. The algorithm - is normally <c>0x00008004</c> indicating the SHA1 hash algorithm. + This is the ID of the algorithm used for the hashes of auxiliary + files in the assembly. These hashes are stored in the + <c>ILModuleRef.Hash</c> fields of this assembly. These are not + cryptographic hashes: they are simple file hashes. The algorithm + is normally <c>0x00008004</c> indicating the SHA1 hash algorithm. @@ -11507,8 +12131,8 @@ "Manifest ILResources" are chunks of resource data, being one of: - the data section of the current module (byte[] of resource given directly). - - in an external file in this assembly (offset given in the ILResourceLocation field). - - as a resources in another assembly of the same name. + - in an external file in this assembly (offset given in the ILResourceLocation field). + - as a resources in another assembly of the same name. @@ -11521,14 +12145,9 @@ Represents a manifest resource in an associated file - - - Represents a manifest resource that is due to be written to the output PE file - - - + - Represents a manifest resource that can be read from within the PE file + Represents a manifest resource that can be read or written to a PE file @@ -11538,12 +12157,12 @@ - these are only found in the ILExportedTypesAndForwarders table in the manifest + these are only found in the ILExportedTypesAndForwarders table in the manifest - these are only found in the "Nested" field of ILExportedTypeOrForwarder objects + these are only found in the "Nested" field of ILExportedTypeOrForwarder objects @@ -11562,13 +12181,13 @@ - Class or interface generated for COM interop. + Class or interface generated for COM interop. - Some classes are marked "HasSecurity" even if there are no permissions attached, - e.g. if they use SuppressUnmanagedCodeSecurityAttribute + Some classes are marked "HasSecurity" even if there are no permissions attached, + e.g. if they use SuppressUnmanagedCodeSecurityAttribute @@ -11588,7 +12207,7 @@ - Represents IL Type Definitions. + Represents IL Type Definitions. @@ -11598,15 +12217,15 @@ - Calls to <c>FindByName</c> will result in any laziness in the overall - set of ILTypeDefs being read in in addition - to the details for the type found, but the remaining individual - type definitions will not be read. + Calls to <c>FindByName</c> will result in any laziness in the overall + set of ILTypeDefs being read in in addition + to the details for the type found, but the remaining individual + type definitions will not be read. - Tables of named type definitions. + Tables of named type definitions. @@ -11691,7 +12310,7 @@ - Tables of fields. Logically equivalent to a list of fields but the table is kept in + Tables of fields. Logically equivalent to a list of fields but the table is kept in a form to allow efficient looking up fields by name. @@ -11723,13 +12342,13 @@ Tables of methods. Logically equivalent to a list of methods but - the table is kept in a form optimized for looking up methods by + the table is kept in a form optimized for looking up methods by name and arity. - Indicates an instance methods that is virtual or abstract or implements an interface slot. + Indicates an instance methods that is virtual or abstract or implements an interface slot. @@ -11764,7 +12383,7 @@ - Some methods are marked "HasSecurity" even if there are no permissions attached, e.g. if they use SuppressUnmanagedCodeSecurityAttribute + Some methods are marked "HasSecurity" even if there are no permissions attached, e.g. if they use SuppressUnmanagedCodeSecurityAttribute @@ -11784,7 +12403,7 @@ - IL Method definitions. + IL Method definitions. @@ -11829,7 +12448,7 @@ - [OverridesSpec] - refer to a method declaration in a superclass or interface. + [OverridesSpec] - refer to a method declaration in a superclass or interface. @@ -11844,7 +12463,7 @@ - Abstract type equivalent to ILSecurityDecl list - use helpers + Abstract type equivalent to ILSecurityDecl list - use helpers below to construct/destruct these. @@ -11855,7 +12474,7 @@ - Marshalling map for parameters. COM Interop only. + Marshalling map for parameters. COM Interop only. @@ -11922,13 +12541,13 @@ - optional idx of parameter giving size plus optional additive i.e. num elems + optional idx of parameter giving size plus optional additive i.e. num elems Native Types, for marshalling to the native C interface. - These are taken directly from the ILASM syntax, see ECMA Spec (Partition II, 7.4). + These are taken directly from the ILASM syntax, see ECMA Spec (Partition II, 7.4). @@ -11938,14 +12557,14 @@ - Indicates that a particular local variable has a particular source - language name within a given set of ranges. This does not effect local - variable numbering, which is global over the whole method. + Indicates that a particular local variable has a particular source + language name within a given set of ranges. This does not effect local + variable numbering, which is global over the whole method. - The instruction set. + The instruction set. @@ -11970,7 +12589,7 @@ - Formal identities of fields. + Formal identities of fields. @@ -11980,27 +12599,27 @@ - Formal identities of methods. + Formal identities of methods. - Actual generic parameters are always types. + Actual generic parameters are always types. - Custom modifiers. + Custom modifiers. - Reference a generic arg. + Reference a generic arg. - ILCode pointers. + ILCode pointers. @@ -12015,7 +12634,7 @@ - Reference types. Also may be used for parents of members even if for members in value types. + Reference types. Also may be used for parents of members even if for members in value types. @@ -12025,7 +12644,7 @@ - Array types + Array types @@ -12035,7 +12654,7 @@ - The type being modified. + The type being modified. @@ -12045,7 +12664,7 @@ - Where is the type, i.e. is it in this module, in another module in this assembly or in another assembly? + Where is the type, i.e. is it in this module, in another module in this assembly or in another assembly? @@ -12075,12 +12694,12 @@ - Type specs and types. + Type specs and types. - Where is the type, i.e. is it in this module, in another module in this assembly or in another assembly? + Where is the type, i.e. is it in this module, in another module in this assembly or in another assembly? @@ -12115,17 +12734,17 @@ - Bounds for a single dimensional, zero based array + Bounds for a single dimensional, zero based array - Lower-bound/size pairs + Lower-bound/size pairs - Array shapes. For most purposes the rank is the only thing that matters. + Array shapes. For most purposes the rank is the only thing that matters. @@ -12135,12 +12754,17 @@ - accepts an explicit 'this' pointer + accepts an explicit 'this' pointer - accepts an implicit 'this' pointer + accepts an implicit 'this' pointer + + + + + A reference to a type in the primary assembly @@ -12160,7 +12784,7 @@ - CLI says this indicates if the assembly can be retargeted (at runtime) to be from a different publisher. + CLI says this indicates if the assembly can be retargeted (at runtime) to be from a different publisher. @@ -12170,16 +12794,16 @@ - Debug info. Values of type "source" can be attached at sequence - points and some other locations. + Debug info. Values of type "source" can be attached at sequence + points and some other locations. - Represents guids + Represents guids - + Find the full set of assemblies referenced by a module. @@ -12194,24 +12818,24 @@ Get a public key token from a public key. - + Discriminating different important built-in types. - This is a 'vendor neutral' way of referencing mscorlib. + This is a 'vendor neutral' way of referencing mscorlib. - Instantiate type variables that occur within types and other items. + Instantiate type variables that occur within types and other items. - Instantiate type variables that occur within types and other items. + Instantiate type variables that occur within types and other items. @@ -12221,41 +12845,41 @@ - Rescoping. The first argument tells the function how to reference the original scope from - the new scope. + Rescoping. The first argument tells the function how to reference the original scope from + the new scope. - Rescoping. The first argument tells the function how to reference the original scope from - the new scope. + Rescoping. The first argument tells the function how to reference the original scope from + the new scope. - Rescoping. The first argument tells the function how to reference the original scope from - the new scope. + Rescoping. The first argument tells the function how to reference the original scope from + the new scope. - Rescoping. The first argument tells the function how to reference the original scope from - the new scope. + Rescoping. The first argument tells the function how to reference the original scope from + the new scope. - Rescoping. The first argument tells the function how to reference the original scope from - the new scope. + Rescoping. The first argument tells the function how to reference the original scope from + the new scope. Generate references to existing type definitions, method definitions etc. Useful for generating references, e.g. to a class we're processing - Also used to reference type definitions that we've generated. [ILScopeRef] + Also used to reference type definitions that we've generated. [ILScopeRef] is normally ILScopeRef.Local, unless we've generated the ILTypeDef in - an auxiliary module or are generating multiple assemblies at + an auxiliary module or are generating multiple assemblies at once. @@ -12266,14 +12890,14 @@ - Create table of types which is loaded/computed on-demand, and whose individual - elements are also loaded/computed on-demand. Any call to tdefs.AsList will + Create table of types which is loaded/computed on-demand, and whose individual + elements are also loaded/computed on-demand. Any call to tdefs.AsList will result in the laziness being forced. Operations can examine the custom attributes and name of each type in order to decide whether to proceed with examining the other details of the type. - - Note that individual type definitions may contain further delays - in their method, field and other tables. + + Note that individual type definitions may contain further delays + in their method, field and other tables. @@ -12288,7 +12912,7 @@ - Given a delegate type definition which lies in a particular scope, + Given a delegate type definition which lies in a particular scope, make a reference to its constructor. @@ -12315,8 +12939,8 @@ Make a type definition for a value type used to point to raw data. - These are useful when generating array initialization code - according to the + These are useful when generating array initialization code + according to the ldtoken field valuetype '<PrivateImplementationDetails>'/'$$struct0x6000127-1' '<PrivateImplementationDetails>'::'$$method0x6000127-1' call void System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class System.Array,valuetype System.RuntimeFieldHandle) idiom. @@ -12355,7 +12979,7 @@ - Make some code that is a straight line sequence of instructions. + Make some code that is a straight line sequence of instructions. The function will add a "return" if the last instruction is not an exiting instruction. @@ -12436,25 +13060,25 @@ - Not all custom attribute data can be decoded without binding types. In particular - enums must be bound in order to discover the size of the underlying integer. - The following assumes enums have size int32. + Not all custom attribute data can be decoded without binding types. In particular + enums must be bound in order to discover the size of the underlying integer. + The following assumes enums have size int32. When writing a binary the fake "toplevel" type definition (called <Module>) - must come first. This function puts it first, and creates it in the returned + must come first. This function puts it first, and creates it in the returned list as an empty typedef if it doesn't already exist. - + Build the table of commonly used references given functions to find types in system assemblies - splitTypeNameRight is like splitILTypeName except the + splitTypeNameRight is like splitILTypeName except the namespace is kept as a whole string, rather than split at dots. @@ -12463,15 +13087,15 @@ a type name into the leading namespace elements (if any), the names of any nested types and the type name itself. This function memoizes and interns the splitting of the namespace portion of - the type name. + the type name. - Find the method definition corresponding to the given property or - event operation. These are always in the same class as the property - or event. This is useful especially if your code is not using the Ilbind - API to bind references. + Find the method definition corresponding to the given property or + event operation. These are always in the same class as the property + or event. This is useful especially if your code is not using the Ilbind + API to bind references. @@ -12500,7 +13124,7 @@ of particular ILTypeDefs. The morphing functions are passed some details about the context in which the item being morphed occurs, e.g. the module being morphed itself, the - ILTypeDef (possibly nested) where the item occurs, + ILTypeDef (possibly nested) where the item occurs, the ILMethodDef (if any) where the item occurs. etc. @@ -12519,9 +13143,53 @@ Imperative buffers and streams of byte[] + + + Creates a ByteMemory object that is backed by a raw pointer. + Use with care. + + + + + Creates a ByteMemory object that has a backing memory mapped file from a file on-disk. + + + + + Creates a ByteMemory object that is backed by a byte array. + + + + + Creates a ByteMemory object that is backed by a byte array with the specified offset and length. + + + + + Create another ByteMemory object that has a backing memory mapped file based on another ByteMemory's contents. + + + + + Get a stream representation of the backing memory. + Disposing this will not free up any of the backing memory. + + + + + Get a stream representation of the backing memory. + Disposing this will not free up any of the backing memory. + Stream cannot be written to. + + + + + May be backed by managed or unmanaged memory, or memory mapped file. + + - Immutable map collection, with explicit flattening to a backing dictionary + Immutable map collection, with explicit flattening to a backing dictionary @@ -12541,7 +13209,7 @@ - This field holds either the function to run or a LazyWithContextFailure object recording the exception raised + This field holds either the function to run or a LazyWithContextFailure object recording the exception raised from running the function. It is null if the thunk has been evaluated successfully. @@ -12576,7 +13244,7 @@ - Computations suspend via a NotYetDone may use local state (mutables), where these are captured by the NotYetDone closure. Computations do not need to be restartable. - - The key thing is that you can take an Eventually value and run it with + - The key thing is that you can take an Eventually value and run it with Eventually.repeatedlyProgressUntilDoneOrTimeShareOverOrCanceled - Cancellation results in a suspended computation rather than complete abandonment @@ -12586,8 +13254,8 @@ Represents a cancellable computation with explicit representation of a cancelled result. - A cancellable computation is passed may be cancelled via a CancellationToken, which is propagated implicitly. - If cancellation occurs, it is propagated as data rather than by raising an OperationCanceledException. + A cancellable computation is passed may be cancelled via a CancellationToken, which is propagated implicitly. + If cancellation occurs, it is propagated as data rather than by raising an OperationCanceledException. @@ -12608,13 +13276,13 @@ - Represents a token that indicates execution on the compilation thread, i.e. + Represents a token that indicates execution on the compilation thread, i.e. - we have full access to the (partially mutable) TAST and TcImports data structures - compiler execution may result in type provider invocations when resolving types and members - we can access various caches in the SourceCodeServices Like other execution tokens this should be passed via argument passing and not captured/stored beyond - the lifetime of stack-based calls. This is not checked, it is a discipline within the compiler code. + the lifetime of stack-based calls. This is not checked, it is a discipline within the compiler code. @@ -12629,7 +13297,7 @@ - Get an initialization hole + Get an initialization hole @@ -12640,7 +13308,7 @@ Represents a place in the compiler codebase where we are passed a CompilationThreadToken unnecessarily. - This reprents code that may potentially not need to be executed on the compilation thread. + This represents code that may potentially not need to be executed on the compilation thread. @@ -12652,7 +13320,7 @@ Per the docs the threshold for the Large Object Heap is 85000 bytes: https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/large-object-heap#how-an-object-ends-up-on-the-large-object-heap-and-how-gc-handles-them - We set the limit to slightly under that to allow for some 'slop' + We set the limit to be 80k to account for larger pointer sizes for when F# is running 64-bit. @@ -12703,7 +13371,7 @@ Take in a filename with an absolute path, and return the same filename - but canonicalized with respect to extra path separators (e.g. C:\\\\foo.txt) + but canonicalized with respect to extra path separators (e.g. C:\\\\foo.txt) and '..' portions @@ -12739,7 +13407,7 @@ - For every entry in m2 find an entry in m1 and fold + For every entry in m2 find an entry in m1 and fold @@ -12749,7 +13417,7 @@ - Not a very useful function - only called in one place - should be changed + Not a very useful function - only called in one place - should be changed @@ -12798,7 +13466,7 @@ - Run the computation in a mode where it may not be cancelled. The computation never results in a + Run the computation in a mode where it may not be cancelled. The computation never results in a ValueOrCancelled.Cancelled. @@ -12880,7 +13548,7 @@ - check if subArray is found in the wholeArray starting + check if subArray is found in the wholeArray starting at the provided index @@ -12914,12 +13582,12 @@ - each int will be 0 <= x <= 255 + each int will be 0 <= x <= 255 - each int must be 0 <= x <= 255 + each int must be 0 <= x <= 255 @@ -12932,7 +13600,7 @@ Various constants and utilities used when parsing the ILASM format for IL - + Unmanaged resource file linker - for native resources (not managed ones). The function may be called twice, once with a zero-RVA and @@ -12942,18 +13610,13 @@ - Functions associated with writing binaries which - vary between supported implementations of the CLI Common Language + Functions associated with writing binaries which + vary between supported implementations of the CLI Common Language Runtime, e.g. between the SSCLI, Mono and the Microsoft CLR. The implementation of the functions can be found in ilsupp-*.fs - - - vararg sentinels - - This function maps production indexes returned in syntax errors to strings representing the non terminal that would be produced by that production @@ -12992,42 +13655,42 @@ - Open a binary reader based on the given bytes. + Open a binary reader based on the given bytes. - Open a binary reader, except first copy the entire contents of the binary into - memory, close the file and ensure any subsequent reads happen from the in-memory store. - PDB files may not be read with this option. + Open a binary reader, except first copy the entire contents of the binary into + memory, close the file and ensure any subsequent reads happen from the in-memory store. + PDB files may not be read with this option. Binary reader. Read a .NET binary and concert it to Abstract IL data structures. - + NOTE: - - The metadata in the loaded modules will be relative to - those modules, e.g. ILScopeRef.Local will mean "local to - that module". You must use [rescopeILType] etc. if you want to include - (i.e. copy) the metadata into your own module. + - The metadata in the loaded modules will be relative to + those modules, e.g. ILScopeRef.Local will mean "local to + that module". You must use [rescopeILType] etc. if you want to include + (i.e. copy) the metadata into your own module. - PDB (debug info) reading/folding: - The PDB reader is invoked if you give a PDB path - This indicates if you want to search for PDB files and have the - reader fold them in. You cannot currently name the pdb file - directly - you can only name the path. Giving "None" says - "do not read the PDB file even if one exists". - - The debug info appears primarily as I_seqpoint annotations in + The PDB reader is invoked if you give a PDB path + This indicates if you want to search for PDB files and have the + reader fold them in. You cannot currently name the pdb file + directly - you can only name the path. Giving "None" says + "do not read the PDB file even if one exists". + + The debug info appears primarily as I_seqpoint annotations in the instruction streams. Unfortunately the PDB information does not, for example, tell you how to map back from a class definition to a source code line number - you will need to explicitly search - for a sequence point in the code for one of the methods of the + for a sequence point in the code for one of the methods of the class. That is not particularly satisfactory, and it may be a good idea to build a small library which extracts the information - you need. + you need. @@ -13037,7 +13700,7 @@ - 28 is the size of the IMAGE_DEBUG_DIRECTORY in ntimage.h + 28 is the size of the IMAGE_DEBUG_DIRECTORY in ntimage.h @@ -13047,12 +13710,12 @@ - The ILPdbWriter + The ILPdbWriter - Write a binary to the file system. Extra configuration parameters can also be specified. + Write a binary to the file system. Extra configuration parameters can also be specified. @@ -13091,6 +13754,16 @@ Emit comparison instructions. + + + convConstructorSpec (like convMethodSpec) + + + + + Get a constructor on a non-TypeBuilder type + + Uses the .CreateType() for emitted type if available. @@ -13113,17 +13786,17 @@ Emit comparison instructions. - Generate the helpers? + Generate the helpers? - Are the representation helpers public? + Are the representation helpers public? - Is the representation public? + Is the representation public? @@ -13138,7 +13811,7 @@ Emit comparison instructions. - ILX extensions to Abstract IL types and instructions F# + ILX extensions to Abstract IL types and instructions F# @@ -13211,16568 +13884,18348 @@ Emit comparison instructions. Make the instruction sequence for a "newdata" operation - + - render a Layout yielding an 'a using a 'b (hidden state) type + Will not dispose of the stream reader. - + - Primitive renders + Render a Layout yielding an 'a using a 'b (hidden state) type - + - Run a render on a Layout + Render layout to collector of TaggedText - + - Generates compiler-generated names marked up with a source code location, but if given the same unique value then - return precisely the same name. Each name generated also includes the StartLine number of the range passed in - at the point of first generation. - - This type may be accessed concurrently, though in practice it is only used from the compilation thread. - It is made concurrency-safe since a global instance of the type is allocated in tast.fs. + Render layout to StringBuilder - + - Generates compiler-generated names. Each name generated also includes the StartLine number of the range passed in - at the point of first generation. - - This type may be accessed concurrently, though in practice it is only used from the compilation thread. - It is made concurrency-safe since a global instance of the type is allocated in tast.fs, and it is good - policy to make all globally-allocated objects concurrency safe in case future versions of the compiler - are used to host multiple concurrent instances of compilation. + Render layout to channel - + - The parser defines a number of tokens for whitespace and - comments eliminated by the lexer. These carry a specification of - a continuation for the lexer for continued processing after we've dealt with - the whitespace. + Render layout to string - + - Specifies how the 'endline' function in the lexer should continue after - it reaches end of line or eof. The options are to continue with 'token' function - or to continue with 'skip' function. + Run a render on a Layout - + - The syntactic elements associated with the "return" of a function or method. Some of this is - mostly dummy information to make the return element look like an argument, - the important thing is that (a) you can give a return type for the function or method, and - (b) you can associate .NET attributes to return of a function or method and these get stored in .NET metadata. + non-optional break ident=2 - + - QualifiedNameOfFile acts to fully-qualify module specifications and implementations, - most importantly the ones that simply contribute fragments to a namespace (i.e. the ParsedSigFileFragment.NamespaceFragment case) - There may be multiple such fragments in a single assembly. There may thus also - be multiple matching pairs of these in an assembly, all contributing types to the same - namespace. + non-optional break ident=1 - + - SynMemberDefn.AutoProperty (attribs, isStatic, id, tyOpt, propKind, memberFlags, xmlDoc, access, synExpr, mGetSet, mWholeAutoProp). - - F# syntax: 'member val X = expr' + non-optional break ident=0 - + - A feature that is not implemented + optional break, indent=4 - + - LetBindings(bindingList, isStatic, isRecursive, wholeRange) - - localDefns + optional break, indent=3 - + - inherit <typ>(args...) as base + optional break, indent=2 - + - implicit ctor args as a defn line, 'as' specification + optional break, indent=0 - + - 'exception E = ... with ...' + never break "glue" - + - 'exception E = ... ' + DSL to create structured layout objects with optional breaks and render them - + - The names and other metadata for the type parameters for a member or function + Represents the XmlDoc fragments as collected from the lexer during parsing - + - The argument names and other metadata for a parameter for a member or function + Used to collect XML documentation during lexing and parsing. - + - SynValInfo(curriedArgInfos, returnInfo) + This code runs for .XML generation and thus influences cross-project xmldoc tooltips; for within-project tooltips, + see XmlDocumentation.fs in the language service - + - The argument names and other metadata for a member or function - - - - - The untyped, unchecked syntax tree associated with the name of a type definition or module - in signature or implementation. - - This includes the name, attributes, type parameters, constraints, documentation and accessibility - for a type definition or module. For modules, entries such as the type parameters are - always empty. + Represents the final form of collected XmlDoc lines - + - The untyped, unchecked syntax tree for a field declaration in a record or class + A parsed signature file - + - The information for a type definition in a signature + A parsed implementation file - + - The untyped, unchecked syntax tree for a type definition in a signature + Gets the syntax range of this constuct - + - Indicates the right right-hand-side is a record, union or other simple type. + Represents the syntax tree for a parsed implementation or signature file - + - Indicates the right right-hand-side is a class, struct, interface or other object-model type + Represents the full syntax tree, file name and other parsing information for a signature file - + - The untyped, unchecked syntax tree for the right-hand-side of a type definition in a signature. - Note: in practice, using a discriminated union to make a distinction between - "simple" types and "object oriented" types is not particularly useful. + Represents the full syntax tree, file name and other parsing information for an implementation file - + - Full type spec given by 'UnionCase: ty1 * tyN -> rty'. Only used in FSharp.Core, otherwise a warning. + The name of the file - + - Normal style declaration + Gets the syntax range of this constuct - + - The untyped, unchecked syntax tree for the right-hand-side of union definition, excluding members, - in either a signature or implementation. + The identifier for the name of the file - + - The untyped, unchecked syntax tree for one case in a union definition. + Represents a qualifying name for anonymous module specifications and implementations, - + - The untyped, unchecked syntax tree for one case in an enum definition. + A pragma to turn a warning off - + - An exception definition, "exception E = ..." + Represents a scoped pragma - + - An abstract definition, "type X" + Represents a parsed signature file made up of fragments - + - A type abbreviation, "type X = A.B.C" + Represents a parsed implementation file made up of fragments - + - A type defined by using an IL assembly representation. Only used in FSharp.Core. - - F# syntax: "type X = (# "..."#) + Represents a parsed syntax tree for an F# Interactive interaction - + - An object oriented type definition. This is not a parse-tree form, but represents the core - type representation which the type checker splits out from the "ObjectModel" cases of type definitions. + A signature file namespace fragment - + - A record type definition, type X = { A: int; B: int } + A signature file which is a module, 'module N' - + - An enum type definition, type X = A = 1 | B = 2 + A signature file which is an anonymous module, e.g. the signature file for the final file in an application - + - A union type definition, type X = A | B + Represents the syntax tree for the contents of a parsed signature file - + - The untyped, unchecked syntax tree for the core of a simple type definition, in either signature - or implementation. + An implementation file fragment which declares a namespace fragment - + - The untyped, unchecked syntax tree for a member signature, used in signature files, abstract member declarations - and member constraints. + An implementation file is a named module definition, 'module N' - + - An artificial member kind used prior to the point where a get/set property is split into two distinct members. + An implementation file which is an anonymous module definition, e.g. a script - + - Note the member kind is actually computed partially by a syntax tree transformation in tc.fs + Represents the syntax tree for the contents of a parsed implementation file - + - Is this attribute being applied to a property getter or setter? + Represents a parsed hash directive - + - Target specifier, e.g. "assembly", "module", etc. + Represents the definition of a module or namespace in a signature file - + - A pattern arising from a parse error + Gets the syntax range of this constuct - + - Used internally in the type checker + Represents the definition of a module or namespace - + - Deprecated character range: ranges + A namespace is declared 'global' - + - &lt;@ expr @&gt;, used for active pattern arguments + A namespace is explicitly declared - + - ':? type ' + A module is anonymously named, e.g. a script - + - '?id' -- for optional argument names + A module is explicitly named 'module N' - + - 'null' + Indicates if this is a module definition - + - Represents a simple set of variable bindings a, (a, b) or (a: Type, b: Type) at a lambda, - function definition or other binding point, after the elimination of pattern matching - from the construct, e.g. after changing a "function pat1 -> rule1 | ..." to a - "fun v -> match v with ..." + Represents the kind of a module or namespace definition - + - We have decided to use an alternative name in tha pattern and related expression + A namespace fragment within a namespace in a signature file - + - We have not decided to use an alternative name in tha pattern and related expression + A hash directive within a module or namespace in a signature file - + - Id (ident, altNameRefCell, isCompilerGenerated, isThisVar, isOptArg, range) - - Indicates a simple pattern variable. - - altNameRefCell - Normally 'None' except for some compiler-generated variables in desugaring pattern matching. - Pattern processing sets this reference for hidden variable introduced by desugaring pattern matching in arguments. - The info indicates an alternative (compiler generated) identifier to be used because the name of the identifier is already bound. - See Product Studio FSharp 1.0, bug 6389. - - isCompilerGenerated: true if a compiler generated name - isThisVar: true if 'this' variable in member - isOptArg: true if a '?' is in front of the name + An 'open' definition within a module or namespace in a signature file - + - 'use x = fixed expr' + An exception definition within a module or namespace in a signature file - + - Inserted for error recovery when there is "expr." and missing tokens or error recovery after the dot + A set of one or more type definitions within a module or namespace in a signature file - + - Inserted for error recovery + A 'val' definition within a module or namespace in a signature file, corresponding + to a 'let' definition in the implementation - + - Inserted for error recovery + A nested module definition within a module or namespace in a signature file - + - Only used in FSharp.Core + A module abbreviation definition within a module or namespace in a signature file - + - Only used in FSharp.Core + Gets the syntax range of this constuct - + - Only used in FSharp.Core + Represents a definition within a module or namespace in a signature file - + - Only used in FSharp.Core + Represents the right hand side of an exception definition in a signature file - + - F# syntax: do! expr - Computation expressions only + A namespace fragment within a module - + - F# syntax: match! expr with pat1 -> expr | ... | patN -> exprN + A hash directive within a module - + - SynExpr.LetOrUseBang(spBind, isUse, isFromSource, pat, rhsExpr, bodyExpr, mWholeExpr). - - F# syntax: let! pat = expr in expr - F# syntax: use! pat = expr in expr - Computation expressions only + An attribute definition within a module, for assembly and .NET module attributes - + - F# syntax: yield! expr - F# syntax: return! expr - Computation expressions only + An 'open' definition within a module - + - F# syntax: yield expr - F# syntax: return expr - Computation expressions only + An 'exception' definition within a module - + - F# syntax: <implicit> - Computation expressions only, implied by final "do" or "do!" + One or more 'type' definitions within a module - + - F# syntax: ... in ... - Computation expressions only, based on JOIN_IN token from lex filter + A 'do expr' within a module - + - F# syntax: ((typar1 or ... or typarN): (member-dig) expr) + A 'let' definition within a module - + - F# syntax: &expr, &&expr + A nested module definition 'module X = ...' - + - F# syntax: null + A module abbreviation definition 'module X = A.B.C' - + - F# syntax: downcast expr + Gets the syntax range of this constuct - + - F# syntax: upcast expr + Represents a definition within a module - + - F# syntax: expr :?> type + An auto-property definition, F# syntax: 'member val X = expr' - + - F# syntax: expr :> type + A nested type definition, a feature that is not implemented - + - F# syntax: expr :? type + A 'val' definition within a class - + - F# syntax: expr.Items(e1) <- e2, rarely used named-property-setter notation, e.g. (stringExpr).Chars(3) <- 'a' + An 'inherit' definition within a class - + - F# syntax: Type.Items(e1) <- e2, rarely used named-property-setter notation, e.g. Foo.Bar.Chars(3) <- 'a' + An interface implementation definition within a class - + - DotIndexedSet (objectExpr, indexExprs, valueExpr, rangeOfLeftOfSet, rangeOfDot, rangeOfWholeExpr) - - F# syntax: expr.[expr, ..., expr] <- expr + An abstract slot definition within a class or interface - + - F# syntax: expr.[expr, ..., expr] + A 'let' definition within a class - + - F# syntax: expr <- expr + An implicit inherit definition, 'inherit <typ>(args...) as base' - + - F# syntax: expr.ident...ident <- expr + An implicit constructor definition - + - DotGet(expr, rangeOfDot, lid, wholeRange) - - F# syntax: expr.ident.ident + A 'member' definition within a type - + - F# syntax: ident.ident...ident <- expr + An 'open' definition within a type - + - F# syntax: ident.ident...ident - LongIdent(isOptional, longIdent, altNameRefCell, m) - isOptional: true if preceded by a '?' for an optional named parameter - altNameRefCell: Normally 'None' except for some compiler-generated variables in desugaring pattern matching. See SynSimplePat.Id + Gets the syntax range of this constuct - + - F# syntax: ident - Optimized representation, = SynExpr.LongIdent(false, [id], id.idRange) + Represents a definition element within a type definition, e.g. 'member ... ' - + - IfThenElse(exprGuard, exprThen, optionalExprElse, spIfToThen, isFromErrorRecovery, mIfToThen, mIfToEndOfLastBranch) - - F# syntax: if expr then expr - F# syntax: if expr then expr else expr + Gets the syntax range of this constuct - + - Seq(seqPoint, isTrueSeq, e1, e2, m) - isTrueSeq: false indicates "let v = a in b; v" - - F# syntax: expr; expr + Represents a type or exception declaration 'type C = ... ' plus + any additional member definitions for the type - + - F# syntax: lazy expr + An exception definition - + - F# syntax: try expr finally expr + A simple type definition (record, union, abbreviation) - + - F# syntax: try expr with pat -> expr + An object model type definition (class or interface) - + - LetOrUse(isRecursive, isUse, bindings, body, wholeRange) - - F# syntax: let pat = expr in expr - F# syntax: let f pat1 .. patN = expr in expr - F# syntax: let rec f pat1 .. patN = expr in expr - F# syntax: use pat = expr in expr + Gets the syntax range of this constuct - + - TypeApp(expr, mLessThan, types, mCommas, mGreaterThan, mTypeArgs, mWholeExpr) - "mCommas" are the ranges for interstitial commas, these only matter for parsing/design-time tooling, the typechecker may munge/discard them - - F# syntax: expr<type1, ..., typeN> + Represents the right hand side of a type or exception declaration 'type C = ... ' plus + any additional member definitions for the type - + - App(exprAtomicFlag, isInfix, funcExpr, argExpr, m) - - exprAtomicFlag: indicates if the application is syntactically atomic, e.g. f.[1] is atomic, but 'f x' is not - - isInfix is true for the first app of an infix operator, e.g. 1+2 becomes App(App(+, 1), 2), where the inner node is marked isInfix - (or more generally, for higher operator fixities, if App(x, y) is such that y comes before x in the source code, then the node is marked isInfix=true) - - F# syntax: f x + Gets the syntax range of this constuct - + - F# syntax: assert expr + Represents the right hand side of an exception declaration 'exception E = ... ' plus + any member definitions for the exception - + - F# syntax: do expr + Gets the syntax range of this constuct - + - F# syntax: match expr with pat1 -> expr | ... | patN -> exprN + Represents the right hand side of an exception declaration 'exception E = ... ' - + - F# syntax: function pat1 -> expr | ... | patN -> exprN + Represents the syntactic elements associated with the "return" of a function or method. - + - First bool indicates if lambda originates from a method. Patterns here are always "simple" - Second bool indicates if this is a "later" part of an iterated sequence of lambdas - - F# syntax: fun pat -> expr + Represents the names and other metadata for the type parameters for a member or function - + - CompExpr(isArrayOrList, isNotNakedRefCell, expr) - - F# syntax: { expr } + Represents the argument names and other metadata for a parameter for a member or function - + - F# syntax: [ expr ], [| expr |] + SynValInfo(curriedArgInfos, returnInfo) - + - SynExpr.ForEach (spBind, seqExprOnly, isFromSource, pat, enumExpr, bodyExpr, mWholeExpr). - - F# syntax: 'for ... in ... do ...' + The argument names and other metadata for a member or function - + - F# syntax: 'for i = ... to ... do ...' + Represents the syntax tree for a 'val' definition in an abstract slot or a signature file - + - F# syntax: 'while ... do ...' + Gets the syntax range of this constuct - + - SynExpr.ObjExpr(objTy, argOpt, binds, extraImpls, mNewExpr, mWholeExpr) + Represents the syntax tree associated with the name of a type definition or module + in signature or implementation. - F# syntax: { new ... with ... } + This includes the name, attributes, type parameters, constraints, documentation and accessibility + for a type definition or module. For modules, entries such as the type parameters are + always empty. - + - F# syntax: new C(...) - The flag is true if known to be 'family' ('protected') scope + Represents the syntax tree for a field declaration in a record or class - + - F# syntax: { f1=e1; ...; fn=en } - SynExpr.Record((baseType, baseCtorArgs, mBaseCtor, sepAfterBase, mInherits), (copyExpr, sepAfterCopyExpr), (recordFieldName, fieldValue, sepAfterField), mWholeExpr) - inherit includes location of separator (for tooling) - copyOpt contains range of the following WITH part (for tooling) - every field includes range of separator after the field (for tooling) + The information for a type definition in a signature - + - F# syntax: [ e1; ...; en ], [| e1; ...; en |] + Represents the syntax tree for a type definition in a signature - + - F# syntax: {| id1=e1; ...; idN=eN |} - F# syntax: struct {| id1=e1; ...; idN=eN |} + Indicates the right right-hand-side is a record, union or other simple type. - + - F# syntax: e1, ..., eN + Indicates the right right-hand-side is a class, struct, interface or other object-model type - + - F# syntax: expr: type + Gets the syntax range of this constuct - + - F# syntax: 1, 1.3, () etc. + Represents the syntax tree for the right-hand-side of a type definition in a signature. + Note: in practice, using a discriminated union to make a distinction between + "simple" types and "object oriented" types is not particularly useful. - + - F# syntax: <@ expr @>, <@@ expr @@> - - Quote(operator, isRaw, quotedSynExpr, isFromQueryExpression, m) + Full type spec given by 'UnionCase: ty1 * tyN -> rty'. Only used in FSharp.Core, otherwise a warning. - + - F# syntax: (expr) - - Paren(expr, leftParenRange, rightParenRange, wholeRangeIncludingParentheses) - - Parenthesized expressions. Kept in AST to distinguish A.M((x, y)) - from A.M(x, y), among other things. + Normal style declaration - + - range ignoring any (parse error) extra trailing dots + Represents the syntax tree for the right-hand-side of union definition, excluding members, + in either a signature or implementation. - + - Attempt to get the range of the first token or initial portion only - this is extremely ad-hoc, just a cheap way to improve a certain 'query custom operation' error range + Gets the syntax range of this constuct - + - Get the syntactic range of source code covered by this construct. + Represents the syntax tree for one case in a union definition. - + - F# syntax: ident=1 etc., used in static parameters to type providers + Gets the syntax range of this constuct - + - F# syntax: const expr, used in static parameters to type providers + Represents the syntax tree for one case in an enum definition. - + - F# syntax: 1, "abc" etc, used in parameters to type providers - For the dimensionless units i.e. 1, and static parameters to provided types + An exception definition, "exception E = ..." - + - F# syntax: for units of measure e.g. m^3, kg^1/2 + An abstract definition, "type X" - + - F# syntax: for units of measure e.g. m / s + A type abbreviation, "type X = A.B.C" - + - F# syntax: #type + A type defined by using an IL assembly representation. Only used in FSharp.Core. + + F# syntax: "type X = (# "..."#) - + - F# syntax: typ with constraints + An object oriented type definition. This is not a parse-tree form, but represents the core + type representation which the type checker splits out from the "ObjectModel" cases of type definitions. - + - F# syntax: _ + A record type definition, type X = { A: int; B: int } - + - F# syntax: 'Var + An enum type definition, type X = A = 1 | B = 2 - + - F# syntax: type -> type + A union type definition, type X = A | B - + - F# syntax: type[] + Gets the syntax range of this constuct - + - F# syntax: {| id: type; ...; id: type |} - F# syntax: struct {| id: type; ...; id: type |} + Represents the syntax tree for the core of a simple type definition, in either signature + or implementation. - + - F# syntax: type * ... * type - F# syntax: struct (type * ... * type) + Represents the kind of a type definition whether explicit or inferred - + - LongIdentApp(typeName, longId, LESSm, tyArgs, commasm, GREATERm, wholem) - - F# syntax: type.A.B.C<type, ..., type> - commasm: ranges for interstitial commas, these only matter for parsing/design-time tooling, the typechecker may munge/discard them + A nested type definition in a signature file (an unimplemented feature) - + - App(typeName, LESSm, typeArgs, commasm, GREATERm, isPostfix, m) - - F# syntax: type<type, ..., type> or type type or (type, ..., type) type - isPostfix: indicates a postfix type application e.g. "int list" or "(int, string) dict" - commasm: ranges for interstitial commas, these only matter for parsing/design-time tooling, the typechecker may munge/discard them + A 'val' definition in a type in a signature file - + - F# syntax: A.B.C + An 'inherit' definition in a type in a signature file - + - Get the syntactic range of source code covered by this construct. + An interface definition in a type in a signature file - + - The unchecked abstract syntax tree of F# types + A member definition in a type in a signature file - + - F# syntax is 'typar: delegate<'Args, unit> + Represents the syntax tree for a member signature (used in signature files, abstract member declarations + and member constraints) - + - F# syntax is 'typar: enum<'UnderlyingType> + An artificial member kind used prior to the point where a + get/set property is split into two distinct members. - + - F# syntax is ^T: (static member MemberName: ^T * int -> ^T) + The member kind is property setter - + - F# syntax is 'typar :> type + The member kind is property getter - + - F# syntax is default ^T: type + The member kind is not yet determined - + - F# syntax is 'typar: equality + The member is a object model constructor - + - F# syntax is 'typar: comparison + The member is a class initializer - + - F# syntax is 'typar: null + Note the member kind is actually computed partially by a syntax tree transformation in tc.fs - + - F# syntax is 'typar: unmanaged + The kind of the member - + - F# syntax: is 'typar: not struct + The member is 'final' - + - F# syntax: is 'typar: struct + The member is an 'override' or explicit interface implementation - + - The unchecked abstract syntax tree of F# type constraints + The member is a dispatch slot - + - Represents the explicit declaration of a type parameter + The member is an instance member (non-static) - + - A 'do' binding in a module. Must have type 'unit' + Represents the flags for a 'member' declaration - + - A normal 'let' binding in a module + Represents the return information in a binding for a 'let' or 'member' declaration - + - A standalone expression in a module + Represents a binding for a 'let' or 'member' declaration - + - The kind associated with a binding - "let", "do" or a standalone expression + Represents extra information about the declaration of a value - + - Says that the expression is an atomic expression, i.e. is of a form that has no whitespace unless - enclosed in parentheses, e.g. 1, "3", ident, ident.[expr] and (expr). If an atomic expression has - type T, then the largest expression ending at the same range as the atomic expression also has type T. + The syntax range of the list of attributes - + - stores pair: record field name + (true if given record field name is syntactically correct and can be used in name resolution) + The list of attributes - + - denotes location of the separator block + optional position of the semicolon (used for tooling support) + List of attributes enclosed in [< ... >]. - + - Indicates if a for loop is 'for x in e1 -> e2', only valid in sequence expressions + The syntax range of the attribute - + - Indicates if a for loop is 'for x in e1 -> e2', only valid in sequence expressions + Is this attribute being applied to a property getter or setter? - + - The unchecked abstract syntax tree of F# unit of measure exponents. + Target specifier, e.g. "assembly", "module", etc. - + - The unchecked abstract syntax tree of F# unit of measure annotations. - This should probably be merged with the representation of SynType. + The argument of the attribute, perhaps a tuple - + - Old comment: "we never iterate, so the const here is not another SynConst.Measure" + The name of the type for the attribute - + - Used internally in the typechecker once an array of unit16 constants - is detected, to allow more efficient processing of large arrays of uint16 constants. + Represents an attribute - + - F# syntax: verbatim or regular byte string, e.g. "abc"B. - - Also used internally in the typechecker once an array of unit16 constants - is detected, to allow more efficient processing of large arrays of uint16 constants. + Gets the syntax range of part of this constuct - + - F# syntax: verbatim or regular string, e.g. "abc" + Gets the syntax range of this constuct - + - UserNum(value, suffix) - - F# syntax: 1Q, 1Z, 1R, 1N, 1G + Represents a clause in a 'match' expression - + - F# syntax: 23.4M + Represents a set of bindings that implement an interface - + - F# syntax: 'a' + A pattern arising from a parse error - + - F# syntax: 1.30, 1.40e10 etc. + Used internally in the type checker - + - F# syntax: 1.30f, 1.40e10f etc. + Deprecated character range: ranges - + - F# syntax: 13un + &lt;@ expr @&gt;, used for active pattern arguments - + - F# syntax: 13n + A type test pattern ':? type ' - + - F# syntax: 13UL + '?id' -- for optional argument names - + - F# syntax: 13L + The 'null' pattern - + - F# syntax: 13u, 0x4000u, 0o0777u + A record pattern - + - F# syntax: 13, 0x4000, 0o0777 + An array or a list as a pattern - + - F# syntax: 13us, 0x4000us, 0o0777us, 0b0111101us + A parentehsized pattern - + - F# syntax: 13s, 0x4000s, 0o0777s, 0b0111101s + A tuple pattern - + - F# syntax: 13uy, 0x40uy, 0oFFuy, 0b0111101uy + A long identifier pattern possibly with argument patterns - + - F# syntax: 13y, 0xFFy, 0o077y, 0b0111101y + A conjunctive pattern 'pat1 & pat2' - + - F# syntax: true, false + A disjunctive pattern 'pat1 | pat2' - + - F# syntax: () + An attributed pattern, used in argument or declaration position - + - The unchecked abstract syntax tree of constants in F# types and expressions. + A typed pattern 'pat : type' - + - LongIdentWithDots(lid, dotms) - Typically dotms.Length = lid.Length-1, but they may be same if (incomplete) code ends in a dot, e.g. "Foo.Bar." - The dots mostly matter for parsing, and are typically ignored by the typechecker, but - if dotms.Length = lid.Length, then the parser must have reported an error, so the typechecker is allowed - more freedom about typechecking these expressions. - LongIdent can be empty list - it is used to denote that name of some AST element is absent (i.e. empty type name in inherit) + A named pattern 'pat as ident' - + - This code runs for .XML generation and thus influences cross-project xmldoc tooltips; for within-project tooltips, - see XmlDocumentation.fs in the language service + A wildcard '_' in a pattern - + - Used to collect XML documentation during lexing and parsing. + A constant in a pattern - + - Reset the generator used for compiler-generated argument names. + Gets the syntax range of this constuct - + - Get the generator used for compiler-generated argument names. + Represents a syntax tree for an F# pattern - + - Get the range corresponding to one of the r.h.s. symbols of a grammar rule while it is being reduced + Represents a syntax tree for argumments patterns - + - Get the range covering two of the r.h.s. symbols of a grammar rule while it is being reduced + Represents a simple set of variable bindings a, (a, b) or (a: Type, b: Type) at a lambda, + function definition or other binding point, after the elimination of pattern matching + from the construct, e.g. after changing a "function pat1 -> rule1 | ..." to a + "fun v -> match v with ..." - + - Get the range corresponding to the result of a grammar rule while it is being reduced + A static optimization conditional that activates for a struct - + - Get an F# compiler range from a lexer range + A static optimization conditional that activates for a particular type instantiation - + - Get an F# compiler position from a lexer position + Represents a syntax tree for a static optimization constraint in the F# core library - + - Helper for parsing the inline IL fragments. + We have decided to use an alternative name in the pattern and related expression - + - Helper for parsing the inline IL fragments. + We have not decided to use an alternative name in the pattern and related expression - + - "fun (UnionCase x) (UnionCase y) -> body" - ==> - "fun tmp1 tmp2 -> - let (UnionCase x) = tmp1 in - let (UnionCase y) = tmp2 in - body" + Represents the alternative identifier for a simple pattern - + - Push non-simple parts of a patten match over onto the r.h.s. of a lambda. - Return a simple pattern and a function to build a match on the r.h.s. if the pattern is complex + An attributed simple pattern - + - Recognize the '()' in 'new()' + A type annotated simple pattern - + - Extract the argument for patterns corresponding to the declaration of 'new ... = ...' + Indicates a simple pattern variable. + + altNameRefCell: + Normally 'None' except for some compiler-generated variables in desugaring pattern matching. + Pattern processing sets this reference for hidden variable introduced + by desugaring pattern matching in arguments. The info indicates an + alternative (compiler generated) identifier to be used because the + name of the identifier is already bound. + + isCompilerGenerated: true if a compiler generated name + isThisVar: true if 'this' variable in member + isOptArg: true if a '?' is in front of the name - + - This affects placement of sequence points + Represents a syntax tree for simple F# patterns - + - Match a long identifier, including the case for single identifiers which gets a more optimized node in the syntax tree. + A one-element item indexer argument - + - The prefix of the names used for the fake namespace path added to all dynamic code entries in FSI.EXE + A two-element range indexer argument - + - The error raised by the parse_error_rich function, which is called by the parser engine - when a syntax error occurs. The first object is the ParseErrorContext which contains a dump of - information about the grammar at the point where the error occurred, e.g. what tokens - are valid to shift next at that point in the grammar. This information is processed in CompileOps.fs. + Gets the syntax range of this constuct - + - Called from the parser each time we parse a construct that marks the end of an XML doc comment range, - e.g. a 'type' declaration. The markerRange is the range of the keyword that delimits the construct. + Get the one or two expressions as a list - + - Called from the lexer to save a single line of XML doc comment. + Represents a syntax tree for an F# indexer expression argument - + - XmlDoc F# lexer/parser state, held in the BufferLocalStore for the lexer. - This is the only use of the lexer BufferLocalStore in the codebase. + 'use x = fixed expr' - + - Infer the syntactic information for a 'let' or 'member' definition, based on the argument pattern, - any declared return information (e.g. .NET attributes on the return element), and the r.h.s. expression - in the case of 'let' definitions. + Inserted for error recovery when there is "expr." and missing tokens or error recovery after the dot - + - For 'let' definitions, we infer syntactic argument information from the r.h.s. of a definition, if it - is an immediate 'fun ... -> ...' or 'function ...' expression. This is noted in the F# language specification. - This does not apply to member definitions. + Inserted for error recovery - + - Transform a property declared using '[static] member P = expr' to a method taking a "unit" argument. - This is similar to IncorporateEmptyTupledArgForPropertyGetter, but applies to member definitions - rather than member signatures. + Inserted for error recovery - + - Make sure only a solitary unit argument has unit elimination + Only used in FSharp.Core - + - Infer the syntactic argument info for one or more arguments a pattern. + Only used in FSharp.Core - + - Infer the syntactic argument info for one or more arguments one or more simple patterns. + Only used in FSharp.Core - + - Infer the syntactic argument info for a single argument from a simple pattern. + Only used in FSharp.Core - + - Get the argument attributes from the syntactic information for an argument. + F# syntax: do! expr + Computation expressions only - + - Get the argument counts for each curried argument group. Used in some adhoc places in tc.fs. + F# syntax: match! expr with pat1 -> expr | ... | patN -> exprN - + - Add a parameter entry to the syntactic value information to represent the value argument for a property setter. This is - used for the implicit value argument in property setter signature specifications. + F# syntax: let! pat = expr in expr + F# syntax: use! pat = expr in expr + F# syntax: let! pat = expr and! ... and! ... and! pat = expr in expr + Computation expressions only - + - Add a parameter entry to the syntactic value information to represent the 'this' argument. This is - used for the implicit 'this' argument in member signature specifications. + F# syntax: yield! expr + F# syntax: return! expr + Computation expressions only - + - Add a parameter entry to the syntactic value information to represent the '()' argument to a property getter. This is - used for the implicit '()' argument in property getter signature specifications. + F# syntax: yield expr + F# syntax: return expr + Computation expressions only - + - Check if there are any optional arguments in the syntactic argument information. Used when adjusting the - types of optional arguments for function and member signatures. + Used internally during type checking for translating computation expressions. - + - Check if one particular argument is an optional argument. Used when adjusting the - types of optional arguments for function and member signatures. + Used in parser error recovery and internally during type checking for translating computation expressions. - + - Determine if a syntactic information represents a member without arguments (which is implicitly a property getter) + F# syntax: ... in ... + Computation expressions only, based on JOIN_IN token from lex filter - + - The 'argument' information for the 'this'/'self' parameter in the cases where it is not given explicitly + F# syntax: ((typar1 or ... or typarN): (member-dig) expr) - + - The 'argument' information for a return value where no attributes are given for the return value (the normal case) + F# syntax: &expr, &&expr - + - The argument information for a '()' argument + F# syntax: null - + - The argument information for a curried argument without a name + F# syntax: downcast expr - + - The argument information for an argument without a name + F# syntax: upcast expr - + - Operations related to the syntactic analysis of arguments of value, function and member definitions and signatures. - - Function and member definitions have strongly syntactically constrained arities. We infer - the arity from the syntax. - - For example, we record the arity for: - StaticProperty --> [1] -- for unit arg - this.InstanceProperty --> [1;1] -- for unit arg - StaticMethod(args) --> map InferSynArgInfoFromSimplePat args - this.InstanceMethod() --> 1 :: map InferSynArgInfoFromSimplePat args - this.InstanceProperty with get(argpat) --> 1 :: [InferSynArgInfoFromSimplePat argpat] - StaticProperty with get(argpat) --> [InferSynArgInfoFromSimplePat argpat] - this.InstanceProperty with get() --> 1 :: [InferSynArgInfoFromSimplePat argpat] - StaticProperty with get() --> [InferSynArgInfoFromSimplePat argpat] - - this.InstanceProperty with set(argpat)(v) --> 1 :: [InferSynArgInfoFromSimplePat argpat; 1] - StaticProperty with set(argpat)(v) --> [InferSynArgInfoFromSimplePat argpat; 1] - this.InstanceProperty with set(v) --> 1 :: [1] - StaticProperty with set(v) --> [1] + F# syntax: expr :?> type - + - This function maps production indexes returned in syntax errors to strings representing the non terminal that would be produced by that production + F# syntax: expr :> type - + - This function maps production indexes returned in syntax errors to strings representing the non terminal that would be produced by that production + F# syntax: expr :? type - + - Keywords paired with their descriptions. Used in completion and quick info. + F# syntax: expr.Items (e1) <- e2, rarely used named-property-setter notation, e.g. (stringExpr).Chars(3) <- 'a' - + - Returns starting position of the token + F# syntax: Type.Items(e1) <- e2, rarely used named-property-setter notation, e.g. Foo.Bar.Chars(3) <- 'a' - + - Returns end position of the token + F# syntax: expr.[expr, ..., expr] <- expr - + - Returns a token 'tok' with the same position as this token, except that - it is shifted by specified number of characters from the left and from the right - Note: positive value means shift to the right in both cases + F# syntax: expr.[expr, ..., expr] - + - Returns a token 'tok' with the same position as this token + F# syntax: expr <- expr - + - Used to save the state related to a token + F# syntax: expr.ident...ident <- expr - + - Used to save some aspects of the lexbuffer state + F# syntax: expr.ident.ident - + - Determine the token that may align with the 'try' of a 'try/catch' or 'try/finally' without closing - the construct + F# syntax: ident.ident...ident <- expr - + - Determine the tokens that may align with the 'if' of an 'if/then/elif/else' without closing - the construct + F# syntax: ident.ident...ident + + isOptional: true if preceded by a '?' for an optional named parameter + altNameRefCell: Normally 'None' except for some compiler-generated + variables in desugaring pattern matching. See SynSimplePat.Id - + - Used for warning strings, which should display columns as 1-based and display - the lines after taking '# line' directives into account (i.e. do not use - p.OriginalLine) + F# syntax: ident + Optimized representation for SynExpr.LongIdent (false, [id], id.idRange) - + - LexFilter - process the token stream prior to parsing. - Implements the offside rule and a copule of other lexical transformations. + F# syntax: if expr then expr + F# syntax: if expr then expr else expr - + - Compute the hash value for the tainted value + F# syntax: expr; expr + + isTrueSeq: false indicates "let v = a in b; v" - + - Test whether the tainted value equals given value. Type providers are ignored (equal tainted values produced by different type providers are equal) - Failure in call to equality operation will be blamed on type provider of first operand + F# syntax: lazy expr - + - Test whether the tainted value equals given value. - Failure in call to equality operation will be blamed on type provider of first operand + F# syntax: try expr finally expr - + - Test whether the tainted value is null + F# syntax: try expr with pat -> expr - + - The table of remappings from type names in the provided assembly to type - names in the statically linked, embedded assembly. + F# syntax: let pat = expr in expr + F# syntax: let f pat1 .. patN = expr in expr + F# syntax: let rec f pat1 .. patN = expr in expr + F# syntax: use pat = expr in expr - + - Create a new static linking map, ready to populate with data. + F# syntax: expr<type1, ..., typeN> - + - The table of information recording remappings from type names in the provided assembly to type - names in the statically linked, embedded assembly, plus what types are nested in side what types. + F# syntax: f x + + flag: indicates if the application is syntactically atomic, e.g. f.[1] is atomic, but 'f x' is not + isInfix is true for the first app of an infix operator, e.g. 1+2 + becomes App(App(+, 1), 2), where the inner node is marked isInfix - + - Represents the remapping information for a generated provided type and its nested types. - - There is one overall tree for each root 'type X = ... type generation expr...' specification. + F# syntax: assert expr - + - Convert the expression to a string for diagnostics + F# syntax: do expr - + - Map the TyconRef objects, if any + F# syntax: match expr with pat1 -> expr | ... | patN -> exprN - + - The context used to interpret information in the closure of System.Type, System.MethodInfo and other - info objects coming from the type provider. - - At the moment this is the "Type --> ILTypeRef" and "Type --> Tycon" remapping - context for generated types (it is empty for erased types). This is computed from - while processing the [<Generate>] declaration related to the type. - - Immutable (after type generation for a [<Generate>] declaration populates the dictionaries). - - The 'obj' values are all TyconRef, but obj is used due to a forward reference being required. Not particularly - pleasant, but better than intertwining the whole "ProvidedType" with the TAST structure. + F# syntax: function pat1 -> expr | ... | patN -> exprN - + - The folder for temporary files + First bool indicates if lambda originates from a method. Patterns here are always "simple" + Second bool indicates if this is a "later" part of an iterated sequence of lambdas + + F# syntax: fun pat -> expr - + - All referenced assemblies, including the type provider itself, and possibly other type providers. + F# syntax: { expr } - + - Whether or not the --showextensionresolution flag was supplied to the compiler. + F# syntax: [ expr ], [| expr |] - + - Output file name + F# syntax: 'for ... in ... do ...' - + - The folder from which an extension provider is resolving from. This is typically the project folder. + F# syntax: 'for i = ... to ... do ...' - + - Carries information about the type provider resolution environment. + F# syntax: 'while ... do ...' - + - Check if this is a direct reference to a non-embedded generated type. This is not permitted at any name resolution. - We check by seeing if the type is absent from the remapping context. + F# syntax: { new ... with ... } - + - Get the ILTypeRef for the provided type (including for nested types). Do not take into account - any type relocations or static linking for generated types. + F# syntax: new C(...) + The flag is true if known to be 'family' ('protected') scope - + - Get the ILTypeRef for the provided type (including for nested types). Take into account - any type relocations or static linking for generated types. + F# syntax: { f1=e1; ...; fn=en } + inherit includes location of separator (for tooling) + copyOpt contains range of the following WITH part (for tooling) + every field includes range of separator after the field (for tooling) - + - Decompose the enclosing name of a type (including any class nestings) into a list of parts. - e.g. System.Object -> ["System"; "Object"] + F# syntax: [ e1; ...; en ], [| e1; ...; en |] - + - Get the parts of a .NET namespace. Special rules: null means global, empty is not allowed. + F# syntax: {| id1=e1; ...; idN=eN |} + F# syntax: struct {| id1=e1; ...; idN=eN |} - + - Try to resolve a type in the given extension type resolver + F# syntax: e1, ..., eN - + - Try to resolve a type in the given extension type resolver + F# syntax: expr: type - + - Try to apply a provided method to the given static arguments. + F# syntax: 1, 1.3, () etc. - + - Try to apply a provided type to the given static arguments. If successful also return a function - to check the type name is as expected (this function is called by the caller of TryApplyProvidedType - after other checks are made). + F# syntax: <@ expr @>, <@@ expr @@> + + Quote(operator, isRaw, quotedSynExpr, isFromQueryExpression, m) - + - Validate that the given provided type meets some of the rules for F# provided types + F# syntax: (expr) + + Parenthesized expressions. Kept in AST to distinguish A.M((x, y)) + from A.M(x, y), among other things. - + - Get the provided expression for a particular use of a method. + Get the Range ignoring any (parse error) extra trailing dots - + - Detect a provided 'Var' expression + Attempt to get the range of the first token or initial portion only - this + is ad-hoc, just a cheap way to improve a certain 'query custom operation' error range - + - Detect a provided 'IfThenElse' expression + Gets the syntax range of this constuct - + - Detect a provided 'set variable' expression + Indicates if this expression arises from error recovery - + - Detect a provided 'let' expression + Represents a syntax tree for F# expressions - + - Detect a provided type-test expression + F# syntax: ident=1 etc., used in static parameters to type providers - + - Detect a provided type-as expression + F# syntax: const expr, used in static parameters to type providers - + - Detect a provided tuple-get expression + F# syntax: 1, "abc" etc, used in parameters to type providers + For the dimensionless units i.e. 1, and static parameters to provided types - + - Detect a provided new-tuple expression + F# syntax: for units of measure e.g. m^3, kg^1/2 - + - Detect a provided default-value expression + F# syntax: for units of measure e.g. m / s - + - Detect a provided constant expression + F# syntax: #type - + - Detect a provided call expression + F# syntax: typ with constraints - + - Detect a provided lambda expression + F# syntax: _ - + - Detect a provided try/finally expression + F# syntax: 'Var - + - Detect a provided try/with expression + F# syntax: type -> type - + - Detect a provided sequential expression + F# syntax: type[] - + - Detect a provided expression which is a for-loop over integers + F# syntax: {| id: type; ...; id: type |} + F# syntax: struct {| id: type; ...; id: type |} - + - Detect a provided new-delegate expression + F# syntax: type * ... * type + F# syntax: struct (type * ... * type) - + - Detect a provided while-loop expression + F# syntax: type.A.B.C<type, ..., type> - + - Detect a provided new-object expression + F# syntax: type<type, ..., type> or type type or (type, ..., type) type + isPostfix: indicates a postfix type application e.g. "int list" or "(int, string) dict" - + - Detect a provided new-array expression + F# syntax: A.B.C - + - Given an extension type resolver, supply a human-readable name suitable for error messages. + Gets the syntax range of this constuct - + - Find and instantiate the set of ITypeProvider components for the given assembly reference + Represents a syntax tree for F# types - + - Get the list of relative paths searched for type provider design-time components + F# syntax is 'typar: delegate<'Args, unit> - + - Raised when an type provider has thrown an exception. + F# syntax is 'typar: enum<'UnderlyingType> - + - Raised when a type provider has thrown an exception. + F# syntax is ^T: (static member MemberName: ^T * int -> ^T) - + - Indicates an F# 3.0+ reference to a named type in an assembly loaded by name + F# syntax is 'typar :> type - + - Indicates an F# 4.0+ reference into the supplied table of type definition references, ultimately resolved by TypeRef/TypeDef data + F# syntax is default ^T: type - + - Code to pickle out quotations in the quotation binary format. + F# syntax is 'typar: equality - + - An AbstractIL type representation that may include type variables + F# syntax is 'typar: comparison - + - An AbstractIL type representation that is just the name of a type. - - CompiledTypeRepr.ILAsmNamed (ilTypeRef, ilBoxity, ilTypeOpt) - - The ilTypeOpt is present for non-generic types. It is an ILType corresponding to the first two elements of the case. This - prevents reallocation of the ILType each time we need to generate it. For generic types, it is None. + F# syntax is 'typar: null - + - Specifies the compiled representations of type and exception definitions. Basically - just an ILTypeRef. Computed and cached by later phases. Stored in - type and exception definitions. Not pickled. Store an optional ILType object for - non-generic types. + F# syntax is 'typar: unmanaged - + - See FreeTyvars above. + F# syntax: is 'typar: not struct - + - The summary of union constructors used in the expression. These may be - marked 'internal' or 'private' and we have to check various conditions associated with that. + F# syntax: is 'typar: struct - + - The summary of fields used in the expression. These may be made private by a signature - or marked 'internal' or 'private' and we have to check various conditions associated with that. + The unchecked abstract syntax tree of F# type constraints - + - The summary of locally defined tycon representations used in the expression. These may be made private by a signature - or marked 'internal' or 'private' and we have to check various conditions associated with that. + Represents the explicit declaration of a type parameter - + - Indicates if the expression contains a call to rethrow that is not bound under a (try-)with branch. - Rethrow may only occur in such locations. + A 'do' binding in a module. Must have type 'unit' - + - Indicates if the expression contains a call to a protected member or a base call. - Calls to protected members and direct calls to super classes can't escape, also code can't be inlined + A normal 'let' binding in a module - + - The summary of locally defined variables used in the expression. These may be hidden at let bindings etc. - or made private by a signature or marked 'internal' or 'private', and we have to check various conditions associated with that. + A standalone expression in a module - + - Represents the set of free variables in an expression + The kind associated with a binding - "let", "do" or a standalone expression - + - Represents an amortized computation of the free variables in an expression + Indicates if an expression is an atomic expression. + + An atomic expression has no whitespace unlessenclosed in parentheses, e.g. + 1, "3", ident, ident.[expr] and (expr). If an atomic expression has type T, + then the largest expression ending at the same range as the atomic expression + also has type T. - + - The summary of type parameters used in the expression. These may not escape the enclosing generic construct - and we have to check various conditions associated with that. + Represents a record field name plus a flag indicating if given record field name is syntactically + correct and can be used in name resolution. - + - The summary of values used as trait solutions + Represents the location of the separator block + optional position + of the semicolon (used for tooling support) - + - The summary of locally defined type definitions used in the expression. These may be made private by a signature - and we have to check various conditions associated with that. + Indicates if a for loop is 'for x in e1 -> e2', only valid in sequence expressions - + - Represents a set of 'free' type-related elements, including named types, trait solutions, union cases and - record fields. + Indicates if a for loop is 'for x in e1 -> e2', only valid in sequence expressions - + - Represents a set of 'free' union cases. Used to collect the union cases referred to from an expression. + Represents whether a debug point should be present for a 'let' binding, + that is whether the construct corresponds to a debug point in the original source. - + - Represents a set of 'free' record field definitions. Used to collect the record field definitions referred to - from an expression. + Represents whether a debug point should be present for the 'while' in a 'while...' loop, + that is whether the construct corresponds to a debug point in the original source. - + - Represents a set of 'free' named type definitions. Used to collect the named type definitions referred to - from a type or expression. + Represents whether a debug point should be present for the 'for' in a 'for...' loop, + that is whether the construct corresponds to a debug point in the original source. - + - Represents a set of free type parameters + Represents whether a debug point should be present for the 'finally' in a 'try .. finally', + that is whether the construct corresponds to a debug point in the original source. - + - Represents a set of free local values. + Represents whether a debug point should be present for the 'with' in a 'try .. with', + that is whether the construct corresponds to a debug point in the original source. - + - Represents a complete typechecked assembly, made up of multiple implementation files. - + Represents whether a debug point should be present for a 'try', that is whether + the construct corresponds to a debug point in the original source. - + - Represents a complete typechecked implementation file, including its typechecked signature if any. - - TImplFile(qualifiedNameOfFile, pragmas, implementationExpressionWithSignature, hasExplicitEntryPoint, isScript) + Represents whether a debug point should be present for either the + first or second part of a sequential execution, that is whether the + construct corresponds to a debug point in the original source. - + - This is the body of the module/namespace + Represents whether a debug point should be present for the target + of a decision tree, that is whether the construct corresponds to a debug + point in the original source. - + - A named module-or-namespace-fragment definition + A construct marked or assumed 'private' - + - Indicates the module fragment is a 'rec' or 'non-rec' definition of types and modules + A construct marked or assumed 'internal' - + - Indicates the module fragment is an evaluation of expression for side-effects + A construct marked or assumed 'public' - + - Indicates the module fragment is a 'let' definition + Represents an accessibility modifier in F# syntax - + - Indicates the module fragment is made of several module fragments in succession + Represents an unchecked syntax tree of F# unit of measure exponents. - + - Indicates the module is a module with a signature + A variable unit of measure - + - The contents of a module-or-namespace-fragment definition + An anonymous (inferred) unit of measure - + - A type for a module-or-namespace-fragment and the actual definition of the module-or-namespace-fragment - The first ModuleOrNamespaceType is the signature and is a binder. However the bindings are not used in the ModuleOrNamespaceExpr: it is only referenced from the 'outside' - is for use by FCS only to report the "hidden" contents of the assembly prior to applying the signature. + The '1' unit of measure - + - Represents a parameter to an abstract method slot. - - TSlotParam(nm, ty, inFlag, outFlag, optionalFlag, attribs) + A power of a unit of measure, e.g. 'kg ^ 2' - + - Represents an abstract method slot, or delegate signature. - - TSlotSig(methodName, declaringType, declaringTypeParameters, methodTypeParameters, slotParameters, returnTy) + A division of two units of measure, e.g. 'kg / m' - + - A representation of a method in an object expression. - - TObjExprMethod(slotsig, attribs, methTyparsOfOverridingMethod, methodParams, methodBodyExpr, m) + A sequence of several units of measure, e.g. 'kg m m' - + - Indicates the kind of an F# core library static optimization construct + A product of two units of measure, e.g. 'kg * m' - + - A call to a base method, e.g. 'base.OnPaint(args)' + A named unit of measure - + - A call to a constructor, e.g. 'new C() = new C(3)' + Represents an unchecked syntax tree of F# unit of measure annotations. - + - A call to a constructor, e.g. 'inherit C()' + Old comment: "we never iterate, so the const here is not another SynConst.Measure" - + - A normal use of a value + Used internally in the typechecker once an array of unit16 constants + is detected, to allow more efficient processing of large arrays of uint16 constants. - + - Indicates a use of a value represents a call to a method that may require - a .NET 2.0 constrained call. A constrained call is only used for calls where + F# syntax: verbatim or regular byte string, e.g. "abc"B. + + Also used internally in the typechecker once an array of unit16 constants + is detected, to allow more efficient processing of large arrays of uint16 constants. - + - Indicates how a value, function or member is being used at a particular usage point. + F# syntax: verbatim or regular string, e.g. "abc" - + - let res = a in b;res + UserNum(value, suffix) + + F# syntax: 1Q, 1Z, 1R, 1N, 1G - + - a ; b + F# syntax: 23.4M - + - Indicates the kind of sequential operation, i.e. "normal" or "to a before returning b" + F# syntax: 'a' - + - In C syntax this is: *localv_ptr = e + F# syntax: 1.30, 1.40e10 etc. - + - In C syntax this is: localv = e, note == *(&localv) = e == LAddrOf; LByrefSet + F# syntax: 1.30f, 1.40e10f etc. - + - In C syntax this is: *localv_ptr + F# syntax: 13un - + - In C syntax this is: &localv + F# syntax: 13n - + - Indicates what kind of pointer operation this is. + F# syntax: 13UL - + - Evaluate start once and end multiple times, loop up + F# syntax: 13L - + - Evaluate start and end once, loop down + F# syntax: 13u, 0x4000u, 0o0777u - + - Evaluate start and end once, loop up + F# syntax: 13, 0x4000, 0o0777 - + - Indicates the kind of looping operation. + F# syntax: 13us, 0x4000us, 0o0777us, 0b0111101us - + - Marks the compiled form of a 'for ... in ... do ' expression + F# syntax: 13s, 0x4000s, 0o0777s, 0b0111101s - + - Indicates the kind of looping operation. + F# syntax: 13uy, 0x40uy, 0oFFuy, 0b0111101uy - + - If this is Some(ty) then it indicates that a .NET 2.0 constrained call is required, with the given type as the - static type of the object argument. + F# syntax: 13y, 0xFFy, 0o077y, 0b0111101y - + - Normal record construction + F# syntax: true, false - + - We're in an explicit constructor. The purpose of the record expression is to - fill in the fields of a pre-created but uninitialized object + F# syntax: () - + - Indicates the kind of record construction operation. + Gets the syntax range of this constuct - + - ILCall(useCallvirt, isProtected, valu, newobj, valUseFlags, isProp, noTailCall, mref, actualTypeInst, actualMethInst, retTy) - - IL method calls. - value -- is the object a value type? - isProp -- used for quotation reflection. - noTailCall - DllImport? if so don't tailcall - actualTypeInst -- instantiation of the enclosing type - actualMethInst -- instantiation of the method - retTy -- the types of pushed values, if any + The unchecked abstract syntax tree of constants in F# types and expressions. - + - Operation nodes representing C-style operations on byrefs and mutable vals (l-values) + Gets the syntax range of this constuct - + - Pseudo method calls. This is used for overloaded operations like op_Addition. + Represents a syntactic type parameter - + - Used for state machine compilation + The construct is a statically inferred type inference variable '^T' - + - Used for state machine compilation + The construct is a normal type inference variable - + - Used for state machine compilation + Represents whether a type parameter has a static requirement or not (^T or 'T) - + - Represents a "rethrow" operation. May not be rebound, or used outside of try-finally, expecting a unit argument + The construct arises from error recovery - + - Conversion node, compiled via type-directed translation or to box/unbox + The construct arises normally - + - Generate a ldflda on an 'a ref. + Indicates if the construct arises from error recovery - + - IL assembly code - type list are the types pushed on the stack + Indicates if the construct ends in '.' due to error recovery - + - An operation representing a field-get from an F# tuple value. + Gets the syntax range for part of this constuct - + - An operation representing a field-set on an F# exception value. + Gets the syntax range of this constuct - + - An operation representing a field-get from an F# exception value. + Get the long ident for this construct - + - An operation representing a field-get from a union value. The value is not assumed to have been proven to be of the corresponding union case. + Represents a long identifier with possible '.' at end. + + Typically dotms.Length = lid.Length-1, but they may be same if (incomplete) code ends in a dot, e.g. "Foo.Bar." + The dots mostly matter for parsing, and are typically ignored by the typechecker, but + if dotms.Length = lid.Length, then the parser must have reported an error, so the typechecker is allowed + more freedom about typechecking these expressions. + LongIdent can be empty list - it is used to denote that name of some AST element is absent (i.e. empty type name in inherit) - + - An operation representing a field-get from a union value, where that value has been proven to be of the corresponding union case. + Represents a long identifier e.g. 'A.B.C' - + - An operation representing a field-get from a union value, where that value has been proven to be of the corresponding union case. + Represents an identifier in F# code - + - An operation representing a coercion that proves a union value is of a particular union case. This is not a test, its - simply added proof to enable us to generate verifiable code for field access on union types + "fun (UnionCase x) (UnionCase y) -> body" + ==> + "fun tmp1 tmp2 -> + let (UnionCase x) = tmp1 in + let (UnionCase y) = tmp2 in + body" - + - An operation representing getting an integer tag for a union value representing the union case number + Push non-simple parts of a patten match over onto the r.h.s. of a lambda. + Return a simple pattern and a function to build a match on the r.h.s. if the pattern is complex - + - An operation representing getting the address of a record field + Recognize the '()' in 'new()' - + - An operation representing getting a record or class field + Extract the argument for patterns corresponding to the declaration of 'new ... = ...' - + - An operation representing setting a record or class field + This affects placement of sequence points - + - Construct a record or object-model value. The ValRef is for self-referential class constructors, otherwise - it indicates that we're in a constructor and the purpose of the expression is to - fill in the fields of a pre-created but uninitialized object, and to assign the initialized - version of the object into the optional mutable cell pointed to be the given value. + Match a long identifier, including the case for single identifiers which gets a more optimized node in the syntax tree. - + - An operation representing a lambda-encoded try/finally + Infer the syntactic information for a 'let' or 'member' definition, based on the argument pattern, + any declared return information (e.g. .NET attributes on the return element), and the r.h.s. expression + in the case of 'let' definitions. - + - An operation representing a lambda-encoded try/catch + For 'let' definitions, we infer syntactic argument information from the r.h.s. of a definition, if it + is an immediate 'fun ... -> ...' or 'function ...' expression. This is noted in the F# language specification. + This does not apply to member definitions. - + - An operation representing a lambda-encoded for loop + Transform a property declared using '[static] member P = expr' to a method taking a "unit" argument. + This is similar to IncorporateEmptyTupledArgForPropertyGetter, but applies to member definitions + rather than member signatures. - + - An operation representing a lambda-encoded while loop. The special while loop marker is used to mark compilations of 'foreach' expressions + Make sure only a solitary unit argument has unit elimination - + - Constant uint16 arrays (used for parser tables) + Infer the syntactic argument info for one or more arguments a pattern. - + - Constant byte arrays (used for parser tables and other embedded data) + Infer the syntactic argument info for one or more arguments one or more simple patterns. - + - An operation representing the creation of an array value + Infer the syntactic argument info for a single argument from a simple pattern. - + - An operation representing the get of a property from an anonymous record + Get the argument attributes from the syntactic information for an argument. - + - An operation representing the creation of an anonymous record + Get the argument counts for each curried argument group. Used in some adhoc places in tc.fs. - + - An operation representing the creation of a tuple value + Add a parameter entry to the syntactic value information to represent the value argument for a property setter. This is + used for the implicit value argument in property setter signature specifications. - + - An operation representing the creation of an exception value using an F# exception declaration + Add a parameter entry to the syntactic value information to represent the 'this' argument. This is + used for the implicit 'this' argument in member signature specifications. - + - An operation representing the creation of a union value of the particular union case + Add a parameter entry to the syntactic value information to represent the '()' argument to a property getter. This is + used for the implicit '()' argument in property getter signature specifications. - + - Typechecking residue: A Expr.Link occurs for every use of a recursively bound variable. While type-checking - the recursive bindings a dummy expression is stored in the mutable reference cell. - After type checking the bindings this is replaced by a use of the variable, perhaps at an - appropriate type instantiation. These are immediately eliminated on subsequent rewrites. + Check if there are any optional arguments in the syntactic argument information. Used when adjusting the + types of optional arguments for function and member signatures. - + - Typechecking residue: Indicates a free choice of typars that arises due to - minimization of polymorphism at let-rec bindings. These are - resolved to a concrete instantiation on subsequent rewrites. + Check if one particular argument is an optional argument. Used when adjusting the + types of optional arguments for function and member signatures. - + - Expr.Quote(quotedExpr, (referencedTypes, spliceTypes, spliceExprs, data) option ref, isFromQueryExpression, fullRange, quotedType) - - Indicates the expression is a quoted expression tree. - + Determine if a syntactic information represents a member without arguments (which is implicitly a property getter) - + - An intrinsic applied to some (strictly evaluated) arguments - A few of intrinsics (TOp_try, TOp.While, TOp.For) expect arguments kept in a normal form involving lambdas + The 'argument' information for the 'this'/'self' parameter in the cases where it is not given explicitly - + - If we statically know some information then in many cases we can use a more optimized expression - This is primarily used by terms in the standard library, particularly those implementing overloaded - operators. + The 'argument' information for a return value where no attributes are given for the return value (the normal case) - + - Matches are a more complicated form of "let" with multiple possible destinations - and possibly multiple ways to get to each destination. - The first mark is that of the expression being matched, which is used - as the mark for all the decision making and binding that happens during the match. + The argument information for a '()' argument - + - Bind a value. + The argument information for a curried argument without a name - + - Bind a recursive set of values. + The argument information for an argument without a name - + - Applications. - Applications combine type and term applications, and are normalized so - that sequential applications are combined, so "(f x y)" becomes "f [[x];[y]]". - The type attached to the function is the formal function type, used to ensure we don't build application - nodes that over-apply when instantiating at function types. + Operations related to the syntactic analysis of arguments of value, function and member definitions and signatures. - + - Type lambdas. These are used for the r.h.s. of polymorphic 'let' bindings and - for expressions that implement first-class polymorphic values. + The parser defines a number of tokens for whitespace and + comments eliminated by the lexer. These carry a specification of + a continuation for the lexer for continued processing after we've dealt with + the whitespace. - + - Why multiple vspecs? A Expr.Lambda taking multiple arguments really accepts a tuple. - But it is in a convenient form to be compile accepting multiple - arguments, e.g. if compiled as a toplevel static method. + Specifies how the 'endline' function in the lexer should continue after + it reaches end of line or eof. The options are to continue with 'token' function + or to continue with 'skip' function. - + - Sequence expressions, used for "a;b", "let a = e in b;a" and "a then b" (the last an OO constructor). + Helper for parsing the inline IL fragments. - + - Reference a value. The flag is only relevant if the value is an object model member - and indicates base calls and special uses of object constructors. + Reset the generator used for compiler-generated argument names. - + - A constant expression. + Get the generator used for compiler-generated argument names. - + - The big type of expressions. + Get the range corresponding to one of the r.h.s. symbols of a grammar rule while it is being reduced - + - Records the extra metadata stored about typars for type parameters - compiled as "real" IL type parameters, specifically for values with - ValReprInfo. Any information here is propagated from signature through - to the compiled code. + Get the range covering two of the r.h.s. symbols of a grammar rule while it is being reduced - + - Records the "extra information" for an argument compiled as a real - method argument, specifically the argument name and attributes. + Get the range corresponding to the result of a grammar rule while it is being reduced - + - ValReprInfo (numTypars, args, result) + Get an F# compiler range from a lexer range - + - Get the total number of arguments + Get an F# compiler position from a lexer position - + - Get the number of type parameters of the value + The error raised by the parse_error_rich function, which is called by the parser engine + when a syntax error occurs. The first object is the ParseErrorContext which contains a dump of + information about the grammar at the point where the error occurred, e.g. what tokens + are valid to shift next at that point in the grammar. This information is processed in CompileOps.fs. - + - Get the number of curried arguments of the value + Called from the parser each time we parse a construct that marks the end of an XML doc comment range, + e.g. a 'type' declaration. The markerRange is the range of the keyword that delimits the construct. - + - Get the kind of each type parameter + Called from the lexer to save a single line of XML doc comment. - + - Indicates if the value has no arguments - neither type parameters nor value arguments + XmlDoc F# lexer/parser state, held in the BufferLocalStore for the lexer. + This is the only use of the lexer BufferLocalStore in the codebase. - + - Get the number of tupled arguments in each curried argument position + This function maps production indexes returned in syntax errors to strings representing the non terminal that would be produced by that production - + - Get the extra information about the arguments for the value + This function maps production indexes returned in syntax errors to strings representing the non terminal that would be produced by that production - + - Records the "extra information" for a value compiled as a method (rather - than a closure or a local), including argument names, attributes etc. + Keywords paired with their descriptions. Used in completion and quick info. - + - Get the index of the active pattern element within the overall active pattern + Returns a token 'tok' with the same position as this token, except that + it is shifted by specified number of characters from the left and from the right + Note: positive value means shift to the right in both cases - + - Get a reference to the value for the active pattern being referred to + Returns a token 'tok' with the same position as this token - + - Get the full information about the active pattern being referred to + Returns starting position of the token - + - Represents a reference to an active pattern element. The - integer indicates which choice in the target set is being selected by this item. + Returns end position of the token - + - The value being bound + Used to save the state related to a token + Treat as though this is read-only. - + - The information about whether to emit a sequence point for the binding + Used to save some aspects of the lexbuffer state - + - The expression the value is being bound to + Determine the token that may align with the 'try' of a 'try/catch' or 'try/finally' without closing + the construct - + - A binding of a variable to an expression, as in a `let` binding or similar + Determine the tokens that may align with the 'if' of an 'if/then/elif/else' without closing + the construct - + - A collection of simultaneous bindings + Used for warning strings, which should display columns as 1-based and display + the lines after taking '# line' directives into account (i.e. do not use + p.OriginalLine) - + - A target of a decision tree. Can be thought of as a little function, though is compiled as a local block. + LexFilter - process the token stream prior to parsing. + Implements the offside rule and a couple of other lexical transformations. - + - Test.ActivePatternCase(activePatExpr, activePatResTys, activePatIdentity, idx, activePatInfo) - - Run the active pattern and bind a successful result to a - variable in the remaining tree. - activePatExpr -- The active pattern function being called, perhaps applied to some active pattern parameters. - activePatResTys -- The result types (case types) of the active pattern. - activePatIdentity -- The value and the types it is applied to. If there are any active pattern parameters then this is empty. - idx -- The case number of the active pattern which the test relates to. - activePatternInfo -- The extracted info for the active pattern. + Compute the hash value for the tainted value - + - IsInst(source, target) - - Test if the input to a decision tree is an instance of the given type + Test whether the tainted value equals given value. Type providers are ignored (equal tainted values produced by different type providers are equal) + Failure in call to equality operation will be blamed on type provider of first operand - + - Test if the input to a decision tree is null + Test whether the tainted value equals given value. + Failure in call to equality operation will be blamed on type provider of first operand - + - Test if the input to a decision tree is the given constant value + Test whether the tainted value is null - + - Test if the input to a decision tree is an array of the given length + The table of remappings from type names in the provided assembly to type + names in the statically linked, embedded assembly. - + - Test if the input to a decision tree matches the given union case + Create a new static linking map, ready to populate with data. - + - Get the discriminator associated with the case + The table of information recording remappings from type names in the provided assembly to type + names in the statically linked, embedded assembly, plus what types are nested in side what types. - + - Get the decision tree or a successful test + Represents the remapping information for a generated provided type and its nested types. + + There is one overall tree for each root 'type X = ... type generation expr...' specification. - + - Represents a test and a subsequent decision tree + Convert the expression to a string for diagnostics - + - TDBind(binding, body) - - Bind the given value through the remaining cases of the dtree. - These arise from active patterns and some optimizations to prevent - repeated computations in decision trees. - binding -- the value and the expression it is bound to - body -- the rest of the decision tree + Map the TyconRef objects, if any - + - TDSuccess(results, targets) + The context used to interpret information in the closure of System.Type, System.MethodInfo and other + info objects coming from the type provider. - Indicates the decision tree has terminated with success, transferring control to the given target with the given parameters. - results -- the expressions to be bound to the variables at the target - target -- the target number for the continuation + At the moment this is the "Type --> ILTypeRef" and "Type --> Tycon" remapping + context for generated types (it is empty for erased types). This is computed from + while processing the [<Generate>] declaration related to the type. + + Immutable (after type generation for a [<Generate>] declaration populates the dictionaries). + + The 'obj' values are all TyconRef, but obj is used due to a forward reference being required. Not particularly + pleasant, but better than intertwining the whole "ProvidedType" with the TAST structure. - + - TDSwitch(input, cases, default, range) - - Indicates a decision point in a decision tree. - input -- The expression being tested. If switching over a struct union this - must be the address of the expression being tested. - cases -- The list of tests and their subsequent decision trees - default -- The default decision tree, if any - range -- (precise documentation needed) + The folder for temporary files - + - Decision trees. Pattern matching has been compiled down to - a decision tree by this point. The right-hand-sides (actions) of - a decision tree by this point. The right-hand-sides (actions) of - the decision tree are labelled by integers that are unique for that - particular tree. + All referenced assemblies, including the type provider itself, and possibly other type providers. - + - Constants in expressions + Whether or not the --showextensionresolution flag was supplied to the compiler. - + - AttribNamedArg(name, type, isField, value) + Output file name - + - AttribExpr(source, evaluated) + The folder from which an extension provider is resolving from. This is typically the project folder. - + - We keep both source expression and evaluated expression around to help intellisense and signature printing + Carries information about the type provider resolution environment. - + - Attrib(kind, unnamedArgs, propVal, appliedToAGetterOrSetter, targetsOpt, range) + Check if this is a direct reference to a non-embedded generated type. This is not permitted at any name resolution. + We check by seeing if the type is absent from the remapping context. - + - Indicates an attribute refers to a type defined in an imported F# assembly + Get the ILTypeRef for the provided type (including for nested types). Do not take into account + any type relocations or static linking for generated types. - + - Indicates an attribute refers to a type defined in an imported .NET assembly + Get the ILTypeRef for the provided type (including for nested types). Take into account + any type relocations or static linking for generated types. - + - Represents the information saved in the assembly signature data resource for an F# assembly + Decompose the enclosing name of a type (including any class nestings) into a list of parts. + e.g. System.Object -> ["System"; "Object"] - + - The result of attempting to resolve an assembly name to a full ccu. - UnresolvedCcu will contain the name of the assembly that could not be resolved. + Get the parts of a .NET namespace. Special rules: null means global, empty is not allowed. - + - ccu.orphanfixup is true when a reference is missing in the transitive closure of static references that - may potentially be required for the metadata of referenced DLLs. It is set to true if the "loader" - used in the F# metadata-deserializer or the .NET metadata reader returns a failing value (e.g. None). - Note: When used from Visual Studio, the loader will not automatically chase down transitively referenced DLLs - they - must be in the explicit references in the project. + Try to resolve a type in the given extension type resolver - + - Indicates that this DLL uses F# 2.0+ quotation literals somewhere. This is used to implement a restriction on static linking. + Try to resolve a type in the given extension type resolver - + - Indicates that this DLL uses F# 2.0+ quotation literals somewhere. This is used to implement a restriction on static linking. + Try to apply a provided method to the given static arguments. - + - The table of type forwarders for this assembly + Try to apply a provided type to the given static arguments. If successful also return a function + to check the type name is as expected (this function is called by the caller of TryApplyProvidedType + after other checks are made). - + - A unique stamp for this DLL + Validate that the given provided type meets some of the rules for F# provided types - + - A hint as to where does the code for the CCU live (e.g what was the tcConfig.implicitIncludeDir at compilation time for this DLL?) + Get the provided expression for a particular use of a method. - + - The table of type definitions at the "root" of the assembly + Given an extension type resolver, supply a human-readable name suitable for error messages. - + - The table of modules and namespaces at the "root" of the assembly + Find and instantiate the set of ITypeProvider components for the given assembly reference - + - The fully qualified assembly reference string to refer to this assembly. This is persisted in quotations + Get the list of relative paths searched for type provider design-time components - + - Is the CCu an EST injected assembly + Raised when an type provider has thrown an exception. - + - Indicates that this DLL was compiled using the F# compiler and has F# metadata + Raised when a type provider has thrown an exception. - + - Holds the data indicating how this assembly/module is referenced from the code being compiled. + Indicates an F# 3.0+ reference to a named type in an assembly loaded by name - + - Holds the filename for the DLL, if any + Indicates an F# 4.0+ reference into the supplied table of type definition references, ultimately resolved by TypeRef/TypeDef data - + - A handle to the full specification of the contents of the module contained in this ccu + Code to pickle out quotations in the quotation binary format. - + - Try to get the .NET Assembly, if known. May not be present for `IsFSharp` for in-memory cross-project references + Unique name generator for stamps attached to lambdas and object expressions - + - Try to resolve a path into the CCU by referencing the .NET/CLI type forwarder table of the CCU + A name generator used by IlxGen for static fields, some generated arguments and other things. + REVIEW: this will mean the hosted compiler service is not deterministic. We should at least create a new one + of these for each compilation. - + - Used to make forward calls into the type/assembly loader when comparing member signatures during linking + A global generator of stable compiler generated names - + - Used to make 'forward' calls into the loader during linking + A global generator of compiler generated names - + - Fixup a CCU to record it as "orphaned", i.e. not available + Generates compiler-generated names marked up with a source code location, but if given the same unique value then + return precisely the same name. Each name generated also includes the StartLine number of the range passed in + at the point of first generation. + + This type may be accessed concurrently, though in practice it is only used from the compilation thread. + It is made concurrency-safe since a global instance of the type is allocated in tast.fs. - + - Fixup a CCU to have the given contents + Generates compiler-generated names. Each name generated also includes the StartLine number of the range passed in + at the point of first generation. + + This type may be accessed concurrently, though in practice it is only used from the compilation thread. + It is made concurrency-safe since a global instance of the type is allocated in tast.fs, and it is good + policy to make all globally-allocated objects concurrency safe in case future versions of the compiler + are used to host multiple concurrent instances of compilation. - + - Ensure the ccu is derefable in advance. Supply a path to attach to any resulting error message. + Unique name generator for stamps attached to to val_specs, tycon_specs etc. - + - Create a CCU with the given name but where the contents have not yet been specified + Defines the global environment for all type checking. - + - Create a CCU with the given name and contents + Create a new Val node - + - A compilation unit is, more or less, the new material created in one - invocation of the compiler. Due to static linking assemblies may hold more - than one compilation unit (i.e. when two assemblies are merged into a compilation - the resulting assembly will contain 3 CUs). Compilation units are also created for referenced - .NET assemblies. - - References to items such as type constructors are via - cross-compilation-unit thunks, which directly reference the data structures that define - these modules. Thus, when saving out values to disk we only wish - to save out the "current" part of the term graph. When reading values - back in we "fixup" the links to previously referenced modules. - - All non-local accesses to the data structures are mediated - by ccu-thunks. Ultimately, a ccu-thunk is either a (named) element of - the data structure, or it is a delayed fixup, i.e. an invalid dangling - reference that has not had an appropriate fixup applied. + Create a new union case node - + - Represents a table of .NET CLI type forwarders for an assembly + Create a new type parameter node - + - The table of .NET CLI type forwarders for this assembly + Create a new type definition node - + - A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality - logic in tastops.fs + Create a new type parameter node for a declared type parameter - + - A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality - logic in tastops.fs + Create a new TAST RecdField node for an F# class, struct or record field - + - A handle to the full specification of the contents of the module contained in this ccu + Create a new node for the representation information for a provided type definition - + - Indicates that this DLL uses pre-F#-4.0 quotation literals somewhere. This is used to implement a restriction on static linking + Create a new entity node for a provided type definition - + - A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality - logic in tastops.fs + Create a new node for the contents of a module or namespace - + - Triggered when the contents of the CCU are invalidated + Create a new entity node for a module or namespace - + - Is the CCu an assembly injected by a type provider + Create a Val based on an existing one using the function 'f'. + We require that we be given the parent for the new Val. - + - Indicates that this DLL was compiled using the F# compiler and has F# metadata + Create a tycon based on an existing one using the function 'f'. + We require that we be given the new parent for the new tycon. + We pass the new tycon to 'f' in case it needs to reparent the + contents of the tycon. - + - A hint as to where does the code for the CCU live (e.g what was the tcConfig.implicitIncludeDir at compilation time for this DLL?) + Create a module Tycon based on an existing one using the function 'f'. + We require that we be given the parent for the new module. + We pass the new module to 'f' in case it needs to reparent the + contents of the module. - + - The fully qualified assembly reference string to refer to this assembly. This is persisted in quotations + Create a new type definition node for a .NET type definition - + - A unique stamp for this DLL + Create a new unfilled cache for free variable calculations - + - Holds the data indicating how this assembly/module is referenced from the code being compiled. + Create a new TAST Entity node for an F# exception definition - + - Holds the filename for the DLL, if any + Create a new node for an empty module or namespace contents - + - Raising a measure to a rational power + Create a new type definition node by cloning an existing one - + - The unit of measure '1', e.g. float = float<1> + Create a new module or namespace node by cloning an existing one - + - An inverse of a units of measure expression + Create the new contents of an overall assembly - + - A product of two units of measure + Create a node for a union type - + - A constant, leaf unit-of-measure such as 'kg' or 'm' + Create the union case tables for a union type - + - A variable unit-of-measure + Create the field tables for a record or class type - + - Some constant, e.g. true or false for tupInfo + Key a Tycon or TyconRef by demangled name and arity - + - Get the ILTypeRef for the generated type implied by the anonymous type + Key a Tycon or TyconRef by both mangled and demangled name. + Generic types can be accessed either by 'List' or 'List`1'. + This lists both keys. - + - Create an AnonRecdTypeInfo from the basic data + Compute the definition location of a provided item - + - Indicates the type is a unit-of-measure expression being used as an argument to a type or member + A set of static methods for constructing types. - + - Indicates the type is a variable type, whether declared, generalized or an inference type parameter + See FreeTyvars above. - + - TType_ucase(unionCaseRef, typeInstantiation) - - Indicates the type is a non-F#-visible type representing a "proof" that a union value belongs to a particular union case - These types are not user-visible and will never appear as an inferred type. They are the types given to - the temporaries arising out of pattern matching on union values. + The summary of union constructors used in the expression. These may be + marked 'internal' or 'private' and we have to check various conditions associated with that. - + - TType_fun(domainType, rangeType). - - Indicates the type is a function type + The summary of fields used in the expression. These may be made private by a signature + or marked 'internal' or 'private' and we have to check various conditions associated with that. - + - TType_tuple(elementTypes). - - Indicates the type is a tuple type. elementTypes must be of length 2 or greater. + The summary of locally defined tycon representations used in the expression. These may be made private by a signature + or marked 'internal' or 'private' and we have to check various conditions associated with that. - + - TType_anon - - Indicates the type is an anonymous record type whose compiled representation is located in the given assembly + Indicates if the expression contains a call to rethrow that is not bound under a (try-)with branch. + Rethrow may only occur in such locations. - + - TType_app(tyconRef, typeInstantiation). - - Indicates the type is built from a named type and a number of type arguments + Indicates if the expression contains a call to a protected member or a base call. + Calls to protected members and direct calls to super classes can't escape, also code can't be inlined - + - TType_forall(typars, bodyTy). - - Indicates the type is a universal type, only used for types of values and members + The summary of locally defined variables used in the expression. These may be hidden at let bindings etc. + or made private by a signature or marked 'internal' or 'private', and we have to check various conditions associated with that. - + - For now, used only as a discriminant in error message. - See https://github.com/Microsoft/visualfsharp/issues/2561 + Represents the set of free variables in an expression - + - The algebra of types + Represents an amortized computation of the free variables in an expression - + - Get a reference to the type containing this union case + The summary of type parameters used in the expression. These may not escape the enclosing generic construct + and we have to check various conditions associated with that. - + - Get the Entity for the type containing this union case + The summary of values used as trait solutions - + - Try to dereference the reference + The summary of locally defined type definitions used in the expression. These may be made private by a signature + and we have to check various conditions associated with that. - + - Get the signature range of the record field + Represents a set of 'free' type-related elements, including named types, trait solutions, union cases and + record fields. - + - Dereference the reference + Represents a set of 'free' union cases. Used to collect the union cases referred to from an expression. - + - Get the declaration range of the record field + Represents a set of 'free' record field definitions. Used to collect the record field definitions referred to + from an expression. - + - Get the attributes associated with the compiled property of the record field + Represents a set of 'free' named type definitions. Used to collect the named type definitions referred to + from a type or expression. Computed and cached by later phases (never cached type checking). Cached + in expressions. Not pickled. - + - Get the name off the field + Represents a set of free type parameters. Computed and cached by later phases + (never cached type checking). Cached in expressions. Not pickled. - + - Get the definition range of the record field + Represents a set of free local values. Computed and cached by later phases + (never cached type checking). Cached in expressions. Not pickled. - + - Represents a reference to a field in a record, class or struct + Represents the information saved in the assembly signature data resource for an F# assembly - + - Dereference the reference to the union case + The result of attempting to resolve an assembly name to a full ccu. + UnresolvedCcu will contain the name of the assembly that could not be resolved. - + - Get a reference to the type containing this union case + ccu.orphanfixup is true when a reference is missing in the transitive closure of static references that + may potentially be required for the metadata of referenced DLLs. It is set to true if the "loader" + used in the F# metadata-deserializer or the .NET metadata reader returns a failing value (e.g. None). + Note: When used from Visual Studio, the loader will not automatically chase down transitively referenced DLLs - they + must be in the explicit references in the project. - + - Get the Entity for the type containing this union case + Indicates that this DLL uses F# 2.0+ quotation literals somewhere. This is used to implement a restriction on static linking. - + - Try to dereference the reference + Indicates that this DLL uses F# 2.0+ quotation literals somewhere. This is used to implement a restriction on static linking. - + - Get the signature range of the union case + The table of type forwarders for this assembly - + - Get the resulting type of the union case + A unique stamp for this assembly - + - Get the range of the union case + A hint as to where does the code for the CCU live (e.g what was the tcConfig.implicitIncludeDir at compilation time for this DLL?) - + - Get the index of the union case amongst the cases + The table of type definitions at the "root" of the assembly - + - Get the definition range of the union case + The table of modules and namespaces at the "root" of the assembly - + - Get the name of this union case + The fully qualified assembly reference string to refer to this assembly. This is persisted in quotations - + - Get the attributes associated with the union case + Indicates if this assembly reference is unresolved - + - Get the fields of the union case + Is this a provider-injected assembly - + - Get a field of the union case by index + Indicates that this DLL was compiled using the F# compiler and has F# metadata - + - Represents a reference to a case of a union type + Holds the data indicating how this assembly/module is referenced from the code being compiled. - + - Indicates a reference to something bound in another CCU + Holds the filename for the assembly, if any - + - Indicates a reference to something bound in this CCU + Dereference the asssembly reference - + - Get or set the signature for the value's XML documentation + A handle to the full specification of the contents of the module contained in this ccu - + - Get the declared documentation for the value + The short name of the asssembly being referenced - + - Records the "extra information" for a value compiled as a method. - - This indicates the number of arguments in each position for a curried function. + Try to get the .NET Assembly, if known. May not be present for `IsFSharp` for + in-memory cross-project references - + - Get the type of the value including any generic type parameters + Try to resolve a path into the CCU by referencing the .NET/CLI type forwarder table of the CCU - + - The type of the value. May be a TType_forall for a generic value. - May be a type variable or type containing type variables during type inference. + Used to make forward calls into the type/assembly loader when comparing member signatures during linking - + - Dereference the ValRef to a Val option. + Used to make 'forward' calls into the loader during linking - + - Get the actual parent entity for the value (a module or a type), i.e. the entity under which the - value will appear in compiled code. For extension members this is the module where the extension member - is declared. + Fixup a CCU to record it as "orphaned", i.e. not available - + - Get the type of the value after removing any generic type parameters + Fixup a CCU to have the given contents - + - A unique stamp within the context of this invocation of the compiler process + Ensure the ccu is derefable in advance. Supply a path to attach to any resulting error message. - + - The quotation expression associated with a value given the [<ReflectedDefinition>] tag + Create a CCU with the given name but where the contents have not yet been specified - + - Get the information about a recursive value used during type inference + Create a CCU with the given name and contents - + - Get the public path to the value, if any? Should be set if and only if - IsMemberOrModuleBinding is set. + A compilation unit is, more or less, the new material created in one + invocation of the compiler. Due to static linking assemblies may hold more + than one compilation unit (i.e. when two assemblies are merged into a compilation + the resulting assembly will contain 3 CUs). Compilation units are also created for referenced + .NET assemblies. + + References to items such as type constructors are via + cross-compilation-unit thunks, which directly reference the data structures that define + these modules. Thus, when saving out values to disk we only wish + to save out the "current" part of the term graph. When reading values + back in we "fixup" the links to previously referenced modules. + + All non-local accesses to the data structures are mediated + by ccu-thunks. Ultimately, a ccu-thunk is either a (named) element of + the data structure, or it is a delayed fixup, i.e. an invalid dangling + reference that has not had an appropriate fixup applied. - + - Get the name of the value, assuming it is compiled as a property. - - If this is a property then this is 'Foo' - - If this is an implementation of an abstract slot then this is the name of the property implemented by the abstract slot + Represents a table of .NET CLI type forwarders for an assembly - + - Indicates if this value allows the use of an explicit type instantiation (i.e. does it itself have explicit type arguments, - or does it have a signature?) + The table of .NET CLI type forwarders for this assembly - + - Get the number of 'this'/'self' object arguments for the member. Instance extension members return '1'. + A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality + logic in tastops.fs - + - Indicates whether the inline declaration for the value indicate that the value must be inlined? + A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality + logic in tastops.fs - + - Is this a member, if so some more data about the member. + A handle to the full specification of the contents of the module contained in this ccu - + - Get the apparent parent entity for a member + Indicates that this DLL uses pre-F#-4.0 quotation literals somewhere. This is used to implement a restriction on static linking - + - Indicates if this is inferred to be a method or function that definitely makes no critical tailcalls? + A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality + logic in tastops.fs - + - The value of a value or member marked with [<LiteralAttribute>] + Triggered when the contents of the CCU are invalidated - + - Indicates whether this value represents a property setter. + Is the CCu an assembly injected by a type provider - + - Indicates whether this value represents a property getter. + Indicates that this DLL was compiled using the F# compiler and has F# metadata - + - Indicates if this value was a member declared 'override' or an implementation of an interface slot + A hint as to where does the code for the CCU live (e.g what was the tcConfig.implicitIncludeDir at compilation time for this DLL?) - + - Indicates if this value is declared 'mutable' + The fully qualified assembly reference string to refer to this assembly. This is persisted in quotations - + - Indicates if this is an F#-defined value in a module, or an extension member, but excluding compiler generated bindings from optimizations + A unique stamp for this DLL - + - Is this a member definition or module definition? + Holds the data indicating how this assembly/module is referenced from the code being compiled. - + - Indicates if this is a member + Holds the filename for the DLL, if any - + - Indicates if this is an F#-defined instance member. - - Note, the value may still be (a) an extension member or (b) and abstract slot without - a true body. These cases are often causes of bugs in the compiler. + Represents a complete typechecked assembly, made up of multiple implementation files. - + - Indicates if this is a member generated from the de-sugaring of 'let' function bindings in the implicit class syntax? + Represents a complete typechecked implementation file, including its typechecked signature if any. + + TImplFile (qualifiedNameOfFile, pragmas, implementationExpressionWithSignature, hasExplicitEntryPoint, isScript) - + - Indicates if this is a constructor member generated from the de-sugaring of implicit constructor for a class type? + This is the body of the module/namespace - + - Indicates if this is an F#-defined extension member + A named module-or-namespace-fragment definition - + - Indicates if this member is an F#-defined dispatch slot. + Indicates the module fragment is a 'rec' or 'non-rec' definition of types and modules - + - Indicates if this is an F#-defined 'new' constructor member + Indicates the module fragment is an evaluation of expression for side-effects - + - Indicates whether this value was generated by the compiler. - - Note: this is true for the overrides generated by hash/compare augmentations + Indicates the module fragment is a 'let' definition - + - Is this represented as a "top level" static binding (i.e. a static field, static member, - instance member), rather than an "inner" binding that may result in a closure. + Indicates the module fragment is made of several module fragments in succession - + - Get the inline declaration on the value + Indicates the module is a module with a signature - + - Dereference the ValRef to a Val. + The contents of a module-or-namespace-fragment definition - + - The parent type or module, if any (None for expression bindings and parameters) + A type for a module-or-namespace-fragment and the actual definition of the module-or-namespace-fragment + The first ModuleOrNamespaceType is the signature and is a binder. However the bindings are not used in the ModuleOrNamespaceExpr: it is only referenced from the 'outside' + is for use by FCS only to report the "hidden" contents of the assembly prior to applying the signature. - + - The name of the method in compiled code (with some exceptions where ilxgen.fs decides not to use a method impl) + Represents a parameter to an abstract method slot. + + TSlotParam(nm, ty, inFlag, outFlag, optionalFlag, attribs) - + - Indicates if this is a 'base' or 'this' value? + The name of the method - + - Get the declared attributes for the value + The method type parameters of the slot - + - Get the apparent parent entity for the value, i.e. the entity under with which the - value is associated. For extension members this is the nominal type the member extends. - For other values it is just the actual parent. + The (instantiated) type which the slot is logically a part of - + - Get the value representing the accessibility of an F# type definition or module. + The formal return type of the slot (regardless of the type or method instantiation) - + - References are either local or nonlocal + The formal parameters of the slot (regardless of the type or method instantiation) - + - note: ModuleOrNamespaceRef and TyconRef are type equivalent + The class type parameters of the slot - + - Indicates a reference to something bound in another CCU + Represents an abstract method slot, or delegate signature. + + TSlotSig(methodName, declaringType, declaringTypeParameters, methodTypeParameters, slotParameters, returnTy) - + - Indicates a reference to something bound in this CCU + A representation of a method in an object expression. + + TObjExprMethod(slotsig, attribs, methTyparsOfOverridingMethod, methodParams, methodBodyExpr, m) - + - The XML documentation sig-string of the entity, if any, to use to lookup an .xml doc file. This also acts - as a cache for this sig-string computation. + Indicates the static optimization applies when a type is a struct - + - The XML documentation of the entity, if any. If the entity is backed by provided metadata - then this _does_ include this documentation. If the entity is backed by Abstract IL metadata - or comes from another F# assembly then it does not (because the documentation will get read from - an XML file). + Indicates the static optimization applies when a type equality holds - + - Get the union cases and other union-type information for a type, if any + Represents the kind of an F# core library static optimization construct - + - Get the union cases for a type, if any, as a list + A call to a base method, e.g. 'base.OnPaint(args)' - + - Get the union cases for a type, if any + A call to a constructor, e.g. 'new C() = new C(3)' - + - The information about the r.h.s. of a type definition, if any. For example, the r.h.s. of a union or record type. + A call to a constructor, e.g. 'inherit C()' - + - Get the value representing the accessibility of the r.h.s. of an F# type definition. + A normal use of a value - + - The kind of the type definition - is it a measure definition or a type definition? + Indicates a use of a value represents a call to a method that may require + a .NET 2.0 constrained call. A constrained call is only used for calls where - + - The logical contents of the entity when it is a type definition. + Indicates how a value, function or member is being used at a particular usage point. - + - Indicates if this entity is an F# type abbreviation definition + let res = a in b;res - + - Get the type parameters for an entity that is a type declaration, otherwise return the empty list. + a ; b - + - The on-demand analysis about whether the entity has the IsByRefLike attribute + Represents the kind of sequential operation, i.e. "normal" or "to a before returning b" - + - The on-demand analysis about whether the entity has the IsByRefLike attribute + In C syntax this is: *localv_ptr = e - + - Dereference the TyconRef to a Tycon option. + In C syntax this is: localv = e, note == *(&localv) = e == LAddrOf; LByrefSet - + - Get a list of all instance fields for F#-defined record, struct and class fields in this type definition, - excluding compiler-generate fields. + In C syntax this is: *localv_ptr - + - Get a list of all fields for F#-defined record, struct and class fields in this type definition, - including static fields, but excluding compiler-generate fields. + In C syntax this is: &localv - + - A unique stamp for this module, namespace or type definition within the context of this compilation. - Note that because of signatures, there are situations where in a single compilation the "same" - module, namespace or type may have two distinct Entity objects that have distinct stamps. + Indicates what kind of pointer operation this is. - + - The signature definition location of the namespace, module or type + Evaluate start once and end multiple times, loop up - + - The code location where the module, namespace or type is defined. + Evaluate start and end once, loop down - + - Get a blob of data indicating how this type is nested in other namespaces, modules or types. + Evaluate start and end once, loop up - + - Indicates if we have pre-determined that a type definition has a default constructor. + Represents the kind of looping operation. - + - The logical contents of the entity when it is a module or namespace fragment. + Marks the compiled form of a 'for ... in ... do ' expression - + - Gets the immediate members of an F# type definition, excluding compiler-generated ones. - Note: result is alphabetically sorted, then for each name the results are in declaration order + Represents the kind of looping operation. - + - Gets all immediate members of an F# type definition keyed by name, including compiler-generated ones. - Note: result is a indexed table, and for each name the results are in reverse declaration order + If this is Some ty then it indicates that a .NET 2.0 constrained call is required, with the given type as the + static type of the object argument. - + - The name of the namespace, module or type, possibly with mangling, e.g. List`1, List or FailureException + Normal record construction - + - Indicate if this is a type whose r.h.s. is known to be a union type definition. + We're in an explicit constructor. The purpose of the record expression is to + fill in the fields of a pre-created but uninitialized object - + - Indicates if this entity is an F# type abbreviation definition + Represents the kind of record construction operation. - + - Indicates if this is a struct or enum type definition, i.e. a value type definition + ILCall(useCallvirt, isProtected, valu, newobj, valUseFlags, isProp, noTailCall, mref, actualTypeInst, actualMethInst, retTy) + + IL method calls. + value -- is the object a value type? + isProp -- used for quotation reflection. + noTailCall - DllImport? if so don't tailcall + actualTypeInst -- instantiation of the enclosing type + actualMethInst -- instantiation of the method + retTy -- the types of pushed values, if any - + - Indicates if the entity is an erased provided type definition that incorporates a static instantiation (and therefore in some sense compiler generated) + Operation nodes representing C-style operations on byrefs and mutable vals (l-values) - + - Indicates if this is an F# type definition whose r.h.s. is known to be a record type definition. + Pseudo method calls. This is used for overloaded operations like op_Addition. - + - Indicates if the entity is a provided namespace fragment + Used for state machine compilation - + - Indicates if the entity is a generated provided type definition, i.e. not erased. + Used for state machine compilation - + - Indicates if the entity is an erased provided type definition + Used for state machine compilation - + - Indicates if the entity is a provided namespace fragment + Represents a "rethrow" operation. May not be rebound, or used outside of try-finally, expecting a unit argument - + - Indicates the type prefers the "tycon<a, b>" syntax for display etc. + Conversion node, compiled via type-directed translation or to box/unbox - + - Indicates if the entity is a namespace + Generate a ldflda on an 'a ref. - + - Indicates the "tycon blob" is actually a module + IL assembly code - type list are the types pushed on the stack - + - Indicates if the entity is an F# module definition + An operation representing a field-get from an F# tuple value. - + - Indicates if this is an F# type definition which is one of the special types in FSharp.Core.dll like 'float<_>' which - defines a measure type with a relation to an existing non-measure type as a representation. + An operation representing a field-set on an F# exception value. - + - Indicate if this is a type definition backed by Abstract IL metadata. + An operation representing a field-get from an F# exception value. - + - Indicates if this is a .NET-defined struct or enum type definition, i.e. a value type definition + An operation representing a field-get from a union value. The value is not assumed to have been proven to be of the corresponding union case. - + - Indicates if this is a .NET-defined enum type definition + An operation representing a field-get from a union value, where that value has been proven to be of the corresponding union case. - + - Indicates if this is an F# type definition whose r.h.s. definition is unknown (i.e. a traditional ML 'abstract' type in a signature, - which in F# is called a 'unknown representation' type). + An operation representing a field-get from a union value, where that value has been proven to be of the corresponding union case. - + - Indicates if this is an F#-defined struct or enum type definition, i.e. a value type definition + An operation representing a coercion that proves a union value is of a particular union case. This is not a test, its + simply added proof to enable us to generate verifiable code for field access on union types - + - Indicates if this is an F# type definition whose r.h.s. is known to be some kind of F# object model definition + An operation representing getting an integer tag for a union value representing the union case number - + - Indicates if this is an F#-defined interface type definition + An operation representing getting the address of a record field - + - Indicates if this is an F#-defined enum type definition + An operation representing getting a record or class field - + - Indicates if this is an F#-defined delegate type definition + An operation representing setting a record or class field - + - Indicates if the entity represents an F# exception declaration. + Construct a record or object-model value. The ValRef is for self-referential class constructors, otherwise + it indicates that we're in a constructor and the purpose of the expression is to + fill in the fields of a pre-created but uninitialized object, and to assign the initialized + version of the object into the optional mutable cell pointed to be the given value. - + - Indicates if the entity is erased, either a measure definition, or an erased provided type definition + An operation representing a lambda-encoded try/finally - + - Indicates if this is an enum type definition + An operation representing a lambda-encoded try/catch - + - Indicates if this is an F# type definition which is one of the special types in FSharp.Core.dll which uses - an assembly-code representation for the type, e.g. the primitive array type constructor. + An operation representing a lambda-encoded for loop - + - Gets the immediate interface definitions of an F# type definition. Further interfaces may be supported through class and interface inheritance. + An operation representing a lambda-encoded while loop. The special while loop marker is used to mark compilations of 'foreach' expressions - + - Gets the immediate interface types of an F# type definition. Further interfaces may be supported through class and interface inheritance. + Constant uint16 arrays (used for parser tables) - + - The identifier at the point of declaration of the type definition. + Constant byte arrays (used for parser tables and other embedded data) - + - Get the Abstract IL metadata for this type definition, assuming it is backed by Abstract IL metadata. + An operation representing the creation of an array value - + - Get the Abstract IL scope, nesting and metadata for this - type definition, assuming it is backed by Abstract IL metadata. + An operation representing the get of a property from an anonymous record - + - Indicates if we have pre-determined that a type definition has a self-referential constructor using 'as x' + An operation representing the creation of an anonymous record - + - Gets any implicit hash/equals (with comparer argument) methods added to an F# record, union or struct type definition. + An operation representing the creation of a tuple value - + - Gets any implicit hash/equals methods added to an F# record, union or struct type definition. + An operation representing the creation of an exception value using an F# exception declaration - + - Gets any implicit CompareTo (with comparer argument) methods added to an F# record, union or struct type definition. + An operation representing the creation of a union value of the particular union case - + - Gets any implicit CompareTo methods added to an F# record, union or struct type definition. + An instance of a link node occurs for every use of a recursively bound variable. When type-checking + the recursive bindings a dummy expression is stored in the mutable reference cell. + After type checking the bindings this is replaced by a use of the variable, perhaps at an + appropriate type instantiation. These are immediately eliminated on subsequent rewrites. - + - Get the blob of information associated with an F# object-model type definition, i.e. class, interface, struct etc. + Indicates a free choice of typars that arises due to + minimization of polymorphism at let-rec bindings. These are + resolved to a concrete instantiation on subsequent rewrites. - + - The information about the r.h.s. of an F# exception definition, if any. + Indicates the expression is a quoted expression tree. + - + - The display name of the namespace, module or type with <_, _, _> added for generic types, including static parameters + An intrinsic applied to some (strictly evaluated) arguments + A few of intrinsics (TOp_try, TOp.While, TOp.For) expect arguments kept in a normal form involving lambdas - + - The display name of the namespace, module or type, e.g. List instead of List`1, including static parameters + If we statically know some information then in many cases we can use a more optimized expression + This is primarily used by terms in the standard library, particularly those implementing overloaded + operators. - + - The display name of the namespace, module or type, e.g. List instead of List`1, not including static parameters + Matches are a more complicated form of "let" with multiple possible destinations + and possibly multiple ways to get to each destination. + The first range is that of the expression being matched, which is used + as the range for all the decision making and binding that happens during the decision tree + execution. - + - Dereference the TyconRef to a Tycon. Amortize the cost of doing this. - This path should not allocate in the amortized case + Bind a value. - + - Demangle the module name, if FSharpModuleWithSuffix is used + Bind a recursive set of values. - + - The implementation definition location of the namespace, module or type + Applications. + Applications combine type and term applications, and are normalized so + that sequential applications are combined, so "(f x y)" becomes "f [[x];[y]]". + The type attached to the function is the formal function type, used to ensure we don't build application + nodes that over-apply when instantiating at function types. - + - Gets the data indicating the compiled representation of a named type or module in terms of Abstract IL data structures. + Type lambdas. These are used for the r.h.s. of polymorphic 'let' bindings and + for expressions that implement first-class polymorphic values. - + - Gets the data indicating the compiled representation of a type or module in terms of Abstract IL data structures. + Why multiple vspecs? A Expr.Lambda taking multiple arguments really accepts a tuple. + But it is in a convenient form to be compile accepting multiple + arguments, e.g. if compiled as a toplevel static method. - + - Get the cache of the compiled ILTypeRef representation of this module or type. + Sequence expressions, used for "a;b", "let a = e in b;a" and "a then b" (the last an OO constructor). - + - The compiled name of the namespace, module or type, e.g. FSharpList`1, ListModule or FailureException + Reference a value. The flag is only relevant if the value is an object model member + and indicates base calls and special uses of object constructors. - + - Get a blob of data indicating how this type is nested inside other namespaces, modules and types. + A constant expression. - + - Get a blob of data indicating how this type is nested inside other namespaces, modules and types. + Represents an expression in the typed abstract syntax - + - Is the destination assembly available? - + Records the extra metadata stored about typars for type parameters + compiled as "real" IL type parameters, specifically for values with + ValReprInfo. Any information here is propagated from signature through + to the compiled code. + - + - The F#-defined custom attributes of the entity, if any. If the entity is backed by Abstract IL or provided metadata - then this does not include any attributes from those sources. + The name for the argument at this position, if any - + - Get a list of all instance fields for F#-defined record, struct and class fields in this type definition. - including hidden fields from the compilation of implicit class constructions. + The attributes for the argument - + - Get a list of fields for all the F#-defined record, struct and class fields in this type definition, including - static fields, 'val' declarations and hidden fields from the compilation of implicit class constructions. + Records the "extra information" for an argument compiled as a real + method argument, specifically the argument name and attributes. - + - Get an array of fields for all the F#-defined record, struct and class fields in this type definition, including - static fields, 'val' declarations and hidden fields from the compilation of implicit class constructions. + ValReprInfo (numTypars, args, result) - + - Get a table of fields for all the F#-defined record, struct and class fields in this type definition, including - static fields, 'val' declarations and hidden fields from the compilation of implicit class constructions. + Get the total number of arguments - + - Get the value representing the accessibility of an F# type definition or module. + Get the number of type parameters of the value - + - Get the type parameters for an entity that is a type declaration, otherwise return the empty list. - - Lazy because it may read metadata, must provide a context "range" in case error occurs reading metadata. + Get the number of curried arguments of the value - + - Set the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct + Get the kind of each type parameter - + - Set the on-demand analysis about whether the entity has the IsByRefLike attribute + Indicates if the value has no arguments - neither type parameters nor value arguments - + - Get a union case of a type by name + Get the number of tupled arguments in each curried argument position - + - Get a field by name. + Get the extra information about the arguments for the value - + - Get a field by index in definition order + Records the "extra information" for a value compiled as a method (rather + than a closure or a local), including argument names, attributes etc. - + - Get the path into the CCU referenced by the nonlocal reference. + Get the index of the active pattern element within the overall active pattern - + - Get the details of the module or namespace fragment for the entity referred to by this non-local reference. + Get a reference to the value for the active pattern being referred to - + - Get the mangled name of the last item in the path of the nonlocal reference. + Get the full information about the active pattern being referred to - + - Get the all-but-last names of the path of the nonlocal reference. + Represents a reference to an active pattern element. The + integer indicates which choice in the target set is being selected by this item. - + - Dereference the nonlocal reference, and raise an error if this fails. + The value being bound - + - Get the CCU referenced by the nonlocal reference. + The expression the value is being bound to - + - Get the name of the assembly referenced by the nonlocal reference. + The information about whether to emit a sequence point for the binding - + - Try to find the entity corresponding to the given path, using type-providers to link the data + A binding of a variable to an expression, as in a `let` binding or similar - + - Try to find the entity corresponding to the given path in the given CCU + A collection of simultaneous bindings - + - Try to link a non-local entity reference to an actual entity + A target of a decision tree. Can be thought of as a little function, though is compiled as a local block. - + - Index into the namespace/module structure of a particular CCU + Used in error recovery - + - The name of the value, or the full signature of the member + Test.ActivePatternCase(activePatExpr, activePatResTys, activePatIdentity, idx, activePatInfo) + + Run the active pattern and bind a successful result to a + variable in the remaining tree. + activePatExpr -- The active pattern function being called, perhaps applied to some active pattern parameters. + activePatResTys -- The result types (case types) of the active pattern. + activePatIdentity -- The value and the types it is applied to. If there are any active pattern parameters then this is empty. + idx -- The case number of the active pattern which the test relates to. + activePatternInfo -- The extracted info for the active pattern. - + - A reference to the entity containing the value or member. This will always be a non-local reference + IsInst(source, target) + + Test if the input to a decision tree is an instance of the given type - + - For debugging + Test if the input to a decision tree is null - + - Get the thunk for the assembly referred to + Test if the input to a decision tree is the given constant value - + - Get the name of the assembly referred to + Test if the input to a decision tree is an array of the given length - + - For debugging + Test if the input to a decision tree matches the given union case - + - Gets updated with 'true' if an abstract slot is implemented in the file being typechecked. Internal only. + Get the discriminator associated with the case - + - Updated with the full implemented slotsig after interface implementation relation is checked + Get the decision tree or a successful test - + - The parent type. For an extension member this is the type being extended + Represents a test and a subsequent decision tree - + - Represents the extra information stored for a member + TDBind(binding, body) + + Bind the given value through the remaining cases of the dtree. + These arise from active patterns and some optimizations to prevent + repeated computations in decision trees. + binding -- the value and the expression it is bound to + body -- the rest of the decision tree - + - See vflags section further below for encoding/decodings here + TDSuccess(results, targets) + + Indicates the decision tree has terminated with success, transferring control to the given target with the given parameters. + results -- the expressions to be bound to the variables at the target + target -- the target number for the continuation - + - Mutable for unpickle linkage + TDSwitch(input, cases, default, range) + + Indicates a decision point in a decision tree. + input -- The expression being tested. If switching over a struct union this + must be the address of the expression being tested. + cases -- The list of tests and their subsequent decision trees + default -- The default decision tree, if any + range -- (precise documentation needed) - + - Mutable for unpickle linkage + Decision trees. Pattern matching has been compiled down to + a decision tree by this point. The right-hand-sides (actions) of + a decision tree by this point. The right-hand-sides (actions) of + the decision tree are labelled by integers that are unique for that + particular tree. - + - Mutable for unpickle linkage + Constants in expressions - + -Get the signature for the value's XML documentation + AttribNamedArg(name, type, isField, value) - + -Get the signature for the value's XML documentation + AttribExpr(source, evaluated) - + - Get the declared documentation for the value + We keep both source expression and evaluated expression around to help intellisense and signature printing - + - Records the "extra information" for a value compiled as a method. - - This indicates the number of arguments in each position for a curried - functions, and relates to the F# spec for arity analysis. - For module-defined values, the currying is based - on the number of lambdas, and in each position the elements are - based on attempting to deconstruct the type of the argument as a - tuple-type. - - The field is mutable because arities for recursive - values are only inferred after the r.h.s. is analyzed, but the - value itself is created before the r.h.s. is analyzed. - - TLR also sets this for inner bindings that it wants to - represent as "top level" bindings. + Attrib(kind, unnamedArgs, propVal, appliedToAGetterOrSetter, targetsOpt, range) - + - Get the type of the value including any generic type parameters + Indicates an attribute refers to a type defined in an imported F# assembly - + - The type of the value. - May be a TType_forall for a generic value. - May be a type variable or type containing type variables during type inference. + Indicates an attribute refers to a type defined in an imported .NET assembly - + - Get the generic type parameters for the value + Raising a measure to a rational power - + - Get the actual parent entity for the value (a module or a type), i.e. the entity under which the - value will appear in compiled code. For extension members this is the module where the extension member - is declared. + The unit of measure '1', e.g. float = float<1> - + - Get the type of the value after removing any generic type parameters + An inverse of a units of measure expression - + - A unique stamp within the context of this invocation of the compiler process + A product of two units of measure - + - Range of the definition (signature) of the value, used by Visual Studio + A constant, leaf unit-of-measure such as 'kg' or 'm' - + - The quotation expression associated with a value given the [<ReflectedDefinition>] tag + A variable unit-of-measure - + - Get the information about the value used during type inference + Represents a unit of measure in the typed AST - + - The place where the value was defined. + Some constant, e.g. true or false for tupInfo - + - Get the public path to the value, if any? Should be set if and only if - IsMemberOrModuleBinding is set. + Get the ILTypeRef for the generated type implied by the anonymous type - + - The name of the property. - - If this is a property then this is 'Foo' - - If this is an implementation of an abstract slot then this is the name of the property implemented by the abstract slot + Create an AnonRecdTypeInfo from the basic data - + - Indicates if this value allows the use of an explicit type instantiation (i.e. does it itself have explicit type arguments, - or does it have a signature?) + Represents the information identifying an anonymous record - + - Get the number of 'this'/'self' object arguments for the member. Instance extension members return '1'. + Indicates the type is a unit-of-measure expression being used as an argument to a type or member - + - Indicates whether the inline declaration for the value indicate that the value must be inlined? + Indicates the type is a variable type, whether declared, generalized or an inference type parameter - + - Is this a member, if so some more data about the member. + TType_ucase(unionCaseRef, typeInstantiation) - Note, the value may still be (a) an extension member or (b) and abstract slot without - a true body. These cases are often causes of bugs in the compiler. + Indicates the type is a non-F#-visible type representing a "proof" that a union value belongs to a particular union case + These types are not user-visible and will never appear as an inferred type. They are the types given to + the temporaries arising out of pattern matching on union values. - + - Get the apparent parent entity for a member + TType_fun(domainType, rangeType). + + Indicates the type is a function type - + - Indicates if this is inferred to be a method or function that definitely makes no critical tailcalls? + TType_tuple(elementTypes). + + Indicates the type is a tuple type. elementTypes must be of length 2 or greater. - + - The name of the method. - - If this is a property then this is 'get_Foo' or 'set_Foo' - - If this is an implementation of an abstract slot then this is the name of the method implemented by the abstract slot - - If this is an extension member then this will be the simple name + TType_anon + + Indicates the type is an anonymous record type whose compiled representation is located in the given assembly - + - The value of a value or member marked with [<LiteralAttribute>] + TType_app(tyconRef, typeInstantiation). + + Indicates the type is built from a named type and a number of type arguments - + - Indicates if this value was a member declared 'override' or an implementation of an interface slot + TType_forall(typars, bodyTy). + + Indicates the type is a universal type, only used for types of values and members - + - Indicates if this is declared 'mutable' + For now, used only as a discriminant in error message. + See https://github.com/Microsoft/visualfsharp/issues/2561 - + - Indicates if this is an F#-defined value in a module, or an extension member, but excluding compiler generated bindings from optimizations + Represents a type in the typed abstract syntax - + - Is this a member definition or module definition? + Get a reference to the type containing this union case - + - Indicates if this is a member + Get the Entity for the type containing this union case - + - Indicates if a value is linked to backing data yet. Only used during unpickling of F# metadata. + Try to dereference the reference - + - Indicates if this is a member, excluding extension members + Get the signature range of the record field - + - Indicates if this is an F#-defined instance member. - - Note, the value may still be (a) an extension member or (b) and abstract slot without - a true body. These cases are often causes of bugs in the compiler. + Dereference the reference - + - Indicates if this is a member generated from the de-sugaring of 'let' function bindings in the implicit class syntax? + Get the declaration range of the record field - + - Indicates if this is a constructor member generated from the de-sugaring of implicit constructor for a class type? + Get the attributes associated with the compiled property of the record field - + - Indicates if the value is pinned/fixed + Get the name off the field - + - Indicates if this is an F#-defined extension member + Get the definition range of the record field - + - Indicates if this member is an F#-defined dispatch slot. + Represents a reference to a field in a record, class or struct - + - Indicates if this is an F#-defined 'new' constructor member + Dereference the reference to the union case - + - Indicates whether this value was generated by the compiler. - - Note: this is true for the overrides generated by hash/compare augmentations + Get a reference to the type containing this union case - + - Indicates if this is something compiled into a module, i.e. a user-defined value, an extension member or a compiler-generated value + Get the Entity for the type containing this union case - + - Is this represented as a "top level" static binding (i.e. a static field, static member, - instance member), rather than an "inner" binding that may result in a closure. - - This is implied by IsMemberOrModuleBinding, however not vice versa, for two reasons. - Some optimizations mutate this value when they decide to change the representation of a - binding to be IsCompiledAsTopLevel. Second, even immediately after type checking we expect - some non-module, non-member bindings to be marked IsCompiledAsTopLevel, e.g. 'y' in - 'let x = let y = 1 in y + y' (NOTE: check this, don't take it as gospel) + Try to dereference the reference - + - Indicates if the backing field for a static value is suppressed. + Get the signature range of the union case - + - Indicates if this is a compiler-generated class constructor member + Get the resulting type of the union case - + - Get the inline declaration on the value + Get the range of the union case - + - Indicates if this is ever referenced? + Get the index of the union case amongst the cases - + - - If this is a property then this is 'Foo' - - If this is an implementation of an abstract slot then this is the name of the method implemented by the abstract slot - - If this is an operator then this is '(+)' + Get the definition range of the union case - + - Range of the definition (implementation) of the value, used by Visual Studio + Get the name of this union case - + - The parent type or module, if any (None for expression bindings and parameters) + Get the attributes associated with the union case - + - The name of the method. - - If this is a property then this is 'Foo' - - If this is an implementation of an abstract slot then this is the name of the method implemented by the abstract slot - - If this is an operator then this is 'op_Addition' + Get the fields of the union case - + - The name of the method in compiled code (with some exceptions where ilxgen.fs decides not to use a method impl) - - If this is a property then this is 'get_Foo' or 'set_Foo' - - If this is an implementation of an abstract slot then this may be a mangled name - - If this is an extension member then this will be a mangled name - - If this is an operator then this is 'op_Addition' + Get a field of the union case by index - + - Indicates if this is a 'base' or 'this' value? + Represents a reference to a case of a union type - + - Get the declared attributes for the value + Indicates a reference to something bound in another CCU - + - Get the apparent parent entity for the value, i.e. the entity under with which the - value is associated. For extension members this is the nominal type the member extends. - For other values it is just the actual parent. + Indicates a reference to something bound in this CCU - + - How visible is this value, function or member? + Get or set the signature for the value's XML documentation - + - Set all the data on a value + Get the declared documentation for the value - + - Create a new value with empty, unlinked data. Only used during unpickling of F# metadata. + Records the "extra information" for a value compiled as a method. + + This indicates the number of arguments in each position for a curried function. - + - Create a new value with the given backing data. Only used during unpickling of F# metadata. + Get the type of the value including any generic type parameters - + - Link a value based on empty, unlinked data to the given data. Only used during unpickling of F# metadata. + The type of the value. May be a TType_forall for a generic value. + May be a type variable or type containing type variables during type inference. - + - The partial information used to index the methods of all those in a ModuleOrNamespace. + Dereference the ValRef to a Val option. - + - The full information used to identify a specific overloaded method amongst all those in a ModuleOrNamespace. + Get the actual parent entity for the value (a module or a type), i.e. the entity under which the + value will appear in compiled code. For extension members this is the module where the extension member + is declared. - + - Custom attributes attached to the value. These contain references to other values (i.e. constructors in types). Mutable to fixup - these value references after copying a collection of values. + Get the type of the value after removing any generic type parameters - + - XML documentation signature for the value + A unique stamp within the context of this invocation of the compiler process - + - Is the value actually an instance method/property/event that augments - a type, and if so what name does it take in the IL? - MUTABILITY: for unpickle linkage + The quotation expression associated with a value given the [<ReflectedDefinition>] tag - + - XML documentation attached to a value. - MUTABILITY: for unpickle linkage + Get the information about a recursive value used during type inference - + - How visible is this? - MUTABILITY: for unpickle linkage + Get the public path to the value, if any? Should be set if and only if + IsMemberOrModuleBinding is set. - + - What is the original, unoptimized, closed-term definition, if any? - Used to implement [<ReflectedDefinition>] + Get the name of the value, assuming it is compiled as a property. + - If this is a property then this is 'Foo' + - If this is an implementation of an abstract slot then this is the name of the property implemented by the abstract slot - + - If this field is populated, this is the implementation range for an item in a signature, otherwise it is - the signature range for an item in an implementation + Indicates if this value allows the use of an explicit type instantiation (i.e. does it itself have explicit type arguments, + or does it have a signature?) - + - MUTABILITY: for unpickle linkage + Get the number of 'this'/'self' object arguments for the member. Instance extension members return '1'. - + - The full type of the value for the purposes of linking. May be None for non-members, since they can't be overloaded. + Indicates whether the inline declaration for the value indicate that the value must be inlined? - + - The partial information used to index the value in a ModuleOrNamespace. + Is this a member, if so some more data about the member. - + - The full information used to identify a specific overloaded method - amongst all those in a ModuleOrNamespace. + Get the apparent parent entity for a member - + - Indicates the total argument count of the member. + Indicates if this is inferred to be a method or function that definitely makes no critical tailcalls? - + - Indicates the logical name of the member. + The value of a value or member marked with [<LiteralAttribute>] - + - Indicates if the member is an override. + Indicates whether this value represents a property setter. - + - The name of the type with which the member is associated. None for non-member values. + Indicates whether this value represents a property getter. - + - The partial information used to index the methods of all those in a ModuleOrNamespace. + Indicates if this value was a member declared 'override' or an implementation of an interface slot - + - Indicates a trait is solved by a 'fake' instance of an operator, like '+' on integers + Indicates if this value is declared 'mutable' - + - ClosedExprSln(expr) - - Indicates a trait is solved by an erased provided expression + Indicates if this is an F#-defined value in a module, or an extension member, but excluding compiler generated bindings from optimizations - + - ILMethSln(ty, extOpt, ilMethodRef, minst) - - Indicates a trait is solved by a .NET method. - ty -- the type and its instantiation - extOpt -- information about an extension member, if any - ilMethodRef -- the method that solves the trait constraint - minst -- the generic method instantiation + Is this a member definition or module definition? - + - Indicates a trait is solved by an F# anonymous record field. + Indicates if this is a member - + - FSRecdFieldSln(tinst, rfref, isSetProp) + Indicates if this is an F#-defined instance member. - Indicates a trait is solved by an F# record field. - tinst -- the instantiation of the declaring type - rfref -- the reference to the record field - isSetProp -- indicates if this is a set of a record field + Note, the value may still be (a) an extension member or (b) and abstract slot without + a true body. These cases are often causes of bugs in the compiler. - + - FSMethSln(ty, vref, minst) - - Indicates a trait is solved by an F# method. - ty -- the type and its instantiation - vref -- the method that solves the trait constraint - minst -- the generic method instantiation + Indicates if this is a member generated from the de-sugaring of 'let' function bindings in the implicit class syntax? - + - Indicates the solution of a member constraint during inference. + Indicates if this is a constructor member generated from the de-sugaring of implicit constructor for a class type? - + - TTrait(tys, nm, memFlags, argtys, rty, colution) - - Indicates the signature of a member constraint. Contains a mutable solution cell - to store the inferred solution of the constraint. + Indicates if this is an F#-defined extension member - + - Get or set the solution of the member constraint during inference + Indicates if this member is an F#-defined dispatch slot. - + - Get or set the solution of the member constraint during inference + Indicates if this is an F#-defined 'new' constructor member - + - Get the return type recorded in the member constraint. + Indicates whether this value was generated by the compiler. + + Note: this is true for the overrides generated by hash/compare augmentations - + - Get the member name associated with the member constraint. + Is this represented as a "top level" static binding (i.e. a static field, static member, + instance member), rather than an "inner" binding that may result in a closure. - + - The specification of a member constraint that must be solved + Get the inline declaration on the value - + - Indicates a constraint that a type is .NET unmanaged type + Dereference the ValRef to a Val. - + - Indicates a constraint that a type is a delegate from the given tuple of args to the given return type + The parent type or module, if any (None for expression bindings and parameters) - + - Indicates a constraint that a type does not have the Equality(false) attribute, or is not a structural type with this attribute, with special rules for some known structural container types + The name of the method in compiled code (with some exceptions where ilxgen.fs decides not to use a method impl) - + - Indicates a constraint that a type implements IComparable, with special rules for some known structural container types + Indicates if this is a 'base' or 'this' value? - + - Indicates a constraint that a type is an enum with the given underlying + Get the declared attributes for the value - + - Indicates a constraint that a type has a parameterless constructor + Get the apparent parent entity for the value, i.e. the entity under with which the + value is associated. For extension members this is the nominal type the member extends. + For other values it is just the actual parent. - + - Indicates a constraint that a type is a simple choice between one of the given ground types. Only arises from 'printf' format strings. See format.fs + Get the value representing the accessibility of an F# type definition or module. - + - Indicates a constraint that a type is a reference type + References are either local or nonlocal - + - Indicates a constraint that a type is a non-Nullable value type - These are part of .NET's model of generic constraints, and in order to - generate verifiable code we must attach them to F# generalized type variables as well. + Represents a type definition reference in the typed abstract syntax. - + - Indicates a constraint that a type has a member with the given signature + Represents a module-or-namespace reference in the typed abstract syntax. - + - Indicates a constraint that a type has a 'null' value + Indicates a reference to something bound in another CCU - + - Indicates a default value for an inference type variable should it be neither generalized nor solved + Indicates a reference to something bound in this CCU - + - Indicates a constraint that a type is a subtype of the given type + The XML documentation sig-string of the entity, if any, to use to lookup an .xml doc file. This also acts + as a cache for this sig-string computation. - + - A cached TAST type used when this type variable is used as type. + The XML documentation of the entity, if any. If the entity is backed by provided metadata + then this _does_ include this documentation. If the entity is backed by Abstract IL metadata + or comes from another F# assembly then it does not (because the documentation will get read from + an XML file). - + - An inferred equivalence for a type inference variable. + Get the union cases and other union-type information for a type, if any - + - The unique stamp of the typar blob. - MUTABILITY: for linking when unpickling + Get the union cases for a type, if any, as a list - + - MUTABILITY: we set the names of generalized inference type parameters to make the look nice for IL code generation + Get the union cases for a type, if any - + - Indicates if the type variable has a static "head type" requirement, i.e. ^a variables used in FSharp.Core and member constraints. + The information about the r.h.s. of a type definition, if any. For example, the r.h.s. of a union or record type. - + - The unique stamp of the type parameter + Get the value representing the accessibility of the r.h.s. of an F# type definition. - + - The inferred equivalence for the type inference variable, if any. + The kind of the type definition - is it a measure definition or a type definition? - + - Indicates if the type variable can be solved or given new constraints. The status of a type variable - generally always evolves towards being either rigid or solved. + The logical contents of the entity when it is a type definition. - + - The range of the identifier for the type parameter definition + Indicates if this entity is an F# type abbreviation definition - + - The name of the type parameter + Get the type parameters for an entity that is a type declaration, otherwise return the empty list. - + - Indicates whether a type variable can be instantiated by types or units-of-measure. + The on-demand analysis about whether the entity has the IsReadOnly attribute - + - Indicates if a type variable has been solved. + The on-demand analysis about whether the entity has the IsByRefLike attribute - + - Indicates if a type variable has been linked. Only used during unpickling of F# metadata. + The on-demand analysis about whether the entity is assumed to be a readonly struct - + - Indicates if the type inference variable was generated after an error when type checking expressions or patterns + Dereference the TyconRef to a Tycon option. - + - Indicates whether a type variable is erased in compiled .NET IL code, i.e. whether it is a unit-of-measure variable + Get a list of all instance fields for F#-defined record, struct and class fields in this type definition, + excluding compiler-generate fields. - + - Indicates if the type variable is compiler generated, i.e. is an implicit type inference variable + Get a list of all fields for F#-defined record, struct and class fields in this type definition, + including static fields, but excluding compiler-generate fields. - + - Indicates that whether this type parameter is a compat-flex type parameter (i.e. where "expr :> tp" only emits an optional warning) + A unique stamp for this module, namespace or type definition within the context of this compilation. + Note that because of signatures, there are situations where in a single compilation the "same" + module, namespace or type may have two distinct Entity objects that have distinct stamps. - + - The identifier for a type parameter definition + The signature definition location of the namespace, module or type - + - Indicates that whether or not a generic type definition satisfies the equality constraint is dependent on whether this type variable satisfies the equality constraint. + The resolved target of the reference - + - Indicates if a type parameter is needed at runtime and may not be eliminated + The code location where the module, namespace or type is defined. - + - Indicates the display name of a type variable + Get a blob of data indicating how this type is nested in other namespaces, modules or types. - + - The inferred constraints for the type inference variable, if any + Indicates if we have pre-determined that a type definition has a default constructor. - + - Indicates that whether or not a generic type definition satisfies the comparison constraint is dependent on whether this type variable satisfies the comparison constraint. + The logical contents of the entity when it is a module or namespace fragment. - + - The declared attributes of the type parameter. Empty for type inference variables and parameters from .NET + Gets the immediate members of an F# type definition, excluding compiler-generated ones. + Note: result is alphabetically sorted, then for each name the results are in declaration order - + - Links a previously unlinked type variable to the given data. Only used during unpickling of F# metadata. + Gets all immediate members of an F# type definition keyed by name, including compiler-generated ones. + Note: result is a indexed table, and for each name the results are in reverse declaration order - + - Sets whether a type variable has a static requirement + The name of the namespace, module or type, possibly with mangling, e.g. List`1, List or FailureException - + - Sets the rigidity of a type variable + Indicate if this is a type whose r.h.s. is known to be a union type definition. - + - Set whether this type parameter is a compat-flex type parameter (i.e. where "expr :> tp" only emits an optional warning) + Indicates if this entity is an F# type abbreviation definition - + - Sets the identifier associated with a type variable + Indicates if this is a struct or enum type definition, i.e. a value type definition - + - Sets whether the equality constraint of a type definition depends on this type variable + Indicates if the entity is an erased provided type definition that incorporates a static instantiation (and therefore in some sense compiler generated) - + - Sets whether a type variable is required at runtime + Indicates if the reference has been resolved - + - Adjusts the constraints associated with a type variable + Indicates if this is an F# type definition whose r.h.s. is known to be a record type definition. - + - Sets whether a type variable is compiler generated + Indicates if the entity is a provided namespace fragment - + - Sets whether the comparison constraint of a type definition depends on this type variable + Indicates if the entity is a generated provided type definition, i.e. not erased. - + - Creates a type variable that contains empty data, and is not yet linked. Only used during unpickling of F# metadata. + Indicates if the entity is an erased provided type definition - + - Creates a type variable based on the given data. Only used during unpickling of F# metadata. + Indicates if the entity is a provided namespace fragment - + - Links a previously unlinked type variable to the given data. Only used during unpickling of F# metadata. + Indicates the type prefers the "tycon<a, b>" syntax for display etc. - + - A declared generic type/measure parameter, or a type/measure inference variable. + Indicates if the entity is a namespace - + - The declared attributes of the type parameter. Empty for type inference variables. + Indicates the "tycon blob" is actually a module - + - The inferred constraints for the type inference variable + Indicates if the entity is an F# module definition - + - The documentation for the type parameter. Empty for type inference variables. - MUTABILITY: for linking when unpickling + Indicates if this is an F# type definition which is one of the special types in FSharp.Core.dll like 'float<_>' which + defines a measure type with a relation to an existing non-measure type as a representation. - + - MUTABILITY: we set the names of generalized inference type parameters to make the look nice for IL code generation + Indicates if the reference is a local reference - + - Indicates the construct can only be accessed from any code in the given type constructor, module or assembly. [] indicates global scope. + Indicate if this is a type definition backed by Abstract IL metadata. - + - A set of static methods for constructing types. + Indicates if this is a .NET-defined struct or enum type definition, i.e. a value type definition - + - Mutation used during compilation of FSharp.Core.dll + Indicates if this is a .NET-defined enum type definition - + - Get a table of types defined within this module, namespace or type. The - table is indexed by both name and, for generic types, also by mangled name. + Indicates if this is an F# type definition whose r.h.s. definition is unknown (i.e. a traditional ML 'abstract' type in a signature, + which in F# is called a 'unknown representation' type). - + - Get a list of types defined within this module, namespace or type. + Indicates if this is an F#-defined struct or enum type definition, i.e. a value type definition - + - Get a list of type and exception definitions defined within this module, namespace or type. + Indicates if this is an F# type definition whose r.h.s. is known to be some kind of F# object model definition - + - Get a table of nested module and namespace fragments indexed by demangled name (so 'ListModule' becomes 'List') + Indicates if this is an F#-defined interface type definition - + - Namespace or module-compiled-as-type? + Indicates if this is an F#-defined enum type definition - + - Get a list of module and namespace definitions defined within this module, namespace or type. + Indicates if this is an F#-defined delegate type definition - + - Get a table of F# exception definitions indexed by demangled name, so 'FailureException' is indexed by 'Failure' + Indicates if the entity represents an F# exception declaration. - + - Get a list of F# exception definitions defined within this module, namespace or type. + Indicates if the entity is erased, either a measure definition, or an erased provided type definition - + - Get a table of values indexed by logical name + Indicates if this is an enum type definition - + - Get a table of values and members indexed by partial linkage key, which includes name, the mangled name of the parent type (if any), - and the method argument count (if any). + Indicates if this is an F# type definition which is one of the special types in FSharp.Core.dll which uses + an assembly-code representation for the type, e.g. the primitive array type constructor. - + - Compute a table of values and members indexed by logical name. + Gets the immediate interface definitions of an F# type definition. Further interfaces may be supported through class and interface inheritance. - + - Values, including members in F# types in this module-or-namespace-fragment. + Gets the immediate interface types of an F# type definition. Further interfaces may be supported through class and interface inheritance. - + - Get a table of entities indexed by both logical name + The identifier at the point of declaration of the type definition. - + - Get a table of entities indexed by both logical and compiled names + Get the Abstract IL metadata for this type definition, assuming it is backed by Abstract IL metadata. - + - Type, mapping mangled name to Tycon, e.g. + Get the Abstract IL scope, nesting and metadata for this + type definition, assuming it is backed by Abstract IL metadata. - + - Get a table of the active patterns defined in this module. + Indicates if we have pre-determined that a type definition has a self-referential constructor using 'as x' - + - Get a table of types defined within this module, namespace or type. The - table is indexed by both name and generic arity. This means that for generic - types "List`1", the entry (List, 1) will be present. + Gets any implicit hash/equals (with comparer argument) methods added to an F# record, union or struct type definition. - + - Try to find the member with the given linkage key in the given module. + Gets any implicit hash/equals methods added to an F# record, union or struct type definition. - + - Return a new module or namespace type with a value added. + Gets any implicit CompareTo (with comparer argument) methods added to an F# record, union or struct type definition. - + - Mutation used in hosting scenarios to hold the hosted types in this module or namespace + Gets any implicit CompareTo methods added to an F# record, union or struct type definition. - + - Mutation used during compilation of FSharp.Core.dll + Get the blob of information associated with an F# object-model type definition, i.e. class, interface, struct etc. - + - Return a new module or namespace type with an entity added. + The information about the r.h.s. of an F# exception definition, if any. - + - Indicates that an exception is abstract, i.e. is in a signature file, and we do not know the representation + The display name of the namespace, module or type with <_, _, _> added for generic types, including static parameters - + - Indicates that an exception carries the given record of values + The display name of the namespace, module or type with <'T, 'U, 'V> added for generic types, including static parameters - + - Indicates that an exception is shorthand for the given .NET exception type + The display name of the namespace, module or type, e.g. List instead of List`1, including static parameters - + - Indicates that an exception is an abbreviation for the given exception + The display name of the namespace, module or type, e.g. List instead of List`1, not including static parameters - + - If this field is populated, this is the implementation range for an item in a signature, otherwise it is - the signature range for an item in an implementation + Dereference the TyconRef to a Tycon. Amortize the cost of doing this. + This path should not allocate in the amortized case - + - Name/declaration-location of the field + Demangle the module name, if FSharpModuleWithSuffix is used - + - Attributes attached to generated field + The implementation definition location of the namespace, module or type - + - Attributes attached to generated property + Gets the data indicating the compiled representation of a named type or module in terms of Abstract IL data structures. - + - Indicates the declared visibility of the field, not taking signatures into account + Gets the data indicating the compiled representation of a type or module in terms of Abstract IL data structures. - + - The default initialization info, for static literals + Get the cache of the compiled ILTypeRef representation of this module or type. - + - Indicates a compiler generated field, not visible to Intellisense or name resolution + The compiled name of the namespace, module or type, e.g. FSharpList`1, ListModule or FailureException - + - Indicates a volatile field + Get a blob of data indicating how this type is nested inside other namespaces, modules and types. - + - Indicates a static field + Get a blob of data indicating how this type is nested inside other namespaces, modules and types. - + - The type of the field, w.r.t. the generic parameters of the enclosing type constructor + Is the destination assembly available? - + - XML Documentation signature for the field + The F#-defined custom attributes of the entity, if any. If the entity is backed by Abstract IL or provided metadata + then this does not include any attributes from those sources. - + - Documentation for the field + Get a list of all instance fields for F#-defined record, struct and class fields in this type definition. + including hidden fields from the compilation of implicit class constructions. - + - Is the field declared mutable in F#? + Get a list of fields for all the F#-defined record, struct and class fields in this type definition, including + static fields, 'val' declarations and hidden fields from the compilation of implicit class constructions. - + - Get or set the XML documentation signature for the field + Get an array of fields for all the F#-defined record, struct and class fields in this type definition, including + static fields, 'val' declarations and hidden fields from the compilation of implicit class constructions. - + - Get or set the XML documentation signature for the field + Get a table of fields for all the F#-defined record, struct and class fields in this type definition, including + static fields, 'val' declarations and hidden fields from the compilation of implicit class constructions. - + - XML Documentation signature for the field + Get the value representing the accessibility of an F# type definition or module. - + - Declaration-location of the field + Get the type parameters for an entity that is a type declaration, otherwise return the empty list. + + Lazy because it may read metadata, must provide a context "range" in case error occurs reading metadata. - + - Attributes attached to generated property + Set the on-demand analysis about whether the entity has the IsReadOnly attribute - + - Name of the field + Set the on-demand analysis about whether the entity has the IsByRefLike attribute - + - The default initialization info, for static literals + Set the on-demand analysis about whether the entity is assumed to be a readonly struct - + - Indicates if the field is zero-initialized + Resolve the reference - + - Indicates a volatile field + Get a union case of a type by name - + - Indicates a static field + Get a field by name. - + - Is the field declared mutable in F#? + Get a field by index in definition order - + - Indicates a compiler generated field, not visible to Intellisense or name resolution + Get the path into the CCU referenced by the nonlocal reference. - + - Name/declaration-location of the field + Get the details of the module or namespace fragment for the entity referred to by this non-local reference. - + - The type of the field, w.r.t. the generic parameters of the enclosing type constructor + Get the mangled name of the last item in the path of the nonlocal reference. - + - Attributes attached to generated field + Get the all-but-last names of the path of the nonlocal reference. - + - Indicates the declared visibility of the field, not taking signatures into account + Dereference the nonlocal reference, and raise an error if this fails. - + - This may represent a "field" in either a struct, class, record or union - It is normally compiled to a property. + Get the CCU referenced by the nonlocal reference. - + - Attributes, attached to the generated static method to make instances of the case + Get the name of the assembly referenced by the nonlocal reference. - + - Indicates the declared visibility of the union constructor, not taking signatures into account + Try to find the entity corresponding to the given path, using type-providers to link the data - + - If this field is populated, this is the implementation range for an item in a signature, otherwise it is - the signature range for an item in an implementation + Try to find the entity corresponding to the given path in the given CCU - + - Name/range of the case + Try to link a non-local entity reference to an actual entity - + - XML documentation signature for the case + Represents an index into the namespace/module structure of an assembly - + - Documentation for the case + Represents the path information for a reference to a value or member in another assembly, disassociated + from any particular reference. - + - Return type constructed by the case. Normally exactly the type of the enclosing type, sometimes an abbreviation of it + The name of the value, or the full signature of the member - + - Data carried by the case. + A reference to the entity containing the value or member. This will always be a non-local reference - + - Name of the case in generated IL code. + For debugging - + - The ILX data structure representing the discriminated union. + Get the thunk for the assembly referred to - + - The cases contained in the discriminated union. + Get the name of the assembly referred to - + - The cases of the discriminated union, indexed by name. + For debugging - + - The cases of the discriminated union, in declaration order. + Gets updated with 'true' if an abstract slot is implemented in the file being typechecked. Internal only. - + - The fields of the record, indexed by name. + Updated with the full implemented slotsig after interface implementation relation is checked - + - The fields of the record, in declaration order. + The parent type. For an extension member this is the type being extended - + - The fields of the class, struct or enum + Represents the extra information stored for a member - + - The declared abstract slots of the class, interface or struct + See vflags section further below for encoding/decodings here - + - Indicates whether the type declaration is a class, interface, enum, delegate or struct + Mutable for unpickle linkage - + - Indicates the type is an enumeration + Mutable for unpickle linkage - + - Indicates the type is a delegate with the given Invoke signature + Mutable for unpickle linkage - + - Indicates the type is a struct +Get the signature for the value's XML documentation - + - Indicates the type is an interface +Get the signature for the value's XML documentation - + - Indicates the type is a class (also used for units-of-measure) + Get the declared documentation for the value - + - Indicates the type is generated, but type-relocation is suppressed + Records the "extra information" for a value compiled as a method. + + This indicates the number of arguments in each position for a curried + functions, and relates to the F# spec for arity analysis. + For module-defined values, the currying is based + on the number of lambdas, and in each position the elements are + based on attempting to deconstruct the type of the argument as a + tuple-type. + + The field is mutable because arities for recursive + values are only inferred after the r.h.s. is analyzed, but the + value itself is created before the r.h.s. is analyzed. + + TLR also sets this for inner bindings that it wants to + represent as "top level" bindings. - + - Indicates the type is erased + Get the type of the value including any generic type parameters - + - A flag read from the provided type and used to compute basic properties of the type definition. - Reading is delayed, since it looks at the .BaseType + The type of the value. + May be a TType_forall for a generic value. + May be a type variable or type containing type variables during type inference. - + - A type read from the provided type and used to compute basic properties of the type definition. - Reading is delayed, since it does an import on the underlying type + Get the generic type parameters for the value - + - A flag read eagerly from the provided type and used to compute basic properties of the type definition. + Get the actual parent entity for the value (a module or a type), i.e. the entity under which the + value will appear in compiled code. For extension members this is the module where the extension member + is declared. - + - A flag read eagerly from the provided type and used to compute basic properties of the type definition. + Get the type of the value after removing any generic type parameters - + - A flag read eagerly from the provided type and used to compute basic properties of the type definition. + A unique stamp within the context of this invocation of the compiler process - + - A flag read eagerly from the provided type and used to compute basic properties of the type definition. + Range of the definition (signature) of the value, used by Visual Studio - + - A flag read eagerly from the provided type and used to compute basic properties of the type definition. + The quotation expression associated with a value given the [<ReflectedDefinition>] tag - + - The base type of the type. We use it to compute the compiled representation of the type for erased types. - Reading is delayed, since it does an import on the underlying type + Get the information about the value used during type inference - + - The underlying System.Type (wrapped as a ProvidedType to make sure we don't call random things on - System.Type, and wrapped as Tainted to make sure we track which provider this came from, for reporting - error messages) + The place where the value was defined. - + - The parameters given to the provider that provided to this type. + Get the public path to the value, if any? Should be set if and only if + IsMemberOrModuleBinding is set. - + - The information kept about a provided type + The name of the property. + - If this is a property then this is 'Foo' + - If this is an implementation of an abstract slot then this is the name of the property implemented by the abstract slot - + - TILObjectReprData(scope, nesting, definition) + Indicates if this value allows the use of an explicit type instantiation (i.e. does it itself have explicit type arguments, + or does it have a signature?) - + - The 'NoRepr' value here has four meanings: - (1) it indicates 'not yet known' during the first 2 phases of establishing type definitions - (2) it indicates 'no representation', i.e. 'type X' in signatures - (3) it is the setting used for exception definitions (!) - (4) it is the setting used for modules and namespaces. - - It would be better to separate the "not yet known" and other cases out. - The information for exception definitions should be folded into here. + Get the number of 'this'/'self' object arguments for the member. Instance extension members return '1'. - + - Indicates the representation information for a provided namespace. + Indicates whether the inline declaration for the value indicate that the value must be inlined? - + - TProvidedTypeExtensionPoint + Is this a member, if so some more data about the member. - Indicates the representation information for a provided type. + Note, the value may still be (a) an extension member or (b) and abstract slot without + a true body. These cases are often causes of bugs in the compiler. - + - Indicates the type is parameterized on a measure (e.g. float<_>) but erases to some other type (e.g. float) + Get the apparent parent entity for a member - + - Indicates the type is implemented as IL assembly code using the given closed Abstract IL type + Indicates if this is inferred to be a method or function that definitely makes no critical tailcalls? - + - Indicates the type is a type from a .NET assembly without F# metadata. + The name of the method. + - If this is a property then this is 'get_Foo' or 'set_Foo' + - If this is an implementation of an abstract slot then this is the name of the method implemented by the abstract slot + - If this is an extension member then this will be the simple name - + - Indicates the type is a discriminated union + The value of a value or member marked with [<LiteralAttribute>] - + - Indicates the type is a record + Indicates if this value was a member declared 'override' or an implementation of an interface slot - + - Indicates the type is a class, struct, enum, delegate or interface + Indicates if this is declared 'mutable' - + - The information for the contents of a type. Also used for a provided namespace. + Indicates if this is an F#-defined value in a module, or an extension member, but excluding compiler generated bindings from optimizations - + - Set to true if the type is determined to be abstract + Is this a member definition or module definition? - + - Set to true at the end of the scope where proper augmentations are allowed + Indicates if this is a member - + - Super type, if any + Indicates if a value is linked to backing data yet. Only used during unpickling of F# metadata. - + - Interface implementations - boolean indicates compiler-generated + Indicates if this is a member, excluding extension members - + - Properties, methods etc. as lookup table + Indicates if this is an F#-defined instance member. + + Note, the value may still be (a) an extension member or (b) and abstract slot without + a true body. These cases are often causes of bugs in the compiler. - + - Properties, methods etc. in declaration order. The boolean flag for each indicates if the - member is known to be an explicit interface implementation. This must be computed and - saved prior to remapping assembly information. + Indicates if this is a member generated from the de-sugaring of 'let' function bindings in the implicit class syntax? - + - True if the type defined an Object.GetHashCode method. In this - case we give a warning if we auto-generate a hash method since the semantics may not match up + Indicates if this is a constructor member generated from the de-sugaring of implicit constructor for a class type? - + - This is the value implementing the auto-generated comparison - semantics if any. It is not present if the type defines its own implementation - of IStructuralEquatable or if the type doesn't implement IComparable implicitly. + Indicates if the value is pinned/fixed - + - This is the value implementing the auto-generated equality - semantics if any. It is not present if the type defines its own implementation - of Object.Equals or if the type doesn't override Object.Equals implicitly. + Indicates if this is an F#-defined extension member - + - This is the value implementing the auto-generated comparison - semantics if any. It is not present if the type defines its own implementation - of IStructuralComparable or if the type doesn't implement IComparable implicitly. + Indicates if this member is an F#-defined dispatch slot. - + - This is the value implementing the auto-generated comparison - semantics if any. It is not present if the type defines its own implementation - of IComparable or if the type doesn't implement IComparable implicitly. + Indicates if this is an F#-defined 'new' constructor member - + - Used during codegen to hold the ILX representation indicating how to access the type + Indicates whether this value was generated by the compiler. + + Note: this is true for the overrides generated by hash/compare augmentations - + - The stable path to the type, e.g. Microsoft.FSharp.Core.FSharpFunc`2 + Indicates if this is something compiled into a module, i.e. a user-defined value, an extension member or a compiler-generated value - + - The stable path to the type, e.g. Microsoft.FSharp.Core.FSharpFunc`2 + Is this represented as a "top level" static binding (i.e. a static field, static member, + instance member), rather than an "inner" binding that may result in a closure. + + This is implied by IsMemberOrModuleBinding, however not vice versa, for two reasons. + Some optimizations mutate this value when they decide to change the representation of a + binding to be IsCompiledAsTopLevel. Second, even immediately after type checking we expect + some non-module, non-member bindings to be marked IsCompiledAsTopLevel, e.g. 'y' in + 'let x = let y = 1 in y + y' (NOTE: check this, don't take it as gospel) - + - This field is used when the 'tycon' is really a module definition. It holds statically nested type definitions and nested modules + Indicates if the backing field for a static value is suppressed. - + - The methods and properties of the type + Indicates if this is a compiler-generated class constructor member - + - The declared representation of the type, i.e. record, union, class etc. + Get the inline declaration on the value - + - The declared attributes for the type + Indicates if the value will ignore byref scoping rules - + - The declaration location for the type constructor + Indicates if this is ever referenced? - + - The name of the type, possibly with `n mangling + - If this is a property then this is 'Foo' + - If this is an implementation of an abstract slot then this is the name of the method implemented by the abstract slot + - If this is an operator then this is '(+)' - + - The unique stamp of the "tycon blob". Note the same tycon in signature and implementation get different stamps + Range of the definition (implementation) of the value, used by Visual Studio - + - The declared type parameters of the type + The parent type or module, if any (None for expression bindings and parameters) - + - The XML documentation sig-string of the entity, if any, to use to lookup an .xml doc file. This also acts - as a cache for this sig-string computation. + The name of the method. + - If this is a property then this is 'Foo' + - If this is an implementation of an abstract slot then this is the name of the method implemented by the abstract slot + - If this is an operator then this is 'op_Addition' - + - The XML documentation sig-string of the entity, if any, to use to lookup an .xml doc file. This also acts - as a cache for this sig-string computation. + Indicates if this is a 'base' or 'this' value? - + - The XML documentation of the entity, if any. If the entity is backed by provided metadata - then this _does_ include this documentation. If the entity is backed by Abstract IL metadata - or comes from another F# assembly then it does not (because the documentation will get read from - an XML file). + Get the declared attributes for the value - + - Get the union cases and other union-type information for a type, if any + Get the apparent parent entity for the value, i.e. the entity under with which the + value is associated. For extension members this is the nominal type the member extends. + For other values it is just the actual parent. - + - Get the union cases for a type, if any, as a list + How visible is this value, function or member? - + - Get the union cases for a type, if any + Set all the data on a value - + - The information about the r.h.s. of a type definition, if any. For example, the r.h.s. of a union or record type. + Create a new value with empty, unlinked data. Only used during unpickling of F# metadata. - + - Get the value representing the accessibility of the r.h.s. of an F# type definition. + Create a new value with the given backing data. Only used during unpickling of F# metadata. - + - The kind of the type definition - is it a measure definition or a type definition? + Link a value based on empty, unlinked data to the given data. Only used during unpickling of F# metadata. - + - The logical contents of the entity when it is a type definition. + The partial information used to index the methods of all those in a ModuleOrNamespace. - + - Get the type abbreviated by this type definition, if it is an F# type abbreviation definition + The full information used to identify a specific overloaded method amongst all those in a ModuleOrNamespace. - + - Get the type parameters for an entity that is a type declaration, otherwise return the empty list. + The name of the method in compiled code (with some exceptions where ilxgen.fs decides not to use a method impl) + - If this is a property then this is 'get_Foo' or 'set_Foo' + - If this is an implementation of an abstract slot then this may be a mangled name + - If this is an extension member then this will be a mangled name + - If this is an operator then this is 'op_Addition' - + - These two bits represents the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct + Custom attributes attached to the value. These contain references to other values (i.e. constructors in types). Mutable to fixup + these value references after copying a collection of values. - + - The on-demand analysis about whether the entity has the IsByRefLike attribute + XML documentation signature for the value - + - Get a list of all instance fields for F#-defined record, struct and class fields in this type definition, - excluding compiler-generate fields. + Is the value actually an instance method/property/event that augments + a type, and if so what name does it take in the IL? + MUTABILITY: for unpickle linkage - + - Get a list of all fields for F#-defined record, struct and class fields in this type definition, - including static fields, but excluding compiler-generate fields. + XML documentation attached to a value. + MUTABILITY: for unpickle linkage - + - A unique stamp for this module, namespace or type definition within the context of this compilation. - Note that because of signatures, there are situations where in a single compilation the "same" - module, namespace or type may have two distinct Entity objects that have distinct stamps. + How visible is this? + MUTABILITY: for unpickle linkage - + - The code location where the module, namespace or type is defined. + What is the original, unoptimized, closed-term definition, if any? + Used to implement [<ReflectedDefinition>] - + - Get a blob of data indicating how this type is nested in other namespaces, modules or types. + If this field is populated, this is the implementation range for an item in a signature, otherwise it is + the signature range for an item in an implementation - + - Indicates if we have pre-determined that a type definition has a default constructor. + MUTABILITY: for unpickle linkage - + - The logical contents of the entity when it is a module or namespace fragment. + The full type of the value for the purposes of linking. May be None for non-members, since they can't be overloaded. - + - Gets the immediate members of an F# type definition, excluding compiler-generated ones. - Note: result is alphabetically sorted, then for each name the results are in declaration order + The partial information used to index the value in a ModuleOrNamespace. - + - Gets all immediate members of an F# type definition keyed by name, including compiler-generated ones. - Note: result is a indexed table, and for each name the results are in reverse declaration order + The full information used to identify a specific overloaded method + amongst all those in a ModuleOrNamespace. - + - The name of the namespace, module or type, possibly with mangling, e.g. List`1, List or FailureException + Indicates the total argument count of the member. - + - Indicate if this is a type whose r.h.s. is known to be a union type definition. + Indicates the logical name of the member. - + - Indicates if this entity is an F# type abbreviation definition + Indicates if the member is an override. - + - Indicates if this is an F# type definition whose r.h.s. is known to be a record type definition that is a value type. + The name of the type with which the member is associated. None for non-member values. - + - Indicates if this is a struct or enum type definition, i.e. a value type definition + The partial information used to index the methods of all those in a ModuleOrNamespace. - + - Indicates if this is an F# type definition whose r.h.s. is known to be a record type definition. + Indicates a trait is solved by a 'fake' instance of an operator, like '+' on integers - + - Indicates if the entity is a provided namespace fragment + ClosedExprSln expr + + Indicates a trait is solved by an erased provided expression - + - Indicates if the entity is a generated provided type definition, i.e. not erased. + ILMethSln(ty, extOpt, ilMethodRef, minst) + + Indicates a trait is solved by a .NET method. + ty -- the type and its instantiation + extOpt -- information about an extension member, if any + ilMethodRef -- the method that solves the trait constraint + minst -- the generic method instantiation - + - Indicates if the entity is an erased provided type definition + Indicates a trait is solved by an F# anonymous record field. - + - Indicates if the entity is a provided type or namespace definition + FSRecdFieldSln(tinst, rfref, isSetProp) + + Indicates a trait is solved by an F# record field. + tinst -- the instantiation of the declaring type + rfref -- the reference to the record field + isSetProp -- indicates if this is a set of a record field - + - Indicates the type prefers the "tycon<a, b>" syntax for display etc. + FSMethSln(ty, vref, minst) + + Indicates a trait is solved by an F# method. + ty -- the type and its instantiation + vref -- the method that solves the trait constraint + minst -- the generic method instantiation - + - Indicates if the entity is a namespace + Represents the solution of a member constraint during inference. - + - Indicates the Entity is actually a module or namespace, not a type definition + Indicates the signature of a member constraint. Contains a mutable solution cell + to store the inferred solution of the constraint. - + - Indicates if the entity is an F# module definition + Get or set the solution of the member constraint during inference - + - Indicates if this is an F# type definition which is one of the special types in FSharp.Core.dll like 'float<_>' which - defines a measure type with a relation to an existing non-measure type as a representation. + Get or set the solution of the member constraint during inference - + - Indicates if the entity is linked to backing data. Only used during unpickling of F# metadata. + Get the return type recorded in the member constraint. - + - Indicate if this is a type definition backed by Abstract IL metadata. + Get the member name associated with the member constraint. - + - Indicates if this is a .NET-defined struct or enum type definition, i.e. a value type definition + Get the argument types required of a member in order to solve the constraint - + - Indicates if this is a .NET-defined enum type definition + Represents the specification of a member constraint that must be solved - + - Indicates if this is an F# type definition whose r.h.s. definition is unknown (i.e. a traditional ML 'abstract' type in a signature, - which in F# is called a 'unknown representation' type). + A constraint that a type is .NET unmanaged type - + - Indicates if this is an F#-defined struct or enum type definition, i.e. a value type definition + A constraint that a type is a delegate from the given tuple of args to the given return type - + - Indicates if this is an F# type definition whose r.h.s. is known to be some kind of F# object model definition + A constraint that a type does not have the Equality(false) attribute, or is not a structural type with this attribute, with special rules for some known structural container types - + - Indicates if this is an F#-defined interface type definition + A constraint that a type implements IComparable, with special rules for some known structural container types - + - Indicates if this is an F#-defined enum type definition + A constraint that a type is an enum with the given underlying - + - Indicates if this is an F#-defined delegate type definition + A constraint that a type has a parameterless constructor - + - Indicates if this is an F#-defined class type definition + A constraint that a type is a simple choice between one of the given ground types. Only arises from 'printf' format strings. See format.fs - + - Indicates if the entity represents an F# exception declaration. + A constraint that a type is a reference type - + - Indicates if the entity is erased, either a measure definition, or an erased provided type definition + A constraint that a type is a non-Nullable value type + These are part of .NET's model of generic constraints, and in order to + generate verifiable code we must attach them to F# generalized type variables as well. - + - Indicates if this is an enum type definition + A constraint that a type has a member with the given signature - + - Indicates if this is an F# type definition which is one of the special types in FSharp.Core.dll which uses - an assembly-code representation for the type, e.g. the primitive array type constructor. + A constraint that a type has a 'null' value - + - Gets the immediate interface definitions of an F# type definition. Further interfaces may be supported through class and interface inheritance. + A constraint for a default value for an inference type variable should it be neither generalized nor solved - + - Gets the immediate interface types of an F# type definition. Further interfaces may be supported through class and interface inheritance. + A constraint that a type is a subtype of the given type - + - The identifier at the point of declaration of the type definition. + Represents a constraint on a type parameter or type - + - Get the Abstract IL metadata for this type definition, assuming it is backed by Abstract IL metadata. + The optional data for the type parameter - + - Get the Abstract IL scope, nesting and metadata for this - type definition, assuming it is backed by Abstract IL metadata. + A cached TAST type used when this type variable is used as type. - + - Indicates if we have pre-determined that a type definition has a self-referential constructor using 'as x' + An inferred equivalence for a type inference variable. - + - Gets any implicit hash/equals (with comparer argument) methods added to an F# record, union or struct type definition. + The unique stamp of the type parameter + MUTABILITY: for linking when unpickling - + - Gets any implicit hash/equals methods added to an F# record, union or struct type definition. + The flag data for the type parameter - + - Gets any implicit CompareTo (with comparer argument) methods added to an F# record, union or struct type definition. + MUTABILITY: we set the names of generalized inference type parameters to make the look nice for IL code generation + The identifier for the type parameter - + - Gets any implicit CompareTo methods added to an F# record, union or struct type definition. + Get the XML documetnation for the type parameter - + - Get the blob of information associated with an F# object-model type definition, i.e. class, interface, struct etc. + Indicates if the type variable has a static "head type" requirement, i.e. ^a variables used in FSharp.Core and member constraints. - + - The information about the r.h.s. of an F# exception definition, if any. + The unique stamp of the type parameter - + - The display name of the namespace, module or type with <_, _, _> added for generic types, plus static parameters if any + The inferred equivalence for the type inference variable, if any. - + - The display name of the namespace, module or type, e.g. List instead of List`1, including static parameters if any + Indicates if the type variable can be solved or given new constraints. The status of a type variable + generally always evolves towards being either rigid or solved. - + - The display name of the namespace, module or type, e.g. List instead of List`1, and no static parameters + The range of the identifier for the type parameter definition - + - Demangle the module name, if FSharpModuleWithSuffix is used + The name of the type parameter - + - The range in the implementation, adjusted for an item in a signature + Indicates whether a type variable can be instantiated by types or units-of-measure. - + - Gets the data indicating the compiled representation of a named type or module in terms of Abstract IL data structures. + Indicates if a type variable has been solved. - + - Gets the data indicating the compiled representation of a type or module in terms of Abstract IL data structures. + Indicates if a type variable has been linked. Only used during unpickling of F# metadata. - + - Get the cache of the compiled ILTypeRef representation of this module or type. + Indicates if the type inference variable was generated after an error when type checking expressions or patterns - + - The compiled name of the namespace, module or type, e.g. FSharpList`1, ListModule or FailureException + Indicates whether a type variable is erased in compiled .NET IL code, i.e. whether it is a unit-of-measure variable - + - Get a blob of data indicating how this type is nested inside other namespaces, modules and types. + Indicates if the type variable is compiler generated, i.e. is an implicit type inference variable - + - Get a blob of data indicating how this type is nested inside other namespaces, modules and types. + Indicates that whether this type parameter is a compat-flex type parameter (i.e. where "expr :> tp" only emits an optional warning) - + - The F#-defined custom attributes of the entity, if any. If the entity is backed by Abstract IL or provided metadata - then this does not include any attributes from those sources. + The identifier for a type parameter definition - + - Get a list of all instance fields for F#-defined record, struct and class fields in this type definition. - including hidden fields from the compilation of implicit class constructions. + Get the IL name of the type parameter - + - Gets all implicit hash/equals/compare methods added to an F# record, union or struct type definition. + Indicates that whether or not a generic type definition satisfies the equality constraint is dependent on whether this type variable satisfies the equality constraint. - + - Get a list of fields for all the F#-defined record, struct and class fields in this type definition, including - static fields, 'val' declarations and hidden fields from the compilation of implicit class constructions. + Indicates if a type parameter is needed at runtime and may not be eliminated - + - Get an array of fields for all the F#-defined record, struct and class fields in this type definition, including - static fields, 'val' declarations and hidden fields from the compilation of implicit class constructions. + Indicates the display name of a type variable - + - Get a table of fields for all the F#-defined record, struct and class fields in this type definition, including - static fields, 'val' declarations and hidden fields from the compilation of implicit class constructions. + The inferred constraints for the type inference variable, if any - + - Get the value representing the accessibility of an F# type definition or module. + Indicates that whether or not a generic type definition satisfies the comparison constraint is dependent on whether this type variable satisfies the comparison constraint. - + - Get the type parameters for an entity that is a type declaration, otherwise return the empty list. - - Lazy because it may read metadata, must provide a context "range" in case error occurs reading metadata. + The declared attributes of the type parameter. Empty for type inference variables and parameters from .NET. - + - Sets the structness of a record or union type definition + Links a previously unlinked type variable to the given data. Only used during unpickling of F# metadata. - + - Set the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct + Sets whether a type variable has a static requirement - + - Set the on-demand analysis about whether the entity has the IsByRefLike attribute + Sets the rigidity of a type variable - + - Set the custom attributes on an F# type definition. + Set whether this type parameter is a compat-flex type parameter (i.e. where "expr :> tp" only emits an optional warning) - + - Create a new entity with empty, unlinked data. Only used during unpickling of F# metadata. + Sets the identifier associated with a type variable - + - Create a new entity with the given backing data. Only used during unpickling of F# metadata. + Set the IL name of the type parameter - + - Link an entity based on empty, unlinked data to the given data. Only used during unpickling of F# metadata. + Sets whether the equality constraint of a type definition depends on this type variable - + - Get a union case of a type by name + Sets whether a type variable is required at runtime - + - Get a field by name. + Adjusts the constraints associated with a type variable - + - Get a field by index in definition order + Sets whether a type variable is compiler generated - + - Represents a type definition, exception definition, module definition or namespace definition. + Sets whether the comparison constraint of a type definition depends on this type variable - + - Field used when the 'tycon' is really an exception definition + Set the attributes on the type parameter - + - Indicates how visible is the entity is. + Creates a type variable that contains empty data, and is not yet linked. Only used during unpickling of F# metadata. - + - The declared accessibility of the representation, not taking signatures into account + Creates a type variable based on the given data. Only used during unpickling of F# metadata. - + - If non-None, indicates the type is an abbreviation for another type. + Links a previously unlinked type variable to the given data. Only used during unpickling of F# metadata. - + - The XML document signature for this entity + A declared generic type/measure parameter, or a type/measure inference variable. - + - The declared documentation for the type or module + The declared attributes of the type parameter. Empty for type inference variables. - + - If this field is populated, this is the implementation range for an item in a signature, otherwise it is - the signature range for an item in an implementation + The inferred constraints for the type parameter or inference variable. - + - The name of the type, possibly with `n mangling + The documentation for the type parameter. Empty for inference variables. + MUTABILITY: for linking when unpickling - + - String 'Module' off an F# module name, if FSharpModuleWithSuffix is used + MUTABILITY: we set the names of generalized inference type parameters to make the look nice for IL code generation + The storage for the IL name for the type parameter. - + - The information ILXGEN needs about the location of an item + Represents less-frequently-required data about a type parameter of type inference variable - + - A public path records where a construct lives within the global namespace - of a CCU. + Indicates the construct can only be accessed from any code in the given type constructor, module or assembly. [] indicates global scope. - + - Indicates that a 'module' is really a namespace + Represents the constraint on access for a construct - + - Indicates that a module is compiled to a class with the same name as the original module + Represents a type or exception definition in the typed AST - + - Indicates that a module is compiled to a class with the "Module" suffix added. + Represents a module or namespace definition in the typed AST - + - These two bits represents the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct + Mutation used during compilation of FSharp.Core.dll - + - These two bits represents the on-demand analysis about whether the entity has the IsByRefLike attribute + Get a table of types defined within this module, namespace or type. The + table is indexed by both name and, for generic types, also by mangled name. - + - This bit is reserved for us in the pickle format, see pickle.fs, it's being listed here to stop it ever being used for anything else + Get a list of types defined within this module, namespace or type. - + - Get the flags as included in the F# binary metadata + Get a list of type and exception definitions defined within this module, namespace or type. - + - This bit represents a F# record that is a value type, or a struct record. + Get a table of nested module and namespace fragments indexed by demangled name (so 'ListModule' becomes 'List') - + - Indicates the type prefers the "tycon<a, b>" syntax for display etc. + Namespace or module-compiled-as-type? - + - Indicates the Entity is actually a module or namespace, not a type definition + Get a list of module and namespace definitions defined within this module, namespace or type. - + - Adjust the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct + Get a table of F# exception definitions indexed by demangled name, so 'FailureException' is indexed by 'Failure' - + - Adjust the on-demand analysis about whether the entity has the IsByRefLike attribute + Get a list of F# exception definitions defined within this module, namespace or type. - + - Encode entity flags into a bit field. We leave lots of space to allow for future expansion. + Get a table of values indexed by logical name - + - Indicates if the type variable has a static "head type" requirement, i.e. ^a variables used in FSharp.Core and member constraints. + Get a table of values and members indexed by partial linkage key, which includes name, the mangled name of the parent type (if any), + and the method argument count (if any). - + - Indicates if the type variable can be solved or given new constraints. The status of a type variable - generally always evolves towards being either rigid or solved. + Compute a table of values and members indexed by logical name. - + - Get the flags as included in the F# binary metadata. We pickle this as int64 to allow for future expansion + Values, including members in F# types in this module-or-namespace-fragment. - + - Indicates whether a type variable can be instantiated by types or units-of-measure. + Get a table of entities indexed by both logical name - + - Indicates if the type inference variable was generated after an error when type checking expressions or patterns + Get a table of entities indexed by both logical and compiled names - + - Indicates if the type variable is compiler generated, i.e. is an implicit type inference variable + Type, mapping mangled name to Tycon, e.g. - + - Indicates that whether this type parameter is a compat-flex type parameter (i.e. where "expr :> tp" only emits an optional warning) + Get a table of the active patterns defined in this module. - + - Indicates that whether or not a generic type definition satisfies the equality constraint is dependent on whether this type variable satisfies the equality constraint. + Get a table of types defined within this module, namespace or type. The + table is indexed by both name and generic arity. This means that for generic + types "List`1", the entry (List, 1) will be present. - + - Indicates if a type parameter is needed at runtime and may not be eliminated + Try to find the member with the given linkage key in the given module. - + - Indicates that whether or not a generic type definition satisfies the comparison constraint is dependent on whether this type variable satisfies the comparison constraint. + Return a new module or namespace type with a value added. - + - Encode typar flags into a bit field + Mutation used in hosting scenarios to hold the hosted types in this module or namespace - + - Indicates the type parameter derives from an '_' anonymous type - For units-of-measure, we give a warning if this gets solved to '1' + Mutation used during compilation of FSharp.Core.dll - + - Indicates the type parameter is an inference variable may be solved + Return a new module or namespace type with an entity added. - + - Indicates we give a warning if the type parameter is ever solved + Represents the contents of of a module of namespace - + - Indicates the type parameter can't be solved, but the variable is not set to "rigid" until after inference is complete + Indicates that an exception is abstract, i.e. is in a signature file, and we do not know the representation - + - Indicates the type parameter can't be solved + Indicates that an exception carries the given record of values - + - Indicates if the type variable can be solved or given new constraints. The status of a type variable - evolves towards being either rigid or solved. + Indicates that an exception is shorthand for the given .NET exception type - + - Represents the kind of a type parameter + Indicates that an exception is an abbreviation for the given exception - + - Get the flags as included in the F# binary metadata + Represents the implementation of an F# exception definition. - + - Flags on values + If this field is populated, this is the implementation range for an item in a signature, otherwise it is + the signature range for an item in an implementation - + - Indicates the 'this' value specified in a memberm e.g. 'x' in 'member x.M() = 1' + Name/declaration-location of the field - + - Indicates a normal value + Attributes attached to generated field - + - Indicates the value called 'base' available for calling base class members + Attributes attached to generated property - + - Indicates a ref-cell holding 'this' or the implicit 'this' used throughout an - implicit constructor to access and set values + Indicates the declared visibility of the field, not taking signatures into account - + - Indicates the type parameter is needed at runtime and may not be eliminated + The default initialization info, for static literals - + - Indicates the type parameter is not needed at runtime and may be eliminated + Indicates a compiler generated field, not visible to Intellisense or name resolution - + - Indicates if a type parameter is needed at runtime and may not be eliminated + Indicates a volatile field - + - The normal value for this flag when the value is not within its recursive scope + Indicates a static field - + - Set while the value is within its recursive scope. The flag indicates if the value has been eagerly generalized and accepts generic-recursive calls + The type of the field, w.r.t. the generic parameters of the enclosing type constructor - + - A flag associated with values that indicates whether the recursive scope of the value is currently being processed, and - if the value has been generalized or not as yet. + XML Documentation signature for the field - + - Indicates the value must never be inlined by the optimizer + Documentation for the field - + - Indicates the value may optionally be inlined by the optimizer + Is the field declared mutable in F#? - + - Indicates the value is inlined but the .NET IL code for the function still exists, e.g. to satisfy interfaces on objects, but that it is also always inlined + Get or set the XML documentation signature for the field - + - Indicates the value must always be inlined and no .NET IL code is generated for the value/function + Get or set the XML documentation signature for the field - + - Returns true if the implementation of a value must always be inlined + XML Documentation signature for the field - + - Unique name generator for stamps attached to lambdas and object expressions + Get the signature location of the field - + - Combine a list of ModuleOrNamespaceType's making up the description of a CCU. checking there are now - duplicate modules etc. + Get the declaration location of the field - + - Create a Val based on an existing one using the function 'f'. - We require that we be given the parent for the new Val. + Attributes attached to generated property - + - Create a module Tycon based on an existing one using the function 'f'. - We require that we be given the parent for the new module. - We pass the new module to 'f' in case it needs to reparent the - contents of the module. + Name of the field - + - Create a tycon based on an existing one using the function 'f'. - We require that we be given the new parent for the new tycon. - We pass the new tycon to 'f' in case it needs to reparent the - contents of the tycon. + The default initialization info, for static literals - + - Create the new contents of an overall assembly + Indicates if the field is zero-initialized - + - Create a new Val object + Indicates a volatile field - + - Create a new TAST RecdField node for an F# class, struct or record field + Indicates a static field - + - Create a new TAST Entity node for an F# exception definition + Is the field declared mutable in F#? - + - Given (newPath, oldPath) replace oldPath by newPath in the TAccess. + Indicates a compiler generated field, not visible to Intellisense or name resolution - + - Primitive routine to compare two ValRef's for equality. On the whole value identity is not particularly - significant in F#. However it is significant for - (a) Active Patterns - (b) detecting uses of "special known values" from FSharp.Core.dll, such as 'seq' - and quotation splicing - - Note this routine doesn't take type forwarding into account + Name/declaration-location of the field - + - Primitive routine to compare two UnionCaseRef's for equality + The type of the field, w.r.t. the generic parameters of the enclosing type constructor - + - Primitive routine to compare two EntityRef's for equality - This takes into account the possibility that they may have type forwarders + Attributes attached to generated field - + - This predicate tests if non-local resolution paths are definitely known to resolve - to different entities. All references with different named paths always resolve to - different entities. Two references with the same named paths may resolve to the same - entities even if they reference through different CCUs, because one reference - may be forwarded to another via a .NET TypeForwarder. + Get the definition location of the field - + - From Ref_private to Ref_nonlocal when exporting data. + Indicates the declared visibility of the field, not taking signatures into account - + - From Ref_private to Ref_nonlocal when exporting data. + Represents a class, struct or record field in an F# type definition. + This may represent a "field" in either a struct, class, record or union. - + - Make a reference to a union case for type in a module or namespace + Attributes, attached to the generated static method to make instances of the case - + - For dereferencing in the middle of a pattern + Indicates the declared visibility of the union constructor, not taking signatures into account - + - Equality on CCU references, implemented as reference equality except when unresolved + If this field is populated, this is the implementation range for an item in a signature, otherwise it is + the signature range for an item in an implementation - + - Equality on value specs, implemented as reference equality + Name/range of the case - + - Equality on type variables, implemented as reference equality. This should be equivalent to using typarEq. + XML documentation signature for the case - + - Generic types can be accessed either by 'List' or 'List`1'. This lists both keys. The second form should really be deprecated. + Documentation for the case - + - A global generator of stable compiler generated names + Return type constructed by the case. Normally exactly the type of the enclosing type, sometimes an abbreviation of it - + - A global generator of compiler generated names + Data carried by the case. - + - Unique name generator for stamps attached to to val_specs, tycon_specs etc. + Get the signature location of the union case - + - Metadata on values (names of arguments etc. + Get the full array of fields of the union case - + - Memoization table to help minimize the number of ILSourceDocument objects we create + Get the full list of fields of the union case - + - Are we assuming all code gen is for F# interactive, with no static linking + Get the declaration location of the union case - + - For debugging + Indicates if the union case has no fields - + - For debugging + Get the display name of the union case - + - For debugging + Get the definition location of the union case - + - For debugging + Get the name of the case in generated IL code. - + - Represents an intrinsic value from FSharp.Core known to the compiler + Get a field of the union case by name - + - Defines the global environment for all type checking. - - The environment (TcGlobals) are well-known types and values are hard-wired - into the compiler. This lets the compiler perform particular optimizations - for these types and values, for example emitting optimized calls for - comparison and hashing functions. + Get a field of the union case by position - + - Represents metadata extracted from a nominal type + Represents a union case in an F# type definition - + - A set of function parameters (visitor) for folding over expressions + The ILX data structure representing the discriminated union. - + - The empty table representing no hiding + The cases contained in the discriminated union. - + - A set of tables summarizing the items hidden by a signature + Get the union cases as a list - + - The list of corresponding modules, namespacea and type definitions + Represents the union cases and related information in an F# type definition - + - The list of corresponding values + The cases of the discriminated union, indexed by name. - + - The empty table + The cases of the discriminated union, in declaration order. - + - The remapping that corresponds to a module meeting its signature - and also report the set of tycons, tycon representations and values hidden in the process. + Get the union cases as a list - + - OnlyCloneExprVals is a nasty setting to reuse the cloning logic in a mode where all - Tycon and "module/member" Val objects keep their identity, but the Val objects for all Expr bindings - are cloned. This is used to 'fixup' the TAST created by tlr.fs - - This is a fragile mode of use. It's not really clear why TLR needs to create a "bad" expression tree that - reuses Val objects as multiple value bindings, and its been the cause of several subtle bugs. + Get a union case by index - + - Indicate what should happen to value definitions when copying expressions + Represents union cases in an F# type definition - + - A flag to govern whether arity inference should be type-directed or syntax-directed when - inferring an arity from a lambda expression. + The fields of the record, indexed by name. - + - Represents a combination of substitutions/instantiations where things replace other things during remapping + The fields of the record, in declaration order. - + - Represents an instantiation where value references replace other value references + Get all non-compiler-generated instance fields as a list - + - Represents an instantiation where type definition references replace other type definition references + Get all non-compiler-generated fields as a list - + - Represents an instantiation where types replace type parameters + Get all the fields as a list - + - The empty map + Get a field by name - + - Make a new map, containing a entries for the given type definitions + Get a field by index - + - Fetch the entries for the given type definition + Represents record fields in an F# type definition - + - Make a new map, containing a new entry for the given type definition + The fields of the class, struct or enum - + - Maps TyconRef to list of T based on stamp keys + The declared abstract slots of the class, interface or struct - + - Get the entry for the given type definition + Indicates whether the type declaration is a class, interface, enum, delegate or struct - + - Determine if the map is empty + Represents member values and class fields relating to the F# object model - + - The empty map + Indicates the type is an enumeration - + - Try to find the entry for the given type definition + Indicates the type is a delegate with the given Invoke signature - + - Remove the entry for the given type definition, if any + Indicates the type is a struct - + - Make a new map, containing entries for the given type definitions + Indicates the type is an interface - + - Determine is the map contains an entry for the given type definition + Indicates the type is a class (also used for units-of-measure) - + - Make a new map, containing a new entry for the given type definition + Indicates if the type definition is a value type - + - Maps TyconRef to T based on stamp keys + Indicates the type is generated, but type-relocation is suppressed - + - Get the entry for the given type parameter + Indicates the type is erased - + - The empty map + A flag read from the provided type and used to compute basic properties of the type definition. + Reading is delayed, since it looks at the .BaseType - + - Try to find the entry for the given type parameter + A type read from the provided type and used to compute basic properties of the type definition. + Reading is delayed, since it does an import on the underlying type - + - Determine is the map contains an entry for the given type parameter + A flag read eagerly from the provided type and used to compute basic properties of the type definition. - + - Make a new map, containing a new entry for the given type parameter + A flag read eagerly from the provided type and used to compute basic properties of the type definition. - + - Maps type parameters to entries based on stamp keys + A flag read eagerly from the provided type and used to compute basic properties of the type definition. - + - Maps Val's to list of T based on stamp keys + A flag read eagerly from the provided type and used to compute basic properties of the type definition. - + - Mutable data structure mapping Val's to T based on stamp keys + A flag read eagerly from the provided type and used to compute basic properties of the type definition. - + - Maps Val to T, based on stamps + A flag read eagerly from the provided type and used to compute basic properties of the type definition. - + - TypeScheme (generalizedTypars, tauTy) - - generalizedTypars -- the truly generalized type parameters - tauTy -- the body of the generalized type. A 'tau' type is one with its type parameters stripped off. + The base type of the type. We use it to compute the compiled representation of the type for erased types. + Reading is delayed, since it does an import on the underlying type - + - Finish the targets + The underlying System.Type (wrapped as a ProvidedType to make sure we don't call random things on + System.Type, and wrapped as Tainted to make sure we track which provider this came from, for reporting + error messages) - + - Build the overall expression + The parameters given to the provider that provided to this type. - + - Add a new destination target + Indicates if the provided type is generated, i.e. not erased - + - Add a new destination target that is an expression result + Gets the base type of an erased provided type - + - Create a new builder + The information kept about a provided type - + - Build decision trees imperatively + The 'NoRepr' value here has four meanings: + (1) it indicates 'not yet known' during the first 2 phases of establishing type definitions + (2) it indicates 'no representation', i.e. 'type X' in signatures + (3) it is the setting used for exception definitions (!) + (4) it is the setting used for modules and namespaces. + + It would be better to separate the "not yet known" and other cases out. + The information for exception definitions should be folded into here. - + - Determines types that are potentially known to satisfy the 'comparable' constraint and returns - a set of residual types that must also satisfy the constraint + Indicates the representation information for a provided namespace. - + - Build for loops + TProvidedTypeExtensionPoint + + Indicates the representation information for a provided type. - + - Check if the type is a byref-like but not a byref. + Indicates the type is parameterized on a measure (e.g. float<_>) but erases to some other type (e.g. float) - + - returns Some(assemblyName) for success + Indicates the type is implemented as IL assembly code using the given closed Abstract IL type - + - Try to find the AttributeUsage attribute, looking for the value of the AllowMultiple named parameter + Indicates the type is a type from a .NET assembly without F# metadata. - + - Try to find a specific attribute on a type definition + Indicates the type is a discriminated union - + - Try to find a specific attribute on a type definition, where the attribute accepts a bool argument. + Indicates the type is a record - + - Try to find a specific attribute on a type definition, where the attribute accepts a string argument. - - This is used to detect the 'DefaultMemberAttribute' and 'ConditionalAttribute' attributes (on type definitions) + Indicates the type is a class, struct, enum, delegate or interface - + - Matches any byref type, yielding the target type + The information for the contents of a type. Also used for a provided namespace. - + - An active pattern to transform System.Nullable types to their input, otherwise leave the input unchanged + Set to true if the type is determined to be abstract - + - An active pattern to match System.Nullable types + Set to true at the end of the scope where proper augmentations are allowed - + - An active pattern to determine if a type is a nominal type, possibly instantiated + Super type, if any - + - For "type Class as self", 'self' is fixed up after initialization. To support this, - it is converted behind the scenes to a ref. This function strips off the ref and - returns the underlying type. + Interface implementations - boolean indicates compiler-generated - + - Determine if a type is a struct, record or union type + Properties, methods etc. as lookup table - + - Determine if a type is an enum type + Properties, methods etc. in declaration order. The boolean flag for each indicates if the + member is known to be an explicit interface implementation. This must be computed and + saved prior to remapping assembly information. - + - Determine if a type is a class type + True if the type defined an Object.GetHashCode method. In this + case we give a warning if we auto-generate a hash method since the semantics may not match up - + - Determine if a type is an unmanaged type + This is the value implementing the auto-generated comparison + semantics if any. It is not present if the type defines its own implementation + of IStructuralEquatable or if the type doesn't implement IComparable implicitly. - + - Determine if a type is a struct type + This is the value implementing the auto-generated equality + semantics if any. It is not present if the type defines its own implementation + of Object.Equals or if the type doesn't override Object.Equals implicitly. - + - If the input type is an enum type, then convert to its underlying type, otherwise return the input type + This is the value implementing the auto-generated comparison + semantics if any. It is not present if the type defines its own implementation + of IStructuralComparable or if the type doesn't implement IComparable implicitly. - + - Determine the underlying type of an enum type (normally int32) + This is the value implementing the auto-generated comparison + semantics if any. It is not present if the type defines its own implementation + of IComparable or if the type doesn't implement IComparable implicitly. - + - Determine if a type is a ComInterop type + An AbstractIL type representation that may include type variables - + - Determine if a type is a sealed type + An AbstractIL type representation that is just the name of a type. + + CompiledTypeRepr.ILAsmNamed (ilTypeRef, ilBoxity, ilTypeOpt) + + The ilTypeOpt is present for non-generic types. It is an ILType corresponding to the first two elements of the case. This + prevents reallocation of the ILType each time we need to generate it. For generic types, it is None. - + - Determine if a type is a FSharpRef type + Specifies the compiled representations of type and exception definitions. Basically + just an ILTypeRef. Computed and cached by later phases. Stored in + type and exception definitions. Not pickled. Store an optional ILType object for + non-generic types. - + - Determine if a type is an interface type + Represents the parent entity of a type definition, if any - + - Determine if a type is a delegate type + Used during codegen to hold the ILX representation indicating how to access the type - + - Determine if a reference to a type definition is an interface type + The stable path to the type, e.g. Microsoft.FSharp.Core.FSharpFunc`2 - + - Get the rank of an array type + The stable path to the type, e.g. Microsoft.FSharp.Core.FSharpFunc`2 - + - Get the element type of an array type + This field is used when the 'tycon' is really a module definition. It holds statically nested type definitions and nested modules - + - Determine if a type is the System.Void type + The methods and properties of the type - + - Determine if a type is the System.Object type + The declared representation of the type, i.e. record, union, class etc. - + - Determine if a type is the F# unit type + The declared attributes for the type - + - Determine the rank of one of the artifical type definitions used for array types + The declaration location for the type constructor - + - Check if a type definition is one of the artifical type definitions used for array types of different ranks + The name of the type, possibly with `n mangling - + - Build an array type of the given rank + The unique stamp of the "tycon blob". Note the same tycon in signature and implementation get different stamps - + - Get the element type of an F# list type + The declared type parameters of the type - + - Get the element type of an array type + The XML documentation sig-string of the entity, if any, to use to lookup an .xml doc file. This also acts + as a cache for this sig-string computation. - + - Determine if a type is a single-dimensional array type + The XML documentation sig-string of the entity, if any, to use to lookup an .xml doc file. This also acts + as a cache for this sig-string computation. - + - Determine if a type is any kind of array type + The XML documentation of the entity, if any. If the entity is backed by provided metadata + then this _does_ include this documentation. If the entity is backed by Abstract IL metadata + or comes from another F# assembly then it does not (because the documentation will get read from + an XML file). - + - Determine if a type is a nominal .NET type + Get the union cases and other union-type information for a type, if any - + - Determine if a type is an F# list type + Get the union cases for a type, if any, as a list - + - Determine if a type is the System.String type + Get the union cases for a type, if any - + - Extract metadata from a type + The information about the r.h.s. of a type definition, if any. For example, the r.h.s. of a union or record type. - + - Extract metadata from a type definition + Get the value representing the accessibility of the r.h.s. of an F# type definition. - + - Build an PrintFormat type + The kind of the type definition - is it a measure definition or a type definition? - + - Build an Lazy type + The logical contents of the entity when it is a type definition. - + - Build an IObserver type + Get the type abbreviated by this type definition, if it is an F# type abbreviation definition - + - Build an IObservable type + Get the type parameters for an entity that is a type declaration, otherwise return the empty list. - + - Build an IEvent type + These two bits represents the on-demand analysis about whether the entity has the IsReadOnly attribute - + - Take apart an IDelegateEvent type + The on-demand analysis about whether the entity has the IsByRefLike attribute - + - Determine if a type is an IDelegateEvent type + These two bits represents the on-demand analysis about whether the entity is assumed to be a readonly struct - + - Try to take apart a System.Linq.Expression type + Get a list of all instance fields for F#-defined record, struct and class fields in this type definition, + excluding compiler-generate fields. - + - Take apart a System.Linq.Expression type + Get a list of all fields for F#-defined record, struct and class fields in this type definition, + including static fields, but excluding compiler-generate fields. - + - Determine if a type is a System.Linq.Expression type + A unique stamp for this module, namespace or type definition within the context of this compilation. + Note that because of signatures, there are situations where in a single compilation the "same" + module, namespace or type may have two distinct Entity objects that have distinct stamps. - + - Try to take apart an option type + The code location where the module, namespace or type is defined. - + - Take apart an option type + Get a blob of data indicating how this type is nested in other namespaces, modules or types. - + - Determine is a type is an option type + Indicates if we have pre-determined that a type definition has a default constructor. - + - Build a single-dimensional array type + The logical contents of the entity when it is a module or namespace fragment. - + - Build a 'voidptr' type + Gets the immediate members of an F# type definition, excluding compiler-generated ones. + Note: result is alphabetically sorted, then for each name the results are in declaration order - + - Build a nativeptr type + Gets all immediate members of an F# type definition keyed by name, including compiler-generated ones. + Note: result is a indexed table, and for each name the results are in reverse declaration order - + - Fold over all the expressions in an expression + The name of the namespace, module or type, possibly with mangling, e.g. List`1, List or FailureException - + - Fold over all the expressions in an implementation file + Indicate if this is a type whose r.h.s. is known to be a union type definition. - + - The empty set of actions for folding over expressions + Indicates if this entity is an F# type abbreviation definition - + - COmbine two static-resolution requirements on a type parameter + Indicates if this is an F# type definition whose r.h.s. is known to be a record type definition that is a value type. - + - Make an application expression, doing beta reduction by introducing let-bindings + Indicates if this is a struct or enum type definition, i.e. a value type definition - + - Given a lambda expression, adjust it to have be one or two lambda expressions (fun a -> (fun b -> ...)) - where the first has the given arity. + Indicates if this is an F# type definition whose r.h.s. is known to be a record type definition. - + - Given a lambda expression taking multiple variables, build a corresponding lambda taking a tuple + Indicates if the entity is a provided namespace fragment - + - Work out what things on the right-han-side of a 'let rec' recursive binding need to be fixed up + Indicates if the entity is a generated provided type definition, i.e. not erased. - + - Make a 'match' expression without applying any peep-hole optimizations. + Indicates if the entity is an erased provided type definition - + - Make a 'match' expression applying some peep-hole optimizations along the way, e.g to - pre-decide the branch taken at compile-time. + Indicates if the entity is a provided type or namespace definition - + - Accumulate the targets actually used in a decision graph (for reporting warnings) + Indicates the type prefers the "tycon<a, b>" syntax for display etc. - + - Build an exression representing the read of an instance class or record field. - First take the address of the record expression if it is a struct. + Indicates if the entity is a namespace - + - Build an expression to take the address of a local - &localv + Indicates the Entity is actually a module or namespace, not a type definition - + - Build an expression to dereference a local pointer - *localv_ptr + Indicates if the entity is an F# module definition - + - Build an expression to mutate the contents of a local pointer - *localv_ptr = e + Indicates if this is an F# type definition which is one of the special types in FSharp.Core.dll like 'float<_>' which + defines a measure type with a relation to an existing non-measure type as a representation. - + - Build an expression to mutate a local - localv <- e + Indicates if the entity is linked to backing data. Only used during unpickling of F# metadata. - + - Build the application of a generic construct to a set of type arguments. - Reduce the application via substitution if the function value is a typed lambda expression. + Indicate if this is a type definition backed by Abstract IL metadata. - + - Build the application of a (possibly generic, possibly curried) function value to a set of type and expression arguments. - Reduce the application via let-bindings if the function value is a lambda expression. + Indicates if this is a .NET-defined struct or enum type definition, i.e. a value type definition - + - Build the application of a (possibly generic, possibly curried) function value to a set of type and expression arguments + Indicates if this is a .NET-defined enum type definition - + - Adjust marks in expressions, replacing all marks by thegiven mark. - Used when inlining. + Indicates if this is an F# type definition whose r.h.s. definition is unknown (i.e. a traditional ML 'abstract' type in a signature, + which in F# is called a 'unknown representation' type). - + - Determine if a record field is hidden by a signature + Indicates if this is an F#-defined struct or enum type definition, i.e. a value type definition - + - Determine if a member, function or value is hidden by a signature + Indicates if this is an F# type definition whose r.h.s. is known to be some kind of F# object model definition - + - Determine if the representation of a type definition is hidden by a signature + Indicates if this is an F#-defined interface type definition - + - Determine if a type definition is hidden by a signature + Indicates if this is an F#-defined enum type definition - + - Make a remapping table for viewing a module or namespace 'from the outside' + Indicates if this is an F#-defined delegate type definition - + - Make the substitution (remapping) table for viewing a module or namespace 'from the outside' - - Given the top-most signatures constrains the public compilation units - of an assembly, compute a remapping that converts local references to non-local references. - This remapping must be applied to all pickled expressions and types - exported from the assembly. + Indicates if this is an F#-defined class type definition - + - Given a value definition, try to produce a reference to that value. Fails for local values. + Indicates if the entity represents an F# exception declaration. - + - Given a namespace, module or type definition, try to produce a reference to that entity. + Indicates if the entity is erased, either a measure definition, or an erased provided type definition - + - Given an implementation, fetch its recorded signature + Indicates if this is an enum type definition - + - Wrap one module or namespace definition in a 'module M = ..' outer wrapper + Indicates if this is an F# type definition which is one of the special types in FSharp.Core.dll which uses + an assembly-code representation for the type, e.g. the primitive array type constructor. - + - Wrap one module or namespace definition in a 'namespace N' outer wrapper + Gets the immediate interface definitions of an F# type definition. Further interfaces may be supported through class and interface inheritance. - + - Wrap one module or namespace implementation in a 'namespace N' outer wrapper + Gets the immediate interface types of an F# type definition. Further interfaces may be supported through class and interface inheritance. - + - Compute the hiding information that corresponds to the hiding applied at an assembly boundary + The identifier at the point of declaration of the type definition. - + - Compute the remapping information implied by an explicit signature being given for an inferred signature + Get the Abstract IL metadata for this type definition, assuming it is backed by Abstract IL metadata. - + - Compute the remapping information implied by a signature being inferred for a particular implementation + Get the Abstract IL scope, nesting and metadata for this + type definition, assuming it is backed by Abstract IL metadata. - + - Instantiate the generic type parameters in an expression, building a new one + Indicates if we have pre-determined that a type definition has a self-referential constructor using 'as x' - + - Instantiate the generic type parameters in a method slot signature, building a new one + Gets any implicit hash/equals (with comparer argument) methods added to an F# record, union or struct type definition. - + - Copy a method slot signature, including new generic type parameters if the slot signature represents a generic method + Gets any implicit hash/equals methods added to an F# record, union or struct type definition. - + - Copy an entire implementation file using the given copying flags + Gets any implicit CompareTo (with comparer argument) methods added to an F# record, union or struct type definition. - + - Copy an entire expression using the given copying flags + Gets any implicit CompareTo methods added to an F# record, union or struct type definition. - + - Copy an entire module or namespace type using the given copying flags + Get the blob of information associated with an F# object-model type definition, i.e. class, interface, struct etc. - + - Remap a (possible generic) type using the given remapping substitution + The information about the r.h.s. of an F# exception definition, if any. - + - Remap an attribute using the given remapping substitution + The display name of the namespace, module or type with <_, _, _> added for generic types, plus static parameters if any - + - Remap an expression using the given remapping substitution + The display name of the namespace, module or type with <'T, 'U, 'V> added for generic types, plus static parameters if any - + - Remap a reference to a value using the given remapping substitution + The display name of the namespace, module or type, e.g. List instead of List`1, including static parameters if any - + - Remap a reference to a record field using the given remapping substitution + The display name of the namespace, module or type, e.g. List instead of List`1, and no static parameters - + - Remap a reference to a union case using the given remapping substitution + Demangle the module name, if FSharpModuleWithSuffix is used - + - Remap a reference to a type definition using the given remapping substitution + The range in the implementation, adjusted for an item in a signature - + - Mutate a value to indicate it should be considered a local rather than a module-bound definition + Gets the data indicating the compiled representation of a named type or module in terms of Abstract IL data structures. - + - Given a lambda binding, extract the ValReprInfo for its arguments and other details + Gets the data indicating the compiled representation of a type or module in terms of Abstract IL data structures. - + - Given a lambda expression, extract the ValReprInfo for its arguments and other details + Get the cache of the compiled ILTypeRef representation of this module or type. - + - Given a (curried) lambda expression, pull off its arguments + The compiled name of the namespace, module or type, e.g. FSharpList`1, ListModule or FailureException - + - Compute the type of an expression from the expression itself + Get a blob of data indicating how this type is nested inside other namespaces, modules and types. - + - Check if a set of free variables are all public + Get a blob of data indicating how this type is nested inside other namespaces, modules and types. - + - Check if a set of free type variables are all public + The F#-defined custom attributes of the entity, if any. If the entity is backed by Abstract IL or provided metadata + then this does not include any attributes from those sources. - + - Get the free variables in the right hand side of a binding. + Get a list of all instance fields for F#-defined record, struct and class fields in this type definition. + including hidden fields from the compilation of implicit class constructions. - + - Get the free variables in an expression. + Gets all implicit hash/equals/compare methods added to an F# record, union or struct type definition. - + - Get the free variables in a module definition. + Get a list of fields for all the F#-defined record, struct and class fields in this type definition, including + static fields, 'val' declarations and hidden fields from the compilation of implicit class constructions. - + - A unique qualified name for each type definition, used to qualify the names of interface implementation methods + Get an array of fields for all the F#-defined record, struct and class fields in this type definition, including + static fields, 'val' declarations and hidden fields from the compilation of implicit class constructions. - + - Return the full text for an item as we want it displayed to the user as a fully qualified entity + Get a table of fields for all the F#-defined record, struct and class fields in this type definition, including + static fields, 'val' declarations and hidden fields from the compilation of implicit class constructions. - + - Returns (parentTypars,memberParentTypars,memberMethodTypars,memberToParentInst,tinst) + Get the value representing the accessibility of an F# type definition or module. - + - Returns (parentTypars,memberParentTypars,memberMethodTypars,memberToParentInst,tinst) + Get the type parameters for an entity that is a type declaration, otherwise return the empty list. + + Lazy because it may read metadata, must provide a context "range" in case error occurs reading metadata. - + - Returns (parentTypars,memberParentTypars,memberMethodTypars,memberToParentInst,tinst) + Sets the structness of a record or union type definition - + - Try to get a TyconRef for a type without erasing type abbreviations + Set the on-demand analysis about whether the entity has the IsReadOnly attribute - + - See through F# exception abbreviations + Set the on-demand analysis about whether the entity has the IsByRefLike attribute - + - set bool to 'true' to allow shortcutting of type parameter equation chains during stripping + Set the on-demand analysis about whether the entity is assumed to be a readonly struct - + - Equality for value references + Set the custom attributes on an F# type definition. - + - Equality for type definition references + Create a new entity with empty, unlinked data. Only used during unpickling of F# metadata. - + - An ordering for type parameters, based on stamp + Create a new entity with the given backing data. Only used during unpickling of F# metadata. - + - An ordering for record fields, based on stamp + Link an entity based on empty, unlinked data to the given data. Only used during unpickling of F# metadata. - + - An ordering for type definitions, based on stamp + Get a union case of a type by name - + - An ordering for value definitions, based on stamp + Get a field by name. - + - Take the address of an expression, or force it into a mutable local. Any allocated - mutable local may need to be kept alive over a larger expression, hence we return - a wrapping function that wraps "let mutable loc = Expr in ..." around a larger - expression. + Get a field by index in definition order - + - Helper to take the address of an expression + Represents a type definition, exception definition, module definition or namespace definition. - + - If it is a tuple type, ensure it's outermost type is a .NET tuple type, otherwise leave unchanged + Field used when the 'tycon' is really an exception definition - + - Evaluate the AnonRecdTypeInfo to work out if it is a struct or a ref. + Indicates how visible is the entity is. - + - Evaluate the TupInfo to work out if it is a struct or a ref. Currently this is very simple - but TupInfo may later be used carry variables that infer structness. + The declared accessibility of the representation, not taking signatures into account - + - Make a TAST expression representing getting an item fromm a tuple + If non-None, indicates the type is an abbreviation for another type. - + - Convert from F# tuple creation expression to .NET tuple creation expressions + The XML document signature for this entity - + - Convert from F# tuple types to .NET tuple types. + The declared documentation for the type or module - + - Get a TyconRef for a .NET tuple type + If this field is populated, this is the implementation range for an item in a signature, otherwise it is + the signature range for an item in an implementation - + - Check if a TyconRef is for a .NET tuple type. Currently this includes Tuple`1 even though - that' not really part of the target set of TyconRef used to represent F# tuples. + The name of the type, possibly with `n mangling - + - The number of fields in the largest tuple before we start encoding, i.e. 7 + String 'Module' off an F# module name, if FSharpModuleWithSuffix is used - + - The largest tuple before we start encoding, i.e. 7 + The information ILXGEN needs about the location of an item - + - Make an expression that gets the address of an element in an array + A public path records where a construct lives within the global namespace + of a CCU. - + - Make an expression that sets an instance field in an F# exception value + Indicates that a 'module' is really a namespace - + - Make an expression that gets an instance field from an F# exception value + Indicates that a module is compiled to a class with the same name as the original module - + - Like mkUnionCaseFieldGetUnprovenViaExprAddr, but for struct-unions, the input should be a copy of the expression. + Indicates that a module is compiled to a class with the "Module" suffix added. - + - Build a 'TOp.UnionCaseFieldSet' expression. For ref-unions, the input expression has 'TType_ucase', which is - an F# compiler internal "type" corresponding to the union case. For struct-unions, - the input should be the address of the expression. + These two bits represents the on-demand analysis about whether the entity has the IsReadOnly attribute - + - Build a 'TOp.UnionCaseFieldGetAddr' expression for a field of a union when we've already determined the value to be a particular union case. For ref-unions, - the input expression has 'TType_ucase', which is an F# compiler internal "type" corresponding to the union case. For struct-unions, - the input should be the address of the expression. + These two bits represents the on-demand analysis about whether the entity has the IsByRefLike attribute - + - Build a 'TOp.UnionCaseFieldGetAddr' expression for a field of a union when we've already determined the value to be a particular union case. For ref-unions, - the input expression has 'TType_ucase', which is an F# compiler internal "type" corresponding to the union case. For struct-unions, - the input should be the address of the expression. + These two bits represents the on-demand analysis about whether the entity is assumed to be a readonly struct - + - Build a 'TOp.UnionCaseFieldGet' expression for something we've already determined to be a particular union case. For ref-unions, - the input expression has 'TType_ucase', which is an F# compiler internal "type" corresponding to the union case. For struct-unions, - the input should be the address of the expression. + This bit is reserved for us in the pickle format, see pickle.fs, it's being listed here to stop it ever being used for anything else - + - Make a 'TOp.UnionCaseProof' expression, which proves a union value is over a particular case (used only for ref-unions, not struct-unions) + Get the flags as included in the F# binary metadata - + - Make an expression that gets the tag of a union value (via the address of the value if it is a struct) + This bit represents a F# record that is a value type, or a struct record. - + - Make an expression that sets an instance the field of a record or class (via the address of the value if it is a struct) + Indicates the type prefers the "tycon<a, b>" syntax for display etc. - + - Make an expression that gets the address of a static field in a record or class + Indicates the Entity is actually a module or namespace, not a type definition - + - Make an expression that sets a static field in a record or class + Adjust the on-demand analysis about whether the entity has the IsReadOnly attribute - + - Make an expression that gets a static field from a record or class + Adjust the on-demand analysis about whether the entity has the IsByRefLike attribute - + - Make an expression that gets the address of an instance field from a record or class (via the address of the value if it is a struct) + Adjust the on-demand analysis about whether the entity is assumed to be a readonly struct - + - Make an expression that gets an instance field from a record or class (via the address of the value if it is a struct) + Encode entity flags into a bit field. We leave lots of space to allow for future expansion. - + - Make an expression that gets an item from an anonymous record (via the address of the value if it is a struct) + Indicates if the type variable has a static "head type" requirement, i.e. ^a variables used in FSharp.Core and member constraints. - + - Make an expression that gets an item from an anonymous record + Indicates if the type variable can be solved or given new constraints. The status of a type variable + generally always evolves towards being either rigid or solved. - + - Make an expression that gets an item from a tuple + Get the flags as included in the F# binary metadata. We pickle this as int64 to allow for future expansion - + - Make an expression that re-raises an exception via a library call + Indicates whether a type variable can be instantiated by types or units-of-measure. - + - Make an expression that re-raises an exception + Indicates if the type inference variable was generated after an error when type checking expressions or patterns - + - Make an expression that coerces one expression to another type + Indicates if the type variable is compiler generated, i.e. is an implicit type inference variable - + - Make an expression that is IL assembly code + Indicates that whether this type parameter is a compat-flex type parameter (i.e. where "expr :> tp" only emits an optional warning) - + - Make an expression that constructs an exception value + Indicates that whether or not a generic type definition satisfies the equality constraint is dependent on whether this type variable satisfies the equality constraint. - + - Make an expression that constructs a union case, e.g. 'Some(expr)' + Indicates if a type parameter is needed at runtime and may not be eliminated - + - Make an out-byref type with an out kind parameter + Indicates that whether or not a generic type definition satisfies the comparison constraint is dependent on whether this type variable satisfies the comparison constraint. - + - Make a in-byref type with a in kind parameter + Encode typar flags into a bit field - + - Make a byref type with a in/out kind inference parameter + Indicates the type parameter derives from an '_' anonymous type + For units-of-measure, we give a warning if this gets solved to '1' - + - Make a byref type + Indicates the type parameter is an inference variable may be solved - + - Make the expression corresponding to 'expr1 || expr2' + Indicates we give a warning if the type parameter is ever solved - + - Make the expression corresponding to 'expr1 && expr2' + Indicates the type parameter can't be solved, but the variable is not set to "rigid" until after inference is complete - + - Test if the type parameter is one of those being generalized by a type scheme. + Indicates the type parameter can't be solved - + - Make the right-hand side of a generalized binding, incorporating the generalized generic parameters from the type - scheme into the right-hand side as type generalizations. + Indicates if the type variable can be solved or given new constraints. The status of a type variable + evolves towards being either rigid or solved. - + - Make a let-rec expression that locally binds values to expressions where self-reference back to the values is possible. + Represents the kind of a type parameter - + - Make a set of bindings that bind values to expressions in an "invisible" way. - Invisible bindings are not given a sequence point and should not have side effects. + Get the flags as included in the F# binary metadata - + - Make a binding that binds a value to an expression in an "invisible" way. - Invisible bindings are not given a sequence point and should not have side effects. + Flags on values - + - Make a let-expression that locally binds a value to an expression in an "invisible" way. - Invisible bindings are not given a sequence point and should not have side effects. + Indicates the 'this' value specified in a memberm e.g. 'x' in 'member x.M() = 1' - + - Make a let-expression that locally binds a compiler-generated value to an expression, where the expression - is returned by the given continuation. Compiler-generated bindings do not give rise to a sequence point in debugging. + Indicates a normal value - + - Make a let-expression that locally binds a compiler-generated value to an expression. - Compiler-generated bindings do not give rise to a sequence point in debugging. + Indicates the value called 'base' available for calling base class members - + - Make a set of bindings that bind compiler generated values to corresponding expressions. - Compiler-generated bindings do not give rise to a sequence point in debugging. + Indicates a ref-cell holding 'this' or the implicit 'this' used throughout an + implicit constructor to access and set values - + - Make a binding that binds a function value to a lambda taking multiple arguments + Indicates the type parameter is needed at runtime and may not be eliminated - + - Build a user-level let expression + Indicates the type parameter is not needed at runtime and may be eliminated - + - Build a user-level value sequence of let bindings + Indicates if a type parameter is needed at runtime and may not be eliminated - + - Build a user-level value sequence of let bindings + The normal value for this flag when the value is not within its recursive scope - + - Build a user-level let-binding + Set while the value is within its recursive scope. The flag indicates if the value has been eagerly generalized and accepts generic-recursive calls - + - Build a user-level value binding + A flag associated with values that indicates whether the recursive scope of the value is currently being processed, and + if the value has been generalized or not as yet. - + - Build a 'try/finally' expression + Indicates the value must never be inlined by the optimizer - + - Build a 'try/with' expression + Indicates the value may optionally be inlined by the optimizer - + - Build a 'for' loop expression + Indicates the value is inlined but the .NET IL code for the function still exists, e.g. to satisfy interfaces on objects, but that it is also always inlined - + - Build a 'while' loop expression + Indicates the value must always be inlined and no .NET IL code is generated for the value/function - + - Build a lambda expression that corresponds to the implementation of a member + Returns true if the implementation of a value must always be inlined - + - Build an iterated generic (type abstraction + tupled+curried) lambda expression + Defines the typed abstract syntax intermediate representation used throughout the F# compiler. - + - Build an iterated (tupled+curried) lambda expression + Given (newPath, oldPath) replace oldPath by newPath in the TAccess. - + - Build an iterated (curried) lambda expression + Primitive routine to compare two ValRef's for equality. On the whole value identity is not particularly + significant in F#. However it is significant for + (a) Active Patterns + (b) detecting uses of "special known values" from FSharp.Core.dll, such as 'seq' + and quotation splicing + + Note this routine doesn't take type forwarding into account - + - Build an type-chose expression, indicating that a local free choice of a type variable + Primitive routine to compare two UnionCaseRef's for equality - + - Build an object expression + Primitive routine to compare two EntityRef's for equality + This takes into account the possibility that they may have type forwarders - + - Build a generic lambda expression (type abstraction) + This predicate tests if non-local resolution paths are definitely known to resolve + to different entities. All references with different named paths always resolve to + different entities. Two references with the same named paths may resolve to the same + entities even if they reference through different CCUs, because one reference + may be forwarded to another via a .NET TypeForwarder. - + - Build a lambda expression taking a single value + From Ref_private to Ref_nonlocal when exporting data. - + - Rebuild a lambda during an expression tree traversal + From Ref_private to Ref_nonlocal when exporting data. - + - Build a lambda expression taking multiple values + Make a reference to a union case for type in a module or namespace - + - Make a new mutable compiler-generated local value, 'let' bind it to an expression - 'invisibly' (no sequence point etc.), and build an expression to reference it + For dereferencing in the middle of a pattern - + - Make a new mutable compiler-generated local value and build an expression to reference it + Equality on CCU references, implemented as reference equality except when unresolved - + - Make a new compiler-generated local value and build an expression to reference it + Equality on value specs, implemented as reference equality - + - Make a new local value and build an expression to reference it + Equality on type variables, implemented as reference equality. This should be equivalent to using typarEq. - + - Build an expression corresponding to the use of a reference to a value + Metadata on values (names of arguments etc. - + - Build an expression corresponding to the use of a value - Note: try to use exprForValRef or the expression returned from mkLocal instead of this. + Memoization table to help minimize the number of ILSourceDocument objects we create - + - Build an if-then statement + Are we assuming all code gen is for F# interactive, with no static linking - + - Build a conditional expression that checks for non-nullness + For debugging - + - Build a conditional expression + For debugging - + - Build a conditional expression + For debugging - + - Add an if-then-else boolean conditional node into a decision tree + For debugging - + - Look for a use of an F# value, possibly including application of a generic thing to a set of type arguments + Represents an intrinsic value from FSharp.Core known to the compiler - + - Get the values for a set of bindings + Defines the global environment for all type checking. + + The environment (TcGlobals) are well-known types and values are hard-wired + into the compiler. This lets the compiler perform particular optimizations + for these types and values, for example emitting optimized calls for + comparison and hashing functions. - + - Ignore 'Expr.Link' in an expression + Represents metadata extracted from a nominal type - + - Module publication, used while compiling fslib. + A set of function parameters (visitor) for folding over expressions - + - Get the curried type corresponding to a lambda + The empty table representing no hiding - + - Get the curried type corresponding to a lambda + A set of tables summarizing the items hidden by a signature - + - Get the natural type of a single argument amongst a set of curried arguments + The list of corresponding modules, namespaces and type definitions - + - Build a curried function type + The list of corresponding values - + - Build a type-forall anonymous generic type if necessary + The empty table - + - Build a function type + The remapping that corresponds to a module meeting its signature + and also report the set of tycons, tycon representations and values hidden in the process. - + - Build a function type + OnlyCloneExprVals is a nasty setting to reuse the cloning logic in a mode where all + Tycon and "module/member" Val objects keep their identity, but the Val objects for all Expr bindings + are cloned. This is used to 'fixup' the TAST created by tlr.fs + + This is a fragile mode of use. It's not really clear why TLR needs to create a "bad" expression tree that + reuses Val objects as multiple value bindings, and its been the cause of several subtle bugs. - + - Reduce a type to its more anonical form subject to an erasure flag, inference equations and abbreviations + Indicate what should happen to value definitions when copying expressions - + - Check the equivalence of two units-of-measure + A flag to govern whether arity inference should be type-directed or syntax-directed when + inferring an arity from a lambda expression. - + - Check the equivalence of two types + Represents a combination of substitutions/instantiations where things replace other things during remapping - + - Check the equivalence of two types up to an erasure flag + Represents an instantiation where value references replace other value references - + - An exception representing a warning for a defensive copy of an immutable struct + Represents an instantiation where type definition references replace other type definition references - + - Debug layout for class and record fields + Represents an instantiation where types replace type parameters - + - Debug layout for a list of implementation files + The empty map - + - Debug layout for an implementation file + Make a new map, containing a entries for the given type definitions - + - Debug layout for a decision tree + Fetch the entries for the given type definition - + - Debug layout for a type definition + Make a new map, containing a new entry for the given type definition - + - Debug layout for an expression + Maps TyconRef to list of T based on stamp keys - + - Debug layout for a binding of an expression to a value + Get the entry for the given type definition - + - Debug layout for the type of a value + Determine if the map is empty - + - Debug layout for a module or namespace definition + The empty map - + - Debug layout for the type signature of a module or namespace definition + Try to find the entry for the given type definition - + - Debug layout for a method slot signature + Remove the entry for the given type definition, if any - + - Debug layout for a type + Make a new map, containing entries for the given type definitions - + - Debug layout for a set of type parameters + Determine is the map contains an entry for the given type definition - + - Debug layout for a type parameter + Make a new map, containing a new entry for the given type definition - + - Debug layout for a trait constraint + Maps TyconRef to T based on stamp keys - + - Debug layout for a type parameter definition + Get the entry for the given type parameter - + - Debug layout for a value definition + The empty map - + - Debug layout for an integer + Try to find the entry for the given type parameter - + - Debug layout for an value definition at its binding site + Determine is the map contains an entry for the given type parameter - + - Debug layout for a reference to a union case + Make a new map, containing a new entry for the given type parameter - + - Debug layout for a reference to a value + Maps type parameters to entries based on stamp keys - + - Convert an expression to a string for debugging purposes + Maps Val's to list of T based on stamp keys - + - Convert a type to a string for debugging purposes + Mutable data structure mapping Val's to T based on stamp keys - + - A global flag indicating whether debug output should include ranges + Maps Val to T, based on stamps - + - Layout for internal compiler debugging purposes + TypeScheme (generalizedTypars, tauTy) + + generalizedTypars -- the truly generalized type parameters + tauTy -- the body of the generalized type. A 'tau' type is one with its type parameters stripped off. - + - Utilities used in simplifying types for visual presentation + Finish the targets - + - Defines derived expression manipulation and construction functions. + Build the overall expression - + - A function to read a value from a given state + Add a new destination target - + - The type of state unpicklers read from + Add a new destination target that is an expression result - + - A function to pickle a value into a given stateful writer + Create a new builder - + - The type of state written to by picklers + Build decision trees imperatively - + - The assumptions that need to be fixed up + Add a label to use as the target for a goto - + - The data that uses a collection of CcuThunks internally + Recognise a try-finally expression - + - Like Fixup but loader may return None, in which case there is no fixup. + Recognise a try-catch expression - + - Represents deserialized data with a dangling set of CCU fixup thunks indexed by name + Recognise a for-loop expression - + - Deserialize an arbitrary object which may have holes referring to other compilation units + Recognise a while expression - + - Deserialize a TAST description of a compilation unit + Match expressions that are an application of a particular F# function value - + - Deserialize a TAST type + Determines types that are potentially known to satisfy the 'comparable' constraint and returns + a set of residual types that must also satisfy the constraint - + - Deserialize a TAST expression + Build for loops - + - Deserialize a TAST union case reference + Check if the type is a byref-like but not a byref. - + - Deserialize a TAST type reference + returns Some(assemblyName) for success - + - Deserialize a TAST value reference + Try to find the AttributeUsage attribute, looking for the value of the AllowMultiple named parameter - + - Deserialize a TAST constant + Try to find a specific attribute on a type definition - + - Deserialize a namemap + Try to find a specific attribute on a type definition, where the attribute accepts a bool argument. - + - Deserialize an array of values + Try to find a specific attribute on a type definition, where the attribute accepts a string argument. + + This is used to detect the 'DefaultMemberAttribute' and 'ConditionalAttribute' attributes (on type definitions) - + - Deserialize a tuple + Create the expression 'expr.Value' for an option-typed expression - + - Deserialize a tuple + Create the expression 'None' for an option-type - + - Deserialize a tuple + Create the expression 'Some(expr)' - + - Deserialize a lazy value (eagerly) + Create the expression 'headExpr :: tailExpr' - + - Deserialize a string + Create the expression '[]' for a list type - + - Deserialize an integer + Create the union case 'Some(expr)' for an option type - + - Deserialize a bool + Create the union case 'None' for an option type - + - Deserialize a byte + Create the Nullable type for a given element type - + - Serialize an arbitrary object using the given pickler + Create the option type for a given element type - + - Serialize a TAST description of a compilation unit + Create the list type for a given element type - + - Serialize a TAST type + Create the IEnumerator type for a given element type - + - Serialize a TAST expression + Create the IEnumerable (seq) type for a given element type - + - Serialize a TAST union case reference + Create the FSharpRef type for a given element type - + - Serialize a TAST type or entity reference + Get the element type of an FSharpRef type - + - Serialize a TAST value reference + Check if a type is an FSharpRef type - + - Serialize a TAST constant + Matches any byref type, yielding the target type - + - Serialize a namemap of data + An active pattern to transform System.Nullable types to their input, otherwise leave the input unchanged - + - Serialize an array of data + An active pattern to match System.Nullable types - + - Serialize a tuple of data + An active pattern to determine if a type is a nominal type, possibly instantiated - + - Serialize a tuple of data + For "type Class as self", 'self' is fixed up after initialization. To support this, + it is converted behind the scenes to a ref. This function strips off the ref and + returns the underlying type. - + - Serialize a tuple of data + Determine if a type is a struct, record or union type - + - Serialize a lazy value (eagerly) + Determine if a type is an enum type - + - Serialize a string + Determine if a type is a class type - + - Serialize an integer + Determine if a type is an unmanaged type - + - Serialize a boolean value + Determine if a type is a struct type - + - Serialize a byte + If the input type is an enum type, then convert to its underlying type, otherwise return the input type - + - Defines the framework for serializing and de-serializing TAST data structures as binary blobs for the F# metadata format. + Determine the underlying type of an enum type (normally int32) - + - The TcGlobals for the import context + Determine if a type is a ComInterop type - + - The AssemblyLoader for the import context + Determine if a type is a sealed type - + - Represents a context used for converting AbstractIL .NET and provided types to F# internal compiler data structures. - Also cache the conversion of AbstractIL ILTypeRef nodes, based on hashes of these. - - There is normally only one ImportMap for any assembly compilation, though additional instances can be created - using tcImports.GetImportMap() if needed, and it is not harmful if multiple instances are used. The object - serves as an interface through to the tables stored in the primary TcImports structures defined in CompileOps.fs. + Determine if a type is a FSharpRef type - + - Record a root for a [<Generate>] type to help guide static linking & type relocation + Determine if a type is an interface type - + - Get a flag indicating if an assembly is a provided assembly, plus the - table of information recording remappings from type names in the provided assembly to type - names in the statically linked, embedded assembly. + Determine if a type is a delegate type - + - Resolve an Abstract IL assembly reference to a Ccu + Determine if a reference to a type definition is an interface type - + - Represents an interface to some of the functionality of TcImports, for loading assemblies - and accessing information about generated provided assemblies. + Get the rank of an array type - + - Import the type forwarder table for an IL assembly + Get the element type of an array type - + - Import an IL assembly as a new TAST CCU + Determine if a type is the System.Void type - + - Import a set of Abstract IL generic parameter specifications as a list of new F# generic parameters. + Determine if a type is the System.Object type - + - Import a provided method reference as an Abstract IL method reference + Determine if a type is the F# unit type - + - Import a provided type as an AbstractIL type + Determine the rank of one of the artificial type definitions used for array types - + - Import a provided type reference as an F# type TyconRef + Check if a type definition is one of the artificial type definitions used for array types of different ranks - + - Import a provided type as an F# type. + Build an array type of the given rank - + - Pre-check for ability to import an IL type as an F# type. + Get the element type of an F# list type - + - Import an IL type as an F# type. + Get the element type of an array type - + - Pre-check for ability to import a reference to a type definition, given an AbstractIL ILTypeRef, with caching + Determine if a type is a single-dimensional array type - + - Import a reference to a type definition, given an AbstractIL ILTypeRef, with caching + Determine if a type is any kind of array type - + - Functions to import .NET binary metadata as TAST objects + Determine if a type is a nominal .NET type - + - Represents the information about the compiled form of a method signature. Used when analyzing implementation - relations between members and abstract slots. + Determine if a type is an F# list type - + - An F# use of an event backed by provided metadata + Determine if a type is the System.String type - + - An F# use of an event backed by .NET metadata + Extract metadata from a type - + - An F# use of an event backed by F#-declared metadata + Extract metadata from a type definition - + - Get the intra-assembly XML documentation for the property. + Build an PrintFormat type - + - Get the TcGlobals associated with the object + Build an Lazy type - + - Get the 'remove' method associated with an event + Build an IObserver type - + - Indicates if the enclosing type for the event is a value type. - - For an extension event, this indicates if the event extends a struct type. + Build an IObservable type - + - Indicates if this property is static. + Build an IEvent type - + - Indicates if this is an extension member + Take apart an IDelegateEvent type - + - Indicates if this event has an associated XML comment authored in this assembly. + Determine if a type is an IDelegateEvent type - + - Get the logical name of the event. + Try to take apart a System.Linq.Expression type - + - Get the declaring type or module holding the method. - Note that C#-style extension properties don't exist in the C# design as yet. - If this is an F#-style extension method it is the logical module - holding the value for the extension method. + Take apart a System.Linq.Expression type - + - Try to get an arbitrary F# ValRef associated with the member. This is to determine if the member is virtual, amongst other things. + Determine if a type is a System.Linq.Expression type - + - Get the enclosing type of the event. - - If this is an extension member, then this is the apparent parent, i.e. the type the event appears to extend. + Take apart a System.Nullable type - + - Get the enclosing type of the method info, using a nominal type for tuple types + Try to take apart a System.Nullable type - + - Get the 'add' method associated with an event + Determine is a type is a System.Nullable type - + - Get the delegate type associated with the event. + Try to take apart an option type - + - Test whether two event infos have the same underlying definition. - Must be compatible with ItemsAreEffectivelyEqual relation. + Take apart an option type - + - Calculates a hash code of event info (similar as previous) - Must be compatible with ItemsAreEffectivelyEqual relation. + Determine if a type is an option type - + - Describes an F# use of an event + Build a single-dimensional array type - + - Get the declaring type of the event as an ILTypeRef + Build a 'voidptr' type - + - Get the ILMethInfo describing the 'remove' method associated with the event + Build a nativeptr type - + - Get the raw Abstract IL metadata for the event + Fold over all the expressions in an expression - + - Get the name of the event + Fold over all the expressions in an implementation file - + - Indicates if the property is static + The empty set of actions for folding over expressions - + - Get the declaring IL type of the event as an ILTypeInfo + Combine two static-resolution requirements on a type parameter - + - Get the enclosing ("parent"/"declaring") type of the field. + Make an application expression, doing beta reduction by introducing let-bindings - + - Get the ILMethInfo describing the 'add' method associated with the event + Given a lambda expression, adjust it to have be one or two lambda expressions (fun a -> (fun b -> ...)) + where the first has the given arity. - + - Describes an F# use of an event backed by Abstract IL metadata + Given a lambda expression taking multiple variables, build a corresponding lambda taking a tuple - + - An F# use of a property backed by provided metadata + Work out what things on the right-han-side of a 'let rec' recursive binding need to be fixed up - + - An F# use of a property backed by Abstract IL metadata + Make a 'match' expression without applying any peep-hole optimizations. - + - An F# use of a property backed by F#-declared metadata + Make a 'match' expression applying some peep-hole optimizations along the way, e.g to + pre-decide the branch taken at compile-time. - + - Get the intra-assembly XML documentation for the property. + Accumulate the targets actually used in a decision graph (for reporting warnings) - + - Get the TcGlobals associated with the object + Build an expression representing the read of an instance class or record field. + First take the address of the record expression if it is a struct. - + - Get a MethInfo for the 'setter' method associated with the property + Build an expression to take the address of a local + &localv - + - Get the logical name of the property. + Build an expression to dereference a local pointer + *localv_ptr - + - True if the getter (or, if absent, the setter) is a virtual method + Build an expression to mutate the contents of a local pointer + *localv_ptr = e - + - Indicates if the enclosing type for the property is a value type. - - For an extension property, this indicates if the property extends a struct type. + Build an expression to mutate a local + localv <- e - + - Indicates if this property is static. + Build the application of a generic construct to a set of type arguments. + Reduce the application via substitution if the function value is a typed lambda expression. - + - Indicates if the property is logically a 'newslot', i.e. hides any previous slots of the same name. + Build the application of a (possibly generic, possibly curried) function value to a set of type and expression arguments. + Reduce the application via let-bindings if the function value is a lambda expression. - + - Indicates if this property is an indexer property, i.e. a property with arguments. + Build the application of a (possibly generic, possibly curried) function value to a set of type and expression arguments - + - Indicates if this is an F# property compiled as a CLI event, e.g. a [<CLIEvent>] property. + Adjust marks in expressions, replacing all marks by the given mark. + Used when inlining. - + - Indicates if this is an extension member + Determine if a record field is hidden by a signature - + - Indicates if the getter (or, if absent, the setter) for the property is a dispatch slot. + Determine if a member, function or value is hidden by a signature - + - Indicates if this property is marked 'override' and thus definitely overrides another property. + Determine if the representation of a type definition is hidden by a signature - + - Indicates if this property has an associated setter method. + Determine if a type definition is hidden by a signature - + - Indicates if this property has an associated getter method. + Make a remapping table for viewing a module or namespace 'from the outside' - + - Indicates if this property has an associated XML comment authored in this assembly. + Make the substitution (remapping) table for viewing a module or namespace 'from the outside' + + Given the top-most signatures constrains the public compilation units + of an assembly, compute a remapping that converts local references to non-local references. + This remapping must be applied to all pickled expressions and types + exported from the assembly. - + - Get a MethInfo for the 'getter' method associated with the property + Given a value definition, try to produce a reference to that value. Fails for local values. - + - Return a new property info where there is no associated setter, only an associated getter. - - Property infos can combine getters and setters, assuming they are consistent w.r.t. 'virtual', indexer argument types etc. - When checking consistency we split these apart + Given a namespace, module or type definition, try to produce a reference to that entity. - + - Return a new property info where there is no associated getter, only an associated setter. + Given an implementation, fetch its recorded signature - + - Get the declaring type or module holding the method. - Note that C#-style extension properties don't exist in the C# design as yet. - If this is an F#-style extension method it is the logical module - holding the value for the extension method. + Wrap one module or namespace definition in a 'module M = ..' outer wrapper - + - Try to get an arbitrary F# ValRef associated with the member. This is to determine if the member is virtual, amongst other things. + Wrap one module or namespace definition in a 'namespace N' outer wrapper - + - Get the enclosing type of the property. - - If this is an extension member, then this is the apparent parent, i.e. the type the property appears to extend. + Wrap one module or namespace implementation in a 'namespace N' outer wrapper - + - Get the enclosing type of the method info, using a nominal type for tuple types + Compute the hiding information that corresponds to the hiding applied at an assembly boundary - + - Test whether two property infos have the same underlying definition. - Uses the same techniques as 'MethInfosUseIdenticalDefinitions'. - Must be compatible with ItemsAreEffectivelyEqual relation. + Compute the remapping information implied by an explicit signature being given for an inferred signature - + - Get the result type of the property + Compute the remapping information implied by a signature being inferred for a particular implementation - + - Get the types of the indexer parameters associated with the property + Instantiate the generic type parameters in an expression, building a new one - + - Get the names and types of the indexer parameters associated with the property - - If the property is in a generic type, then the type parameters are instantiated in the types returned. + Instantiate the generic type parameters in a method slot signature, building a new one - + - Get the details of the indexer parameters associated with the property + Copy a method slot signature, including new generic type parameters if the slot signature represents a generic method - + - Calculates a hash code of property info. Must be compatible with ItemsAreEffectivelyEqual relation. + Copy an entire implementation file using the given copying flags - + - Describes an F# use of a property + Copy an entire expression using the given copying flags - + - Get the TcGlobals governing this value + Copy an entire module or namespace type using the given copying flags - + - Gets the ILMethInfo of the 'set' method for the IL property + Remap a (possible generic) type using the given remapping substitution - + - Get the raw Abstract IL metadata for the IL property + Remap an attribute using the given remapping substitution - + - Get the name of the IL property + Remap an expression using the given remapping substitution - + - Indicates if the IL property is virtual + Remap a reference to a value using the given remapping substitution - + - Indicates if the IL property is static + Remap a reference to a record field using the given remapping substitution - + - Indicates if the IL property is logically a 'newslot', i.e. hides any previous slots of the same name. + Remap a reference to a union case using the given remapping substitution - + - Get the declaring IL type of the IL property, including any generic instantiation + Remap a reference to a type definition using the given remapping substitution - + - Indicates if the IL property has a 'set' method + Mutate a value to indicate it should be considered a local rather than a module-bound definition - + - Indicates if the IL property has a 'get' method + Given a lambda binding, extract the ValReprInfo for its arguments and other details - + - Gets the ILMethInfo of the 'get' method for the IL property + Given a lambda expression, extract the ValReprInfo for its arguments and other details - + - Get the apparent declaring type of the method as an F# type. - If this is a C#-style extension method then this is the type which the method - appears to extend. This may be a variable type. + Given a (curried) lambda expression, pull off its arguments - + - Like ApparentEnclosingType but use the compiled nominal type if this is a method on a tuple type + Compute the type of an expression from the expression itself - + - Get the return type of the IL property. - - Any type parameters of the enclosing type are instantiated in the type returned. + Check if a set of free variables are all public - + - Get the types of the indexer arguments associated with the IL property. - - Any type parameters of the enclosing type are instantiated in the type returned. + Check if a set of free type variables are all public - + - Get the names and types of the indexer arguments associated with the IL property. - - Any type parameters of the enclosing type are instantiated in the type returned. + Get the free variables in the right hand side of a binding. - + - Describes an F# use of a property backed by Abstract IL metadata + Get the free variables in an expression. - + - Get a reference to the F# metadata for the uninstantiated union case + Get the free variables in a module definition. - + - Get the F# metadata for the uninstantiated union case + A unique qualified name for each type definition, used to qualify the names of interface implementation methods - + - Get the list of types for the instantiation of the type parameters of the declaring type of the union case + Return the full text for an item as we want it displayed to the user as a fully qualified entity - + - Get a reference to the F# metadata for the declaring union type + Returns (parentTypars,memberParentTypars,memberMethodTypars,memberToParentInst,tinst) - + - Get the F# metadata for the declaring union type + Returns (parentTypars,memberParentTypars,memberMethodTypars,memberToParentInst,tinst) - + - Get the name of the union case + Returns (parentTypars,memberParentTypars,memberMethodTypars,memberToParentInst,tinst) - + - Get the instantiation of the type parameters of the declaring type of the union case + Try to get a TyconRef for a type without erasing type abbreviations - + - Describes an F# use of a union case + See through F# exception abbreviations - + - Get the generic instantiation of the declaring type of the field + set bool to 'true' to allow shortcutting of type parameter equation chains during stripping - + - Get a reference to the F# metadata for the F#-declared record, class or struct type + From typars to types - + - Get the F# metadata for the F#-declared record, class or struct type + Equality for value references - + - Get a reference to the F# metadata for the uninstantiated field + Equality for type definition references - + - Get the F# metadata for the uninstantiated field + An ordering for type parameters, based on stamp - + - Get the name of the field in an F#-declared record, class or struct type + An ordering for record fields, based on stamp - + - Indicate if the field is a literal field in an F#-declared record, class or struct type + An ordering for type definitions, based on stamp - + - Indicate if the field is a static field in an F#-declared record, class or struct type + An ordering for value definitions, based on stamp - + - Get the (instantiated) type of the field in an F#-declared record, class or struct type + Take the address of an expression, or force it into a mutable local. Any allocated + mutable local may need to be kept alive over a larger expression, hence we return + a wrapping function that wraps "let mutable loc = Expr in ..." around a larger + expression. - + - Get the enclosing (declaring) type of the field in an F#-declared record, class or struct type + Helper to take the address of an expression - + - Describes an F# use of a field in an F#-declared record, class or struct type + Helper to create an expression that dereferences an address. - + - Represents a single use of a field backed by provided metadata + If it is a tuple type, ensure it's outermost type is a .NET tuple type, otherwise leave unchanged - + - Represents a single use of a field backed by Abstract IL metadata + Evaluate the AnonRecdTypeInfo to work out if it is a struct or a ref. - + - Get the type instantiation of the declaring type of the field + Evaluate the TupInfo to work out if it is a struct or a ref. Currently this is very simple + but TupInfo may later be used carry variables that infer structness. - + - Get the scope used to interpret IL metadata + Make a TAST expression representing getting an item fromm a tuple - + - Indicates if the field is a literal field with an associated literal value + Convert from F# tuple creation expression to .NET tuple creation expressions - + - Indicates if the field is a member of a struct or enum type + Convert from F# tuple types to .NET tuple types. - + - Indicates if the field is static + Get a TyconRef for a .NET tuple type - + - Indicates if the field has the 'specialname' property in the .NET IL + Check if a TyconRef is for a .NET tuple type. Currently this includes Tuple`1 even though + that' not really part of the target set of TyconRef used to represent F# tuples. - + - Indicates if the field is readonly (in the .NET/C# sense of readonly) + The number of fields in the largest tuple before we start encoding, i.e. 7 - + - Get a reference to the declaring type of the field as an ILTypeRef + The largest tuple before we start encoding, i.e. 7 - + - Get the type of the field as an IL type + Make an expression that gets the address of an element in an array - + - Get an (uninstantiated) reference to the field as an Abstract IL ILFieldRef + Make an expression that sets an instance field in an F# exception value - + - Get the name of the field + Make an expression that gets an instance field from an F# exception value - + - Get the enclosing ("parent"/"declaring") type of the field. + Like mkUnionCaseFieldGetUnprovenViaExprAddr, but for struct-unions, the input should be a copy of the expression. - + - Tests whether two infos have the same underlying definition. - Must be compatible with ItemsAreEffectivelyEqual relation. + Build a 'TOp.UnionCaseFieldSet' expression. For ref-unions, the input expression has 'TType_ucase', which is + an F# compiler internal "type" corresponding to the union case. For struct-unions, + the input should be the address of the expression. - + - Get the type of the field as an F# type + Build a 'TOp.UnionCaseFieldGetAddr' expression for a field of a union when we've already determined the value to be a particular union case. For ref-unions, + the input expression has 'TType_ucase', which is an F# compiler internal "type" corresponding to the union case. For struct-unions, + the input should be the address of the expression. - + - Calculates a hash code of field info. Must be compatible with ItemsAreEffectivelyEqual relation. + Build a 'TOp.UnionCaseFieldGetAddr' expression for a field of a union when we've already determined the value to be a particular union case. For ref-unions, + the input expression has 'TType_ucase', which is an F# compiler internal "type" corresponding to the union case. For struct-unions, + the input should be the address of the expression. - + - Represents a single use of a IL or provided field from one point in an F# program + Build a 'TOp.UnionCaseFieldGet' expression for something we've already determined to be a particular union case. For ref-unions, + the input expression has 'TType_ucase', which is an F# compiler internal "type" corresponding to the union case. For struct-unions, + the input should be the address of the expression. - + - Describes a use of a method backed by provided metadata + Make a 'TOp.UnionCaseProof' expression, which proves a union value is over a particular case (used only for ref-unions, not struct-unions) - + - Describes a use of a pseudo-method corresponding to the default constructor for a .NET struct type + Make an expression that gets the tag of a union value (via the address of the value if it is a struct) - + - ILMeth(tcGlobals, ilMethInfo, extensionMethodPriority). - - Describes a use of a method backed by Abstract IL # metadata + Make an expression that sets an instance the field of a record or class (via the address of the value if it is a struct) - + - FSMeth(tcGlobals, enclosingType, valRef, extensionMethodPriority). - - Describes a use of a method declared in F# code and backed by F# metadata. + Make an expression that gets the address of a static field in a record or class - + - Get the XML documentation associated with the method + Make an expression that sets a static field in a record or class - + - Get the TcGlobals value that governs the method declaration + Make an expression that gets a static field from a record or class - + - Get the information about provided static parameters, if any + Make an expression that gets the address of an instance field from a record or class (via the address of the value if it is a struct) - + - Get a list of argument-number counts, one count for each set of curried arguments. - - For an extension member, drop the 'this' argument. + Make an expression that gets an instance field from a record or class (via the address of the value if it is a struct) - + - Get the method name in LogicalName form, i.e. the name as it would be stored in .NET metadata + Make an expression that gets an item from an anonymous record (via the address of the value if it is a struct) - + - Indicates if the enclosing type for the method is a value type. - - For an extension method, this indicates if the method extends a struct type. + Make an expression that gets an item from an anonymous record - + - Indicates if this method takes no arguments + Make an expression that gets an item from a tuple - + - Does the method appear to the user as an instance method? + Make an expression that re-raises an exception via a library call - + - Indicates if this is an F# extension member. + Make an expression that re-raises an exception - + - Check if this method is an explicit implementation of an interface member + Make an expression that coerces one expression to another type - + - Indicates if this method is a generated method associated with an F# CLIEvent property compiled as a .NET event + Make an expression that is IL assembly code - + - Indicates if this is an extension member. + Make an expression that constructs an exception value - + - Check if this method is marked 'override' and thus definitely overrides another method. + Make an expression that constructs a union case, e.g. 'Some(expr)' - + - Indicates if this is an C#-style extension member. + Make an out-byref type with an out kind parameter - + - Indicates if this is a method defined in this assembly with an internal XML comment + Make a in-byref type with a in kind parameter - + - Get the number of generic method parameters for a method. - For an extension method this includes all type parameters, even if it is extending a generic type. + Make a byref type with a in/out kind inference parameter - + - Get the formal generic method parameters for the method as a list of type variables. - - For an extension method this includes all type parameters, even if it is extending a generic type. + Make a byref type - + - Get the formal generic method parameters for the method as a list of variable types. + Make the expression corresponding to 'expr1 || expr2' - + - Get the extension method priority of the method, if it has one. + Make the expression corresponding to 'expr1 && expr2' - + - Get the extension method priority of the method. If it is not an extension method - then use the highest possible value since non-extension methods always take priority - over extension members. + Test if the type parameter is one of those being generalized by a type scheme. - + - Get the method name in DisplayName form + Make the right-hand side of a generalized binding, incorporating the generalized generic parameters from the type + scheme into the right-hand side as type generalizations. - + - Get the actual type instantiation of the declaring type associated with this use of the method. - - For extension members this is empty (the instantiation of the declaring type). + Make a let-rec expression that locally binds values to expressions where self-reference back to the values is possible. - + - Get the declaring type or module holding the method. If this is an C#-style extension method then this is the type - holding the static member that is the extension method. If this is an F#-style extension method it is the logical module - holding the value for the extension method. + Make a set of bindings that bind values to expressions in an "invisible" way. + Invisible bindings are not given a sequence point and should not have side effects. - + - Try to get an arbitrary F# ValRef associated with the member. This is to determine if the member is virtual, amongst other things. + Make a binding that binds a value to an expression in an "invisible" way. + Invisible bindings are not given a sequence point and should not have side effects. - + - Get the enclosing type of the method info. - - If this is an extension member, then this is the apparent parent, i.e. the type the method appears to extend. - This may be a variable type. + Make a let-expression that locally binds a value to an expression in an "invisible" way. + Invisible bindings are not given a sequence point and should not have side effects. - + - Get the enclosing type of the method info, using a nominal type for tuple types + Make a let-expression that locally binds a compiler-generated value to an expression, where the expression + is returned by the given continuation. Compiler-generated bindings do not give rise to a sequence point in debugging. - + - Tries to get the object arg type if it's a byref type. + Make a let-expression that locally binds a compiler-generated value to an expression. + Compiler-generated bindings do not give rise to a sequence point in debugging. - + - Indicates if this is an extension member (e.g. on a struct) that takes a byref arg + Make a set of bindings that bind compiler generated values to corresponding expressions. + Compiler-generated bindings do not give rise to a sequence point in debugging. - + - Tests whether two method infos have the same underlying definition. - Used to merge operator overloads collected from left and right of an operator constraint. - Must be compatible with ItemsAreEffectivelyEqual relation. + Make a binding that binds a function value to a lambda taking multiple arguments - + - Apply a type instantiation to a method info, i.e. apply the instantiation to the enclosing type. + Build a user-level let expression - + - Get the ParamData objects for the parameters of a MethInfo + Build a user-level value sequence of let bindings - + - Get the signature of an abstract method slot. + Build a user-level value sequence of let bindings - + - Get the parameter types of a method info + Build a user-level let-binding - + - Get the ParamData objects for the parameters of a MethInfo + Build a user-level value binding - + - Get the parameter attributes of a method info, which get combined with the parameter names and types + Build a 'try/finally' expression - + - Get the (zero or one) 'self'/'this'/'object' arguments associated with a method. - An instance method returns one object argument. + Build a 'try/with' expression - + - Select all the type parameters of the declaring type of a method. - - For extension methods, no type parameters are returned, because all the - type parameters are part of the apparent type, rather the - declaring type, even for extension methods extending generic types. + Build a 'for' loop expression - + - Get the return type of a method info, where 'void' is returned as 'unit' + Build a 'while' loop expression - + - Get the return type of a method info, where 'void' is returned as 'None' + Build a lambda expression that corresponds to the implementation of a member - + - Build IL method infos. + Build an iterated generic (type abstraction + tupled+curried) lambda expression - + - Build IL method infos for a C#-style extension method + Build an iterated (tupled+curried) lambda expression - + - Calculates a hash code of method info. Must be compatible with ItemsAreEffectivelyEqual relation. + Build an iterated (curried) lambda expression - + - Add the actual type instantiation of the apparent type of an F# extension method. + Build an type-chose expression, indicating that a local free choice of a type variable - + - Describes an F# use of a method + Build an object expression - + - ILMethInfo(g, ilApparentType, ilDeclaringTyconRefOpt, ilMethodDef, ilGenericMethodTyArgs) - - Describes an F# use of an IL method. - - If ilDeclaringTyconRefOpt is 'Some' then this is an F# use of an C#-style extension method. - If ilDeclaringTyconRefOpt is 'None' then ilApparentType is an IL type definition. + Build a generic lambda expression (type abstraction) - + - Get the Abstract IL metadata associated with the method. + Build a lambda expression taking a single value - + - Get the Abstract IL metadata corresponding to the parameters of the method. - If this is an C#-style extension method then drop the object argument. + Rebuild a lambda during an expression tree traversal - + - Get the number of parameters of the method + Build a lambda expression taking multiple values - + - Get the Abstract IL scope information associated with interpreting the Abstract IL metadata that backs this method. + Make a new mutable compiler-generated local value, 'let' bind it to an expression + 'invisibly' (no sequence point etc.), and build an expression to reference it - + - Indicates if the IL method is marked virtual. + Make a new mutable compiler-generated local value and build an expression to reference it - + - Does it appear to the user as a static method? + Make a new compiler-generated local value and build an expression to reference it - + - Indicates if the method has protected accessibility, + Make a new local value and build an expression to reference it - + - Does it have the .NET IL 'newslot' flag set, and is also a virtual? + Build an expression corresponding to the use of a reference to a value - + - Does it appear to the user as an instance method? + Build an expression corresponding to the use of a value + Note: try to use exprForValRef or the expression returned from mkLocal instead of this. - + - Indicates if the method is an extension method + Build an if-then statement - + - Indicates if the IL method is marked final. + Build a conditional expression that checks for non-nullness - + - Indicates if the method is a constructor + Build a conditional expression - + - Indicates if the method is a class initializer. + Build a conditional expression - + - Indicates if the IL method is marked abstract. + Add an if-then-else boolean conditional node into a decision tree - + - Get the IL name of the method + Look for a use of an F# value, possibly including application of a generic thing to a set of type arguments - + - Get a reference to the method (dropping all generic instantiations), as an Abstract IL ILMethodRef. + Get the values for a set of bindings - + - Get the declaring type associated with an extension member, if any. + Ignore 'Expr.Link' in an expression - + - Get the formal method type parameters associated with a method. + Module publication, used while compiling fslib. - + - Get the instantiation of the declaring type of the method. - If this is an C#-style extension method then this is empty because extension members - are never in generic classes. + Get the curried type corresponding to a lambda - + - Get the declaring type of the method. If this is an C#-style extension method then this is the IL type - holding the static member that is the extension method. + Get the curried type corresponding to a lambda - + - Get the apparent declaring type of the method as an F# type. - If this is a C#-style extension method then this is the type which the method - appears to extend. This may be a variable type. + Get the natural type of a single argument amongst a set of curried arguments - + - Like ApparentEnclosingType but use the compiled nominal type if this is a method on a tuple type + Build a curried function type - + - Indicates if the method is marked as a DllImport (a PInvoke). This is done by looking at the IL custom attributes on - the method. + Build a type-forall anonymous generic type if necessary - + - Get all the argument types of the IL method. Include the object argument even if this is - an C#-style extension method. + Build a function type - + - Get the argument types of the the IL method. If this is an C#-style extension method - then drop the object argument. + Build a function type - + - Get info about the arguments of the IL method. If this is an C#-style extension method then - drop the object argument. - - Any type parameters of the enclosing type are instantiated in the type returned. + Reduce a type to its more canonical form subject to an erasure flag, inference equations and abbreviations - + - Get the (zero or one) 'self'/'this'/'object' arguments associated with an IL method. - An instance extension method returns one object argument. + Check the equivalence of two units-of-measure - + - Get the F# view of the return type of the method, where 'void' is 'unit'. + Check the equivalence of two types - + - Get the compiled return type of the method, where 'void' is None. + Check the equivalence of two types up to an erasure flag - + - Describes an F# use of an IL method. + An exception representing a warning for a defensive copy of an immutable struct - + - ILTypeInfo (tyconRef, ilTypeRef, typeArgs, ilTypeDef). + Debug layout for class and record fields - + - Get the compiled nominal type. In the case of tuple types, this is a .NET tuple type + Debug layout for a list of implementation files - + - Describes an F# use of an IL type, including the type instantiation associated with the type at a particular usage point. - - This is really just 1:1 with the subset ot TType which result from building types using IL type definitions. + Debug layout for an implementation file - + - Full information about a parameter returned for use by the type checker and language service. + Debug layout for a decision tree - + - Partial information about a parameter returned for use by the Language Service + Debug layout for a type definition - + - The argument is optional, and is a caller-side .NET optional or default arg. - Note this is correctly termed caller side, even though the default value is optically specified on the callee: - in fact the default value is read from the metadata and passed explicitly to the callee on the caller side. + Debug layout for an expression - + - The argument is optional, and is an F# callee-side optional arg + Debug layout for a binding of an expression to a value - + - The argument is not optional + Debug layout for the type of a value - + - Compute the OptionalArgInfo for an IL parameter - - This includes the Visual Basic rules for IDispatchConstant and IUnknownConstant and optional arguments. + Debug layout for a module or namespace definition - + - Represents information about a parameter indicating if it is optional. + Debug layout for the type signature of a module or namespace definition - + - The caller-side value for the optional arg, if any + Debug layout for a method slot signature - + - Describes the sequence order of the introduction of an extension method. Extension methods that are introduced - later through 'open' get priority in overload resolution. + Debug layout for a type - + - Indicates whether we should visit multiple instantiations of the same generic interface or not + Debug layout for a set of type parameters - + - Indicates whether we can skip interface types that lie outside the reference set + Debug layout for a type parameter - + - Used to hide/filter members from super classes based on signature + Debug layout for a trait constraint - + - Used to hide/filter members from super classes based on signature + Debug layout for a type parameter definition - + - Used to hide/filter members from super classes based on signature + Debug layout for a value definition - + - Used to hide/filter members from super classes based on signature - Inref and outref parameter types will be treated as a byref type for equivalency. + Debug layout for an integer - + - Get the information about the compiled form of a method signature. Used when analyzing implementation - relations between members and abstract slots. + Debug layout for an value definition at its binding site - + - Strips inref and outref to be a byref. + Debug layout for a reference to a union case - + - Find the delegate type that an F# event property implements by looking through the type hierarchy of the type of the property - for the first instantiation of IDelegateEvent. + Debug layout for a reference to a value - + - Create an error object to raise should an event not have the shape expected by the .NET idiom described further below + Convert an expression to a string for debugging purposes - + - Properties compatible with type IDelegateEvent and attributed with CLIEvent are special: - we generate metadata and add/remove methods - to make them into a .NET event, and mangle the name of a property. - We don't handle static, indexer or abstract properties correctly. - Note the name mangling doesn't affect the name of the get/set methods for the property - and so doesn't affect how we compile F# accesses to the property. + Convert a type to a string for debugging purposes - + - Try to get an arbitrary ProvidedMethodInfo associated with a property. + A global flag indicating whether debug output should include ranges - + - Compute the ILFieldInit for the given provided constant value for a provided enum type. + Layout for internal compiler debugging purposes - + - Compute the OptionalArgInfo for a provided parameter. - - This is the same logic as OptionalArgInfoOfILParameter except we do not apply the - Visual Basic rules for IDispatchConstant and IUnknownConstant to optional - provided parameters. + Utilities used in simplifying types for visual presentation - + - Compute the ILFieldInit for the given provided constant value for a provided enum type. + same as PrettifyTypes, but allows passing the types along with a discriminant value + useful to prettify many types that need to be sorted out after prettifying operation + took place. - + - Work out the instantiation relevant to interpret the backing metadata for a property. + Defines derived expression manipulation and construction functions. - + - Work out the instantiation relevant to interpret the backing metadata for a member. - - The 'methTyArgs' is the instantiation of any generic method type parameters (this instantiation is - not included in the MethInfo objects, but carried separately). + A function to read a value from a given state - + - Combine the type instantiation and generic method instantiation + The type of state unpicklers read from - + - Get the object type for a member value which is a C#-style extension method + A function to pickle a value into a given stateful writer - + - Get the object type for a member value which is an extension method (C#-style or F#-style) + The type of state written to by picklers - + - Split the type of an F# member value into - - the type parameters associated with method but matching those of the enclosing type - - the type parameters associated with a generic method - - the return type of the method - - the actual type arguments of the enclosing type. + The assumptions that need to be fixed up - + - Construct the data representing the signature of an abstract method slot + The data that uses a collection of CcuThunks internally - + - Construct the data representing a parameter in the signature of an abstract method slot + Like Fixup but loader may return None, in which case there is no fixup. - + - The slotsig returned by methInfo.GetSlotSig is in terms of the type parameters on the parent type of the overriding method. - Reverse-map the slotsig so it is in terms of the type parameters for the overriding method + Represents deserialized data with a dangling set of CCU fixup thunks indexed by name - + - Get the return type of a provided method, where 'void' is returned as 'None' + Deserialize an arbitrary object which may have holes referring to other compilation units - + - Check if an F#-declared member value is an explicit interface member implementation + Deserialize a TAST description of a compilation unit - + - Check if an F#-declared member value is an 'override' or explicit member implementation + Deserialize a TAST type - + - Check if an F#-declared member value is a dispatch slot + Deserialize a TAST expression - + - Check if an F#-declared member value is a virtual method + Deserialize a TAST union case reference - + - Indicates if an F#-declared function or member value is a CLIEvent property compiled as a .NET event + Deserialize a TAST type reference - + - The constraints for each typar copied from another typar can only be fixed up once - we have generated all the new constraints, e.g. f<A :> List<B>, B :> List<A>> ... + Deserialize a TAST value reference - + - Copy constraints. If the constraint comes from a type parameter associated - with a type constructor then we are simply renaming type variables. If it comes - from a generic method in a generic class (e.g. ty.M<_>) then we may be both substituting the - instantiation associated with 'ty' as well as copying the type parameters associated with - M and instantiating their constraints - - Note: this now looks identical to constraint instantiation. + Deserialize a TAST constant - + - Get the return type of an IL method, taking into account instantiations for type, return attributes and method generic parameters, and - translating 'void' to 'None'. + Deserialize a namemap - + - Get the parameter type of an IL method. + Deserialize an array of values - + - Read an Abstract IL type from metadata, including any attributes that may affect the type itself, and convert to an F# type. + Deserialize a tuple - + - Read an Abstract IL type from metadata and convert to an F# type. + Deserialize a tuple - + - Check if a type exists somewhere in the hierarchy which has the given head type. + Deserialize a tuple - + - Check if a type exists somewhere in the hierarchy which has the same head type as the given type (note, the given type need not have a head type at all) + Deserialize a lazy value (eagerly) - + - Check if a type has a particular head type + Deserialize a string - + - Check if two types have the same nominal head type + Deserialize an integer - + - Get all interfaces of a type, including the type itself if it is an interface + Deserialize a bool - + - Get all super types of the type, including the type itself + Deserialize a byte - + - Search for one element where a function returns a 'Some' result, following interfaces + Serialize an arbitrary object using the given pickler - + - Search for one element satisfying a predicate, following interfaces + Serialize a TAST description of a compilation unit - + - Iterate, following interfaces. Skipping interfaces that lie outside the referenced assembly set is allowed. + Serialize a TAST type - + - Fold, following interfaces. Skipping interfaces that lie outside the referenced assembly set is allowed. + Serialize a TAST expression - + - Fold, do not follow interfaces (unless the type is itself an interface) + Serialize a TAST union case reference - + - Traverse the type hierarchy, e.g. f D (f C (f System.Object acc)). - Visit base types and interfaces first. + Serialize a TAST type or entity reference - + - Collect the set of immediate declared interface types for an F# type, but do not - traverse the type hierarchy to collect further interfaces. + Serialize a TAST value reference - + - Make a type for System.Collections.Generic.IList<ty> + Serialize a TAST constant - + - Get the base type of a type, taking into account type instantiations. Return None if the - type has no base type. + Serialize a namemap of data - + - Indicates if an F# type is the type associated with an F# exception declaration + Serialize an array of data - + - Import an IL type as an F# type. importInst gives the context for interpreting type variables. + Serialize a tuple of data - + - An exception type used to raise an error using the old error system. - - Error text: "A definition to be compiled as a .NET event does not have the expected form. Only property members can be compiled as .NET events." + Serialize a tuple of data - + - An AccessorDomain which returns all items + Serialize a tuple of data - + - An AccessorDomain which returns everything but .NET private/internal items. - This is used - - when solving member trait constraints, which are solved independently of accessibility - - for failure paths in error reporting, e.g. to produce an error that an F# item is not accessible - - an adhoc use in service.fs to look up a delegate signature + Serialize a lazy value (eagerly) - + - An AccessorDomain which returns public items + Serialize a string - + - AccessibleFrom(cpaths, tyconRefOpt) - - cpaths: indicates we have the keys to access any members private to the given paths - tyconRefOpt: indicates we have the keys to access any protected members of the super types of 'TyconRef' + Serialize an integer - + - Represents the 'keys' a particular piece of code can use to access other constructs?. + Serialize a boolean value - + - Uses a separate accessibility domains for containing type and method itself - This makes sense cases like - type A() = - type protected B() = - member this.Public() = () - member protected this.Protected() = () - type C() = - inherit A() - let x = A.B() - do x.Public() - when calling x.SomeMethod() we need to use 'adTyp' do verify that type of x is accessible from C - and 'ad' to determine accessibility of SomeMethod. - I.e when calling x.Public() and x.Protected() -in both cases first check should succeed and second - should fail in the latter one. + Serialize a byte - + - IndiCompute the accessibility of a provided member + Defines the framework for serializing and de-serializing TAST data structures as binary blobs for the F# metadata format. - + - Compute the accessibility of a provided member + The TcGlobals for the import context - + - Indicate if a provided member is accessible + The AssemblyLoader for the import context - + - Indicates if a type is accessible (both definition and instantiation) + Represents a context used for converting AbstractIL .NET and provided types to F# internal compiler data structures. + Also cache the conversion of AbstractIL ILTypeRef nodes, based on hashes of these. + + There is normally only one ImportMap for any assembly compilation, though additional instances can be created + using tcImports.GetImportMap() if needed, and it is not harmful if multiple instances are used. The object + serves as an interface through to the tables stored in the primary TcImports structures defined in CompileOps.fs. - + - Check that a type definition and its representation contents are accessible + Record a root for a [<Generate>] type to help guide static linking & type relocation - + - Indicates if a type definition and its representation contents are accessible + Get a flag indicating if an assembly is a provided assembly, plus the + table of information recording remappings from type names in the provided assembly to type + names in the statically linked, embedded assembly. - + - Check that an entity is accessible + Resolve an Abstract IL assembly reference to a Ccu - + - Indicates if an entity is accessible + Represents an interface to some of the functionality of TcImports, for loading assemblies + and accessing information about generated provided assemblies. - + - Indicates if an IL member associated with the given ILType is accessible + Import the type forwarder table for an IL assembly - + - Indicates if given IL based TyconRef is accessible. If TyconRef is nested then we'll - walk though the list of enclosing types and test if all of them are accessible + Import an IL assembly as a new TAST CCU - + - Indicates if a TyconRef is visible through the AccessibleFrom(cpaths, _). - Note that InternalsVisibleTo extends those cpaths. + Import a set of Abstract IL generic parameter specifications as a list of new F# generic parameters. - + - Indicates if tdef is accessible. If tdef.Access = ILTypeDefAccess.Nested then encTyconRefOpt s TyconRef of enclosing type - and visibility of tdef is obtained using member access rules + Import a provided method reference as an Abstract IL method reference - + - Indicates if an IL member is accessible (ignoring its enclosing type) + Import a provided type as an AbstractIL type - + - Indicates if an F# item is accessible + Import a provided type reference as an F# type TyconRef - + - The basic logic of private/internal/protected/InternalsVisibleTo/public accessibility + Import a provided type as an F# type. - + - Check the attributes on a record field, returning errors and warnings as data. + Pre-check for ability to import an IL type as an F# type. - + - Check the attributes on an F# value, returning errors and warnings as data. + Import an IL type as an F# type. - + - Check the attributes on a record field, returning errors and warnings as data. + Pre-check for ability to import a reference to a type definition, given an AbstractIL ILTypeRef, with caching - + - Check the attributes on a union case, returning errors and warnings as data. + Import a reference to a type definition, given an AbstractIL ILTypeRef, with caching - + - Check the attributes on an entity, returning errors and warnings as data. + Functions to import .NET binary metadata as TAST objects - + - Indicate if a property has 'Obsolete' or 'CompilerMessageAttribute'. - Used to suppress the item in intellisense. + Represents the information about the compiled form of a method signature. Used when analyzing implementation + relations between members and abstract slots. - + - Indicate if a method has 'Obsolete', 'CompilerMessageAttribute' or 'TypeProviderEditorHideMethodsAttribute'. - Used to suppress the item in intellisense. + An F# use of an event backed by provided metadata - + - Check the attributes associated with a method, returning warnings and errors as data. + An F# use of an event backed by .NET metadata - + - Check the attributes associated with a IL field, returning warnings and errors as data. + An F# use of an event backed by F#-declared metadata - + - Check the attributes associated with a property, returning warnings and errors as data. + Get the intra-assembly XML documentation for the property. - + - Indicate if a list of provided attributes contains 'ObsoleteAttribute'. Used to suppress the item in intellisense. + Get the TcGlobals associated with the object - + - Indicate if a list of F# attributes contains 'ObsoleteAttribute'. Used to suppress the item in intellisense. - Also check the attributes for CompilerMessageAttribute, which has an IsHidden argument that allows - items to be suppressed from intellisense. + Get the 'remove' method associated with an event - + - Indicate if a list of F# attributes contains 'ObsoleteAttribute'. Used to suppress the item in intellisense. + Indicates if the enclosing type for the event is a value type. + + For an extension event, this indicates if the event extends a struct type. - + - Checks the attributes for CompilerMessageAttribute, which has an IsHidden argument that allows - items to be suppressed from intellisense. + Indicates if this property is static. - + - Indicate if a list of IL attributes contains 'ObsoleteAttribute'. Used to suppress the item in intellisense. + Indicates if this is an extension member - + - Check a list of provided attributes for 'ObsoleteAttribute', returning errors and warnings as data + Indicates if this event has an associated XML comment authored in this assembly. - + - Check F# attributes for 'ObsoleteAttribute', 'CompilerMessageAttribute' and 'ExperimentalAttribute', - returning errors and warnings as data + Get the logical name of the event. - + - Check IL attributes for 'ObsoleteAttribute', returning errors and warnings as data + Get the declaring type or module holding the method. + Note that C#-style extension properties don't exist in the C# design as yet. + If this is an F#-style extension method it is the logical module + holding the value for the extension method. - + - Check if a method has a specific attribute. + Try to get an arbitrary F# ValRef associated with the member. This is to determine if the member is virtual, amongst other things. - + - Try to find a specific attribute on a method, where the attribute accepts a string argument. + Get the enclosing type of the event. - This is just used for the 'ConditionalAttribute' attribute + If this is an extension member, then this is the apparent parent, i.e. the type the event appears to extend. - + - Analyze three cases for attributes declared on methods: IL-declared attributes, F#-declared attributes and - provided attributes. + Get the enclosing type of the method info, using a nominal type for tuple types - + - Analyze three cases for attributes declared on methods: IL-declared attributes, F#-declared attributes and - provided attributes. + Get the 'add' method associated with an event - + - Analyze three cases for attributes declared on type definitions: IL-declared attributes, F#-declared attributes and - provided attributes. + Get the delegate type associated with the event. - + - Check custom attributes. This is particularly messy because custom attributes come in in three different - formats. + Test whether two event infos have the same underlying definition. + Must be compatible with ItemsAreEffectivelyEqual relation. - + - Logic associated with checking "ObsoleteAttribute" and other attributes - on items from name resolution + Calculates a hash code of event info (similar as previous) + Must be compatible with ItemsAreEffectivelyEqual relation. - + - The Invoke MethInfo, the function argument types, the function return type - and the overall F# function type for the function type associated with a .NET delegate type + Describes an F# use of an event - + - Get the item sets + Get the declaring type of the event as an ILTypeRef - + - Get an empty set of items + Get the ILMethInfo describing the 'remove' method associated with the event - + - Get the items with a particular name + Get the raw Abstract IL metadata for the event - + - Filter a set of new items to add according to the content of the list. Only keep an item - if it passes 'keepTest' for all matching items already in the list. + Get the name of the event - + - Add new items, extracting the names using the given function. + Indicates if the property is static - + - The input list is sorted from most-derived to least-derived type, so any System.Object methods - are at the end of the list. Return a filtered list where prior/subsequent members matching by name and - that are in the same equivalence class have been removed. We keep a name-indexed table to - be more efficient when we check to see if we've already seen a particular named method. + Get the declaring IL type of the event as an ILTypeInfo - + - Get overrides instead of abstract slots when measuring whether a class/interface implements all its required slots. + Get the enclosing ("parent"/"declaring") type of the field. - + - Prefer items toward the top of the hierarchy, which we do if the items are virtual - but not when resolving base calls. + Get the ILMethInfo describing the 'add' method associated with the event - + - Indicates if we prefer overrides or abstract slots. + Describes an F# use of an event backed by Abstract IL metadata - + - Try and find a record or class field for a type. + An F# use of a property backed by provided metadata - + - Try and find an item with the given name in a type. + An F# use of a property backed by Abstract IL metadata - + - Read the record or class fields of a type, including inherited ones. Cache the result for monomorphic types. + An F# use of a property backed by F#-declared metadata - + - Read the raw property sets of a type, including inherited ones. Cache the result for monomorphic types + Get the intra-assembly XML documentation for the property. - + - Read the raw method sets of a type, including inherited ones. Cache the result for monomorphic types + Get the TcGlobals associated with the object - + - Get the super-types of a type, excluding interface types. + Get a MethInfo for the 'setter' method associated with the property - + - Read the IL fields of a type, including inherited ones. Cache the result for monomorphic types. + Get the logical name of the property. - + - Read the events of a type, including inherited ones. Cache the result for monomorphic types. + True if the getter (or, if absent, the setter) is a virtual method - + - Get the super-types of a type, including interface types. + Indicates if the enclosing type for the property is a value type. + + For an extension property, this indicates if the property extends a struct type. - + - An InfoReader is an object to help us read and cache infos. - We create one of these for each file we typecheck. + Indicates if this property is static. - + - Sets of methods up the hierarchy, ignoring duplicates by name and sig. - Used to collect sets of virtual methods, protected methods, protected - properties etc. + Indicates if the property is logically a 'newslot', i.e. hides any previous slots of the same name. - + - A helper type to help collect properties. - - Join up getters and setters which are not associated in the F# data structure + Indicates if this property is an indexer property, i.e. a property with arguments. - + - Get the type of the event when looked at as if it is a property - Used when displaying the property in Intellisense + Indicates if this is an F# property compiled as a CLI event, e.g. a [<CLIEvent>] property. - + - Get the (perhaps tupled) argument type accepted by an event + Indicates if this is an extension member - + - The .NET Framework guidelines indicate that the delegate type used for - an event should take two parameters, an "object source" parameter - indicating the source of the event, and an "e" parameter that - encapsulates any additional information about the event. The type of - the "e" parameter should derive from the EventArgs class. For events - that do not use any additional information, the .NET Framework has - already defined an appropriate delegate type: EventHandler. - (from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vcwlkEventsTutorial.asp) + Indicates if the getter (or, if absent, the setter) for the property is a dispatch slot. - + - Try and interpret a delegate type as a "standard" .NET delegate type associated with an event, with a "sender" parameter. + Indicates if this property is marked 'override' and thus definitely overrides another property. - + - Given a delegate type work out the minfo, argument types, return type - and F# function type by looking at the Invoke signature of the delegate. + Indicates if this property has an associated setter method. - + - Try to find a particular named property on a type. Only used to ensure that local 'let' definitions and property names - are distinct, a somewhat adhoc check in tc.fs. + Indicates if this property has an associated getter method. - + - Try to detect the existence of a method on a type. - Used for - -- getting the GetEnumerator, get_Current, MoveNext methods for enumerable types - -- getting the Dispose method when resolving the 'use' construct - -- getting the various methods used to desugar the computation expression syntax + Indicates if this property has an associated XML comment authored in this assembly. - + - Perform type-directed name resolution of a particular named member in an F# type + Get a MethInfo for the 'getter' method associated with the property - + - Get the flattened list of intrinsic properties in the hierarchy + Return a new property info where there is no associated setter, only an associated getter. + + Property infos can combine getters and setters, assuming they are consistent w.r.t. 'virtual', indexer argument types etc. + When checking consistency we split these apart - + - Get the flattened list of intrinsic methods in the hierarchy + Return a new property info where there is no associated getter, only an associated setter. - + - Get the sets intrinsic properties in the hierarchy (not including extension properties) + Get the declaring type or module holding the method. + Note that C#-style extension properties don't exist in the C# design as yet. + If this is an F#-style extension method it is the logical module + holding the value for the extension method. - + - Get the sets of intrinsic methods in the hierarchy (not including extension methods) + Try to get an arbitrary F# ValRef associated with the member. This is to determine if the member is virtual, amongst other things. - + - Exclude properties from super types which have the same name as a property in a more specific type. + Get the enclosing type of the property. + + If this is an extension member, then this is the apparent parent, i.e. the type the property appears to extend. - + - Exclude methods from super types which have the same signature as a method in a more specific type. + Get the enclosing type of the method info, using a nominal type for tuple types - + - Filter the overrides of properties, either keeping the overrides or keeping the dispatch slots. + Test whether two property infos have the same underlying definition. + Uses the same techniques as 'MethInfosUseIdenticalDefinitions'. + Must be compatible with ItemsAreEffectivelyEqual relation. - + - Filter the overrides of methods, either keeping the overrides or keeping the dispatch slots. + Get the result type of the property - + - Filter the overrides of methods or properties, either keeping the overrides or keeping the dispatch slots. + Get the types of the indexer parameters associated with the property - + - Add all the items to the IndexedList, preferring the ones in the sub-types. + Get the names and types of the indexer parameters associated with the property + + If the property is in a generic type, then the type parameters are instantiated in the types returned. - + - Add all the items to the IndexedList, preferring the ones in the super-types. This is used to hide methods - in super classes and/or hide overrides of methods in subclasses. - - Assume no items in 'items' are equivalent according to 'equivTest'. This is valid because each step in a - .NET class hierarchy introduces a consistent set of methods, none of which hide each other within the - given set. This is an important optimization because it means we don't have filter for equivalence between the - large overload sets introduced by methods like System.WriteLine. - - Assume items can be given names by 'nmf', where two items with different names are - not equivalent. + Get the details of the indexer parameters associated with the property - + - Get the declared constructors of any F# type + Calculates a hash code of property info. Must be compatible with ItemsAreEffectivelyEqual relation. - + - Query the immediate properties of an F# type, not taking into account inherited properties. The optFilter - parameter is an optional name to restrict the set of properties returned. + Describes an F# use of a property - + - Query the immediate methods of an F# type, not taking into account inherited methods. The optFilter - parameter is an optional name to restrict the set of properties returned. + Get the TcGlobals governing this value - + - Try to select an F# value when querying members, and if so return a MethInfo that wraps the F# value. + Gets the ILMethInfo of the 'set' method for the IL property - + - Check whether a name matches an optional filter + Get the raw Abstract IL metadata for the IL property - + - Use the given function to select some of the member values from the members of an F# type + Get the name of the IL property - + - Select members from a type by name, searching the type hierarchy if needed + Indicates if the IL property is virtual - + - Generate text for comparing two types. - - If the output text is different without showing constraints and/or imperative type variable - annotations and/or fully qualifying paths then don't show them! + Indicates if the IL property is static - + - Pass negative number as pos in case of single cased discriminated unions + Indicates if the IL property is logically a 'newslot', i.e. hides any previous slots of the same name. - + - Convert a ParamData to a string + Get the declaring IL type of the IL property, including any generic instantiation - + - Convert a MethInfo to a string + Indicates if the IL property has a 'set' method - + - Convert a PropInfo to a string + Indicates if the IL property has a 'get' method - + - Convert a MethInfo to a string + Gets the ILMethInfo of the 'get' method for the IL property - + - Print members with a qualification showing the type they are contained in + Get the apparent declaring type of the method as an F# type. + If this is a C#-style extension method then this is the type which the method + appears to extend. This may be a variable type. - + - Nice printing of a subset of expressions, e.g. for refutations in pattern matching + Like ApparentEnclosingType but use the compiled nominal type if this is a method on a tuple type - + - Layout the inferred signature of a compilation unit + Get the return type of the IL property. + + Any type parameters of the enclosing type are instantiated in the type returned. - + - Another re-implementation of type printing, this time based off provided info objects. + Get the types of the indexer arguments associated with the IL property. + + Any type parameters of the enclosing type are instantiated in the type returned. - + - When to force a break? "type tyname = <HERE> repn" - When repn is class or datatype constructors (not single one). + Get the names and types of the indexer arguments associated with the IL property. + + Any type parameters of the enclosing type are instantiated in the type returned. - + - Printing TAST objects + Describes an F# use of a property backed by Abstract IL metadata - + - Format a method to a layout (actually just containing a string) using "free style" (aka "standalone"). + Get a reference to the F# metadata for the uninstantiated union case - + - Format a method to a buffer using "standalone" display style. - For example, these are the formats used when printing signatures of methods that have not been overridden, - and the format used when showing the individual member in QuickInfo and DeclarationInfo. - The formats differ between .NET/provided methods and F# methods. Surprisingly people don't really seem - to notice this, or they find it helpful. It feels that moving from this position should not be done lightly. + Get the F# metadata for the uninstantiated union case - + - Format a method info using "half C# style". + Get the list of types for the instantiation of the type parameters of the declaring type of the union case - + - Format a method info using "F# style". + Get a reference to the F# metadata for the declaring union type - + - Format the arguments of a method to a buffer. - - This uses somewhat "old fashioned" printf-style buffer printing. + Get the F# metadata for the declaring union type - + - Printing info objects + Get the name of the union case - + - Printing TAST objects + Get the instantiation of the type parameters of the declaring type of the union case - + - Layout type parameters + Describes an F# use of a union case - + - Layout a single type used as the type of a member or value + Get the generic instantiation of the declaring type of the field - + - Layout a single type, taking TypeSimplificationInfo into account + Get a reference to the F# metadata for the F#-declared record, class or struct type - + - Layout a list of types, separated with the given separator, either '*' or ',' + Get the F# metadata for the F#-declared record, class or struct type - + - Layout a type, taking precedence into account to insert brackets where needed + Get a reference to the F# metadata for the uninstantiated field - + - Layout type arguments, either NAME<ty, ..., ty> or (ty, ..., ty) NAME *) + Get the F# metadata for the uninstantiated field - + - Layout a unit expression + Get the name of the field in an F#-declared record, class or struct type - + - Layout constraints, taking TypeSimplificationInfo into account + Indicate if the field is a literal field in an F#-declared record, class or struct type - + - Layout type parameter constraints, taking TypeSimplificationInfo into account + Indicate if the field is a static field in an F#-declared record, class or struct type - + - Layout a single type parameter declaration, taking TypeSimplificationInfo into account - There are several printing-cases for a typar: - - 'a - is multiple occurrence. - _ - singleton occurrence, an underscore preferred over 'b. (OCaml accepts but does not print) - #Type - inplace coercion constraint and singleton. - ('a :> Type) - inplace coercion constraint not singleton. - ('a.opM: S->T) - inplace operator constraint. - + Get the (instantiated) type of the field in an F#-declared record, class or struct type - + - Layout '[<attribs>]' above another block + Get the enclosing (declaring) type of the field in an F#-declared record, class or struct type - + - Layout an attribute 'Type(arg1, ..., argN)' + Describes an F# use of a field in an F#-declared record, class or struct type - + - Layout arguments of an attribute 'arg1, ..., argN' + Represents a single use of a field backed by provided metadata - + - Layout a single attribute arg, following the cases of 'gen_attr_arg' in ilxgen.fs - This is the subset of expressions we display in the NicePrint pretty printer - See also dataExprL - there is overlap between these that should be removed + Represents a single use of a field backed by Abstract IL metadata - + - Layout the flags of a member + Get the type instantiation of the declaring type of the field - + - Layout a reference to a type + Get the scope used to interpret IL metadata - + - Layout a method's signature using type-only-F#-style. No argument names are printed. - - In the case that we've a constructor, we - pull off the class name from the `path`; naturally, it's the - most-deeply-nested element. + Indicates if the field is a literal field with an associated literal value - + - Layout a function pointer signature using type-only-F#-style. No argument names are printed. + Indicates if the field is a member of a struct or enum type - + - Layout a function pointer signature using type-only-F#-style. No argument names are printed. + Indicates if the field is static - + - Layout a function pointer signature using type-only-F#-style. No argument names are printed. + Indicates if the field has the 'specialname' property in the .NET IL - + - this fixes up a name just like adjustILName but also handles F# - operators + Indicates if the field is readonly (in the .NET/C# sense of readonly) - + - fix up a name coming from IL metadata by quoting "funny" names (keywords, otherwise invalid identifiers) + Get a reference to the declaring type of the field as an ILTypeRef - + - This predicate can be used once type inference is complete, before then it is an approximation - that doesn't assert any new constraints + Get the type of the field as an IL type - + - Generate the hash/compare functions we add to user-defined types by default. + Get an (uninstantiated) reference to the field as an Abstract IL ILFieldRef - + - Notify the sink of the information needed to complete recording a use of a symbol - for the purposes of the language service. One of the callbacks should be called by - the checker. - - The first callback represents a case where we have learned the type - instantiation of a generic method or value. - - The second represents the case where we have resolved overloading and/or - a specific override. The 'Item option' contains the candidate overrides. + Get the name of the field - + - Notification is not needed + Get the enclosing ("parent"/"declaring") type of the field. - + - Specifies extra work to do after overload resolution + Tests whether two infos have the same underlying definition. + Must be compatible with ItemsAreEffectivelyEqual relation. - + - Indicates if we only need one result or all possible results from a resolution. + Get the type of the field as an F# type - + - Indicates whether we permit a direct reference to a type generator. Only set when resolving the - right-hand-side of a [<Generate>] declaration. + Calculates a hash code of field info. Must be compatible with ItemsAreEffectivelyEqual relation. - + - Indicates if a warning should be given for the use of upper-case identifiers in patterns + Represents a single use of a IL or provided field from one point in an F# program - + - Indicates the kind of lookup being performed. Note, this type should be made private to nameres.fs. + Describes a use of a method backed by provided metadata - + - An abstract type for reporting the results of name resolution and type checking, and which allows - temporary suspension and/or redirection of reporting. + Describes a use of a pseudo-method corresponding to the default constructor for a .NET struct type - + - Get all the uses of all symbols reported to the sink + ILMeth(tcGlobals, ilMethInfo, extensionMethodPriority). + + Describes a use of a method backed by Abstract IL # metadata - + - Get all the resolutions reported to the sink + FSMeth(tcGlobals, enclosingType, valRef, extensionMethodPriority). + + Describes a use of a method declared in F# code and backed by F# metadata. - + - Get all open declarations reported to the sink + Get the XML documentation associated with the method - + - Create a TcResultsSinkImpl + Get the TcGlobals value that governs the method declaration - + - An implementation of ITypecheckResultsSink to collect information during type checking + Get the information about provided static parameters, if any - + - Cached line-end normalized source text and an array of line end positions, used for format string parsing + Get a list of argument-number counts, one count for each set of curried arguments. + + For an extension member, drop the 'this' argument. - + - Get the current source + Get the method name in LogicalName form, i.e. the name as it would be stored in .NET metadata - + - Record that an open declaration occured in a given scope range + Indicates if the enclosing type for the method is a value type. + + For an extension method, this indicates if the method extends a struct type. - + - Record that a name resolution occurred at a specific location in the source + Indicates if this method is read-only; usually by the [<IsReadOnly>] attribute. + Must be an instance method. + Receiver must be a struct type. - + - Record that a printf format specifier occurred at a specific location in the source + Indicates if this method takes no arguments - + - Record that an expression has a specific type at the given range. + Does the method appear to the user as an instance method? - + - Record that an environment is active over the given scope range + Indicates if this is an IL method. - + - An abstract type for reporting the results of name resolution and type checking + Indicates if this is an F# extension member. - + - Array of line start positions + Check if this method is an explicit implementation of an interface member - + - Source text + Indicates if this method is a generated method associated with an F# CLIEvent property compiled as a .NET event - + - Source text and an array of line end positions, used for format string parsing + Indicates if this is an extension member. - + - If it's `namespace Xxx.Yyy` declaration. + Check if this method is marked 'override' and thus definitely overrides another method. - + - Scope in which open declaration is visible. + Indicates if this is an C#-style extension member. - + - Modules or namespaces which is opened with this declaration. + Indicates if this is a method defined in this assembly with an internal XML comment - + - Full range of the open declaration. + Get the number of generic method parameters for a method. + For an extension method this includes all type parameters, even if it is extending a generic type. - + - Long identifier as it's presented in soruce code. + Get the formal generic method parameters for the method as a list of type variables. + + For an extension method this includes all type parameters, even if it is extending a generic type. - + - Create a new instance of OpenDeclaration. + Get the formal generic method parameters for the method as a list of variable types. - + - Represents open declaration statement. + Get the extension method priority of the method, if it has one. - + - All the uses of all items within the file + Get the extension method priority of the method. If it is not an extension method + then use the highest possible value since non-extension methods always take priority + over extension members. - + - Get all the uses of a particular item within the file + Get the method name in DisplayName form - + - Get the locations of all the printf format specifiers in the file + Get the actual type instantiation of the declaring type associated with this use of the method. + + For extension members this is empty (the instantiation of the declaring type). - + - Represents container for all name resolutions that were met so far when typechecking some particular file + Get the declaring type or module holding the method. If this is an C#-style extension method then this is the type + holding the static member that is the extension method. If this is an F#-style extension method it is the logical module + holding the value for the extension method. - + - Represents the empty set of resolutions + Get the method name in DebuggerDisplayForm - + - Exact name resolutions + Try to get an arbitrary F# ValRef associated with the member. This is to determine if the member is virtual, amongst other things. - + - Represents all the resolutions of names to groups of methods. + Get the enclosing type of the method info. + + If this is an extension member, then this is the apparent parent, i.e. the type the method appears to extend. + This may be a variable type. - + - Information of exact types found for expressions, that can be to the left of a dot. - typ - the inferred type for an expression + Get the enclosing type of the method info, using a nominal type for tuple types - + - Name resolution environments for every interesting region in the file. These regions may - overlap, in which case the smallest region applicable should be used. + Tries to get the object arg type if it's a byref type. - + - The starting and ending position + Indicates if this is an extension member (e.g. on a struct) that takes a byref arg - + - line and column + Tests whether two method infos have the same underlying definition. + Used to merge operator overloads collected from left and right of an operator constraint. + Must be compatible with ItemsAreEffectivelyEqual relation. - + - Naming environment--for example, currently open namespaces. + Indicates if this method is an extension member that is read-only. + An extension member is considered read-only if the first argument is a read-only byref (inref) type. - + - The active instantiation for any generic type parameters + Apply a type instantiation to a method info, i.e. apply the instantiation to the enclosing type. - + - Information about the occurrence of the symbol + Get the ParamData objects for the parameters of a MethInfo - + - Named item + Get the signature of an abstract method slot. - + - Information about printing. For example, should redundant keywords be hidden? + Get the parameter types of a method info - + - The access rights of code at the location + Get the ParamData objects for the parameters of a MethInfo - + - Represents the kind of the occurrence when reporting a name in name resolution + Get the parameter attributes of a method info, which get combined with the parameter names and types - + - Represents information which guides name resolution of types. + Get the (zero or one) 'self'/'this'/'object' arguments associated with a method. + An instance method returns one object argument. - + - Indicates definite knowledge of empty type arguments, i.e. the logical equivalent of name< > + Select all the type parameters of the declaring type of a method. + + For extension methods, no type parameters are returned, because all the + type parameters are part of the apparent type, rather the + declaring type, even for extension methods extending generic types. - + - Deduce definite knowledge of type arguments + Get the return type of a method info, where 'void' is returned as 'unit' - + - Represents information about the generic argument count of a type name when resolving it. - - In some situations we resolve "List" to any type definition with that name regardless of the number - of generic arguments. In others, we know precisely how many generic arguments are needed. + Get the return type of a method info, where 'void' is returned as 'None' - + - Indicates we are resolving type names to type definitions + Build IL method infos. - + - Indicates we are resolving type names to constructor methods. + Build IL method infos for a C#-style extension method - + - Indicates whether we are resolving type names to type definitions or to constructor methods. + Calculates a hash code of method info. Must be compatible with ItemsAreEffectivelyEqual relation. - + - A flag which indicates if it is an error to have two declared type parameters with identical names - in the name resolution environment. + Add the actual type instantiation of the apparent type of an F# extension method. - + - The environment of information used to resolve names + Describes an F# use of a method - + - Information about an extension member held in the name resolution environment + ILMethInfo(g, ilApparentType, ilDeclaringTyconRefOpt, ilMethodDef, ilGenericMethodTyArgs) + + Describes an F# use of an IL method. + + If ilDeclaringTyconRefOpt is 'Some' then this is an F# use of an C#-style extension method. + If ilDeclaringTyconRefOpt is 'None' then ilApparentType is an IL type definition. - + - Represents a record field resolution and the information if the usage is deprecated. + Get the Abstract IL metadata associated with the method. - + - Pairs an Item with a TyparInst showing how generic type variables of the item are instantiated at - a particular usage point. + Get the Abstract IL metadata corresponding to the parameters of the method. + If this is an C#-style extension method then drop the object argument. - + - Represents the potential resolution of an unqualified name to a type. + Get the number of parameters of the method - + - Represents the resolution of a name to a named property setter + Get the Abstract IL scope information associated with interpreting the Abstract IL metadata that backs this method. - + - Represents the resolution of a name to a named argument + Indicates if the IL method is marked virtual. - + - Represents the resolution of a name to an operator + Does it appear to the user as a static method? - + - Represents the resolution of a name to a module or namespace + Indicates if the method has protected accessibility, - + - Represents the resolution of a name to a type variable + Does it have the .NET IL 'newslot' flag set, and is also a virtual? - + - Represents the resolution of a name to a custom builder in the F# computation expression syntax + Does it appear to the user as an instance method? - + - CustomOperation(nm, helpText, methInfo) - - Used to indicate the availability or resolution of a custom query operation such as 'sortBy' or 'where' in computation expression syntax + Indicates if the method is an extension method - + - Represents the resolution of a name to a group of types + Indicates if the IL method is marked final. - + - Represents the resolution of a name to a delegate + Indicates if the method is a constructor - + - Represents the resolution of a name to the fake constructor simulated for an interface type. + Indicates if the method is a class initializer. - + - Represents the resolution of a name to a constructor + Indicates if the IL method is marked abstract. - + - Represents the resolution of a name to a group of methods. + Get the IL name of the method - + - Represents the resolution of a name to a property + Get a reference to the method (dropping all generic instantiations), as an Abstract IL ILMethodRef. - + - Represents the resolution of a name to an event + Get the declaring type associated with an extension member, if any. - + - Represents the resolution of a name to a .NET field + Get the formal method type parameters associated with a method. - + - Represents the resolution of a name at the point of its own definition. + Get the instantiation of the declaring type of the method. + If this is an C#-style extension method then this is empty because extension members + are never in generic classes. - + - Represents the resolution of a name to a field of an anonymous record type. + Get the declaring type of the method. If this is an C#-style extension method then this is the IL type + holding the static member that is the extension method. - + - Represents the resolution of a name to an F# record field. + Get the apparent declaring type of the method as an F# type. + If this is a C#-style extension method then this is the type which the method + appears to extend. This may be a variable type. - + - Represents the resolution of a name to an F# exception definition. + Like ApparentEnclosingType but use the compiled nominal type if this is a method on a tuple type - + - Represents the resolution of a name to an F# active pattern case within the body of an active pattern. + Indicates if the method is marked with the [<IsReadOnly>] attribute. This is done by looking at the IL custom attributes on + the method. - + - Represents the resolution of a name to an F# active pattern result. + Indicates if the method is marked as a DllImport (a PInvoke). This is done by looking at the IL custom attributes on + the method. - + - Represents the resolution of a name to an F# union case. + Get all the argument types of the IL method. Include the object argument even if this is + an C#-style extension method. - + - Represents the resolution of a name to an F# value or function. + Get the argument types of the the IL method. If this is an C#-style extension method + then drop the object argument. - + - Represents an item that results from name resolution + Get info about the arguments of the IL method. If this is an C#-style extension method then + drop the object argument. + + Any type parameters of the enclosing type are instantiated in the type returned. - + - The named argument is a static parameter to a union case constructor + Get the (zero or one) 'self'/'this'/'object' arguments associated with an IL method. + An instance extension method returns one object argument. - + - The named argument is a static parameter to a provided type or a parameter to an F# exception constructor + Get the F# view of the return type of the method, where 'void' is 'unit'. - + - The named argument is an argument of a method + Get the compiled return type of the method, where 'void' is None. - + - Represents the item with which a named argument is associated. + Describes an F# use of an IL method. - + - A NameResolver is a context for name resolution. It primarily holds an InfoReader. + ILTypeInfo (tyconRef, ilTypeRef, typeArgs, ilTypeDef). - + - Resolve a (possibly incomplete) long identifier to a set of possible resolutions, qualified by type. + Get the compiled nominal type. In the case of tuple types, this is a .NET tuple type - + - Resolve a (possibly incomplete) long identifier to a set of possible resolutions. + Describes an F# use of an IL type, including the type instantiation associated with the type at a particular usage point. + + This is really just 1:1 with the subset ot TType which result from building types using IL type definitions. - + - Try to resolve a long identifier as type. + Full information about a parameter returned for use by the type checker and language service. - + - A generator of type instantiations used when no more specific type instantiation is known. + Partial information about a parameter returned for use by the Language Service - + - Resolve a long identifier occurring in an expression position, qualified by a type. + The argument is optional, and is a caller-side .NET optional or default arg. + Note this is correctly termed caller side, even though the default value is optically specified on the callee: + in fact the default value is read from the metadata and passed explicitly to the callee on the caller side. - + - Resolve a long identifier occurring in an expression position. + The argument is optional, and is an F# callee-side optional arg - + - Return the fields for the given class or record + The argument is not optional - + - Resolve a (possibly incomplete) long identifier to a loist of possible class or record fields + Compute the OptionalArgInfo for an IL parameter + + This includes the Visual Basic rules for IDispatchConstant and IUnknownConstant and optional arguments. - + - Resolve a long identifier occurring in an expression position + Represents information about a parameter indicating if it is optional. - + - Resolve a long identifier to a field + The caller-side value for the optional arg, if any - + - Resolve a long identifier to a type definition + Describes the sequence order of the introduction of an extension method. Extension methods that are introduced + later through 'open' get priority in overload resolution. - + - Resolve a long identifier representing a type name + Indicates whether we should visit multiple instantiations of the same generic interface or not - + - Resolve a long identifier when used in a pattern. + Indicates whether we can skip interface types that lie outside the reference set - + - Resolve a long identifier using type-qualified name resolution. + Used to hide/filter members from super classes based on signature - + - Resolve a long identifier to an object constructor. + Used to hide/filter members from super classes based on signature - + - Resolve a long identifier to a namespace or module. + Used to hide/filter members from super classes based on signature - + - Generate a new reference to a record field with a fresh type instantiation + Used to hide/filter members from super classes based on signature + Inref and outref parameter types will be treated as a byref type for equivalency. - + - Get the available methods of a type (both declared and inherited) + Inref and outref parameter types will be treated as a byref type for equivalency. - + - Get all the available properties of a type (only extension) + Get the information about the compiled form of a method signature. Used when analyzing implementation + relations between members and abstract slots. - + - Get all the available properties of a type (both intrinsic and extension) + Strips inref and outref to be a byref. - + - Report an open declaration + Find the delegate type that an F# event property implements by looking through the type hierarchy of the type of the property + for the first instantiation of IDelegateEvent. - + - Report a specific name resolution at a source range + Create an error object to raise should an event not have the shape expected by the .NET idiom described further below - + - Report a specific name resolution at a source range, replacing any previous resolutions + Properties compatible with type IDelegateEvent and attributed with CLIEvent are special: + we generate metadata and add/remove methods + to make them into a .NET event, and mangle the name of a property. + We don't handle static, indexer or abstract properties correctly. + Note the name mangling doesn't affect the name of the get/set methods for the property + and so doesn't affect how we compile F# accesses to the property. - + - Report a specific name resolution at a source range + Try to get an arbitrary ProvidedMethodInfo associated with a property. - + - Report the active name resolution environment for a source range + Compute the ILFieldInit for the given provided constant value for a provided enum type. - + - Temporarily suspend reporting of name resolution and type checking results + Compute the OptionalArgInfo for a provided parameter. + + This is the same logic as OptionalArgInfoOfILParameter except we do not apply the + Visual Basic rules for IDispatchConstant and IUnknownConstant to optional + provided parameters. - + - Temporarily redirect reporting of name resolution and type checking results + Compute the ILFieldInit for the given provided constant value for a provided enum type. - + - Hash compatible with ItemsAreEffectivelyEqual + Work out the instantiation relevant to interpret the backing metadata for a property. - + - Check for equality, up to signature matching + Work out the instantiation relevant to interpret the backing metadata for a member. + + The 'methTyArgs' is the instantiation of any generic method type parameters (this instantiation is + not included in the MethInfo objects, but carried separately). - + - Qualified lookup of type names in the environment + Combine the type instantiation and generic method instantiation - + - Add some declared type parameters to the name resolution environment + Get the object type for a member value which is a C#-style extension method - + - Add a list of modules or namespaces to the name resolution environment + Get the object type for a member value which is an extension method (C#-style or F#-style) - + - Add a single modules or namespace to the name resolution environment + Split the type of an F# member value into + - the type parameters associated with method but matching those of the enclosing type + - the type parameters associated with a generic method + - the return type of the method + - the actual type arguments of the enclosing type. - + - Add a list of module or namespace to the name resolution environment, including any sub-modules marked 'AutoOpen' + Construct the data representing the signature of an abstract method slot - + - Add a module abbreviation to the name resolution environment + Construct the data representing a parameter in the signature of an abstract method slot - + - Add an F# exception definition to the name resolution environment + The slotsig returned by methInfo.GetSlotSig is in terms of the type parameters on the parent type of the overriding method. + Reverse-map the slotsig so it is in terms of the type parameters for the overriding method - + - Add a list of type definitions to the name resolution environment + Get the return type of a provided method, where 'void' is returned as 'None' - + - Add active pattern result tags to the environment. + Check if an F#-declared member value is an explicit interface member implementation - + - Add a single F# value to the environment. + Check if an F#-declared member value is an 'override' or explicit member implementation - + - Add some extra items to the environment for Visual Studio, e.g. record members + Check if an F#-declared member value is a dispatch slot - + - Add extra items to the environment for Visual Studio, e.g. static members + Check if an F#-declared member value is a virtual method - + - Find a field in anonymous record type + Indicates if an F#-declared function or member value is a CLIEvent property compiled as a .NET event - + - Detect a use of a nominal type, including type abbreviations. - When reporting symbols, we care about abbreviations, e.g. 'int' and 'int32' count as two separate symbols. + The constraints for each typar copied from another typar can only be fixed up once + we have generated all the new constraints, e.g. f<A :> List<B>, B :> List<A>> ... - + - Get the active pattern elements defined in a module, if any. Cache in the slot in the module type. + Copy constraints. If the constraint comes from a type parameter associated + with a type constructor then we are simply renaming type variables. If it comes + from a generic method in a generic class (e.g. ty.M<_>) then we may be both substituting the + instantiation associated with 'ty' as well as copying the type parameters associated with + M and instantiating their constraints + + Note: this now looks identical to constraint instantiation. - + - Used to report a warning condition for the use of upper-case identifiers in patterns + Get the return type of an IL method, taking into account instantiations for type, return attributes and method generic parameters, and + translating 'void' to 'None'. - + - Used to report an error condition where name resolution failed due to an indeterminate type + Get the parameter type of an IL method. - + - "Single Feasible Type" inference - Look for the unique supertype of ty2 for which ty2 :> ty1 might feasibly hold + Read an Abstract IL type from metadata, including any attributes that may affect the type itself, and convert to an F# type. - + - Do AdjustArityOfLambdaBody for a series of - iterated lambdas, producing one method. - The required iterated function arity (List.length topValInfo) must be identical - to the iterated function arity of the input lambda (List.length vsl) + Read an Abstract IL type from metadata and convert to an F# type. - + - Break apart lambdas. Needs ChooseTyparSolutionsForFreeChoiceTypars because it's used in - PostTypeCheckSemanticChecks before we've eliminated these nodes. + Check if a type exists somewhere in the hierarchy which has the given head type. - + - Choose solutions for Expr.TyChoose type "hidden" variables introduced - by letrec nodes. Also used by the pattern match compiler to choose type - variables when compiling patterns at generalized bindings. - e.g. let ([], x) = ([], []) - Here x gets a generalized type "list<'T>". + Check if a type exists somewhere in the hierarchy which has the same head type as the given type (note, the given type need not have a head type at all) - + - The feasible coercion relation. Part of the language spec. + Check if a type has a particular head type - + - The feasible equivalence relation. Part of the language spec. + Check if two types have the same nominal head type - + - Implements a :> b without coercion based on finalized (no type variable) types + Get all interfaces of a type, including the type itself if it is an interface - + - Primary relations on types and signatures, with the exception of - constraint solving and method overload resolution. + Get all super types of the type, including the type itself - + - Check the names add up between a signature and its implementation. We check this first. + Search for one element where a function returns a 'Some' result, following interfaces - + - Primary relations on types and signatures, with the exception of - constraint solving and method overload resolution. + Search for one element satisfying a predicate, following interfaces - + - The overall information about a method implementation in a class or object expression + Iterate, following interfaces. Skipping interfaces that lie outside the referenced assembly set is allowed. - + - Get the properties relevant to determining if a uniquely-identified-override exists based on the syntactic information - at the member signature prior to type inference. This is used to pre-assign type information if it does + Fold, following interfaces. Skipping interfaces that lie outside the referenced assembly set is allowed. - + - Get the methods relevant to determining if a uniquely-identified-override exists based on the syntactic information - at the member signature prior to type inference. This is used to pre-assign type information if it does + Fold, do not follow interfaces (unless the type is itself an interface) - + - "Type Completion" inference and a few other checks at the end of the inference scope + Traverse the type hierarchy, e.g. f D (f C (f System.Object acc)). + Visit base types and interfaces first. - + - Check that a type definition implements all its required interfaces after processing all declarations - within a file. + Collect the set of immediate declared interface types for an F# type, but do not + traverse the type hierarchy to collect further interfaces. - + - Get the slots of a type that can or must be implemented. This depends - partly on the full set of interface types that are being implemented - simultaneously, e.g. - { new C with interface I2 = ... interface I3 = ... } - allReqdTys = {C;I2;I3} - - allReqdTys can include one class/record/union type. + Make a type for System.Collections.Generic.IList<ty> - + - Check all implementations implement some dispatch slot. + Get the base type of a type, taking into account type instantiations. Return None if the + type has no base type. - + - Check all dispatch slots are implemented by some override. + Indicates if an F# type is the type associated with an F# exception declaration - + - Check if a dispatch slot is already implemented + Import an IL type as an F# type. importInst gives the context for interpreting type variables. - + - Check if an override implements a dispatch slot + An exception type used to raise an error using the old error system. + + Error text: "A definition to be compiled as a .NET event does not have the expected form. Only property members can be compiled as .NET events." - + - Check if an override exactly matches the requirements for a dispatch slot + An AccessorDomain which returns all items - + - Compose two instantiations of type parameters. + An AccessorDomain which returns everything but .NET private/internal items. + This is used + - when solving member trait constraints, which are solved independently of accessibility + - for failure paths in error reporting, e.g. to produce an error that an F# item is not accessible + - an adhoc use in service.fs to look up a delegate signature - + - Compute the reverse of a type parameter renaming. + An AccessorDomain which returns public items - + - Check if an override is a partial match for the requirements for a dispatch slot + AccessibleFrom(cpaths, tyconRefOpt) + + cpaths: indicates we have the keys to access any members private to the given paths + tyconRefOpt: indicates we have the keys to access any protected members of the super types of 'TyconRef' - + - Check if the kinds of type parameters match between a dispatch slot and an override. + Represents the 'keys' a particular piece of code can use to access other constructs?. - + - Check if an override matches a dispatch slot by name + Uses a separate accessibility domains for containing type and method itself + This makes sense cases like + type A() = + type protected B() = + member this.Public() = () + member protected this.Protected() = () + type C() = + inherit A() + let x = A.B() + do x.Public() + when calling x.SomeMethod() we need to use 'adTyp' do verify that type of x is accessible from C + and 'ad' to determine accessibility of SomeMethod. + I.e when calling x.Public() and x.Protected() -in both cases first check should succeed and second - should fail in the latter one. - + - Check if an override matches a dispatch slot by name + IndiCompute the accessibility of a provided member - + - Get the override information for an object expression method being used to implement dispatch slots + Compute the accessibility of a provided member - + - Get the override info for a value being used to implement a dispatch slot. + Indicate if a provided member is accessible - + - Get the override info for an existing (inherited) method being used to implement a dispatch slot. + Indicates if a type is accessible (both definition and instantiation) - + - Format the signature of a MethInfo as a string as part of an error message + Check that a type definition and its representation contents are accessible - + - Format the signature of an override as a string as part of an error message + Indicates if a type definition and its representation contents are accessible - + - Print the signature of a MethInfo to a buffer as part of an error message + Check that an entity is accessible - + - Print the signature of an override to a buffer as part of an error message + Indicates if an entity is accessible - + - Primary logic related to method overrides. + Indicates if an IL member associated with the given ILType is accessible - + - unnamed called out args: return these as part of the return tuple + Indicates if given IL based TyconRef is accessible. If TyconRef is nested then we'll + walk though the list of enclosing types and test if all of them are accessible - + - unnamed called optional args: pass defaults for these + Indicates if a TyconRef is visible through the AccessibleFrom(cpaths, _). + Note that InternalsVisibleTo extends those cpaths. - + - unassigned args + Indicates if tdef is accessible. If tdef.Access = ILTypeDefAccess.Nested then encTyconRefOpt s TyconRef of enclosing type + and visibility of tdef is obtained using member access rules - + - the method we're attempting to call + Indicates if an IL member is accessible (ignoring its enclosing type) - + - the formal instantiation of the method we're attempting to call + Indicates if an F# item is accessible - + - The types of the actual object arguments, if any + The basic logic of private/internal/protected/InternalsVisibleTo/public accessibility - + - the instantiation of the method we're attempting to call + Check the attributes on a record field, returning errors and warnings as data. - + - the instantiation of the method we're attempting to call + Check the attributes on an F# value, returning errors and warnings as data. - + - return type after tupling of out args is taken into account + Check the attributes on a record field, returning errors and warnings as data. - + - return type after implicit deference of byref returns is taken into account + Check the attributes on a union case, returning errors and warnings as data. - + - args assigned to specify values for attribute fields and properties (these are not necessarily "property sets") + Check the attributes on an entity, returning errors and warnings as data. - + - the property related to the method we're attempting to call, if any + Indicate if a property has 'Obsolete' or 'CompilerMessageAttribute'. + Used to suppress the item in intellisense. - + - named setters + Indicate if a method has 'Obsolete', 'CompilerMessageAttribute' or 'TypeProviderEditorHideMethodsAttribute'. + Used to suppress the item in intellisense. - + - The argument analysis for each set of curried arguments + Check the attributes associated with a method, returning warnings and errors as data. - + - Represents the syntactic matching between a caller of a method and the called method. - - The constructor takes all the information about the caller and called side of a method, match up named arguments, property setters etc., - and returns a CalledMeth object for further analysis. + Check the attributes associated with a IL field, returning warnings and errors as data. - + - Named args + Check the attributes associated with a property, returning warnings and errors as data. - + - Any unnamed caller arguments assigned to a "param array" argument + Indicate if a list of provided attributes contains 'ObsoleteAttribute'. Used to suppress the item in intellisense. - + - The called "ParamArray" argument, if any + Indicate if a list of F# attributes contains 'ObsoleteAttribute'. Used to suppress the item in intellisense. + Also check the attributes for CompilerMessageAttribute, which has an IsHidden argument that allows + items to be suppressed from intellisense. - + - Any unnamed caller arguments not otherwise assigned + Indicate if a list of F# attributes contains 'ObsoleteAttribute'. Used to suppress the item in intellisense. - + - The called arguments corresponding to "unnamed" arguments + Checks the attributes for CompilerMessageAttribute, which has an IsHidden argument that allows + items to be suppressed from intellisense. - + - Represents the resolution of a caller argument as a named-setter argument + Indicate if a list of IL attributes contains 'ObsoleteAttribute'. Used to suppress the item in intellisense. - + - Represents the possibilities for a named-setter argument (a property, field, or a record field setter) + Check a list of provided attributes for 'ObsoleteAttribute', returning errors and warnings as data - + - The argument on the caller side + Check F# attributes for 'ObsoleteAttribute', 'CompilerMessageAttribute' and 'ExperimentalAttribute', + returning errors and warnings as data - + - The called argument in the method + Check IL attributes for 'ObsoleteAttribute', returning errors and warnings as data - + - The identifier for a named argument, if any + Check if a method has a specific attribute. - + - Represents a match between a caller argument and a called argument, arising from either - a named argument or an unnamed argument. + Try to find a specific attribute on a method, where the attribute accepts a string argument. + + This is just used for the 'ConditionalAttribute' attribute - + - Represents the information about an argument in the method being called + Analyze three cases for attributes declared on methods: IL-declared attributes, F#-declared attributes and + provided attributes. - + - CallerArg(ty, range, isOpt, exprInfo) + Analyze three cases for attributes declared on methods: IL-declared attributes, F#-declared attributes and + provided attributes. - + - In the following, 'T gets instantiated to: - 1. the expression being supplied for an argument - 2. "unit", when simply checking for the existence of an overload that satisfies - a signature, or when finding the corresponding witness. - Note the parametricity helps ensure that overload resolution doesn't depend on the - expression on the callside (though it is in some circumstances allowed - to depend on some type information inferred syntactically from that - expression, e.g. a lambda expression may be converted to a delegate as - an adhoc conversion. - - The bool indicates if named using a '?' + Analyze three cases for attributes declared on type definitions: IL-declared attributes, F#-declared attributes and + provided attributes. - + - Implements the elaborated form of adhoc conversions from functions to delegates at member callsites + Check custom attributes. This is particularly messy because custom attributes come in in three different + formats. - + - Build an expression that calls a given method info. - This is called after overload resolution, and also to call other - methods such as 'setters' for properties. + Logic associated with checking "ObsoleteAttribute" and other attributes + on items from name resolution - + - Make a call to a method info. Used by the optimizer and code generator to build - calls to the type-directed solutions to member constraints. + "Single Feasible Type" inference + Look for the unique supertype of ty2 for which ty2 :> ty1 might feasibly hold - + - Build a call to an F# method. + Do AdjustArityOfLambdaBody for a series of + iterated lambdas, producing one method. + The required iterated function arity (List.length topValInfo) must be identical + to the iterated function arity of the input lambda (List.length vsl) - + - Build a call to an F# method. - - Consume the arguments in chunks and build applications. This copes with various F# calling signatures - all of which ultimately become 'methods'. - - QUERY: this looks overly complex considering that we are doing a fundamentally simple - thing here. + Break apart lambdas. Needs ChooseTyparSolutionsForFreeChoiceTypars because it's used in + PostTypeCheckSemanticChecks before we've eliminated these nodes. - + - Build a call to the System.Object constructor taking no arguments, + Choose solutions for Expr.TyChoose type "hidden" variables introduced + by letrec nodes. Also used by the pattern match compiler to choose type + variables when compiling patterns at generalized bindings. + e.g. let ([], x) = ([], []) + Here x gets a generalized type "list<'T>". - + - Build an expression node that is a call to a .NET method. + The feasible coercion relation. Part of the language spec. - + - Adjust the 'this' pointer before making a call - Take the address of a struct, and coerce to an interface/base/constraint type if necessary + The feasible equivalence relation. Part of the language spec. - + - Compute whether we insert a 'coerce' on the 'this' pointer for an object model call - For example, when calling an interface method on a struct, or a method on a constrained - variable type. + Implements a :> b without coercion based on finalized (no type variable) types - + - Is this a 'base' call (in the sense of C#) + Primary relations on types and signatures, with the exception of + constraint solving and method overload resolution. - + - Erasure over System.Type. - - This is a reimplementation of the logic of provided-type erasure, working entirely over (tainted, provided) System.Type - values. This is used when preparing ParameterInfo objects to give to the provider in GetInvokerExpression. - These ParameterInfo have erased ParameterType - giving the provider an erased type makes it considerably easier - to implement a correct GetInvokerExpression. - - Ideally we would implement this operation by converting to an F# TType using ImportSystemType, and then erasing, and then converting - back to System.Type. However, there is currently no way to get from an arbitrary F# TType (even the TType for - System.Object) to a System.Type to give to the type provider. + The Invoke MethInfo, the function argument types, the function return type + and the overall F# function type for the function type associated with a .NET delegate type - + - Logic associated with resolving method calls. + Get the item sets - + - Represents the typechecked, elaborated form of a pattern, prior to pattern-match compilation. + Get an empty set of items - + - What should the decision tree contain for any incomplete match? + Get the items with a particular name - + - Compile a pattern into a decision tree and a set of targets. + Filter a set of new items to add according to the content of the list. Only keep an item + if it passes 'keepTest' for all matching items already in the list. - + - A function that denotes captured tcVal, Used in constraint solver and elsewhere to get appropriate expressions for a ValRef. + Add new items, extracting the names using the given function. - + - The type equation comes from a sequence expression. + The input list is sorted from most-derived to least-derived type, so any System.Object methods + are at the end of the list. Return a filtered list where prior/subsequent members matching by name and + that are in the same equivalence class have been removed. We keep a name-indexed table to + be more efficient when we check to see if we've already seen a particular named method. - + - The type equation comes from a pattern match guard. + Get overrides instead of abstract slots when measuring whether a class/interface implements all its required slots. - + - The type equation comes from a return type of a pattern match clause (not the first clause). + Prefer items toward the top of the hierarchy, which we do if the items are virtual + but not when resolving base calls. - + - The type equation comes from an downcast where a upcast could be used. + Indicates if we prefer overrides or abstract slots. - + - The type equation comes from a runtime type test. + Try and find a record or class field for a type. - + - The type equation comes from a yield in a computation expression. + Try and find an item with the given name in a type. - + - The type equation comes from a return in a computation expression. + Check if the given language feature is supported by the runtime. - + - The type equation comes from a list or array constructor + Read the record or class fields of a type, including inherited ones. Cache the result for monomorphic types. - + - The type equation comes from the verification of a tuple in record fields. + Read the raw property sets of a type, including inherited ones. Cache the result for monomorphic types - + - The type equation comes from the verification of record fields. + Read the raw method sets of a type, including inherited ones. Cache the result for monomorphic types - + - The type equation comes from a type check of the result of an else branch. + Get the super-types of a type, excluding interface types. - + - The type equation comes from an omitted else branch. + Read the raw method sets of a type that are the most specific overrides. Cache the result for monomorphic types - + - The type equation comes from an IF expression. + Read the IL fields of a type, including inherited ones. Cache the result for monomorphic types. - + - No context was given. + Read the events of a type, including inherited ones. Cache the result for monomorphic types. - + - Information about the context of a type equation. + Get the super-types of a type, including interface types. - + - 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. + An InfoReader is an object to help us read and cache infos. + We create one of these for each file we typecheck. - + - Create a list of inference type variables, one for each element in the input list + Sets of methods up the hierarchy, ignoring duplicates by name and sig. + Used to collect sets of virtual methods, protected methods, protected + properties etc. - + - Create an inference type variable representing an error condition when checking a measure + A helper type to help collect properties. + + Join up getters and setters which are not associated in the F# data structure - + - Create an inference type variable representing an error condition when checking an expression + Get the type of the event when looked at as if it is a property + Used when displaying the property in Intellisense - + - Create an inference type variable for the kind of a byref pointer + Get the (perhaps tupled) argument type accepted by an event - + - Create an inference type variable + The .NET Framework guidelines indicate that the delegate type used for + an event should take two parameters, an "object source" parameter + indicating the source of the event, and an "e" parameter that + encapsulates any additional information about the event. The type of + the "e" parameter should derive from the EventArgs class. For events + that do not use any additional information, the .NET Framework has + already defined an appropriate delegate type: EventHandler. + (from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vcwlkEventsTutorial.asp) - + - Create a type variable representing the use of a "_" in F# code + Try and interpret a delegate type as a "standard" .NET delegate type associated with an event, with a "sender" parameter. - + - Solves constraints using a mutable constraint-solver state + Given a delegate type work out the minfo, argument types, return type + and F# function type by looking at the Invoke signature of the delegate. - + - Parse "printf-style" format specifiers at compile time, producing - a list of items that specify the types of the things that follow. - - Must be updated if the Printf runtime component is updated. + Get a set of most specific override methods. - + - The environment and collector + Try to find a particular named property on a type. Only used to ensure that local 'let' definitions and property names + are distinct, a somewhat adhoc check in tc.fs. - + - Walk expressions, collecting type variables + Try to detect the existence of a method on a type. + Used for + -- getting the GetEnumerator, get_Current, MoveNext methods for enumerable types + -- getting the Dispose method when resolving the 'use' construct + -- getting the various methods used to desugar the computation expression syntax - + - Walk types, collecting type variables + Perform type-directed name resolution of a particular named member in an F# type - + - Find unsolved, uninstantiated type variables + Get the flattened list of intrinsic properties in the hierarchy - + - Indicates that type references are emitted as integer indexes into a supplied table + Get the flattened list of intrinsic methods in the hierarchy - + - Perform the checks on the TAST for a file after type inference is complete. + Get the sets intrinsic properties in the hierarchy (not including extension properties) - + - Implements a set of checks on the TAST for a file that can only be performed after type inference - is complete. + Get the sets of intrinsic methods in the hierarchy (not including extension methods) - + - Optimization information + Exclude properties from super types which have the same name as a property in a more specific type. - + - Check if an expression has an effect + Exclude methods from super types which have the same signature as a method in a more specific type. - + - Combine optimization infos + Filter the overrides of properties, either keeping the overrides or keeping the dispatch slots. - + - Ensure that 'internal' items are not exported in the optimization info + Filter the overrides of methods, either keeping the overrides or keeping the dispatch slots. - + - Rewrite the module info using the export remapping + Filter the overrides of methods or properties, either keeping the overrides or keeping the dispatch slots. - + - Saving and re-reading optimization information + Add all the items to the IndexedList, preferring the ones in the sub-types. - + - Optimize one implementation file in the given environment + Add all the items to the IndexedList, preferring the ones in the super-types. This is used to hide methods + in super classes and/or hide overrides of methods in subclasses. + + Assume no items in 'items' are equivalent according to 'equivTest'. This is valid because each step in a + .NET class hierarchy introduces a consistent set of methods, none of which hide each other within the + given set. This is an important optimization because it means we don't have filter for equivalence between the + large overload sets introduced by methods like System.WriteLine. + + Assume items can be given names by 'nmf', where two items with different names are + not equivalent. - + - For building optimization environments incrementally + Get the declared constructors of any F# type - + - top of expr toplevel? (true) + From the given method sets, filter each set down to the most specific ones. - + - val not defined under lambdas + Finds the most specific methods from a method collection by a given method's signature. - + - v -> recursive? * v list -- the others in the mutual binding + Get the items that are considered the most specific in the hierarchy out of the given items by type. + REVIEW: Note complexity O(N^2) - + - bound in a decision tree? + Query the immediate properties of an F# type, not taking into account inherited properties. The optFilter + parameter is an optional name to restrict the set of properties returned. - + - v -> binding repr + Query the immediate methods of an F# type, not taking into account inherited methods. The optFilter + parameter is an optional name to restrict the set of properties returned. - + - v -> context / APP inst args + Try to select an F# value when querying members, and if so return a MethInfo that wraps the F# value. - + - Results is "expr information". - This could extend to be a full graph view of the expr. - Later could support "safe" change operations, and optimisations could be in terms of those. + Check whether a name matches an optional filter - + - The vars captured by the non-synchronous path + Use the given function to select some of the member values from the members of an F# type - + - The state variables allocated for one portion of the sequence expression (i.e. the local let-bound variables which become state variables) + Select members from a type by name, searching the type hierarchy if needed - + - any actual work done in Close + Generate text for comparing two types. + + If the output text is different without showing constraints and/or imperative type variable + annotations and/or fully qualifying paths then don't show them! - + - The labels allocated for one portion of the sequence expression + Pass negative number as pos in case of single cased discriminated unions - + - The code to run in the second phase, to rebuild the expressions, once all code labels and their mapping to program counters have been determined - 'nextVar' is the argument variable for the GenerateNext method that represents the byref argument that holds the "goto" destination for a tailcalling sequence expression + Convert a ParamData to a string - + - Analyze a TAST expression to detect the elaborated form of a sequence expression. - Then compile it to a state machine represented as a TAST containing goto, return and label nodes. - The returned state machine will also contain references to state variables (from internal 'let' bindings), - a program counter (pc) that records the current state, and a current generated value (current). - All these variables are then represented as fields in a hosting closure object along with any additional - free variables of the sequence expression. - - The analysis is done in two phases. The first phase determines the state variables and state labels (as Abstract IL code labels). - We then allocate an integer pc for each state label and proceed with the second phase, which builds two related state machine - expressions: one for 'MoveNext' and one for 'Dispose'. + Convert a MethInfo to a string - + - An "expr -> expr" pass that eta-expands under-applied values of - known arity to lambda expressions and beta-var-reduces to bind - any known arguments. The results are later optimized by the peephole - optimizer in opt.fs + Convert a PropInfo to a string - + - Rewrite mutable locals to reference cells across an entire implementation file + Convert a MethInfo to a string - + - Rewrite bindings for mutable locals which we are transforming + Print members with a qualification showing the type they are contained in - + - Rewrite fetches, stores and address-of expressions for mutable locals which we are transforming + Nice printing of a subset of expressions, e.g. for refutations in pattern matching - + - Find all the mutable locals to promote to reference cells in an implementation file + Layout the inferred signature of a compilation unit - + - Find all the mutable locals that escape a set of bindings + Another re-implementation of type printing, this time based off provided info objects. - + - Find all the mutable locals that escape a binding + When to force a break? "type tyname = <HERE> repn" + When repn is class or datatype constructors (not single one). - + - Find all the mutable locals that escape a lambda expression or object expression + Printing TAST objects - + -Special cases where representation uses Lambda. - Handle these as special cases since mutables are allowed inside their bodies + Format a method to a layout (actually just containing a string) using "free style" (aka "standalone"). - + - Find all the mutable locals that escape a lambda expression, ignoring the arguments to the lambda + Format a method to a buffer using "standalone" display style. + For example, these are the formats used when printing signatures of methods that have not been overridden, + and the format used when showing the individual member in QuickInfo and DeclarationInfo. + The formats differ between .NET/provided methods and F# methods. Surprisingly people don't really seem + to notice this, or they find it helpful. It feels that moving from this position should not be done lightly. - + - Find all the mutable locals that escape a method, function or lambda expression + Format a method info using "half C# style". - + - Invert the compilation of the given value and return its current dynamic value and its compiled System.Type + Format a method info using "F# style". - + - Generate ILX code for an assembly fragment + Format the arguments of a method to a buffer. + + This uses somewhat "old fashioned" printf-style buffer printing. - + - Invert the compilation of the given value and clear the storage of the value + Printing info objects - + - Register a fragment of the current assembly with the ILX code generator. If 'isIncrementalFragment' is true then the input - is assumed to be a fragment 'typed' into FSI.EXE, otherwise the input is assumed to be the result of a '#load' + Printing TAST objects - + - Register a set of referenced assemblies with the ILX code generator + layouts the elements of an unresolved overloaded method call: + argInfos: unammed and named arguments + retTy: return type + genParamTy: generic parameter types - + - Create an incremental ILX code generator for a single assembly + Layout type parameters - + - An incremental ILX code generator for a single assembly + Layout a single type used as the type of a member or value - + - Used to support the compilation-inversion operations "ClearGeneratedValue" and "LookupGeneratedValue" + Layout a single type, taking TypeSimplificationInfo into account - + - The generated IL/ILX resources associated with F# quotations + Layout a list of types, separated with the given separator, either '*' or ',' - + - The security attributes to attach to the assembly + Layout a type, taking precedence into account to insert brackets where needed - + - The attributes for the assembly in F# form + Layout type arguments, either NAME<ty, ..., ty> or (ty, ..., ty) NAME *) - + - The generated IL/ILX .NET module attributes + Layout a unit expression - + - The generated IL/ILX assembly attributes + Layout constraints, taking TypeSimplificationInfo into account - + - The generated IL/ILX type definitions + Layout type parameter constraints, taking TypeSimplificationInfo into account - + - The results of the ILX compilation of one fragment of an assembly + Layout a single type parameter declaration, taking TypeSimplificationInfo into account + There are several printing-cases for a typar: + + 'a - is multiple occurrence. + _ - singleton occurrence, an underscore preferred over 'b. (OCaml accepts but does not print) + #Type - inplace coercion constraint and singleton. + ('a :> Type) - inplace coercion constraint not singleton. + ('a.opM: S->T) - inplace operator constraint. + - + - Indicates that, whenever possible, use callvirt instead of call + Layout '[<attribs>]' above another block - + - Indicates the code generated is an interactive 'it' expression. We generate a setter to allow clearing of the underlying - storage, even though 'it' is not logically mutable + Layout an attribute 'Type(arg1, ..., argN)' - + - Indicates the code is being generated in FSI.EXE and is executed immediately after code generation - This includes all interactively compiled code, including #load, definitions, and expressions + Layout arguments of an attribute 'arg1, ..., argN' - + - Indicates which backend we are generating code for + Layout a single attribute arg, following the cases of 'gen_attr_arg' in ilxgen.fs + This is the subset of expressions we display in the NicePrint pretty printer + See also dataExprL - there is overlap between these that should be removed - + - A flag to help test emit of debug information + Layout the flags of a member - + - Indicates if we are generating debug symbols or not + Layout a reference to a type - + - Indicates if local optimizations are active + Layout a method's signature using type-only-F#-style. No argument names are printed. + + In the case that we've a constructor, we + pull off the class name from the `path`; naturally, it's the + most-deeply-nested element. - + - If this is set, then the last module becomes the "main" module + Layout a function pointer signature using type-only-F#-style. No argument names are printed. - + - Indicates if static array data should be emitted using static blobs + Layout a function pointer signature using type-only-F#-style. No argument names are printed. - + - Indicates if we should workaround old reflection emit bugs + Layout a function pointer signature using type-only-F#-style. No argument names are printed. - + - Indicates if we are generating filter blocks + this fixes up a name just like adjustILName but also handles F# + operators - + - Indicates how the generated IL code is ultimately emitted + fix up a name coming from IL metadata by quoting "funny" names (keywords, otherwise invalid identifiers) - + - Determine if an F#-declared value, method or function is compiled as a method. + Print Signatures/Types, for signatures, intellisense, quick info, FSI responses - + - Diagnostics seen while processing the compiler options implied root of closure + This predicate can be used once type inference is complete, before then it is an approximation + that doesn't assert any new constraints - + - Diagnostics to show for root of closure (used by fsc.fs) + Generate the hash/compare functions we add to user-defined types by default. - + - Diagnostics seen while processing resolutions + Notify the sink of the information needed to complete recording a use of a symbol + for the purposes of the language service. One of the callbacks should be called by + the checker. + + The first callback represents a case where we have learned the type + instantiation of a generic method or value. + + The second represents the case where we have resolved overloading and/or + a specific override. The 'Item option' contains the candidate overrides. - + - The #nowarns + Notification is not needed - + - The original #load references, including those that didn't resolve + Specifies extra work to do after overload resolution - + - The list of all sources in the closure with inputs when available, with associated parse errors and warnings + Indicates whether we permit a direct reference to a type generator. Only set when resolving the + right-hand-side of a [<Generate>] declaration. - + - The list of references that were not resolved during load closure. + Indicates if a warning should be given for the use of upper-case identifiers in patterns - + - The resolved references along with the ranges of the #r positions in each file. + Indicates the kind of lookup being performed. Note, this type should be made private to nameres.fs. - + - The source files along with the ranges of the #load positions in each file. + Indicates if we only need one result or all possible results from a resolution. - + - A temporary TcConfig is created along the way, is why this routine takes so many arguments. We want to be sure to use exactly the - same arguments as the rest of the application. + An abstract type for reporting the results of name resolution and type checking, and which allows + temporary suspension and/or redirection of reporting. - + - Analyze a set of script files and find the closure of their references. The resulting references are then added to the given TcConfig. - Used from fsi.fs and fsc.fs, for #load and command line. + Get all the uses of all symbols reported to the sink - + - Get the typing environment implied by the set of signature files and/or inferred signatures of implementation files checked so far + Get all the resolutions reported to the sink - + - Get the typing environment implied by the set of implementation files checked so far + Get all open declarations reported to the sink - + - The inferred contents of the assembly, containing the signatures of all files. + Get the format specifier locations - + - The CcuThunk for the current assembly being checked + Create a TcResultsSinkImpl - + - Represents the incremental type checking state for a set of inputs + An implementation of ITypecheckResultsSink to collect information during type checking - + - Try to resolve a referenced assembly based on TcConfig settings. + Cached line-end normalized source text and an array of line end positions, used for format string parsing - + - Try to find a provider-generated assembly + Get the current source - + - Try to find the given assembly reference by simple name. Used in magic assembly resolution. Effectively does implicit - unification of assemblies by simple assembly name. + Record that an open declaration occured in a given scope range - + - Try to find the given assembly reference. + Record that a name resolution occurred at a specific location in the source - + - Resolve a referenced assembly and report an error if the resolution fails. + Record that a method group name resolution occurred at a specific location in the source - + - Report unresolved references that also weren't consumed by any type providers. + Record that a printf format specifier occurred at a specific location in the source - + - This excludes any framework imports (which may be shared between multiple builds) + Record that an expression has a specific type at the given range. - + - Represents a table of imported assemblies with their resolutions. + Record that an environment is active over the given scope range - + - Represents a resolved imported assembly + An abstract type for reporting the results of name resolution and type checking - + - Represents a resolved imported binary + Array of line start positions - + - Get a TcConfigProvider which will return only the exact TcConfig. + Source text - + - Get a TcConfigProvider which will continue to respect changes in the underlying - TcConfigBuilder rather than delivering snapshots. + Source text and an array of line end positions, used for format string parsing - + - Represents a computation to return a TcConfig. Normally this is just a constant immutable TcConfig, - but for F# Interactive it may be based on an underlying mutable TcConfigBuilder. + If it's `namespace Xxx.Yyy` declaration. - + - Set if the user has explicitly turned indentation-aware syntax on/off + Scope in which open declaration is visible. - + - If true, indicates all type checking and code generation is in the context of fsi.exe + Modules or namespaces which is opened with this declaration. - + - File system query based on TcConfig settings + Full range of the open declaration. - + - File system query based on TcConfig settings + Long identifier as it's presented in source code. - + - Get the loaded sources that exist and issue a warning for the ones that don't + Create a new instance of OpenDeclaration. - + - Prevent erasure of conditional attributes and methods so tooling is able analyse them. + Represents open declaration statement. - + - if true - 'let mutable x = Span.Empty', the value 'x' is a stack referring span. Used for internal testing purposes only until we get true stack spans. + Empty collection of symbol uses - + - A function to call to try to get an object that acts as a snapshot of the metadata section of a .NET binary, - and from which we can read the metadata. Only used when metadataOnly=true. + All the uses of all items within the file - + - If true, indicates all type checking and code generation is in the context of fsi.exe + Get all the uses of a particular item within the file - + - Sources added into the build with #load + Get the locations of all the printf format specifiers in the file - + - Set if the user has explicitly turned indentation-aware syntax on/off + Represents container for all name resolutions that were met so far when typechecking some particular file - + - Represents the file or string used for the --version flag + Represents the empty set of resolutions - + - Whether or not this is an installed system assembly (for example, System.dll) + Exact name resolutions - + - Create the tooltip text for the assembly reference + Represents additional resolutions of names to groups of methods. + CapturedNameResolutions should be checked when no captured method group is found. + See TypeCheckInfo.GetCapturedNameResolutions for example. - + - Path to the resolvedFile + Information of exact types found for expressions, that can be to the left of a dot. + typ - the inferred type for an expression - + - The original reference to the assembly. + Name resolution environments for every interesting region in the file. These regions may + overlap, in which case the smallest region applicable should be used. - + - The name of the assembly file generated by the project + The starting and ending position - + - Get the logical timestamp that would be the timestamp of the assembly file generated by the project. - - For project references this is maximum of the timestamps of all dependent files. - The project is not actually built, nor are any assemblies read, but the timestamps for each dependent file - are read via the FileSystem. If the files don't exist, then a default timestamp is used. - - The operation returns None only if it is not possible to create an IncrementalBuilder for the project at all, e.g. if there - are fatal errors in the options for the project. + line and column - + - Evaluate raw contents of the assembly file generated by the project + Naming environment--for example, currently open namespaces. - + - The identity of the module + The active instantiation for any generic type parameters - + - The raw IL module definition in the assembly, if any. This is not present for cross-project references - in the language service + Information about the occurrence of the symbol - + - The table of type forwarders in the assembly + Named item - + - The raw F# signature data in the assembly, if any + Information about printing. For example, should redundant keywords be hidden? - + - The raw F# optimization data in the assembly, if any + The access rights of code at the location - + - The raw list InternalsVisibleToAttribute attributes in the assembly + Represents the kind of the occurrence when reporting a name in name resolution - + - The raw list AutoOpenAttribute attributes in the assembly + Represents information which guides name resolution of types. - + - Represents a reference to an F# assembly. May be backed by a real assembly on disk (read by Abstract IL), or a cross-project - reference in FSharp.Compiler.Service. + Indicates definite knowledge of empty type arguments, i.e. the logical equivalent of name< > - + - Part of LegacyHostedCompilerForTesting + Deduce definite knowledge of type arguments - + - Part of LegacyHostedCompilerForTesting + Represents information about the generic argument count of a type name when resolving it. + + In some situations we resolve "List" to any type definition with that name regardless of the number + of generic arguments. In others, we know precisely how many generic arguments are needed. - + - Part of LegacyHostedCompilerForTesting + Indicates we are resolving type names to type definitions - + - Part of LegacyHostedCompilerForTesting + Indicates we are resolving type names to constructor methods. - + - State used to de-deuplicate module names along a list of file names + Indicates whether we are resolving type names to type definitions or to constructor methods. - + - Indicates if we should report a warning as an error + A flag which indicates if it is an error to have two declared type parameters with identical names + in the name resolution environment. - + - Indicates if we should report a warning + Typars (always available by unqualified names). Further typars can be + in the tpenv, a structure folded through each top-level definition. - + - Check a single input and finish the checking + Other extension members unindexed by type - + - Check a closed set of inputs + Extension members by type and name - + - Finish the checking of a closed set of inputs + Tycons available by unqualified, demangled names (i.e. (List,1) --> TyconRef) - + - Finish the checking of multiple inputs + Tycons available by unqualified, demangled names (i.e. (List,1) --> TyconRef) - + - Check one input, returned as an Eventually computation + Tycons indexed by the various names that may be used to access them, e.g. + "List" --> multiple TyconRef's for the various tycons accessible by this name. + "List`1" --> TyconRef - + - Get the initial type checking state for a set of inputs + RecdField labels in scope. RecdField labels are those where type are inferred + by label rather than by known type annotation. + Bools indicate if from a record, where no warning is given on indeterminate lookup - + - Get the initial type checking environment including the loading of mscorlib/System.Core, FSharp.Core - applying the InternalsVisibleTo in referenced assemblies and opening 'Checked' if requested. + Fully qualified modules and namespaces. 'open' does not change this. - + - Parse one input file + Modules accessible via "." notation. Note this is a multi-map. + Adding a module abbreviation adds it a local entry to this List.map. + Likewise adding a ccu or opening a path adds entries to this List.map. - + - This list is the default set of references for "non-project" files. + Data Tags and Active Pattern Tags available by unqualified name - + - Get an error logger that filters the reporting of warnings based on scoped pragma information + Values and Data Tags available by unqualified name - + - Find the scoped #nowarn pragmas with their range information + Display environment information for output - + - Process the #nowarn in an input + The environment of information used to resolve names - + - Process all the #r, #I etc. in an input + ILExtMem(declaringTyconRef, ilMetadata, pri) + + IL-style extension member, backed by some kind of method with an [<Extension>] attribute - + - Processing # commands + F#-style Extrinsic extension member, defined in F# code - + - Process #r in F# Interactive. - Adds the reference to the tcImports and add the ccu to the type checking environment. + Describes the sequence order of the introduction of an extension method. Extension methods that are introduced + later through 'open' get priority in overload resolution. - + - Write F# optimization data as an IL resource + Information about an extension member held in the name resolution environment - + - Write F# signature data as an IL resource + Represents a record field resolution and the information if the usage is deprecated. - + - Determine if an IL resource attached to an F# assembly is an F# quotation data resource for reflected definitions + Pairs an Item with a TyparInst showing how generic type variables of the item are instantiated at + a particular usage point. - + - Determine if an IL resource attached to an F# assembly is an F# optimization data resource + Represents the potential resolution of an unqualified name to a type. - + - Determine if an IL resource attached to an F# assembly is an F# signature data resource + Represents the resolution of a name to a named property setter - + - Part of LegacyHostedCompilerForTesting + Represents the resolution of a name to a named argument - + - Output extra context information for an error or warning to a buffer + Represents the resolution of a name to an operator - + - Output an error or warning to a buffer + Represents the resolution of a name to a module or namespace - + - Output an error to a buffer + Represents the resolution of a name to a type variable - + - Split errors into a "main" error and a set of associated errors + Represents the resolution of a name to a custom builder in the F# computation expression syntax - + - Get the number associated with an error + CustomOperation(nm, helpText, methInfo) + + Used to indicate the availability or resolution of a custom query operation such as 'sortBy' or 'where' in computation expression syntax - + - Get the location associated with an error + Represents the resolution of a name to a group of types - + - Parse a single input (A signature file or implementation file) + Represents the resolution of a name to a delegate - + - Checks if a ParsedInput is using a module name that was already given and deduplicates the name if needed. + Represents the resolution of a name to the fake constructor simulated for an interface type. - + - Get the name used for FSharp.Core + Represents the resolution of a name to a constructor - + - File suffixes where #light is the default + Represents the resolution of a name to a group of methods. - + - Script file suffixes + Represents the resolution of a name to a property - + - Implementation file suffixes + Represents the resolution of a name to an event - + - Signature file suffixes + Represents the resolution of a name to a .NET field - + - Coordinating compiler operations - configuration, loading initial context, reporting errors etc. + Represents the resolution of a name at the point of its own definition. - + - CompilerOption(name, argumentDescriptionString, actionSpec, exceptionOpt, helpTextOpt + Represents the resolution of a name to a field of an anonymous record type. - + - The spec value describes the action of the argument, - and whether it expects a following parameter. + Represents the resolution of a name to a union case field. - + - Apply args to TcConfigBuilder and return new list of source files + Represents the resolution of a name to an F# record or exception field. - + - Parse and process a set of compiler options + Represents the resolution of a name to an F# exception definition. - + - The default ErrorLogger implementation, reporting messages to the Console up to the maxerrors maximum + Represents the resolution of a name to an F# active pattern case within the body of an active pattern. - + - Part of LegacyHostedCompilerForTesting + Represents the resolution of a name to an F# active pattern result. - + - Process the given set of command line arguments + Represents the resolution of a name to an F# union case. - + - Set the concrete inputs for this build. + Represents the resolution of a name to an F# value or function. - + - Declare a named vector output. + Represents an item that results from name resolution - + - Declare a named scalar output. + The named argument is a static parameter to a provided type. - + - Declare build outputs and bind them to real values. - Only required for unit testing. + The named argument is an argument of a method - + - Declare a named scalar output. + Represents the item with which a named argument is associated. - + - A set of build rules and the corresponding, possibly partial, results from building. + A NameResolver is a context for name resolution. It primarily holds an InfoReader. - + - Get an element of vector result or None if there were no results. Only required for unit testing. + Resolve a (possibly incomplete) long identifier to a set of possible resolutions, qualified by type. - + - Get a result vector. All results must be available or thrown an exception. Only required for unit testing. + Resolve a (possibly incomplete) long identifier to a set of possible resolutions. - + - Get a scalar vector. Result must be available. Only required for unit testing. + Try to resolve a long identifier as type. - + - Do one step in the build. Only required for unit testing. + A generator of type instantiations used when no more specific type instantiation is known. - + - Evaluate a build for a vector up to a limit. Only required for unit testing. + Resolve a long identifier occurring in an expression position, qualified by a type. - + - Evaluate a build. Only required for unit testing. + Resolve a long identifier occurring in an expression position. - + - Used for unit testing. Causes all steps of underlying incremental graph evaluation to cancel + Return the fields for the given class or record - + - Declares a scalar build input. - Only required for unit testing. + Resolve a (possibly incomplete) long identifier to a loist of possible class or record fields - + - Declares a vector build input. - Only required for unit testing. + Resolve a long identifier occurring in an expression position - + - Convert a Vector into a Scalar. + Resolve a long identifier to a field - + - Apply a function to a vector to get a scalar value. + Resolve a long identifier to a type definition - + - Apply a function to each element of the vector, threading an accumulator argument - through the computation. Returns intermediate results in a vector. + Resolve a long identifier representing a type name - + - Updates the creates a new vector with the same items but with - timestamp specified by the passed-in function. + Resolve a long identifier when used in a pattern. - + - Maps one vector to another using the given function. + Resolve a long identifier using type-qualified name resolution. - + - Methods for acting on build Vectors - Only required for unit testing. + Resolve a long identifier to an object constructor. - + - Generalized Incremental Builder. This is exposed only for unittesting purposes. + Resolve a long identifier to a namespace, module or static class. - + - Used for unit testing + Generate a new reference to a record field with a fresh type instantiation - + - Tests whether the user is typing something like "member x." or "override (*comment*) x." + Get the available methods of a type (both declared and inherited) - + - Get the partial long name of the identifier to the left of index. - For example, for `System.DateTime.Now` it returns PartialLongName ([|"System"; "DateTime"|], "Now", Some 32), where "32" pos of the last dot. + Get all the available properties of a type (only extension) - + - Get the partial long name of the identifier to the left of index. + Get all the available properties of a type (both intrinsic and extension) - + - Given a string and a position in that string, find an identifier as - expected by `GotoDefinition`. This will work when the cursor is - immediately before the identifier, within the identifier, or immediately - after the identifier. - - 'tolerateJustAfter' indicates that we tolerate being one character after the identifier, used - for goto-definition - - In general, only identifiers composed from upper/lower letters and '.' are supported, but there - are a couple of explicitly handled exceptions to allow some common scenarios: - - When the name contains only letters and '|' symbol, it may be an active pattern, so we - treat it as a valid identifier - e.g. let ( |Identitiy| ) a = a - (but other identifiers that include '|' are not allowed - e.g. '||' operator) - - It searches for double tick (``) to see if the identifier could be something like ``a b`` - - REVIEW: Also support, e.g., operators, performing the necessary mangling. - (i.e., I would like that the name returned here can be passed as-is - (post `.`-chopping) to `GetDeclarationLocation.) - - In addition, return the position where a `.` would go if we were making - a call to `DeclItemsForNamesAtPosition` for intellisense. This will - allow us to use find the correct qualified items rather than resorting - to the more expensive and less accurate environment lookup. + Report an open declaration - + - Puts us after the last character. + Report a specific name resolution at a source range - + - Methods for cheaply and innacurately parsing F#. - - These methods are very old and are mostly to do with extracting "long identifier islands" - A.B.C - from F# source code, an approach taken from pre-F# VS samples for implementing intelliense. - - This code should really no longer be needed since the language service has access to - parsed F# source code ASTs. However, the long identifiers are still passed back to GetDeclarations and friends in the - F# Compiler Service and it's annoyingly hard to remove their use completely. - - In general it is unlikely much progress will be made by fixing this code - it will be better to - extract more information from the F# ASTs. - - It's also surprising how hard even the job of getting long identifier islands can be. For example the code - below is inaccurate for long identifier chains involving ``...`` identifiers. And there are special cases - for active pattern names and so on. + Report a specific name resolution at a source range, replacing any previous resolutions - + - Defines a write-only stream used to capture output of the hosted F# Interactive dynamic compiler. + Report a specific method group name resolution at a source range - + - Feeds content into the stream. + Report a specific name resolution at a source range - + - Defines a read-only input stream used to feed content to the hosted F# Interactive dynamic compiler. + Report the active name resolution environment for a source range - + - Raised when an interaction is successfully typechecked and executed, resulting in an update to the - type checking state. - - This event is triggered after parsing and checking, either via input from 'stdin', or via a call to EvalInteraction. + Temporarily suspend reporting of name resolution and type checking results - + - A host calls this to get the active language ID if provided by fsi-server-lcid + Temporarily redirect reporting of name resolution and type checking results - + - A host calls this to determine if the --gui parameter is active + Hash compatible with ItemsAreEffectivelyEqual - + - The single, global interactive checker to use in conjunction with other operations - on the FsiEvaluationSession. - - If you are using an FsiEvaluationSession in this process, you should only use this InteractiveChecker - for additional checking operations. + Check for equality, up to signature matching - + - Get a handle to the dynamicly generated assembly + Qualified lookup of type names in the environment - + - Get a handle to the resolved view of the current signature of the incrementally generated assembly. + Add some declared type parameters to the name resolution environment - + - Load the dummy interaction, load the initial files, and, - if interacting, start the background thread to read the standard input. - - Performs these steps: - - Load the dummy interaction, if any - - Set up exception handling, if any - - Load the initial files, if any - - Start the background thread to read the standard input, if any - - Sit in the GUI event loop indefinitely, if needed + Add a list of modules or namespaces to the name resolution environment - + - A host calls this to report an unhandled exception in a standard way, e.g. an exception on the GUI thread gets printed to stderr + Add a single modules or namespace to the name resolution environment - + - Typecheck the given script fragment in the type checking context implied by the current state - of F# Interactive. The results can be used to access intellisense, perform resolutions, - check brace matching and other information. - - Operations may be run concurrently with other requests to the InteractiveChecker. - - Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - by input from 'stdin'. + Add a list of module or namespace to the name resolution environment, including any sub-modules marked 'AutoOpen' - + - A host calls this to request an interrupt on the evaluation thread. + Add a module abbreviation to the name resolution environment - + - Get a configuration that uses a private inbuilt implementation of the 'fsi' object and does not - implicitly reference FSharp.Compiler.Interactive.Settings.dll. + Add an F# exception definition to the name resolution environment - + - Get a configuration that uses the 'fsi' object (normally from FSharp.Compiler.Interactive.Settings.dll, - an object from another DLL with identical characteristics) to provide an implementation of the configuration. - FSharp.Compiler.Interactive.Settings.dll is referenced by default. + Add a list of type definitions to the name resolution environment - + - Get a configuration that uses the 'fsi' object (normally from FSharp.Compiler.Interactive.Settings.dll, - an object from another DLL with identical characteristics) to provide an implementation of the configuration. - The flag indicates if FSharp.Compiler.Interactive.Settings.dll is referenced by default. + Add active pattern result tags to the environment. - + - A host calls this to get the completions for a long identifier, e.g. in the console - - Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - by input from 'stdin'. + Add a single F# value to the environment. - + - Format a value to a string using the current PrintDepth, PrintLength etc settings provided by the active fsi configuration object + Add some extra items to the environment for Visual Studio, e.g. record members - + - Execute the given script. Stop on first error, discarding the rest - of the script. Errors and warnings are collected apart from any exception arising from execution - which is returned via a Choice. Execution is performed on the 'Run()' thread. - - Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - by input from 'stdin'. + Add extra items to the environment for Visual Studio, e.g. static members - + - Execute the given script. Stop on first error, discarding the rest - of the script. Errors are sent to the output writer, a 'true' return value indicates there - were no errors overall. Execution is performed on the 'Run()' thread. - - Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - by input from 'stdin'. + Find a field in anonymous record type - + - Execute the code as if it had been entered as one or more interactions, with an - implicit termination at the end of the input. Stop on first error, discarding the rest - of the input. Errors and warnings are collected apart from any exception arising from execution - which is returned via a Choice. Execution is performed on the 'Run()' thread. - - Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - by input from 'stdin'. + Detect a use of a nominal type, including type abbreviations. + When reporting symbols, we care about abbreviations, e.g. 'int' and 'int32' count as two separate symbols. - + - Execute the code as if it had been entered as one or more interactions, with an - implicit termination at the end of the input. Stop on first error, discarding the rest - of the input. Errors are sent to the output writer, a 'true' return value indicates there - were no errors overall. Execution is performed on the 'Run()' thread. - - Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - by input from 'stdin'. + Get the active pattern elements defined in a module, if any. Cache in the slot in the module type. - + - Execute the code as if it had been entered as one or more interactions, with an - implicit termination at the end of the input. Stop on first error, discarding the rest - of the input. Errors and warnings are collected apart from any exception arising from execution - which is returned via a Choice. Parsing is performed on the current thread, and execution is performed - sycnhronously on the 'main' thread. - - Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - by input from 'stdin'. + Used to report a warning condition for the use of upper-case identifiers in patterns - + - Execute the code as if it had been entered as one or more interactions, with an - implicit termination at the end of the input. Stop on first error, discarding the rest - of the input. Errors are sent to the output writer. Parsing is performed on the current thread, and execution is performed - sycnhronously on the 'main' thread. - - Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - by input from 'stdin'. + Used to report an error condition where name resolution failed due to an indeterminate type - + - Create an FsiEvaluationSession, reading from the given text input, writing to the given text output and error writers. - - <summary>Create an FsiEvaluationSession, reading from the given text input, writing to the given text output and error writers</summary> - - <param name="fsiConfig">The dynamic configuration of the evaluation session</param> - <param name="argv">The commmand line arguments for the evaluation session</param> - <param name="inReader">Read input from the given reader</param> - <param name="outWriter">Write output to the given writer</param> - <param name="collectible">Optionally make the dynamic assmbly for the session collectible</param> + Check the names add up between a signature and its implementation. We check this first. - + - Represents an F# Interactive evaluation session. + Primary relations on types and signatures, with the exception of + constraint solving and method overload resolution. - + - Implicitly reference FSharp.Compiler.Interactive.Settings.dll + A slot that *might* have ambiguity due to multiple inheritance; happens with default interface implementations. - + - Called by the evaluation session to ask the host for parameters to format text for output + Gets the method info. - + - Called by the evaluation session to ask the host for parameters to format text for output + A slot which does not have to be implemented, because an inherited implementation is available. - + - Called by the evaluation session to ask the host for parameters to format text for output + A slot which has a default interface implementation. + A combination of this flag and the lack of IsOptional means the slot may have been reabstracted. - + - Called by the evaluation session to ask the host for parameters to format text for output + The overall information about a method implementation in a class or object expression - + - Called by the evaluation session to ask the host for parameters to format text for output + Get the properties relevant to determining if a uniquely-identified-override exists based on the syntactic information + at the member signature prior to type inference. This is used to pre-assign type information if it does - + - Called by the evaluation session to ask the host for parameters to format text for output + Get the methods relevant to determining if a uniquely-identified-override exists based on the syntactic information + at the member signature prior to type inference. This is used to pre-assign type information if it does - + - Called by the evaluation session to ask the host for parameters to format text for output + "Type Completion" inference and a few other checks at the end of the inference scope - + - Hook for listening for evaluation bindings + Check that a type definition implements all its required interfaces after processing all declarations + within a file. - + - Called by the evaluation session to ask the host for parameters to format text for output + Get the slots of a type that can or must be implemented. This depends + partly on the full set of interface types that are being implemented + simultaneously, e.g. + { new C with interface I2 = ... interface I3 = ... } + allReqdTys = {C;I2;I3} + + allReqdTys can include one class/record/union type. - + - Called by the evaluation session to ask the host for parameters to format text for output + Check all implementations implement some dispatch slot. - + - Called by the evaluation session to ask the host for parameters to format text for output + Get a collection of slots for the given type and implied types. - + - The evaluation session calls this at an appropriate point in the startup phase if the --fsi-server parameter was given + Get a collection of slots for the given class type. - + - The evaluation session calls this to report the preferred view of the command line arguments after - stripping things like "/use:file.fsx", "-r:Foo.dll" etc. + Get a collection of slots for the given interface type. - + - Indicate a special console "readline" reader for the evaluation session, if any.  - - A "console" gets used if --readline is specified (the default on Windows + .NET); and --fsi-server is not - given (always combine with --readline-), and OptionalConsoleReadLine is given. - When a console is used, special rules apply to "peekahead", which allows early typing on the console. - Peekahead happens if --peekahead- is not specified (the default). - In this case, a prompt is printed early, a background thread is created and - the OptionalConsoleReadLine is used to read the first line. - If a console is not used, then inReader.Peek() is called early instead. -   - - Further lines are read using OptionalConsoleReadLine(). - If not provided, lines are read using inReader.ReadLine(). -   + Finds the override interface methods from the most specific overrides by the given method. - + - Schedule a restart for the event loop. + This is to find override methods that are at the most specific in the hierarchy of interface types. - + - Called by the evaluation session to ask the host to enter a dispatch loop like Application.Run(). - Only called if --gui option is used (which is the default). - Gets called towards the end of startup and every time a ThreadAbort escaped to the backup driver loop. - Return true if a 'restart' is required, which is a bit meaningless. + Check all dispatch slots are implemented by some override. - + - Request that the given operation be run synchronously on the event loop. + Check if a dispatch slot is already implemented - + - The FSharpSymbolUse for the symbol defined + Check if an override implements a dispatch slot - + - The symbol defined + Check if an override exactly matches the requirements for a dispatch slot. - + - The display name of the symbol defined + Check if an override exactly matches the requirements for a dispatch slot except for the name. - + - The details of the expression defined + Compose two instantiations of type parameters. - + - The value of the symbol defined, if any + Compute the reverse of a type parameter renaming. - + - The value, as an object + Check if an override is a partial match for the requirements for a dispatch slot. - + - The type of the value, from the point of view of the .NET type system + Check if an override is a partial match for the requirements for a dispatch slot except for the name. - + - Represents an evaluated F# value + Check if the kinds of type parameters match between a dispatch slot and an override. - - When set to 'false', disables the display of properties of evaluated objects in the output of the interactive session. + + + Check if an override matches a dispatch slot by name + - - When set to 'false', disables the display of sequences in the output of the interactive session. + + + Check if an override matches a dispatch slot by name + - - When set to 'false', disables the display of declaration values in the output of the interactive session. + + + Get the override information for an object expression method being used to implement dispatch slots + - - Get or set the print width of the interactive session. + + + Get the override info for a value being used to implement a dispatch slot. + - - Get or set the total print size of the interactive session. + + + Get the override info for an existing (inherited) method being used to implement a dispatch slot. + - - Get or set the total print length of the interactive session. + + + Format the signature of a MethInfo as a string as part of an error message + - - Get or set the print depth of the interactive session. + + + Format the signature of an override as a string as part of an error message + - - Get or set the format provider used in the output of the interactive session. + + + Print the signature of a MethInfo to a buffer as part of an error message + - - Get or set the floating point format used in the output of the interactive session. - - - Gets or sets a the current event loop being used to process interactions. - - - The command line arguments after ignoring the arguments relevant to the interactive - environment and replacing the first argument with the name of the last script file, - if any. Thus 'fsi.exe test1.fs test2.fs -- hello goodbye' will give arguments - 'test2.fs', 'hello', 'goodbye'. This value will normally be different to those - returned by System.Environment.GetCommandLineArgs. - - - When set to 'false', disables the display of properties of evaluated objects in the output of the interactive session. - - - When set to 'false', disables the display of sequences in the output of the interactive session. - - - When set to 'false', disables the display of declaration values in the output of the interactive session. - - - Get or set the print width of the interactive session. - - - Get or set the total print size of the interactive session. - - - Get or set the total print length of the interactive session. - - - Get or set the print depth of the interactive session. - - - Get or set the format provider used in the output of the interactive session. - - - Get or set the floating point format used in the output of the interactive session. - - - Gets or sets a the current event loop being used to process interactions. - - - The command line arguments after ignoring the arguments relevant to the interactive - environment and replacing the first argument with the name of the last script file, - if any. Thus 'fsi.exe test1.fs test2.fs -- hello goodbye' will give arguments - 'test2.fs', 'hello', 'goodbye'. This value will normally be different to those - returned by System.Environment.GetCommandLineArgs. - - - Register a printer that controls the output of the interactive session. - - - Register a print transformer that controls the output of the interactive session. - - - Operations supported by the currently executing F# Interactive session. - - - Schedule a restart for the event loop. - - - Run the event loop. - True if the event loop was restarted; false otherwise. - - - Request that the given operation be run synchronously on the event loop. - The result of the operation. - - - An event loop used by the currently executing F# Interactive session to execute code - in the context of a GUI or another event-based system. - - + - A default implementation of the 'fsi' object, used by GetDefaultConfiguration(). Note this - is a different object to FSharp.Compiler.Interactive.Settings.fsi in FSharp.Compiler.Interactive.Settings.dll, - which can be used as an alternative implementation of the interactiev settings if passed as a parameter - to GetDefaultConfiguration(fsiObj). + Print the signature of an override to a buffer as part of an error message - + - A default implementation of the 'fsi' object, used by GetDefaultConfiguration() + Primary logic related to method overrides. - + - This represents the global state established as each task function runs as part of the build. - - Use to reset error and warning handlers. + method parameters - + - Get the captured errors + unnamed called out args: return these as part of the return tuple - + - Create the error logger + unnamed called optional args: pass defaults for these - + - An error logger that capture errors, filtering them according to warning levels etc. + unassigned args - + - A list of data tip elements to display. + the method we're attempting to call - + - Information for building a tool tip box. + the formal instantiation of the method we're attempting to call - + - A single data tip display element with where text is expressed as <see cref="Layout"/> + The types of the actual object arguments, if any - + - A single data tip display element with where text is expressed as string + the instantiation of the method we're attempting to call - + - An error occurred formatting this element + the instantiation of the method we're attempting to call - + - A single type, method, etc with comment. May represent a method overload group. + return type after tupling of out args is taken into account - + - A single tool tip display element + return type after implicit deference of byref returns is taken into account - + - Parameter name + args assigned to specify values for attribute fields and properties (these are not necessarily "property sets") - + - Extra text, goes at the end + the property related to the method we're attempting to call, if any - + - typar insantiation text, to go after xml + named setters - + - A single data tip display element + The argument analysis for each set of curried arguments - + - Indicates that the text for the documentation can be found in a .xml documentation file, using the given signature key + Represents the syntactic matching between a caller of a method and the called method. + + The constructor takes all the information about the caller and called side of a method, match up named arguments, property setters etc., + and returns a CalledMeth object for further analysis. - + - The text for documentation + Named args - + - No documentation is available + Any unnamed caller arguments assigned to a "param array" argument - + - Describe a comment as either a block of text or a file+signature reference into an intellidoc file. + The called "ParamArray" argument, if any - + - The symbol referenced + Any unnamed caller arguments not otherwise assigned - + - The range of text representing the reference to the symbol + The called arguments corresponding to "unnamed" arguments - + - Indicates if the reference is in a syntactic type + Represents the list of unnamed / named arguments at method call site + remark: The usage of list list is due to tupling and currying of arguments, + stemming from SynValInfo in the AST. - + - Indicates if the reference is in a pattern + Represents the resolution of a caller argument as a named-setter argument - + - Indicates if the reference is in open statement + Represents the possibilities for a named-setter argument (a property, field, or a record field setter) - + - Indicates if the reference is via the member being implemented in a class or object expression + The argument on the caller side - + - Indicates if the reference is a definition for the symbol, either in a signature or implementation + The called argument in the method - + - Indicates if the reference is either a builder or a custom operation in a computation expression + The identifier for a named argument, if any - + - Indicates if the reference is in an attribute + Represents a match between a caller argument and a called argument, arising from either + a named argument or an unnamed argument. - + - The file name the reference occurs in + Represents the information about an argument in the method being called - + - The display context active at the point where the symbol is used. Can be passed to FSharpType.Format - and other methods to format items in a way that is suitable for a specific source code location. + CallerArg(ty, range, isOpt, exprInfo) - + - Represents the use of an F# symbol from F# source code + In the following, 'T gets instantiated to: + 1. the expression being supplied for an argument + 2. "unit", when simply checking for the existence of an overload that satisfies + a signature, or when finding the corresponding witness. + Note the parametricity helps ensure that overload resolution doesn't depend on the + expression on the callside (though it is in some circumstances allowed + to depend on some type information inferred syntactically from that + expression, e.g. a lambda expression may be converted to a delegate as + an adhoc conversion. + + The bool indicates if named using a '?', making the caller argument explicit-optional - + - Range of the open declaration. + Generate a witness for the given (solved) constraint. Five possiblilities are taken + into account. + 1. The constraint is solved by a .NET-declared method or an F#-declared method + 2. The constraint is solved by an F# record field + 3. The constraint is solved by an F# anonymous record field + 4. The constraint is considered solved by a "built in" solution + 5. The constraint is solved by a closed expression given by a provided method from a type provider + + In each case an expression is returned where the method is applied to the given arguments, or the + field is dereferenced. + + None is returned in the cases where the trait has not been solved (e.g. is part of generic code) + or there is an unexpected mismatch of some kind. - + - Modules or namespaces which is opened with this declaration. + Build the argument list for a method call. Adjust for param array, optional arguments, byref arguments and coercions. + For example, if you pass an F# reference cell to a byref then we must get the address of the + contents of the ref. Likewise lots of adjustments are made for optional arguments etc. - + - Idents. + Adjust any '[<ParamArray>]' arguments, converting to an array - + - If it's `namespace Xxx.Yyy` declaration. + Adjust any 'out' arguments, passing in the address of a mutable local - + - Scope in which open declaration is visible. + Get the expression that must be inserted on the caller side for an optional arg where + no caller argument has been provided. - + - Represents open declaration in F# code. + Get the expression that must be inserted on the caller side for a CalleeSide optional arg where + no caller argument has been provided. Normally this is 'None', however CallerMemberName and friends + can be used with 'CalleeSide' optional arguments - + - The named arguments for the attribute + Get the expression that must be inserted on the caller side for a CallerSide optional arg, + i.e. one where there is no corresponding caller arg. - + - Indicates if the attribute type is in an unresolved assembly + Some of the code below must allocate temporary variables or bind other variables to particular values. + As usual we represent variable allocators by expr -> expr functions + which we then use to wrap the whole expression. These will either do nothing or pre-bind a variable. It doesn't + matter what order they are applied in as long as they are all composed together. - + - The arguments to the constructor for the attribute + Implements the elaborated form of adhoc conversions from functions to delegates at member callsites - + - The type of the attribute + Build a call to the System.Object constructor taking no arguments, - + - Format the attribute using the rules of the given display context + Build an expression that calls a given method info. + This is called after overload resolution, and also to call other + methods such as 'setters' for properties. - + - Represents a custom attribute attached to F# source code or a compiler .NET component + Make a call to a method info. Used by the optimizer and code generator to build + calls to the type-directed solutions to member constraints. - + - Get the type definition for a type + Build a call to an F# method. - + - Indicates this is a named type in an unresolved assembly + Build a call to an F# method. + + Consume the arguments in chunks and build applications. This copes with various F# calling signatures + all of which ultimately become 'methods'. + + QUERY: this looks overly complex considering that we are doing a fundamentally simple + thing here. - + - Indicates if the type is a tuple type (reference or struct). The GenericArguments property returns the elements of the tuple type. + Build an expression node that is a call to a .NET method. - + - Indicates if the type is a struct tuple type. The GenericArguments property returns the elements of the tuple type. + Adjust the 'this' pointer before making a call + Take the address of a struct, and coerce to an interface/base/constraint type if necessary - + - Indicates if the type is a variable type, whether declared, generalized or an inference type parameter + Compute whether we insert a 'coerce' on the 'this' pointer for an object model call + For example, when calling an interface method on a struct, or a method on a constrained + variable type. - + - Indicates if the type is a function type. The GenericArguments property returns the domain and range of the function type. + Is this a 'base' call (in the sense of C#) - + - Indicates if the type is an anonymous record type. The GenericArguments property returns the type instantiation of the anonymous record type + Adjust the called argument type to take into account whether the caller's argument is CSharpMethod(?arg=Some(3)) or CSharpMethod(arg=1) - + - Indicates this is an abbreviation for another type + Erasure over System.Type. + + This is a reimplementation of the logic of provided-type erasure, working entirely over (tainted, provided) System.Type + values. This is used when preparing ParameterInfo objects to give to the provider in GetInvokerExpression. + These ParameterInfo have erased ParameterType - giving the provider an erased type makes it considerably easier + to implement a correct GetInvokerExpression. + + Ideally we would implement this operation by converting to an F# TType using ImportSystemType, and then erasing, and then converting + back to System.Type. However, there is currently no way to get from an arbitrary F# TType (even the TType for + System.Object) to a System.Type to give to the type provider. - + - Indicates if the type is constructed using a named entity, including array and byref types + Logic associated with resolving method calls. - + - Get the generic parameter data for a generic parameter type + Represents the typechecked, elaborated form of a pattern, prior to pattern-match compilation. - + - Get the generic arguments for a tuple type, a function type or a type constructed using a named entity + What should the decision tree contain for any incomplete match? - + - Get the base type, if any, taking into account the instantiation of this type - if it is an instantiation of a generic type. + Compile a pattern into a decision tree and a set of targets. - + - Get the details of the anonymous record type. + A function that denotes captured tcVal, Used in constraint solver and elsewhere to get appropriate expressions for a ValRef. - + - Get all the interface implementations, by walking the type hierarchy, taking into account the instantiation of this type - if it is an instantiation of a generic type. + Cases for overload resolution failure that exists in the implementation of the compiler. - + - Get the type for which this is an abbreviation + Captures relevant information for a particular failed overload resolution. - + - Adjust the types in a group of curried parameters and return type by removing any occurrences of type inference variables, replacing them - systematically with lower-case type inference variables such as <c>'a</c>. + The type equation comes from a sequence expression. - + - Adjust the types in a group of curried parameters by removing any occurrences of type inference variables, replacing them - systematically with lower-case type inference variables such as <c>'a</c>. + The type equation comes from a pattern match guard. - + - Adjust the types in a group of parameters by removing any occurrences of type inference variables, replacing them - systematically with lower-case type inference variables such as <c>'a</c>. + The type equation comes from a return type of a pattern match clause (not the first clause). - + - Adjust the type in a single parameter by removing any occurrences of type inference variables, replacing them - systematically with lower-case type inference variables such as <c>'a</c>. + The type equation comes from an downcast where a upcast could be used. - + - Adjust a group of types by removing any occurrences of type inference variables, replacing them - systematically with lower-case type inference variables such as <c>'a</c>. + The type equation comes from a runtime type test. - + - Adjust the type by removing any occurrences of type inference variables, replacing them - systematically with lower-case type inference variables such as <c>'a</c>. + The type equation comes from a yield in a computation expression. - + - Instantiate generic type parameters in a type + The type equation comes from a return in a computation expression. - + - Format the type using the rules of the given display context + The type equation comes from a list or array constructor - + - Format the type using the rules of the given display context + The type equation comes from the verification of a tuple in record fields. - + - Internal use only. Create a ground type. + The type equation comes from the verification of record fields. - + - Get the type indicating signature of the active pattern + The type equation comes from a type check of the result of an else branch. - + - The names of the active pattern cases + The type equation comes from an omitted else branch. - + - The whole group name + The type equation comes from an IF expression. - + - Indicate this is a total active pattern + No context was given. - + - Try to get the entity in which the active pattern is declared + Information about the context of a type equation. - + - Represents all cases within an active pattern + Remove the global constraints where these type variables appear in the support of the constraint - + - XML documentation signature for the active pattern case, used for .xml file lookup for compiled code + 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. - + - Get the in-memory XML documentation for the active pattern case, used when code is checked in-memory + Create a list of inference type variables, one for each element in the input list - + - The name of the active pattern case + Create an inference type variable representing an error condition when checking a measure - + - Index of the case in the pattern group + Create an inference type variable representing an error condition when checking an expression - + - The group of active pattern cases this belongs to + Create an inference type variable for the kind of a byref pointer - + - The location of declaration of the active pattern case + Create an inference type variable - + - A subtype of FSharpSymbol that represents a single case within an active pattern + Create a type variable representing the use of a "_" in F# code - + - The declared or inferred type of the parameter + Solves constraints using a mutable constraint-solver state - + - The optional name of the parameter + Parse "printf-style" format specifiers at compile time, producing + a list of items that specify the types of the things that follow. + + Must be updated if the Printf runtime component is updated. - + - Indicate this is a param array argument + Find all unsolved inference variables after type inference for an entire file - + - Indicate this is an out argument + Indicates that type references are emitted as integer indexes into a supplied table - + - Indicate this is an optional argument + Convert quoted TAST data structures to structures ready for pickling - + - Indicate this is an in argument + Perform the checks on the TAST for a file after type inference is complete. - + - The declaration location of the parameter + Implements a set of checks on the TAST for a file that can only be performed after type inference + is complete. - + - The declared attributes of the parameter + Optimization information - + - A subtype of FSharpSymbol that represents a parameter + Check if an expression has an effect - + - XML documentation signature for the value, used for .xml file lookup for compiled code + Combine optimization infos - + - Get the in-memory XML documentation for the value, used when code is checked in-memory + Ensure that 'internal' items are not exported in the optimization info - + - Get an associated setter method of the property + Rewrite the module info using the export remapping - + - Get the logical name of the member + Saving and re-reading optimization information - + - Indicates if this is a [<Literal>] value, and if so what value? (may be null) + Optimize one implementation file in the given environment - + - Indicated if this is a value + For building optimization environments incrementally - + - Indicated if this is a value compiled to a method + top of expr toplevel? (true) - + - Indicates if the member, function or value is in an unresolved assembly + val not defined under lambdas - + - Indicates if this is an F# type function + v -> recursive? * v list -- the others in the mutual binding - + - Indicates if this is a setter method for a property, or a use of a property in setter mode + bound in a decision tree? - + - Indicates if this is a setter method for a property, or a use of a property in setter mode + v -> binding repr - + - Indicates if this is a getter method for a property, or a use of a property in getter mode + v -> context / APP inst args - + - Indicates if this is a property member + Results is "expr information". + This could extend to be a full graph view of the expr. + Later could support "safe" change operations, and optimisations could be in terms of those. - + - Indicates if this is an 'override', 'default' or an explicit implementation of an interface member + Analyze a TAST expression to detect the elaborated form of a sequence expression. + Then compile it to a state machine represented as a TAST containing goto, return and label nodes. + The returned state machine will also contain references to state variables (from internal 'let' bindings), + a program counter (pc) that records the current state, and a current generated value (current). + All these variables are then represented as fields in a hosting closure object along with any additional + free variables of the sequence expression. - + - Indicates if this is a mutable value + An "expr -> expr" pass that eta-expands under-applied values of + known arity to lambda expressions and beta-var-reduces to bind + any known arguments. The results are later optimized by the peephole + optimizer in opt.fs - + - Indicates if this is a module or member value + Rewrite mutable locals to reference cells across an entire implementation file - + - Indicates if this is the "x" in "member x.M = ..." + Invert the compilation of the given value and return its current dynamic value and its compiled System.Type - + - Indicates if this is a member, including extension members? + Generate ILX code for an assembly fragment - + - Indicates if this is an instance member in compiled code. - - Explanatory note: some members such as IsNone and IsSome on types with UseNullAsTrueValue appear - as instance members in F# code but are compiled as static members. + Invert the compilation of the given value and clear the storage of the value - + - Indicates if this is an instance member, when seen from F#? + Register a fragment of the current assembly with the ILX code generator. If 'isIncrementalFragment' is true then the input + is assumed to be a fragment 'typed' into FSI.EXE, otherwise the input is assumed to be the result of a '#load' - + - Indicates if this is an implicit constructor? + Register a set of referenced assemblies with the ILX code generator - + - Indicates if this is a getter method for a property, or a use of a property in getter mode + Create an incremental ILX code generator for a single assembly - + - Indicates if this is an extension member? + An incremental ILX code generator for a single assembly - + - Indicates if this is an explicit implementation of an interface member + Used to support the compilation-inversion operations "ClearGeneratedValue" and "LookupGeneratedValue" - + - Indicates if this is a remove method for an event + The generated IL/ILX resources associated with F# quotations - + - Indicates if this is an add method for an event + The security attributes to attach to the assembly - + - Indicates if this is an event member + The attributes for the assembly in F# form - + - Indicates if this is an abstract member? + The generated IL/ILX .NET module attributes - + - Indicates if this is the "x" in "type C() as x = ..." + The generated IL/ILX assembly attributes - + - Indicates if this is a constructor. + The generated IL/ILX type definitions - + - Indicates if this is a compiler generated value + The results of the ILX compilation of one fragment of an assembly - + - Indicates if this is "base" in "base.M(...)" + Indicates that, whenever possible, use callvirt instead of call - + - Indicates if this value or member is an F# active pattern + Indicates the code generated is an interactive 'it' expression. We generate a setter to allow clearing of the underlying + storage, even though 'it' is not logically mutable - + - Get a result indicating if this is a must-inline value + Indicates the code is being generated in FSI.EXE and is executed immediately after code generation + This includes all interactively compiled code, including #load, definitions, and expressions - + - Gets the list of the abstract slot signatures implemented by the member + Indicates which backend we are generating code for - + - Indicates if this is a property and there exists an associated setter method + A flag to help test emit of debug information - + - Indicates if this is a property and there exists an associated getter method + Indicates if we are generating debug symbols or not - + - Get an associated getter method of the property + Indicates if local optimizations are active - + - Get the typars of the member, function or value + If this is set, then the last module becomes the "main" module - + - Get the full type of the member, function or value when used as a first class value + Indicates if static array data should be emitted using static blobs - + - Get an associated remove method of an event + Indicates if we should workaround old reflection emit bugs - + - Indicate if an event can be considered to be a property for the F# type system of type IEvent or IDelegateEvent. - In this case ReturnParameter will have a type corresponding to the property type. For - non-standard events, ReturnParameter will have a type corresponding to the delegate type. + Indicates if we are generating filter blocks - + - Gets the event symbol implied by the use of a property, - for the case where the property is actually an F#-declared CLIEvent. - - Uses of F#-declared events are considered to be properties as far as the language specification - and this API are concerned. + Indicates how the generated IL code is ultimately emitted - + - Get an associated delegate type of an event + Determine if an F#-declared value, method or function is compiled as a method. - + - Get an associated add method of an event + Gets the tfm E.g netcore3.0, net472 - + - Get the name as presented in F# error messages and documentation + Diagnostics seen while processing the compiler options implied root of closure - + - Get the enclosing entity for the definition + Diagnostics to show for root of closure (used by fsc.fs) - + - Get the declaration location of the member, function or value + Diagnostics seen while processing resolutions - + - Get the member name in compiled code + The #nowarns - + - Custom attributes attached to the value. These contain references to other values (i.e. constructors in types). Mutable to fixup - these value references after copying a collection of values. + The original #load references, including those that didn't resolve - + - Get the logical enclosing entity, which for an extension member is type being extended + The list of all sources in the closure with inputs when available, with associated parse errors and warnings - + - Get the accessibility information for the member, function or value + The list of references that were not resolved during load closure. - + - Gets the overloads for the current method - matchParameterNumber indicates whether to filter the overloads to match the number of parameters in the current symbol + The resolved references along with the ranges of the #r positions in each file. - + - Format the type using the rules of the given display context + The source files along with the ranges of the #load positions in each file. - + - A subtype of F# symbol that represents an F# method, property, event, function or value, including extension members. + A temporary TcConfig is created along the way, is why this routine takes so many arguments. We want to be sure to use exactly the + same arguments as the rest of the application. - + - Indicates the value is aggressively inlined by the .NET runtime + Analyze a set of script files and find the closure of their references. The resulting references are then added to the given TcConfig. + Used from fsi.fs and fsc.fs, for #load and command line. - + - Indicates the value is never inlined + Get the typing environment implied by the set of signature files and/or inferred signatures of implementation files checked so far - + - Indicates the value is optionally inlined + Get the typing environment implied by the set of implementation files checked so far - + - Indicates the value is inlined but compiled code for the function still exists, e.g. to satisfy interfaces on objects, but that it is also always inlined + The inferred contents of the assembly, containing the signatures of all files. - + - Indicates the value is inlined and compiled code for the function does not exist + The CcuThunk for the current assembly being checked - + - Gets further information about a choice constraint + Represents the incremental type checking state for a set of inputs - + - Gets further information about a member constraint + Try to resolve a referenced assembly based on TcConfig settings. - + - Indicates a constraint that a type is an unmanaged type + Try to find a provider-generated assembly - + - Indicates a constraint that a type has a 'null' value + Try to find the given assembly reference by simple name. Used in magic assembly resolution. Effectively does implicit + unification of assemblies by simple assembly name. - + - Indicates a constraint that is a type is a simple choice between one of the given ground types. Used by printf format strings. + Try to find the given assembly reference. - + - Indicates a constraint that a type has a parameterless constructor + Resolve a referenced assembly and report an error if the resolution fails. - + - Indicates a constraint that a type is a reference type + Report unresolved references that also weren't consumed by any type providers. - + - Indicates a constraint that a type is a non-Nullable value type + This excludes any framework imports (which may be shared between multiple builds) - + - Indicates a constraint that a type has a member with the given signature + Represents a table of imported assemblies with their resolutions. + Is a disposable object, but it is recommended not to explicitly call Dispose unless you absolutely know nothing will be using its contents after the disposal. + Otherwise, simply allow the GC to collect this and it will properly call Dispose from the finalizer. - + - Indicates a constraint that a type supports F# generic equality + Represents a resolved imported assembly - + - Indicates a constraint that a type is an enum with the given underlying + Represents a resolved imported binary - + - Indicates a constraint that a type is a delegate from the given tuple of args to the given return type + Get a TcConfigProvider which will return only the exact TcConfig. - + - Indicates a default value for an inference type variable should it be neither generalized nor solved + Get a TcConfigProvider which will continue to respect changes in the underlying + TcConfigBuilder rather than delivering snapshots. - + - Indicates a constraint that a type supports F# generic comparison + Represents a computation to return a TcConfig. Normally this is just a constant immutable TcConfig, + but for F# Interactive it may be based on an underlying mutable TcConfigBuilder. - + - Indicates a constraint that a type is a subtype of the given type + Set if the user has explicitly turned indentation-aware syntax on/off - + - Gets further information about an enumeration constraint + If true, indicates all type checking and code generation is in the context of fsi.exe - + - Gets further information about a delegate constraint + File system query based on TcConfig settings - + - Gets further information about a defaults-to constraint + File system query based on TcConfig settings - + - Gets further information about a coerces-to constraint + Get the loaded sources that exist and issue a warning for the ones that don't - + - Represents a constraint on a generic type parameter + Prevent erasure of conditional attributes and methods so tooling is able analyse them. - + - Get the default type associated with the 'defaults to' constraint + if true - 'let mutable x = Span.Empty', the value 'x' is a stack referring span. Used for internal testing purposes only until we get true stack spans. - + - Get the priority off the 'defaults to' constraint + A function to call to try to get an object that acts as a snapshot of the metadata section of a .NET binary, + and from which we can read the metadata. Only used when metadataOnly=true. - + - Represents further information about a 'defaults to' constraint on a generic type parameter + If true, indicates all type checking and code generation is in the context of fsi.exe - + - Get the tupled argument type required by the constraint + Sources added into the build with #load - + - Get the return type required by the constraint + Set if the user has explicitly turned indentation-aware syntax on/off - + - Represents further information about a delegate constraint on a generic type parameter + Represents the file or string used for the --version flag - + - Get the types that may be used to satisfy the constraint + Enqueue work to be done on a compilation thread. - + - Get the return type of the method required by the constraint + The thread in which compilation calls will be enqueued and done work on. + Note: This is currently only used when disposing of type providers and will be extended to all the other type provider calls when compilations can be done in parallel. + Right now all calls in FCS to type providers are single-threaded through use of the reactor thread. - + - Get the name of the method required by the constraint + Whether or not this is an installed system assembly (for example, System.dll) - + - Indicates if the the method required by the constraint must be static + Create the tooltip text for the assembly reference - + - Get the argument types of the method required by the constraint + Path to the resolvedFile - + - Represents further information about a member constraint on a generic type parameter + The original reference to the assembly. - + - Get the name of the static parameter + The name of the assembly file generated by the project - + - Get the kind of the static parameter + Get the logical timestamp that would be the timestamp of the assembly file generated by the project. + + For project references this is maximum of the timestamps of all dependent files. + The project is not actually built, nor are any assemblies read, but the timestamps for each dependent file + are read via the FileSystem. If the files don't exist, then a default timestamp is used. + + The operation returns None only if it is not possible to create an IncrementalBuilder for the project at all, e.g. if there + are fatal errors in the options for the project. - + - Indicates if the static parameter is optional + Evaluate raw contents of the assembly file generated by the project - + - Get the default value for the static parameter + The identity of the module - + - Get the declaration location of the static parameter + The raw IL module definition in the assembly, if any. This is not present for cross-project references + in the language service - + - A subtype of FSharpSymbol that represents a static parameter to an F# type provider + The table of type forwarders in the assembly - + - Get the in-memory XML documentation for the type parameter, used when code is checked in-memory + The raw F# signature data in the assembly, if any - + - Get the name of the generic parameter + The raw F# optimization data in the assembly, if any - + - Indicates if this is a statically resolved type variable + The raw list InternalsVisibleToAttribute attributes in the assembly - + - Indicates if this is a measure variable + The raw list AutoOpenAttribute attributes in the assembly - + - Indicates if this is a compiler generated type parameter + Represents a reference to an F# assembly. May be backed by a real assembly on disk (read by Abstract IL), or a cross-project + reference in FSharp.Compiler.Service. - + - Get the range of the generic parameter + Part of LegacyHostedCompilerForTesting - + - Get the declared or inferred constraints for the type parameter + Part of LegacyHostedCompilerForTesting - + - Get the declared attributes of the type parameter. + Part of LegacyHostedCompilerForTesting - + - A subtype of FSharpSymbol that represents a generic parameter for an FSharpSymbol + Part of LegacyHostedCompilerForTesting - + - Represents the rights of a compilation to access symbols + State used to de-deduplicate module names along a list of file names - + - Get the XML documentation signature for .xml file lookup for the field, used for .xml file lookup for compiled code + Indicates if we should report a warning as an error - + - Get the in-memory XML documentation for the field, used when code is checked in-memory + Indicates if we should report a warning - + - Get the attributes attached to generated property + Check a single input and finish the checking - + - Get the name of the field + Check a closed set of inputs - + - Get the default initialization info, for static literals + Finish the checking of a closed set of inputs - + - Indicates if the field is declared volatile + Finish the checking of multiple inputs - + - Indicates if the record field is for a type in an unresolved assembly + Check one input, returned as an Eventually computation - + - Indicates a static field + Get the initial type checking state for a set of inputs - + - Indicates if the field name was generated by compiler (e.g. ItemN names in union cases and DataN in exceptions). - This API returns true for source defined symbols only. + Get the initial type checking environment including the loading of mscorlib/System.Core, FSharp.Core + applying the InternalsVisibleTo in referenced assemblies and opening 'Checked' if requested. - + - Indicates if the field is declared 'static' + Parse one input file - + - Indicates if the field has a literal value + This list is the default set of references for "non-project" files. - + - Indicates if the field declared is declared 'DefaultValue' + Get an error logger that filters the reporting of warnings based on scoped pragma information - + - Indicates a compiler generated field, not visible to Intellisense or name resolution + Find the scoped #nowarn pragmas with their range information - + - Is this a field from an anonymous record type? + Process the #nowarn in an input - + - Get the type of the field, w.r.t. the generic parameters of the enclosing type constructor + Process all the #r, #I etc. in an input - + - Get the attributes attached to generated field + Processing # commands - + - Get the declaring entity of this field, if any. Fields from anonymous types do not have a declaring entity + Process #r in F# Interactive. + Adds the reference to the tcImports and add the ccu to the type checking environment. - + - Get the declaration location of the field + Write F# optimization data as an IL resource - + - If the field is from an anonymous record type then get the details of the field including the index in the sorted array of fields + Write F# signature data as an IL resource - + - Indicates if the declared visibility of the field, not taking signatures into account + Determine if an IL resource attached to an F# assembly is an F# quotation data resource for reflected definitions - + - A subtype of FSharpSymbol that represents a record or union case field as seen by the F# language + Determine if an IL resource attached to an F# assembly is an F# optimization data resource - + - The sorted labels of the anonymous type + Determine if an IL resource attached to an F# assembly is an F# signature data resource - + - Names of any enclosing types of the compiled form of the anonymous type (if the anonymous type was defined as a nested type) + Part of LegacyHostedCompilerForTesting - + - The name of the compiled form of the anonymous type + Output extra context information for an error or warning to a buffer - + - The assembly where the compiled form of the anonymous type is defined + Output an error or warning to a buffer - + - A subtype of FSharpSymbol that represents a record or union case field as seen by the F# language + Output an error to a buffer - + - Get the XML documentation signature for .xml file lookup for the union case, used for .xml file lookup for compiled code + Split errors into a "main" error and a set of associated errors - + - Get the in-memory XML documentation for the union case, used when code is checked in-memory + Get the number associated with an error - + - Get the data carried by the case. + Get the location associated with an error - + - Get the type constructed by the case. Normally exactly the type of the enclosing type, sometimes an abbreviation of it + Parse a single input (A signature file or implementation file) - + - Get the name of the union case + Checks if a ParsedInput is using a module name that was already given and deduplicates the name if needed. - + - Indicates if the union case is for a type in an unresolved assembly + Get the name used for FSharp.Core - + - Get the range of the name of the case + File suffixes where #light is the default - + - Get the name of the case in generated IL code + Script file suffixes - + - Get the attributes for the case, attached to the generated static method to make instances of the case + Implementation file suffixes - + - Indicates if the declared visibility of the union constructor, not taking signatures into account + Signature file suffixes - + - A subtype of FSharpSymbol that represents a union case as seen by the F# language + Coordinating compiler operations - configuration, loading initial context, reporting errors etc. - + - Get the name of the abstract slot + CompilerOption(name, argumentDescriptionString, actionSpec, exceptionOpt, helpTextOpt - + - Get the generic arguments of the abstract slot + The spec value describes the action of the argument, + and whether it expects a following parameter. - + - Get the generic arguments of the type defining the abstract slot + Apply args to TcConfigBuilder and return new list of source files - + - Get the declaring type of the abstract slot + Parse and process a set of compiler options - + - Get the return type of the abstract slot + The default ErrorLogger implementation, reporting messages to the Console up to the maxerrors maximum - + - Get the arguments of the abstract slot + Part of LegacyHostedCompilerForTesting - + - Represents the signature of an abstract slot of a class or interface + Process the given set of command line arguments - + - The declared or inferred type of the parameter + Set the concrete inputs for this build. - + - The optional name of the parameter + Declare a named vector output. - + - Indicate this is an out argument + Declare a named scalar output. - + - Indicate this is an optional argument + Declare build outputs and bind them to real values. + Only required for unit testing. - + - Indicate this is an in argument + Declare a named scalar output. - + - The declared attributes of the parameter + A set of build rules and the corresponding, possibly partial, results from building. - + - Represents a parameter in an abstract method of a class or interface + Get an element of vector result or None if there were no results. Only required for unit testing. - + - Get the return type of the delegate signature + Get a result vector. All results must be available or thrown an exception. Only required for unit testing. - + - Get the argument types of the delegate signature + Get a scalar vector. Result must be available. Only required for unit testing. - + - Represents a delegate signature in an F# symbol + Do one step in the build. Only required for unit testing. - + - Get the XML documentation signature for the entity, used for .xml file lookup for compiled code + Evaluate a build for a vector up to a limit. Only required for unit testing. - + - Get the in-memory XML documentation for the entity, used when code is checked in-memory + Evaluate a build. Only required for unit testing. - + - Indicates if the type prefers the "tycon<a,b>" syntax for display etc. + Used for unit testing. Causes all steps of underlying incremental graph evaluation to cancel - + - Get the cases of a union type + Declares a scalar build input. + Only required for unit testing. - + - Get the full name of the type or module if it is available + Declares a vector build input. + Only required for unit testing. - + - Get the static parameters for a provided type + Convert a Vector into a Scalar. - + - Get the declared accessibility of the representation, not taking signatures into account + Apply a function to a vector to get a scalar value. - + - Get the fully qualified name of the type or module + Apply a function to each element of the vector, threading an accumulator argument + through the computation. Returns intermediate results in a vector. - + - Get the modules and types defined in a module, or the nested types of a type + Updates the creates a new vector with the same items but with + timestamp specified by the passed-in function. - + - Get the namespace containing the type or module, if any. Use 'None' for item not in a namespace. + Maps one vector to another using the given function. - + - Get the properties, events and methods of a type definitions, or the functions and values of a module + Methods for acting on build Vectors + Only required for unit testing. - + - Get the name of the type or module, possibly with `n mangling + Generalized Incremental Builder. This is exposed only for unit testing purposes. - + - Indicates if the entity is a struct or enum + Used for unit testing - + - Indicates if the entity is in an unresolved assembly + Tests whether the user is typing something like "member x." or "override (*comment*) x." - + - Indicates if the entity is a 'fake' symbol related to a static instantiation of a type provider + Get the partial long name of the identifier to the left of index. + For example, for `System.DateTime.Now` it returns PartialLongName ([|"System"; "DateTime"|], "Now", Some 32), where "32" pos of the last dot. - + - Indicates if the entity is a generated provided type + Get the partial long name of the identifier to the left of index. - + - Indicates if the entity is an erased provided type + Given a string and a position in that string, find an identifier as + expected by `GotoDefinition`. This will work when the cursor is + immediately before the identifier, within the identifier, or immediately + after the identifier. + + 'tolerateJustAfter' indicates that we tolerate being one character after the identifier, used + for goto-definition + + In general, only identifiers composed from upper/lower letters and '.' are supported, but there + are a couple of explicitly handled exceptions to allow some common scenarios: + - When the name contains only letters and '|' symbol, it may be an active pattern, so we + treat it as a valid identifier - e.g. let ( |Identity| ) a = a + (but other identifiers that include '|' are not allowed - e.g. '||' operator) + - It searches for double tick (``) to see if the identifier could be something like ``a b`` + + REVIEW: Also support, e.g., operators, performing the necessary mangling. + (i.e., I would like that the name returned here can be passed as-is + (post `.`-chopping) to `GetDeclarationLocation.) + + In addition, return the position where a `.` would go if we were making + a call to `DeclItemsForNamesAtPosition` for intellisense. This will + allow us to use find the correct qualified items rather than resorting + to the more expensive and less accurate environment lookup. - + - Indicates if the entity is a provided type + Puts us after the last character. - + - Indicates if the entity is a type definition for a reference type where the implementation details are hidden by a signature + Methods for cheaply and inaccurately parsing F#. + + These methods are very old and are mostly to do with extracting "long identifier islands" + A.B.C + from F# source code, an approach taken from pre-F# VS samples for implementing intelliense. + + This code should really no longer be needed since the language service has access to + parsed F# source code ASTs. However, the long identifiers are still passed back to GetDeclarations and friends in the + F# Compiler Service and it's annoyingly hard to remove their use completely. + + In general it is unlikely much progress will be made by fixing this code - it will be better to + extract more information from the F# ASTs. + + It's also surprising how hard even the job of getting long identifier islands can be. For example the code + below is inaccurate for long identifier chains involving ``...`` identifiers. And there are special cases + for active pattern names and so on. - + - Indicates if the entity is a part of a namespace path + Defines a write-only stream used to capture output of the hosted F# Interactive dynamic compiler. - + - Indicates if the entity is a measure definition + Feeds content into the stream. - + - Indicates if the entity is an interface type definition + Defines a read-only input stream used to feed content to the hosted F# Interactive dynamic compiler. - + - Indicates if the entity is union type + Event fires when a root-level value is bound to an identifier, e.g., via `let x = ...`. - + - Indicates if the entity is record type + Raised when an interaction is successfully typechecked and executed, resulting in an update to the + type checking state. + + This event is triggered after parsing and checking, either via input from 'stdin', or via a call to EvalInteraction. - + - Indicates if the entity is an F# module definition + A host calls this to get the active language ID if provided by fsi-server-lcid - + - Indicates an F# exception declaration + A host calls this to determine if the --gui parameter is active - + - Indicates if the entity is a measure, type or exception abbreviation + The single, global interactive checker to use in conjunction with other operations + on the FsiEvaluationSession. + + If you are using an FsiEvaluationSession in this process, you should only use this InteractiveChecker + for additional checking operations. - + - Indicates if this is a reference to something in an F#-compiled assembly + Get a handle to the dynamically generated assembly - + - Indicates if the entity is an enum type definition + Get a handle to the resolved view of the current signature of the incrementally generated assembly. - + - Indicates if the entity is a delegate type definition + Load the dummy interaction, load the initial files, and, + if interacting, start the background thread to read the standard input. + + Performs these steps: + - Load the dummy interaction, if any + - Set up exception handling, if any + - Load the initial files, if any + - Start the background thread to read the standard input, if any + - Sit in the GUI event loop indefinitely, if needed - + - Indicates if the entity is a class type definition + A host calls this to report an unhandled exception in a standard way, e.g. an exception on the GUI thread gets printed to stderr - + - Indicates if is the 'byref<_>' type definition used for byref types in F#-compiled assemblies + Typecheck the given script fragment in the type checking context implied by the current state + of F# Interactive. The results can be used to access intellisense, perform resolutions, + check brace matching and other information. + + Operations may be run concurrently with other requests to the InteractiveChecker. + + Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered + by input from 'stdin'. - + - Check if the entity inherits from System.Attribute in its type hierarchy + A host calls this to request an interrupt on the evaluation thread. - + - Indicates if the entity is an array type + Get a configuration that uses a private inbuilt implementation of the 'fsi' object and does not + implicitly reference FSharp.Compiler.Interactive.Settings.dll. - + - Indicates that a module is compiled to a class with the given mangled name. The mangling is reversed during lookup + Get a configuration that uses the 'fsi' object (normally from FSharp.Compiler.Interactive.Settings.dll, + an object from another DLL with identical characteristics) to provide an implementation of the configuration. + FSharp.Compiler.Interactive.Settings.dll is referenced by default. - + - Indicates if the type is implemented through a mapping to IL assembly code. This is only - true for types in FSharp.Core.dll + Get a configuration that uses the 'fsi' object (normally from FSharp.Compiler.Interactive.Settings.dll, + an object from another DLL with identical characteristics) to provide an implementation of the configuration. + The flag indicates if FSharp.Compiler.Interactive.Settings.dll is referenced by default. - + - Get the generic parameters, possibly including unit-of-measure parameters + A host calls this to get the completions for a long identifier, e.g. in the console + + Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered + by input from 'stdin'. - + - Get the full name of the type or module + Format a value to a string using the current PrintDepth, PrintLength etc settings provided by the active fsi configuration object - + - Get the fields of a record, class, struct or enum from the perspective of the F# language. - This includes static fields, the 'val' bindings in classes and structs, and the value definitions in enums. - For classes, the list may include compiler generated fields implied by the use of primary constructors. + Execute the given script. Stop on first error, discarding the rest + of the script. Errors and warnings are collected apart from any exception arising from execution + which is returned via a Choice. Execution is performed on the 'Run()' thread. + + Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered + by input from 'stdin'. - + - Indicates if the type is a delegate with the given Invoke signature + Execute the given script. Stop on first error, discarding the rest + of the script. Errors are sent to the output writer, a 'true' return value indicates there + were no errors overall. Execution is performed on the 'Run()' thread. + + Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered + by input from 'stdin'. - + - Get the name of the type or module as displayed in F# code + Execute the code as if it had been entered as one or more interactions, with an + implicit termination at the end of the input. Stop on first error, discarding the rest + of the input. Errors and warnings are collected apart from any exception arising from execution + which is returned via a Choice. Execution is performed on the 'Run()' thread. + + Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered + by input from 'stdin'. - + - Get the enclosing entity for the definition + Execute the code as if it had been entered as one or more interactions, with an + implicit termination at the end of the input. Stop on first error, discarding the rest + of the input. Errors are sent to the output writer, a 'true' return value indicates there + were no errors overall. Execution is performed on the 'Run()' thread. + + Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered + by input from 'stdin'. - + - Get the declared interface implementations + Execute the code as if it had been entered as one or more interactions, with an + implicit termination at the end of the input. Stop on first error, discarding the rest + of the input. Errors and warnings are collected apart from any exception arising from execution + which is returned via a Choice. Parsing is performed on the current thread, and execution is performed + synchronously on the 'main' thread. + + Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered + by input from 'stdin'. - + - Get the declaration location for the type constructor + Execute the code as if it had been entered as one or more interactions, with an + implicit termination at the end of the input. Stop on first error, discarding the rest + of the input. Errors are sent to the output writer. Parsing is performed on the current thread, and execution is performed + synchronously on the 'main' thread. + + Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered + by input from 'stdin'. - + - Get the compiled name of the type or module, possibly with `n mangling. This is identical to LogicalName - unless the CompiledName attribute is used. + Create an FsiEvaluationSession, reading from the given text input, writing to the given text output and error writers. + + <summary>Create an FsiEvaluationSession, reading from the given text input, writing to the given text output and error writers</summary> + + <param name="fsiConfig">The dynamic configuration of the evaluation session</param> + <param name="argv">The command line arguments for the evaluation session</param> + <param name="inReader">Read input from the given reader</param> + <param name="outWriter">Write output to the given writer</param> + <param name="collectible">Optionally make the dynamic assembly for the session collectible</param> - + - Get the base type, if any + Represents an F# Interactive evaluation session. - + - Get the declared attributes for the type + Thrown when there was an error compiling the given code in FSI. - + - Get the rank of an array type + Implicitly reference FSharp.Compiler.Interactive.Settings.dll - + - Get all the interface implementations, by walking the type hierarchy + Called by the evaluation session to ask the host for parameters to format text for output - + - Get all compilation paths, taking `Module` suffixes into account. + Called by the evaluation session to ask the host for parameters to format text for output - + - Get all active pattern cases defined in all active patterns in the module. + Called by the evaluation session to ask the host for parameters to format text for output - + - Get the declared accessibility of the type + Called by the evaluation session to ask the host for parameters to format text for output - + - Get the path used to address the entity (e.g. "Namespace.Module1.NestedModule2"). Gives - "global" for items not in a namespace. + Called by the evaluation session to ask the host for parameters to format text for output - + - Get the type abbreviated by an F# type abbreviation + Called by the evaluation session to ask the host for parameters to format text for output - + - A subtype of FSharpSymbol that represents a type definition or module as seen by the F# language + Called by the evaluation session to ask the host for parameters to format text for output - + - The (non-nested) module and type definitions in this signature + Hook for listening for evaluation bindings - + - Get the declared attributes for the assembly. - Only available when parsing an entire project. + Called by the evaluation session to ask the host for parameters to format text for output - + - Find entity using compiled names + Called by the evaluation session to ask the host for parameters to format text for output - + - Represents an inferred signature of part of an assembly as seen by the F# language + Called by the evaluation session to ask the host for parameters to format text for output - + - The simple name for the assembly + The evaluation session calls this at an appropriate point in the startup phase if the --fsi-server parameter was given - + - The qualified name of the assembly + The evaluation session calls this to report the preferred view of the command line arguments after + stripping things like "/use:file.fsx", "-r:Foo.dll" etc. - + - Indicates if the assembly was generated by a type provider and is due for static linking + Indicate a special console "readline" reader for the evaluation session, if any.  + + A "console" gets used if --readline is specified (the default on Windows + .NET); and --fsi-server is not + given (always combine with --readline-), and OptionalConsoleReadLine is given. + When a console is used, special rules apply to "peekahead", which allows early typing on the console. + Peekahead happens if --peekahead- is not specified (the default). + In this case, a prompt is printed early, a background thread is created and + the OptionalConsoleReadLine is used to read the first line. + If a console is not used, then inReader.Peek() is called early instead. +   + + Further lines are read using OptionalConsoleReadLine(). + If not provided, lines are read using inReader.ReadLine(). +   - + - The file name for the assembly, if any + Schedule a restart for the event loop. - + - The contents of the this assembly + Called by the evaluation session to ask the host to enter a dispatch loop like Application.Run(). + Only called if --gui option is used (which is the default). + Gets called towards the end of startup and every time a ThreadAbort escaped to the backup driver loop. + Return true if a 'restart' is required, which is a bit meaningless. - + - Represents an assembly as seen by the F# language + Request that the given operation be run synchronously on the event loop. - + - Get the signature location for the symbol if it was declared in an implementation + The FSharpSymbolUse for the symbol defined - + - Get the implementation location for the symbol if it was declared in a signature that has an implementation + The symbol defined - + - Get a textual representation of the full name of the symbol. The text returned for some symbols - may not be a valid identifier path in F# code, but rather a human-readable representation of the symbol. + The display name of the symbol defined - + - Gets the short display name for the symbol + The details of the expression defined - + - Get the declaration location for the symbol + The value of the symbol defined, if any - + - Get the assembly declaring this symbol + The value, as an object - + - Return true if two symbols are effectively the same when referred to in F# source code text. - This sees through signatures (a symbol in a signature will be considered effectively the same as - the matching symbol in an implementation). In addition, other equivalances are applied - when the same F# source text implies the same declaration name - for example, constructors - are considered to be effectively the same symbol as the corresponding type definition. - - This is the relation used by GetUsesOfSymbol and GetUsesOfSymbolInFile. + The type of the value, from the point of view of the .NET type system - + - Computes if the symbol is accessible for the given accessibility rights + Represents an evaluated F# value - + + When set to 'false', disables the display of properties of evaluated objects in the output of the interactive session. + + + When set to 'false', disables the display of sequences in the output of the interactive session. + + + When set to 'false', disables the display of declaration values in the output of the interactive session. + + + Get or set the print width of the interactive session. + + + Get or set the total print size of the interactive session. + + + Get or set the total print length of the interactive session. + + + Get or set the print depth of the interactive session. + + + Get or set the format provider used in the output of the interactive session. + + + Get or set the floating point format used in the output of the interactive session. + + + Gets or sets a the current event loop being used to process interactions. + + + The command line arguments after ignoring the arguments relevant to the interactive + environment and replacing the first argument with the name of the last script file, + if any. Thus 'fsi.exe test1.fs test2.fs -- hello goodbye' will give arguments + 'test2.fs', 'hello', 'goodbye'. This value will normally be different to those + returned by System.Environment.GetCommandLineArgs. + + + When set to 'false', disables the display of properties of evaluated objects in the output of the interactive session. + + + When set to 'false', disables the display of sequences in the output of the interactive session. + + + When set to 'false', disables the display of declaration values in the output of the interactive session. + + + Get or set the print width of the interactive session. + + + Get or set the total print size of the interactive session. + + + Get or set the total print length of the interactive session. + + + Get or set the print depth of the interactive session. + + + Get or set the format provider used in the output of the interactive session. + + + Get or set the floating point format used in the output of the interactive session. + + + Gets or sets a the current event loop being used to process interactions. + + + The command line arguments after ignoring the arguments relevant to the interactive + environment and replacing the first argument with the name of the last script file, + if any. Thus 'fsi.exe test1.fs test2.fs -- hello goodbye' will give arguments + 'test2.fs', 'hello', 'goodbye'. This value will normally be different to those + returned by System.Environment.GetCommandLineArgs. + + + Register a printer that controls the output of the interactive session. + + + Register a print transformer that controls the output of the interactive session. + + + Operations supported by the currently executing F# Interactive session. + + + Schedule a restart for the event loop. + + + Run the event loop. + True if the event loop was restarted; false otherwise. + + + Request that the given operation be run synchronously on the event loop. + The result of the operation. + + + An event loop used by the currently executing F# Interactive session to execute code + in the context of a GUI or another event-based system. + + - A hash compatible with the IsEffectivelySameAs relation + A default implementation of the 'fsi' object, used by GetDefaultConfiguration(). Note this + is a different object to FSharp.Compiler.Interactive.Settings.fsi in FSharp.Compiler.Interactive.Settings.dll, + which can be used as an alternative implementation of the interactive settings if passed as a parameter + to GetDefaultConfiguration(fsiObj). - + - Represents a symbol in checked F# source code or a compiled .NET component. - - The subtype of the symbol may reveal further information and can be one of FSharpEntity, FSharpUnionCase - FSharpField, FSharpGenericParameter, FSharpStaticParameter, FSharpMemberOrFunctionOrValue, FSharpParameter, - or FSharpActivePatternCase. + A default implementation of the 'fsi' object, used by GetDefaultConfiguration() - + - Represents the information needed to format types and other information in a style - suitable for use in F# source text at a particular source location. + This represents the global state established as each task function runs as part of the build. - Acquired via GetDisplayEnvAtLocationAlternate and similar methods. May be passed - to the Format method on FSharpType and other methods. + Use to reset error and warning handlers. - + - Indicates the symbol has public accessibility + Get the captured errors - + - Indicates the symbol has private accessibility + Create the error logger - + - Indicates the symbol has internal accessibility + An error logger that capture errors, filtering them according to warning levels etc. - + - The underlying Accessibility + A list of data tip elements to display. - + - Indicates the accessibility of a symbol, as seen by the F# language + Information for building a tool tip box. - + - The signature of the implemented abstract slot + A single data tip display element with where text is expressed as <see cref="Layout"/> - + - The generic parameters of the method + A single data tip display element with where text is expressed as string - + - The parameters of the method + An error occurred formatting this element - + - The expression that forms the body of the method + A single type, method, etc with comment. May represent a method overload group. - + - Represents a checked method in an object expression, as seen by the F# language. + A single tool tip display element - + - The type of the expression + Parameter name - + - The range of the expression + Extra text, goes at the end - + - The immediate sub-expressions of the expression. + typar instantiation text, to go after xml - + - Represents a checked and reduced expression, as seen by the F# language. The active patterns - in 'FSharp.Compiler.SourceCodeServices' can be used to analyze information about the expression. - - Pattern matching is reduced to decision trees and conditional tests. Some other - constructs may be represented in reduced form. + A single data tip display element - + - Represents the declaration of a static initialization action + Indicates that the text for the documentation can be found in a .xml documentation file, using the given signature key - + - Represents the declaration of a member, function or value, including the parameters and body of the member + The text for documentation - + - Represents the declaration of a type + No documentation is available - + - Represents a declaration in an implementation file, as seen by the F# language + Describe a comment as either a block of text or a file+signature reference into an intellidoc file. - + - The qualified name acts to fully-qualify module specifications and implementations + Object model for diagnostics - + - Indicates if the implementation file is a script + The symbol referenced - + - Indicates if the implementation file has an explicit entry point + The range of text representing the reference to the symbol - + - Get the system path of the implementation file + Indicates if the FSharpSymbolUse is declared as private - + - Get the declarations that make up this implementation file + Indicates if the reference is in a syntactic type - + - Represents the definitional contents of a single file or fragment in an assembly, as seen by the F# language + Indicates if the reference is in a pattern - + - The contents of the implementation files in the assembly + Indicates if the reference is in open statement - + - Represents the definitional contents of an assembly, as seen by the F# language + Indicates if the reference is via the member being implemented in a class or object expression - + - The timespan in milliseconds before background work begins after the operations queue is empty + Indicates if the reference is a definition for the symbol, either in a signature or implementation - + - Get the reactor + Indicates if the reference is either a builder or a custom operation in a computation expression - + - The timespan in milliseconds before background work begins after the operations queue is empty + Indicates if the reference is in an attribute - + - For debug purposes + The file name the reference occurs in - + - Block until the current implicit background build is complete. Unit test only. + The display context active at the point where the symbol is used. Can be passed to FSharpType.Format + and other methods to format items in a way that is suitable for a specific source code location. - + - Set the background building function, which is called repeatedly - until it returns 'false'. If None then no background operation is used. + Represents the use of an F# symbol from F# source code - + - Enqueue an uncancellable operation and return immediately. + Range of the open declaration. - + - Put the operation in the queue, and return an async handle to its result. + Modules or namespaces which is opened with this declaration. - + - Block until all operations in the queue are complete + Idents. - + - Cancel any work being don by the background building function. + If it's `namespace Xxx.Yyy` declaration. - + - Reactor is intended for long-running but interruptible operations, interleaved - with one-off asynchronous operations. - - It is used to guard the global compiler state while maintaining responsiveness on - the UI thread. - Reactor operations + Scope in which open declaration is visible. - + - Enqueue an operation and return immediately. + Represents open declaration in F# code. - + - Put the operation in the queue, and return an async handle to its result. + The named arguments for the attribute - + - Represents the capability to schedule work in the compiler service operations queue for the compilation thread + Indicates if the attribute type is in an unresolved assembly - + - Tokenizer for a source file. Holds some expensive-to-compute resources at the scope of the file. + The arguments to the constructor for the attribute - + - Scan one token from the line + The type of the attribute - + - Object to tokenize a line of F# source code, starting with the given lexState. The lexState should be FSharpTokenizerLexState.Initial for - the first line of text. Returns an array of ranges of the text and two enumerations categorizing the - tokens and characters covered by that range, i.e. FSharpTokenColorKind and FSharpTokenCharKind. The enumerations - are somewhat adhoc but useful enough to give good colorization options to the user in an IDE. - - A new lexState is also returned. An IDE-plugin should in general cache the lexState - values for each line of the edited code. + Format the attribute using the rules of the given display context - + - The full length consumed by this match, including delayed tokens (which can be ignored in naive lexers) + Represents a custom attribute attached to F# source code or a compiler .NET component - + - Provides additional information about the token + Get the type definition for a type - + - The tag is an integer identifier for the token + Indicates this is a named type in an unresolved assembly - + - Actions taken when the token is typed + Indicates if the type is a tuple type (reference or struct). The GenericArguments property returns the elements of the tuple type. - + - Gives an indication of the class to assign to the token an IDE + Indicates if the type is a struct tuple type. The GenericArguments property returns the elements of the tuple type. - + - Right column of the token. + Indicates if the type is a variable type, whether declared, generalized or an inference type parameter - + - Left column of the token. + Indicates if the type is a function type. The GenericArguments property returns the domain and range of the function type. - + - Information about a particular token from the tokenizer + Indicates if the type is an anonymous record type. The GenericArguments property returns the type instantiation of the anonymous record type - + - Gives an indication of the class to assign to the characters of the token an IDE + Indicates this is an abbreviation for another type - + - Gives an indication of what should happen when the token is typed in an IDE + Indicates if the type is constructed using a named entity, including array and byref types - + - Gives an indicattion of the color class to assign to the token an IDE + Get the generic parameter data for a generic parameter type - + - Represents stable information for the state of the laxing engine at the end of a line + Get the generic arguments for a tuple type, a function type or a type constructed using a named entity - + - Represents encoded information for the end-of-line continuation of lexing + Get the base type, if any, taking into account the instantiation of this type + if it is an instantiation of a generic type. - + - Represents result of 'GetNavigationItems' operation - this contains - all the members and currently selected indices. First level correspond to - types & modules and second level are methods etc. + Get the details of the anonymous record type. - + - Represents top-level declarations (that should be in the type drop-down) - with nested declarations (that can be shown in the member drop-down) + Get all the interface implementations, by walking the type hierarchy, taking into account the instantiation of this type + if it is an instantiation of a generic type. - + - Represents an item to be displayed in the navigation bar + Get the type for which this is an abbreviation - + - Indicates a kind of item to show in an F# navigation bar + Adjust the types in a group of curried parameters and return type by removing any occurrences of type inference variables, replacing them + systematically with lower-case type inference variables such as <c>'a</c>. - + - The locations of commas and close parenthesis (or, last char of last arg, if no final close parenthesis) + Adjust the types in a group of curried parameters by removing any occurrences of type inference variables, replacing them + systematically with lower-case type inference variables such as <c>'a</c>. - + - The location of the open-parentheses + Adjust the types in a group of parameters by removing any occurrences of type inference variables, replacing them + systematically with lower-case type inference variables such as <c>'a</c>. - + - Either empty or a name if an actual named parameter; f(0,a=4,?b=None) would be [|None; Some "a"; Some "b"|] + Adjust the type in a single parameter by removing any occurrences of type inference variables, replacing them + systematically with lower-case type inference variables such as <c>'a</c>. - + - The start location of long identifier prior to the open-parentheses + Adjust a group of types by removing any occurrences of type inference variables, replacing them + systematically with lower-case type inference variables such as <c>'a</c>. - + - The end location of long identifier prior to the open-parentheses + Adjust the type by removing any occurrences of type inference variables, replacing them + systematically with lower-case type inference variables such as <c>'a</c>. - + - The text of the long identifier prior to the open-parentheses + Instantiate generic type parameters in a type - + - Is false if either this is a call without parens "f x" or the parser recovered as in "f(x,y" + Format the type using the rules of the given display context - + - Find the information about parameter info locations at a particular source location + Format the type using the rules of the given display context - + - Represents the locations relevant to activating parameter info in an IDE + Internal use only. Create a ground type. - + - completing pattern type (e.g. foo (x: |)) + Get the type indicating signature of the active pattern - + - completing named parameters\setters in parameter list of constructor\method calls - end of name ast node * list of properties\parameters that were already set + The names of the active pattern cases - + - completing records field + The whole group name - + - completing something after the inherit keyword + Indicate this is a total active pattern - + - completion context cannot be determined due to errors + Try to get the entity in which the active pattern is declared - + - The syntax tree resulting from the parse + Represents all cases within an active pattern - + - Indicates if any errors occurred during the parse + XML documentation signature for the active pattern case, used for .xml file lookup for compiled code - + - Name of the file for which this information were created + Get the in-memory XML documentation for the active pattern case, used when code is checked in-memory - + - Get the errors and warnings for the parse + The name of the active pattern case - + - When these files change then the build is invalid + Index of the case in the pattern group - + - Return the inner-most range associated with a possible breakpoint location + The group of active pattern cases this belongs to - + - Get declared items and the selected item at the specified location + The location of declaration of the active pattern case - + - Notable parse info for ParameterInfo at a given location + A subtype of FSharpSymbol that represents a single case within an active pattern - + - Represents the results of parsing an F# file + The declared or inferred type of the parameter - + - The methods (or other items) in the group + The optional name of the parameter - + - The shared name of the methods (or other items) in the group + Indicate this is a param array argument - + - Represents a group of methods (or other items) returned by GetMethods. + Indicate this is an out argument - + - The documentation for the item + Indicate this is an optional argument - + - The The structured description representation for the method (or other item) + Indicate this is an in argument - + - The structured description representation for the method (or other item) + The declaration location of the parameter - + - Does the type name or method support a static arguments list, like TP<42,"foo"> or conn.CreateCommand<42, "foo">(arg1, arg2)? + The declared attributes of the parameter - + - The formatted type text for the method (or other item) + A subtype of FSharpSymbol that represents a parameter - + - The parameters of the method in the overload set + XML documentation signature for the value, used for .xml file lookup for compiled code - + - Does the method support an arguments list? This is always true except for static type instantiations like TP<42,"foo">. + Get the in-memory XML documentation for the value, used when code is checked in-memory - + - Does the method support a params list arg? + Get an associated setter method of the property - + - The formatted description text for the method (or other item) + Get the logical name of the member - + - Represents one method (or other item) in a method group. The item may represent either a method or - a single, non-overloaded item such as union case or a named function value. + Indicates if this is a [<Literal>] value, and if so what value? (may be null) - + - The structured representation for the parameter including its name, its type and visual indicators of other - information such as whether it is optional. + Indicated if this is a value - + - The name of the parameter. + Indicated if this is a value compiled to a method - + - Is the parameter optional + Indicates if the member, function or value is in an unresolved assembly - + - The text to display for the parameter including its name, its type and visual indicators of other - information such as whether it is optional. + Indicates if this is an F# type function - + - A key that can be used for sorting the parameters, used to help sort overloads. + Indicates if this is a setter method for a property, or a use of a property in setter mode - + - Represents one parameter for one method (or other item) in a group. + Indicates if this is a setter method for a property, or a use of a property in setter mode - + - Represents a set of declarations in F# source code, with information attached ready for display by an editor. - Returned by GetDeclarations. + Indicates if this is a getter method for a property, or a use of a property in getter mode - + - Get the description text, asynchronously. Never returns "Loading...". + Indicates if this is a property member - + - Get the description text for the declaration. Computing this property may require using compiler - resources and may trigger execution of a type provider method to retrieve documentation. - - May return "Loading..." if timeout occurs + Indicates if this is an 'override', 'default' or an explicit implementation of an interface member - + - Get the name for the declaration as it's presented in source code. + Indicates if this is a mutable value - + - Get the display name for the declaration. + Indicates if this is a module or member value - + - Represents a declaration in F# source code, with information attached ready for display by an editor. - Returned by GetDeclarations. + Indicates if this is the "x" in "member x.M = ..." - + - Where open statements should be added. + Indicates if this is a member, including extension members? - + - Current position (F# compiler line number). + Indicates if this is an instance member in compiled code. + + Explanatory note: some members such as IsNone and IsSome on types with UseNullAsTrueValue appear + as instance members in F# code but are compiled as static members. - + - Current scope kind. + Indicates if this is an instance member, when seen from F#? - + - Insert open namespace context. + Indicates if this is an implicit constructor? - + - Kind of lexical scope. + Indicates if this is a getter method for a property, or a use of a property in getter mode - + - Last part of the entity's full name. + Indicates if this is an extension member? - + - Full display name (i.e. last ident plus modules with `RequireQualifiedAccess` attribute prefixed). + Indicates if this is an explicit implementation of an interface member - + - Namespace that is needed to open to make the entity resolvable in the current scope. + Indicates if this is a remove method for an event - + - Ident parts needed to append to the current ident to make it resolvable in current scope. + Indicates if this is an add method for an event - + - Full name, relative to the current scope. + Indicates if this is an event member - + - Helper data structure representing a symbol, sutable for implementing unresolved identifiers resolution code fixes. + Indicates if this is an abstract member? - + - Lond identifier (i.e. it may contain dots). + Indicates if this is the "x" in "type C() as x = ..." - + - Performs an operation on the cache in thread safe manner. + Indicates if this is a constructor. - + - Clears the cache. + Indicates if this is a compiler generated value - + - Thread safe wrapper over `IAssemblyContentCache`. + Indicates if this is "base" in "base.M(...)" - + - Try get an assembly cached content. + Indicates if this value or member is an F# active pattern - + - Store an assembly content. + Get a result indicating if this is a must-inline value - + - Assembly content cache. + Gets the list of the abstract slot signatures implemented by the member - + - Assembly content. + Indicates if this is a property and there exists an associated setter method - + - Content type used to get assembly content. + Indicates if this is a property and there exists an associated getter method - + - Assembly file last write time. + Get an associated getter method of the property - + - `RawEntity` list retrieved from an assembly. + Get the typars of the member, function or value - + - Cache display name and namespace, used for completion. + Get the full type of the member, function or value when used as a first class value - + - Function that returns `EntityKind` based of given `LookupKind`. + Get an associated remove method of an event - + - Parent module that has `AutoOpen` attribute. + Indicate if an event can be considered to be a property for the F# type system of type IEvent or IDelegateEvent. + In this case ReturnParameter will have a type corresponding to the property type. For + non-standard events, ReturnParameter will have a type corresponding to the delegate type. - + - Parent module that has the largest scope and has `RequireQualifiedAccess` attribute. + Gets the event symbol implied by the use of a property, + for the case where the property is actually an F#-declared CLIEvent. + + Uses of F#-declared events are considered to be properties as far as the language specification + and this API are concerned. - + - The most narrative parent module that has `RequireQualifiedAccess` attribute. + Get an associated delegate type of an event - + - `FSharpEntity.Namespace`. + Get an associated add method of an event - + - Entity name parts with removed module suffixes (Ns.M1Module.M2Module.M3.entity -> Ns.M1.M2.M3.entity) - and replaced compiled names with display names (FSharpEntity.DisplayName, FSharpValueOrFucntion.DisplayName). - Note: *all* parts are cleaned, not the last one. + Get the name as presented in F# error messages and documentation - + - Full entity name as it's seen in compiled code (raw FSharpEntity.FullName, FSharpValueOrFunction.FullName). + Get the enclosing entity for the definition - + - Represents type, module, member, function or value in a compiled assembly. + Get the declaration location of the member, function or value - + - Assembly path. + Get the member name in compiled code - + - Entity lookup type. + Custom attributes attached to the value. These contain references to other values (i.e. constructors in types). Mutable to fixup + these value references after copying a collection of values. - + - Array of `MaybeUnresolvedIdent`. + Get the logical enclosing entity, which for an extension member is type being extended - + - `ShortIdent` with a flag indicating if it's resolved in some scope. + Get the accessibility information for the member, function or value - + - An array of `ShortIdent`. + Gets the overloads for the current method + matchParameterNumber indicates whether to filter the overloads to match the number of parameters in the current symbol - + - Short identifier, i.e. an identifier that contains no dots. + Format the type using the rules of the given display context - + - All assembly content. + A subtype of F# symbol that represents an F# method, property, event, function or value, including extension members. - + - Public assembly content only. + Indicates the value is aggressively inlined by the .NET runtime - + - Assembly content type. + Indicates the value is never inlined - + - Represent an Xml documentation block in source code + Indicates the value is optionally inlined - + - Represents a symbol in an external (non F#) assembly + Indicates the value is inlined but compiled code for the function still exists, e.g. to satisfy interfaces on objects, but that it is also always inlined - + - Represents the type of a single method parameter + Indicates the value is inlined and compiled code for the function does not exist - + - Type variable defined in non-F# assembly. + Gets further information about a choice constraint - + - Pointer defined in non-F# assembly. + Gets further information about a member constraint - + - Array of type that is defined in non-F# assembly. + Indicates a constraint that a type is an unmanaged type - + - Type defined in non-F# assembly. + Indicates a constraint that a type has a 'null' value - + - Represents a type in an external (non F#) assembly. + Indicates a constraint that is a type is a simple choice between one of the given ground types. Used by printf format strings. - + - The default location of FSharp.Core.dll and fsc.exe based on the version of fsc.exe that is running + Indicates a constraint that a type has a parameterless constructor - + - Information about the compilation environment + Indicates a constraint that a type is a reference type - - An optional string used for tracing compiler operations associated with this request. + + + Indicates a constraint that a type is a non-Nullable value type + - + - Get or set the pause time in milliseconds before background work is started. + Indicates a constraint that a type has a member with the given signature - + - A maximum number of megabytes of allocated memory. If the figure reported by <c>System.GC.GetTotalMemory(false)</c> goes over this limit, the FSharpChecker object will attempt to free memory and reduce cache sizes to a minimum.</param> + Indicates a constraint that a type supports F# generic equality - + - Get or set a flag which controls if background work is started implicitly. - - If true, calls to CheckFileInProject implicitly start a background check of that project, replacing - any other background checks in progress. This is useful in IDE applications with spare CPU cycles as - it prepares the project analysis results for use. The default is 'true'. + Indicates a constraint that a type is an enum with the given underlying - + - Notify the host that a project has been fully checked in the background (using file contents provided by the file system API) - - The event may be raised on a background thread. + Indicates a constraint that a type is a delegate from the given tuple of args to the given return type - + - Get or set the pause time in milliseconds before background work is started. + Indicates a default value for an inference type variable should it be neither generalized nor solved - + - Raised after the maxMB memory threshold limit is reached + Indicates a constraint that a type supports F# generic comparison - + - A maximum number of megabytes of allocated memory. If the figure reported by <c>System.GC.GetTotalMemory(false)</c> goes over this limit, the FSharpChecker object will attempt to free memory and reduce cache sizes to a minimum.</param> + Indicates a constraint that a type is a subtype of the given type - + - Get or set a flag which controls if background work is started implicitly. - - If true, calls to CheckFileInProject implicitly start a background check of that project, replacing - any other background checks in progress. This is useful in IDE applications with spare CPU cycles as - it prepares the project analysis results for use. The default is 'true'. + Gets further information about an enumeration constraint - + - Report a statistic for testability + Gets further information about a delegate constraint - + - Report a statistic for testability + Gets further information about a defaults-to constraint - + - Raised after a parse of a file in the background analysis. - - The event will be raised on a background thread. + Gets further information about a coerces-to constraint - + - Raised after a check of a file in the background analysis. - - The event will be raised on a background thread. + Represents a constraint on a generic type parameter - + - Current queue length of the service, for debug purposes. - In addition, a single async operation or a step of a background build - may be in progress - such an operation is not counted in the queue length. + Get the default type associated with the 'defaults to' constraint - + - Notify the host that the logical type checking context for a file has now been updated internally - and that the file has become eligible to be re-typechecked for errors. - - The event will be raised on a background thread. + Get the priority off the 'defaults to' constraint - + - Block until the background compile finishes. + Represents further information about a 'defaults to' constraint on a generic type parameter - - - Try to get type check results for a file. This looks up the results of recent type checks of the - same file, regardless of contents. The version tag specified in the original check of the file is returned. - If the source of the file has changed the results returned by this function may be out of date, though may - still be usable for generating intellisense menus and information. - - The filename for the file. - The options for the project or script, used to determine active --define conditionals and other options relevant to parsing. - Optionally, specify source that must match the previous parse precisely. - An optional string used for tracing compiler operations associated with this request. + + + Get the tupled argument type required by the constraint + - + - Tokenize a single line, returning token information and a tokenization state represented by an integer + Get the return type required by the constraint - + - Tokenize an entire file, line by line + Represents further information about a delegate constraint on a generic type parameter - + - Stop the background compile. + Get the types that may be used to satisfy the constraint - - - Parse a source code file, returning a handle that can be used for obtaining navigation bar information - To get the full information, call 'CheckFileInProject' method on the result - All files except the one being checked are read from the FileSystem API - - - The filename for the file. - The full source for the file. - The options for the project or script, used to determine active --define conditionals and other options relevant to parsing. - An optional string used for tracing compiler operations associated with this request. + + + Get the return type of the method required by the constraint + - - - Parse a source code file, returning a handle that can be used for obtaining navigation bar information - To get the full information, call 'CheckFileInProject' method on the result - - - The filename for the file. - The full source for the file. - Parsing options for the project or script. - An optional string used for tracing compiler operations associated with this request. + + + Get the name of the method required by the constraint + - - - Parse and typecheck all files in a project. - All files are read from the FileSystem API - - - The options for the project or script. - An optional string used for tracing compiler operations associated with this request. + + + Indicates if the the method required by the constraint must be static + - - - - Parse and check a source code file, returning a handle to the results - - - Note: all files except the one being checked are read from the FileSystem API - - - Return FSharpCheckFileAnswer.Aborted if a parse tree was not available. - - - - The name of the file in the project whose source is being checked. - An integer that can be used to indicate the version of the file. This will be returned by TryGetRecentCheckResultsForFile when looking up the file. - The full source for the file. - The options for the project or script. - - An item passed back to 'hasTextChangedSinceLastTypecheck' (from some calls made on 'FSharpCheckFileResults') to help determine if - an approximate intellisense resolution is inaccurate because a range of text has changed. This - can be used to marginally increase accuracy of intellisense results in some situations. - - An optional string used for tracing compiler operations associated with this request. + + + Get the argument types of the method required by the constraint + - - - This function is called when a project has been cleaned/rebuilt, and thus any live type providers should be refreshed. - - An optional string used for tracing compiler operations associated with this request. + + + Represents further information about a member constraint on a generic type parameter + - - - Parse a source code file, returning information about brace matching in the file. - Return an enumeration of the matching parenthetical tokens in the file. - - - The filename for the file, used to help caching of results. - The full source for the file. - Parsing options for the project or script. - An optional string used for tracing compiler operations associated with this request. + + + Get the name of the static parameter + - - - Parse a source code file, returning information about brace matching in the file. - Return an enumeration of the matching parenthetical tokens in the file. - - - The filename for the file, used to help caching of results. - The full source for the file. - Parsing options for the project or script. - An optional string used for tracing compiler operations associated with this request. - - - - Create resources for the project and keep the project alive until the returned object is disposed. - - - The options for the project or script. - An optional string used for tracing compiler operations associated with this request. - - + - This function is called when the configuration is known to have changed for reasons not encoded in the ProjectOptions. - For example, dependent references may have been deleted or created. - <param name="startBackgroundCompileIfAlreadySeen">Start a background compile of the project if a project with the same name has already been seen before.</param> - <param name="userOpName">An optional string used for tracing compiler operations associated with this request.</param> + Get the kind of the static parameter - + - This function is called when the entire environment is known to have changed for reasons not encoded in the ProjectOptions of any project/compilation. + Indicates if the static parameter is optional - - - 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. - - - Used to differentiate between scripts, to consider each script a separate project. - Also used in formatted error messages. - - Indicates when the script was loaded into the editing environment, - so that an 'unload' and 'reload' action will cause the script to be considered as a new project, - so that references are re-resolved. - An optional string used for tracing compiler operations associated with this request. - - - - Get the FSharpProjectOptions implied by a set of command line arguments. - - - Used to differentiate between projects and for the base directory of the project. - The command line arguments for the project build. - Indicates when the script was loaded into the editing environment, - so that an 'unload' and 'reload' action will cause the script to be considered as a new project, - so that references are re-resolved. - - - - Get the FSharpParsingOptions implied by a FSharpProjectOptions. - - - The command line arguments for the project build. - - - - Get the FSharpParsingOptions implied by a set of command line arguments. - - - The command line arguments for the project build. - - - - Get the FSharpParsingOptions implied by a set of command line arguments and list of source files. - - - Initial source files list. Additional files may be added during argv evaluation. - The command line arguments for the project build. - - - - Like ParseFile, but uses results from the background builder. - All files are read from the FileSystem API, including the file being checked. - - - The filename for the file. - The options for the project or script, used to determine active --define conditionals and other options relevant to parsing. - An optional string used for tracing compiler operations associated with this request. - - - - Like CheckFileInProject, but uses the existing results from the background builder. - All files are read from the FileSystem API, including the file being checked. - - - The filename for the file. - The options for the project or script, used to determine active --define conditionals and other options relevant to parsing. - An optional string used for tracing compiler operations associated with this request. - - - - Create an instance of an FSharpChecker. - - - The optional size of the project checking cache. - Keep the checked contents of projects. - If false, do not keep full intermediate checking results from background checking suitable for returning from GetBackgroundCheckResultsForFileInProject. This reduces memory usage. - An optional resolver for non-file references, for legacy purposes - An optional resolver to access the contents of .NET binaries in a memory-efficient way - - - - TypeCheck and compile provided AST - - An optional string used for tracing compiler operations associated with this request. - - - - Compiles to a dynamic assembly using the given flags. - - The first argument is ignored and can just be "fsc.exe". - - Any source files names are resolved via the FileSystem API. An output file name must be given by a -o flag, but this will not - be written - instead a dynamic assembly will be created and loaded. - - If the 'execute' parameter is given the entry points for the code are executed and - the given TextWriters are used for the stdout and stderr streams respectively. In this - case, a global setting is modified during the execution. - - An optional string used for tracing compiler operations associated with this request. - - - - TypeCheck and compile provided AST - - An optional string used for tracing compiler operations associated with this request. - - - - Compile using the given flags. Source files names are resolved via the FileSystem API. - The output file must be given by a -o flag. - The first argument is ignored and can just be "fsc.exe". - - An optional string used for tracing compiler operations associated with this request. - - + - Flush all caches and garbage collect + Get the default value for the static parameter - + - Set the project to be checked in the background. Overrides any previous call to <c>CheckProjectInBackground</c> + Get the declaration location of the static parameter - - - Check a source code file, returning a handle to the results of the parse including - the reconstructed types in the file. - - All files except the one being checked are read from the FileSystem API - Note: returns NoAntecedent if the background builder is not yet done preparing the type check context for the - file (e.g. loading references and parsing/checking files in the project that this file depends upon). - In this case, the caller can either retry, or wait for FileTypeCheckStateIsDirty to be raised for this file. - - - - The results of ParseFile for this file. - The name of the file in the project whose source is being checked. - An integer that can be used to indicate the version of the file. This will be returned by TryGetRecentCheckResultsForFile when looking up the file. - The full source for the file. - The options for the project or script. - - An item passed back to 'hasTextChangedSinceLastTypecheck' (from some calls made on 'FSharpCheckFileResults') to help determine if - an approximate intellisense resolution is inaccurate because a range of text has changed. This - can be used to marginally increase accuracy of intellisense results in some situations. - - An optional string used for tracing compiler operations associated with this request. - - - - - Check a source code file, returning a handle to the results - - - Note: all files except the one being checked are read from the FileSystem API - - - Return FSharpCheckFileAnswer.Aborted if a parse tree was not available. - - - - The results of ParseFile for this file. - The name of the file in the project whose source is being checked. - An integer that can be used to indicate the version of the file. This will be returned by TryGetRecentCheckResultsForFile when looking up the file. - The full source for the file. - The options for the project or script. - - An item passed back to 'hasTextChangedSinceLastTypecheck' (from some calls made on 'FSharpCheckFileResults') to help determine if - an approximate intellisense resolution is inaccurate because a range of text has changed. This - can be used to marginally increase accuracy of intellisense results in some situations. - - An optional string used for tracing compiler operations associated with this request. - - + - Used to parse and check F# source code. + A subtype of FSharpSymbol that represents a static parameter to an F# type provider - + - The result of calling TypeCheckResult including the possibility of abort and background compiler not caught up. + Get the in-memory XML documentation for the type parameter, used when code is checked in-memory - + - An optional stamp to uniquely identify this set of options - If two sets of options both have stamps, then they are considered equal - if and only if the stamps are equal + Get the name of the generic parameter - + - Extra information passed back on event trigger + Indicates if this is a statically resolved type variable - + - Unused in this API and should be '[]' when used as user-specified input + Indicates if this is a measure variable - + - Unused in this API and should be 'None' when used as user-specified input + Indicates if this is a compiler generated type parameter - + - Timestamp of project/script load, used to differentiate between different instances of a project load. - This ensures that a complete reload of the project or script type checking - context occurs on project or script unload/reload. + Get the range of the generic parameter - + - When true, use the reference resolution rules for scripts rather than the rules for compiler. + Get the declared or inferred constraints for the type parameter - + - When true, the typechecking environment is known a priori to be incomplete, for - example when a .fs file is opened outside of a project. In this case, the number of error - messages reported is reduced. + Get the declared attributes of the type parameter. - + - The command line arguments for the other projects referenced by this project, indexed by the - exact text used in the "-r:" reference in FSharpProjectOptions. + A subtype of FSharpSymbol that represents a generic parameter for an FSharpSymbol - + - Additional command line argument options for the project. These can include additional files and references. + Represents the rights of a compilation to access symbols - + - The files in the project + Get the XML documentation signature for .xml file lookup for the field, used for .xml file lookup for compiled code - + - This is the unique identifier for the project, it is case sensitive. If it's None, will key off of ProjectFileName in our caching. + Get the in-memory XML documentation for the field, used when code is checked in-memory - - A set of information describing a project or script build configuration. - - + - Options used to determine active --define conditionals and other options relevant to parsing files in a project + Get the attributes attached to generated property - - Unused in this API - - + - Get the resolution of the ProjectOptions + Get the name of the field - + - Indicates if critical errors existed in the project options + Get the default initialization info, for static literals - + - The errors returned by processing the project + Indicates if the field is declared volatile - + - Indicates the set of files which must be watched to accurately track changes that affect these results, - Clients interested in reacting to updates to these files should watch these files and take actions as described - in the documentation for compiler service. + Indicates if the record field is for a type in an unresolved assembly - + - Get a view of the overall signature of the assembly. Only valid to use if HasCriticalErrors is false. + Indicates if the field is declared in a union case - + + + Indicates a static field + + + + + Indicates if the field name was generated by compiler (e.g. ItemN names in union cases and DataN in exceptions). + This API returns true for source defined symbols only. + + + + + Indicates if the field is declared 'static' + + + + + Indicates if the field has a literal value + + + + + Indicates if the field declared is declared 'DefaultValue' + + + + + Indicates a compiler generated field, not visible to Intellisense or name resolution + + + + + Is this a field from an anonymous record type? + + + + + Get the type of the field, w.r.t. the generic parameters of the enclosing type constructor + + + + + Get the attributes attached to generated field + + + + + Returns the declaring union case symbol + + + + + Get the declaring entity of this field, if any. Fields from anonymous types do not have a declaring entity + + + + + Get the declaration location of the field + + + + + If the field is from an anonymous record type then get the details of the field including the index in the sorted array of fields + + + + + Indicates if the declared visibility of the field, not taking signatures into account + + + + + A subtype of FSharpSymbol that represents a record or union case field as seen by the F# language + + + + + The sorted labels of the anonymous type + + + + + Names of any enclosing types of the compiled form of the anonymous type (if the anonymous type was defined as a nested type) + + + + + The name of the compiled form of the anonymous type + + + + + The assembly where the compiled form of the anonymous type is defined + + + + + A subtype of FSharpSymbol that represents a record or union case field as seen by the F# language + + + + + Get the XML documentation signature for .xml file lookup for the union case, used for .xml file lookup for compiled code + + + + + Get the in-memory XML documentation for the union case, used when code is checked in-memory + + + + + Get the data carried by the case. + + + + + Get the type constructed by the case. Normally exactly the type of the enclosing type, sometimes an abbreviation of it + + + + + Get the name of the union case + + + + + Indicates if the union case is for a type in an unresolved assembly + + + + + Indicates if the union case has field definitions + + + + + Get the range of the name of the case + + + + + Get the name of the case in generated IL code + + + + + Get the attributes for the case, attached to the generated static method to make instances of the case + + + + + Indicates if the declared visibility of the union constructor, not taking signatures into account + + + + + A subtype of FSharpSymbol that represents a union case as seen by the F# language + + + + + Get the name of the abstract slot + + + + + Get the generic arguments of the abstract slot + + + + + Get the generic arguments of the type defining the abstract slot + + + + + Get the declaring type of the abstract slot + + + + + Get the return type of the abstract slot + + + + + Get the arguments of the abstract slot + + + + + Represents the signature of an abstract slot of a class or interface + + + + + The declared or inferred type of the parameter + + + + + The optional name of the parameter + + + + + Indicate this is an out argument + + + + + Indicate this is an optional argument + + + + + Indicate this is an in argument + + + + + The declared attributes of the parameter + + + + + Represents a parameter in an abstract method of a class or interface + + + + + Get the return type of the delegate signature + + + + + Get the argument types of the delegate signature + + + + + Represents a delegate signature in an F# symbol + + + + + Get the XML documentation signature for the entity, used for .xml file lookup for compiled code + + + + + Get the in-memory XML documentation for the entity, used when code is checked in-memory + + + + + Indicates if the type prefers the "tycon<a,b>" syntax for display etc. + + + + + Get the cases of a union type + + + + + Get the full name of the type or module if it is available + + + + + Get the static parameters for a provided type + + + + + Get the declared accessibility of the representation, not taking signatures into account + + + + + Get the fully qualified name of the type or module + + + + + Get the modules and types defined in a module, or the nested types of a type + + + + + Get the namespace containing the type or module, if any. Use 'None' for item not in a namespace. + + + + + Get the properties, events and methods of a type definitions, or the functions and values of a module + + + + + Get the name of the type or module, possibly with `n mangling + + + + + Indicates if the entity is a struct or enum + + + + + Indicates if the entity is in an unresolved assembly + + + + + Indicates if the entity is a 'fake' symbol related to a static instantiation of a type provider + + + + + Indicates if the entity is a generated provided type + + + + + Indicates if the entity is an erased provided type + + + + + Indicates if the entity is a provided type + + + + + Indicates if the entity is a type definition for a reference type where the implementation details are hidden by a signature + + + + + Indicates if the entity is a part of a namespace path + + + + + Indicates if the entity is a measure definition + + + + + Indicates if the entity is an interface type definition + + + + + Indicates if the entity is union type + + + + + Indicates if the entity is record type + + + + + Indicates if the entity is an F# module definition + + + + + Indicates an F# exception declaration + + + + + Indicates if the entity is a measure, type or exception abbreviation + + + + + Indicates if this is a reference to something in an F#-compiled assembly + + + + + Indicates if the entity is an enum type definition + + + + + Indicates if the entity is a delegate type definition + + + + + Indicates if the entity is a class type definition + + + + + Indicates if is the 'byref<_>' type definition used for byref types in F#-compiled assemblies + + + + + Check if the entity inherits from System.Attribute in its type hierarchy + + + + + Indicates if the entity is an array type + + + + + Indicates that a module is compiled to a class with the given mangled name. The mangling is reversed during lookup + + + + + Indicates if the type is implemented through a mapping to IL assembly code. This is only + true for types in FSharp.Core.dll + + + + + Get the generic parameters, possibly including unit-of-measure parameters + + + + + Get the full name of the type or module + + + + + Get the fields of a record, class, struct or enum from the perspective of the F# language. + This includes static fields, the 'val' bindings in classes and structs, and the value definitions in enums. + For classes, the list may include compiler generated fields implied by the use of primary constructors. + + + + + Indicates if the type is a delegate with the given Invoke signature + + + + + Get the name of the type or module as displayed in F# code + + + + + Get the enclosing entity for the definition + + + + + Get the declared interface implementations + + + + + Get the declaration location for the type constructor + + + + + Get the compiled name of the type or module, possibly with `n mangling. This is identical to LogicalName + unless the CompiledName attribute is used. + + + + + Get the base type, if any + + + + + Get the declared attributes for the type + + + + + Get the rank of an array type + + + + + Get all the interface implementations, by walking the type hierarchy + + + + + Get all compilation paths, taking `Module` suffixes into account. + + + + + Get all active pattern cases defined in all active patterns in the module. + + + + + Get the declared accessibility of the type + + + + + Get the path used to address the entity (e.g. "Namespace.Module1.NestedModule2"). Gives + "global" for items not in a namespace. + + + + + Get the type abbreviated by an F# type abbreviation + + + + + A subtype of FSharpSymbol that represents a type definition or module as seen by the F# language + + + + + The (non-nested) module and type definitions in this signature + + + + + Get the declared attributes for the assembly. + Only available when parsing an entire project. + + + + + Find entity using compiled names + + + + + Represents an inferred signature of part of an assembly as seen by the F# language + + + + + The simple name for the assembly + + + + + The qualified name of the assembly + + + + + Indicates if the assembly was generated by a type provider and is due for static linking + + + + + The file name for the assembly, if any + + + + + The contents of the this assembly + + + + + Represents an assembly as seen by the F# language + + + + + Get the signature location for the symbol if it was declared in an implementation + + + + + Get the implementation location for the symbol if it was declared in a signature that has an implementation + + + + + Get a textual representation of the full name of the symbol. The text returned for some symbols + may not be a valid identifier path in F# code, but rather a human-readable representation of the symbol. + + + + + Gets the short display name for the symbol + + + + + Get the declaration location for the symbol + + + + + Get the assembly declaring this symbol + + + + + Return true if two symbols are effectively the same when referred to in F# source code text. + This sees through signatures (a symbol in a signature will be considered effectively the same as + the matching symbol in an implementation). In addition, other equivalences are applied + when the same F# source text implies the same declaration name - for example, constructors + are considered to be effectively the same symbol as the corresponding type definition. + + This is the relation used by GetUsesOfSymbol and GetUsesOfSymbolInFile. + + + + + Computes if the symbol is accessible for the given accessibility rights + + + + + A hash compatible with the IsEffectivelySameAs relation + + + + + Represents a symbol in checked F# source code or a compiled .NET component. + + The subtype of the symbol may reveal further information and can be one of FSharpEntity, FSharpUnionCase + FSharpField, FSharpGenericParameter, FSharpStaticParameter, FSharpMemberOrFunctionOrValue, FSharpParameter, + or FSharpActivePatternCase. + + + + + Represents the information needed to format types and other information in a style + suitable for use in F# source text at a particular source location. + + Acquired via GetDisplayEnvAtLocationAlternate and similar methods. May be passed + to the Format method on FSharpType and other methods. + + + + + Indicates the symbol has public accessibility. + + + + + Indicates the symbol has protected accessibility. + + + + + Indicates the symbol has private accessibility. + + + + + Indicates the symbol has internal accessibility. + + + + + The underlying Accessibility + + + + + Indicates the accessibility of a symbol, as seen by the F# language + + + + + The signature of the implemented abstract slot + + + + + The generic parameters of the method + + + + + The parameters of the method + + + + + The expression that forms the body of the method + + + + + Represents a checked method in an object expression, as seen by the F# language. + + + + + The type of the expression + + + + + The range of the expression + + + + + The immediate sub-expressions of the expression. + + + + + Represents a checked and reduced expression, as seen by the F# language. The active patterns + in 'FSharp.Compiler.SourceCodeServices' can be used to analyze information about the expression. + + Pattern matching is reduced to decision trees and conditional tests. Some other + constructs may be represented in reduced form. + + + + + Represents the declaration of a static initialization action + + + + + Represents the declaration of a member, function or value, including the parameters and body of the member + + + + + Represents the declaration of a type + + + + + Represents a declaration in an implementation file, as seen by the F# language + + + + + The qualified name acts to fully-qualify module specifications and implementations + + + + + Indicates if the implementation file is a script + + + + + Indicates if the implementation file has an explicit entry point + + + + + Get the system path of the implementation file + + + + + Get the declarations that make up this implementation file + + + + + Represents the definitional contents of a single file or fragment in an assembly, as seen by the F# language + + + + + The contents of the implementation files in the assembly + + + + + Represents the definitional contents of an assembly, as seen by the F# language + + + + + The timespan in milliseconds before background work begins after the operations queue is empty + + + + + Get the reactor + + + + + The timespan in milliseconds before background work begins after the operations queue is empty + + + + + For debug purposes + + + + + Block until the current implicit background build is complete. Unit test only. + + + + + Allows to specify the language for error messages + + + + + Set the background building function, which is called repeatedly + until it returns 'false'. If None then no background operation is used. + + + + + Enqueue an uncancellable operation and return immediately. + + + + + Put the operation in the queue, and return an async handle to its result. + + + + + Block until all operations in the queue are complete + + + + + Cancel any work being don by the background building function. + + + + + Reactor is intended for long-running but interruptible operations, interleaved + with one-off asynchronous operations. + + It is used to guard the global compiler state while maintaining responsiveness on + the UI thread. + Reactor operations + + + + + Enqueue an operation and return immediately. + + + + + Put the operation in the queue, and return an async handle to its result. + + + + + Represents the capability to schedule work in the compiler service operations queue for the compilation thread + + + + + A kind that determines what range in a source's text is semantically classified as after type-checking. + + + + + A builder that will build an item key store based on the written Item and its associated range. + + + + + Stores a list of item key strings and their ranges in a memory mapped file. + + + + + Tokenizer for a source file. Holds some expensive-to-compute resources at the scope of the file. + + + + + Scan one token from the line + + + + + Object to tokenize a line of F# source code, starting with the given lexState. The lexState should be FSharpTokenizerLexState.Initial for + the first line of text. Returns an array of ranges of the text and two enumerations categorizing the + tokens and characters covered by that range, i.e. FSharpTokenColorKind and FSharpTokenCharKind. The enumerations + are somewhat adhoc but useful enough to give good colorization options to the user in an IDE. + + A new lexState is also returned. An IDE-plugin should in general cache the lexState + values for each line of the edited code. + + + + + The full length consumed by this match, including delayed tokens (which can be ignored in naive lexers) + + + + + Provides additional information about the token + + + + + The tag is an integer identifier for the token + + + + + Actions taken when the token is typed + + + + + Gives an indication of the class to assign to the token an IDE + + + + + Right column of the token. + + + + + Left column of the token. + + + + + Information about a particular token from the tokenizer + + + + + Gives an indication of the class to assign to the characters of the token an IDE + + + + + Gives an indication of what should happen when the token is typed in an IDE + + + + + Gives an indication of the color class to assign to the token an IDE + + + + + Represents stable information for the state of the lexing engine at the end of a line + + + + + Represents encoded information for the end-of-line continuation of lexing + + + + + Represents result of 'GetNavigationItems' operation - this contains + all the members and currently selected indices. First level correspond to + types & modules and second level are methods etc. + + + + + Represents top-level declarations (that should be in the type drop-down) + with nested declarations (that can be shown in the member drop-down) + + + + + Represents an item to be displayed in the navigation bar + + + + + Indicates a kind of item to show in an F# navigation bar + + + + + The locations of commas and close parenthesis (or, last char of last arg, if no final close parenthesis) + + + + + The location of the open-parentheses + + + + + Either empty or a name if an actual named parameter; f(0,a=4,?b=None) would be [|None; Some "a"; Some "b"|] + + + + + The start location of long identifier prior to the open-parentheses + + + + + The end location of long identifier prior to the open-parentheses + + + + + The text of the long identifier prior to the open-parentheses + + + + + Is false if either this is a call without parens "f x" or the parser recovered as in "f(x,y" + + + + + Find the information about parameter info locations at a particular source location + + + + + Represents the locations relevant to activating parameter info in an IDE + + + + + completing pattern type (e.g. foo (x: |)) + + + + + completing named parameters\setters in parameter list of constructor\method calls + end of name ast node * list of properties\parameters that were already set + + + + + completing records field + + + + + completing something after the inherit keyword + + + + + completion context cannot be determined due to errors + + + + + The syntax tree resulting from the parse + + + + + Indicates if any errors occurred during the parse + + + + + Name of the file for which this information were created + + + + + Get the errors and warnings for the parse + + + + + When these files change then the build is invalid + + + + + Return the inner-most range associated with a possible breakpoint location + + + + + Get declared items and the selected item at the specified location + + + + + Notable parse info for ParameterInfo at a given location + + + + + Represents the results of parsing an F# file + + + + + The methods (or other items) in the group + + + + + The shared name of the methods (or other items) in the group + + + + + Represents a group of methods (or other items) returned by GetMethods. + + + + + The documentation for the item + + + + + The The structured description representation for the method (or other item) + + + + + The structured description representation for the method (or other item) + + + + + Does the type name or method support a static arguments list, like TP<42,"foo"> or conn.CreateCommand<42, "foo">(arg1, arg2)? + + + + + The formatted type text for the method (or other item) + + + + + The parameters of the method in the overload set + + + + + Does the method support an arguments list? This is always true except for static type instantiations like TP<42,"foo">. + + + + + Does the method support a params list arg? + + + + + The formatted description text for the method (or other item) + + + + + Represents one method (or other item) in a method group. The item may represent either a method or + a single, non-overloaded item such as union case or a named function value. + + + + + The structured representation for the parameter including its name, its type and visual indicators of other + information such as whether it is optional. + + + + + The name of the parameter. + + + + + Is the parameter optional + + + + + The text to display for the parameter including its name, its type and visual indicators of other + information such as whether it is optional. + + + + + A key that can be used for sorting the parameters, used to help sort overloads. + + + + + Represents one parameter for one method (or other item) in a group. + + + + + Represents a set of declarations in F# source code, with information attached ready for display by an editor. + Returned by GetDeclarations. + + + + + Get the description text, asynchronously. Never returns "Loading...". + + + + + Get the description text for the declaration. Computing this property may require using compiler + resources and may trigger execution of a type provider method to retrieve documentation. + + May return "Loading..." if timeout occurs + + + + + Get the name for the declaration as it's presented in source code. + + + + + Get the display name for the declaration. + + + + + Represents a declaration in F# source code, with information attached ready for display by an editor. + Returned by GetDeclarations. + + + + + Where open statements should be added. + + + + + Current position (F# compiler line number). + + + + + Current scope kind. + + + + + Insert open namespace context. + + + + + Kind of lexical scope. + + + + + Last part of the entity's full name. + + + + + Full display name (i.e. last ident plus modules with `RequireQualifiedAccess` attribute prefixed). + + + + + Namespace that is needed to open to make the entity resolvable in the current scope. + + + + + Ident parts needed to append to the current ident to make it resolvable in current scope. + + + + + Full name, relative to the current scope. + + + + + Helper data structure representing a symbol, suitable for implementing unresolved identifiers resolution code fixes. + + + + + Long identifier (i.e. it may contain dots). + + + + + Performs an operation on the cache in thread safe manner. + + + + + Clears the cache. + + + + + Thread safe wrapper over `IAssemblyContentCache`. + + + + + Try get an assembly cached content. + + + + + Store an assembly content. + + + + + Assembly content cache. + + + + + Assembly content. + + + + + Content type used to get assembly content. + + + + + Assembly file last write time. + + + + + `RawEntity` list retrieved from an assembly. + + + + + Cache display name and namespace, used for completion. + + + + + Function that returns `EntityKind` based of given `LookupKind`. + + + + + Parent module that has `AutoOpen` attribute. + + + + + Parent module that has the largest scope and has `RequireQualifiedAccess` attribute. + + + + + The most narrative parent module that has `RequireQualifiedAccess` attribute. + + + + + `FSharpEntity.Namespace`. + + + + + Entity name parts with removed module suffixes (Ns.M1Module.M2Module.M3.entity -> Ns.M1.M2.M3.entity) + and replaced compiled names with display names (FSharpEntity.DisplayName, FSharpValueOrFunction.DisplayName). + Note: *all* parts are cleaned, not the last one. + + + + + Full entity name as it's seen in compiled code (raw FSharpEntity.FullName, FSharpValueOrFunction.FullName). + + + + + Represents type, module, member, function or value in a compiled assembly. + + + + + Assembly path. + + + + + Entity lookup type. + + + + + Array of `MaybeUnresolvedIdent`. + + + + + `ShortIdent` with a flag indicating if it's resolved in some scope. + + + + + An array of `ShortIdent`. + + + + + Short identifier, i.e. an identifier that contains no dots. + + + + + All assembly content. + + + + + Public assembly content only. + + + + + Assembly content type. + + + + + Represent an Xml documentation block in source code + + + + + Represents a symbol in an external (non F#) assembly + + + + + Represents the type of a single method parameter + + + + + Type variable defined in non-F# assembly. + + + + + Pointer defined in non-F# assembly. + + + + + Array of type that is defined in non-F# assembly. + + + + + Type defined in non-F# assembly. + + + + + Represents a type in an external (non F#) assembly. + + + + + Get the resolution of the ProjectOptions + + + + + Indicates if critical errors existed in the project options + + + + + The errors returned by processing the project + + + + + Indicates the set of files which must be watched to accurately track changes that affect these results, + Clients interested in reacting to updates to these files should watch these files and take actions as described + in the documentation for compiler service. + + + + + Get a view of the overall signature of the assembly. Only valid to use if HasCriticalErrors is false. + + + + + Get a view of the overall contents of the assembly. Only valid to use if HasCriticalErrors is false. + + + + + Get the textual usages that resolved to the given symbol throughout the project + + + + + Get an optimized view of the overall contents of the assembly. Only valid to use if HasCriticalErrors is false. + + + + + Get all textual usages of all symbols throughout the project + + + + + A handle to the results of CheckFileInProject. + + + + + Success + + + + + Aborted because cancellation caused an abandonment of the operation + + + + + The result of calling TypeCheckResult including the possibility of abort and background compiler not caught up. + + + + + Get the resolution of the ProjectOptions + + + + + Get a view of the contents of the assembly up to and including the file just checked + + + + + Open declarations in the file, including auto open modules. + + + + + Represents complete typechecked implementation file, including its typechecked signatures if any. + + + + + Indicates whether type checking successfully occurred with some results returned. If false, indicates that + an unrecoverable error in earlier checking/parsing/resolution steps. + + + + + The errors returned by parsing a source file. + + + + + Indicates the set of files which must be watched to accurately track changes that affect these results, + Clients interested in reacting to updates to these files should watch these files and take actions as described + in the documentation for compiler service. + + + + + Tries to get the current successful TcImports. This is only used in testing. Do not use it for other stuff. + + + + + Internal constructor + + + + + Internal constructor + + + + + Determines if a long ident is resolvable at a specific point. + <param name="userOpName">An optional string used for tracing compiler operations associated with this request.</param> + + + + + Determines if a long ident is resolvable at a specific point. + <param name="userOpName">An optional string used for tracing compiler operations associated with this request.</param> + + + + + Get the textual usages that resolved to the given symbol throughout the file + + + + Compute a formatted tooltip for the given location + + The line number where the information is being requested. + The column number at the end of the identifiers where the information is being requested. + The text of the line where the information is being requested. + The identifiers at the location where the information is being requested. + Used to discriminate between 'identifiers', 'strings' and others. For strings, an attempt is made to give a tooltip for a #r "..." location. Use a value from FSharpTokenInfo.Tag, or FSharpTokenTag.Identifier, unless you have other information available. + An optional string used for tracing compiler operations associated with this request. + + + Resolve the names at the given location to a use of symbol. + + The line number where the information is being requested. + The column number at the end of the identifiers where the information is being requested. + The text of the line where the information is being requested. + The identifiers at the location where the information is being requested. + An optional string used for tracing compiler operations associated with this request. + + + Compute a formatted tooltip for the given location + + The line number where the information is being requested. + The column number at the end of the identifiers where the information is being requested. + The text of the line where the information is being requested. + The identifiers at the location where the information is being requested. + Used to discriminate between 'identifiers', 'strings' and others. For strings, an attempt is made to give a tooltip for a #r "..." location. Use a value from FSharpTokenInfo.Tag, or FSharpTokenTag.Identifier, unless you have other information available. + An optional string used for tracing compiler operations associated with this request. + + + Get any extra colorization info that is available after the typecheck + + + Compute a set of method overloads to show in a dialog relevant to the given code location. The resulting method overloads are returned as symbols. + The line number where the information is being requested. + The column number at the end of the identifiers where the information is being requested. + The text of the line where the information is being requested. + The identifiers at the location where the information is being requested. + An optional string used for tracing compiler operations associated with this request. + + + Compute a set of method overloads to show in a dialog relevant to the given code location. + + The line number where the information is being requested. + The column number at the end of the identifiers where the information is being requested. + The text of the line where the information is being requested. + The identifiers at the location where the information is being requested. + An optional string used for tracing compiler operations associated with this request. + + + Get the locations of and number of arguments associated with format specifiers + + + Get the locations of format specifiers + + + Compute the Visual Studio F1-help key identifier for the given location, based on name resolution results + + The line number where the information is being requested. + The column number at the end of the identifiers where the information is being requested. + The text of the line where the information is being requested. + The identifiers at the location where the information is being requested. + An optional string used for tracing compiler operations associated with this request. + + + + Find the most precise display environment for the given line and column. + + + + Resolve the names at the given location to the declaration location of the corresponding construct. + + The line number where the information is being requested. + The column number at the end of the identifiers where the information is being requested. + The text of the line where the information is being requested. + The identifiers at the location where the information is being requested. + If not given, then get the location of the symbol. If false, then prefer the location of the corresponding symbol in the implementation of the file (rather than the signature if present). If true, prefer the location of the corresponding symbol in the signature of the file (rather than the implementation). + An optional string used for tracing compiler operations associated with this request. + + + Get the items for a declaration list in FSharpSymbol format + + + If this is present, it is used to filter declarations based on location in the + parse tree, specifically at 'open' declarations, 'inherit' of class or interface + 'record field' locations and r.h.s. of 'range' operator a..b + + The line number where the completion is happening + + Partial long name. QuickParse.GetPartialLongNameEx can be used to get it. + + + The text of the line where the completion is happening. This is only used to make a couple + of adhoc corrections to completion accuracy (e.g. checking for "..") + + + Function that returns all entities from current and referenced assemblies. + + + If text has been used from a captured name resolution from the typecheck, then + callback to the client to check if the text has changed. If it has, then give up + and assume that we're going to repeat the operation later on. + + An optional string used for tracing compiler operations associated with this request. + + + Get the items for a declaration list + + + If this is present, it is used to filter declarations based on location in the + parse tree, specifically at 'open' declarations, 'inherit' of class or interface + 'record field' locations and r.h.s. of 'range' operator a..b + + The line number where the completion is happening + + Partial long name. QuickParse.GetPartialLongNameEx can be used to get it. + + + The text of the line where the completion is happening. This is only used to make a couple + of adhoc corrections to completion accuracy (e.g. checking for "..") + + + Function that returns all entities from current and referenced assemblies. + + + If text has been used from a captured name resolution from the typecheck, then + callback to the client to check if the text has changed. If it has, then give up + and assume that we're going to repeat the operation later on. + + An optional string used for tracing compiler operations associated with this request. + + + + Get all textual usages of all symbols throughout the file + + + + + Internal constructor - check a file and collect errors + + + + + A handle to the results of CheckFileInProject. + + + + + Options used to determine active --define conditionals and other options relevant to parsing files in a project + + + + + Get the accessibility rights for this project context w.r.t. InternalsVisibleTo attributes granting access to other assemblies + + + + + Get the resolution and full contents of the assemblies referenced by the project options + + + + + Represents the checking context implied by the ProjectOptions + + + + + Indicates an external declaration was found + + + + + Indicates a declaration location was found + + + + + Indicates a declaration location was not found, with an additional reason + + + + + Represents the result of the GetDeclarationLocation operation. + + + + + Trying to find declaration of ProvidedMember without TypeProviderDefinitionLocationAttribute + + + + + Trying to find declaration of ProvidedType without TypeProviderDefinitionLocationAttribute + + + + + Source code file is not available + + + + + Generic reason: no particular information about error apart from a message + + + + + Represents the reason why the GetDeclarationLocation operation failed. + + + + + The default location of FSharp.Core.dll and fsc.exe based on the version of fsc.exe that is running + + + + + Information about the compilation environment + + + + + Get or set the pause time in milliseconds before background work is started. + + + - Get a view of the overall contents of the assembly. Only valid to use if HasCriticalErrors is false. + A maximum number of megabytes of allocated memory. If the figure reported by <c>System.GC.GetTotalMemory(false)</c> goes over this limit, the FSharpChecker object will attempt to free memory and reduce cache sizes to a minimum.</param> - + - Get the textual usages that resolved to the given symbol throughout the project + Get or set a flag which controls if background work is started implicitly. + + If true, calls to CheckFileInProject implicitly start a background check of that project, replacing + any other background checks in progress. This is useful in IDE applications with spare CPU cycles as + it prepares the project analysis results for use. The default is 'true'. - + - Get an optimized view of the overall contents of the assembly. Only valid to use if HasCriticalErrors is false. + Notify the host that a project has been fully checked in the background (using file contents provided by the file system API) + + The event may be raised on a background thread. - + - Get all textual usages of all symbols throughout the project + Get or set the pause time in milliseconds before background work is started. - + - A handle to the results of CheckFileInProject. + Raised after the maxMB memory threshold limit is reached - + - Get the resolution of the ProjectOptions + A maximum number of megabytes of allocated memory. If the figure reported by <c>System.GC.GetTotalMemory(false)</c> goes over this limit, the FSharpChecker object will attempt to free memory and reduce cache sizes to a minimum.</param> - + - Get a view of the contents of the assembly up to and including the file just checked + Get or set a flag which controls if background work is started implicitly. + + If true, calls to CheckFileInProject implicitly start a background check of that project, replacing + any other background checks in progress. This is useful in IDE applications with spare CPU cycles as + it prepares the project analysis results for use. The default is 'true'. - + - Open declarations in the file, including auto open modules. + Report a statistic for testability - + - Represents complete typechecked implementation file, including its typechecked signatures if any. + Report a statistic for testability - + - Indicates whether type checking successfully occurred with some results returned. If false, indicates that - an unrecoverable error in earlier checking/parsing/resolution steps. + Raised after a parse of a file in the background analysis. + + The event will be raised on a background thread. - + - The errors returned by parsing a source file. + Raised after a check of a file in the background analysis. + + The event will be raised on a background thread. - + - Indicates the set of files which must be watched to accurately track changes that affect these results, - Clients interested in reacting to updates to these files should watch these files and take actions as described - in the documentation for compiler service. + Current queue length of the service, for debug purposes. + In addition, a single async operation or a step of a background build + may be in progress - such an operation is not counted in the queue length. - + - Determines if a long ident is resolvable at a specific point. - <param name="userOpName">An optional string used for tracing compiler operations associated with this request.</param> + Notify the host that the logical type checking context for a file has now been updated internally + and that the file has become eligible to be re-typechecked for errors. + + The event will be raised on a background thread. - + - Determines if a long ident is resolvable at a specific point. + Block until the background compile finishes. + + + + + Try to get type check results for a file. This looks up the results of recent type checks of the + same file, regardless of contents. The version tag specified in the original check of the file is returned. + If the source of the file has changed the results returned by this function may be out of date, though may + still be usable for generating intellisense menus and information. + + The filename for the file. + The options for the project or script, used to determine active --define conditionals and other options relevant to parsing. + Optionally, specify source that must match the previous parse precisely. + An optional string used for tracing compiler operations associated with this request. + + + + Tokenize a single line, returning token information and a tokenization state represented by an integer + + + + + Tokenize an entire file, line by line + + + + + Stop the background compile. + + + + + Parses a source code for a file. Returns an AST that can be traversed for various features. + + + The path for the file. The file name is also as a module name for implicit top level modules (e.g. in scripts). + The source to be parsed. + Parsing options for the project or script. + An optional string used for tracing compiler operations associated with this request. + + + + Parses a source code for a file. Returns an AST that can be traversed for various features. + + + The path for the file. The file name is also as a module name for implicit top level modules (e.g. in scripts). + The source to be parsed. + Parsing options for the project or script. + An optional string used for tracing compiler operations associated with this request. + + + + Parses a source code for a file and caches the results. Returns an AST that can be traversed for various features. + + + The path for the file. The file name is used as a module name for implicit top level modules (e.g. in scripts). + The source to be parsed. + Parsing options for the project or script. + An optional string used for tracing compiler operations associated with this request. + + + + Parse and typecheck all files in a project. + All files are read from the FileSystem API + + + The options for the project or script. + An optional string used for tracing compiler operations associated with this request. + + + + + Parse and check a source code file, returning a handle to the results + + + Note: all files except the one being checked are read from the FileSystem API + + + Return FSharpCheckFileAnswer.Aborted if a parse tree was not available. + + + + The name of the file in the project whose source is being checked. + An integer that can be used to indicate the version of the file. This will be returned by TryGetRecentCheckResultsForFile when looking up the file. + The full source for the file. + The options for the project or script. + + An item passed back to 'hasTextChangedSinceLastTypecheck' (from some calls made on 'FSharpCheckFileResults') to help determine if + an approximate intellisense resolution is inaccurate because a range of text has changed. This + can be used to marginally increase accuracy of intellisense results in some situations. + + An optional string used for tracing compiler operations associated with this request. + + + + This function is called when a project has been cleaned/rebuilt, and thus any live type providers should be refreshed. + + An optional string used for tracing compiler operations associated with this request. + + + + Parse a source code file, returning information about brace matching in the file. + Return an enumeration of the matching parenthetical tokens in the file. + + + The filename for the file, used to help caching of results. + The full source for the file. + Parsing options for the project or script. + An optional string used for tracing compiler operations associated with this request. + + + + Parse a source code file, returning information about brace matching in the file. + Return an enumeration of the matching parenthetical tokens in the file. + + + The filename for the file, used to help caching of results. + The full source for the file. + Parsing options for the project or script. + An optional string used for tracing compiler operations associated with this request. + + + + This function is called when the configuration is known to have changed for reasons not encoded in the ProjectOptions. + For example, dependent references may have been deleted or created. + <param name="startBackgroundCompileIfAlreadySeen">Start a background compile of the project if a project with the same name has already been seen before.</param> <param name="userOpName">An optional string used for tracing compiler operations associated with this request.</param> - + - Get the textual usages that resolved to the given symbol throughout the file + This function is called when the entire environment is known to have changed for reasons not encoded in the ProjectOptions of any project/compilation. - - Compute a formatted tooltip for the given location + + + 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. + - The line number where the information is being requested. - The column number at the end of the identifiers where the information is being requested. - The text of the line where the information is being requested. - The identifiers at the location where the information is being requested. - Used to discriminate between 'identifiers', 'strings' and others. For strings, an attempt is made to give a tooltip for a #r "..." location. Use a value from FSharpTokenInfo.Tag, or FSharpTokenTag.Identifier, unless you have other information available. + Used to differentiate between scripts, to consider each script a separate project. + Also used in formatted error messages. + + Indicates when the script was loaded into the editing environment, + so that an 'unload' and 'reload' action will cause the script to be considered as a new project, + so that references are re-resolved. An optional string used for tracing compiler operations associated with this request. - - Resolve the names at the given location to a use of symbol. + + + Get the FSharpProjectOptions implied by a set of command line arguments. + - The line number where the information is being requested. - The column number at the end of the identifiers where the information is being requested. - The text of the line where the information is being requested. - The identifiers at the location where the information is being requested. + Used to differentiate between projects and for the base directory of the project. + The command line arguments for the project build. + Indicates when the script was loaded into the editing environment, + so that an 'unload' and 'reload' action will cause the script to be considered as a new project, + so that references are re-resolved. + + + + Get the FSharpParsingOptions implied by a FSharpProjectOptions. + + + The command line arguments for the project build. + + + + Get the FSharpParsingOptions implied by a set of command line arguments. + + + The command line arguments for the project build. + + + + Get the FSharpParsingOptions implied by a set of command line arguments and list of source files. + + + Initial source files list. Additional files may be added during argv evaluation. + The command line arguments for the project build. + + + + Get semantic classification for a file. + All files are read from the FileSystem API, including the file being checked. + + + The filename for the file. + The options for the project or script, used to determine active --define conditionals and other options relevant to parsing. + An optional string used for tracing compiler operations associated with this request. + + + + Like ParseFile, but uses results from the background builder. + All files are read from the FileSystem API, including the file being checked. + + + The filename for the file. + The options for the project or script, used to determine active --define conditionals and other options relevant to parsing. + An optional string used for tracing compiler operations associated with this request. + + + + Like CheckFileInProject, but uses the existing results from the background builder. + All files are read from the FileSystem API, including the file being checked. + + + The filename for the file. + The options for the project or script, used to determine active --define conditionals and other options relevant to parsing. An optional string used for tracing compiler operations associated with this request. - - Compute a formatted tooltip for the given location + + + Optimized find references for a given symbol in a file of project. + All files are read from the FileSystem API, including the file being checked. + - The line number where the information is being requested. - The column number at the end of the identifiers where the information is being requested. - The text of the line where the information is being requested. - The identifiers at the location where the information is being requested. - Used to discriminate between 'identifiers', 'strings' and others. For strings, an attempt is made to give a tooltip for a #r "..." location. Use a value from FSharpTokenInfo.Tag, or FSharpTokenTag.Identifier, unless you have other information available. + The filename for the file. + The options for the project or script, used to determine active --define conditionals and other options relevant to parsing. + The symbol to find all uses in the file. An optional string used for tracing compiler operations associated with this request. - - Get any extra colorization info that is available after the typecheck + + + Create an instance of an FSharpChecker. + + + The optional size of the project checking cache. + Keep the checked contents of projects. + If false, do not keep full intermediate checking results from background checking suitable for returning from GetBackgroundCheckResultsForFileInProject. This reduces memory usage. + An optional resolver for non-file references, for legacy purposes + An optional resolver to access the contents of .NET binaries in a memory-efficient way - - Compute a set of method overloads to show in a dialog relevant to the given code location. The resulting method overloads are returned as symbols. - The line number where the information is being requested. - The column number at the end of the identifiers where the information is being requested. - The text of the line where the information is being requested. - The identifiers at the location where the information is being requested. + + + TypeCheck and compile provided AST + An optional string used for tracing compiler operations associated with this request. - - Compute a set of method overloads to show in a dialog relevant to the given code location. + + + Compiles to a dynamic assembly using the given flags. - The line number where the information is being requested. - The column number at the end of the identifiers where the information is being requested. - The text of the line where the information is being requested. - The identifiers at the location where the information is being requested. + The first argument is ignored and can just be "fsc.exe". + + Any source files names are resolved via the FileSystem API. An output file name must be given by a -o flag, but this will not + be written - instead a dynamic assembly will be created and loaded. + + If the 'execute' parameter is given the entry points for the code are executed and + the given TextWriters are used for the stdout and stderr streams respectively. In this + case, a global setting is modified during the execution. + An optional string used for tracing compiler operations associated with this request. - - Get the locations of and number of arguments associated with format specifiers - - - Get the locations of format specifiers + + + TypeCheck and compile provided AST + + An optional string used for tracing compiler operations associated with this request. - - Compute the Visual Studio F1-help key identifier for the given location, based on name resolution results - - The line number where the information is being requested. - The column number at the end of the identifiers where the information is being requested. - The text of the line where the information is being requested. - The identifiers at the location where the information is being requested. + + + Compile using the given flags. Source files names are resolved via the FileSystem API. + The output file must be given by a -o flag. + The first argument is ignored and can just be "fsc.exe". + An optional string used for tracing compiler operations associated with this request. - + - Find the most precise display environment for the given line and column. + Flush all caches and garbage collect - - Resolve the names at the given location to the declaration location of the corresponding construct. - - The line number where the information is being requested. - The column number at the end of the identifiers where the information is being requested. - The text of the line where the information is being requested. - The identifiers at the location where the information is being requested. - If not given, then get the location of the symbol. If false, then prefer the location of the corresponding symbol in the implementation of the file (rather than the signature if present). If true, prefer the location of the corresponding symbol in the signature of the file (rather than the implementation). - An optional string used for tracing compiler operations associated with this request. + + + Set the project to be checked in the background. Overrides any previous call to <c>CheckProjectInBackground</c> + - - Get the items for a declaration list in FSharpSymbol format + + + Check a source code file, returning a handle to the results of the parse including + the reconstructed types in the file. - - If this is present, it is used to filter declarations based on location in the - parse tree, specifically at 'open' declarations, 'inherit' of class or interface - 'record field' locations and r.h.s. of 'range' operator a..b - - The line number where the completion is happening - - Partial long name. QuickParse.GetPartialLongNameEx can be used to get it. - - - The text of the line where the completion is happening. This is only used to make a couple - of adhoc corrections to completion accuracy (e.g. checking for "..") - - - Function that returns all entities from current and referenced assemblies. - - - If text has been used from a captured name resolution from the typecheck, then - callback to the client to check if the text has changed. If it has, then give up - and assume that we're going to repeat the operation later on. + All files except the one being checked are read from the FileSystem API + Note: returns NoAntecedent if the background builder is not yet done preparing the type check context for the + file (e.g. loading references and parsing/checking files in the project that this file depends upon). + In this case, the caller can either retry, or wait for FileTypeCheckStateIsDirty to be raised for this file. + + + + The results of ParseFile for this file. + The name of the file in the project whose source is being checked. + An integer that can be used to indicate the version of the file. This will be returned by TryGetRecentCheckResultsForFile when looking up the file. + The full source for the file. + The options for the project or script. + + An item passed back to 'hasTextChangedSinceLastTypecheck' (from some calls made on 'FSharpCheckFileResults') to help determine if + an approximate intellisense resolution is inaccurate because a range of text has changed. This + can be used to marginally increase accuracy of intellisense results in some situations. An optional string used for tracing compiler operations associated with this request. - - Get the items for a declaration list + + + + Check a source code file, returning a handle to the results + + + Note: all files except the one being checked are read from the FileSystem API + + + Return FSharpCheckFileAnswer.Aborted if a parse tree was not available. + + - - If this is present, it is used to filter declarations based on location in the - parse tree, specifically at 'open' declarations, 'inherit' of class or interface - 'record field' locations and r.h.s. of 'range' operator a..b - - The line number where the completion is happening - - Partial long name. QuickParse.GetPartialLongNameEx can be used to get it. - - - The text of the line where the completion is happening. This is only used to make a couple - of adhoc corrections to completion accuracy (e.g. checking for "..") - - - Function that returns all entities from current and referenced assemblies. - - - If text has been used from a captured name resolution from the typecheck, then - callback to the client to check if the text has changed. If it has, then give up - and assume that we're going to repeat the operation later on. + The results of ParseFile for this file. + The name of the file in the project whose source is being checked. + An integer that can be used to indicate the version of the file. This will be returned by TryGetRecentCheckResultsForFile when looking up the file. + The full source for the file. + The options for the project or script. + + An item passed back to 'hasTextChangedSinceLastTypecheck' (from some calls made on 'FSharpCheckFileResults') to help determine if + an approximate intellisense resolution is inaccurate because a range of text has changed. This + can be used to marginally increase accuracy of intellisense results in some situations. An optional string used for tracing compiler operations associated with this request. - + - Get all textual usages of all symbols throughout the file + Used to parse and check F# source code. - + - A handle to the results of CheckFileInProject. + An optional stamp to uniquely identify this set of options + If two sets of options both have stamps, then they are considered equal + if and only if the stamps are equal - + - Get the accessibility rights for this project context w.r.t. InternalsVisibleTo attributes granting access to other assemblies + Extra information passed back on event trigger - + - Get the resolution and full contents of the assemblies referenced by the project options + Unused in this API and should be '[]' when used as user-specified input - + - Represents the checking context implied by the ProjectOptions + Unused in this API and should be 'None' when used as user-specified input - + - Indicates an external declaration was found + Timestamp of project/script load, used to differentiate between different instances of a project load. + This ensures that a complete reload of the project or script type checking + context occurs on project or script unload/reload. - + - Indicates a declaration location was found + When true, use the reference resolution rules for scripts rather than the rules for compiler. - + - Indicates a declaration location was not found, with an additional reason + When true, the typechecking environment is known a priori to be incomplete, for + example when a .fs file is opened outside of a project. In this case, the number of error + messages reported is reduced. - + - Represents the result of the GetDeclarationLocation operation. + The command line arguments for the other projects referenced by this project, indexed by the + exact text used in the "-r:" reference in FSharpProjectOptions. - + - Trying to find declaration of ProvidedMember without TypeProviderDefinitionLocationAttribute + Additional command line argument options for the project. These can include additional files and references. - + - Trying to find declaration of ProvidedType without TypeProviderDefinitionLocationAttribute + The files in the project - + - Source code file is not available + This is the unique identifier for the project, it is case sensitive. If it's None, will key off of ProjectFileName in our caching. - - - Generic reason: no particular information about error apart from a message - + + A set of information describing a project or script build configuration. - - - Represents the reason why the GetDeclarationLocation operation failed. - + + Unused in this API @@ -29806,7 +32259,7 @@ Special cases where representation uses Lambda. - Matches expressions for an unresolved call to a trait + Matches expressions for an unresolved call to a trait @@ -29846,7 +32299,7 @@ Special cases where representation uses Lambda. - Matches while loops + Matches while loops @@ -29856,7 +32309,7 @@ Special cases where representation uses Lambda. - Matches sequential expressions + Matches sequential expressions @@ -29892,7 +32345,7 @@ Special cases where representation uses Lambda. - Matches array expressions + Matches array expressions @@ -29907,7 +32360,7 @@ Special cases where representation uses Lambda. - Matches tuple expressions + Matches tuple expressions @@ -29953,12 +32406,12 @@ Special cases where representation uses Lambda. - Matches anonymous record expressions + Matches anonymous record expressions - Matches record expressions + Matches record expressions @@ -29983,7 +32436,7 @@ Special cases where representation uses Lambda. - Matches expressions which are calls to object constructors + Matches expressions which are calls to object constructors @@ -30015,7 +32468,7 @@ Special cases where representation uses Lambda. - Matches expressions with a decision expression, each branch of which ends in DecisionTreeSuccess pasing control and values to one of the targets. + Matches expressions with a decision expression, each branch of which ends in DecisionTreeSuccess passing control and values to one of the targets. @@ -30025,12 +32478,12 @@ Special cases where representation uses Lambda. - Matches expressions which are the application of function values + Matches expressions which are the application of function values - Matches expressions which are uses of values + Matches expressions which are uses of values @@ -30043,6 +32496,11 @@ Special cases where representation uses Lambda. Patterns over FSharpSymbol and derivatives. + + + Extension methods for the TcResolutions type. + + Keywords paired with their descriptions. Used in completion and quick info. @@ -30058,9 +32516,14 @@ Special cases where representation uses Lambda. Add backticks if the identifier is a keyword. + + + Checks if adding backticks to identifier is needed. + + - Indicates the token is keyword `new` + Indicates the token is keyword `new` @@ -30204,6 +32667,11 @@ Special cases where representation uses Lambda. + + Indicates the token is a `..^` + + + Indicates the token is a `..` @@ -30358,62 +32826,62 @@ Special cases where representation uses Lambda. Some of the values in the field FSharpTokenInfo.Tag - + VisitTypeAbbrev(ty,m), defaults to ignoring this leaf of the AST - + VisitType allows overriding behavior when visiting type hints (x: ..., etc.) - + VisitType allows overriding behavior when visiting simple pats - + VisitRecordField allows overriding behavior when visiting l.h.s. of constructed record instances - + VisitPat allows overriding behavior when visiting patterns - + VisitModuleOrNamespace allows overriding behavior when visiting module or namespaces - + VisitModuleDecl allows overriding module declaration behavior - + VisitMatchClause allows overriding clause behavior (note: by default it would defaultTraverse expression) - + VisitLetOrUse allows overriding behavior when visiting module or local let or use bindings - + VisitInterfaceSynMemberDefnType allows overriding behavior for visiting interface member in types (by default - do nothing) - + VisitInheritSynMemberDefn allows overriding inherit behavior (by default do nothing) - + VisitImplicitInherit(defaultTraverse,ty,expr,m), defaults to just visiting expr @@ -30423,22 +32891,22 @@ Special cases where representation uses Lambda. VisitHashDirective allows overriding behavior when visiting hash directives in FSX scripts, like #r, #load and #I. - + VisitExpr(path, traverseSynExpr, defaultTraverse, expr) - controls the behavior when a SynExpr is reached; it can just do + controls the behavior when a SynExpr is reached; it can just do defaultTraverse(expr) if you have no special logic for this node, and want the default processing to pick which sub-node to dive deeper into or can inject non-default behavior, which might incorporate: traverseSynExpr(subExpr) to recurse deeper on some particular sub-expression based on your own logic path helps to track AST nodes that were passed during traversal - + - VisitComponentInfo allows overriding behavior when visiting type component infos + VisitComponentInfo allows overriding behavior when visiting type component infos - + VisitBinding allows overriding binding behavior (note: by default it would defaultTraverse expression) @@ -30448,7 +32916,7 @@ Special cases where representation uses Lambda. used to track route during traversal AST - + traverse an implementation file walking all the way down to SynExpr or TypeAbbrev at a particular location @@ -30524,17 +32992,17 @@ Special cases where representation uses Lambda. Corrects insertion line number based on kind of scope and text surrounding the insertion point. - + - Returns lond identifier at position. + Returns long identifier at position. - + Returns `InsertContext` based on current position and symbol idents. - + Returns `InsertContext` based on current position and symbol idents. @@ -30559,7 +33027,7 @@ Special cases where representation uses Lambda. Provides assembly content. - + Get the list of Xml documentation from current source code @@ -30569,14 +33037,19 @@ Special cases where representation uses Lambda. if it's a blank XML comment with trailing "<", returns Some (index of the "<"), otherwise returns None + + + A set of helpers for dealing with F# files. + + - All the keywords in the F# language + All the keywords in the F# language - A utility to help determine if an identifier needs to be quoted + A utility to help determine if an identifier needs to be quoted @@ -30613,10 +33086,10 @@ Special cases where representation uses Lambda. - Information about the compilation environment + Information about the compilation environment - + Find corresponding interface declaration at a given position @@ -30666,7 +33139,7 @@ Special cases where representation uses Lambda. - Tag to identify the constuct that can be stored alongside its associated ranges + Tag to identify the construct that can be stored alongside its associated ranges @@ -30676,19 +33149,39 @@ Special cases where representation uses Lambda. following a binding or the right hand side of a pattern, e.g. `let x = ...` - + Returns outlining ranges for given parsed input. - + - Get all unused open declarations in a file + Get all unused declarations in a file - + - Defines a read-only input stream used to feed content to the hosted F# Interactive dynamic compiler. + The relative name that can be applied to a simplifiable name + + + + + The range of a name that can be simplified + + + + + Data for use in finding unnecessarily-qualified names and generating diagnostics to simplify them + + + + + Get all ranges that can be simplified in a file + + + + + Get all unused open declarations in a file diff --git a/package-lock.json b/package-lock.json index ea11b7979b..400bd75e74 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2,85 +2,58 @@ "requires": true, "lockfileVersion": 1, "dependencies": { - "@ava/babel-plugin-throws-helper": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@ava/babel-plugin-throws-helper/-/babel-plugin-throws-helper-3.0.0.tgz", - "integrity": "sha512-mN9UolOs4WX09QkheU1ELkVy2WPnwonlO3XMdN8JF8fQqRVgVTR21xDbvEOUsbwz6Zwjq7ji9yzyjuXqDPalxg==" - }, - "@ava/babel-preset-stage-4": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@ava/babel-preset-stage-4/-/babel-preset-stage-4-2.0.0.tgz", - "integrity": "sha512-OWqMYeTSZ16AfLx0Vn0Uj7tcu+uMRlbKmks+DVCFlln7vomVsOtst+Oz+HCussDSFGpE+30VtHAUHLy6pLDpHQ==", - "requires": { - "@babel/plugin-proposal-async-generator-functions": "^7.0.0", - "@babel/plugin-proposal-object-rest-spread": "^7.0.0", - "@babel/plugin-proposal-optional-catch-binding": "^7.0.0", - "@babel/plugin-transform-async-to-generator": "^7.0.0", - "@babel/plugin-transform-dotall-regex": "^7.0.0", - "@babel/plugin-transform-exponentiation-operator": "^7.0.0", - "@babel/plugin-transform-modules-commonjs": "^7.0.0" - } - }, - "@ava/babel-preset-transform-test-files": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/@ava/babel-preset-transform-test-files/-/babel-preset-transform-test-files-5.0.0.tgz", - "integrity": "sha512-rqgyQwkT0+j2JzYP51dOv80u33rzAvjBtXRzUON+7+6u26mjoudRXci2+1s18rat8r4uOlZfbzm114YS6pwmYw==", - "requires": { - "@ava/babel-plugin-throws-helper": "^3.0.0", - "babel-plugin-espower": "^3.0.1" - } - }, - "@ava/write-file-atomic": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@ava/write-file-atomic/-/write-file-atomic-2.2.0.tgz", - "integrity": "sha512-BTNB3nGbEfJT+69wuqXFr/bQH7Vr7ihx2xGOMNqPgDGhwspoZhiWumDDZNjBy7AScmqS5CELIOGtPVXESyrnDA==", - "requires": { - "graceful-fs": "^4.1.11", - "imurmurhash": "^0.1.4", - "slide": "^1.1.5" - } - }, "@babel/cli": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/cli/-/cli-7.4.3.tgz", - "integrity": "sha512-cbC5H9iTDV9H7sMxK5rUm18UbdVPNTPqgdzmQAkOUP3YLysgDWLZaysVAfylK49rgTlzL01a6tXyq9rCb3yLhQ==", + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/cli/-/cli-7.8.4.tgz", + "integrity": "sha512-XXLgAm6LBbaNxaGhMAznXXaxtCWfuv6PIDJ9Alsy9JYTOh+j2jJz+L/162kkfU1j/pTSxK1xGmlwI4pdIMkoag==", "requires": { - "chokidar": "^2.0.4", - "commander": "^2.8.1", + "chokidar": "^2.1.8", + "commander": "^4.0.1", "convert-source-map": "^1.1.0", "fs-readdir-recursive": "^1.1.0", "glob": "^7.0.0", - "lodash": "^4.17.11", - "mkdirp": "^0.5.1", - "output-file-sync": "^2.0.0", + "lodash": "^4.17.13", + "make-dir": "^2.1.0", "slash": "^2.0.0", "source-map": "^0.5.0" } }, "@babel/code-frame": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz", - "integrity": "sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.8.3.tgz", + "integrity": "sha512-a9gxpmdXtZEInkCSHUJDLHZVBgb1QS0jhss4cPP93EW7s+uC5bikET2twEF3KV+7rDblJcmNvTR7VJejqd2C2g==", "requires": { - "@babel/highlight": "^7.0.0" + "@babel/highlight": "^7.8.3" } }, - "@babel/core": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.4.3.tgz", - "integrity": "sha512-oDpASqKFlbspQfzAE7yaeTmdljSH2ADIvBlb0RwbStltTuWa0+7CCI1fYVINNv9saHPa1W7oaKeuNuKj+RQCvA==", + "@babel/compat-data": { + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.9.0.tgz", + "integrity": "sha512-zeFQrr+284Ekvd9e7KAX954LkapWiOmQtsfHirhxqfdlX6MEC32iRE+pqUGlYIBchdevaCwvzxWGSy/YBNI85g==", "requires": { - "@babel/code-frame": "^7.0.0", - "@babel/generator": "^7.4.0", - "@babel/helpers": "^7.4.3", - "@babel/parser": "^7.4.3", - "@babel/template": "^7.4.0", - "@babel/traverse": "^7.4.3", - "@babel/types": "^7.4.0", - "convert-source-map": "^1.1.0", + "browserslist": "^4.9.1", + "invariant": "^2.2.4", + "semver": "^5.5.0" + } + }, + "@babel/core": { + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.9.0.tgz", + "integrity": "sha512-kWc7L0fw1xwvI0zi8OKVBuxRVefwGOrKSQMvrQ3dW+bIIavBY3/NpXmpjMy7bQnLgwgzWQZ8TlM57YHpHNHz4w==", + "requires": { + "@babel/code-frame": "^7.8.3", + "@babel/generator": "^7.9.0", + "@babel/helper-module-transforms": "^7.9.0", + "@babel/helpers": "^7.9.0", + "@babel/parser": "^7.9.0", + "@babel/template": "^7.8.6", + "@babel/traverse": "^7.9.0", + "@babel/types": "^7.9.0", + "convert-source-map": "^1.7.0", "debug": "^4.1.0", - "json5": "^2.1.0", - "lodash": "^4.17.11", + "gensync": "^1.0.0-beta.1", + "json5": "^2.1.2", + "lodash": "^4.17.13", "resolve": "^1.3.2", "semver": "^5.4.1", "source-map": "^0.5.0" @@ -95,667 +68,791 @@ } }, "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" } } }, "@babel/generator": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.4.0.tgz", - "integrity": "sha512-/v5I+a1jhGSKLgZDcmAUZ4K/VePi43eRkUs3yePW1HB1iANOD5tqJXwGSG4BZhSksP8J9ejSlwGeTiiOFZOrXQ==", + "version": "7.9.4", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.9.4.tgz", + "integrity": "sha512-rjP8ahaDy/ouhrvCoU1E5mqaitWrxwuNGU+dy1EpaoK48jZay4MdkskKGIMHLZNewg8sAsqpGSREJwP0zH3YQA==", "requires": { - "@babel/types": "^7.4.0", + "@babel/types": "^7.9.0", "jsesc": "^2.5.1", - "lodash": "^4.17.11", - "source-map": "^0.5.0", - "trim-right": "^1.0.1" + "lodash": "^4.17.13", + "source-map": "^0.5.0" } }, "@babel/helper-annotate-as-pure": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.0.0.tgz", - "integrity": "sha512-3UYcJUj9kvSLbLbUIfQTqzcy5VX7GRZ/CCDrnOaZorFFM01aXp1+GJwuFGV4NDDoAS+mOUyHcO6UD/RfqOks3Q==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.8.3.tgz", + "integrity": "sha512-6o+mJrZBxOoEX77Ezv9zwW7WV8DdluouRKNY/IR5u/YTMuKHgugHOzYWlYvYLpLA9nPsQCAAASpCIbjI9Mv+Uw==", "requires": { - "@babel/types": "^7.0.0" + "@babel/types": "^7.8.3" } }, "@babel/helper-builder-binary-assignment-operator-visitor": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.1.0.tgz", - "integrity": "sha512-qNSR4jrmJ8M1VMM9tibvyRAHXQs2PmaksQF7c1CGJNipfe3D8p+wgNwgso/P2A2r2mdgBWAXljNWR0QRZAMW8w==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.8.3.tgz", + "integrity": "sha512-5eFOm2SyFPK4Rh3XMMRDjN7lBH0orh3ss0g3rTYZnBQ+r6YPj7lgDyCvPphynHvUrobJmeMignBr6Acw9mAPlw==", "requires": { - "@babel/helper-explode-assignable-expression": "^7.1.0", - "@babel/types": "^7.0.0" + "@babel/helper-explode-assignable-expression": "^7.8.3", + "@babel/types": "^7.8.3" } }, - "@babel/helper-call-delegate": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/@babel/helper-call-delegate/-/helper-call-delegate-7.4.0.tgz", - "integrity": "sha512-SdqDfbVdNQCBp3WhK2mNdDvHd3BD6qbmIc43CAyjnsfCmgHMeqgDcM3BzY2lchi7HBJGJ2CVdynLWbezaE4mmQ==", + "@babel/helper-compilation-targets": { + "version": "7.8.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.8.7.tgz", + "integrity": "sha512-4mWm8DCK2LugIS+p1yArqvG1Pf162upsIsjE7cNBjez+NjliQpVhj20obE520nao0o14DaTnFJv+Fw5a0JpoUw==", "requires": { - "@babel/helper-hoist-variables": "^7.4.0", - "@babel/traverse": "^7.4.0", - "@babel/types": "^7.4.0" + "@babel/compat-data": "^7.8.6", + "browserslist": "^4.9.1", + "invariant": "^2.2.4", + "levenary": "^1.1.1", + "semver": "^5.5.0" + } + }, + "@babel/helper-create-regexp-features-plugin": { + "version": "7.8.8", + "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.8.8.tgz", + "integrity": "sha512-LYVPdwkrQEiX9+1R29Ld/wTrmQu1SSKYnuOk3g0CkcZMA1p0gsNxJFj/3gBdaJ7Cg0Fnek5z0DsMULePP7Lrqg==", + "requires": { + "@babel/helper-annotate-as-pure": "^7.8.3", + "@babel/helper-regex": "^7.8.3", + "regexpu-core": "^4.7.0" } }, "@babel/helper-define-map": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/@babel/helper-define-map/-/helper-define-map-7.4.0.tgz", - "integrity": "sha512-wAhQ9HdnLIywERVcSvX40CEJwKdAa1ID4neI9NXQPDOHwwA+57DqwLiPEVy2AIyWzAk0CQ8qx4awO0VUURwLtA==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-define-map/-/helper-define-map-7.8.3.tgz", + "integrity": "sha512-PoeBYtxoZGtct3md6xZOCWPcKuMuk3IHhgxsRRNtnNShebf4C8YonTSblsK4tvDbm+eJAw2HAPOfCr+Q/YRG/g==", "requires": { - "@babel/helper-function-name": "^7.1.0", - "@babel/types": "^7.4.0", - "lodash": "^4.17.11" + "@babel/helper-function-name": "^7.8.3", + "@babel/types": "^7.8.3", + "lodash": "^4.17.13" } }, "@babel/helper-explode-assignable-expression": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@babel/helper-explode-assignable-expression/-/helper-explode-assignable-expression-7.1.0.tgz", - "integrity": "sha512-NRQpfHrJ1msCHtKjbzs9YcMmJZOg6mQMmGRB+hbamEdG5PNpaSm95275VD92DvJKuyl0s2sFiDmMZ+EnnvufqA==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-explode-assignable-expression/-/helper-explode-assignable-expression-7.8.3.tgz", + "integrity": "sha512-N+8eW86/Kj147bO9G2uclsg5pwfs/fqqY5rwgIL7eTBklgXjcOJ3btzS5iM6AitJcftnY7pm2lGsrJVYLGjzIw==", "requires": { - "@babel/traverse": "^7.1.0", - "@babel/types": "^7.0.0" + "@babel/traverse": "^7.8.3", + "@babel/types": "^7.8.3" } }, "@babel/helper-function-name": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.1.0.tgz", - "integrity": "sha512-A95XEoCpb3TO+KZzJ4S/5uW5fNe26DjBGqf1o9ucyLyCmi1dXq/B3c8iaWTfBk3VvetUxl16e8tIrd5teOCfGw==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.8.3.tgz", + "integrity": "sha512-BCxgX1BC2hD/oBlIFUgOCQDOPV8nSINxCwM3o93xP4P9Fq6aV5sgv2cOOITDMtCfQ+3PvHp3l689XZvAM9QyOA==", "requires": { - "@babel/helper-get-function-arity": "^7.0.0", - "@babel/template": "^7.1.0", - "@babel/types": "^7.0.0" + "@babel/helper-get-function-arity": "^7.8.3", + "@babel/template": "^7.8.3", + "@babel/types": "^7.8.3" } }, "@babel/helper-get-function-arity": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0.tgz", - "integrity": "sha512-r2DbJeg4svYvt3HOS74U4eWKsUAMRH01Z1ds1zx8KNTPtpTL5JAsdFv8BNyOpVqdFhHkkRDIg5B4AsxmkjAlmQ==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.8.3.tgz", + "integrity": "sha512-FVDR+Gd9iLjUMY1fzE2SR0IuaJToR4RkCDARVfsBBPSP53GEqSFjD8gNyxg246VUyc/ALRxFaAK8rVG7UT7xRA==", "requires": { - "@babel/types": "^7.0.0" + "@babel/types": "^7.8.3" } }, "@babel/helper-hoist-variables": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.4.0.tgz", - "integrity": "sha512-/NErCuoe/et17IlAQFKWM24qtyYYie7sFIrW/tIQXpck6vAu2hhtYYsKLBWQV+BQZMbcIYPU/QMYuTufrY4aQw==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.8.3.tgz", + "integrity": "sha512-ky1JLOjcDUtSc+xkt0xhYff7Z6ILTAHKmZLHPxAhOP0Nd77O+3nCsd6uSVYur6nJnCI029CrNbYlc0LoPfAPQg==", "requires": { - "@babel/types": "^7.4.0" + "@babel/types": "^7.8.3" } }, "@babel/helper-member-expression-to-functions": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.0.0.tgz", - "integrity": "sha512-avo+lm/QmZlv27Zsi0xEor2fKcqWG56D5ae9dzklpIaY7cQMK5N8VSpaNVPPagiqmy7LrEjK1IWdGMOqPu5csg==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.8.3.tgz", + "integrity": "sha512-fO4Egq88utkQFjbPrSHGmGLFqmrshs11d46WI+WZDESt7Wu7wN2G2Iu+NMMZJFDOVRHAMIkB5SNh30NtwCA7RA==", "requires": { - "@babel/types": "^7.0.0" + "@babel/types": "^7.8.3" } }, "@babel/helper-module-imports": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.0.0.tgz", - "integrity": "sha512-aP/hlLq01DWNEiDg4Jn23i+CXxW/owM4WpDLFUbpjxe4NS3BhLVZQ5i7E0ZrxuQ/vwekIeciyamgB1UIYxxM6A==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.8.3.tgz", + "integrity": "sha512-R0Bx3jippsbAEtzkpZ/6FIiuzOURPcMjHp+Z6xPe6DtApDJx+w7UYyOLanZqO8+wKR9G10s/FmHXvxaMd9s6Kg==", "requires": { - "@babel/types": "^7.0.0" + "@babel/types": "^7.8.3" } }, "@babel/helper-module-transforms": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.4.3.tgz", - "integrity": "sha512-H88T9IySZW25anu5uqyaC1DaQre7ofM+joZtAaO2F8NBdFfupH0SZ4gKjgSFVcvtx/aAirqA9L9Clio2heYbZA==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.9.0.tgz", + "integrity": "sha512-0FvKyu0gpPfIQ8EkxlrAydOWROdHpBmiCiRwLkUiBGhCUPRRbVD2/tm3sFr/c/GWFrQ/ffutGUAnx7V0FzT2wA==", "requires": { - "@babel/helper-module-imports": "^7.0.0", - "@babel/helper-simple-access": "^7.1.0", - "@babel/helper-split-export-declaration": "^7.0.0", - "@babel/template": "^7.2.2", - "@babel/types": "^7.2.2", - "lodash": "^4.17.11" + "@babel/helper-module-imports": "^7.8.3", + "@babel/helper-replace-supers": "^7.8.6", + "@babel/helper-simple-access": "^7.8.3", + "@babel/helper-split-export-declaration": "^7.8.3", + "@babel/template": "^7.8.6", + "@babel/types": "^7.9.0", + "lodash": "^4.17.13" } }, "@babel/helper-optimise-call-expression": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.0.0.tgz", - "integrity": "sha512-u8nd9NQePYNQV8iPWu/pLLYBqZBa4ZaY1YWRFMuxrid94wKI1QNt67NEZ7GAe5Kc/0LLScbim05xZFWkAdrj9g==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.8.3.tgz", + "integrity": "sha512-Kag20n86cbO2AvHca6EJsvqAd82gc6VMGule4HwebwMlwkpXuVqrNRj6CkCV2sKxgi9MyAUnZVnZ6lJ1/vKhHQ==", "requires": { - "@babel/types": "^7.0.0" + "@babel/types": "^7.8.3" } }, "@babel/helper-plugin-utils": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.0.0.tgz", - "integrity": "sha512-CYAOUCARwExnEixLdB6sDm2dIJ/YgEAKDM1MOeMeZu9Ld/bDgVo8aiWrXwcY7OBh+1Ea2uUcVRcxKk0GJvW7QA==" + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.8.3.tgz", + "integrity": "sha512-j+fq49Xds2smCUNYmEHF9kGNkhbet6yVIBp4e6oeQpH1RUs/Ir06xUKzDjDkGcaaokPiTNs2JBWHjaE4csUkZQ==" }, "@babel/helper-regex": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/helper-regex/-/helper-regex-7.4.3.tgz", - "integrity": "sha512-hnoq5u96pLCfgjXuj8ZLX3QQ+6nAulS+zSgi6HulUwFbEruRAKwbGLU5OvXkE14L8XW6XsQEKsIDfgthKLRAyA==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-regex/-/helper-regex-7.8.3.tgz", + "integrity": "sha512-BWt0QtYv/cg/NecOAZMdcn/waj/5P26DR4mVLXfFtDokSR6fyuG0Pj+e2FqtSME+MqED1khnSMulkmGl8qWiUQ==", "requires": { - "lodash": "^4.17.11" + "lodash": "^4.17.13" } }, "@babel/helper-remap-async-to-generator": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.1.0.tgz", - "integrity": "sha512-3fOK0L+Fdlg8S5al8u/hWE6vhufGSn0bN09xm2LXMy//REAF8kDCrYoOBKYmA8m5Nom+sV9LyLCwrFynA8/slg==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.8.3.tgz", + "integrity": "sha512-kgwDmw4fCg7AVgS4DukQR/roGp+jP+XluJE5hsRZwxCYGg+Rv9wSGErDWhlI90FODdYfd4xG4AQRiMDjjN0GzA==", "requires": { - "@babel/helper-annotate-as-pure": "^7.0.0", - "@babel/helper-wrap-function": "^7.1.0", - "@babel/template": "^7.1.0", - "@babel/traverse": "^7.1.0", - "@babel/types": "^7.0.0" + "@babel/helper-annotate-as-pure": "^7.8.3", + "@babel/helper-wrap-function": "^7.8.3", + "@babel/template": "^7.8.3", + "@babel/traverse": "^7.8.3", + "@babel/types": "^7.8.3" } }, "@babel/helper-replace-supers": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.4.0.tgz", - "integrity": "sha512-PVwCVnWWAgnal+kJ+ZSAphzyl58XrFeSKSAJRiqg5QToTsjL+Xu1f9+RJ+d+Q0aPhPfBGaYfkox66k86thxNSg==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.8.6.tgz", + "integrity": "sha512-PeMArdA4Sv/Wf4zXwBKPqVj7n9UF/xg6slNRtZW84FM7JpE1CbG8B612FyM4cxrf4fMAMGO0kR7voy1ForHHFA==", "requires": { - "@babel/helper-member-expression-to-functions": "^7.0.0", - "@babel/helper-optimise-call-expression": "^7.0.0", - "@babel/traverse": "^7.4.0", - "@babel/types": "^7.4.0" + "@babel/helper-member-expression-to-functions": "^7.8.3", + "@babel/helper-optimise-call-expression": "^7.8.3", + "@babel/traverse": "^7.8.6", + "@babel/types": "^7.8.6" } }, "@babel/helper-simple-access": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.1.0.tgz", - "integrity": "sha512-Vk+78hNjRbsiu49zAPALxTb+JUQCz1aolpd8osOF16BGnLtseD21nbHgLPGUwrXEurZgiCOUmvs3ExTu4F5x6w==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.8.3.tgz", + "integrity": "sha512-VNGUDjx5cCWg4vvCTR8qQ7YJYZ+HBjxOgXEl7ounz+4Sn7+LMD3CFrCTEU6/qXKbA2nKg21CwhhBzO0RpRbdCw==", "requires": { - "@babel/template": "^7.1.0", - "@babel/types": "^7.0.0" + "@babel/template": "^7.8.3", + "@babel/types": "^7.8.3" } }, "@babel/helper-split-export-declaration": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.4.0.tgz", - "integrity": "sha512-7Cuc6JZiYShaZnybDmfwhY4UYHzI6rlqhWjaIqbsJGsIqPimEYy5uh3akSRLMg65LSdSEnJ8a8/bWQN6u2oMGw==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.8.3.tgz", + "integrity": "sha512-3x3yOeyBhW851hroze7ElzdkeRXQYQbFIb7gLK1WQYsw2GWDay5gAJNw1sWJ0VFP6z5J1whqeXH/WCdCjZv6dA==", "requires": { - "@babel/types": "^7.4.0" + "@babel/types": "^7.8.3" } }, + "@babel/helper-validator-identifier": { + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.9.0.tgz", + "integrity": "sha512-6G8bQKjOh+of4PV/ThDm/rRqlU7+IGoJuofpagU5GlEl29Vv0RGqqt86ZGRV8ZuSOY3o+8yXl5y782SMcG7SHw==" + }, "@babel/helper-wrap-function": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.2.0.tgz", - "integrity": "sha512-o9fP1BZLLSrYlxYEYyl2aS+Flun5gtjTIG8iln+XuEzQTs0PLagAGSXUcqruJwD5fM48jzIEggCKpIfWTcR7pQ==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.8.3.tgz", + "integrity": "sha512-LACJrbUET9cQDzb6kG7EeD7+7doC3JNvUgTEQOx2qaO1fKlzE/Bf05qs9w1oXQMmXlPO65lC3Tq9S6gZpTErEQ==", "requires": { - "@babel/helper-function-name": "^7.1.0", - "@babel/template": "^7.1.0", - "@babel/traverse": "^7.1.0", - "@babel/types": "^7.2.0" + "@babel/helper-function-name": "^7.8.3", + "@babel/template": "^7.8.3", + "@babel/traverse": "^7.8.3", + "@babel/types": "^7.8.3" } }, "@babel/helpers": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.4.3.tgz", - "integrity": "sha512-BMh7X0oZqb36CfyhvtbSmcWc3GXocfxv3yNsAEuM0l+fAqSO22rQrUpijr3oE/10jCTrB6/0b9kzmG4VetCj8Q==", + "version": "7.9.2", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.9.2.tgz", + "integrity": "sha512-JwLvzlXVPjO8eU9c/wF9/zOIN7X6h8DYf7mG4CiFRZRvZNKEF5dQ3H3V+ASkHoIB3mWhatgl5ONhyqHRI6MppA==", "requires": { - "@babel/template": "^7.4.0", - "@babel/traverse": "^7.4.3", - "@babel/types": "^7.4.0" + "@babel/template": "^7.8.3", + "@babel/traverse": "^7.9.0", + "@babel/types": "^7.9.0" } }, "@babel/highlight": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0.tgz", - "integrity": "sha512-UFMC4ZeFC48Tpvj7C8UgLvtkaUuovQX+5xNWrsIoMG8o2z+XFKjKaN9iVmS84dPwVN00W4wPmqvYoZF3EGAsfw==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.9.0.tgz", + "integrity": "sha512-lJZPilxX7Op3Nv/2cvFdnlepPXDxi29wxteT57Q965oc5R9v86ztx0jfxVrTcBk8C2kcPkkDa2Z4T3ZsPPVWsQ==", "requires": { + "@babel/helper-validator-identifier": "^7.9.0", "chalk": "^2.0.0", - "esutils": "^2.0.2", "js-tokens": "^4.0.0" } }, "@babel/parser": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.4.3.tgz", - "integrity": "sha512-gxpEUhTS1sGA63EGQGuA+WESPR/6tz6ng7tSHFCmaTJK/cGK8y37cBTspX+U2xCAue2IQVvF6Z0oigmjwD8YGQ==" + "version": "7.9.4", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.9.4.tgz", + "integrity": "sha512-bC49otXX6N0/VYhgOMh4gnP26E9xnDZK3TmbNpxYzzz9BQLBosQwfyOe9/cXUU3txYhTzLCbcqd5c8y/OmCjHA==" }, "@babel/plugin-proposal-async-generator-functions": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.2.0.tgz", - "integrity": "sha512-+Dfo/SCQqrwx48ptLVGLdE39YtWRuKc/Y9I5Fy0P1DDBB9lsAHpjcEJQt+4IifuSOSTLBKJObJqMvaO1pIE8LQ==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.8.3.tgz", + "integrity": "sha512-NZ9zLv848JsV3hs8ryEh7Uaz/0KsmPLqv0+PdkDJL1cJy0K4kOCFa8zc1E3mp+RHPQcpdfb/6GovEsW4VDrOMw==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/helper-remap-async-to-generator": "^7.1.0", - "@babel/plugin-syntax-async-generators": "^7.2.0" + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/helper-remap-async-to-generator": "^7.8.3", + "@babel/plugin-syntax-async-generators": "^7.8.0" + } + }, + "@babel/plugin-proposal-dynamic-import": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-dynamic-import/-/plugin-proposal-dynamic-import-7.8.3.tgz", + "integrity": "sha512-NyaBbyLFXFLT9FP+zk0kYlUlA8XtCUbehs67F0nnEg7KICgMc2mNkIeu9TYhKzyXMkrapZFwAhXLdnt4IYHy1w==", + "requires": { + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/plugin-syntax-dynamic-import": "^7.8.0" } }, "@babel/plugin-proposal-json-strings": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-json-strings/-/plugin-proposal-json-strings-7.2.0.tgz", - "integrity": "sha512-MAFV1CA/YVmYwZG0fBQyXhmj0BHCB5egZHCKWIFVv/XCxAeVGIHfos3SwDck4LvCllENIAg7xMKOG5kH0dzyUg==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-json-strings/-/plugin-proposal-json-strings-7.8.3.tgz", + "integrity": "sha512-KGhQNZ3TVCQG/MjRbAUwuH+14y9q0tpxs1nWWs3pbSleRdDro9SAMMDyye8HhY1gqZ7/NqIc8SKhya0wRDgP1Q==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/plugin-syntax-json-strings": "^7.2.0" + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/plugin-syntax-json-strings": "^7.8.0" + } + }, + "@babel/plugin-proposal-nullish-coalescing-operator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-nullish-coalescing-operator/-/plugin-proposal-nullish-coalescing-operator-7.8.3.tgz", + "integrity": "sha512-TS9MlfzXpXKt6YYomudb/KU7nQI6/xnapG6in1uZxoxDghuSMZsPb6D2fyUwNYSAp4l1iR7QtFOjkqcRYcUsfw==", + "requires": { + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.0" + } + }, + "@babel/plugin-proposal-numeric-separator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-numeric-separator/-/plugin-proposal-numeric-separator-7.8.3.tgz", + "integrity": "sha512-jWioO1s6R/R+wEHizfaScNsAx+xKgwTLNXSh7tTC4Usj3ItsPEhYkEpU4h+lpnBwq7NBVOJXfO6cRFYcX69JUQ==", + "requires": { + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.8.3" } }, "@babel/plugin-proposal-object-rest-spread": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.4.3.tgz", - "integrity": "sha512-xC//6DNSSHVjq8O2ge0dyYlhshsH4T7XdCVoxbi5HzLYWfsC5ooFlJjrXk8RcAT+hjHAK9UjBXdylzSoDK3t4g==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.9.0.tgz", + "integrity": "sha512-UgqBv6bjq4fDb8uku9f+wcm1J7YxJ5nT7WO/jBr0cl0PLKb7t1O6RNR1kZbjgx2LQtsDI9hwoQVmn0yhXeQyow==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/plugin-syntax-object-rest-spread": "^7.2.0" + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/plugin-syntax-object-rest-spread": "^7.8.0" } }, "@babel/plugin-proposal-optional-catch-binding": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-optional-catch-binding/-/plugin-proposal-optional-catch-binding-7.2.0.tgz", - "integrity": "sha512-mgYj3jCcxug6KUcX4OBoOJz3CMrwRfQELPQ5560F70YQUBZB7uac9fqaWamKR1iWUzGiK2t0ygzjTScZnVz75g==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-optional-catch-binding/-/plugin-proposal-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-0gkX7J7E+AtAw9fcwlVQj8peP61qhdg/89D5swOkjYbkboA2CVckn3kiyum1DE0wskGb7KJJxBdyEBApDLLVdw==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/plugin-syntax-optional-catch-binding": "^7.2.0" + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.0" + } + }, + "@babel/plugin-proposal-optional-chaining": { + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-optional-chaining/-/plugin-proposal-optional-chaining-7.9.0.tgz", + "integrity": "sha512-NDn5tu3tcv4W30jNhmc2hyD5c56G6cXx4TesJubhxrJeCvuuMpttxr0OnNCqbZGhFjLrg+NIhxxC+BK5F6yS3w==", + "requires": { + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.0" } }, "@babel/plugin-proposal-unicode-property-regex": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-unicode-property-regex/-/plugin-proposal-unicode-property-regex-7.4.0.tgz", - "integrity": "sha512-h/KjEZ3nK9wv1P1FSNb9G079jXrNYR0Ko+7XkOx85+gM24iZbPn0rh4vCftk+5QKY7y1uByFataBTmX7irEF1w==", + "version": "7.8.8", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-unicode-property-regex/-/plugin-proposal-unicode-property-regex-7.8.8.tgz", + "integrity": "sha512-EVhjVsMpbhLw9ZfHWSx2iy13Q8Z/eg8e8ccVWt23sWQK5l1UdkoLJPN5w69UA4uITGBnEZD2JOe4QOHycYKv8A==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/helper-regex": "^7.0.0", - "regexpu-core": "^4.5.4" + "@babel/helper-create-regexp-features-plugin": "^7.8.8", + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-syntax-async-generators": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.2.0.tgz", - "integrity": "sha512-1ZrIRBv2t0GSlcwVoQ6VgSLpLgiN/FVQUzt9znxo7v2Ov4jJrs8RY8tv0wvDmFN3qIdMKWrmMMW6yZ0G19MfGg==", + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", + "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-dynamic-import": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.8.3.tgz", + "integrity": "sha512-5gdGbFon+PszYzqs83S3E5mpi7/y/8M9eC90MRTZfduQOYW76ig6SOSPNe41IG5LoP3FGBn2N0RjVDSQiS94kQ==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.0" } }, "@babel/plugin-syntax-json-strings": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.2.0.tgz", - "integrity": "sha512-5UGYnMSLRE1dqqZwug+1LISpA403HzlSfsg6P9VXU6TBjcSHeNlw4DxDx7LgpF+iKZoOG/+uzqoRHTdcUpiZNg==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", + "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-nullish-coalescing-operator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", + "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-numeric-separator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.8.3.tgz", + "integrity": "sha512-H7dCMAdN83PcCmqmkHB5dtp+Xa9a6LKSvA2hiFBC/5alSHxM5VgWZXFqDi0YFe8XNGT6iCa+z4V4zSt/PdZ7Dw==", + "requires": { + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-syntax-object-rest-spread": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.2.0.tgz", - "integrity": "sha512-t0JKGgqk2We+9may3t0xDdmneaXmyxq0xieYcKHxIsrJO64n1OiMWNUtc5gQK1PA0NpdCRrtZp4z+IUaKugrSA==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", + "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.0" } }, "@babel/plugin-syntax-optional-catch-binding": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.2.0.tgz", - "integrity": "sha512-bDe4xKNhb0LI7IvZHiA13kff0KEfaGX/Hv4lMA9+7TEc63hMNvfKo6ZFpXhKuEp+II/q35Gc4NoMeDZyaUbj9w==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-optional-chaining": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", + "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-top-level-await": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.8.3.tgz", + "integrity": "sha512-kwj1j9lL/6Wd0hROD3b/OZZ7MSrZLqqn9RAZ5+cYYsflQ9HZBIKCUkr3+uL1MEJ1NePiUbf98jjiMQSv0NMR9g==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-arrow-functions": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.2.0.tgz", - "integrity": "sha512-ER77Cax1+8/8jCB9fo4Ud161OZzWN5qawi4GusDuRLcDbDG+bIGYY20zb2dfAFdTRGzrfq2xZPvF0R64EHnimg==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.8.3.tgz", + "integrity": "sha512-0MRF+KC8EqH4dbuITCWwPSzsyO3HIWWlm30v8BbbpOrS1B++isGxPnnuq/IZvOX5J2D/p7DQalQm+/2PnlKGxg==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-async-to-generator": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.4.0.tgz", - "integrity": "sha512-EeaFdCeUULM+GPFEsf7pFcNSxM7hYjoj5fiYbyuiXobW4JhFnjAv9OWzNwHyHcKoPNpAfeRDuW6VyaXEDUBa7g==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.8.3.tgz", + "integrity": "sha512-imt9tFLD9ogt56Dd5CI/6XgpukMwd/fLGSrix2httihVe7LOGVPhyhMh1BU5kDM7iHD08i8uUtmV2sWaBFlHVQ==", "requires": { - "@babel/helper-module-imports": "^7.0.0", - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/helper-remap-async-to-generator": "^7.1.0" + "@babel/helper-module-imports": "^7.8.3", + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/helper-remap-async-to-generator": "^7.8.3" } }, "@babel/plugin-transform-block-scoped-functions": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.2.0.tgz", - "integrity": "sha512-ntQPR6q1/NKuphly49+QiQiTN0O63uOwjdD6dhIjSWBI5xlrbUFh720TIpzBhpnrLfv2tNH/BXvLIab1+BAI0w==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.8.3.tgz", + "integrity": "sha512-vo4F2OewqjbB1+yaJ7k2EJFHlTP3jR634Z9Cj9itpqNjuLXvhlVxgnjsHsdRgASR8xYDrx6onw4vW5H6We0Jmg==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-block-scoping": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.4.0.tgz", - "integrity": "sha512-AWyt3k+fBXQqt2qb9r97tn3iBwFpiv9xdAiG+Gr2HpAZpuayvbL55yWrsV3MyHvXk/4vmSiedhDRl1YI2Iy5nQ==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.8.3.tgz", + "integrity": "sha512-pGnYfm7RNRgYRi7bids5bHluENHqJhrV4bCZRwc5GamaWIIs07N4rZECcmJL6ZClwjDz1GbdMZFtPs27hTB06w==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0", - "lodash": "^4.17.11" + "@babel/helper-plugin-utils": "^7.8.3", + "lodash": "^4.17.13" } }, "@babel/plugin-transform-classes": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.4.3.tgz", - "integrity": "sha512-PUaIKyFUDtG6jF5DUJOfkBdwAS/kFFV3XFk7Nn0a6vR7ZT8jYw5cGtIlat77wcnd0C6ViGqo/wyNf4ZHytF/nQ==", - "requires": { - "@babel/helper-annotate-as-pure": "^7.0.0", - "@babel/helper-define-map": "^7.4.0", - "@babel/helper-function-name": "^7.1.0", - "@babel/helper-optimise-call-expression": "^7.0.0", - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/helper-replace-supers": "^7.4.0", - "@babel/helper-split-export-declaration": "^7.4.0", + "version": "7.9.2", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.9.2.tgz", + "integrity": "sha512-TC2p3bPzsfvSsqBZo0kJnuelnoK9O3welkUpqSqBQuBF6R5MN2rysopri8kNvtlGIb2jmUO7i15IooAZJjZuMQ==", + "requires": { + "@babel/helper-annotate-as-pure": "^7.8.3", + "@babel/helper-define-map": "^7.8.3", + "@babel/helper-function-name": "^7.8.3", + "@babel/helper-optimise-call-expression": "^7.8.3", + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/helper-replace-supers": "^7.8.6", + "@babel/helper-split-export-declaration": "^7.8.3", "globals": "^11.1.0" } }, "@babel/plugin-transform-computed-properties": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.2.0.tgz", - "integrity": "sha512-kP/drqTxY6Xt3NNpKiMomfgkNn4o7+vKxK2DDKcBG9sHj51vHqMBGy8wbDS/J4lMxnqs153/T3+DmCEAkC5cpA==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.8.3.tgz", + "integrity": "sha512-O5hiIpSyOGdrQZRQ2ccwtTVkgUDBBiCuK//4RJ6UfePllUTCENOzKxfh6ulckXKc0DixTFLCfb2HVkNA7aDpzA==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-destructuring": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.4.3.tgz", - "integrity": "sha512-rVTLLZpydDFDyN4qnXdzwoVpk1oaXHIvPEOkOLyr88o7oHxVc/LyrnDx+amuBWGOwUb7D1s/uLsKBNTx08htZg==", + "version": "7.8.8", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.8.8.tgz", + "integrity": "sha512-eRJu4Vs2rmttFCdhPUM3bV0Yo/xPSdPw6ML9KHs/bjB4bLA5HXlbvYXPOD5yASodGod+krjYx21xm1QmL8dCJQ==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-dotall-regex": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.4.3.tgz", - "integrity": "sha512-9Arc2I0AGynzXRR/oPdSALv3k0rM38IMFyto7kOCwb5F9sLUt2Ykdo3V9yUPR+Bgr4kb6bVEyLkPEiBhzcTeoA==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.8.3.tgz", + "integrity": "sha512-kLs1j9Nn4MQoBYdRXH6AeaXMbEJFaFu/v1nQkvib6QzTj8MZI5OQzqmD83/2jEM1z0DLilra5aWO5YpyC0ALIw==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/helper-regex": "^7.4.3", - "regexpu-core": "^4.5.4" + "@babel/helper-create-regexp-features-plugin": "^7.8.3", + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-duplicate-keys": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-7.2.0.tgz", - "integrity": "sha512-q+yuxW4DsTjNceUiTzK0L+AfQ0zD9rWaTLiUqHA8p0gxx7lu1EylenfzjeIWNkPy6e/0VG/Wjw9uf9LueQwLOw==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-7.8.3.tgz", + "integrity": "sha512-s8dHiBUbcbSgipS4SMFuWGqCvyge5V2ZeAWzR6INTVC3Ltjig/Vw1G2Gztv0vU/hRG9X8IvKvYdoksnUfgXOEQ==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-exponentiation-operator": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.2.0.tgz", - "integrity": "sha512-umh4hR6N7mu4Elq9GG8TOu9M0bakvlsREEC+ialrQN6ABS4oDQ69qJv1VtR3uxlKMCQMCvzk7vr17RHKcjx68A==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.8.3.tgz", + "integrity": "sha512-zwIpuIymb3ACcInbksHaNcR12S++0MDLKkiqXHl3AzpgdKlFNhog+z/K0+TGW+b0w5pgTq4H6IwV/WhxbGYSjQ==", "requires": { - "@babel/helper-builder-binary-assignment-operator-visitor": "^7.1.0", - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-builder-binary-assignment-operator-visitor": "^7.8.3", + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-for-of": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.4.3.tgz", - "integrity": "sha512-UselcZPwVWNSURnqcfpnxtMehrb8wjXYOimlYQPBnup/Zld426YzIhNEvuRsEWVHfESIECGrxoI6L5QqzuLH5Q==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.9.0.tgz", + "integrity": "sha512-lTAnWOpMwOXpyDx06N+ywmF3jNbafZEqZ96CGYabxHrxNX8l5ny7dt4bK/rGwAh9utyP2b2Hv7PlZh1AAS54FQ==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-function-name": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-function-name/-/plugin-transform-function-name-7.4.3.tgz", - "integrity": "sha512-uT5J/3qI/8vACBR9I1GlAuU/JqBtWdfCrynuOkrWG6nCDieZd5przB1vfP59FRHBZQ9DC2IUfqr/xKqzOD5x0A==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-function-name/-/plugin-transform-function-name-7.8.3.tgz", + "integrity": "sha512-rO/OnDS78Eifbjn5Py9v8y0aR+aSYhDhqAwVfsTl0ERuMZyr05L1aFSCJnbv2mmsLkit/4ReeQ9N2BgLnOcPCQ==", "requires": { - "@babel/helper-function-name": "^7.1.0", - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-function-name": "^7.8.3", + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-literals": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-7.2.0.tgz", - "integrity": "sha512-2ThDhm4lI4oV7fVQ6pNNK+sx+c/GM5/SaML0w/r4ZB7sAneD/piDJtwdKlNckXeyGK7wlwg2E2w33C/Hh+VFCg==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-7.8.3.tgz", + "integrity": "sha512-3Tqf8JJ/qB7TeldGl+TT55+uQei9JfYaregDcEAyBZ7akutriFrt6C/wLYIer6OYhleVQvH/ntEhjE/xMmy10A==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-member-expression-literals": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-7.2.0.tgz", - "integrity": "sha512-HiU3zKkSU6scTidmnFJ0bMX8hz5ixC93b4MHMiYebmk2lUVNGOboPsqQvx5LzooihijUoLR/v7Nc1rbBtnc7FA==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-7.8.3.tgz", + "integrity": "sha512-3Wk2EXhnw+rP+IDkK6BdtPKsUE5IeZ6QOGrPYvw52NwBStw9V1ZVzxgK6fSKSxqUvH9eQPR3tm3cOq79HlsKYA==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-modules-amd": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-7.2.0.tgz", - "integrity": "sha512-mK2A8ucqz1qhrdqjS9VMIDfIvvT2thrEsIQzbaTdc5QFzhDjQv2CkJJ5f6BXIkgbmaoax3zBr2RyvV/8zeoUZw==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-7.9.0.tgz", + "integrity": "sha512-vZgDDF003B14O8zJy0XXLnPH4sg+9X5hFBBGN1V+B2rgrB+J2xIypSN6Rk9imB2hSTHQi5OHLrFWsZab1GMk+Q==", "requires": { - "@babel/helper-module-transforms": "^7.1.0", - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-module-transforms": "^7.9.0", + "@babel/helper-plugin-utils": "^7.8.3", + "babel-plugin-dynamic-import-node": "^2.3.0" } }, "@babel/plugin-transform-modules-commonjs": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.4.3.tgz", - "integrity": "sha512-sMP4JqOTbMJMimqsSZwYWsMjppD+KRyDIUVW91pd7td0dZKAvPmhCaxhOzkzLParKwgQc7bdL9UNv+rpJB0HfA==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.9.0.tgz", + "integrity": "sha512-qzlCrLnKqio4SlgJ6FMMLBe4bySNis8DFn1VkGmOcxG9gqEyPIOzeQrA//u0HAKrWpJlpZbZMPB1n/OPa4+n8g==", "requires": { - "@babel/helper-module-transforms": "^7.4.3", - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/helper-simple-access": "^7.1.0" + "@babel/helper-module-transforms": "^7.9.0", + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/helper-simple-access": "^7.8.3", + "babel-plugin-dynamic-import-node": "^2.3.0" } }, "@babel/plugin-transform-modules-systemjs": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.4.0.tgz", - "integrity": "sha512-gjPdHmqiNhVoBqus5qK60mWPp1CmYWp/tkh11mvb0rrys01HycEGD7NvvSoKXlWEfSM9TcL36CpsK8ElsADptQ==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.9.0.tgz", + "integrity": "sha512-FsiAv/nao/ud2ZWy4wFacoLOm5uxl0ExSQ7ErvP7jpoihLR6Cq90ilOFyX9UXct3rbtKsAiZ9kFt5XGfPe/5SQ==", "requires": { - "@babel/helper-hoist-variables": "^7.4.0", - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-hoist-variables": "^7.8.3", + "@babel/helper-module-transforms": "^7.9.0", + "@babel/helper-plugin-utils": "^7.8.3", + "babel-plugin-dynamic-import-node": "^2.3.0" } }, "@babel/plugin-transform-modules-umd": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-7.2.0.tgz", - "integrity": "sha512-BV3bw6MyUH1iIsGhXlOK6sXhmSarZjtJ/vMiD9dNmpY8QXFFQTj+6v92pcfy1iqa8DeAfJFwoxcrS/TUZda6sw==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-7.9.0.tgz", + "integrity": "sha512-uTWkXkIVtg/JGRSIABdBoMsoIeoHQHPTL0Y2E7xf5Oj7sLqwVsNXOkNk0VJc7vF0IMBsPeikHxFjGe+qmwPtTQ==", "requires": { - "@babel/helper-module-transforms": "^7.1.0", - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-module-transforms": "^7.9.0", + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-named-capturing-groups-regex": { - "version": "7.4.2", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.4.2.tgz", - "integrity": "sha512-NsAuliSwkL3WO2dzWTOL1oZJHm0TM8ZY8ZSxk2ANyKkt5SQlToGA4pzctmq1BEjoacurdwZ3xp2dCQWJkME0gQ==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.8.3.tgz", + "integrity": "sha512-f+tF/8UVPU86TrCb06JoPWIdDpTNSGGcAtaD9mLP0aYGA0OS0j7j7DHJR0GTFrUZPUU6loZhbsVZgTh0N+Qdnw==", "requires": { - "regexp-tree": "^0.1.0" + "@babel/helper-create-regexp-features-plugin": "^7.8.3" } }, "@babel/plugin-transform-new-target": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-new-target/-/plugin-transform-new-target-7.4.0.tgz", - "integrity": "sha512-6ZKNgMQmQmrEX/ncuCwnnw1yVGoaOW5KpxNhoWI7pCQdA0uZ0HqHGqenCUIENAnxRjy2WwNQ30gfGdIgqJXXqw==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-new-target/-/plugin-transform-new-target-7.8.3.tgz", + "integrity": "sha512-QuSGysibQpyxexRyui2vca+Cmbljo8bcRckgzYV4kRIsHpVeyeC3JDO63pY+xFZ6bWOBn7pfKZTqV4o/ix9sFw==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-object-super": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.2.0.tgz", - "integrity": "sha512-VMyhPYZISFZAqAPVkiYb7dUe2AsVi2/wCT5+wZdsNO31FojQJa9ns40hzZ6U9f50Jlq4w6qwzdBB2uwqZ00ebg==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.8.3.tgz", + "integrity": "sha512-57FXk+gItG/GejofIyLIgBKTas4+pEU47IXKDBWFTxdPd7F80H8zybyAY7UoblVfBhBGs2EKM+bJUu2+iUYPDQ==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/helper-replace-supers": "^7.1.0" + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/helper-replace-supers": "^7.8.3" } }, "@babel/plugin-transform-parameters": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.4.3.tgz", - "integrity": "sha512-ULJYC2Vnw96/zdotCZkMGr2QVfKpIT/4/K+xWWY0MbOJyMZuk660BGkr3bEKWQrrciwz6xpmft39nA4BF7hJuA==", + "version": "7.9.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.9.3.tgz", + "integrity": "sha512-fzrQFQhp7mIhOzmOtPiKffvCYQSK10NR8t6BBz2yPbeUHb9OLW8RZGtgDRBn8z2hGcwvKDL3vC7ojPTLNxmqEg==", "requires": { - "@babel/helper-call-delegate": "^7.4.0", - "@babel/helper-get-function-arity": "^7.0.0", - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-get-function-arity": "^7.8.3", + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-property-literals": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.2.0.tgz", - "integrity": "sha512-9q7Dbk4RhgcLp8ebduOpCbtjh7C0itoLYHXd9ueASKAG/is5PQtMR5VJGka9NKqGhYEGn5ITahd4h9QeBMylWQ==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.8.3.tgz", + "integrity": "sha512-uGiiXAZMqEoQhRWMK17VospMZh5sXWg+dlh2soffpkAl96KAm+WZuJfa6lcELotSRmooLqg0MWdH6UUq85nmmg==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-regenerator": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.4.3.tgz", - "integrity": "sha512-kEzotPuOpv6/iSlHroCDydPkKYw7tiJGKlmYp6iJn4a6C/+b2FdttlJsLKYxolYHgotTJ5G5UY5h0qey5ka3+A==", + "version": "7.8.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.8.7.tgz", + "integrity": "sha512-TIg+gAl4Z0a3WmD3mbYSk+J9ZUH6n/Yc57rtKRnlA/7rcCvpekHXe0CMZHP1gYp7/KLe9GHTuIba0vXmls6drA==", "requires": { - "regenerator-transform": "^0.13.4" + "regenerator-transform": "^0.14.2" } }, "@babel/plugin-transform-reserved-words": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-7.2.0.tgz", - "integrity": "sha512-fz43fqW8E1tAB3DKF19/vxbpib1fuyCwSPE418ge5ZxILnBhWyhtPgz8eh1RCGGJlwvksHkyxMxh0eenFi+kFw==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-7.8.3.tgz", + "integrity": "sha512-mwMxcycN3omKFDjDQUl+8zyMsBfjRFr0Zn/64I41pmjv4NJuqcYlEtezwYtw9TFd9WR1vN5kiM+O0gMZzO6L0A==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-shorthand-properties": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.2.0.tgz", - "integrity": "sha512-QP4eUM83ha9zmYtpbnyjTLAGKQritA5XW/iG9cjtuOI8s1RuL/3V6a3DeSHfKutJQ+ayUfeZJPcnCYEQzaPQqg==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.8.3.tgz", + "integrity": "sha512-I9DI6Odg0JJwxCHzbzW08ggMdCezoWcuQRz3ptdudgwaHxTjxw5HgdFJmZIkIMlRymL6YiZcped4TTCB0JcC8w==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-spread": { - "version": "7.2.2", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.2.2.tgz", - "integrity": "sha512-KWfky/58vubwtS0hLqEnrWJjsMGaOeSBn90Ezn5Jeg9Z8KKHmELbP1yGylMlm5N6TPKeY9A2+UaSYLdxahg01w==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.8.3.tgz", + "integrity": "sha512-CkuTU9mbmAoFOI1tklFWYYbzX5qCIZVXPVy0jpXgGwkplCndQAa58s2jr66fTeQnA64bDox0HL4U56CFYoyC7g==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-sticky-regex": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.2.0.tgz", - "integrity": "sha512-KKYCoGaRAf+ckH8gEL3JHUaFVyNHKe3ASNsZ+AlktgHevvxGigoIttrEJb8iKN03Q7Eazlv1s6cx2B2cQ3Jabw==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.8.3.tgz", + "integrity": "sha512-9Spq0vGCD5Bb4Z/ZXXSK5wbbLFMG085qd2vhL1JYu1WcQ5bXqZBAYRzU1d+p79GcHs2szYv5pVQCX13QgldaWw==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/helper-regex": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/helper-regex": "^7.8.3" } }, "@babel/plugin-transform-template-literals": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.2.0.tgz", - "integrity": "sha512-FkPix00J9A/XWXv4VoKJBMeSkyY9x/TqIh76wzcdfl57RJJcf8CehQ08uwfhCDNtRQYtHQKBTwKZDEyjE13Lwg==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.8.3.tgz", + "integrity": "sha512-820QBtykIQOLFT8NZOcTRJ1UNuztIELe4p9DCgvj4NK+PwluSJ49we7s9FB1HIGNIYT7wFUJ0ar2QpCDj0escQ==", "requires": { - "@babel/helper-annotate-as-pure": "^7.0.0", - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-annotate-as-pure": "^7.8.3", + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-typeof-symbol": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.2.0.tgz", - "integrity": "sha512-2LNhETWYxiYysBtrBTqL8+La0jIoQQnIScUJc74OYvUGRmkskNY4EzLCnjHBzdmb38wqtTaixpo1NctEcvMDZw==", + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.8.4.tgz", + "integrity": "sha512-2QKyfjGdvuNfHsb7qnBBlKclbD4CfshH2KvDabiijLMGXPHJXGxtDzwIF7bQP+T0ysw8fYTtxPafgfs/c1Lrqg==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0" + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/plugin-transform-unicode-regex": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.4.3.tgz", - "integrity": "sha512-lnSNgkVjL8EMtnE8eSS7t2ku8qvKH3eqNf/IwIfnSPUqzgqYmRwzdsQWv4mNQAN9Nuo6Gz1Y0a4CSmdpu1Pp6g==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.8.3.tgz", + "integrity": "sha512-+ufgJjYdmWfSQ+6NS9VGUR2ns8cjJjYbrbi11mZBTaWm+Fui/ncTLFF28Ei1okavY+xkojGr1eJxNsWYeA5aZw==", "requires": { - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/helper-regex": "^7.4.3", - "regexpu-core": "^4.5.4" + "@babel/helper-create-regexp-features-plugin": "^7.8.3", + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/preset-env": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.4.3.tgz", - "integrity": "sha512-FYbZdV12yHdJU5Z70cEg0f6lvtpZ8jFSDakTm7WXeJbLXh4R0ztGEu/SW7G1nJ2ZvKwDhz8YrbA84eYyprmGqw==", - "requires": { - "@babel/helper-module-imports": "^7.0.0", - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/plugin-proposal-async-generator-functions": "^7.2.0", - "@babel/plugin-proposal-json-strings": "^7.2.0", - "@babel/plugin-proposal-object-rest-spread": "^7.4.3", - "@babel/plugin-proposal-optional-catch-binding": "^7.2.0", - "@babel/plugin-proposal-unicode-property-regex": "^7.4.0", - "@babel/plugin-syntax-async-generators": "^7.2.0", - "@babel/plugin-syntax-json-strings": "^7.2.0", - "@babel/plugin-syntax-object-rest-spread": "^7.2.0", - "@babel/plugin-syntax-optional-catch-binding": "^7.2.0", - "@babel/plugin-transform-arrow-functions": "^7.2.0", - "@babel/plugin-transform-async-to-generator": "^7.4.0", - "@babel/plugin-transform-block-scoped-functions": "^7.2.0", - "@babel/plugin-transform-block-scoping": "^7.4.0", - "@babel/plugin-transform-classes": "^7.4.3", - "@babel/plugin-transform-computed-properties": "^7.2.0", - "@babel/plugin-transform-destructuring": "^7.4.3", - "@babel/plugin-transform-dotall-regex": "^7.4.3", - "@babel/plugin-transform-duplicate-keys": "^7.2.0", - "@babel/plugin-transform-exponentiation-operator": "^7.2.0", - "@babel/plugin-transform-for-of": "^7.4.3", - "@babel/plugin-transform-function-name": "^7.4.3", - "@babel/plugin-transform-literals": "^7.2.0", - "@babel/plugin-transform-member-expression-literals": "^7.2.0", - "@babel/plugin-transform-modules-amd": "^7.2.0", - "@babel/plugin-transform-modules-commonjs": "^7.4.3", - "@babel/plugin-transform-modules-systemjs": "^7.4.0", - "@babel/plugin-transform-modules-umd": "^7.2.0", - "@babel/plugin-transform-named-capturing-groups-regex": "^7.4.2", - "@babel/plugin-transform-new-target": "^7.4.0", - "@babel/plugin-transform-object-super": "^7.2.0", - "@babel/plugin-transform-parameters": "^7.4.3", - "@babel/plugin-transform-property-literals": "^7.2.0", - "@babel/plugin-transform-regenerator": "^7.4.3", - "@babel/plugin-transform-reserved-words": "^7.2.0", - "@babel/plugin-transform-shorthand-properties": "^7.2.0", - "@babel/plugin-transform-spread": "^7.2.0", - "@babel/plugin-transform-sticky-regex": "^7.2.0", - "@babel/plugin-transform-template-literals": "^7.2.0", - "@babel/plugin-transform-typeof-symbol": "^7.2.0", - "@babel/plugin-transform-unicode-regex": "^7.4.3", - "@babel/types": "^7.4.0", - "browserslist": "^4.5.2", - "core-js-compat": "^3.0.0", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.9.0.tgz", + "integrity": "sha512-712DeRXT6dyKAM/FMbQTV/FvRCms2hPCx+3weRjZ8iQVQWZejWWk1wwG6ViWMyqb/ouBbGOl5b6aCk0+j1NmsQ==", + "requires": { + "@babel/compat-data": "^7.9.0", + "@babel/helper-compilation-targets": "^7.8.7", + "@babel/helper-module-imports": "^7.8.3", + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/plugin-proposal-async-generator-functions": "^7.8.3", + "@babel/plugin-proposal-dynamic-import": "^7.8.3", + "@babel/plugin-proposal-json-strings": "^7.8.3", + "@babel/plugin-proposal-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-proposal-numeric-separator": "^7.8.3", + "@babel/plugin-proposal-object-rest-spread": "^7.9.0", + "@babel/plugin-proposal-optional-catch-binding": "^7.8.3", + "@babel/plugin-proposal-optional-chaining": "^7.9.0", + "@babel/plugin-proposal-unicode-property-regex": "^7.8.3", + "@babel/plugin-syntax-async-generators": "^7.8.0", + "@babel/plugin-syntax-dynamic-import": "^7.8.0", + "@babel/plugin-syntax-json-strings": "^7.8.0", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.0", + "@babel/plugin-syntax-numeric-separator": "^7.8.0", + "@babel/plugin-syntax-object-rest-spread": "^7.8.0", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.0", + "@babel/plugin-syntax-optional-chaining": "^7.8.0", + "@babel/plugin-syntax-top-level-await": "^7.8.3", + "@babel/plugin-transform-arrow-functions": "^7.8.3", + "@babel/plugin-transform-async-to-generator": "^7.8.3", + "@babel/plugin-transform-block-scoped-functions": "^7.8.3", + "@babel/plugin-transform-block-scoping": "^7.8.3", + "@babel/plugin-transform-classes": "^7.9.0", + "@babel/plugin-transform-computed-properties": "^7.8.3", + "@babel/plugin-transform-destructuring": "^7.8.3", + "@babel/plugin-transform-dotall-regex": "^7.8.3", + "@babel/plugin-transform-duplicate-keys": "^7.8.3", + "@babel/plugin-transform-exponentiation-operator": "^7.8.3", + "@babel/plugin-transform-for-of": "^7.9.0", + "@babel/plugin-transform-function-name": "^7.8.3", + "@babel/plugin-transform-literals": "^7.8.3", + "@babel/plugin-transform-member-expression-literals": "^7.8.3", + "@babel/plugin-transform-modules-amd": "^7.9.0", + "@babel/plugin-transform-modules-commonjs": "^7.9.0", + "@babel/plugin-transform-modules-systemjs": "^7.9.0", + "@babel/plugin-transform-modules-umd": "^7.9.0", + "@babel/plugin-transform-named-capturing-groups-regex": "^7.8.3", + "@babel/plugin-transform-new-target": "^7.8.3", + "@babel/plugin-transform-object-super": "^7.8.3", + "@babel/plugin-transform-parameters": "^7.8.7", + "@babel/plugin-transform-property-literals": "^7.8.3", + "@babel/plugin-transform-regenerator": "^7.8.7", + "@babel/plugin-transform-reserved-words": "^7.8.3", + "@babel/plugin-transform-shorthand-properties": "^7.8.3", + "@babel/plugin-transform-spread": "^7.8.3", + "@babel/plugin-transform-sticky-regex": "^7.8.3", + "@babel/plugin-transform-template-literals": "^7.8.3", + "@babel/plugin-transform-typeof-symbol": "^7.8.4", + "@babel/plugin-transform-unicode-regex": "^7.8.3", + "@babel/preset-modules": "^0.1.3", + "@babel/types": "^7.9.0", + "browserslist": "^4.9.1", + "core-js-compat": "^3.6.2", "invariant": "^2.2.2", - "js-levenshtein": "^1.1.3", + "levenary": "^1.1.1", "semver": "^5.5.0" } }, + "@babel/preset-modules": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@babel/preset-modules/-/preset-modules-0.1.3.tgz", + "integrity": "sha512-Ra3JXOHBq2xd56xSF7lMKXdjBn3T772Y1Wet3yWnkDly9zHvJki029tAFzvAAK5cf4YV3yoxuP61crYRol6SVg==", + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/plugin-proposal-unicode-property-regex": "^7.4.4", + "@babel/plugin-transform-dotall-regex": "^7.4.4", + "@babel/types": "^7.4.4", + "esutils": "^2.0.2" + } + }, "@babel/register": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/@babel/register/-/register-7.4.0.tgz", - "integrity": "sha512-ekziebXBnS/7V6xk8sBfLSSD6YZuy6P29igBtR6OL/tswKdxOV+Yqq0nzICMguVYtGRZYUCGpfGV8J9Za2iBdw==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/register/-/register-7.9.0.tgz", + "integrity": "sha512-Tv8Zyi2J2VRR8g7pC5gTeIN8Ihultbmk0ocyNz8H2nEZbmhp1N6q0A1UGsQbDvGP/sNinQKUHf3SqXwqjtFv4Q==", "requires": { - "core-js": "^3.0.0", "find-cache-dir": "^2.0.0", - "lodash": "^4.17.11", - "mkdirp": "^0.5.1", + "lodash": "^4.17.13", + "make-dir": "^2.1.0", "pirates": "^4.0.0", - "source-map-support": "^0.5.9" + "source-map-support": "^0.5.16" + } + }, + "@babel/runtime": { + "version": "7.9.2", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.9.2.tgz", + "integrity": "sha512-NE2DtOdufG7R5vnfQUTehdTfNycfUANEtCa9PssN9O/xmTzP4E08UI797ixaei6hBEVL9BI/PsdJS5x7mWoB9Q==", + "requires": { + "regenerator-runtime": "^0.13.4" } }, "@babel/template": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.4.0.tgz", - "integrity": "sha512-SOWwxxClTTh5NdbbYZ0BmaBVzxzTh2tO/TeLTbF6MO6EzVhHTnff8CdBXx3mEtazFBoysmEM6GU/wF+SuSx4Fw==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.8.6.tgz", + "integrity": "sha512-zbMsPMy/v0PWFZEhQJ66bqjhH+z0JgMoBWuikXybgG3Gkd/3t5oQ1Rw2WQhnSrsOmsKXnZOx15tkC4qON/+JPg==", "requires": { - "@babel/code-frame": "^7.0.0", - "@babel/parser": "^7.4.0", - "@babel/types": "^7.4.0" + "@babel/code-frame": "^7.8.3", + "@babel/parser": "^7.8.6", + "@babel/types": "^7.8.6" } }, "@babel/traverse": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.4.3.tgz", - "integrity": "sha512-HmA01qrtaCwwJWpSKpA948cBvU5BrmviAief/b3AVw936DtcdsTexlbyzNuDnthwhOQ37xshn7hvQaEQk7ISYQ==", - "requires": { - "@babel/code-frame": "^7.0.0", - "@babel/generator": "^7.4.0", - "@babel/helper-function-name": "^7.1.0", - "@babel/helper-split-export-declaration": "^7.4.0", - "@babel/parser": "^7.4.3", - "@babel/types": "^7.4.0", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.9.0.tgz", + "integrity": "sha512-jAZQj0+kn4WTHO5dUZkZKhbFrqZE7K5LAQ5JysMnmvGij+wOdr+8lWqPeW0BcF4wFwrEXXtdGO7wcV6YPJcf3w==", + "requires": { + "@babel/code-frame": "^7.8.3", + "@babel/generator": "^7.9.0", + "@babel/helper-function-name": "^7.8.3", + "@babel/helper-split-export-declaration": "^7.8.3", + "@babel/parser": "^7.9.0", + "@babel/types": "^7.9.0", "debug": "^4.1.0", "globals": "^11.1.0", - "lodash": "^4.17.11" + "lodash": "^4.17.13" }, "dependencies": { "debug": { @@ -767,190 +864,268 @@ } }, "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" } } }, "@babel/types": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.4.0.tgz", - "integrity": "sha512-aPvkXyU2SPOnztlgo8n9cEiXW755mgyvueUPcpStqdzoSPm0fjO0vQBjLkt3JKJW7ufikfcnMTTPsN1xaTsBPA==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.9.0.tgz", + "integrity": "sha512-BS9JKfXkzzJl8RluW4JGknzpiUV7ZrvTayM6yfqLTVBEnFtyowVIOu6rqxRd5cVO6yGoWf4T8u8dgK9oB+GCng==", "requires": { - "esutils": "^2.0.2", - "lodash": "^4.17.11", + "@babel/helper-validator-identifier": "^7.9.0", + "lodash": "^4.17.13", "to-fast-properties": "^2.0.0" } }, - "@concordance/react": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@concordance/react/-/react-2.0.0.tgz", - "integrity": "sha512-huLSkUuM2/P+U0uy2WwlKuixMsTODD8p4JVQBI4VKeopkiN0C7M3N9XYVawb4M+4spN5RrO/eLhk7KoQX6nsfA==", - "requires": { - "arrify": "^1.0.1" + "@istanbuljs/load-nyc-config": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.0.0.tgz", + "integrity": "sha512-ZR0rq/f/E4f4XcgnDvtMWXCUJpi8eO0rssVhmztsZqLIEFA9UUP9zmpE0VxlM+kv/E1ul2I876Fwil2ayptDVg==", + "dev": true, + "requires": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "dependencies": { + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + }, + "resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true + } } }, + "@istanbuljs/schema": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.2.tgz", + "integrity": "sha512-tsAQNx32a8CoFhjhijUIhI4kccIAgmGhy8LZMZgGfmXcpMbPRUqn5LWmgRttILi6yeGmBJd2xsPkFMs0PzgPCw==", + "dev": true + }, + "@matthid/source-map-visualization": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@matthid/source-map-visualization/-/source-map-visualization-0.5.0.tgz", + "integrity": "sha512-k+D8WnqtWOge8X6/4mSKnOicqLNamhcLtTBVCvTOGpnGYzfJ+dgNa1GJeJUjXOLd7Qbr5U9n1gYuYc/fkLckZQ==", + "dev": true + }, + "@types/color-name": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@types/color-name/-/color-name-1.1.1.tgz", + "integrity": "sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ==", + "dev": true + }, "@types/node": { - "version": "11.13.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-11.13.0.tgz", - "integrity": "sha512-rx29MMkRdVmzunmiA4lzBYJNnXsW/PhG4kMBy2ATsYaDjGGR75dCFEVVROKpNwlVdcUX3xxlghKQOeDPBJobng==" + "version": "13.11.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-13.11.1.tgz", + "integrity": "sha512-eWQGP3qtxwL8FGneRrC5DwrJLGN4/dH1clNTuLfN81HCrxVtxRjygDTUoZJ5ASlDEeo0ppYFQjQIlXhtXpOn6g==" }, "@webassemblyjs/ast": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.8.5.tgz", - "integrity": "sha512-aJMfngIZ65+t71C3y2nBBg5FFG0Okt9m0XEgWZ7Ywgn1oMAT8cNwx00Uv1cQyHtidq0Xn94R4TAywO+LCQ+ZAQ==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.9.0.tgz", + "integrity": "sha512-C6wW5L+b7ogSDVqymbkkvuW9kruN//YisMED04xzeBBqjHa2FYnmvOlS6Xj68xWQRgWvI9cIglsjFowH/RJyEA==", "requires": { - "@webassemblyjs/helper-module-context": "1.8.5", - "@webassemblyjs/helper-wasm-bytecode": "1.8.5", - "@webassemblyjs/wast-parser": "1.8.5" + "@webassemblyjs/helper-module-context": "1.9.0", + "@webassemblyjs/helper-wasm-bytecode": "1.9.0", + "@webassemblyjs/wast-parser": "1.9.0" } }, "@webassemblyjs/floating-point-hex-parser": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.8.5.tgz", - "integrity": "sha512-9p+79WHru1oqBh9ewP9zW95E3XAo+90oth7S5Re3eQnECGq59ly1Ri5tsIipKGpiStHsUYmY3zMLqtk3gTcOtQ==" + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.9.0.tgz", + "integrity": "sha512-TG5qcFsS8QB4g4MhrxK5TqfdNe7Ey/7YL/xN+36rRjl/BlGE/NcBvJcqsRgCP6Z92mRE+7N50pRIi8SmKUbcQA==" }, "@webassemblyjs/helper-api-error": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.8.5.tgz", - "integrity": "sha512-Za/tnzsvnqdaSPOUXHyKJ2XI7PDX64kWtURyGiJJZKVEdFOsdKUCPTNEVFZq3zJ2R0G5wc2PZ5gvdTRFgm81zA==" + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.9.0.tgz", + "integrity": "sha512-NcMLjoFMXpsASZFxJ5h2HZRcEhDkvnNFOAKneP5RbKRzaWJN36NC4jqQHKwStIhGXu5mUWlUUk7ygdtrO8lbmw==" }, "@webassemblyjs/helper-buffer": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.8.5.tgz", - "integrity": "sha512-Ri2R8nOS0U6G49Q86goFIPNgjyl6+oE1abW1pS84BuhP1Qcr5JqMwRFT3Ah3ADDDYGEgGs1iyb1DGX+kAi/c/Q==" + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.9.0.tgz", + "integrity": "sha512-qZol43oqhq6yBPx7YM3m9Bv7WMV9Eevj6kMi6InKOuZxhw+q9hOkvq5e/PpKSiLfyetpaBnogSbNCfBwyB00CA==" }, "@webassemblyjs/helper-code-frame": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-code-frame/-/helper-code-frame-1.8.5.tgz", - "integrity": "sha512-VQAadSubZIhNpH46IR3yWO4kZZjMxN1opDrzePLdVKAZ+DFjkGD/rf4v1jap744uPVU6yjL/smZbRIIJTOUnKQ==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-code-frame/-/helper-code-frame-1.9.0.tgz", + "integrity": "sha512-ERCYdJBkD9Vu4vtjUYe8LZruWuNIToYq/ME22igL+2vj2dQ2OOujIZr3MEFvfEaqKoVqpsFKAGsRdBSBjrIvZA==", "requires": { - "@webassemblyjs/wast-printer": "1.8.5" + "@webassemblyjs/wast-printer": "1.9.0" } }, "@webassemblyjs/helper-fsm": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-fsm/-/helper-fsm-1.8.5.tgz", - "integrity": "sha512-kRuX/saORcg8se/ft6Q2UbRpZwP4y7YrWsLXPbbmtepKr22i8Z4O3V5QE9DbZK908dh5Xya4Un57SDIKwB9eow==" + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-fsm/-/helper-fsm-1.9.0.tgz", + "integrity": "sha512-OPRowhGbshCb5PxJ8LocpdX9Kl0uB4XsAjl6jH/dWKlk/mzsANvhwbiULsaiqT5GZGT9qinTICdj6PLuM5gslw==" }, "@webassemblyjs/helper-module-context": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-module-context/-/helper-module-context-1.8.5.tgz", - "integrity": "sha512-/O1B236mN7UNEU4t9X7Pj38i4VoU8CcMHyy3l2cV/kIF4U5KoHXDVqcDuOs1ltkac90IM4vZdHc52t1x8Yfs3g==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-module-context/-/helper-module-context-1.9.0.tgz", + "integrity": "sha512-MJCW8iGC08tMk2enck1aPW+BE5Cw8/7ph/VGZxwyvGbJwjktKkDK7vy7gAmMDx88D7mhDTCNKAW5tED+gZ0W8g==", "requires": { - "@webassemblyjs/ast": "1.8.5", - "mamacro": "^0.0.3" + "@webassemblyjs/ast": "1.9.0" } }, "@webassemblyjs/helper-wasm-bytecode": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.8.5.tgz", - "integrity": "sha512-Cu4YMYG3Ddl72CbmpjU/wbP6SACcOPVbHN1dI4VJNJVgFwaKf1ppeFJrwydOG3NDHxVGuCfPlLZNyEdIYlQ6QQ==" + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.9.0.tgz", + "integrity": "sha512-R7FStIzyNcd7xKxCZH5lE0Bqy+hGTwS3LJjuv1ZVxd9O7eHCedSdrId/hMOd20I+v8wDXEn+bjfKDLzTepoaUw==" }, "@webassemblyjs/helper-wasm-section": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.8.5.tgz", - "integrity": "sha512-VV083zwR+VTrIWWtgIUpqfvVdK4ff38loRmrdDBgBT8ADXYsEZ5mPQ4Nde90N3UYatHdYoDIFb7oHzMncI02tA==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.9.0.tgz", + "integrity": "sha512-XnMB8l3ek4tvrKUUku+IVaXNHz2YsJyOOmz+MMkZvh8h1uSJpSen6vYnw3IoQ7WwEuAhL8Efjms1ZWjqh2agvw==", "requires": { - "@webassemblyjs/ast": "1.8.5", - "@webassemblyjs/helper-buffer": "1.8.5", - "@webassemblyjs/helper-wasm-bytecode": "1.8.5", - "@webassemblyjs/wasm-gen": "1.8.5" + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/helper-buffer": "1.9.0", + "@webassemblyjs/helper-wasm-bytecode": "1.9.0", + "@webassemblyjs/wasm-gen": "1.9.0" } }, "@webassemblyjs/ieee754": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.8.5.tgz", - "integrity": "sha512-aaCvQYrvKbY/n6wKHb/ylAJr27GglahUO89CcGXMItrOBqRarUMxWLJgxm9PJNuKULwN5n1csT9bYoMeZOGF3g==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.9.0.tgz", + "integrity": "sha512-dcX8JuYU/gvymzIHc9DgxTzUUTLexWwt8uCTWP3otys596io0L5aW02Gb1RjYpx2+0Jus1h4ZFqjla7umFniTg==", "requires": { "@xtuc/ieee754": "^1.2.0" } }, "@webassemblyjs/leb128": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.8.5.tgz", - "integrity": "sha512-plYUuUwleLIziknvlP8VpTgO4kqNaH57Y3JnNa6DLpu/sGcP6hbVdfdX5aHAV716pQBKrfuU26BJK29qY37J7A==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.9.0.tgz", + "integrity": "sha512-ENVzM5VwV1ojs9jam6vPys97B/S65YQtv/aanqnU7D8aSoHFX8GyhGg0CMfyKNIHBuAVjy3tlzd5QMMINa7wpw==", "requires": { "@xtuc/long": "4.2.2" } }, "@webassemblyjs/utf8": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.8.5.tgz", - "integrity": "sha512-U7zgftmQriw37tfD934UNInokz6yTmn29inT2cAetAsaU9YeVCveWEwhKL1Mg4yS7q//NGdzy79nlXh3bT8Kjw==" + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.9.0.tgz", + "integrity": "sha512-GZbQlWtopBTP0u7cHrEx+73yZKrQoBMpwkGEIqlacljhXCkVM1kMQge/Mf+csMJAjEdSwhOyLAS0AoR3AG5P8w==" }, "@webassemblyjs/wasm-edit": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.8.5.tgz", - "integrity": "sha512-A41EMy8MWw5yvqj7MQzkDjU29K7UJq1VrX2vWLzfpRHt3ISftOXqrtojn7nlPsZ9Ijhp5NwuODuycSvfAO/26Q==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.9.0.tgz", + "integrity": "sha512-FgHzBm80uwz5M8WKnMTn6j/sVbqilPdQXTWraSjBwFXSYGirpkSWE2R9Qvz9tNiTKQvoKILpCuTjBKzOIm0nxw==", "requires": { - "@webassemblyjs/ast": "1.8.5", - "@webassemblyjs/helper-buffer": "1.8.5", - "@webassemblyjs/helper-wasm-bytecode": "1.8.5", - "@webassemblyjs/helper-wasm-section": "1.8.5", - "@webassemblyjs/wasm-gen": "1.8.5", - "@webassemblyjs/wasm-opt": "1.8.5", - "@webassemblyjs/wasm-parser": "1.8.5", - "@webassemblyjs/wast-printer": "1.8.5" + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/helper-buffer": "1.9.0", + "@webassemblyjs/helper-wasm-bytecode": "1.9.0", + "@webassemblyjs/helper-wasm-section": "1.9.0", + "@webassemblyjs/wasm-gen": "1.9.0", + "@webassemblyjs/wasm-opt": "1.9.0", + "@webassemblyjs/wasm-parser": "1.9.0", + "@webassemblyjs/wast-printer": "1.9.0" } }, "@webassemblyjs/wasm-gen": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.8.5.tgz", - "integrity": "sha512-BCZBT0LURC0CXDzj5FXSc2FPTsxwp3nWcqXQdOZE4U7h7i8FqtFK5Egia6f9raQLpEKT1VL7zr4r3+QX6zArWg==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.9.0.tgz", + "integrity": "sha512-cPE3o44YzOOHvlsb4+E9qSqjc9Qf9Na1OO/BHFy4OI91XDE14MjFN4lTMezzaIWdPqHnsTodGGNP+iRSYfGkjA==", "requires": { - "@webassemblyjs/ast": "1.8.5", - "@webassemblyjs/helper-wasm-bytecode": "1.8.5", - "@webassemblyjs/ieee754": "1.8.5", - "@webassemblyjs/leb128": "1.8.5", - "@webassemblyjs/utf8": "1.8.5" + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/helper-wasm-bytecode": "1.9.0", + "@webassemblyjs/ieee754": "1.9.0", + "@webassemblyjs/leb128": "1.9.0", + "@webassemblyjs/utf8": "1.9.0" } }, "@webassemblyjs/wasm-opt": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.8.5.tgz", - "integrity": "sha512-HKo2mO/Uh9A6ojzu7cjslGaHaUU14LdLbGEKqTR7PBKwT6LdPtLLh9fPY33rmr5wcOMrsWDbbdCHq4hQUdd37Q==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.9.0.tgz", + "integrity": "sha512-Qkjgm6Anhm+OMbIL0iokO7meajkzQD71ioelnfPEj6r4eOFuqm4YC3VBPqXjFyyNwowzbMD+hizmprP/Fwkl2A==", "requires": { - "@webassemblyjs/ast": "1.8.5", - "@webassemblyjs/helper-buffer": "1.8.5", - "@webassemblyjs/wasm-gen": "1.8.5", - "@webassemblyjs/wasm-parser": "1.8.5" + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/helper-buffer": "1.9.0", + "@webassemblyjs/wasm-gen": "1.9.0", + "@webassemblyjs/wasm-parser": "1.9.0" } }, "@webassemblyjs/wasm-parser": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.8.5.tgz", - "integrity": "sha512-pi0SYE9T6tfcMkthwcgCpL0cM9nRYr6/6fjgDtL6q/ZqKHdMWvxitRi5JcZ7RI4SNJJYnYNaWy5UUrHQy998lw==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.9.0.tgz", + "integrity": "sha512-9+wkMowR2AmdSWQzsPEjFU7njh8HTO5MqO8vjwEHuM+AMHioNqSBONRdr0NQQ3dVQrzp0s8lTcYqzUdb7YgELA==", "requires": { - "@webassemblyjs/ast": "1.8.5", - "@webassemblyjs/helper-api-error": "1.8.5", - "@webassemblyjs/helper-wasm-bytecode": "1.8.5", - "@webassemblyjs/ieee754": "1.8.5", - "@webassemblyjs/leb128": "1.8.5", - "@webassemblyjs/utf8": "1.8.5" + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/helper-api-error": "1.9.0", + "@webassemblyjs/helper-wasm-bytecode": "1.9.0", + "@webassemblyjs/ieee754": "1.9.0", + "@webassemblyjs/leb128": "1.9.0", + "@webassemblyjs/utf8": "1.9.0" } }, "@webassemblyjs/wast-parser": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-parser/-/wast-parser-1.8.5.tgz", - "integrity": "sha512-daXC1FyKWHF1i11obK086QRlsMsY4+tIOKgBqI1lxAnkp9xe9YMcgOxm9kLe+ttjs5aWV2KKE1TWJCN57/Btsg==", - "requires": { - "@webassemblyjs/ast": "1.8.5", - "@webassemblyjs/floating-point-hex-parser": "1.8.5", - "@webassemblyjs/helper-api-error": "1.8.5", - "@webassemblyjs/helper-code-frame": "1.8.5", - "@webassemblyjs/helper-fsm": "1.8.5", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-parser/-/wast-parser-1.9.0.tgz", + "integrity": "sha512-qsqSAP3QQ3LyZjNC/0jBJ/ToSxfYJ8kYyuiGvtn/8MK89VrNEfwj7BPQzJVHi0jGTRK2dGdJ5PRqhtjzoww+bw==", + "requires": { + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/floating-point-hex-parser": "1.9.0", + "@webassemblyjs/helper-api-error": "1.9.0", + "@webassemblyjs/helper-code-frame": "1.9.0", + "@webassemblyjs/helper-fsm": "1.9.0", "@xtuc/long": "4.2.2" } }, "@webassemblyjs/wast-printer": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.8.5.tgz", - "integrity": "sha512-w0U0pD4EhlnvRyeJzBqaVSJAo9w/ce7/WPogeXLzGkO6hzhr4GnQIZ4W4uUt5b9ooAaXPtnXlj0gzsXEOUNYMg==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.9.0.tgz", + "integrity": "sha512-2J0nE95rHXHyQ24cWjMKJ1tqB/ds8z/cyeOZxJhcb+rW+SQASVjuznUSmdz5GpVJTzU8JkhYut0D3siFDD6wsA==", "requires": { - "@webassemblyjs/ast": "1.8.5", - "@webassemblyjs/wast-parser": "1.8.5", + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/wast-parser": "1.9.0", "@xtuc/long": "4.2.2" } }, @@ -964,27 +1139,45 @@ "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==" }, - "acorn": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.1.1.tgz", - "integrity": "sha512-jPTiwtOxaHNaAPg/dmrJ/beuzLRnXtB0kQPQ8JpotKJgTB6rX6c8mlf315941pyjBSaPg8NHXS9fhP4u17DpGA==" + "abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" }, - "acorn-dynamic-import": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/acorn-dynamic-import/-/acorn-dynamic-import-4.0.0.tgz", - "integrity": "sha512-d3OEjQV4ROpoflsnUA8HozoIR504TFxNivYEUi6uwz0IYhBkTDXGuWlNdMtybRt3nqVx/L6XqMt0FxkXuWKZhw==" + "acorn": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.4.1.tgz", + "integrity": "sha512-ZVA9k326Nwrj3Cj9jlh3wGFutC2ZornPNARZwsNYqQYgN0EsV2d53w5RN/co65Ohn4sUAUtb1rSUAOD6XN9idA==" }, "after": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/after/-/after-0.8.2.tgz", "integrity": "sha1-/ts5T58OAqqXaOcCvaI7UF+ufh8=" }, + "aggregate-error": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.0.1.tgz", + "integrity": "sha512-quoaXsZ9/BLNae5yiNoUz+Nhkwz83GhWwtYFglcjEQB2NDHCIpApbqXxIFnm4Pq/Nvhrsq5sYJFyohrrxnTGAA==", + "dev": true, + "requires": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + }, + "dependencies": { + "indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true + } + } + }, "ajv": { - "version": "6.10.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.10.0.tgz", - "integrity": "sha512-nffhOpkymDECQyR0mnsUtoCE8RlX38G0rYP+wgLWFyZuUyuuojSSvi/+euOiQBIn63whYwYVIIH1TvE3tu4OEg==", + "version": "6.12.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.0.tgz", + "integrity": "sha512-D6gFiFA0RRLyUbvijN74DWAjXSFxWKaWP7mldxkVhyhAV3+SWA9HEJPHQ2c9soIeTFJqcSdFDGFgdqs1iUU2Hw==", "requires": { - "fast-deep-equal": "^2.0.1", + "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" @@ -996,9 +1189,9 @@ "integrity": "sha512-DCRfO/4nQ+89p/RK43i8Ezd41EqdGIU4ld7nGF8OQ14oc/we5rEntLCUa7+jrn3nn83BosfwZA0wb4pon2o8iQ==" }, "ajv-keywords": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.4.0.tgz", - "integrity": "sha512-aUjdRFISbuFOl0EIZc+9e4FfZp0bDZgAdOOf30bJmw8VM9v84SHyVyxDfbWxpGYbdZD/9XoKxfHVNmxPkhwyGw==" + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.4.1.tgz", + "integrity": "sha512-RO1ibKvd27e6FEShVFfPALuHI3WjSVNeK5FIsmme/LYRNxjKuNj+Dt7bucLa6NdSv3JcVTyMlm9kGR84z1XpaQ==" }, "ansi-align": { "version": "2.0.0", @@ -1006,6 +1199,30 @@ "integrity": "sha1-w2rsy6VjuJzrVW82kPCx2eNUf38=", "requires": { "string-width": "^2.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" + }, + "string-width": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + } + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "requires": { + "ansi-regex": "^3.0.0" + } + } } }, "ansi-colors": { @@ -1013,15 +1230,10 @@ "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-3.2.3.tgz", "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, - "ansi-escapes": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", - "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" - }, "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" }, "ansi-styles": { "version": "3.2.1", @@ -1050,11 +1262,26 @@ } } }, + "append-transform": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/append-transform/-/append-transform-2.0.0.tgz", + "integrity": "sha512-7yeyCEurROLQJFv5Xj4lEGTy0borxepjFv1g22oAdqFu//SrAlDl1O1Nxx15SH1RoliUml6p8dwJW9jvZughhg==", + "dev": true, + "requires": { + "default-require-extensions": "^3.0.0" + } + }, "aproba": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/aproba/-/aproba-1.2.0.tgz", "integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==" }, + "archy": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/archy/-/archy-1.0.0.tgz", + "integrity": "sha1-+cjBN1fMHde8N5rHeyxipcKGjEA=", + "dev": true + }, "argparse": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", @@ -1078,46 +1305,16 @@ "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=" }, - "array-differ": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/array-differ/-/array-differ-2.1.0.tgz", - "integrity": "sha512-KbUpJgx909ZscOc/7CLATBFam7P1Z1QRQInvgT0UztM9Q72aGKCunKASAl7WNW0tnPmPyEMeMhdsfWhfmW037w==" - }, "array-find-index": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz", "integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=" }, - "array-union": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", - "integrity": "sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=", - "requires": { - "array-uniq": "^1.0.1" - }, - "dependencies": { - "array-uniq": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", - "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=" - } - } - }, - "array-uniq": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-2.1.0.tgz", - "integrity": "sha512-bdHxtev7FN6+MXI1YFW0Q8mQ8dTJc2S8AMfju+ZR77pbg2yAdVyDlwkaUI7Har0LyOMRFPHrJ9lYdyjZZswdlQ==" - }, "array-unique": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=" }, - "arrify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", - "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" - }, "asn1.js": { "version": "4.10.1", "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.10.1.tgz", @@ -1129,10 +1326,11 @@ } }, "assert": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/assert/-/assert-1.4.1.tgz", - "integrity": "sha1-mZEtWRg2tab1s0XA8H7vwI/GXZE=", + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/assert/-/assert-1.5.0.tgz", + "integrity": "sha512-EDsgawzwoun2CZkCgtxJbv392v4nbk9XDD06zI+kQYoBM/3RBWLlEyJARDOmhAAosBjWACEkKL6S+lIZtcAubA==", "requires": { + "object-assign": "^4.1.1", "util": "0.10.3" }, "dependencies": { @@ -1157,235 +1355,60 @@ "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=" }, "async-each": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.2.tgz", - "integrity": "sha512-6xrbvN0MOBKSJDdonmSSz2OwFSgxRaVtBDes26mj9KIGtDo+g9xosFRSC+i1gQh2oAN/tQ62AI/pGZGQjVOiRg==" + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.3.tgz", + "integrity": "sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ==" }, "atob": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==" }, - "ava": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/ava/-/ava-1.4.1.tgz", - "integrity": "sha512-wKpgOPTL7hJSBWpfbU4SA8rlsTZrph9g9g7qYDV7M6uK1rKeW8oCUJWRwCd8B24S4N0Y5myf6cTEnA66WIk0sA==", - "requires": { - "@ava/babel-preset-stage-4": "^2.0.0", - "@ava/babel-preset-transform-test-files": "^5.0.0", - "@ava/write-file-atomic": "^2.2.0", - "@babel/core": "^7.4.0", - "@babel/generator": "^7.4.0", - "@babel/plugin-syntax-async-generators": "^7.2.0", - "@babel/plugin-syntax-object-rest-spread": "^7.2.0", - "@babel/plugin-syntax-optional-catch-binding": "^7.2.0", - "@concordance/react": "^2.0.0", - "ansi-escapes": "^3.2.0", - "ansi-styles": "^3.2.1", - "arr-flatten": "^1.1.0", - "array-union": "^1.0.1", - "array-uniq": "^2.0.0", - "arrify": "^1.0.0", - "bluebird": "^3.5.3", - "chalk": "^2.4.2", - "chokidar": "^2.1.5", - "chunkd": "^1.0.0", - "ci-parallel-vars": "^1.0.0", - "clean-stack": "^2.0.0", - "clean-yaml-object": "^0.1.0", - "cli-cursor": "^2.1.0", - "cli-truncate": "^1.1.0", - "code-excerpt": "^2.1.1", - "common-path-prefix": "^1.0.0", - "concordance": "^4.0.0", - "convert-source-map": "^1.6.0", - "currently-unhandled": "^0.4.1", - "debug": "^4.1.1", - "del": "^4.0.0", - "dot-prop": "^4.2.0", - "emittery": "^0.4.1", - "empower-core": "^1.2.0", - "equal-length": "^1.0.0", - "escape-string-regexp": "^1.0.5", - "esm": "^3.2.20", - "figures": "^2.0.0", - "find-up": "^3.0.0", - "get-port": "^4.2.0", - "globby": "^7.1.1", - "ignore-by-default": "^1.0.0", - "import-local": "^2.0.0", - "indent-string": "^3.2.0", - "is-ci": "^2.0.0", - "is-error": "^2.2.1", - "is-observable": "^1.1.0", - "is-plain-object": "^2.0.4", - "is-promise": "^2.1.0", - "lodash.clone": "^4.5.0", - "lodash.clonedeep": "^4.5.0", - "lodash.clonedeepwith": "^4.5.0", - "lodash.debounce": "^4.0.3", - "lodash.difference": "^4.3.0", - "lodash.flatten": "^4.2.0", - "loud-rejection": "^1.2.0", - "make-dir": "^2.1.0", - "matcher": "^1.1.1", - "md5-hex": "^2.0.0", - "meow": "^5.0.0", - "ms": "^2.1.1", - "multimatch": "^3.0.0", - "observable-to-promise": "^0.5.0", - "ora": "^3.2.0", - "package-hash": "^3.0.0", - "pkg-conf": "^3.0.0", - "plur": "^3.0.1", - "pretty-ms": "^4.0.0", - "require-precompiled": "^0.1.0", - "resolve-cwd": "^2.0.0", - "slash": "^2.0.0", - "source-map-support": "^0.5.11", - "stack-utils": "^1.0.2", - "strip-ansi": "^5.2.0", - "strip-bom-buf": "^1.0.0", - "supertap": "^1.0.0", - "supports-color": "^6.1.0", - "trim-off-newlines": "^1.0.1", - "trim-right": "^1.0.1", - "unique-temp-dir": "^1.0.0", - "update-notifier": "^2.5.0" + "babel-loader": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-8.1.0.tgz", + "integrity": "sha512-7q7nC1tYOrqvUrN3LQK4GwSk/TQorZSOlO9C+RZDZpODgyN4ZlCqE5q9cDsyWOliN+aU9B4JX01xK9eJXowJLw==", + "requires": { + "find-cache-dir": "^2.1.0", + "loader-utils": "^1.4.0", + "mkdirp": "^0.5.3", + "pify": "^4.0.1", + "schema-utils": "^2.6.5" + } + }, + "babel-plugin-dynamic-import-node": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/babel-plugin-dynamic-import-node/-/babel-plugin-dynamic-import-node-2.3.0.tgz", + "integrity": "sha512-o6qFkpeQEBxcqt0XYlWzAVxNCSCZdUgcR8IRlhD/8DylxjjO4foPcvTW0GGKa/cVt3rvxZ7o5ippJ+/0nvLhlQ==", + "requires": { + "object.assign": "^4.1.0" + } + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" + }, + "base": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", + "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==", + "requires": { + "cache-base": "^1.0.1", + "class-utils": "^0.3.5", + "component-emitter": "^1.2.1", + "define-property": "^1.0.0", + "isobject": "^3.0.1", + "mixin-deep": "^1.2.0", + "pascalcase": "^0.1.1" }, "dependencies": { - "debug": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", - "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", "requires": { - "ms": "^2.1.1" - } - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" - }, - "supports-color": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", - "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, - "babel-loader": { - "version": "8.0.5", - "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-8.0.5.tgz", - "integrity": "sha512-NTnHnVRd2JnRqPC0vW+iOQWU5pchDbYXsG2E6DMXEpMfUcQKclF9gmf3G3ZMhzG7IG9ji4coL0cm+FxeWxDpnw==", - "requires": { - "find-cache-dir": "^2.0.0", - "loader-utils": "^1.0.2", - "mkdirp": "^0.5.1", - "util.promisify": "^1.0.0" - } - }, - "babel-plugin-espower": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/babel-plugin-espower/-/babel-plugin-espower-3.0.1.tgz", - "integrity": "sha512-Ms49U7VIAtQ/TtcqRbD6UBmJBUCSxiC3+zPc+eGqxKUIFO1lTshyEDRUjhoAbd2rWfwYf3cZ62oXozrd8W6J0A==", - "requires": { - "@babel/generator": "^7.0.0", - "@babel/parser": "^7.0.0", - "call-matcher": "^1.0.0", - "core-js": "^2.0.0", - "espower-location-detector": "^1.0.0", - "espurify": "^1.6.0", - "estraverse": "^4.1.1" - }, - "dependencies": { - "core-js": { - "version": "2.6.5", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.5.tgz", - "integrity": "sha512-klh/kDpwX8hryYL14M9w/xei6vrv6sE8gTHDG7/T/+SEovB/G4ejwcfE/CBzO6Edsu+OETZMZ3wcX/EjUkrl5A==" - } - } - }, - "balanced-match": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", - "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" - }, - "base": { - "version": "0.11.2", - "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", - "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==", - "requires": { - "cache-base": "^1.0.1", - "class-utils": "^0.3.5", - "component-emitter": "^1.2.1", - "define-property": "^1.0.0", - "isobject": "^3.0.1", - "mixin-deep": "^1.2.0", - "pascalcase": "^0.1.1" - }, - "dependencies": { - "define-property": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", - "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", - "requires": { - "is-descriptor": "^1.0.0" + "is-descriptor": "^1.0.0" } }, "is-accessor-descriptor": { @@ -1417,9 +1440,9 @@ } }, "base64-js": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.0.tgz", - "integrity": "sha512-ccav/yGvoa80BQDljCxsmmQ3Xvx60/UpBIij5QN21W3wBi/hhIC9OoO+KLpu9IJTS9j4DRVJ3aDDF9cMSoa2lw==" + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.1.tgz", + "integrity": "sha512-mLQ4i2QO1ytvGWFWmcngKO//JXAQueZvwEKtjgQFM4jIK0kU+ytMfplL8j+n5mspOfjHwoAg+9yhb7BwAHm36g==" }, "big.js": { "version": "5.2.2", @@ -1431,6 +1454,15 @@ "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-1.13.1.tgz", "integrity": "sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw==" }, + "bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "optional": true, + "requires": { + "file-uri-to-path": "1.0.0" + } + }, "bl": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/bl/-/bl-1.2.2.tgz", @@ -1441,9 +1473,9 @@ } }, "bluebird": { - "version": "3.5.4", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.4.tgz", - "integrity": "sha512-FG+nFEZChJrbQ9tIccIfZJBz3J7mLrAhxakAbnrJWn8d7aKOC+LWifa0G+p4ZqKp4y13T7juYvdhq9NzKdsrjw==" + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==" }, "bn.js": { "version": "4.11.8", @@ -1462,6 +1494,35 @@ "string-width": "^2.0.0", "term-size": "^1.2.0", "widest-line": "^2.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" + }, + "camelcase": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz", + "integrity": "sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0=" + }, + "string-width": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + } + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "requires": { + "ansi-regex": "^3.0.0" + } + } } }, "brace-expansion": { @@ -1576,19 +1637,20 @@ } }, "browserslist": { - "version": "4.5.4", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.5.4.tgz", - "integrity": "sha512-rAjx494LMjqKnMPhFkuLmLp8JWEX0o8ADTGeAbOqaF+XCvYLreZrG5uVjnPBlAQ8REZK4pzXGvp0bWgrFtKaag==", + "version": "4.11.1", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.11.1.tgz", + "integrity": "sha512-DCTr3kDrKEYNw6Jb9HFxVLQNaue8z+0ZfRBRjmCunKDEXEBajKDj2Y+Uelg+Pi29OnvaSGwjOsnRyNEkXzHg5g==", "requires": { - "caniuse-lite": "^1.0.30000955", - "electron-to-chromium": "^1.3.122", - "node-releases": "^1.1.13" + "caniuse-lite": "^1.0.30001038", + "electron-to-chromium": "^1.3.390", + "node-releases": "^1.1.53", + "pkg-up": "^2.0.0" } }, "buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.2.1.tgz", - "integrity": "sha512-c+Ko0loDaFfuPWiL02ls9Xd3GO3cPVmUobQ6t3rXNUk304u6hGq+8N/kFi+QEIKhzK3uwolVhLzszmfLmMLnqg==", + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.5.0.tgz", + "integrity": "sha512-9FTEDjLjwoAkEwyMGDjYJQN2gfRgOKBKRfiglhvibGbpeeU/pQn1bJxQqm32OD/AIeEuHxU9roxXxg34Byp/Ww==", "requires": { "base64-js": "^1.0.2", "ieee754": "^1.1.4" @@ -1639,21 +1701,22 @@ "integrity": "sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug=" }, "cacache": { - "version": "11.3.2", - "resolved": "https://registry.npmjs.org/cacache/-/cacache-11.3.2.tgz", - "integrity": "sha512-E0zP4EPGDOaT2chM08Als91eYnf8Z+eH1awwwVsngUmgppfM5jjJ8l3z5vO5p5w/I3LsiXawb1sW0VY65pQABg==", + "version": "12.0.4", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-12.0.4.tgz", + "integrity": "sha512-a0tMB40oefvuInr4Cwb3GerbL9xTj1D5yg0T5xrjGCGyfvbxseIXX7BAO/u/hIXdafzOI5JC3wDwHyf24buOAQ==", "requires": { - "bluebird": "^3.5.3", + "bluebird": "^3.5.5", "chownr": "^1.1.1", "figgy-pudding": "^3.5.1", - "glob": "^7.1.3", + "glob": "^7.1.4", "graceful-fs": "^4.1.15", + "infer-owner": "^1.0.3", "lru-cache": "^5.1.1", "mississippi": "^3.0.0", "mkdirp": "^0.5.1", "move-concurrently": "^1.0.1", "promise-inflight": "^1.0.1", - "rimraf": "^2.6.2", + "rimraf": "^2.6.3", "ssri": "^6.0.1", "unique-filename": "^1.1.1", "y18n": "^4.0.0" @@ -1668,9 +1731,9 @@ } }, "yallist": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.0.3.tgz", - "integrity": "sha512-S+Zk8DEWE6oKpV+vI3qWkaK+jSbIK86pCwe2IF/xwIpQ8jEuxpw9NyaGjmp9+BoJv5FV2piqCDcoCtStppiq2A==" + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==" } } }, @@ -1690,48 +1753,72 @@ "unset-value": "^1.0.0" } }, - "call-matcher": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/call-matcher/-/call-matcher-1.1.0.tgz", - "integrity": "sha512-IoQLeNwwf9KTNbtSA7aEBb1yfDbdnzwjCetjkC8io5oGeOmK2CBNdg0xr+tadRYKO0p7uQyZzvon0kXlZbvGrw==", - "requires": { - "core-js": "^2.0.0", - "deep-equal": "^1.0.0", - "espurify": "^1.6.0", - "estraverse": "^4.0.0" + "caching-transform": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/caching-transform/-/caching-transform-4.0.0.tgz", + "integrity": "sha512-kpqOvwXnjjN44D89K5ccQC+RUrsy7jB/XLlRrx0D7/2HNcTPqzsb6XgYoErwko6QsV184CA2YgS1fxDiiDZMWA==", + "dev": true, + "requires": { + "hasha": "^5.0.0", + "make-dir": "^3.0.0", + "package-hash": "^4.0.0", + "write-file-atomic": "^3.0.0" }, "dependencies": { - "core-js": { - "version": "2.6.5", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.5.tgz", - "integrity": "sha512-klh/kDpwX8hryYL14M9w/xei6vrv6sE8gTHDG7/T/+SEovB/G4ejwcfE/CBzO6Edsu+OETZMZ3wcX/EjUkrl5A==" + "make-dir": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.0.2.tgz", + "integrity": "sha512-rYKABKutXa6vXTXhoV18cBE7PaewPXHe/Bdq4v+ZLMhxbWApkFFplT0LcbMW+6BbjnQXzZ/sAvSE/JdguApG5w==", + "dev": true, + "requires": { + "semver": "^6.0.0" + } + }, + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + }, + "write-file-atomic": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz", + "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", + "dev": true, + "requires": { + "imurmurhash": "^0.1.4", + "is-typedarray": "^1.0.0", + "signal-exit": "^3.0.2", + "typedarray-to-buffer": "^3.1.5" + } } } }, - "call-signature": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/call-signature/-/call-signature-0.0.2.tgz", - "integrity": "sha1-qEq8glpV70yysCi9dOIFpluaSZY=" - }, "camelcase": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz", - "integrity": "sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0=" + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==" }, "camelcase-keys": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-4.2.0.tgz", - "integrity": "sha1-oqpfsa9oh1glnDLBQUJteJI7m3c=", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", + "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", "requires": { - "camelcase": "^4.1.0", - "map-obj": "^2.0.0", - "quick-lru": "^1.0.0" + "camelcase": "^2.0.0", + "map-obj": "^1.0.0" + }, + "dependencies": { + "camelcase": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", + "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=" + } } }, "caniuse-lite": { - "version": "1.0.30000957", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30000957.tgz", - "integrity": "sha512-8wxNrjAzyiHcLXN/iunskqQnJquQQ6VX8JHfW5kLgAPRSiSuKZiNfmIkP5j7jgyXqAQBSoXyJxfnbCFS0ThSiQ==" + "version": "1.0.30001039", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001039.tgz", + "integrity": "sha512-SezbWCTT34eyFoWHgx8UWso7YtvtM7oosmFoXbCkdC6qJzRfBTeTgE9REtKtiuKXuMwWTZEvdnFNGAyVMorv8Q==" }, "capture-stack-trace": { "version": "1.0.1", @@ -1760,9 +1847,9 @@ } }, "chokidar": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-2.1.5.tgz", - "integrity": "sha512-i0TprVWp+Kj4WRPtInjexJ8Q+BqTE909VpH8xVhXrJkoc5QC8VO9TryGOqTr+2hljzc1sC62t22h5tZePodM/A==", + "version": "2.1.8", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-2.1.8.tgz", + "integrity": "sha512-ZmZUazfOzf0Nve7duiCKD23PFSCs4JPoYyccjUFF3aQkQadqBhfzhjkwBH2mNOG9cTBwhamM37EIsIkZw3nRgg==", "requires": { "anymatch": "^2.0.0", "async-each": "^1.0.1", @@ -1779,32 +1866,22 @@ } }, "chownr": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.1.tgz", - "integrity": "sha512-j38EvO5+LHX84jlo6h4UzmOwi0UgW61WRyPtJz4qaadK5eY3BTS5TY/S1Stc3Uk2lIM6TPevAlULiEJwie860g==" + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==" }, "chrome-trace-event": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.0.tgz", - "integrity": "sha512-xDbVgyfDTT2piup/h8dK/y4QZfJRSa73bw1WZ8b4XM1o7fsFubUVGYcE+1ANtOzJJELGpYoG2961z0Z6OAld9A==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.2.tgz", + "integrity": "sha512-9e/zx1jw7B4CO+c/RXoCsfg/x1AfUBioy4owYH0bJprEYAx5hRFLRhWBqHAG57D0ZM4H7vxbP7bPe0VwhQRYDQ==", "requires": { "tslib": "^1.9.0" } }, - "chunkd": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/chunkd/-/chunkd-1.0.0.tgz", - "integrity": "sha512-xx3Pb5VF9QaqCotolyZ1ywFBgyuJmu6+9dLiqBxgelEse9Xsr3yUlpoX3O4Oh11M00GT2kYMsRByTKIMJW2Lkg==" - }, "ci-info": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", - "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==" - }, - "ci-parallel-vars": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/ci-parallel-vars/-/ci-parallel-vars-1.0.0.tgz", - "integrity": "sha512-u6dx20FBXm+apMi+5x7UVm6EH7BL1gc4XrcnQewjcB7HWRcor/V5qWc3RG2HwpgDJ26gIi2DSEu3B7sXynAw/g==" + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", + "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, "cipher-base": { "version": "1.0.4", @@ -1837,80 +1914,26 @@ } }, "clean-stack": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.0.0.tgz", - "integrity": "sha512-VEoL9Qh7I8s8iHnV53DaeWSt8NJ0g3khMfK6NiCPB7H657juhro+cSw2O88uo3bo0c0X5usamtXk0/Of0wXa5A==" - }, - "clean-yaml-object": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/clean-yaml-object/-/clean-yaml-object-0.1.0.tgz", - "integrity": "sha1-Y/sRDcLOGoTcIfbZM0h20BCui2g=" + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", + "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", + "dev": true }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", "integrity": "sha1-T6kXw+WclKAEzWH47lCdplFocUM=" }, - "cli-cursor": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", - "integrity": "sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU=", - "requires": { - "restore-cursor": "^2.0.0" - } - }, - "cli-spinners": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.1.0.tgz", - "integrity": "sha512-8B00fJOEh1HPrx4fo5eW16XmE1PcL1tGpGrxy63CXGP9nHdPBN63X75hA1zhvQuhVztJWLqV58Roj2qlNM7cAA==" - }, - "cli-truncate": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-1.1.0.tgz", - "integrity": "sha512-bAtZo0u82gCfaAGfSNxUdTI9mNyza7D8w4CVCcaOsy7sgwDzvx6ekr6cuWJqY3UGzgnQ1+4wgENup5eIhgxEYA==", - "requires": { - "slice-ansi": "^1.0.0", - "string-width": "^2.0.0" - } - }, "cliui": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-4.1.0.tgz", - "integrity": "sha512-4FG+RSG9DL7uEwRUZXZn3SS34DiDPfzP0VOiEwtUWlE+AR2EIg+hSyvrIgUUfhdgR/UkAeW2QHgeP+hWrXs7jQ==", - "requires": { - "string-width": "^2.1.1", - "strip-ansi": "^4.0.0", - "wrap-ansi": "^2.0.0" - }, - "dependencies": { - "strip-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", - "requires": { - "ansi-regex": "^3.0.0" - } - } - } - }, - "clone": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", - "integrity": "sha1-2jCcwmPfFZlMaIypAheco8fNfH4=" - }, - "code-excerpt": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/code-excerpt/-/code-excerpt-2.1.1.tgz", - "integrity": "sha512-tJLhH3EpFm/1x7heIW0hemXJTUU5EWl2V0EIX558jp05Mt1U6DVryCgkp3l37cxqs+DNbNgxG43SkwJXpQ14Jw==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", + "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", "requires": { - "convert-to-spaces": "^1.0.1" + "string-width": "^3.1.0", + "strip-ansi": "^5.2.0", + "wrap-ansi": "^5.1.0" } }, - "code-point-at": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", - "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=" - }, "collection-visit": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/collection-visit/-/collection-visit-1.0.0.tgz", @@ -1934,14 +1957,9 @@ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "commander": { - "version": "2.20.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" - }, - "common-path-prefix": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/common-path-prefix/-/common-path-prefix-1.0.0.tgz", - "integrity": "sha1-zVL28HEuC6q5fW+XModPIvR3UsA=" + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==" }, "commondir": { "version": "1.0.1", @@ -1949,9 +1967,9 @@ "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=" }, "component-emitter": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz", - "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=" + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", + "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==" }, "concat-map": { "version": "0.0.1", @@ -1969,66 +1987,28 @@ "typedarray": "^0.0.6" } }, - "concordance": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/concordance/-/concordance-4.0.0.tgz", - "integrity": "sha512-l0RFuB8RLfCS0Pt2Id39/oCPykE01pyxgAFypWTlaGRgvLkZrtczZ8atEHpTeEIW+zYWXTBuA9cCSeEOScxReQ==", - "requires": { - "date-time": "^2.1.0", - "esutils": "^2.0.2", - "fast-diff": "^1.1.2", - "js-string-escape": "^1.0.1", - "lodash.clonedeep": "^4.5.0", - "lodash.flattendeep": "^4.4.0", - "lodash.islength": "^4.0.1", - "lodash.merge": "^4.6.1", - "md5-hex": "^2.0.0", - "semver": "^5.5.1", - "well-known-symbols": "^2.0.0" - } - }, "concurrently": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-4.1.0.tgz", - "integrity": "sha512-pwzXCE7qtOB346LyO9eFWpkFJVO3JQZ/qU/feGeaAHiX1M3Rw3zgXKc5cZ8vSH5DGygkjzLFDzA/pwoQDkRNGg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-5.1.0.tgz", + "integrity": "sha512-9ViZMu3OOCID3rBgU31mjBftro2chOop0G2u1olq1OuwRBVRw/GxHTg80TVJBUTJfoswMmEUeuOg1g1yu1X2dA==", "requires": { - "chalk": "^2.4.1", - "date-fns": "^1.23.0", - "lodash": "^4.17.10", + "chalk": "^2.4.2", + "date-fns": "^2.0.1", + "lodash": "^4.17.15", "read-pkg": "^4.0.1", - "rxjs": "^6.3.3", + "rxjs": "^6.5.2", "spawn-command": "^0.0.2-1", - "supports-color": "^4.5.0", - "tree-kill": "^1.1.0", - "yargs": "^12.0.1" + "supports-color": "^6.1.0", + "tree-kill": "^1.2.2", + "yargs": "^13.3.0" }, "dependencies": { - "has-flag": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-2.0.0.tgz", - "integrity": "sha1-6CB68cx7MNRGzHC3NLXovhj4jVE=" - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=" - }, - "read-pkg": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-4.0.1.tgz", - "integrity": "sha1-ljYlN48+HE1IyFhytabsfV0JMjc=", - "requires": { - "normalize-package-data": "^2.3.2", - "parse-json": "^4.0.0", - "pify": "^3.0.0" - } - }, "supports-color": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-4.5.0.tgz", - "integrity": "sha1-vnoN5ITexcXN34s9WRJQRJEvY1s=", + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", + "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", "requires": { - "has-flag": "^2.0.0" + "has-flag": "^3.0.0" } } } @@ -2071,12 +2051,9 @@ } }, "console-browserify": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz", - "integrity": "sha1-8CQcRXMKn8YyOyBtvzjtx0HQuxA=", - "requires": { - "date-now": "^0.1.4" - } + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.2.0.tgz", + "integrity": "sha512-ZMkYO/LkF17QvCPqM0gxw8yUzigAOZOSWSHg91FH6orS7vcEj5dVZTidN2fQ14yBSdg97RqhSNwLUXInd52OTA==" }, "constants-browserify": { "version": "1.0.0", @@ -2092,18 +2069,13 @@ } }, "convert-source-map": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.6.0.tgz", - "integrity": "sha512-eFu7XigvxdZ1ETfbgPBohgyQ/Z++C0eEhTor0qRwBw9unw+L0/6V8wkSuGgzdThkiS5lSpdptOQPD8Ak40a+7A==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.7.0.tgz", + "integrity": "sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA==", "requires": { "safe-buffer": "~5.1.1" } }, - "convert-to-spaces": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/convert-to-spaces/-/convert-to-spaces-1.0.2.tgz", - "integrity": "sha1-fj5Iu+bZl7FBfdyihoIEtNPYVxU=" - }, "copy-concurrently": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/copy-concurrently/-/copy-concurrently-1.0.5.tgz", @@ -2122,27 +2094,22 @@ "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=" }, - "core-js": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.0.0.tgz", - "integrity": "sha512-WBmxlgH2122EzEJ6GH8o9L/FeoUKxxxZ6q6VUxoTlsE4EvbTWKJb447eyVxTEuq0LpXjlq/kCB2qgBvsYRkLvQ==" - }, "core-js-compat": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.0.0.tgz", - "integrity": "sha512-W/Ppz34uUme3LmXWjMgFlYyGnbo1hd9JvA0LNQ4EmieqVjg2GPYbj3H6tcdP2QGPGWdRKUqZVbVKLNIFVs/HiA==", + "version": "3.6.4", + "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.6.4.tgz", + "integrity": "sha512-zAa3IZPvsJ0slViBQ2z+vgyyTuhd3MFn1rBQjZSKVEgB0UMYhUkCj9jJUVPgGTGqWvsBVmfnruXgTcNyTlEiSA==", "requires": { - "browserslist": "^4.5.1", - "core-js": "3.0.0", - "core-js-pure": "3.0.0", - "semver": "^5.6.0" + "browserslist": "^4.8.3", + "semver": "7.0.0" + }, + "dependencies": { + "semver": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.0.0.tgz", + "integrity": "sha512-+GB6zVA9LWh6zovYQLALHwv5rb2PHGlJi3lfiqIHxR0uuwCgefcOJc59v9fv1w8GbStwxuuqqAjI9NMAOOgq1A==" + } } }, - "core-js-pure": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/core-js-pure/-/core-js-pure-3.0.0.tgz", - "integrity": "sha512-yPiS3fQd842RZDgo/TAKGgS0f3p2nxssF1H65DIZvZv0Od5CygP8puHXn3IQiM/39VAvgCbdaMQpresrbGgt9g==" - }, "core-util-is": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", @@ -2232,27 +2199,14 @@ } }, "cyclist": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/cyclist/-/cyclist-0.2.2.tgz", - "integrity": "sha1-GzN5LhHpFKL9bW7WRHRkRE5fpkA=" + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/cyclist/-/cyclist-1.0.1.tgz", + "integrity": "sha1-WW6WmP0MgOEgOMK4LW6xs1tiJNk=" }, "date-fns": { - "version": "1.30.1", - "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-1.30.1.tgz", - "integrity": "sha512-hBSVCvSmWC+QypYObzwGOd9wqdDpOt+0wl0KbU+R+uuZBS1jN8VsD1ss3irQDknRj5NvxiTF6oj/nDRnN/UQNw==" - }, - "date-now": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz", - "integrity": "sha1-6vQ5/U1ISK105cx9vvIAZyueNFs=" - }, - "date-time": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/date-time/-/date-time-2.1.0.tgz", - "integrity": "sha512-/9+C44X7lot0IeiyfgJmETtRMhBidBYM2QFFIkGa0U1k+hSyY87Nw7PY3eDqpvCBm7I3WCSfPeZskW/YYq6m4g==", - "requires": { - "time-zone": "^1.0.0" - } + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.11.1.tgz", + "integrity": "sha512-3RdUoinZ43URd2MJcquzBbDQo+J87cSzB8NkXdZiN5ia1UNyep0oCyitfiL88+R7clGTeq/RniXAc16gWyAu1w==" }, "debug": { "version": "2.6.9", @@ -2267,31 +2221,15 @@ "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=" }, - "decamelize-keys": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/decamelize-keys/-/decamelize-keys-1.1.0.tgz", - "integrity": "sha1-0XGoeTMlKAfrPLYdwcFEXQeN8tk=", - "requires": { - "decamelize": "^1.1.0", - "map-obj": "^1.0.0" - }, - "dependencies": { - "map-obj": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", - "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=" - } - } - }, "decode-uri-component": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=" }, "decompress": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/decompress/-/decompress-4.2.0.tgz", - "integrity": "sha1-eu3YVCflqS2s/lVnSnxQXpbQH50=", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/decompress/-/decompress-4.2.1.tgz", + "integrity": "sha512-e48kc2IjU+2Zw8cTb6VZcJQ3lgVbS4uuB1TfCHbiZIP/haNXm+SVyhu+87jts5/3ROpd82GSVCoNs/z8l4ZOaQ==", "requires": { "decompress-tar": "^4.0.0", "decompress-tarbz2": "^4.0.0", @@ -2404,22 +2342,26 @@ } } }, - "deep-equal": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz", - "integrity": "sha1-9dJgKStmDghO/0zbyfCK0yR0SLU=" - }, "deep-extend": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==" }, - "defaults": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.3.tgz", - "integrity": "sha1-xlYFHpgX2f8I7YgUd/P+QBnz730=", + "default-require-extensions": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/default-require-extensions/-/default-require-extensions-3.0.0.tgz", + "integrity": "sha512-ek6DpXq/SCpvjhpFsLFRVtIxJCRw6fUR42lYMVZuUMK7n8eMz4Uh5clckdBjEpLhn/gEBZo7hDJnJcwdKLKQjg==", + "dev": true, "requires": { - "clone": "^1.0.2" + "strip-bom": "^4.0.0" + }, + "dependencies": { + "strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "dev": true + } } }, "define-properties": { @@ -2467,44 +2409,10 @@ } } }, - "del": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/del/-/del-4.1.0.tgz", - "integrity": "sha512-C4kvKNlYrwXhKxz97BuohF8YoGgQ23Xm9lvoHmgT7JaPGprSEjk3+XFled74Yt/x0ZABUHg2D67covzAPUKx5Q==", - "requires": { - "globby": "^6.1.0", - "is-path-cwd": "^2.0.0", - "is-path-in-cwd": "^2.0.0", - "p-map": "^2.0.0", - "pify": "^4.0.1", - "rimraf": "^2.6.3" - }, - "dependencies": { - "globby": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-6.1.0.tgz", - "integrity": "sha1-9abXDoOV4hyFj7BInWTfAkJNUGw=", - "requires": { - "array-union": "^1.0.1", - "glob": "^7.0.3", - "object-assign": "^4.0.1", - "pify": "^2.0.0", - "pinkie-promise": "^2.0.0" - }, - "dependencies": { - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=" - } - } - } - } - }, "des.js": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.0.tgz", - "integrity": "sha1-wHTS4qpqipoH29YfmhXCzYPsjsw=", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.1.tgz", + "integrity": "sha512-Q0I4pfFrv2VPd34/vfLrFOoRmlYj3OV50i7fskps1jZWK1kApMWWT9G6RRUeYedLcBDIhnSDaUvJMb3AhUlaEA==", "requires": { "inherits": "^2.0.1", "minimalistic-assert": "^1.0.0" @@ -2530,14 +2438,6 @@ "randombytes": "^2.0.0" } }, - "dir-glob": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-2.2.2.tgz", - "integrity": "sha512-f9LBi5QWzIW3I6e//uxZoLBlUt9kcp66qo0sSCxL6YZKc75R1c4MFCoe/LaZiBGmgujvQdxc5Bn3QhfyvK5Hsw==", - "requires": { - "path-type": "^3.0.0" - } - }, "domain-browser": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/domain-browser/-/domain-browser-1.2.0.tgz", @@ -2569,27 +2469,6 @@ "pify": "^3.0.0" }, "dependencies": { - "got": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/got/-/got-7.1.0.tgz", - "integrity": "sha512-Y5WMo7xKKq1muPsxD+KmrR8DH5auG7fBdDVueZwETwV6VytKyU9OX/ddpq2/1hp1vIPvVb4T81dKQz3BivkNLw==", - "requires": { - "decompress-response": "^3.2.0", - "duplexer3": "^0.1.4", - "get-stream": "^3.0.0", - "is-plain-obj": "^1.1.0", - "is-retry-allowed": "^1.0.0", - "is-stream": "^1.0.0", - "isurl": "^1.0.0-alpha5", - "lowercase-keys": "^1.0.0", - "p-cancelable": "^0.3.0", - "p-timeout": "^1.1.1", - "safe-buffer": "^5.0.1", - "timed-out": "^4.0.0", - "url-parse-lax": "^1.0.0", - "url-to-options": "^1.0.1" - } - }, "make-dir": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.3.0.tgz", @@ -2612,158 +2491,6 @@ "requires": { "download": "^6.2.1", "meow": "^3.3.0" - }, - "dependencies": { - "camelcase": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", - "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=" - }, - "camelcase-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", - "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", - "requires": { - "camelcase": "^2.0.0", - "map-obj": "^1.0.0" - } - }, - "find-up": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", - "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", - "requires": { - "path-exists": "^2.0.0", - "pinkie-promise": "^2.0.0" - } - }, - "indent-string": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-2.1.0.tgz", - "integrity": "sha1-ji1INIdCEhtKghi3oTfppSBJ3IA=", - "requires": { - "repeating": "^2.0.0" - } - }, - "load-json-file": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", - "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", - "requires": { - "graceful-fs": "^4.1.2", - "parse-json": "^2.2.0", - "pify": "^2.0.0", - "pinkie-promise": "^2.0.0", - "strip-bom": "^2.0.0" - } - }, - "map-obj": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", - "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=" - }, - "meow": { - "version": "3.7.0", - "resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz", - "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", - "requires": { - "camelcase-keys": "^2.0.0", - "decamelize": "^1.1.2", - "loud-rejection": "^1.0.0", - "map-obj": "^1.0.1", - "minimist": "^1.1.3", - "normalize-package-data": "^2.3.4", - "object-assign": "^4.0.1", - "read-pkg-up": "^1.0.1", - "redent": "^1.0.0", - "trim-newlines": "^1.0.0" - } - }, - "minimist": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=" - }, - "parse-json": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", - "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", - "requires": { - "error-ex": "^1.2.0" - } - }, - "path-exists": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", - "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", - "requires": { - "pinkie-promise": "^2.0.0" - } - }, - "path-type": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-1.1.0.tgz", - "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=", - "requires": { - "graceful-fs": "^4.1.2", - "pify": "^2.0.0", - "pinkie-promise": "^2.0.0" - } - }, - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=" - }, - "read-pkg": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-1.1.0.tgz", - "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", - "requires": { - "load-json-file": "^1.0.0", - "normalize-package-data": "^2.3.2", - "path-type": "^1.0.0" - } - }, - "read-pkg-up": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-1.0.1.tgz", - "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", - "requires": { - "find-up": "^1.0.0", - "read-pkg": "^1.0.0" - } - }, - "redent": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/redent/-/redent-1.0.0.tgz", - "integrity": "sha1-z5Fqsf1fHxbfsggi3W7H9zDCr94=", - "requires": { - "indent-string": "^2.1.0", - "strip-indent": "^1.0.1" - } - }, - "strip-bom": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", - "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", - "requires": { - "is-utf8": "^0.2.0" - } - }, - "strip-indent": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-1.0.1.tgz", - "integrity": "sha1-DHlipq3vp7vUrDZkYKY4VSrhoKI=", - "requires": { - "get-stdin": "^4.0.1" - } - }, - "trim-newlines": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-1.0.0.tgz", - "integrity": "sha1-WIeWa7WCpFA6QetST301ARgVphM=" - } } }, "duplexer2": { @@ -2814,14 +2541,14 @@ } }, "electron-to-chromium": { - "version": "1.3.124", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.124.tgz", - "integrity": "sha512-glecGr/kFdfeXUHOHAWvGcXrxNU+1wSO/t5B23tT1dtlvYB26GY8aHzZSWD7HqhqC800Lr+w/hQul6C5AF542w==" + "version": "1.3.397", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.397.tgz", + "integrity": "sha512-zcUd1p/7yzTSdWkCTrqGvbnEOASy96d0RJL/lc5BDJoO23Z3G/VHd0yIPbguDU9n8QNUTCigLO7oEdtOb7fp2A==" }, "elliptic": { - "version": "6.4.1", - "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.4.1.tgz", - "integrity": "sha512-BsXLz5sqX8OHcsh7CqBMztyXARmGQ3LWPtGjJi6DiJHq5C/qvi9P3OqgswKSDftbu8+IoI/QDTAm2fFnQ9SZSQ==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.2.tgz", + "integrity": "sha512-f4x70okzZbIQl/NSRLkI/+tteV/9WqL98zx+SQ69KbXxmVrmjwsNUPn/gYJJ0sHvEak24cZgHIPegRePAtA/xw==", "requires": { "bn.js": "^4.4.0", "brorand": "^1.0.1", @@ -2832,60 +2559,45 @@ "minimalistic-crypto-utils": "^1.0.0" } }, - "emittery": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.4.1.tgz", - "integrity": "sha512-r4eRSeStEGf6M5SKdrQhhLK5bOwOBxQhIE3YSTnZE3GpKiLfnnhE+tPtrJE79+eDJgm39BM6LSoI8SCx4HbwlQ==" - }, "emoji-regex": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==" }, "emojis-list": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz", - "integrity": "sha1-TapNnbAPmBmIDHn6RXrlsJof04k=" - }, - "empower-core": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/empower-core/-/empower-core-1.2.0.tgz", - "integrity": "sha512-g6+K6Geyc1o6FdXs9HwrXleCFan7d66G5xSCfSF7x1mJDCes6t0om9lFQG3zOrzh3Bkb/45N0cZ5Gqsf7YrzGQ==", - "requires": { - "call-signature": "0.0.2", - "core-js": "^2.0.0" - }, - "dependencies": { - "core-js": { - "version": "2.6.5", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.5.tgz", - "integrity": "sha512-klh/kDpwX8hryYL14M9w/xei6vrv6sE8gTHDG7/T/+SEovB/G4ejwcfE/CBzO6Edsu+OETZMZ3wcX/EjUkrl5A==" - } - } + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-3.0.0.tgz", + "integrity": "sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q==" }, "end-of-stream": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.1.tgz", - "integrity": "sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q==", + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", "requires": { "once": "^1.4.0" } }, "enhanced-resolve": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-4.1.0.tgz", - "integrity": "sha512-F/7vkyTtyc/llOIn8oWclcB25KdRaiPBpZYDgJHgh/UHtpgT2p2eldQgtQnLtUvfMKPKxbRaQM/hHkvLHt1Vng==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-4.1.1.tgz", + "integrity": "sha512-98p2zE+rL7/g/DzMHMTF4zZlCgeVdJ7yr6xzEpJRYwFYrGi9ANdn5DnJURg6RpBkyk60XYDnWIv51VfIhfNGuA==", "requires": { "graceful-fs": "^4.1.2", - "memory-fs": "^0.4.0", + "memory-fs": "^0.5.0", "tapable": "^1.0.0" + }, + "dependencies": { + "memory-fs": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/memory-fs/-/memory-fs-0.5.0.tgz", + "integrity": "sha512-jA0rdU5KoQMC0e6ppoNRtpp6vjFq6+NY7r8hywnC7V+1Xj/MtHwGIbB1QaK/dunyjWteJzmkpd7ooeWg10T7GA==", + "requires": { + "errno": "^0.1.3", + "readable-stream": "^2.0.1" + } + } } }, - "equal-length": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/equal-length/-/equal-length-1.0.1.tgz", - "integrity": "sha1-IcoRLUirJLTh5//A5TOdMf38J0w=" - }, "errno": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.7.tgz", @@ -2903,22 +2615,27 @@ } }, "es-abstract": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.13.0.tgz", - "integrity": "sha512-vDZfg/ykNxQVwup/8E1BZhVzFfBxs9NqMzGcvIJrqg5k2/5Za2bWo40dK2J1pgLngZ7c+Shh8lwYtLGyrwPutg==", + "version": "1.17.5", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.17.5.tgz", + "integrity": "sha512-BR9auzDbySxOcfog0tLECW8l28eRGpDpU3Dm3Hp4q/N+VtLTmyj4EUN088XZWQDW/hzj6sYRDXeOFsaAODKvpg==", "requires": { - "es-to-primitive": "^1.2.0", + "es-to-primitive": "^1.2.1", "function-bind": "^1.1.1", "has": "^1.0.3", - "is-callable": "^1.1.4", - "is-regex": "^1.0.4", - "object-keys": "^1.0.12" + "has-symbols": "^1.0.1", + "is-callable": "^1.1.5", + "is-regex": "^1.0.5", + "object-inspect": "^1.7.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.0", + "string.prototype.trimleft": "^2.1.1", + "string.prototype.trimright": "^2.1.1" } }, "es-to-primitive": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.0.tgz", - "integrity": "sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", "requires": { "is-callable": "^1.1.4", "is-date-object": "^1.0.1", @@ -2928,7 +2645,8 @@ "es6-error": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz", - "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==" + "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==", + "dev": true }, "escape-string-regexp": { "version": "1.0.5", @@ -2944,42 +2662,11 @@ "estraverse": "^4.1.1" } }, - "esm": { - "version": "3.2.22", - "resolved": "https://registry.npmjs.org/esm/-/esm-3.2.22.tgz", - "integrity": "sha512-z8YG7U44L82j1XrdEJcqZOLUnjxco8pO453gKOlaMD1/md1n/5QrscAmYG+oKUspsmDLuBFZrpbxI6aQ67yRxA==" - }, - "espower-location-detector": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/espower-location-detector/-/espower-location-detector-1.0.0.tgz", - "integrity": "sha1-oXt+zFnTDheeK+9z+0E3cEyzMbU=", - "requires": { - "is-url": "^1.2.1", - "path-is-absolute": "^1.0.0", - "source-map": "^0.5.0", - "xtend": "^4.0.0" - } - }, "esprima": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" }, - "espurify": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/espurify/-/espurify-1.8.1.tgz", - "integrity": "sha512-ZDko6eY/o+D/gHCWyHTU85mKDgYcS4FJj7S+YD6WIInm7GQ6AnOjmcL4+buFV/JOztVLELi/7MmuGU5NHta0Mg==", - "requires": { - "core-js": "^2.0.0" - }, - "dependencies": { - "core-js": { - "version": "2.6.5", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.5.tgz", - "integrity": "sha512-klh/kDpwX8hryYL14M9w/xei6vrv6sE8gTHDG7/T/+SEovB/G4ejwcfE/CBzO6Edsu+OETZMZ3wcX/EjUkrl5A==" - } - } - }, "esrecurse": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz", @@ -2989,19 +2676,19 @@ } }, "estraverse": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", - "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=" + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==" }, "esutils": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", - "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=" + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==" }, "events": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/events/-/events-3.0.0.tgz", - "integrity": "sha512-Dc381HFWJzEOhQ+d8pkNon++bk9h6cdAoAj4iE6Q4y6xgTzySWXlKn05/TVNpjnfRqi/X0EpJEJohPjNI3zpVA==" + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.1.0.tgz", + "integrity": "sha512-Rv+u8MLHNOdMjTAFeT3nCjHn2aGlx435FP/sDHNaRhDEMwyI/aB22Kj2qIN8R0cw3z28psEQLYwxVKLsKrMgWg==" }, "evp_bytestokey": { "version": "1.0.3", @@ -3162,72 +2849,68 @@ } }, "fable-babel-plugins": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/fable-babel-plugins/-/fable-babel-plugins-2.2.0.tgz", - "integrity": "sha512-4g8CIyXCILk5LLiwNPtvtrPy3YuV5eJV18SYJCZxu3A1BSKNvPGHLSg5YcFJ2zt4qmBvSkBewlQ2bVQYG+TnrQ==" + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/fable-babel-plugins/-/fable-babel-plugins-2.3.0.tgz", + "integrity": "sha512-alGBNw5HZJzTEznXKfypFEkD5aWsspbCcoVDu9j8Mqdi77dgp4BSjhYSg61mQEg9UluIAZxRM5lhGARYbU97DQ==" }, "fable-compiler": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/fable-compiler/-/fable-compiler-2.2.3.tgz", - "integrity": "sha512-cu5GJW/38PmXjmC1+f8oLEbcp63pf6dyMwrQFUWwqz1lCNuiHcfgUAS5A5M46EqHNlYBHc0v3fZcMFUFzNUeLg==" + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/fable-compiler/-/fable-compiler-2.5.1.tgz", + "integrity": "sha512-/fIjdBWxVJhyX/XNjxlse2N1/ZxWVm918EAxIshQI+n2S1jH8HD4R1Pt7Tcu1823w+PVOlh10+/WMREifSCmsA==" }, "fable-compiler-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/fable-compiler-js/-/fable-compiler-js-1.0.3.tgz", - "integrity": "sha512-cy+s9Ey0pEo1yA5nyVnPPWp1PSCzdyoOQZkfwRZFytZDmL8V3AmL7rbRmRq+JKOuKLvhN/WolTj2OaOKexSEGA==", + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/fable-compiler-js/-/fable-compiler-js-1.3.1.tgz", + "integrity": "sha512-2aI7sLolRzukxesGcDNfR45S8iuFtrRQoyB1QDOwTqaPXgZYn+0USp5eNP61piEt7RRm7n5buYVVL5B1/GZCgA==", "requires": { - "@babel/core": "^7.3.4", - "@babel/plugin-transform-modules-commonjs": "^7.2.0", - "fable-babel-plugins": "^2.2.0", - "fable-metadata": "^1.0.1", - "fable-standalone": "^1.0.3" + "@babel/core": "^7.7.5", + "@babel/plugin-transform-modules-commonjs": "^7.7.5", + "fable-babel-plugins": "^2.3.0", + "fable-metadata": "^1.4.0", + "fable-standalone": "^1.3.9", + "glob": "^7.1.6" } }, "fable-loader": { - "version": "2.1.6", - "resolved": "https://registry.npmjs.org/fable-loader/-/fable-loader-2.1.6.tgz", - "integrity": "sha512-dmtQvDl3B/szazOUzic6lUukNBOr5jL5cbt2BAdS3rFOutRN/iIFqofBFpQuR6TF3O7QgZVioxDwB+cfbW8tgA==", + "version": "2.1.9", + "resolved": "https://registry.npmjs.org/fable-loader/-/fable-loader-2.1.9.tgz", + "integrity": "sha512-ffFfAx4+92yGRjV7iZQOCzqsjQF1he6Lei6hDqfaW1Qjbyx9bhVa8jCX53+I1mhWEw2JWIQpFzwHnYwz2eT4Hw==", "requires": { - "fable-babel-plugins": "^2.2.0" + "fable-babel-plugins": "^2.3.0" } }, "fable-metadata": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/fable-metadata/-/fable-metadata-1.0.1.tgz", - "integrity": "sha512-ddxWZkGfQ6V/07u8hHxebInQXnr7nVMk6M3Jy3r8a3RXNY/8WxgxK91RIPqePjbEbcK9U0jy43xVUqVa93FiwQ==" + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/fable-metadata/-/fable-metadata-1.4.0.tgz", + "integrity": "sha512-8r/jLuCTAS2KqHb3vdGZCpOba8CNpR8p8uYmfD59np/LWK2/KST7OOv7t2vkSgc0tnbMUsh1FhW1MTgcpvz4eQ==" }, "fable-splitter": { - "version": "2.1.8", - "resolved": "https://registry.npmjs.org/fable-splitter/-/fable-splitter-2.1.8.tgz", - "integrity": "sha512-qAbkWowyZtvZI+Evy/wn8/4+Xw8n5D8s6PoFI1XVrlodl98EImc4RmG2IbaJVYC3EmShEcbjg2RGDdaC9fCWog==", + "version": "2.1.13", + "resolved": "https://registry.npmjs.org/fable-splitter/-/fable-splitter-2.1.13.tgz", + "integrity": "sha512-eNXQ0uGjCFE6CaJBPSr9J5Bocn66qXLscMmTV5YwjWBJEMG/9UR1TXBm4IPMEpT4tQbyYZI+Wj/hWRf3C7thOw==", "requires": { "@babel/core": "^7.1.6", "@babel/plugin-transform-modules-commonjs": "^7.1.0", "chalk": "^2.4.1", "chokidar": "^2.0.4", - "fable-babel-plugins": "^2.2.0", + "fable-babel-plugins": "^2.3.0", "fs-extra": "^7.0.0" } }, "fable-standalone": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/fable-standalone/-/fable-standalone-1.0.3.tgz", - "integrity": "sha512-lyeYtjGnGcB0cGHadbVSKX3Rt7zU0dSMzRYHw+d2U9pOT9LhT2arXAqxu6wpL67rtwvKekmv77PRuinVNT/wlw==" + "version": "1.3.10", + "resolved": "https://registry.npmjs.org/fable-standalone/-/fable-standalone-1.3.10.tgz", + "integrity": "sha512-ooCdO7CinjlrO6+guFi1yiLQxgOhc/aCbRCXRUGIWV9EWZEWVY2vG3I8bFtEnNUMnAzq6rbYNtjPjUxErIGCaQ==" }, "fast-deep-equal": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", - "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=" - }, - "fast-diff": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.2.0.tgz", - "integrity": "sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w==" + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.1.tgz", + "integrity": "sha512-8UEa58QDLauDNfpbrX55Q9jrGHThw2ZMdOky5Gl1CDtVeJDPVrG4Jxx1N8jw2gkWaff5UUuX1KJd+9zGe2B+ZA==" }, "fast-json-stable-stringify": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", - "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=" + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" }, "fd-slicer": { "version": "1.1.0", @@ -3238,23 +2921,21 @@ } }, "figgy-pudding": { - "version": "3.5.1", - "resolved": "https://registry.npmjs.org/figgy-pudding/-/figgy-pudding-3.5.1.tgz", - "integrity": "sha512-vNKxJHTEKNThjfrdJwHc7brvM6eVevuO5nTj6ez8ZQ1qbXTvGthucRF7S4vf2cr71QVnT70V34v0S1DyQsti0w==" - }, - "figures": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", - "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", - "requires": { - "escape-string-regexp": "^1.0.5" - } + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/figgy-pudding/-/figgy-pudding-3.5.2.tgz", + "integrity": "sha512-0btnI/H8f2pavGMN8w40mlSKOfTK2SVJmBfBeVIj3kNw0swwgzyRq0d5TJVOwodFmtvpPeWPN/MCcfuWF0Ezbw==" }, "file-type": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/file-type/-/file-type-5.2.0.tgz", "integrity": "sha1-LdvqfHP/42No365J3DOMBYwritY=" }, + "file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "optional": true + }, "filename-reserved-regex": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/filename-reserved-regex/-/filename-reserved-regex-2.0.0.tgz", @@ -3302,32 +2983,22 @@ } }, "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", + "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", "requires": { - "locate-path": "^3.0.0" + "locate-path": "^2.0.0" } }, "findup-sync": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-2.0.0.tgz", - "integrity": "sha1-kyaxSIwi0aYIhlCoaQGy2akKLLw=", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-3.0.0.tgz", + "integrity": "sha512-YbffarhcicEhOrm4CtrwdKBdCuz576RLdhJDsIfvNtxUuhdRet1qZcsMjqbePtAseKdAnDyM/IyXbu7PRPRLYg==", "requires": { "detect-file": "^1.0.0", - "is-glob": "^3.1.0", + "is-glob": "^4.0.0", "micromatch": "^3.0.4", "resolve-dir": "^1.0.1" - }, - "dependencies": { - "is-glob": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", - "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", - "requires": { - "is-extglob": "^2.1.0" - } - } } }, "flat": { @@ -3339,9 +3010,9 @@ }, "dependencies": { "is-buffer": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.3.tgz", - "integrity": "sha512-U15Q7MXTuZlrbymiz95PJpZxu8IlipAp4dtS3wOdgPXx3mqBnslrWU14kxfHB+Py/+2PVKSr37dMAgM2A4uArw==" + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.4.tgz", + "integrity": "sha512-Kq1rokWXOPXWuaMAqZiJW4XxsmD9zGx9q4aePabbn3qCRGedtH7Cm+zV8WETitMfu1wdh+Rvd6w5egwSngUX2A==" } } }, @@ -3359,6 +3030,59 @@ "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=" }, + "foreground-child": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-2.0.0.tgz", + "integrity": "sha512-dCIq9FpEcyQyXKCkyzmlPTFNgrCzPudOe+mhvJU5zAtlBnGVy2yKxtfsxK2tQBThwq225jcvBjpw1Gr40uzZCA==", + "dev": true, + "requires": { + "cross-spawn": "^7.0.0", + "signal-exit": "^3.0.2" + }, + "dependencies": { + "cross-spawn": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.2.tgz", + "integrity": "sha512-PD6G8QG3S4FK/XCGFbEQrDqO2AnMMsy0meR7lerlIOHAAbkuavGU/pOqprrlvfTNjvowivTeBsjebAL0NSoMxw==", + "dev": true, + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + } + }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + } + } + }, "fragment-cache": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", @@ -3376,6 +3100,12 @@ "readable-stream": "^2.0.0" } }, + "fromentries": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/fromentries/-/fromentries-1.2.0.tgz", + "integrity": "sha512-33X7H/wdfO99GdRLLgkjUrD4geAFdq/Uv0kl3HD4da6HDixd2GUg8Mw7dahLCV9r/EARkmtYBB6Tch4EEokFTQ==", + "dev": true + }, "fs-constants": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", @@ -3413,13 +3143,14 @@ "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" }, "fsevents": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.7.tgz", - "integrity": "sha512-Pxm6sI2MeBD7RdD12RYsqaP0nMiwx8eZBXCa6z2L+mRHm2DYrOYwihmhjpkdjUHwQhslWQjRpEgNq4XvBmaAuw==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.12.tgz", + "integrity": "sha512-Ggd/Ktt7E7I8pxZRbGIs7vwqAPscSESMrCSkx2FtWeqmheJgCo2R74fTsZFCifr0VTPwqRpPv17+6b8Zp7th0Q==", "optional": true, "requires": { - "nan": "^2.9.2", - "node-pre-gyp": "^0.10.0" + "bindings": "^1.5.0", + "nan": "^2.12.1", + "node-pre-gyp": "*" }, "dependencies": { "abbrev": { @@ -3461,7 +3192,7 @@ } }, "chownr": { - "version": "1.1.1", + "version": "1.1.4", "bundled": true, "optional": true }, @@ -3486,11 +3217,11 @@ "optional": true }, "debug": { - "version": "2.6.9", + "version": "3.2.6", "bundled": true, "optional": true, "requires": { - "ms": "2.0.0" + "ms": "^2.1.1" } }, "deep-extend": { @@ -3509,11 +3240,11 @@ "optional": true }, "fs-minipass": { - "version": "1.2.5", + "version": "1.2.7", "bundled": true, "optional": true, "requires": { - "minipass": "^2.2.1" + "minipass": "^2.6.0" } }, "fs.realpath": { @@ -3537,7 +3268,7 @@ } }, "glob": { - "version": "7.1.3", + "version": "7.1.6", "bundled": true, "optional": true, "requires": { @@ -3563,7 +3294,7 @@ } }, "ignore-walk": { - "version": "3.0.1", + "version": "3.0.3", "bundled": true, "optional": true, "requires": { @@ -3580,7 +3311,7 @@ } }, "inherits": { - "version": "2.0.3", + "version": "2.0.4", "bundled": true, "optional": true }, @@ -3611,12 +3342,12 @@ } }, "minimist": { - "version": "0.0.8", + "version": "1.2.5", "bundled": true, "optional": true }, "minipass": { - "version": "2.3.5", + "version": "2.9.0", "bundled": true, "optional": true, "requires": { @@ -3625,38 +3356,38 @@ } }, "minizlib": { - "version": "1.2.1", + "version": "1.3.3", "bundled": true, "optional": true, "requires": { - "minipass": "^2.2.1" + "minipass": "^2.9.0" } }, "mkdirp": { - "version": "0.5.1", + "version": "0.5.3", "bundled": true, "optional": true, "requires": { - "minimist": "0.0.8" + "minimist": "^1.2.5" } }, "ms": { - "version": "2.0.0", + "version": "2.1.2", "bundled": true, "optional": true }, "needle": { - "version": "2.2.4", + "version": "2.3.3", "bundled": true, "optional": true, "requires": { - "debug": "^2.1.2", + "debug": "^3.2.6", "iconv-lite": "^0.4.4", "sax": "^1.2.4" } }, "node-pre-gyp": { - "version": "0.10.3", + "version": "0.14.0", "bundled": true, "optional": true, "requires": { @@ -3669,11 +3400,11 @@ "rc": "^1.2.7", "rimraf": "^2.6.1", "semver": "^5.3.0", - "tar": "^4" + "tar": "^4.4.2" } }, "nopt": { - "version": "4.0.1", + "version": "4.0.3", "bundled": true, "optional": true, "requires": { @@ -3682,17 +3413,26 @@ } }, "npm-bundled": { - "version": "1.0.5", + "version": "1.1.1", + "bundled": true, + "optional": true, + "requires": { + "npm-normalize-package-bin": "^1.0.1" + } + }, + "npm-normalize-package-bin": { + "version": "1.0.1", "bundled": true, "optional": true }, "npm-packlist": { - "version": "1.2.0", + "version": "1.4.8", "bundled": true, "optional": true, "requires": { "ignore-walk": "^3.0.1", - "npm-bundled": "^1.0.1" + "npm-bundled": "^1.0.1", + "npm-normalize-package-bin": "^1.0.1" } }, "npmlog": { @@ -3749,7 +3489,7 @@ "optional": true }, "process-nextick-args": { - "version": "2.0.0", + "version": "2.0.1", "bundled": true, "optional": true }, @@ -3762,17 +3502,10 @@ "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" - }, - "dependencies": { - "minimist": { - "version": "1.2.0", - "bundled": true, - "optional": true - } } }, "readable-stream": { - "version": "2.3.6", + "version": "2.3.7", "bundled": true, "optional": true, "requires": { @@ -3786,7 +3519,7 @@ } }, "rimraf": { - "version": "2.6.3", + "version": "2.7.1", "bundled": true, "optional": true, "requires": { @@ -3809,7 +3542,7 @@ "optional": true }, "semver": { - "version": "5.6.0", + "version": "5.7.1", "bundled": true, "optional": true }, @@ -3855,17 +3588,17 @@ "optional": true }, "tar": { - "version": "4.4.8", + "version": "4.4.13", "bundled": true, "optional": true, "requires": { "chownr": "^1.1.1", "fs-minipass": "^1.2.5", - "minipass": "^2.3.4", - "minizlib": "^1.1.1", + "minipass": "^2.8.6", + "minizlib": "^1.2.1", "mkdirp": "^0.5.0", "safe-buffer": "^5.1.2", - "yallist": "^3.0.2" + "yallist": "^3.0.3" } }, "util-deprecate": { @@ -3887,7 +3620,7 @@ "optional": true }, "yallist": { - "version": "3.0.3", + "version": "3.1.1", "bundled": true, "optional": true } @@ -3898,15 +3631,15 @@ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" }, - "get-caller-file": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.3.tgz", - "integrity": "sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==" + "gensync": { + "version": "1.0.0-beta.1", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.1.tgz", + "integrity": "sha512-r8EC6NO1sngH/zdD9fiRDLdcgnbayXah+mLgManTaIZJqEC1MZstmnox8KpnI2/fxQwrp5OpCOYWLp4rBl4Jcg==" }, - "get-port": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/get-port/-/get-port-4.2.0.tgz", - "integrity": "sha512-/b3jarXkH8KJoOMQc3uVGHASwGLPq3gSFJ7tgJm2diza+bydJPTGOibin2steecKeOylE8oY2JERlVWkAJO6yw==" + "get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" }, "get-proxy": { "version": "2.1.0", @@ -3962,9 +3695,9 @@ } }, "glob": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", - "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -4002,13 +3735,23 @@ } }, "global-modules": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", - "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-2.0.0.tgz", + "integrity": "sha512-NGbfmJBp9x8IxyJSd1P+otYK8vonoJactOogrVfFRIAEY1ukil8RSKDz2Yo7wh1oihl51l/r6W4epkeKJHqL8A==", "requires": { - "global-prefix": "^1.0.1", - "is-windows": "^1.0.1", - "resolve-dir": "^1.0.0" + "global-prefix": "^3.0.0" + }, + "dependencies": { + "global-prefix": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-3.0.0.tgz", + "integrity": "sha512-awConJSVCHVGND6x3tmMaKcQvwXLhjdkmomy2W+Goaui8YPgYgXJZewhg3fWC+DlfqqQuWg8AwqjGTD2nAPVWg==", + "requires": { + "ini": "^1.3.5", + "kind-of": "^6.0.2", + "which": "^1.3.1" + } + } } }, "global-prefix": { @@ -4024,57 +3767,35 @@ } }, "globals": { - "version": "11.11.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.11.0.tgz", - "integrity": "sha512-WHq43gS+6ufNOEqlrDBxVEbb8ntfXrfAUU2ZOpCxrBdGKW3gyv8mCxAfIBD0DroPKGrJ2eSsXsLtY9MPntsyTw==" - }, - "globby": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/globby/-/globby-7.1.1.tgz", - "integrity": "sha1-+yzP+UAfhgCUXfral0QMypcrhoA=", - "requires": { - "array-union": "^1.0.1", - "dir-glob": "^2.0.0", - "glob": "^7.1.2", - "ignore": "^3.3.5", - "pify": "^3.0.0", - "slash": "^1.0.0" - }, - "dependencies": { - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=" - }, - "slash": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-1.0.0.tgz", - "integrity": "sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU=" - } - } + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==" }, "got": { - "version": "6.7.1", - "resolved": "https://registry.npmjs.org/got/-/got-6.7.1.tgz", - "integrity": "sha1-JAzQV4WpoY5WHcG0S0HHY+8ejbA=", + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/got/-/got-7.1.0.tgz", + "integrity": "sha512-Y5WMo7xKKq1muPsxD+KmrR8DH5auG7fBdDVueZwETwV6VytKyU9OX/ddpq2/1hp1vIPvVb4T81dKQz3BivkNLw==", "requires": { - "create-error-class": "^3.0.0", + "decompress-response": "^3.2.0", "duplexer3": "^0.1.4", "get-stream": "^3.0.0", - "is-redirect": "^1.0.0", + "is-plain-obj": "^1.1.0", "is-retry-allowed": "^1.0.0", "is-stream": "^1.0.0", + "isurl": "^1.0.0-alpha5", "lowercase-keys": "^1.0.0", + "p-cancelable": "^0.3.0", + "p-timeout": "^1.1.1", "safe-buffer": "^5.0.1", "timed-out": "^4.0.0", - "unzip-response": "^2.0.1", - "url-parse-lax": "^1.0.0" + "url-parse-lax": "^1.0.0", + "url-to-options": "^1.0.1" } }, "graceful-fs": { - "version": "4.1.15", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", - "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==" + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.3.tgz", + "integrity": "sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ==" }, "graceful-readlink": { "version": "1.0.1", @@ -4094,21 +3815,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -4120,9 +3826,9 @@ "integrity": "sha512-3ToOva++HaW+eCpgqZrCfN51IPB+7bJNVT6CUATzueB5Heb8o6Nam0V3HG5dlDvZU1Gn5QLcbahiKw/XVk5JJw==" }, "has-symbols": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.0.tgz", - "integrity": "sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q=" + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", + "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==" }, "has-to-string-tag-x": { "version": "1.4.1", @@ -4180,11 +3886,21 @@ } }, "hasha": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/hasha/-/hasha-3.0.0.tgz", - "integrity": "sha1-UqMvq4Vp1BymmmH/GiFPjrfIvTk=", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/hasha/-/hasha-5.2.0.tgz", + "integrity": "sha512-2W+jKdQbAdSIrggA8Q35Br8qKadTrqCTC8+XZvBWepKDK6m9XkX6Iz1a2yh2KP01kzAR/dpuMeUnocoLYDcskw==", + "dev": true, "requires": { - "is-stream": "^1.0.1" + "is-stream": "^2.0.0", + "type-fest": "^0.8.0" + }, + "dependencies": { + "is-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz", + "integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==", + "dev": true + } } }, "he": { @@ -4211,9 +3927,15 @@ } }, "hosted-git-info": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.7.1.tgz", - "integrity": "sha512-7T/BxH19zbcCTa8XkMlbK5lTo1WtgkFi3GvdWEyNuc4Vex7/9Dqbnpsf4JMydcfj9HCg4zUWFTL3Za6lapg5/w==" + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.8.tgz", + "integrity": "sha512-f/wzC2QaWBs7t9IYqB4T3sR1xviIViXJRJTWBlx2Gf3g0Xi5vI7Yy4koXQ1c9OYDGHN9sBy1DQ2AB8fqZBWhUg==" + }, + "html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true }, "https-browserify": { "version": "1.0.0", @@ -4247,11 +3969,6 @@ "resolved": "https://registry.npmjs.org/iferr/-/iferr-0.1.5.tgz", "integrity": "sha1-xg7taebY/bazEEofy8ocGS3FtQE=" }, - "ignore": { - "version": "3.3.10", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.10.tgz", - "integrity": "sha512-Pgs951kaMm5GXP7MOvxERINe3gsaVjUWFm+UZPSq9xYriQAksyhg0csnS0KXSNRD5NmNdapXEpjxG49+AKh/ug==" - }, "ignore-by-default": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", @@ -4277,14 +3994,17 @@ "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=" }, "indent-string": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-3.2.0.tgz", - "integrity": "sha1-Sl/W0nzDMvN+VBmlBNu4NxBckok=" + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-2.1.0.tgz", + "integrity": "sha1-ji1INIdCEhtKghi3oTfppSBJ3IA=", + "requires": { + "repeating": "^2.0.0" + } }, - "indexof": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/indexof/-/indexof-0.0.1.tgz", - "integrity": "sha1-gtwzbSMrkGIXnQWrMpOmYFn9Q10=" + "infer-owner": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/infer-owner/-/infer-owner-1.0.4.tgz", + "integrity": "sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A==" }, "inflight": { "version": "1.0.6", @@ -4296,9 +4016,9 @@ } }, "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, "ini": { "version": "1.3.5", @@ -4323,11 +4043,6 @@ "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-2.0.0.tgz", "integrity": "sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==" }, - "irregular-plurals": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/irregular-plurals/-/irregular-plurals-2.0.0.tgz", - "integrity": "sha512-Y75zBYLkh0lJ9qxeHlMjQ7bSbyiSqNW/UOPWDmzC7cXskL1hekSITh1Oc6JV0XCWWZ9DE8VYSB71xocLk3gmGw==" - }, "is-accessor-descriptor": { "version": "0.1.6", "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", @@ -4365,16 +4080,16 @@ "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==" }, "is-callable": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.4.tgz", - "integrity": "sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA==" + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.5.tgz", + "integrity": "sha512-ESKv5sMCJB2jnHTWZ3O5itG+O128Hsus4K4Qh1h2/cgn2vbgnLSVqfV46AeJA9D5EeeLa9w81KUXMtn34zhX+Q==" }, "is-ci": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz", - "integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-1.2.1.tgz", + "integrity": "sha512-s6tfsaQaQi3JNciBH6shVqEDvhGut0SUXr31ag8Pd8BBbVVlcGfWhpPmEOoM6RJ5TFhbypvf5yyRw/VXW1IiWg==", "requires": { - "ci-info": "^2.0.0" + "ci-info": "^1.5.0" } }, "is-data-descriptor": { @@ -4396,9 +4111,9 @@ } }, "is-date-object": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.1.tgz", - "integrity": "sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=" + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.2.tgz", + "integrity": "sha512-USlDT524woQ08aoZFzh3/Z6ch9Y/EWXEHQ/AaRN0SkKq4t2Jw2R2339tSXmwuVoY7LLlBCbOIlx2myP/L5zk0g==" }, "is-descriptor": { "version": "0.1.6", @@ -4417,11 +4132,6 @@ } } }, - "is-error": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/is-error/-/is-error-2.2.1.tgz", - "integrity": "sha1-aEqW2EB2V3yY9M20DG0mpRI78Zw=" - }, "is-extendable": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", @@ -4433,12 +4143,9 @@ "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=" }, "is-finite": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", - "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", - "requires": { - "number-is-nan": "^1.0.0" - } + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.1.0.tgz", + "integrity": "sha512-cdyMtqX/BOqqNBBiKlIVkytNHm49MtMlYyn1zxzvJKWmFMlGzm+ry5BBfYyeY9YmNKbRSo/o7OX9w9ale0wg3w==" }, "is-fullwidth-code-point": { "version": "2.0.0", @@ -4500,27 +4207,6 @@ "resolved": "https://registry.npmjs.org/is-object/-/is-object-1.0.1.tgz", "integrity": "sha1-iVJojF7C/9awPsyF52ngKQMINHA=" }, - "is-observable": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-observable/-/is-observable-1.1.0.tgz", - "integrity": "sha512-NqCa4Sa2d+u7BWc6CukaObG3Fh+CU9bvixbpcXYhy2VvYS7vVGIdAgnIS5Ks3A/cqk4rebLJ9s8zBstT2aKnIA==", - "requires": { - "symbol-observable": "^1.1.0" - } - }, - "is-path-cwd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-2.0.0.tgz", - "integrity": "sha512-m5dHHzpOXEiv18JEORttBO64UgTEypx99vCxQLjbBvGhOJxnTNglYoFXxwo6AbsQb79sqqycQEHv2hWkHZAijA==" - }, - "is-path-in-cwd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-path-in-cwd/-/is-path-in-cwd-2.0.0.tgz", - "integrity": "sha512-6Vz5Gc9s/sDA3JBVu0FzWufm8xaBsqy1zn8Q6gmvGP6nSDMw78aS4poBNeatWjaRpTpxxLn1WOndAiOlk+qY8A==", - "requires": { - "is-path-inside": "^1.0.0" - } - }, "is-path-inside": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-1.0.1.tgz", @@ -4542,28 +4228,23 @@ "isobject": "^3.0.1" } }, - "is-promise": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", - "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=" - }, "is-redirect": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-redirect/-/is-redirect-1.0.0.tgz", "integrity": "sha1-HQPd7VO9jbDzDCbk+V02/HyH3CQ=" }, "is-regex": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz", - "integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=", + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.5.tgz", + "integrity": "sha512-vlKW17SNq44owv5AQR3Cq0bQPEb8+kF3UKZ2fiZNOWtztYE5i0CzCZxFDwO58qAOWtxdBRVO/V5Qin1wjCqFYQ==", "requires": { - "has": "^1.0.1" + "has": "^1.0.3" } }, "is-retry-allowed": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-1.1.0.tgz", - "integrity": "sha1-EaBgVotnM5REAz0BJaYaINVk+zQ=" + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-1.2.0.tgz", + "integrity": "sha512-RUbUeKwvm3XG2VYamhJL1xFktgjvPzL0Hq8C+6yrWIswDy3BIXGqCxhxkc30N9jqK311gVU137K8Ei55/zVJRg==" }, "is-stream": { "version": "1.1.0", @@ -4571,17 +4252,18 @@ "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=" }, "is-symbol": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.2.tgz", - "integrity": "sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.3.tgz", + "integrity": "sha512-OwijhaRSgqvhm/0ZdAcXNZt9lYdKFpcRDT5ULUuYXPoT794UNOdU+gpT6Rzo7b4V2HUl/op6GqY894AZwv9faQ==", "requires": { - "has-symbols": "^1.0.0" + "has-symbols": "^1.0.1" } }, - "is-url": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/is-url/-/is-url-1.2.4.tgz", - "integrity": "sha512-ITvGim8FhRiYe4IQ5uHSkj7pVaPDrCTkNd3yq3cV7iZAcJdHTUMPMEHcqSOy9xZ9qFenQCvi+2wjH9a1nXqHww==" + "is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", + "dev": true }, "is-utf8": { "version": "0.2.1", @@ -4593,6 +4275,11 @@ "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==" }, + "is-wsl": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-1.1.0.tgz", + "integrity": "sha1-HxbkqiKwTRM2tmGIpmrzxgDDpm0=" + }, "isarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", @@ -4608,6 +4295,213 @@ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=" }, + "istanbul-lib-coverage": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.0.0.tgz", + "integrity": "sha512-UiUIqxMgRDET6eR+o5HbfRYP1l0hqkWOs7vNxC/mggutCMUIhWMm8gAHb8tHlyfD3/l6rlgNA5cKdDzEAf6hEg==", + "dev": true + }, + "istanbul-lib-hook": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-hook/-/istanbul-lib-hook-3.0.0.tgz", + "integrity": "sha512-Pt/uge1Q9s+5VAZ+pCo16TYMWPBIl+oaNIjgLQxcX0itS6ueeaA+pEfThZpH8WxhFgCiEb8sAJY6MdUKgiIWaQ==", + "dev": true, + "requires": { + "append-transform": "^2.0.0" + } + }, + "istanbul-lib-instrument": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-4.0.1.tgz", + "integrity": "sha512-imIchxnodll7pvQBYOqUu88EufLCU56LMeFPZZM/fJZ1irYcYdqroaV+ACK1Ila8ls09iEYArp+nqyC6lW1Vfg==", + "dev": true, + "requires": { + "@babel/core": "^7.7.5", + "@babel/parser": "^7.7.5", + "@babel/template": "^7.7.4", + "@babel/traverse": "^7.7.4", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.0.0", + "semver": "^6.3.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "istanbul-lib-processinfo": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/istanbul-lib-processinfo/-/istanbul-lib-processinfo-2.0.2.tgz", + "integrity": "sha512-kOwpa7z9hme+IBPZMzQ5vdQj8srYgAtaRqeI48NGmAQ+/5yKiHLV0QbYqQpxsdEF0+w14SoB8YbnHKcXE2KnYw==", + "dev": true, + "requires": { + "archy": "^1.0.0", + "cross-spawn": "^7.0.0", + "istanbul-lib-coverage": "^3.0.0-alpha.1", + "make-dir": "^3.0.0", + "p-map": "^3.0.0", + "rimraf": "^3.0.0", + "uuid": "^3.3.3" + }, + "dependencies": { + "cross-spawn": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.2.tgz", + "integrity": "sha512-PD6G8QG3S4FK/XCGFbEQrDqO2AnMMsy0meR7lerlIOHAAbkuavGU/pOqprrlvfTNjvowivTeBsjebAL0NSoMxw==", + "dev": true, + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + } + }, + "make-dir": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.0.2.tgz", + "integrity": "sha512-rYKABKutXa6vXTXhoV18cBE7PaewPXHe/Bdq4v+ZLMhxbWApkFFplT0LcbMW+6BbjnQXzZ/sAvSE/JdguApG5w==", + "dev": true, + "requires": { + "semver": "^6.0.0" + } + }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true + }, + "rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + } + } + }, + "istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", + "dev": true, + "requires": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^3.0.0", + "supports-color": "^7.1.0" + }, + "dependencies": { + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "make-dir": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.0.2.tgz", + "integrity": "sha512-rYKABKutXa6vXTXhoV18cBE7PaewPXHe/Bdq4v+ZLMhxbWApkFFplT0LcbMW+6BbjnQXzZ/sAvSE/JdguApG5w==", + "dev": true, + "requires": { + "semver": "^6.0.0" + } + }, + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + }, + "supports-color": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", + "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "istanbul-lib-source-maps": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.0.tgz", + "integrity": "sha512-c16LpFRkR8vQXyHZ5nLpY35JZtzj1PQY1iZmesUbf1FZHbIupcWfjgOXBY9YHkLEQ6puz1u4Dgj6qmU/DisrZg==", + "dev": true, + "requires": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "istanbul-reports": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.0.2.tgz", + "integrity": "sha512-9tZvz7AiR3PEDNGiV9vIouQ/EAcqMXFmkcA1CDFTwOB98OZVDL0PH9glHotf5Ugp6GCOTypfzGWI/OqjWNCRUw==", + "dev": true, + "requires": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + } + }, "isurl": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isurl/-/isurl-1.0.0.tgz", @@ -4617,16 +4511,6 @@ "is-object": "^1.0.1" } }, - "js-levenshtein": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/js-levenshtein/-/js-levenshtein-1.1.6.tgz", - "integrity": "sha512-X2BB11YZtrRqY4EnQcLX5Rh373zbK4alC1FW7D7MBhL2gtcC17cTnr6DmfHZeS0s2rTHjUTMMHfG7gO8SSdw+g==" - }, - "js-string-escape": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/js-string-escape/-/js-string-escape-1.0.1.tgz", - "integrity": "sha1-4mJbrbwNZ8dTPp7cEGjFh65BN+8=" - }, "js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -4662,18 +4546,11 @@ "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" }, "json5": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.0.tgz", - "integrity": "sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.3.tgz", + "integrity": "sha512-KXPvOm8K9IJKFM0bmdn8QXh7udDh1g/giieX0NLCaMnb4hEiVFqnop2ImTXCc5e0/oHz3LTqmHGtExn5hfMkOA==", "requires": { - "minimist": "^1.2.0" - }, - "dependencies": { - "minimist": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=" - } + "minimist": "^1.2.5" } }, "jsonfile": { @@ -4685,20 +4562,40 @@ } }, "jsonist": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/jsonist/-/jsonist-2.1.0.tgz", - "integrity": "sha1-RHek0WzTd/rsWNjPhwt+OS9tf+k=", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/jsonist/-/jsonist-2.1.2.tgz", + "integrity": "sha512-8yqmWJAC2VaYoSKQAbsfgCpGY5o/1etWzx6ZxaZrC4iGaHrHUZEo+a2MyF8w+2uTavTlHdLWaZUoR19UfBstxQ==", "requires": { - "bl": "~1.2.0", - "hyperquest": "~2.1.2", + "bl": "~3.0.0", + "hyperquest": "~2.1.3", "json-stringify-safe": "~5.0.1", "xtend": "~4.0.1" + }, + "dependencies": { + "bl": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-3.0.0.tgz", + "integrity": "sha512-EUAyP5UHU5hxF8BPT0LKW8gjYLhq1DQIcneOX/pL/m2Alo+OYDQAJlHq+yseMP50Os2nHXOSic6Ss3vSQeyf4A==", + "requires": { + "readable-stream": "^3.0.1" + } + }, + "readable-stream": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", + "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + } } }, "kind-of": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", - "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==" + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==" }, "latest-version": { "version": "3.1.0", @@ -4716,21 +4613,43 @@ "invert-kv": "^2.0.0" } }, + "leven": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", + "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==" + }, + "levenary": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/levenary/-/levenary-1.1.1.tgz", + "integrity": "sha512-mkAdOIt79FD6irqjYSs4rdbnlT5vRonMEvBVPVb3XmevfS8kgRXwfes0dhPdEtzTWD/1eNE/Bm/G1iRt6DcnQQ==", + "requires": { + "leven": "^3.1.0" + } + }, "load-json-file": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", - "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", + "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", "requires": { "graceful-fs": "^4.1.2", - "parse-json": "^4.0.0", - "pify": "^3.0.0", - "strip-bom": "^3.0.0" + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0", + "strip-bom": "^2.0.0" }, "dependencies": { + "parse-json": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", + "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", + "requires": { + "error-ex": "^1.2.0" + } + }, "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=" + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=" } } }, @@ -4740,12 +4659,12 @@ "integrity": "sha512-Jsmr89RcXGIwivFY21FcRrisYZfvLMTWx5kOLc+JTxtpBOG6xML0vzbc6SEQG2FO9/4Fc3wW4LVcB5DmGflaRw==" }, "loader-utils": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.2.3.tgz", - "integrity": "sha512-fkpz8ejdnEMG3s37wGL07iSBDg99O9D5yflE9RGNH3hRdx9SOwYfnGYdZOUIZitN8E+E2vkq3MUMYMvPYl5ZZA==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.0.tgz", + "integrity": "sha512-qH0WSMBtn/oHuwjy/NucEgbx5dbxxnxup9s4PVXJUDHZBQY+s0NWA9rJf53RBnQZxfch7euUui7hpoAPvALZdA==", "requires": { "big.js": "^5.2.2", - "emojis-list": "^2.0.0", + "emojis-list": "^3.0.0", "json5": "^1.0.1" }, "dependencies": { @@ -4756,72 +4675,28 @@ "requires": { "minimist": "^1.2.0" } - }, - "minimist": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=" } } }, "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", + "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", "requires": { - "p-locate": "^3.0.0", + "p-locate": "^2.0.0", "path-exists": "^3.0.0" } }, "lodash": { - "version": "4.17.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" - }, - "lodash.clone": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.clone/-/lodash.clone-4.5.0.tgz", - "integrity": "sha1-GVhwRQ9aExkkeN9Lw9I9LeoZB7Y=" - }, - "lodash.clonedeep": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", - "integrity": "sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=" - }, - "lodash.clonedeepwith": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.clonedeepwith/-/lodash.clonedeepwith-4.5.0.tgz", - "integrity": "sha1-buMFc6A6GmDWcKYu8zwQzxr9vdQ=" - }, - "lodash.debounce": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", - "integrity": "sha1-gteb/zCmfEAF/9XiUVMArZyk168=" - }, - "lodash.difference": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.difference/-/lodash.difference-4.5.0.tgz", - "integrity": "sha1-nMtOUF1Ia5FlE0V3KIWi3yf9AXw=" - }, - "lodash.flatten": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz", - "integrity": "sha1-8xwiIlqWMtK7+OSt2+8kCqdlph8=" + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==" }, "lodash.flattendeep": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/lodash.flattendeep/-/lodash.flattendeep-4.4.0.tgz", - "integrity": "sha1-+wMJF/hqMTTlvJvsDWngAT3f7bI=" - }, - "lodash.islength": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/lodash.islength/-/lodash.islength-4.0.1.tgz", - "integrity": "sha1-Tpho1FJXXXUK/9NYyXlUPcIO1Xc=" - }, - "lodash.merge": { - "version": "4.6.1", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.1.tgz", - "integrity": "sha512-AOYza4+Hf5z1/0Hztxpm2/xiPZgi/cjMqdnKTUWTBSKchJlxXXuUSxCCl8rJlf4g6yww/j6mA8nC8Hw/EZWxKQ==" + "integrity": "sha1-+wMJF/hqMTTlvJvsDWngAT3f7bI=", + "dev": true }, "lodash.uniq": { "version": "4.5.0", @@ -4829,11 +4704,11 @@ "integrity": "sha1-0CJTc662Uq3BvILklFM5qEJ1R3M=" }, "log-symbols": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-2.2.0.tgz", - "integrity": "sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-3.0.0.tgz", + "integrity": "sha512-dSkNGuI7iG3mfvDzUuYZyvk5dD9ocYCYzNU6CYDE6+Xqd+gwme6Z00NS3dUh8mq/73HaEtT7m6W+yUPtU6BZnQ==", "requires": { - "chalk": "^2.0.1" + "chalk": "^2.4.2" } }, "loose-envify": { @@ -4876,11 +4751,6 @@ "semver": "^5.6.0" } }, - "mamacro": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/mamacro/-/mamacro-0.0.3.tgz", - "integrity": "sha512-qMEwh+UujcQ+kbz3T6V+wAmO2U8veoq2w+3wY8MquqwVA3jChfwY+Tk52GZKDfACEPjuZ7r2oJLejwpt8jtwTA==" - }, "map-age-cleaner": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/map-age-cleaner/-/map-age-cleaner-0.1.3.tgz", @@ -4895,9 +4765,9 @@ "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=" }, "map-obj": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-2.0.0.tgz", - "integrity": "sha1-plzSkIepJZi4eRJXpSPgISIqwfk=" + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", + "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=" }, "map-visit": { "version": "1.0.0", @@ -4907,27 +4777,6 @@ "object-visit": "^1.0.0" } }, - "matcher": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/matcher/-/matcher-1.1.1.tgz", - "integrity": "sha512-+BmqxWIubKTRKNWx/ahnCkk3mG8m7OturVlqq6HiojGJTd5hVYbgZm6WzcYPCoB+KBT4Vd6R7WSRG2OADNaCjg==", - "requires": { - "escape-string-regexp": "^1.0.4" - } - }, - "md5-hex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/md5-hex/-/md5-hex-2.0.0.tgz", - "integrity": "sha1-0FiOnxx0lUSS7NJKwKxs6ZfZLjM=", - "requires": { - "md5-o-matic": "^0.1.1" - } - }, - "md5-o-matic": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/md5-o-matic/-/md5-o-matic-0.1.1.tgz", - "integrity": "sha1-givM1l4RfFFPqxdrJZRdVBAKA8M=" - }, "md5.js": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", @@ -4946,13 +4795,6 @@ "map-age-cleaner": "^0.1.1", "mimic-fn": "^2.0.0", "p-is-promise": "^2.0.0" - }, - "dependencies": { - "mimic-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", - "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==" - } } }, "memory-fs": { @@ -4965,19 +4807,20 @@ } }, "meow": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/meow/-/meow-5.0.0.tgz", - "integrity": "sha512-CbTqYU17ABaLefO8vCU153ZZlprKYWDljcndKKDCFcYQITzWCXZAVk4QMFZPgvzrnUQ3uItnIE/LoUOwrT15Ig==", + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz", + "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", "requires": { - "camelcase-keys": "^4.0.0", - "decamelize-keys": "^1.0.0", + "camelcase-keys": "^2.0.0", + "decamelize": "^1.1.2", "loud-rejection": "^1.0.0", - "minimist-options": "^3.0.1", + "map-obj": "^1.0.1", + "minimist": "^1.1.3", "normalize-package-data": "^2.3.4", - "read-pkg-up": "^3.0.0", - "redent": "^2.0.0", - "trim-newlines": "^2.0.0", - "yargs-parser": "^10.0.0" + "object-assign": "^4.0.1", + "read-pkg-up": "^1.0.1", + "redent": "^1.0.0", + "trim-newlines": "^1.0.0" } }, "micromatch": { @@ -5010,14 +4853,14 @@ } }, "mime-db": { - "version": "1.39.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.39.0.tgz", - "integrity": "sha512-DTsrw/iWVvwHH+9Otxccdyy0Tgiil6TWK/xhfARJZF/QFhwOgZgOIvA2/VIGpM8U7Q8z5nDmdDWC6tuVMJNibw==" + "version": "1.43.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.43.0.tgz", + "integrity": "sha512-+5dsGEEovYbT8UY9yD7eE4XTc4UwJ1jBYlgaQQF38ENsKR3wj/8q8RFZrF9WIZpB2V1ArTVFUva8sAul1NzRzQ==" }, "mimic-fn": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", - "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==" + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==" }, "mimic-response": { "version": "1.0.1", @@ -5043,18 +4886,9 @@ } }, "minimist": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", - "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=" - }, - "minimist-options": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/minimist-options/-/minimist-options-3.0.2.tgz", - "integrity": "sha512-FyBrT/d0d4+uiZRbqznPXqw3IpZZG3gl3wKWiX784FycUKVwBt0uLBFkQrtE4tZOrgo78nZp2jnKz3L65T5LdQ==", - "requires": { - "arrify": "^1.0.1", - "is-plain-obj": "^1.1.0" - } + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" }, "mississippi": { "version": "3.0.0", @@ -5085,9 +4919,9 @@ } }, "mixin-deep": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.1.tgz", - "integrity": "sha512-8ZItLHeEgaqEvd5lYBXfm4EZSFCX29Jb9K+lAHhDKzReKBQKj3R+7NOF6tjqYi9t4oI8VUfaWITJQm86wnXGNQ==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.2.tgz", + "integrity": "sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA==", "requires": { "for-in": "^1.0.2", "is-extendable": "^1.0.1" @@ -5104,20 +4938,21 @@ } }, "mkdirp": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", - "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", "requires": { - "minimist": "0.0.8" + "minimist": "^1.2.5" } }, "mocha": { - "version": "6.1.4", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-6.1.4.tgz", - "integrity": "sha512-PN8CIy4RXsIoxoFJzS4QNnCH4psUCPWc4/rPrst/ecSJJbLBkubMiyGCP2Kj/9YnWbotFqAoeXyXMucj7gwCFg==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-7.1.1.tgz", + "integrity": "sha512-3qQsu3ijNS3GkWcccT5Zw0hf/rWvu1fTN9sPvEd81hlwsr30GX2GcDSSoBxo24IR8FelmrAydGC6/1J5QQP4WA==", "requires": { "ansi-colors": "3.2.3", "browser-stdout": "1.3.1", + "chokidar": "3.3.0", "debug": "3.2.6", "diff": "3.5.0", "escape-string-regexp": "1.0.5", @@ -5126,25 +4961,57 @@ "growl": "1.10.5", "he": "1.2.0", "js-yaml": "3.13.1", - "log-symbols": "2.2.0", + "log-symbols": "3.0.0", "minimatch": "3.0.4", - "mkdirp": "0.5.1", + "mkdirp": "0.5.3", "ms": "2.1.1", - "node-environment-flags": "1.0.5", + "node-environment-flags": "1.0.6", "object.assign": "4.1.0", "strip-json-comments": "2.0.1", "supports-color": "6.0.0", "which": "1.3.1", "wide-align": "1.1.3", - "yargs": "13.2.2", - "yargs-parser": "13.0.0", - "yargs-unparser": "1.5.0" + "yargs": "13.3.2", + "yargs-parser": "13.1.2", + "yargs-unparser": "1.6.0" }, "dependencies": { - "camelcase": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==" + "anymatch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.1.tgz", + "integrity": "sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg==", + "requires": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + } + }, + "binary-extensions": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.0.0.tgz", + "integrity": "sha512-Phlt0plgpIIBOGTT/ehfFnbNlfsDEiqmzE2KRXoX1bLIlir4X/MR+zSyBEkL05ffWgnRSf/DXv+WrUAVr93/ow==" + }, + "braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "requires": { + "fill-range": "^7.0.1" + } + }, + "chokidar": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.3.0.tgz", + "integrity": "sha512-dGmKLDdT3Gdl7fBUe8XK+gAtGmzy5Fn0XkkWQuYxGIgWVPPse2CxFA5mtrlD0TOHaHjEUqkWNyP1XdHoJES/4A==", + "requires": { + "anymatch": "~3.1.1", + "braces": "~3.0.2", + "fsevents": "~2.1.1", + "glob-parent": "~5.1.0", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.2.0" + } }, "debug": { "version": "3.2.6", @@ -5154,29 +5021,111 @@ "ms": "^2.1.1" } }, - "get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" + "fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "requires": { + "locate-path": "^3.0.0" + } + }, + "fsevents": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.1.2.tgz", + "integrity": "sha512-R4wDiBwZ0KzpgOWetKDug1FZcYhqYnUYKtfZYt4mD5SBz76q0KR4Q9o7GIPamsVPGmW3EYPPJ0dOOjvx32ldZA==", + "optional": true + }, + "glob": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", + "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "glob-parent": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.1.tgz", + "integrity": "sha512-FnI+VGOpnlGHWZxthPGR+QhR78fuiK0sNLkHQv+bL9fQi57lNNdquIbna/WrfROrolq8GK5Ek6BiMwqL/voRYQ==", + "requires": { + "is-glob": "^4.0.1" + } + }, + "is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "requires": { + "binary-extensions": "^2.0.0" + } + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==" + }, + "locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "requires": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + } + }, + "mkdirp": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.3.tgz", + "integrity": "sha512-P+2gwrFqx8lhew375MQHHeTlY8AuOJSrGf0R5ddkEndUkmwpgUob/vQuBD1V22/Cw1/lJr4x+EjllSezBThzBg==", + "requires": { + "minimist": "^1.2.5" + } }, "ms": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" }, - "require-main-filename": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", - "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "requires": { + "p-try": "^2.0.0" + } }, - "string-width": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", - "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", "requires": { - "emoji-regex": "^7.0.1", - "is-fullwidth-code-point": "^2.0.0", - "strip-ansi": "^5.1.0" + "p-limit": "^2.0.0" + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==" + }, + "readdirp": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.2.0.tgz", + "integrity": "sha512-crk4Qu3pmXwgxdSgGhgA/eXiJAPQiX4GMOZZMXnqKxHX7TaoL+3gQVo/WeuAiogr07DpnfjIMpXXa+PAIvwPGQ==", + "requires": { + "picomatch": "^2.0.4" } }, "supports-color": { @@ -5187,31 +5136,12 @@ "has-flag": "^3.0.0" } }, - "yargs": { - "version": "13.2.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.2.2.tgz", - "integrity": "sha512-WyEoxgyTD3w5XRpAQNYUB9ycVH/PQrToaTXdYXRdOXvEy1l19br+VJsc0vcO8PTGg5ro/l/GY7F/JMEBmI0BxA==", - "requires": { - "cliui": "^4.0.0", - "find-up": "^3.0.0", - "get-caller-file": "^2.0.1", - "os-locale": "^3.1.0", - "require-directory": "^2.1.1", - "require-main-filename": "^2.0.0", - "set-blocking": "^2.0.0", - "string-width": "^3.0.0", - "which-module": "^2.0.0", - "y18n": "^4.0.0", - "yargs-parser": "^13.0.0" - } - }, - "yargs-parser": { - "version": "13.0.0", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.0.0.tgz", - "integrity": "sha512-w2LXjoL8oRdRQN+hOyppuXs+V/fVAYtpcrRxZuF7Kt/Oc+Jr2uAcVntaUTNT6w5ihoWfFDpNY8CPx1QskxZ/pw==", + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "requires": { - "camelcase": "^5.0.0", - "decamelize": "^1.2.0" + "is-number": "^7.0.0" } } } @@ -5234,21 +5164,10 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" }, - "multimatch": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/multimatch/-/multimatch-3.0.0.tgz", - "integrity": "sha512-22foS/gqQfANZ3o+W7ST2x25ueHDVNWl/b9OlGcLpy/iKxjCpvcNCM51YCenUi7Mt/jAjjqv8JwZRs8YP5sRjA==", - "requires": { - "array-differ": "^2.0.3", - "array-union": "^1.0.2", - "arrify": "^1.0.1", - "minimatch": "^3.0.4" - } - }, "nan": { - "version": "2.13.2", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.13.2.tgz", - "integrity": "sha512-TghvYc72wlMGMVMluVo9WRJc0mB8KxxF/gZ4YYFy7V2ZQX9l7rgbPg7vjS9mt6U5HXODVFVI2bOduCzwOMv/lw==", + "version": "2.14.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.0.tgz", + "integrity": "sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg==", "optional": true }, "nanomatch": { @@ -5270,9 +5189,9 @@ } }, "neo-async": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.0.tgz", - "integrity": "sha512-MFh0d/Wa7vkKO3Y3LlacqAEeHK0mckVqzDieUKTT+KGxi+zIpeVsFxymkIiRpbpDziHc290Xr9A1O4Om7otoRA==" + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.1.tgz", + "integrity": "sha512-iyam8fBuCUpWeKPGpaNMetEocMt364qkCsfL9JuhjXX6dRnguRVOfk2GZaDpPjcOKiiXCPINZC1GczQ7iTq3Zw==" }, "nice-try": { "version": "1.0.5", @@ -5280,18 +5199,18 @@ "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==" }, "node-environment-flags": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/node-environment-flags/-/node-environment-flags-1.0.5.tgz", - "integrity": "sha512-VNYPRfGfmZLx0Ye20jWzHUjyTW/c+6Wq+iLhDzUI4XmhrDd9l/FozXV3F2xOaXjvp0co0+v1YSR3CMP6g+VvLQ==", + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/node-environment-flags/-/node-environment-flags-1.0.6.tgz", + "integrity": "sha512-5Evy2epuL+6TM0lCQGpFIj6KwiEsGh1SrHUhTbNX+sLbBtjidPZFAnVK9y5yU1+h//RitLbRHTIMyxQPtxMdHw==", "requires": { "object.getownpropertydescriptors": "^2.0.3", "semver": "^5.7.0" } }, "node-libs-browser": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/node-libs-browser/-/node-libs-browser-2.2.0.tgz", - "integrity": "sha512-5MQunG/oyOaBdttrL40dA7bUfPORLRWMUJLQtMg7nluxUvk5XwnLdL9twQHFAjRx/y7mIMkLKT9++qPbbk6BZA==", + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/node-libs-browser/-/node-libs-browser-2.2.1.tgz", + "integrity": "sha512-h/zcD8H9kaDZ9ALUWwlBUDo6TKF8a7qBSCSEGfjTVIYeqsioSKaAX+BN7NgiMGp6iSIXZ3PxgCu8KS3b71YK5Q==", "requires": { "assert": "^1.1.1", "browserify-zlib": "^0.2.0", @@ -5303,7 +5222,7 @@ "events": "^3.0.0", "https-browserify": "^1.0.0", "os-browserify": "^0.3.0", - "path-browserify": "0.0.0", + "path-browserify": "0.0.1", "process": "^0.11.10", "punycode": "^1.2.4", "querystring-es3": "^0.2.0", @@ -5315,13 +5234,13 @@ "tty-browserify": "0.0.0", "url": "^0.11.0", "util": "^0.11.0", - "vm-browserify": "0.0.4" + "vm-browserify": "^1.0.1" }, "dependencies": { "buffer": { - "version": "4.9.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.1.tgz", - "integrity": "sha1-bRu2AbB6TvztlwlBMgkwJ8lbwpg=", + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.2.tgz", + "integrity": "sha512-xq+q3SRMOxGivLhBNaUdC64hDTQwejJ+H0T/NB1XMtTVEwNTrfFF3gAxiyW0Bu/xWEGhjVKgUcMhCrUy2+uCWg==", "requires": { "base64-js": "^1.0.2", "ieee754": "^1.1.4", @@ -5340,12 +5259,146 @@ "resolved": "https://registry.npmjs.org/node-modules-regexp/-/node-modules-regexp-1.0.0.tgz", "integrity": "sha1-jZ2+KJZKSsVxLpExZCEHxx6Q7EA=" }, + "node-preload": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/node-preload/-/node-preload-0.2.1.tgz", + "integrity": "sha512-RM5oyBy45cLEoHqCeh+MNuFAxO0vTFBLskvQbOKnEE7YTTSN4tbN8QWDIPQ6L+WvKsB/qLEGpYe2ZZ9d4W9OIQ==", + "dev": true, + "requires": { + "process-on-spawn": "^1.0.0" + } + }, "node-releases": { - "version": "1.1.13", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-1.1.13.tgz", - "integrity": "sha512-fKZGviSXR6YvVPyc011NHuJDSD8gFQvLPmc2d2V3BS4gr52ycyQ1Xzs7a8B+Ax3Ni/W+5h1h4SqmzeoA8WZRmA==", + "version": "1.1.53", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-1.1.53.tgz", + "integrity": "sha512-wp8zyQVwef2hpZ/dJH7SfSrIPD6YoJz6BDQDpGEkcA0s3LpAQoxBIYmfIq6QAhC1DhwsyCgTaTTcONwX8qzCuQ==" + }, + "nodemon": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-2.0.2.tgz", + "integrity": "sha512-GWhYPMfde2+M0FsHnggIHXTqPDHXia32HRhh6H0d75Mt9FKUoCBvumNHr7LdrpPBTKxsWmIEOjoN+P4IU6Hcaw==", + "requires": { + "chokidar": "^3.2.2", + "debug": "^3.2.6", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.0.4", + "pstree.remy": "^1.1.7", + "semver": "^5.7.1", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.2", + "update-notifier": "^2.5.0" + }, + "dependencies": { + "anymatch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.1.tgz", + "integrity": "sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg==", + "requires": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + } + }, + "binary-extensions": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.0.0.tgz", + "integrity": "sha512-Phlt0plgpIIBOGTT/ehfFnbNlfsDEiqmzE2KRXoX1bLIlir4X/MR+zSyBEkL05ffWgnRSf/DXv+WrUAVr93/ow==" + }, + "braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "requires": { + "fill-range": "^7.0.1" + } + }, + "chokidar": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.3.1.tgz", + "integrity": "sha512-4QYCEWOcK3OJrxwvyyAOxFuhpvOVCYkr33LPfFNBjAD/w3sEzWsp2BUOkI4l9bHvWioAd0rc6NlHUOEaWkTeqg==", + "requires": { + "anymatch": "~3.1.1", + "braces": "~3.0.2", + "fsevents": "~2.1.2", + "glob-parent": "~5.1.0", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.3.0" + } + }, + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "fsevents": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.1.2.tgz", + "integrity": "sha512-R4wDiBwZ0KzpgOWetKDug1FZcYhqYnUYKtfZYt4mD5SBz76q0KR4Q9o7GIPamsVPGmW3EYPPJ0dOOjvx32ldZA==", + "optional": true + }, + "glob-parent": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.1.tgz", + "integrity": "sha512-FnI+VGOpnlGHWZxthPGR+QhR78fuiK0sNLkHQv+bL9fQi57lNNdquIbna/WrfROrolq8GK5Ek6BiMwqL/voRYQ==", + "requires": { + "is-glob": "^4.0.1" + } + }, + "is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "requires": { + "binary-extensions": "^2.0.0" + } + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==" + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "readdirp": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.3.0.tgz", + "integrity": "sha512-zz0pAkSPOXXm1viEwygWIPSPkcBYjW1xU5j/JBh5t9bGCJwa6f9+BJa6VaB2g+b55yVrmXzqkyLf4xaWYM0IkQ==", + "requires": { + "picomatch": "^2.0.7" + } + }, + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "requires": { + "is-number": "^7.0.0" + } + } + } + }, + "nopt": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-1.0.10.tgz", + "integrity": "sha1-bd0hvSoxQXuScn3Vhfim83YI6+4=", "requires": { - "semver": "^5.3.0" + "abbrev": "1" } }, "normalize-package-data": { @@ -5388,10 +5441,254 @@ "path-key": "^2.0.0" } }, - "number-is-nan": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", - "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=" + "nyc": { + "version": "15.0.1", + "resolved": "https://registry.npmjs.org/nyc/-/nyc-15.0.1.tgz", + "integrity": "sha512-n0MBXYBYRqa67IVt62qW1r/d9UH/Qtr7SF1w/nQLJ9KxvWF6b2xCHImRAixHN9tnMMYHC2P14uo6KddNGwMgGg==", + "dev": true, + "requires": { + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "caching-transform": "^4.0.0", + "convert-source-map": "^1.7.0", + "decamelize": "^1.2.0", + "find-cache-dir": "^3.2.0", + "find-up": "^4.1.0", + "foreground-child": "^2.0.0", + "glob": "^7.1.6", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-hook": "^3.0.0", + "istanbul-lib-instrument": "^4.0.0", + "istanbul-lib-processinfo": "^2.0.2", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.0.2", + "make-dir": "^3.0.0", + "node-preload": "^0.2.1", + "p-map": "^3.0.0", + "process-on-spawn": "^1.0.0", + "resolve-from": "^5.0.0", + "rimraf": "^3.0.0", + "signal-exit": "^3.0.2", + "spawn-wrap": "^2.0.0", + "test-exclude": "^6.0.0", + "yargs": "^15.0.2" + }, + "dependencies": { + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "dev": true, + "requires": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "find-cache-dir": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.1.tgz", + "integrity": "sha512-t2GDMt3oGC/v+BMwzmllWDuJF/xcDtE5j/fCGbqDD7OLuJkj0cfh1YSA5VKPvwMeLFLNDBkwOKZ2X85jGLVftQ==", + "dev": true, + "requires": { + "commondir": "^1.0.1", + "make-dir": "^3.0.2", + "pkg-dir": "^4.1.0" + } + }, + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "make-dir": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.0.2.tgz", + "integrity": "sha512-rYKABKutXa6vXTXhoV18cBE7PaewPXHe/Bdq4v+ZLMhxbWApkFFplT0LcbMW+6BbjnQXzZ/sAvSE/JdguApG5w==", + "dev": true, + "requires": { + "semver": "^6.0.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + }, + "pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "requires": { + "find-up": "^4.0.0" + } + }, + "resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true + }, + "rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + }, + "string-width": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", + "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", + "dev": true, + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" + } + }, + "strip-ansi": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.0" + } + }, + "wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "dev": true, + "requires": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + } + }, + "yargs": { + "version": "15.3.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.3.1.tgz", + "integrity": "sha512-92O1HWEjw27sBfgmXiixJWT5hRBp2eobqXicLtPBIDBhYB+1HpwZlXmbW2luivBJHBzki+7VyCLRtAkScbTBQA==", + "dev": true, + "requires": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.1" + } + }, + "yargs-parser": { + "version": "18.1.2", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.2.tgz", + "integrity": "sha512-hlIPNR3IzC1YuL1c2UwwDKpXlNFBqD1Fswwh1khz5+d8Cq/8yc/Mn0i+rQXduu8hcrFKvO7Eryk+09NecTQAAQ==", + "dev": true, + "requires": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + } + } }, "object-assign": { "version": "4.1.1", @@ -5426,10 +5723,15 @@ } } }, + "object-inspect": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.7.0.tgz", + "integrity": "sha512-a7pEHdh1xKIAgTySUGgLMx/xwDZskN1Ud6egYYN3EdRW4ZMPNEDUTF+hwy2LUC+Bl+SyLXANnwz/jyh/qutKUw==" + }, "object-keys": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.0.tgz", - "integrity": "sha512-6OO5X1+2tYkNyNEx6TsCxEqFfRWaqx6EtMiSbGrw8Ob8v9Ne+Hl8rBAgLBZn5wjEz3s/s6U1WXFUFOcxxAwUpg==" + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==" }, "object-visit": { "version": "1.0.1", @@ -5451,12 +5753,12 @@ } }, "object.getownpropertydescriptors": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/object.getownpropertydescriptors/-/object.getownpropertydescriptors-2.0.3.tgz", - "integrity": "sha1-h1jIRvW0B62rDyNuCYbxSwUcqhY=", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/object.getownpropertydescriptors/-/object.getownpropertydescriptors-2.1.0.tgz", + "integrity": "sha512-Z53Oah9A3TdLoblT7VKJaTDdXdT+lQO+cNpKVnya5JDe9uLvzu1YyY1yFDFrcxrlRgWrEFH0jJtD/IbuwjcEVg==", "requires": { - "define-properties": "^1.1.2", - "es-abstract": "^1.5.1" + "define-properties": "^1.1.3", + "es-abstract": "^1.17.0-next.1" } }, "object.pick": { @@ -5467,32 +5769,6 @@ "isobject": "^3.0.1" } }, - "observable-to-promise": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/observable-to-promise/-/observable-to-promise-0.5.0.tgz", - "integrity": "sha1-yCjw8NxH6fhq+KSXfF1VB2znqR8=", - "requires": { - "is-observable": "^0.2.0", - "symbol-observable": "^1.0.4" - }, - "dependencies": { - "is-observable": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/is-observable/-/is-observable-0.2.0.tgz", - "integrity": "sha1-s2ExHYPG5dcmyr9eJQsCNxBvWuI=", - "requires": { - "symbol-observable": "^0.2.2" - }, - "dependencies": { - "symbol-observable": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-0.2.4.tgz", - "integrity": "sha1-lag9smGG1q9+ehjb2XYKL4bQj0A=" - } - } - } - } - }, "once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -5501,27 +5777,6 @@ "wrappy": "1" } }, - "onetime": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", - "integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=", - "requires": { - "mimic-fn": "^1.0.0" - } - }, - "ora": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/ora/-/ora-3.4.0.tgz", - "integrity": "sha512-eNwHudNbO1folBP3JsZ19v9azXWtQZjICdr3Q0TDPIaeBQ3mXLrh54wM+er0+hSp+dWKf+Z8KM58CYzEyIYxYg==", - "requires": { - "chalk": "^2.4.2", - "cli-cursor": "^2.1.0", - "cli-spinners": "^2.0.0", - "log-symbols": "^2.2.0", - "strip-ansi": "^5.2.0", - "wcwidth": "^1.0.1" - } - }, "os-browserify": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz", @@ -5573,21 +5828,6 @@ } } }, - "os-tmpdir": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", - "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=" - }, - "output-file-sync": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/output-file-sync/-/output-file-sync-2.0.1.tgz", - "integrity": "sha512-mDho4qm7WgIXIGf4eYU1RHN2UU5tPfVYVSRwDJw0uTmj35DQUt/eNp19N7v6T3SrR0ESTEf2up2CGO73qI35zQ==", - "requires": { - "graceful-fs": "^4.1.11", - "is-plain-obj": "^1.1.0", - "mkdirp": "^0.5.1" - } - }, "p-cancelable": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-0.3.0.tgz", @@ -5612,30 +5852,34 @@ "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=" }, "p-is-promise": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-is-promise/-/p-is-promise-2.0.0.tgz", - "integrity": "sha512-pzQPhYMCAgLAKPWD2jC3Se9fEfrD9npNos0y150EeqZll7akhEgGhTW/slB6lHku8AvYGiJ+YJ5hfHKePPgFWg==" + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/p-is-promise/-/p-is-promise-2.1.0.tgz", + "integrity": "sha512-Y3W0wlRPK8ZMRbNq97l4M5otioeA5lm1z7bkNkxCka8HSPjR0xRWmpCmc9utiaLP9Jb1eD8BgeIxTW4AIF45Pg==" }, "p-limit": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz", - "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", + "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", "requires": { - "p-try": "^2.0.0" + "p-try": "^1.0.0" } }, "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", + "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", "requires": { - "p-limit": "^2.0.0" + "p-limit": "^1.1.0" } }, "p-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-map/-/p-map-2.0.0.tgz", - "integrity": "sha512-GO107XdrSUmtHxVoi60qc9tUl/KkNKm+X2CF4P9amalpGxv5YqVPJNfSb0wcA+syCopkZvYYIzW8OVTQW59x/w==" + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-3.0.0.tgz", + "integrity": "sha512-d3qXVTF/s+W+CdJ5A29wywV2n8CQQYahlgz2bFiA+4eVNJbHJodPZ+/gXwPGh0bOqA+j8S+6+ckmvLGPk1QpxQ==", + "dev": true, + "requires": { + "aggregate-error": "^3.0.0" + } }, "p-timeout": { "version": "1.2.1", @@ -5646,17 +5890,18 @@ } }, "p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==" + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", + "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=" }, "package-hash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/package-hash/-/package-hash-3.0.0.tgz", - "integrity": "sha512-lOtmukMDVvtkL84rJHI7dpTYq+0rli8N2wlnqUcBuDWCfVhRUfOmnR9SsoHFMLpACvEV60dX7rd0rFaYDZI+FA==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/package-hash/-/package-hash-4.0.0.tgz", + "integrity": "sha512-whdkPIooSu/bASggZ96BWVvZTRMOFxnyUG5PnTSGKoJE2gd5mbVNmR2Nj20QFzxYYgAXpoqC+AiXzl+UMRh7zQ==", + "dev": true, "requires": { "graceful-fs": "^4.1.15", - "hasha": "^3.0.0", + "hasha": "^5.0.0", "lodash.flattendeep": "^4.4.0", "release-zalgo": "^1.0.0" } @@ -5670,27 +5915,47 @@ "registry-auth-token": "^3.0.1", "registry-url": "^3.0.3", "semver": "^5.1.0" + }, + "dependencies": { + "got": { + "version": "6.7.1", + "resolved": "https://registry.npmjs.org/got/-/got-6.7.1.tgz", + "integrity": "sha1-JAzQV4WpoY5WHcG0S0HHY+8ejbA=", + "requires": { + "create-error-class": "^3.0.0", + "duplexer3": "^0.1.4", + "get-stream": "^3.0.0", + "is-redirect": "^1.0.0", + "is-retry-allowed": "^1.0.0", + "is-stream": "^1.0.0", + "lowercase-keys": "^1.0.0", + "safe-buffer": "^5.0.1", + "timed-out": "^4.0.0", + "unzip-response": "^2.0.1", + "url-parse-lax": "^1.0.0" + } + } } }, "pako": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.10.tgz", - "integrity": "sha512-0DTvPVU3ed8+HNXOu5Bs+o//Mbdj9VNQMUOe9oKCwh8l0GNwpTDMKCWbRjgtD291AWnkAgkqA/LOnQS8AmS1tw==" + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==" }, "parallel-transform": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/parallel-transform/-/parallel-transform-1.1.0.tgz", - "integrity": "sha1-1BDwZbBdojCB/NEPKIVMKb2jOwY=", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/parallel-transform/-/parallel-transform-1.2.0.tgz", + "integrity": "sha512-P2vSmIu38uIlvdcU7fDkyrxj33gTUy/ABO5ZUbGowxNCopBq/OoD42bP4UmMrJoPyk4Uqf0mu3mtWBhHCZD8yg==", "requires": { - "cyclist": "~0.2.2", + "cyclist": "^1.0.1", "inherits": "^2.0.3", "readable-stream": "^2.1.5" } }, "parse-asn1": { - "version": "5.1.4", - "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.4.tgz", - "integrity": "sha512-Qs5duJcuvNExRfFZ99HDD3z4mAi3r9Wl/FOjEOijlxwCZs7E7mW2vjTpgQ4J8LpTF8x5v+1Vn5UQFejmWT11aw==", + "version": "5.1.5", + "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.5.tgz", + "integrity": "sha512-jkMYn1dcJqF6d5CpU689bq7w/b5ALS9ROVSpQDPrZsqqesUJii9qutvoT5ltGedNXMO2e16YUWIghG9KxaViTQ==", "requires": { "asn1.js": "^4.0.0", "browserify-aes": "^1.0.0", @@ -5709,11 +5974,6 @@ "json-parse-better-errors": "^1.0.1" } }, - "parse-ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-2.0.0.tgz", - "integrity": "sha512-AddiXFSLLCqj+tCRJ9MrUtHZB4DWojO3tk0NVZ+g5MaMQHF2+p2ktqxuoXyPFLljz/aUK0Nfhd/uGWnhXVXEyA==" - }, "parse-passwd": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", @@ -5725,9 +5985,9 @@ "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=" }, "path-browserify": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.0.tgz", - "integrity": "sha1-oLhwcpquIUAFt9UDLsLLuw+0RRo=" + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.1.tgz", + "integrity": "sha512-BapA40NHICOS+USX9SN4tyhq+A2RrN/Ws5F0Z5aMHDp98Fl86lX8Oti8B7uN93L4Ifv4fHOEA+pQw87gmMO/lQ==" }, "path-dirname": { "version": "1.0.2", @@ -5760,17 +6020,19 @@ "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==" }, "path-type": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", - "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-1.1.0.tgz", + "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=", "requires": { - "pify": "^3.0.0" + "graceful-fs": "^4.1.2", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" }, "dependencies": { "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=" + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=" } } }, @@ -5791,6 +6053,11 @@ "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", "integrity": "sha1-elfrVQpng/kRUzH89GY9XI4AelA=" }, + "picomatch": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz", + "integrity": "sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==" + }, "pify": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", @@ -5817,47 +6084,60 @@ "node-modules-regexp": "^1.0.0" } }, - "pkg-conf": { + "pkg-dir": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pkg-conf/-/pkg-conf-3.0.0.tgz", - "integrity": "sha512-YOvV9hWNY9+abaZdgaZs4eyTzfeO1bwEYCYRskER2aP5ZWZAdrb/8YeOo95mb6tr01MR9ZUGArl1sMy2At/YWQ==", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", + "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", "requires": { - "find-up": "^3.0.0", - "load-json-file": "^5.2.0" + "find-up": "^3.0.0" }, "dependencies": { - "load-json-file": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-5.2.0.tgz", - "integrity": "sha512-HvjIlM2Y/RDHk1X6i4sGgaMTrAsnNrgQCJtuf5PEhbOV6MCJuMVZLMdlJRE0JGLMkF7b6O5zs9LcDxKIUt9CbQ==", + "find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", "requires": { - "graceful-fs": "^4.1.2", - "parse-json": "^4.0.0", - "pify": "^3.0.0", - "strip-bom": "^3.0.0" + "locate-path": "^3.0.0" } }, - "pify": { + "locate-path": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=" + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "requires": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "requires": { + "p-limit": "^2.0.0" + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==" } } }, - "pkg-dir": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", - "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", - "requires": { - "find-up": "^3.0.0" - } - }, - "plur": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/plur/-/plur-3.0.1.tgz", - "integrity": "sha512-lJl0ojUynAM1BZn58Pas2WT/TXeC1+bS+UqShl0x9+49AtOn7DixRXVzaC8qrDOIxNDmepKnLuMTH7NQmkX0PA==", + "pkg-up": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pkg-up/-/pkg-up-2.0.0.tgz", + "integrity": "sha1-yBmscoBZpGHKscOImivjxJoATX8=", "requires": { - "irregular-plurals": "^2.0.0" + "find-up": "^2.1.0" } }, "posix-character-classes": { @@ -5870,14 +6150,6 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, - "pretty-ms": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-4.0.0.tgz", - "integrity": "sha512-qG66ahoLCwpLXD09ZPHSCbUWYTqdosB7SMP4OffgTgL2PBKXMuUsrk5Bwg8q4qPkjTXsKBMr+YK3Ltd/6F9s/Q==", - "requires": { - "parse-ms": "^2.0.0" - } - }, "private": { "version": "0.1.8", "resolved": "https://registry.npmjs.org/private/-/private-0.1.8.tgz", @@ -5889,9 +6161,18 @@ "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=" }, "process-nextick-args": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", - "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==" + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" + }, + "process-on-spawn": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/process-on-spawn/-/process-on-spawn-1.0.0.tgz", + "integrity": "sha512-1WsPDsUSMmZH5LeMLegqkPDrsGgsWwk1Exipy2hvB0o/F0ASzbpIctSCcZIK1ykJvtTJULEH+20WOFjMvGnCTg==", + "dev": true, + "requires": { + "fromentries": "^1.2.0" + } }, "promise-inflight": { "version": "1.0.1", @@ -5913,6 +6194,11 @@ "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=" }, + "pstree.remy": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.7.tgz", + "integrity": "sha512-xsMgrUwRpuGskEzBFkH8NmTimbZ5PcPup0LA8JJkHIm2IMUbQcpo3yeLNWVrufEYjh8YwtSVh0xz6UeWc5Oh5A==" + }, "public-encrypt": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.3.tgz", @@ -5971,11 +6257,6 @@ "resolved": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz", "integrity": "sha1-nsYfeQSYdXB9aUFFlv2Qek1xHnM=" }, - "quick-lru": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-1.1.0.tgz", - "integrity": "sha1-Q2CxfGETatOAeDl/8RQW4Ybc+7g=" - }, "randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -6002,78 +6283,67 @@ "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" - }, - "dependencies": { - "minimist": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=" - } } }, "read-pkg": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", - "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-4.0.1.tgz", + "integrity": "sha1-ljYlN48+HE1IyFhytabsfV0JMjc=", "requires": { - "load-json-file": "^4.0.0", "normalize-package-data": "^2.3.2", - "path-type": "^3.0.0" + "parse-json": "^4.0.0", + "pify": "^3.0.0" + }, + "dependencies": { + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=" + } } }, "read-pkg-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-3.0.0.tgz", - "integrity": "sha1-PtSWaF26D4/hGNBpHcUfSh/5bwc=", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-1.0.1.tgz", + "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", "requires": { - "find-up": "^2.0.0", - "read-pkg": "^3.0.0" + "find-up": "^1.0.0", + "read-pkg": "^1.0.0" }, "dependencies": { "find-up": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", - "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", - "requires": { - "locate-path": "^2.0.0" - } - }, - "locate-path": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", - "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", + "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", "requires": { - "p-locate": "^2.0.0", - "path-exists": "^3.0.0" + "path-exists": "^2.0.0", + "pinkie-promise": "^2.0.0" } }, - "p-limit": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", - "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", + "path-exists": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", + "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", "requires": { - "p-try": "^1.0.0" + "pinkie-promise": "^2.0.0" } }, - "p-locate": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", - "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", + "read-pkg": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-1.1.0.tgz", + "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", "requires": { - "p-limit": "^1.1.0" + "load-json-file": "^1.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^1.0.0" } - }, - "p-try": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", - "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=" } } }, "readable-stream": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", - "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", "requires": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", @@ -6095,12 +6365,12 @@ } }, "redent": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/redent/-/redent-2.0.0.tgz", - "integrity": "sha1-wbIAe0LVfrE4kHmzyDM2OdXhzKo=", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-1.0.0.tgz", + "integrity": "sha1-z5Fqsf1fHxbfsggi3W7H9zDCr94=", "requires": { - "indent-string": "^3.0.0", - "strip-indent": "^2.0.0" + "indent-string": "^2.1.0", + "strip-indent": "^1.0.1" } }, "regenerate": { @@ -6109,19 +6379,25 @@ "integrity": "sha512-1G6jJVDWrt0rK99kBjvEtziZNCICAuvIPkSiUFIQxVP06RCVpq3dmDo2oi6ABpYaDYaTRr67BEhL8r1wgEZZKg==" }, "regenerate-unicode-properties": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-8.0.2.tgz", - "integrity": "sha512-SbA/iNrBUf6Pv2zU8Ekv1Qbhv92yxL4hiDa2siuxs4KKn4oOoMDHXjAf7+Nz9qinUQ46B1LcWEi/PhJfPWpZWQ==", + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-8.2.0.tgz", + "integrity": "sha512-F9DjY1vKLo/tPePDycuH3dn9H1OTPIkVD9Kz4LODu+F2C75mgjAJ7x/gwy6ZcSNRAAkhNlJSOHRe8k3p+K9WhA==", "requires": { "regenerate": "^1.4.0" } }, + "regenerator-runtime": { + "version": "0.13.5", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.5.tgz", + "integrity": "sha512-ZS5w8CpKFinUzOwW3c83oPeVXoNsrLsaCoLtJvAClH135j/R77RuymhiSErhm2lKcwSCIpmvIWSbDkIfAqKQlA==" + }, "regenerator-transform": { - "version": "0.13.4", - "resolved": "https://registry.npmjs.org/regenerator-transform/-/regenerator-transform-0.13.4.tgz", - "integrity": "sha512-T0QMBjK3J0MtxjPmdIMXm72Wvj2Abb0Bd4HADdfijwMdoIsyQZ6fWC7kDFhk2YinBBEMZDL7Y7wh0J1sGx3S4A==", + "version": "0.14.4", + "resolved": "https://registry.npmjs.org/regenerator-transform/-/regenerator-transform-0.14.4.tgz", + "integrity": "sha512-EaJaKPBI9GvKpvUz2mz4fhx7WPgvwRLY9v3hlNHWmAuJHI13T4nwKnNvm5RWJzEdnI5g5UwtOww+S8IdoUC2bw==", "requires": { - "private": "^0.1.6" + "@babel/runtime": "^7.8.4", + "private": "^0.1.8" } }, "regex-not": { @@ -6133,22 +6409,17 @@ "safe-regex": "^1.1.0" } }, - "regexp-tree": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/regexp-tree/-/regexp-tree-0.1.5.tgz", - "integrity": "sha512-nUmxvfJyAODw+0B13hj8CFVAxhe7fDEAgJgaotBu3nnR+IgGgZq59YedJP5VYTlkEfqjuK6TuRpnymKdatLZfQ==" - }, "regexpu-core": { - "version": "4.5.4", - "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-4.5.4.tgz", - "integrity": "sha512-BtizvGtFQKGPUcTy56o3nk1bGRp4SZOTYrDtGNlqCQufptV5IkkLN6Emw+yunAJjzf+C9FQFtvq7IoA3+oMYHQ==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-4.7.0.tgz", + "integrity": "sha512-TQ4KXRnIn6tz6tjnrXEkD/sshygKH/j5KzK86X8MkeHyZ8qst/LZ89j3X4/8HEIfHANTFIP/AbXakeRhWIl5YQ==", "requires": { "regenerate": "^1.4.0", - "regenerate-unicode-properties": "^8.0.2", - "regjsgen": "^0.5.0", - "regjsparser": "^0.6.0", + "regenerate-unicode-properties": "^8.2.0", + "regjsgen": "^0.5.1", + "regjsparser": "^0.6.4", "unicode-match-property-ecmascript": "^1.0.4", - "unicode-match-property-value-ecmascript": "^1.1.0" + "unicode-match-property-value-ecmascript": "^1.2.0" } }, "registry-auth-token": { @@ -6169,14 +6440,14 @@ } }, "regjsgen": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/regjsgen/-/regjsgen-0.5.0.tgz", - "integrity": "sha512-RnIrLhrXCX5ow/E5/Mh2O4e/oa1/jW0eaBKTSy3LaCj+M3Bqvm97GWDp2yUtzIs4LEn65zR2yiYGFqb2ApnzDA==" + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/regjsgen/-/regjsgen-0.5.1.tgz", + "integrity": "sha512-5qxzGZjDs9w4tzT3TPhCJqWdCc3RLYwy9J2NB0nm5Lz+S273lvWcpjaTGHsT1dc6Hhfq41uSEOw8wBmxrKOuyg==" }, "regjsparser": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.6.0.tgz", - "integrity": "sha512-RQ7YyokLiQBomUJuUG8iGVvkgOLxwyZM8k6d3q5SAXpg4r5TZJZigKFvC6PpD+qQ98bCDC5YelPeA3EucDoNeQ==", + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.6.4.tgz", + "integrity": "sha512-64O87/dPDgfk8/RQqC4gkZoGyyWFIEUTTh80CU6CWuK5vkCGyekIx+oKcEIYtP/RAxSQltCZHCNu/mdd7fqlJw==", "requires": { "jsesc": "~0.5.0" }, @@ -6192,6 +6463,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/release-zalgo/-/release-zalgo-1.0.0.tgz", "integrity": "sha1-CXALflB0Mpc5Mw5TXFqQ+2eFFzA=", + "dev": true, "requires": { "es6-error": "^4.0.1" } @@ -6225,19 +6497,14 @@ "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=" }, "require-main-filename": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz", - "integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=" - }, - "require-precompiled": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/require-precompiled/-/require-precompiled-0.1.0.tgz", - "integrity": "sha1-WhtS63Dr7UPrmC6XTIWrWVceVvo=" + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.10.0.tgz", - "integrity": "sha512-3sUr9aq5OfSg2S9pNtPA9hL1FVEAjvfOC4leW0SNf/mpnaakz2a9femSd6LqAww2RaFctwyf1lCqnTHuF1rxDg==", + "version": "1.15.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.15.1.tgz", + "integrity": "sha512-84oo6ZTtoTUpjgNEr5SJyzQhzL72gaRodsSfyxC/AXRvwu0Yse9H8eF9IpGo7b8YetZhlI6v7ZQ6bKBFV/6S7w==", "requires": { "path-parse": "^1.0.6" } @@ -6257,6 +6524,18 @@ "requires": { "expand-tilde": "^2.0.0", "global-modules": "^1.0.0" + }, + "dependencies": { + "global-modules": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", + "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==", + "requires": { + "global-prefix": "^1.0.1", + "is-windows": "^1.0.1", + "resolve-dir": "^1.0.0" + } + } } }, "resolve-from": { @@ -6269,24 +6548,15 @@ "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=" }, - "restore-cursor": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", - "integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=", - "requires": { - "onetime": "^2.0.0", - "signal-exit": "^3.0.2" - } - }, "ret": { "version": "0.1.15", "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==" }, "rimraf": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", - "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", "requires": { "glob": "^7.1.3" } @@ -6300,6 +6570,22 @@ "inherits": "^2.0.1" } }, + "rollup": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.6.1.tgz", + "integrity": "sha512-1RhFDRJeg027YjBO6+JxmVWkEZY0ASztHhoEUEWxOwkh4mjO58TFD6Uo7T7Y3FbmDpRTfKhM5NVxJyimCn0Elg==", + "requires": { + "fsevents": "~2.1.2" + }, + "dependencies": { + "fsevents": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.1.2.tgz", + "integrity": "sha512-R4wDiBwZ0KzpgOWetKDug1FZcYhqYnUYKtfZYt4mD5SBz76q0KR4Q9o7GIPamsVPGmW3EYPPJ0dOOjvx32ldZA==", + "optional": true + } + } + }, "run-queue": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/run-queue/-/run-queue-1.0.3.tgz", @@ -6309,9 +6595,9 @@ } }, "rxjs": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.4.0.tgz", - "integrity": "sha512-Z9Yfa11F6B9Sg/BK9MnqnQ+aQYicPLtilXBp2yUtDt2JRCE0h26d33EnfO3ZxoNxG0T92OUucP3Ct7cpfkdFfw==", + "version": "6.5.5", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.5.tgz", + "integrity": "sha512-WfQI+1gohdf0Dai/Bbmk5L5ItH5tYqm3ki2c5GdWhKjalzjg93N3avFjVStyZZz+A2Em+ZxKH5bNghw9UeylGQ==", "requires": { "tslib": "^1.9.0" } @@ -6330,13 +6616,12 @@ } }, "schema-utils": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-1.0.0.tgz", - "integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==", + "version": "2.6.5", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-2.6.5.tgz", + "integrity": "sha512-5KXuwKziQrTVHh8j/Uxz+QUbxkaLW9X/86NBlx/gnKgtsZA2GIVMUn17qWhRFwF8jdYb3Dig5hRO/W5mZqy6SQ==", "requires": { - "ajv": "^6.1.0", - "ajv-errors": "^1.0.0", - "ajv-keywords": "^3.1.0" + "ajv": "^6.12.0", + "ajv-keywords": "^3.4.1" } }, "seek-bzip": { @@ -6358,9 +6643,9 @@ } }, "semver": { - "version": "5.7.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz", - "integrity": "sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==" + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" }, "semver-diff": { "version": "2.1.0", @@ -6370,15 +6655,10 @@ "semver": "^5.0.3" } }, - "serialize-error": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-2.1.0.tgz", - "integrity": "sha1-ULZ51WNc34Rme9yOWa9OW4HV9go=" - }, "serialize-javascript": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-1.6.1.tgz", - "integrity": "sha512-A5MOagrPFga4YaKQSWHryl7AXvbQkEqpw4NNYMTNYUNV51bA8ABHgYFpqKx+YFFrw59xMV1qGH1R4AgoNIVgCw==" + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-2.1.2.tgz", + "integrity": "sha512-rs9OggEUF0V4jUSecXazOYsLfu7OGK2qIn3c7IPBiffz32XniEp/TX9Xmc9LQfK2nQ2QKHvZ2oygKUGU0lG4jQ==" }, "set-blocking": { "version": "2.0.0", @@ -6386,9 +6666,9 @@ "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=" }, "set-value": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.0.tgz", - "integrity": "sha512-hw0yxk9GT/Hr5yJEYnHNKYXkIA8mVJgd9ditYZCe16ZczcaELYYcfvaXesNACk2O8O0nTiPQcQhGUQj8JLzeeg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.1.tgz", + "integrity": "sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw==", "requires": { "extend-shallow": "^2.0.1", "is-extendable": "^0.1.1", @@ -6434,9 +6714,9 @@ "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=" }, "signal-exit": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", - "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=" + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", + "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==" }, "simple-mime": { "version": "0.1.0", @@ -6448,19 +6728,6 @@ "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==" }, - "slice-ansi": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-1.0.0.tgz", - "integrity": "sha512-POqxBK6Lb3q6s047D/XsDVNPnF9Dl8JSaqe9h9lURl0OdNqy/ujDrOiIHtsqXMGbWWTIomRzAMaTyawAU//Reg==", - "requires": { - "is-fullwidth-code-point": "^2.0.0" - } - }, - "slide": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/slide/-/slide-1.1.6.tgz", - "integrity": "sha1-VusCfWW00tzmyy4tMsTUr8nh1wc=" - }, "snapdragon": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", @@ -6585,11 +6852,11 @@ "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" }, "source-map-resolve": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.2.tgz", - "integrity": "sha512-MjqsvNwyz1s0k81Goz/9vRBe9SZdB09Bdw+/zYyO+3CuPk6fouTaxscHkgtE8jKvf01kVfl8riHzERQ/kefaSA==", + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.3.tgz", + "integrity": "sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw==", "requires": { - "atob": "^2.1.1", + "atob": "^2.1.2", "decode-uri-component": "^0.2.0", "resolve-url": "^0.2.1", "source-map-url": "^0.4.0", @@ -6597,9 +6864,9 @@ } }, "source-map-support": { - "version": "0.5.11", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.11.tgz", - "integrity": "sha512-//sajEx/fGL3iw6fltKMdPvy8kL3kJ2O3iuYlRoT3k9Kb4BjOoZ+BZzaNHeuaruSt+Kf3Zk9tnfAQg9/AJqUVQ==", + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.16.tgz", + "integrity": "sha512-efyLRJDr68D9hBBNIPWFjhpFzURh+KJykQwvMyW5UiZzYwoF6l4YMMDIJJEyFWxWCqfyxLzz6tSfUFR+kXXsVQ==", "requires": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" @@ -6622,6 +6889,55 @@ "resolved": "https://registry.npmjs.org/spawn-command/-/spawn-command-0.0.2-1.tgz", "integrity": "sha1-YvXpRmmBwbeW3Fkpk34RycaSG9A=" }, + "spawn-wrap": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/spawn-wrap/-/spawn-wrap-2.0.0.tgz", + "integrity": "sha512-EeajNjfN9zMnULLwhZZQU3GWBoFNkbngTUPfaawT4RkMiviTxcX0qfhVbGey39mfctfDHkWtuecgQ8NJcyQWHg==", + "dev": true, + "requires": { + "foreground-child": "^2.0.0", + "is-windows": "^1.0.2", + "make-dir": "^3.0.0", + "rimraf": "^3.0.0", + "signal-exit": "^3.0.2", + "which": "^2.0.1" + }, + "dependencies": { + "make-dir": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.0.2.tgz", + "integrity": "sha512-rYKABKutXa6vXTXhoV18cBE7PaewPXHe/Bdq4v+ZLMhxbWApkFFplT0LcbMW+6BbjnQXzZ/sAvSE/JdguApG5w==", + "dev": true, + "requires": { + "semver": "^6.0.0" + } + }, + "rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + } + } + }, "spdx-correct": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.0.tgz", @@ -6646,9 +6962,9 @@ } }, "spdx-license-ids": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.3.tgz", - "integrity": "sha512-uBIcIl3Ih6Phe3XHK1NqboJLdGfwr1UN3k6wSD1dZpmPsIkb8AGNbZYJ1fOBk834+Gxy8rpfDxrS6XLEMZMY2g==" + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.5.tgz", + "integrity": "sha512-J+FWzZoynJEXGphVIS+XEh3kFSjZX/1i9gFBaWQcB+/tmpe2qUsSBABpcxqxnAxFdiUFEgAX1bjYGQvIZmoz9Q==" }, "split-string": { "version": "3.1.0", @@ -6671,11 +6987,6 @@ "figgy-pudding": "^3.5.1" } }, - "stack-utils": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-1.0.2.tgz", - "integrity": "sha512-MTX+MeG5U994cazkjd/9KNAapsHnibjMLnfXodlkXw76JEea0UiNzrqidzo1emMwk7w5Qhc9jd4Bn9TBb1MFwA==" - }, "static-extend": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", @@ -6726,27 +7037,56 @@ } }, "stream-shift": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.0.tgz", - "integrity": "sha1-1cdSgl5TZ+eG944Y5EXqIjoVWVI=" + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.1.tgz", + "integrity": "sha512-AiisoFqQ0vbGcZgQPY1cdP2I76glaVA/RauYR4G4thNFgkTqr90yXTo4LYX60Jl+sIlPNHHdGSwo01AvbKUSVQ==" }, "string-width": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", - "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", "requires": { + "emoji-regex": "^7.0.1", "is-fullwidth-code-point": "^2.0.0", - "strip-ansi": "^4.0.0" - }, - "dependencies": { - "strip-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", - "requires": { - "ansi-regex": "^3.0.0" - } - } + "strip-ansi": "^5.1.0" + } + }, + "string.prototype.trimend": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.0.tgz", + "integrity": "sha512-EEJnGqa/xNfIg05SxiPSqRS7S9qwDhYts1TSLR1BQfYUfPe1stofgGKvwERK9+9yf+PpfBMlpBaCHucXGPQfUA==", + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5" + } + }, + "string.prototype.trimleft": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/string.prototype.trimleft/-/string.prototype.trimleft-2.1.2.tgz", + "integrity": "sha512-gCA0tza1JBvqr3bfAIFJGqfdRTyPae82+KTnm3coDXkZN9wnuW3HjGgN386D7hfv5CHQYCI022/rJPVlqXyHSw==", + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5", + "string.prototype.trimstart": "^1.0.0" + } + }, + "string.prototype.trimright": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/string.prototype.trimright/-/string.prototype.trimright-2.1.2.tgz", + "integrity": "sha512-ZNRQ7sY3KroTaYjRS6EbNiiHrOkjihL9aQE/8gfQ4DtAC/aEBRHFJa44OmoWxGGqXuJlfKkZW4WcXErGr+9ZFg==", + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5", + "string.prototype.trimend": "^1.0.0" + } + }, + "string.prototype.trimstart": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.0.tgz", + "integrity": "sha512-iCP8g01NFYiiBOnwG1Xc3WZLyoo+RuBymwIlWncShXDDJYWN6DbnM3odslBJdgCdRlq94B5s63NWAZlcn2CS4w==", + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5" } }, "string_decoder": { @@ -6763,26 +7103,14 @@ "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { "ansi-regex": "^4.1.0" - }, - "dependencies": { - "ansi-regex": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" - } } }, "strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=" - }, - "strip-bom-buf": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/strip-bom-buf/-/strip-bom-buf-1.0.0.tgz", - "integrity": "sha1-HLRar1dTD0yvhsf3UXnSyaUd1XI=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", + "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", "requires": { - "is-utf8": "^0.2.1" + "is-utf8": "^0.2.0" } }, "strip-dirs": { @@ -6799,9 +7127,12 @@ "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=" }, "strip-indent": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-2.0.0.tgz", - "integrity": "sha1-XvjbKV0B5u1sv3qrlpmNeCJSe2g=" + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-1.0.1.tgz", + "integrity": "sha1-DHlipq3vp7vUrDZkYKY4VSrhoKI=", + "requires": { + "get-stdin": "^4.0.1" + } }, "strip-json-comments": { "version": "2.0.1", @@ -6816,28 +7147,6 @@ "escape-string-regexp": "^1.0.2" } }, - "supertap": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supertap/-/supertap-1.0.0.tgz", - "integrity": "sha512-HZJ3geIMPgVwKk2VsmO5YHqnnJYl6bV5A9JW2uzqV43WmpgliNEYbuvukfor7URpaqpxuw3CfZ3ONdVbZjCgIA==", - "requires": { - "arrify": "^1.0.1", - "indent-string": "^3.2.0", - "js-yaml": "^3.10.0", - "serialize-error": "^2.1.0", - "strip-ansi": "^4.0.0" - }, - "dependencies": { - "strip-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", - "requires": { - "ansi-regex": "^3.0.0" - } - } - } - }, "supports-color": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", @@ -6846,15 +7155,10 @@ "has-flag": "^3.0.0" } }, - "symbol-observable": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-1.2.0.tgz", - "integrity": "sha512-e900nM8RRtGhlV36KGEU9k65K3mPb1WV70OdjfxlG2EAuM1noi/E/BaW/uMhL7bPEssK8QV57vN3esixjUvcXQ==" - }, "tapable": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/tapable/-/tapable-1.1.1.tgz", - "integrity": "sha512-9I2ydhj8Z9veORCw5PRm4u9uebCn0mcCa6scWoNcbZ6dAtoo2618u9UUzxgmsCOreJpqDDuv61LvwofW7hLcBA==" + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-1.1.3.tgz", + "integrity": "sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA==" }, "tar-stream": { "version": "1.6.2", @@ -6879,15 +7183,20 @@ } }, "terser": { - "version": "3.17.0", - "resolved": "https://registry.npmjs.org/terser/-/terser-3.17.0.tgz", - "integrity": "sha512-/FQzzPJmCpjAH9Xvk2paiWrFq+5M6aVOf+2KRbwhByISDX/EujxsK+BAvrhb6H+2rtrLCHK9N01wO014vrIwVQ==", + "version": "4.6.11", + "resolved": "https://registry.npmjs.org/terser/-/terser-4.6.11.tgz", + "integrity": "sha512-76Ynm7OXUG5xhOpblhytE7X58oeNSmC8xnNhjWVo8CksHit0U0kO4hfNbPrrYwowLWFgM2n9L176VNx2QaHmtA==", "requires": { - "commander": "^2.19.0", + "commander": "^2.20.0", "source-map": "~0.6.1", - "source-map-support": "~0.5.10" + "source-map-support": "~0.5.12" }, "dependencies": { + "commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==" + }, "source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", @@ -6896,20 +7205,31 @@ } }, "terser-webpack-plugin": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-1.2.3.tgz", - "integrity": "sha512-GOK7q85oAb/5kE12fMuLdn2btOS9OBZn4VsecpHDywoUC/jLhSAKOiYo0ezx7ss2EXPMzyEWFoE0s1WLE+4+oA==", + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-1.4.3.tgz", + "integrity": "sha512-QMxecFz/gHQwteWwSo5nTc6UaICqN1bMedC5sMtUc7y3Ha3Q8y6ZO0iCR8pq4RJC8Hjf0FEPEHZqcMB/+DFCrA==", "requires": { - "cacache": "^11.0.2", - "find-cache-dir": "^2.0.0", + "cacache": "^12.0.2", + "find-cache-dir": "^2.1.0", + "is-wsl": "^1.1.0", "schema-utils": "^1.0.0", - "serialize-javascript": "^1.4.0", + "serialize-javascript": "^2.1.2", "source-map": "^0.6.1", - "terser": "^3.16.1", - "webpack-sources": "^1.1.0", - "worker-farm": "^1.5.2" + "terser": "^4.1.2", + "webpack-sources": "^1.4.0", + "worker-farm": "^1.7.0" }, "dependencies": { + "schema-utils": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-1.0.0.tgz", + "integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==", + "requires": { + "ajv": "^6.1.0", + "ajv-errors": "^1.0.0", + "ajv-keywords": "^3.1.0" + } + }, "source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", @@ -6917,6 +7237,17 @@ } } }, + "test-exclude": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "dev": true, + "requires": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + } + }, "through": { "version": "2.3.8", "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", @@ -6954,20 +7285,15 @@ } } }, - "time-zone": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/time-zone/-/time-zone-1.0.0.tgz", - "integrity": "sha1-mcW/VZWJZq9tBtg73zgA3IL67F0=" - }, "timed-out": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/timed-out/-/timed-out-4.0.1.tgz", "integrity": "sha1-8y6srFoXW+ol1/q1Zas+2HQe9W8=" }, "timers-browserify": { - "version": "2.0.10", - "resolved": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-2.0.10.tgz", - "integrity": "sha512-YvC1SV1XdOUaL6gx5CoGroT3Gu49pK9+TZ38ErPldOWW4j49GI1HKs9DV+KGq/w6y+LZ72W1c8cKz2vzY+qpzg==", + "version": "2.0.11", + "resolved": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-2.0.11.tgz", + "integrity": "sha512-60aV6sgJ5YEbzUdn9c8kYGIqOubPoUdqQCul3SBAsRCZ40s6Y5cMcrW4dt3/k/EsbLVJNl9n6Vz3fTc+k2GeKQ==", "requires": { "setimmediate": "^1.0.4" } @@ -7025,20 +7351,23 @@ "repeat-string": "^1.6.1" } }, + "touch": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.0.tgz", + "integrity": "sha512-WBx8Uy5TLtOSRtIq+M03/sKDrXCLHxwDcquSP2c43Le03/9serjQBIztjRz6FkJez9D/hleyAXTBGLwwZUw9lA==", + "requires": { + "nopt": "~1.0.10" + } + }, "tree-kill": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.1.tgz", - "integrity": "sha512-4hjqbObwlh2dLyW4tcz0Ymw0ggoaVDMveUB9w8kFSQScdRLo0gxO9J7WFcUBo+W3C1TLdFIEwNOWebgZZ0RH9Q==" + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==" }, "trim-newlines": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-2.0.0.tgz", - "integrity": "sha1-tAPQuRvlDDMd/EuC7s6yLD3hbSA=" - }, - "trim-off-newlines": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/trim-off-newlines/-/trim-off-newlines-1.0.1.tgz", - "integrity": "sha1-n5up2e+odkw4dpi8v+sshI8RrbM=" + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-1.0.0.tgz", + "integrity": "sha1-WIeWa7WCpFA6QetST301ARgVphM=" }, "trim-repeated": { "version": "1.0.0", @@ -7048,34 +7377,41 @@ "escape-string-regexp": "^1.0.2" } }, - "trim-right": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", - "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=" - }, "tslib": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz", - "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.11.1.tgz", + "integrity": "sha512-aZW88SY8kQbU7gpV19lN24LtXh/yD4ZZg6qieAJDDg+YBsJcSmLGK9QpnUjAKVG/xefmvJGd1WUmfpT/g6AJGA==" }, "tslint": { - "version": "5.15.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.15.0.tgz", - "integrity": "sha512-6bIEujKR21/3nyeoX2uBnE8s+tMXCQXhqMmaIPJpHmXJoBJPTLcI7/VHRtUwMhnLVdwLqqY3zmd8Dxqa5CVdJA==", + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-6.1.1.tgz", + "integrity": "sha512-kd6AQ/IgPRpLn6g5TozqzPdGNZ0q0jtXW4//hRcj10qLYBaa3mTUU2y2MCG+RXZm8Zx+KZi0eA+YCrMyNlF4UA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", - "diff": "^3.2.0", + "diff": "^4.0.1", "glob": "^7.1.1", - "js-yaml": "^3.13.0", + "js-yaml": "^3.13.1", "minimatch": "^3.0.4", - "mkdirp": "^0.5.1", + "mkdirp": "^0.5.3", "resolve": "^1.3.2", "semver": "^5.3.0", - "tslib": "^1.8.0", + "tslib": "^1.10.0", "tsutils": "^2.29.0" + }, + "dependencies": { + "commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==" + }, + "diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==" + } } }, "tsutils": { @@ -7099,30 +7435,48 @@ "safe-buffer": "^5.0.1" } }, + "type-fest": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz", + "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", + "dev": true + }, "typedarray": { "version": "0.0.6", "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=" }, - "typescript": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.4.2.tgz", - "integrity": "sha512-Og2Vn6Mk7JAuWA1hQdDQN/Ekm/SchX80VzLhjKN9ETYrIepBFAd8PkOdOTK2nKt0FCkmMZKBJvQ1dV1gIxPu/A==" + "typedarray-to-buffer": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "dev": true, + "requires": { + "is-typedarray": "^1.0.0" + } }, - "uid2": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/uid2/-/uid2-0.0.3.tgz", - "integrity": "sha1-SDEm4Rd03y9xuLY53NeZw3YWK4I=" + "typescript": { + "version": "3.8.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.8.3.tgz", + "integrity": "sha512-MYlEfn5VrLNsgudQTVJeNaQFUAI7DkhnOjdpAp4T+ku1TfQClewlbSuTVHiA+8skNBgaf02TL/kLOvig4y3G8w==" }, "unbzip2-stream": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/unbzip2-stream/-/unbzip2-stream-1.3.3.tgz", - "integrity": "sha512-fUlAF7U9Ah1Q6EieQ4x4zLNejrRvDWUYmxXUpN3uziFYCHapjWFaCAnreY9bGgxzaMCFAPPpYNng57CypwJVhg==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/unbzip2-stream/-/unbzip2-stream-1.4.0.tgz", + "integrity": "sha512-kVx7CDAsdBSWVf404Mw7oI9i09w5/mTT/Ruk+RWa64PLYKvsAucLLFHvQtnvjeADM4ZizxrvG5SHnF4Te4T2Cg==", "requires": { "buffer": "^5.2.1", "through": "^2.3.8" } }, + "undefsafe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.3.tgz", + "integrity": "sha512-nrXZwwXrD/T/JXeygJqdCO6NZZ1L66HrxM/Z7mIq2oPanoN0F1nLx3lwJMu6AwJY69hdixaFQOuoYsMjE5/C2A==", + "requires": { + "debug": "^2.2.0" + } + }, "unicode-canonical-property-names-ecmascript": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-1.0.4.tgz", @@ -7138,45 +7492,24 @@ } }, "unicode-match-property-value-ecmascript": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-1.1.0.tgz", - "integrity": "sha512-hDTHvaBk3RmFzvSl0UVrUmC3PuW9wKVnpoUDYH0JDkSIovzw+J5viQmeYHxVSBptubnr7PbH2e0fnpDRQnQl5g==" + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-1.2.0.tgz", + "integrity": "sha512-wjuQHGQVofmSJv1uVISKLE5zO2rNGzM/KCYZch/QQvez7C1hUhBIuZ701fYXExuufJFMPhv2SyL8CyoIfMLbIQ==" }, "unicode-property-aliases-ecmascript": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-1.0.5.tgz", - "integrity": "sha512-L5RAqCfXqAwR3RriF8pM0lU0w4Ryf/GgzONwi6KnL1taJQa7x1TCxdJnILX59WIGOwR57IVxn7Nej0fz1Ny6fw==" + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-1.1.0.tgz", + "integrity": "sha512-PqSoPh/pWetQ2phoj5RLiaqIk4kCNwoV3CI+LfGmWLKI3rE3kl1h59XpX2BjgDrmbxD9ARtQobPGU1SguCYuQg==" }, "union-value": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.0.tgz", - "integrity": "sha1-XHHDTLW61dzr4+oM0IIHulqhrqQ=", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.1.tgz", + "integrity": "sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg==", "requires": { "arr-union": "^3.1.0", "get-value": "^2.0.6", "is-extendable": "^0.1.1", - "set-value": "^0.4.3" - }, - "dependencies": { - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "requires": { - "is-extendable": "^0.1.0" - } - }, - "set-value": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/set-value/-/set-value-0.4.3.tgz", - "integrity": "sha1-fbCPnT0i3H945Trzw79GZuzfzPE=", - "requires": { - "extend-shallow": "^2.0.1", - "is-extendable": "^0.1.1", - "is-plain-object": "^2.0.1", - "to-object-path": "^0.3.0" - } - } + "set-value": "^2.0.1" } }, "unique-filename": { @@ -7188,9 +7521,9 @@ } }, "unique-slug": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-2.0.1.tgz", - "integrity": "sha512-n9cU6+gITaVu7VGj1Z8feKMmfAjEAQGhwD9fE3zvpRRa0wEIx8ODYkVGfSc94M2OX00tUFV8wH3zYbm1I8mxFg==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-2.0.2.tgz", + "integrity": "sha512-zoWr9ObaxALD3DOPfjPSqxt4fnZiWblxHIgeWqW8x7UqDzEtHEQLzji2cuJYQFCU6KmoJikOYAZlrTHHebjx2w==", "requires": { "imurmurhash": "^0.1.4" } @@ -7203,16 +7536,6 @@ "crypto-random-string": "^1.0.0" } }, - "unique-temp-dir": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unique-temp-dir/-/unique-temp-dir-1.0.0.tgz", - "integrity": "sha1-bc6VsmgcoAPuv7MEpBX5y6vMU4U=", - "requires": { - "mkdirp": "^0.5.1", - "os-tmpdir": "^1.0.1", - "uid2": "0.0.3" - } - }, "universalify": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", @@ -7260,9 +7583,9 @@ "integrity": "sha1-0vD3N9FrBhXnKmk17QQhRXLVb5c=" }, "upath": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/upath/-/upath-1.1.2.tgz", - "integrity": "sha512-kXpym8nmDmlCBr7nKdIx8P2jNBa+pBpIUFRnKJ4dr8htyYGJFokkr2ZvERRtUN+9SY+JqXouNgUPtv6JQva/2Q==" + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/upath/-/upath-1.2.0.tgz", + "integrity": "sha512-aZwGpamFO61g3OlfT7OQCHqhGnW43ieH9WZeP7QxN/G/jS4jfqUkZxoryvJgVPEcrl5NL/ggHsSmLMHuH64Lhg==" }, "update-notifier": { "version": "2.5.0", @@ -7279,21 +7602,6 @@ "latest-version": "^3.0.0", "semver-diff": "^2.0.0", "xdg-basedir": "^3.0.0" - }, - "dependencies": { - "ci-info": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", - "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" - }, - "is-ci": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-1.2.1.tgz", - "integrity": "sha512-s6tfsaQaQi3JNciBH6shVqEDvhGut0SUXr31ag8Pd8BBbVVlcGfWhpPmEOoM6RJ5TFhbypvf5yyRw/VXW1IiWg==", - "requires": { - "ci-info": "^1.5.0" - } - } } }, "uri-js": { @@ -7354,6 +7662,13 @@ "integrity": "sha512-HShAsny+zS2TZfaXxD9tYj4HQGlBezXZMZuM/S5PKLLoZkShZiGk9o5CzukI1LVHZvjdvZ2Sj1aW/Ndn2NB/HQ==", "requires": { "inherits": "2.0.3" + }, + "dependencies": { + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + } } }, "util-deprecate": { @@ -7361,19 +7676,16 @@ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" }, - "util.promisify": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/util.promisify/-/util.promisify-1.0.0.tgz", - "integrity": "sha512-i+6qA2MPhvoKLuxnJNpXAGhg7HphQOSUq2LKMZD0m15EiskXUkMvKdF4Uui0WYeCUGea+o2cw/ZuwehtfsrNkA==", - "requires": { - "define-properties": "^1.1.2", - "object.getownpropertydescriptors": "^2.0.3" - } + "uuid": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", + "dev": true }, "v8-compile-cache": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.0.2.tgz", - "integrity": "sha512-1wFuMUIM16MDJRCrpbpuEPTUGmM5QMUg0cr3KFwra2XgOgFcPGDQHDh3CszSCD2Zewc/dh/pamNEW8CbfDebUw==" + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.0.3.tgz", + "integrity": "sha512-CNmdbwQMBjwr9Gsmohvm0pbL954tJrNzf6gWL3K+QMQf00PF7ERGrEiLgjuU3mKreLC2MeGhUsNV9ybTbLgd3w==" }, "validate-npm-package-license": { "version": "3.0.4", @@ -7385,78 +7697,78 @@ } }, "vm-browserify": { - "version": "0.0.4", - "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-0.0.4.tgz", - "integrity": "sha1-XX6kW7755Kb/ZflUOOCofDV9WnM=", - "requires": { - "indexof": "0.0.1" - } + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.2.tgz", + "integrity": "sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ==" }, "watchpack": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-1.6.0.tgz", - "integrity": "sha512-i6dHe3EyLjMmDlU1/bGQpEw25XSjkJULPuAVKCbNRefQVq48yXKUpwg538F7AZTf9kyr57zj++pQFltUa5H7yA==", + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-1.6.1.tgz", + "integrity": "sha512-+IF9hfUFOrYOOaKyfaI7h7dquUIOgyEMoQMLA7OP5FxegKA2+XdXThAZ9TU2kucfhDH7rfMHs1oPYziVGWRnZA==", "requires": { - "chokidar": "^2.0.2", + "chokidar": "^2.1.8", "graceful-fs": "^4.1.2", "neo-async": "^2.5.0" } }, - "wcwidth": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", - "integrity": "sha1-8LDc+RW8X/FSivrbLA4XtTLaL+g=", - "requires": { - "defaults": "^1.0.3" - } - }, "webpack": { - "version": "4.29.6", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-4.29.6.tgz", - "integrity": "sha512-MwBwpiE1BQpMDkbnUUaW6K8RFZjljJHArC6tWQJoFm0oQtfoSebtg4Y7/QHnJ/SddtjYLHaKGX64CFjG5rehJw==", - "requires": { - "@webassemblyjs/ast": "1.8.5", - "@webassemblyjs/helper-module-context": "1.8.5", - "@webassemblyjs/wasm-edit": "1.8.5", - "@webassemblyjs/wasm-parser": "1.8.5", - "acorn": "^6.0.5", - "acorn-dynamic-import": "^4.0.0", - "ajv": "^6.1.0", - "ajv-keywords": "^3.1.0", - "chrome-trace-event": "^1.0.0", + "version": "4.42.1", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-4.42.1.tgz", + "integrity": "sha512-SGfYMigqEfdGchGhFFJ9KyRpQKnipvEvjc1TwrXEPCM6H5Wywu10ka8o3KGrMzSMxMQKt8aCHUFh5DaQ9UmyRg==", + "requires": { + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/helper-module-context": "1.9.0", + "@webassemblyjs/wasm-edit": "1.9.0", + "@webassemblyjs/wasm-parser": "1.9.0", + "acorn": "^6.2.1", + "ajv": "^6.10.2", + "ajv-keywords": "^3.4.1", + "chrome-trace-event": "^1.0.2", "enhanced-resolve": "^4.1.0", - "eslint-scope": "^4.0.0", + "eslint-scope": "^4.0.3", "json-parse-better-errors": "^1.0.2", - "loader-runner": "^2.3.0", - "loader-utils": "^1.1.0", - "memory-fs": "~0.4.1", - "micromatch": "^3.1.8", - "mkdirp": "~0.5.0", - "neo-async": "^2.5.0", - "node-libs-browser": "^2.0.0", + "loader-runner": "^2.4.0", + "loader-utils": "^1.2.3", + "memory-fs": "^0.4.1", + "micromatch": "^3.1.10", + "mkdirp": "^0.5.3", + "neo-async": "^2.6.1", + "node-libs-browser": "^2.2.1", "schema-utils": "^1.0.0", - "tapable": "^1.1.0", - "terser-webpack-plugin": "^1.1.0", - "watchpack": "^1.5.0", - "webpack-sources": "^1.3.0" + "tapable": "^1.1.3", + "terser-webpack-plugin": "^1.4.3", + "watchpack": "^1.6.0", + "webpack-sources": "^1.4.1" + }, + "dependencies": { + "schema-utils": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-1.0.0.tgz", + "integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==", + "requires": { + "ajv": "^6.1.0", + "ajv-errors": "^1.0.0", + "ajv-keywords": "^3.1.0" + } + } } }, "webpack-cli": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-3.3.0.tgz", - "integrity": "sha512-t1M7G4z5FhHKJ92WRKwZ1rtvi7rHc0NZoZRbSkol0YKl4HvcC8+DsmGDmK7MmZxHSAetHagiOsjOB6MmzC2TUw==", - "requires": { - "chalk": "^2.4.1", - "cross-spawn": "^6.0.5", - "enhanced-resolve": "^4.1.0", - "findup-sync": "^2.0.0", - "global-modules": "^1.0.0", - "import-local": "^2.0.0", - "interpret": "^1.1.0", - "loader-utils": "^1.1.0", - "supports-color": "^5.5.0", - "v8-compile-cache": "^2.0.2", - "yargs": "^12.0.5" + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-3.3.11.tgz", + "integrity": "sha512-dXlfuml7xvAFwYUPsrtQAA9e4DOe58gnzSxhgrO/ZM/gyXTBowrsYeubyN4mqGhYdpXMFNyQ6emjJS9M7OBd4g==", + "requires": { + "chalk": "2.4.2", + "cross-spawn": "6.0.5", + "enhanced-resolve": "4.1.0", + "findup-sync": "3.0.0", + "global-modules": "2.0.0", + "import-local": "2.0.0", + "interpret": "1.2.0", + "loader-utils": "1.2.3", + "supports-color": "6.1.0", + "v8-compile-cache": "2.0.3", + "yargs": "13.2.4" }, "dependencies": { "cross-spawn": { @@ -7470,13 +7782,110 @@ "shebang-command": "^1.2.0", "which": "^1.2.9" } + }, + "emojis-list": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz", + "integrity": "sha1-TapNnbAPmBmIDHn6RXrlsJof04k=" + }, + "enhanced-resolve": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-4.1.0.tgz", + "integrity": "sha512-F/7vkyTtyc/llOIn8oWclcB25KdRaiPBpZYDgJHgh/UHtpgT2p2eldQgtQnLtUvfMKPKxbRaQM/hHkvLHt1Vng==", + "requires": { + "graceful-fs": "^4.1.2", + "memory-fs": "^0.4.0", + "tapable": "^1.0.0" + } + }, + "find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "requires": { + "locate-path": "^3.0.0" + } + }, + "json5": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", + "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "requires": { + "minimist": "^1.2.0" + } + }, + "loader-utils": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.2.3.tgz", + "integrity": "sha512-fkpz8ejdnEMG3s37wGL07iSBDg99O9D5yflE9RGNH3hRdx9SOwYfnGYdZOUIZitN8E+E2vkq3MUMYMvPYl5ZZA==", + "requires": { + "big.js": "^5.2.2", + "emojis-list": "^2.0.0", + "json5": "^1.0.1" + } + }, + "locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "requires": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "requires": { + "p-limit": "^2.0.0" + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==" + }, + "supports-color": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", + "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", + "requires": { + "has-flag": "^3.0.0" + } + }, + "yargs": { + "version": "13.2.4", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.2.4.tgz", + "integrity": "sha512-HG/DWAJa1PAnHT9JAhNa8AbAv3FPaiLzioSjCcmuXXhP8MlpHO5vwls4g4j6n30Z74GVQj8Xa62dWVx1QCGklg==", + "requires": { + "cliui": "^5.0.0", + "find-up": "^3.0.0", + "get-caller-file": "^2.0.1", + "os-locale": "^3.1.0", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^3.0.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^13.1.0" + } } } }, "webpack-sources": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-1.3.0.tgz", - "integrity": "sha512-OiVgSrbGu7NEnEvQJJgdSFPl2qWKkWq5lHMhgiToIiN9w34EBnjYzSYs+VbL5KoYiLNtFFa7BZIKxRED3I32pA==", + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-1.4.3.tgz", + "integrity": "sha512-lgTS3Xhv1lCOKo7SA5TjKXMjpSM4sBjNV5+q2bqesbSPs5FjGmU6jjtBSkX9b4qW87vDIsCIlUPOEhbZrMdjeQ==", "requires": { "source-list-map": "^2.0.0", "source-map": "~0.6.1" @@ -7489,11 +7898,6 @@ } } }, - "well-known-symbols": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/well-known-symbols/-/well-known-symbols-2.0.0.tgz", - "integrity": "sha512-ZMjC3ho+KXo0BfJb7JgtQ5IBuvnShdlACNkKkdsqBmYw3bPAaJfPeYUo6tLUaT5tG/Gkh7xkpBhKRQ9e7pyg9Q==" - }, "which": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", @@ -7513,6 +7917,30 @@ "integrity": "sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA==", "requires": { "string-width": "^1.0.2 || 2" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" + }, + "string-width": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + } + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "requires": { + "ansi-regex": "^3.0.0" + } + } } }, "widest-line": { @@ -7521,67 +7949,59 @@ "integrity": "sha512-Ba5m9/Fa4Xt9eb2ELXt77JxVDV8w7qQrH0zS/TWSJdLyAwQjWoOzpzj5lwVftDz6n/EOu3tNACS84v509qwnJA==", "requires": { "string-width": "^2.1.1" - } - }, - "worker-farm": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/worker-farm/-/worker-farm-1.6.0.tgz", - "integrity": "sha512-6w+3tHbM87WnSWnENBUvA2pxJPLhQUg5LKwUQHq3r+XPhIM+Gh2R5ycbwPCyuGbNg+lPgdcnQUhuC02kJCvffQ==", - "requires": { - "errno": "~0.1.7" - } - }, - "wrap-ansi": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", - "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", - "requires": { - "string-width": "^1.0.1", - "strip-ansi": "^3.0.1" }, "dependencies": { "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "is-fullwidth-code-point": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", - "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", - "requires": { - "number-is-nan": "^1.0.0" - } + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" }, "string-width": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", - "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", "requires": { - "code-point-at": "^1.0.0", - "is-fullwidth-code-point": "^1.0.0", - "strip-ansi": "^3.0.0" + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" } }, "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", "requires": { - "ansi-regex": "^2.0.0" + "ansi-regex": "^3.0.0" } } } }, + "worker-farm": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/worker-farm/-/worker-farm-1.7.0.tgz", + "integrity": "sha512-rvw3QTZc8lAxyVrqcSGVm5yP/IJ2UcB3U0graE3LCFoZ0Yn2x4EoVSqJKdB/T5M+FLcRPjz4TDacRf3OCfNUzw==", + "requires": { + "errno": "~0.1.7" + } + }, + "wrap-ansi": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", + "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "requires": { + "ansi-styles": "^3.2.0", + "string-width": "^3.0.0", + "strip-ansi": "^5.0.0" + } + }, "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.2.tgz", - "integrity": "sha512-s0b6vB3xIVRLWywa6X9TOMA7k9zio0TMOsl9ZnDkliA/cfJlpHXAscj0gbHVJiTdIuAYpIyqS5GW91fqm6gG5g==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", @@ -7594,9 +8014,9 @@ "integrity": "sha1-SWsswQnsqNus/i3HK2A8F8WHCtQ=" }, "xtend": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", - "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=" + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==" }, "y18n": { "version": "4.0.0", @@ -7609,56 +8029,79 @@ "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=" }, "yargs": { - "version": "12.0.5", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-12.0.5.tgz", - "integrity": "sha512-Lhz8TLaYnxq/2ObqHDql8dX8CJi97oHxrjUcYtzKbbykPtVW9WB+poxI+NM2UIzsMgNCZTIf0AQwsjK5yMAqZw==", + "version": "13.3.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.2.tgz", + "integrity": "sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw==", "requires": { - "cliui": "^4.0.0", - "decamelize": "^1.2.0", + "cliui": "^5.0.0", "find-up": "^3.0.0", - "get-caller-file": "^1.0.1", - "os-locale": "^3.0.0", + "get-caller-file": "^2.0.1", "require-directory": "^2.1.1", - "require-main-filename": "^1.0.1", + "require-main-filename": "^2.0.0", "set-blocking": "^2.0.0", - "string-width": "^2.0.0", + "string-width": "^3.0.0", "which-module": "^2.0.0", - "y18n": "^3.2.1 || ^4.0.0", - "yargs-parser": "^11.1.1" + "y18n": "^4.0.0", + "yargs-parser": "^13.1.2" }, "dependencies": { - "camelcase": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==" + "find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "requires": { + "locate-path": "^3.0.0" + } }, - "yargs-parser": { - "version": "11.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-11.1.1.tgz", - "integrity": "sha512-C6kB/WJDiaxONLJQnF8ccx9SEeoTTLek8RVbaOIsrAUS8VrBEXfmeSnCZxygc+XC2sNMBIwOOnfcxiynjHsVSQ==", + "locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", "requires": { - "camelcase": "^5.0.0", - "decamelize": "^1.2.0" + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "requires": { + "p-limit": "^2.0.0" } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==" } } }, "yargs-parser": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-10.1.0.tgz", - "integrity": "sha512-VCIyR1wJoEBZUqk5PA+oOBF6ypbwh5aNB3I50guxAL/quggdfs4TtNHQrSazFA3fYZ+tEqfs0zIGlv0c/rgjbQ==", + "version": "13.1.2", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.2.tgz", + "integrity": "sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg==", "requires": { - "camelcase": "^4.1.0" + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" } }, "yargs-unparser": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-1.5.0.tgz", - "integrity": "sha512-HK25qidFTCVuj/D1VfNiEndpLIeJN78aqgR23nL3y4N0U/91cOAzqfHlF8n2BvoNDcZmJKin3ddNSvOxSr8flw==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-1.6.0.tgz", + "integrity": "sha512-W9tKgmSn0DpSatfri0nx52Joq5hVXgeLiqR/5G0sZNDoLZFOr/xjBUDcShCOGNsBnEMNo1KAMBkTej1Hm62HTw==", "requires": { "flat": "^4.1.0", - "lodash": "^4.17.11", - "yargs": "^12.0.5" + "lodash": "^4.17.15", + "yargs": "^13.3.0" } }, "yauzl": { diff --git a/package.json b/package.json index 5d31be48f4..bd68284250 100644 --- a/package.json +++ b/package.json @@ -4,31 +4,60 @@ "build": "fable build.fsx --run", "publish": "fable build.fsx --run publish", "test": "fable build.fsx --run test", - "quicktest": "fable-splitter -c src/quicktest/splitter.config.js --watch --run", + "build-compiler-js": "fable src/fable-compiler-js/src/fable-compiler-js.fsproj build/fable-compiler-js/out", + "postbuild-compiler-js": "rollup build/fable-compiler-js/out/app.js --file src/fable-compiler-js/dist/app.js --format umd --name Fable", + "minify-compiler-js": "terser src/fable-compiler-js/dist/app.js -o src/fable-compiler-js/dist/app.min.js --mangle --compress", "test-js": "node src/fable-compiler-js/dist/app.js tests/Main/Fable.Tests.fsproj build/tests-js --commonjs", "posttest-js": "mocha build/tests-js --reporter dot -t 10000" }, "dependencies": { - "@babel/cli": "^7.4.3", - "@babel/core": "^7.4.3", - "@babel/plugin-transform-modules-commonjs": "^7.4.3", - "@babel/preset-env": "^7.4.3", - "@babel/register": "^7.4.0", - "@types/node": "^11.13.0", - "ava": "^1.4.1", - "babel-loader": "^8.0.5", - "concurrently": "^4.1.0", + "@babel/cli": "^7.8.4", + "@babel/core": "^7.9.0", + "@babel/plugin-transform-modules-commonjs": "^7.9.0", + "@babel/preset-env": "^7.9.0", + "@babel/register": "^7.9.0", + "@types/node": "^13.11.1", + "babel-loader": "^8.1.0", + "concurrently": "^5.1.0", "download-cli": "^1.1.1", - "fable-babel-plugins": "^2.2.0", - "fable-compiler": "^2.2.3", - "fable-compiler-js": "^1.0.3", - "fable-loader": "^2.1.6", - "fable-splitter": "^2.1.8", + "fable-babel-plugins": "^2.3.0", + "fable-compiler": "^2.5.1", + "fable-compiler-js": "^1.3.1", + "fable-loader": "^2.1.9", + "fable-splitter": "^2.1.13", "ghreleases": "^3.0.2", - "mocha": "^6.1.4", - "tslint": "^5.15.0", - "typescript": "^3.4.2", - "webpack": "^4.29.6", - "webpack-cli": "^3.3.0" + "mocha": "^7.1.1", + "nodemon": "^2.0.2", + "rollup": "^2.6.1", + "terser": "^4.6.11", + "tslint": "^6.1.1", + "typescript": "^3.8.3", + "webpack": "^4.42.1", + "webpack-cli": "^3.3.11" + }, + "devDependencies": { + "@matthid/source-map-visualization": "^0.5.0", + "nyc": "^15.0.1", + "source-map-support": "^0.5.16" + }, + "nyc": { + "extension": [ + ".ts", + ".fs", + ".tsx" + ], + "exclude": [ + "**/*.d.ts" + ], + "reporter": [ + "lcov", + "cobertura", + "text" + ], + "report-dir": "./build/coverage/nyc", + "temp-dir": "./build/coverage/nyc/temp", + "sourceMap": true, + "produce-source-map": true, + "all": true } } diff --git a/src/Fable.Cli/Fable.Cli.fsproj b/src/Fable.Cli/Fable.Cli.fsproj index 707d55c620..b0e91118ab 100644 --- a/src/Fable.Cli/Fable.Cli.fsproj +++ b/src/Fable.Cli/Fable.Cli.fsproj @@ -3,11 +3,13 @@ Exe netcoreapp2.1 - 2.1.0 + + Major true + @@ -24,8 +26,8 @@ - - + + diff --git a/src/Fable.Cli/Globbing.fs b/src/Fable.Cli/Globbing.fs new file mode 100644 index 0000000000..6d4b991a24 --- /dev/null +++ b/src/Fable.Cli/Globbing.fs @@ -0,0 +1,377 @@ +namespace Fable.Cli + +open System.Collections.Generic +open System.IO + +/// Globbing support and operators +/// +/// Forked from `Fake.IO.FileSystem` +module Globbing = + /// This module contains a file pattern globbing implementation. + [] + module Glob = + open System + open System.Text.RegularExpressions + + // Normalizes path for different OS + let inline normalizePath (path : string) = + path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar) + + type private SearchOption = + | Directory of string + | Drive of string + | Recursive + | FilePattern of string + + let private checkSubDirs absolute (dir : string) root = + if dir.Contains "*" then + try Directory.EnumerateDirectories(root, dir, SearchOption.TopDirectoryOnly) |> Seq.toList + with :? System.IO.DirectoryNotFoundException -> List.empty + else + let path = Path.Combine(root, dir) + + let di = + if absolute then new DirectoryInfo(dir) + else new DirectoryInfo(path) + if di.Exists then [ di.FullName ] + else [] + + let rec private buildPaths acc (input : SearchOption list) = + match input with + | [] -> acc + | Directory name :: t -> + let subDirs = List.collect (checkSubDirs false name) acc + buildPaths subDirs t + | Drive name :: t -> + let subDirs = List.collect (checkSubDirs true name) acc + buildPaths subDirs t + | Recursive :: [] -> + let dirs = + Seq.collect (fun dir -> + try Directory.EnumerateFileSystemEntries(dir, "*", SearchOption.AllDirectories) + with :? System.IO.DirectoryNotFoundException -> Seq.empty) acc + buildPaths (acc @ Seq.toList dirs) [] + | Recursive :: t -> + let dirs = + Seq.collect (fun dir -> + try Directory.EnumerateDirectories(dir, "*", SearchOption.AllDirectories) + with :? System.IO.DirectoryNotFoundException -> Seq.empty) acc + buildPaths (acc @ Seq.toList dirs) t + | FilePattern pattern :: _ -> + acc |> List.collect (fun dir -> + if Directory.Exists (Path.Combine (dir, pattern)) then [Path.Combine (dir, pattern)] + else + try + Directory.EnumerateFiles (dir, pattern) |> Seq.toList + with + | :? System.IO.DirectoryNotFoundException + | :? System.IO.PathTooLongException -> []) + + let private driveRegex = Regex(@"^[A-Za-z]:$", RegexOptions.Compiled) + + let inline private normalizeOutputPath (p : string) = + p.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar) + .TrimEnd(Path.DirectorySeparatorChar) + + let internal getRoot (baseDirectory : string) (pattern : string) = + let baseDirectory = normalizePath baseDirectory + let normPattern = normalizePath pattern + + let patternParts = normPattern.Split([| '/'; '\\' |], StringSplitOptions.RemoveEmptyEntries) + let patternPathParts = + patternParts + |> Seq.takeWhile(fun p -> not (p.Contains("*"))) + |> Seq.toArray + + let globRoot = + // If we did not find any "*", then drop the last bit (it is a file name, not a pattern) + ( if patternPathParts.Length = patternParts.Length then + patternPathParts.[0 .. patternPathParts.Length-2] + else patternPathParts ) + |> String.concat (Path.DirectorySeparatorChar.ToString()) + + let globRoot = + // If we dropped "/" from the beginning of the path in the 'Split' call, put it back! + if normPattern.StartsWith("/") then "/" + globRoot + else globRoot + + if Path.IsPathRooted globRoot then globRoot + else Path.Combine(baseDirectory, globRoot) + + let internal search (baseDir : string) (originalInput : string) = + let baseDir = normalizePath baseDir + let input = normalizePath originalInput + let input = + if String.IsNullOrEmpty baseDir + then input + else + // The final \ (or /) makes sure to only match complete folder + // names (as one folder name could be a substring of the other) + let start = + baseDir.TrimEnd([|Path.DirectorySeparatorChar|]) + + string Path.DirectorySeparatorChar + // See https://github.com/fsharp/FAKE/issues/1925 + if input.StartsWith start then + input.Substring start.Length + else input + + let filePattern = Path.GetFileName(input) + + let splits = input.Split([| '/'; '\\' |], StringSplitOptions.None) + let baseItems = + let start, rest = + if input.StartsWith "\\\\" && splits.Length >= 4 then + let serverName = splits.[2] + let share = splits.[3] + [ Directory (sprintf "\\\\%s\\%s" serverName share) ], splits |> Seq.skip 4 + elif splits.Length >= 2 && Path.IsPathRooted input && driveRegex.IsMatch splits.[0] then + [ Directory(splits.[0] + "\\") ], splits |> Seq.skip 1 + elif splits.Length >= 2 && Path.IsPathRooted input && input.StartsWith "/" then + [ Directory("/") ], splits |> Array.toSeq + else + if Path.IsPathRooted input then + if input.StartsWith "\\" + then + failwithf "Please remove the leading '\\' or '/' and replace them with \ + '.\\' or './' if you want to use a relative path. Leading \ + slashes are considered an absolute path (input was '%s')!" + originalInput + else + failwithf "Unknown globbing input '%s', try to use a \ + relative path and report an issue!" originalInput + [], splits |> Array.toSeq + let restList = + rest + |> Seq.filter (String.IsNullOrEmpty >> not) + |> Seq.map (function + | "**" -> Recursive + | a when a = filePattern -> FilePattern(a) + | a -> Directory(a)) + |> Seq.toList + start @ restList + baseItems + |> buildPaths [ baseDir ] + |> List.map normalizeOutputPath + + let internal compileGlobToRegex pattern = + let pattern = normalizePath pattern + + let escapedPattern = (Regex.Escape pattern) + let regexPattern = + let xTOy = + [ + "dirwildcard", (@"\\\*\\\*(/|\\\\)", @"(.*(/|\\))?") + "stardotstar", (@"\\\*\\.\\\*", @"([^\\/]*)") + "wildcard", (@"\\\*", @"([^\\/]*)") + ] |> List.map(fun (key, (pattern, replace)) -> + let pattern = sprintf "(?<%s>%s)" key pattern + key, (pattern, replace) + ) + let xTOyMap = xTOy |> Map.ofList + let replacePattern = xTOy |> List.map(fun x -> x |> snd |> fst) |> String.concat("|") + let replaced = Regex(replacePattern).Replace(escapedPattern, fun m -> + let matched = xTOy |> Seq.map(fst) |> Seq.find(fun n -> + m.Groups.Item(n).Success + ) + (xTOyMap |> Map.tryFind matched).Value |> snd + ) + "^" + replaced + "$" + + Regex(regexPattern) + + let private globRegexCache = System.Collections.Concurrent.ConcurrentDictionary() + + let isMatch pattern path : bool = + let path = normalizePath path + + let regex = + let outRegex : ref = ref null + if globRegexCache.TryGetValue(pattern, outRegex) then + !outRegex + else + let compiled = compileGlobToRegex pattern + globRegexCache.TryAdd(pattern, compiled) |> ignore + compiled + + regex.IsMatch(path) + + type IGlobbingPattern = + inherit IEnumerable + abstract BaseDirectory : string + abstract Includes : string list + abstract Excludes : string list + + type LazyGlobbingPattern = + { BaseDirectory : string + Includes : string list + Excludes : string list } + + interface IGlobbingPattern with + member this.BaseDirectory = this.BaseDirectory + member this.Includes = this.Includes + member this.Excludes = this.Excludes + + interface IEnumerable with + + member this.GetEnumerator() = + let hashSet = HashSet() + + let excludes = + seq { + for pattern in this.Excludes do + yield! Glob.search this.BaseDirectory pattern + } + |> Set.ofSeq + + let files = + seq { + for pattern in this.Includes do + yield! Glob.search this.BaseDirectory pattern + } + |> Seq.filter (fun x -> not (Set.contains x excludes)) + |> Seq.filter (fun x -> hashSet.Add x) + + files.GetEnumerator() + + member this.GetEnumerator() = + (this :> IEnumerable).GetEnumerator() :> System.Collections.IEnumerator + + type ResolvedGlobbingPattern = + { BaseDirectory : string + Includes : string list + Excludes : string list + Results : string list } + + interface IGlobbingPattern with + member this.BaseDirectory = this.BaseDirectory + member this.Includes = this.Includes + member this.Excludes = this.Excludes + + interface IEnumerable with + member this.GetEnumerator() = + (this.Results :> IEnumerable).GetEnumerator() + member this.GetEnumerator() = + (this :> IEnumerable).GetEnumerator() :> System.Collections.IEnumerator + + [] + module GlobbingPatternExtensions = + type IGlobbingPattern with + member internal this.Pattern = + match this with + | :? LazyGlobbingPattern as l -> l + | _ -> + { BaseDirectory = this.BaseDirectory + Includes = this.Includes + Excludes = this.Excludes } + member this.Resolve() = + match this with + | :? ResolvedGlobbingPattern as res -> res :> IGlobbingPattern + | _ -> + let list = + this + |> Seq.toList + { BaseDirectory = this.BaseDirectory + Includes = this.Includes + Excludes = this.Excludes + Results = list } :> IGlobbingPattern + /// Adds the given pattern to the file includes + member this.And pattern = + { this.Pattern with Includes = this.Includes @ [ pattern ] } :> IGlobbingPattern + + /// Ignores files with the given pattern + member this.ButNot pattern = + { this.Pattern with Excludes = pattern :: this.Excludes } :> IGlobbingPattern + + /// Sets a directory as BaseDirectory. + member this.SetBaseDirectory(dir : string) = + { this.Pattern with + BaseDirectory = dir.TrimEnd(Path.DirectorySeparatorChar) } :> IGlobbingPattern + + /// Checks if a particular file is matched + member this.IsMatch (path : string) = + let fullDir (pattern: string) = + if Path.IsPathRooted(pattern) then + pattern + else + System.IO.Path.Combine(this.BaseDirectory, pattern) + let fullPath = Path.GetFullPath path + let included = + this.Includes + |> Seq.exists(fun fileInclude -> + Glob.isMatch (fullDir fileInclude) fullPath + ) + let excluded = + this.Excludes + |> Seq.exists(fun fileExclude -> + Glob.isMatch (fullDir fileExclude) fullPath + ) + + included && not excluded + + [] + module GlobbingPattern = + let private defaultBaseDir = Path.GetFullPath "." + + /// Include files + let create x = + { BaseDirectory = defaultBaseDir + Includes = [ x ] + Excludes = [] } :> IGlobbingPattern + + /// Start an empty globbing pattern from the specified directory + let createFrom (dir : string) = + { BaseDirectory = dir + Includes = [] + Excludes = [] } :> IGlobbingPattern + + /// Sets a directory as baseDirectory for fileIncludes. + let setBaseDir (dir : string) (fileIncludes : IGlobbingPattern) = + fileIncludes.SetBaseDirectory dir + + /// Get base include directories. + /// + /// Used to get a smaller set of directories from a globbing pattern. + let getBaseDirectoryIncludes (fileIncludes: IGlobbingPattern) = + let directoryIncludes = + fileIncludes.Includes + |> Seq.map (fun file -> + Glob.getRoot fileIncludes.BaseDirectory file) + + // remove subdirectories + directoryIncludes + |> Seq.filter (fun d -> + directoryIncludes + |> Seq.exists (fun p -> + d.StartsWith (p + string Path.DirectorySeparatorChar) + && p <> d) + |> not) + |> Seq.toList + + /// Contains operators to find and process files. + /// + /// ### Simple glob using as list + /// + /// let csProjectFiles = !! "src/*.csproj" + /// + /// for projectFile in csProjectFiles do + /// printf "F# ProjectFile: %s" projectFile + /// + /// ### Combine globs + /// + /// let projectFiles = + /// !! "src/*/*.*proj" + /// ++ "src/*/*.target" + /// -- "src/*/*.vbproj" + /// + /// for projectFile in projectFiles do + /// printf "ProjectFile: %s" projectFile + /// + module Operators = + /// Add Include operator + let inline (++) (x : IGlobbingPattern) pattern = x.And pattern + + /// Exclude operator + let inline (--) (x : IGlobbingPattern) pattern = x.ButNot pattern + + /// Includes a single pattern and scans the files - !! x = AllFilesMatching x + let inline (!!) x = GlobbingPattern.create x diff --git a/src/Fable.Cli/Main.fs b/src/Fable.Cli/Main.fs index 6e7871bdf5..03ccfb3a04 100644 --- a/src/Fable.Cli/Main.fs +++ b/src/Fable.Cli/Main.fs @@ -109,8 +109,13 @@ let startServerWithProcess workingDir port exec args = p.ExitCode let setGlobalParams(args: string[]) = + let verbosity = + match tryFindArgValue "--verbose" args, tryFindArgValue "--silent" args with + | Some _, _ -> Verbosity.Verbose + | None, Some _ -> Verbosity.Silent + | None, None -> Verbosity.Normal GlobalParams.Singleton.SetValues( - verbose = (tryFindArgValue "--verbose" args |> Option.isSome), + verbosity = verbosity, forcePkgs = (tryFindArgValue "--force-pkgs" args |> Option.isSome), ?replaceFiles = (tryFindArgValue "--replace-files" args), ?experimental = (tryFindArgValue "--experimental" args), @@ -140,6 +145,7 @@ Fable arguments: --cwd Working directory where the subprocess should run --port Port number where the Fable daemon should run --verbose Print more info during execution + --silent Don't print any log --force-pkgs Force a new copy of package sources into `.fable` folder. To pass arguments to the script, write them after `--`. Example: diff --git a/src/Fable.Cli/Parser.fs b/src/Fable.Cli/Parser.fs index 319eaa45fd..5e087fee14 100644 --- a/src/Fable.Cli/Parser.fs +++ b/src/Fable.Cli/Parser.fs @@ -53,7 +53,8 @@ let private parseDic (key: string) (o: JObject): IDictionary = let toCompilerOptions (msg: Message): CompilerOptions = { typedArrays = msg.typedArrays clampByteArrays = msg.clampByteArrays - verbose = GlobalParams.Singleton.Verbose + debugMode = Array.contains "DEBUG" msg.define + verbosity = GlobalParams.Singleton.Verbosity outputPublicInlinedFunctions = Array.contains "FABLE_REPL_LIB" msg.define quotations = Array.contains "FABLE_QUOTATIONS" msg.define precompiledLib = None diff --git a/src/Fable.Cli/ProjectCoreCracker.fs b/src/Fable.Cli/ProjectCoreCracker.fs index e1c21403fd..a2e18e3982 100644 --- a/src/Fable.Cli/ProjectCoreCracker.fs +++ b/src/Fable.Cli/ProjectCoreCracker.fs @@ -55,9 +55,12 @@ let private msbuildPropStringList (s: string) = let rec private projInfo additionalMSBuildProps (file: string) = let projDir = Path.GetDirectoryName file - let projectAssetsJsonPath = Path.Combine(projDir, "obj", "project.assets.json") - if not(File.Exists(projectAssetsJsonPath)) then - failwithf "Cannot find restored info for project %s" file +// Sometimes project.assets.json is not in "obj" folder, see #1843 +// Also, we're already calling "dotnet restore" before running this anyways + +// let projectAssetsJsonPath = Path.Combine(projDir, "obj", "project.assets.json") +// if not(File.Exists(projectAssetsJsonPath)) then +// failwithf "Cannot find restored info for project %s" file let getFscArgs = Dotnet.ProjInfo.Inspect.getFscArgs let getP2PRefs = Dotnet.ProjInfo.Inspect.getResolvedP2PRefs @@ -129,7 +132,7 @@ let rec private projInfo additionalMSBuildProps (file: string) = //| None -> failwith "error, 'TargetPath' property not found" let compileFilesToAbsolutePath (f: string) = - if f.EndsWith(".fs") then + if f.EndsWith(".fs") || f.EndsWith(".fsi") then if Path.IsPathRooted f then f else Path.Combine(projDir, f) else f diff --git a/src/Fable.Cli/ProjectCracker.fs b/src/Fable.Cli/ProjectCracker.fs index d65592ea7f..723869048a 100644 --- a/src/Fable.Cli/ProjectCracker.fs +++ b/src/Fable.Cli/ProjectCracker.fs @@ -9,6 +9,7 @@ open System.Xml.Linq open System.Collections.Generic open FSharp.Compiler.SourceCodeServices open Fable +open Globbing.Operators let isSystemPackage (pkgName: string) = pkgName.StartsWith("System.") @@ -131,21 +132,16 @@ let getProjectOptionsFromScript (define: string[]) scriptFile: CrackedFsproj lis for constant in define do yield "--define:" + constant |] let checker = FSharpChecker.Create() - checker.GetProjectOptionsFromScript(scriptFile, File.readAllTextNonBlocking scriptFile, + checker.GetProjectOptionsFromScript(scriptFile, + File.readAllTextNonBlocking scriptFile |> FSharp.Compiler.Text.SourceText.ofString, assumeDotNetFramework=false, otherFlags=otherFlags) |> Async.RunSynchronously |> fun (opts, _errors) -> // TODO: Check errors - // The FCS resolver uses a wrong dir for System.XXX.dll refs, we need to replace them - let badSystemDllDir = opts.OtherOptions |> Array.pick (fun o -> - if o.EndsWith("mscorlib.dll") then IO.Path.GetDirectoryName o.[3..] |> Some else None) - let goodSystemDllDir = Process.getNetcoreAssembliesDir() let dllRefs = - [ yield! Literals.SYSTEM_CORE_REFERENCES |> Seq.map (fun x -> IO.Path.Combine(goodSystemDllDir, x + ".dll")) - yield! opts.OtherOptions |> Seq.choose (fun o -> - if o.StartsWith("-r:") then - let dllRef = o.[3..] - if not(dllRef.StartsWith(badSystemDllDir)) then Some dllRef else None - else None) ] + opts.OtherOptions + |> Array.filter (fun r -> r.StartsWith("-r:")) + |> Array.map (fun r -> r.[3..]) + |> List.ofArray let fablePkgs = opts.OtherOptions @@ -213,8 +209,15 @@ let getSourcesFromFsproj (projFile: string) = | att -> att.Value::src else src)) |> List.concat - |> List.map (fun fileName -> - Path.Combine(projDir, fileName) |> Path.normalizeFullPath) + |> List.collect (fun fileName -> + Path.Combine(projDir, fileName) + |> Path.normalizeFullPath + |> function + | path when (path.Contains("*") || path.Contains("?")) -> + match !! path |> List.ofSeq with + | [] -> [ path ] + | globResults -> globResults + | path -> [ path ]) let private getDllName (dllFullPath: string) = let i = dllFullPath.LastIndexOf('/') @@ -223,7 +226,8 @@ let private getDllName (dllFullPath: string) = let private isUsefulOption (opt : string) = [ "--nowarn" "--warnon" - "--warnaserror" ] + "--warnaserror" + "--langversion" ] |> List.exists opt.StartsWith /// Use Dotnet.ProjInfo (through ProjectCoreCracker) to invoke MSBuild diff --git a/src/Fable.Cli/Util.fs b/src/Fable.Cli/Util.fs index 0b03cff832..f12ac62afe 100644 --- a/src/Fable.Cli/Util.fs +++ b/src/Fable.Cli/Util.fs @@ -2,45 +2,49 @@ namespace Fable.Cli module Literals = - let [] VERSION = "2.3.10" - let [] CORE_VERSION = "2.1.0" - let [] DEFAULT_PORT = 61225 - let [] FORCE = "force:" - let [] EXIT = "exit" - - /// System references needed to compile Fable projects, see fable-standalone/src/Metadata - let SYSTEM_CORE_REFERENCES = - [| // "Fable.Core" - // "FSharp.Core" - "mscorlib" - "netstandard" - "System.Collections" - "System.Collections.Concurrent" - "System.ComponentModel" - "System.ComponentModel.Primitives" - "System.ComponentModel.TypeConverter" - "System.Console" - "System.Core" - "System.Diagnostics.Debug" - "System.Diagnostics.Tracing" - "System.Globalization" - "System" - "System.IO" - "System.Numerics" - "System.Reflection" - "System.Reflection.Extensions" - "System.Reflection.Metadata" - "System.Reflection.Primitives" - "System.Reflection.TypeExtensions" - "System.Runtime" - "System.Runtime.Extensions" - "System.Runtime.Numerics" - "System.Text.Encoding" - "System.Text.Encoding.Extensions" - "System.Text.RegularExpressions" - "System.Threading" - "System.Threading.Tasks" - "System.ValueTuple" |] + let [] VERSION = "2.8.1" + let [] CORE_VERSION = "2.1.0" + let [] DEFAULT_PORT = 61225 + let [] FORCE = "force:" + let [] EXIT = "exit" + + /// System references needed to compile Fable projects, see fable-standalone/src/Metadata + let SYSTEM_CORE_REFERENCES = [| + // "Fable.Core" + // "FSharp.Core" + "mscorlib" + "netstandard" + "System.Collections" + "System.Collections.Concurrent" + "System.ComponentModel" + "System.ComponentModel.Primitives" + "System.ComponentModel.TypeConverter" + "System.Console" + "System.Core" + "System.Diagnostics.Debug" + "System.Diagnostics.Tools" + "System.Diagnostics.Tracing" + "System.Globalization" + "System" + "System.IO" + "System.Net.Requests" + "System.Net.WebClient" + "System.Numerics" + "System.Reflection" + "System.Reflection.Extensions" + "System.Reflection.Metadata" + "System.Reflection.Primitives" + "System.Reflection.TypeExtensions" + "System.Runtime" + "System.Runtime.Extensions" + "System.Runtime.Numerics" + "System.Text.Encoding" + "System.Text.Encoding.Extensions" + "System.Text.RegularExpressions" + "System.Threading" + "System.Threading.Tasks" + "System.ValueTuple" + |] open System.IO open System.Reflection @@ -57,9 +61,9 @@ type AgentMsg = type private TypeInThisAssembly = class end [] -type GlobalParams private (verbose, forcePkgs, fableLibraryPath, workingDir) = +type GlobalParams private (verbosity, forcePkgs, fableLibraryPath, workingDir) = static let mutable singleton: GlobalParams option = None - let mutable _verbose = verbose + let mutable _verbosity = verbosity let mutable _forcePkgs = forcePkgs let mutable _fableLibraryPath = fableLibraryPath let mutable _workingDir = workingDir @@ -83,19 +87,19 @@ type GlobalParams private (verbose, forcePkgs, fableLibraryPath, workingDir) = defaultFableLibraryPaths |> List.tryFind Directory.Exists |> Option.defaultValue (List.last defaultFableLibraryPaths) - let p = GlobalParams(false, false, fableLibraryPath, workingDir) + let p = GlobalParams(Fable.Verbosity.Normal, false, fableLibraryPath, workingDir) singleton <- Some p p - member __.Verbose: bool = _verbose + member __.Verbosity: Fable.Verbosity = _verbosity member __.ForcePkgs: bool = _forcePkgs member __.FableLibraryPath: string = _fableLibraryPath member __.WorkingDir: string = _workingDir member __.ReplaceFiles = _replaceFiles member __.Experimental = _experimental - member __.SetValues(?verbose, ?forcePkgs, ?fableLibraryPath, ?workingDir, ?replaceFiles: string, ?experimental: string) = - _verbose <- defaultArg verbose _verbose + member __.SetValues(?verbosity, ?forcePkgs, ?fableLibraryPath, ?workingDir, ?replaceFiles: string, ?experimental: string) = + _verbosity <- defaultArg verbosity _verbosity _forcePkgs <- defaultArg forcePkgs _forcePkgs _fableLibraryPath <- defaultArg fableLibraryPath _fableLibraryPath _workingDir <- defaultArg workingDir _workingDir @@ -121,12 +125,13 @@ module Log = let writerLock = obj() let always (msg: string) = - lock writerLock (fun () -> - Console.Out.WriteLine(msg) - Console.Out.Flush()) + if GlobalParams.Singleton.Verbosity <> Fable.Verbosity.Silent then + lock writerLock (fun () -> + Console.Out.WriteLine(msg) + Console.Out.Flush()) let verbose (msg: Lazy) = - if GlobalParams.Singleton.Verbose then + if GlobalParams.Singleton.Verbosity = Fable.Verbosity.Verbose then always msg.Value module Json = @@ -255,48 +260,6 @@ module Process = exitCode - let getNetcoreAssembliesDir() = - let matchProcessOutput exe args regexPattern = - let _, logOut, _ = - runProcess "." exe args - Regex.Match(String.concat " " logOut, regexPattern) - let nugetCache = - matchProcessOutput "dotnet" "nuget locals global-packages --list" - @"info\s*:\s*global-packages\s*:\s*(.+)" - |> fun m -> m.Groups.[1].Value.Trim() - let hostVersion = - matchProcessOutput "dotnet" "--info" - @"Host[\s\S]*?Version\s*:\s*([\d.]+)" - |> fun m -> m.Groups.[1].Value - let v = hostVersion.Split('.') - let netCoreAssembliesDir = Path.Combine(nugetCache, "microsoft.netcore.app", hostVersion, "ref", "netcoreapp" + v.[0] + "." + v.[1]) - - if not(Directory.Exists(netCoreAssembliesDir)) then - // Create a temp proj file that has the current Microsoft.NETCore.App as dependency. - // Restore the proj file which will add the nuget package in the global cache. - // We do this because using the System dll listed in C:\Program Files\dotnet\sdk\2.1.503 - // lead to weird behavior in the checkedProject.AssemblyContents.ImplementationFiles in Agent.fs. - let netappCore = sprintf "%s.%s" v.[0] v.[1] - let proj = sprintf """ - - - netcoreapp%s - - - - - - """ netappCore hostVersion - - let tempFolder = Path.GetTempPath() - let tempProj = System.IO.Path.Combine(tempFolder, (sprintf "%s.proj" (System.Guid.NewGuid().ToString("N")))) - - System.IO.File.WriteAllText(tempProj, proj) - let restoreCode = runProcess tempFolder "dotnet" (sprintf "restore \"%s\"" tempProj) - System.IO.File.Delete(tempProj) - - netCoreAssembliesDir - [] module Async = let fold f (state: 'State) (xs: 'T seq) = async { diff --git a/src/Fable.Core/Fable.Core.JS.fs b/src/Fable.Core/Fable.Core.JS.fs index 13479c082f..b7ee3e8c6e 100644 --- a/src/Fable.Core/Fable.Core.JS.fs +++ b/src/Fable.Core/Fable.Core.JS.fs @@ -60,14 +60,14 @@ module JS = abstract defineProperty: o: obj * propertyKey: obj * attributes: PropertyDescriptor -> obj and [] Math = - abstract E: float with get, set - abstract LN10: float with get, set - abstract LN2: float with get, set - abstract LOG2E: float with get, set - abstract LOG10E: float with get, set - abstract PI: float with get, set - abstract SQRT1_2: float with get, set - abstract SQRT2: float with get, set + abstract E: float + abstract LN10: float + abstract LN2: float + abstract LOG2E: float + abstract LOG10E: float + abstract PI: float + abstract SQRT1_2: float + abstract SQRT2: float abstract abs: x: float -> float abstract acos: x: float -> float abstract asin: x: float -> float @@ -164,7 +164,7 @@ module JS = abstract stringify: value: obj * ?replacer: (string->obj->obj) * ?space: obj -> string and [] Map<'K, 'V> = - abstract size: float with get, set + abstract size: int abstract clear: unit -> unit abstract delete: key: 'K -> bool abstract entries: unit -> seq<'K * 'V> @@ -176,7 +176,7 @@ module JS = abstract values: unit -> seq<'V> and [] MapConstructor = - [] abstract Create: ?iterable: seq<'K * 'V> -> Map<'K, 'V> + [] abstract Create: ?iterable: seq<'K * 'V> -> Map<'K, 'V> and [] WeakMap<'K, 'V> = abstract clear: unit -> unit @@ -189,7 +189,7 @@ module JS = [] abstract Create: ?iterable: seq<'K * 'V> -> WeakMap<'K, 'V> and [] Set<'T> = - abstract size: float with get, set + abstract size: int abstract add: value: 'T -> Set<'T> abstract clear: unit -> unit abstract delete: value: 'T -> bool @@ -228,7 +228,7 @@ module JS = [] abstract Create: pattern: string * ?flags: string -> Regex and [] ArrayBuffer = - abstract byteLength: int with get, set + abstract byteLength: int abstract slice: ``begin``: int * ?``end``: int -> ArrayBuffer and [] ArrayBufferConstructor = @@ -240,6 +240,9 @@ module JS = abstract byteLength: int abstract byteOffset: int + and ArrayBufferViewConstructor = + [] abstract Create: size: int -> ArrayBufferView + and [] DataView = abstract buffer: ArrayBuffer abstract byteLength: int @@ -261,10 +264,159 @@ module JS = abstract setUint16: byteOffset: int * value: uint16 * ?littleEndian: bool -> unit abstract setUint32: byteOffset: int * value: uint32 * ?littleEndian: bool -> unit - // TODO: Add constructors for other typed arrays from buffer? and [] DataViewConstructor = [] abstract Create: buffer: ArrayBuffer * ?byteOffset: int * ?byteLength: float -> DataView + and TypedArray = + abstract buffer: ArrayBuffer + abstract byteLength: int + abstract byteOffset: int + abstract length: int + abstract copyWithin: targetStartIndex:int * start:int * ? ``end``:int -> unit + abstract entries: unit -> obj + abstract keys: unit -> obj + abstract join: separator:string -> string + + and TypedArray<'T> = + inherit TypedArray + [] abstract Item: index: int -> 'T with get, set + abstract fill: value:'T * ?``begin``:int * ?``end``:int -> TypedArray<'T> + abstract filter: ('T -> int -> TypedArray<'T> -> bool) -> TypedArray<'T> + abstract filter: ('T -> int -> bool) -> TypedArray<'T> + abstract filter: ('T -> bool) -> TypedArray<'T> + abstract find: ('T -> int -> TypedArray<'T> -> bool) -> 'T option + abstract find: ('T -> int -> bool) -> 'T option + abstract find: ('T -> bool) -> 'T option + abstract findIndex: ('T -> int -> TypedArray<'T> -> bool) -> int + abstract findIndex: ('T -> int -> bool) -> int + abstract findIndex: ('T -> bool) -> int + abstract forEach: ('T -> int -> TypedArray<'T> -> bool) -> unit + abstract forEach: ('T -> int -> bool) -> unit + abstract forEach: ('T -> bool) -> unit + abstract includes: searchElement:'T * ?fromIndex:int -> bool + abstract indexOf: searchElement:'T * ?fromIndex:int -> int + abstract lastIndexOf: searchElement:'T * ?fromIndex:int -> int + abstract map: ('T -> int -> TypedArray<'T> -> 'U) -> TypedArray<'U> + abstract map: ('T -> int -> 'U) -> TypedArray<'U> + abstract map: ('T -> 'U) -> TypedArray<'U> + abstract reduce: ('State -> 'T -> int -> TypedArray<'T> -> 'State) * state:'State -> 'State + abstract reduce: ('State -> 'T -> int -> 'State) * state:'State -> 'State + abstract reduce: ('State -> 'T -> 'State) * state:'State -> 'State + abstract reduceRight: ('State -> 'T -> int -> TypedArray<'T> -> 'State) * state:'State -> 'State + abstract reduceRight: ('State -> 'T -> int -> 'State) * state:'State -> 'State + abstract reduceRight: ('State -> 'T -> 'State) * state:'State -> 'State + abstract reverse: unit -> TypedArray<'T> + abstract set: source:Array * ?offset:int -> TypedArray<'T> + abstract set: source:#TypedArray * ?offset:int -> TypedArray<'T> + abstract slice: ?``begin``:int * ?``end``:int -> TypedArray<'T> + abstract some: ('T -> int -> TypedArray<'T> -> bool) -> bool + abstract some: ('T -> int -> bool) -> bool + abstract some: ('T -> bool) -> bool + abstract sort: ?sortFunction:('T -> 'T -> int) -> bool + abstract subarray: ?``begin``:int * ?``end``:int -> TypedArray<'T> + abstract values: unit -> obj + + + and Int8Array = TypedArray + + and Int8ArrayConstructor = + [] abstract Create: size: int -> Int8Array + [] abstract Create: typedArray: TypedArray -> Int8Array + [] abstract Create: buffer: ArrayBuffer * ?offset:int * ?length:int -> Int8Array + [] abstract Create: data:obj -> Int8Array + + + and Uint8Array = TypedArray + + and Uint8ArrayConstructor = + [] abstract Create: size: int -> Uint8Array + [] abstract Create: typedArray: TypedArray -> Uint8Array + [] abstract Create: buffer: ArrayBuffer * ?offset:int * ?length:int -> Uint8Array + [] abstract Create: data:obj -> Uint8Array + + + and Uint8ClampedArray = TypedArray + + and Uint8ClampedArrayConstructor = + [] abstract Create: size: int -> Uint8ClampedArray + [] abstract Create: typedArray: TypedArray -> Uint8ClampedArray + [] abstract Create: buffer: ArrayBuffer * ?offset:int * ?length:int -> Uint8ClampedArray + [] abstract Create: data:obj -> Uint8ClampedArray + + + and Int16Array = TypedArray + + and Int16ArrayConstructor = + [] abstract Create: size: int -> Int16Array + [] abstract Create: typedArray: TypedArray -> Int16Array + [] abstract Create: buffer: ArrayBuffer * ?offset:int * ?length:int -> Int16Array + [] abstract Create: data:obj -> Int16Array + + + and Uint16Array = TypedArray + + and Uint16ArrayConstructor = + [] abstract Create: size: int -> Uint16Array + [] abstract Create: typedArray: TypedArray -> Uint16Array + [] abstract Create: buffer: ArrayBuffer * ?offset:int * ?length:int -> Uint16Array + [] abstract Create: data:obj -> Uint16Array + + + and Int32Array = TypedArray + + and Int32ArrayConstructor = + [] abstract Create: size: int -> Int32Array + [] abstract Create: typedArray: TypedArray -> Int32Array + [] abstract Create: buffer: ArrayBuffer * ?offset:int * ?length:int -> Int32Array + [] abstract Create: data:obj -> Int32Array + + + and Uint32Array = TypedArray + + and Uint32ArrayConstructor = + [] abstract Create: size: int -> Uint32Array + [] abstract Create: typedArray: TypedArray -> Uint32Array + [] abstract Create: buffer: ArrayBuffer * ?offset:int * ?length:int -> Uint32Array + [] abstract Create: data:obj -> Uint32Array + + + and Float32Array = TypedArray + + and Float32ArrayConstructor = + [] abstract Create: size: int -> Float32Array + [] abstract Create: typedArray: TypedArray -> Float32Array + [] abstract Create: buffer: ArrayBuffer * ?offset:int * ?length:int -> Float32Array + [] abstract Create: data:obj -> Float32Array + + + and Float64Array = TypedArray + + and Float64ArrayConstructor = + [] abstract Create: size: int -> Float64Array + [] abstract Create: typedArray: TypedArray -> Float64Array + [] abstract Create: buffer: ArrayBuffer * ?offset:int * ?length:int -> Float64Array + [] abstract Create: data:obj -> Float64Array + + + and BigInt64Array = TypedArray + + and BigInt64ArrayConstructor = + [] abstract Create: size: int -> BigInt64Array + [] abstract Create: typedArray: TypedArray -> BigInt64Array + [] abstract Create: buffer: ArrayBuffer * ?offset:int * ?length:int -> BigInt64Array + [] abstract Create: data:obj -> BigInt64Array + + + // no equivalent ? + //and BigUint64Array = TypedArray + + // and BigUint64ArrayConstructor = + // [] abstract Create: size: int -> BigUint64Array + // [] abstract Create: typedArray: TypedArray -> BigUint64Array + // [] abstract Create: buffer: ArrayBuffer * ?offset:int * ?length:int -> BigUint64Array + // [] abstract Create: data:obj -> BigUint64Array + + and [] Console = abstract ``assert``: ?test: bool * ?message: string * [] optionalParams: obj[] -> unit abstract clear: unit -> unit @@ -286,22 +438,10 @@ module JS = abstract warn: ?message: obj * [] optionalParams: obj[] -> unit abstract table: ?data: obj -> unit - let [] Array: ArrayConstructor = jsNative - let [] Number: NumberConstructor = jsNative let [] NaN: float = jsNative let [] Infinity: float = jsNative - let [] Object: ObjectConstructor = jsNative let [] Math: Math = jsNative - let [] Date: DateConstructor = jsNative let [] JSON: JSON = jsNative - let [] Map: MapConstructor = jsNative - let [] WeakMap: WeakMapConstructor = jsNative - let [] Set: SetConstructor = jsNative - let [] WeakSet: WeakSetConstructor = jsNative - let [] Promise: PromiseConstructor = jsNative - let [] RegExp: RegExpConstructor = jsNative - let [] ArrayBuffer: ArrayBufferConstructor = jsNative - let [] DataView: DataViewConstructor = jsNative let [] eval: string -> string = jsNative let [] isFinite: float -> bool = jsNative let [] isNaN: float -> bool = jsNative @@ -318,3 +458,103 @@ module JS = let [] clearInterval (token: int): unit = jsNative let [] debugger () : unit = jsNative let [] undefined<'a> : 'a = jsNative + + [] + let private CONSTRUCTORS_WARNING = "JS constructors are now in Fable.Core.JS.Constructors module to prevent conflicts with modules with same name" + + [] + let [] Number: NumberConstructor = jsNative + + [] + let [] Object: ObjectConstructor = jsNative + + [] + let [] Date: DateConstructor = jsNative + + [] + let [] Map: MapConstructor = jsNative + + [] + let [] WeakMap: WeakMapConstructor = jsNative + + [] + let [] Set: SetConstructor = jsNative + + [] + let [] WeakSet: WeakSetConstructor = jsNative + + [] + let [] Promise: PromiseConstructor = jsNative + + [] + let [] RegExp: RegExpConstructor = jsNative + + [] + let [] Array: ArrayConstructor = jsNative + + [] + let [] DataView: DataViewConstructor = jsNative + + [] + let [] ArrayBuffer: ArrayBufferConstructor = jsNative + + [] + let [] ArrayBufferView: ArrayBufferViewConstructor = jsNative + + [] + let [] Int8Array: Int8ArrayConstructor = jsNative + + [] + let [] Uint8Array: Uint8ArrayConstructor = jsNative + + [] + let [] Uint8ClampedArray: Uint8ClampedArrayConstructor = jsNative + + [] + let [] Int16Array: Int16ArrayConstructor = jsNative + + [] + let [] Uint16Array: Uint16ArrayConstructor = jsNative + + [] + let [] Int32Array: Int32ArrayConstructor = jsNative + + [] + let [] Uint32Array: Uint32ArrayConstructor = jsNative + + [] + let [] Float32Array: Float32ArrayConstructor = jsNative + + [] + let [] Float64Array: Float64ArrayConstructor = jsNative + + // [] + // let [] BigInt64Array: BigInt64ArrayConstructor = jsNative + + [] + module Constructors = + + let [] Number: NumberConstructor = jsNative + let [] Object: ObjectConstructor = jsNative + let [] Date: DateConstructor = jsNative + let [] Map: MapConstructor = jsNative + let [] WeakMap: WeakMapConstructor = jsNative + let [] Set: SetConstructor = jsNative + let [] WeakSet: WeakSetConstructor = jsNative + let [] Promise: PromiseConstructor = jsNative + let [] RegExp: RegExpConstructor = jsNative + let [] Array: ArrayConstructor = jsNative + let [] DataView: DataViewConstructor = jsNative + let [] ArrayBuffer: ArrayBufferConstructor = jsNative + let [] ArrayBufferView: ArrayBufferViewConstructor = jsNative + let [] Int8Array: Int8ArrayConstructor = jsNative + let [] Uint8Array: Uint8ArrayConstructor = jsNative + let [] Uint8ClampedArray: Uint8ClampedArrayConstructor = jsNative + let [] Int16Array: Int16ArrayConstructor = jsNative + let [] Uint16Array: Uint16ArrayConstructor = jsNative + let [] Int32Array: Int32ArrayConstructor = jsNative + let [] Uint32Array: Uint32ArrayConstructor = jsNative + let [] Float32Array: Float32ArrayConstructor = jsNative + let [] Float64Array: Float64ArrayConstructor = jsNative + let [] BigInt64Array: BigInt64ArrayConstructor = jsNative + // let [] BigUint64Array: BigUint64ArrayConstructor = jsNative diff --git a/src/Fable.Core/Fable.Core.Types.fs b/src/Fable.Core/Fable.Core.Types.fs index 15f9af6915..3c4e3218df 100644 --- a/src/Fable.Core/Fable.Core.Types.fs +++ b/src/Fable.Core/Fable.Core.Types.fs @@ -4,7 +4,14 @@ open System type CaseRules = | None = 0 + /// FooBar -> fooBar | LowerFirst = 1 + /// FooBar -> foo_bar + | SnakeCase = 2 + /// FooBar -> FOO_BAR + | SnakeCaseAllCaps = 3 + /// FooBar -> foo-bar + | KebabCase = 4 type JsInterfaceAttribute() = inherit Attribute() diff --git a/src/Fable.Core/Fable.Core.Util.fs b/src/Fable.Core/Fable.Core.Util.fs index b8852076de..fb6bb742ed 100644 --- a/src/Fable.Core/Fable.Core.Util.fs +++ b/src/Fable.Core/Fable.Core.Util.fs @@ -22,8 +22,8 @@ module Experimental = module Testing = type Assert = - static member AreEqual(expected: 'T, actual: 'T, ?msg: string): unit = jsNative - static member NotEqual(expected: 'T, actual: 'T, ?msg: string): unit = jsNative + static member AreEqual(actual: 'T, expected: 'T, ?msg: string): unit = jsNative + static member NotEqual(actual: 'T, expected: 'T, ?msg: string): unit = jsNative module Reflection = diff --git a/src/Fable.Core/Fable.Core.fsproj b/src/Fable.Core/Fable.Core.fsproj index 68dfe04131..ab51a92de9 100644 --- a/src/Fable.Core/Fable.Core.fsproj +++ b/src/Fable.Core/Fable.Core.fsproj @@ -4,8 +4,8 @@ Fable Core Library netstandard2.0 true - 3.0.0 - 3.0.0 + 3.1.5 + 3.1.5 diff --git a/src/Fable.Core/RELEASE_NOTES.md b/src/Fable.Core/RELEASE_NOTES.md index e7ec6cd98c..c20dad326d 100644 --- a/src/Fable.Core/RELEASE_NOTES.md +++ b/src/Fable.Core/RELEASE_NOTES.md @@ -1,3 +1,28 @@ +### 3.1.5 + +* Fixed missing indexer in JS TypedArray. + +### 3.1.4 + +* Fix JS Map constructor @Luiz-Monad + +### 3.1.3 + +* PR #1935: Put JS constructors in different module to prevent conflicts @pauldorehill + +### 3.1.2 + +* Add CaseRules.SnakeCase + +### 3.1.1 + +* Fix TypedArray bindings @Titaye + +### 3.1.0 + +* Add JS Typed Arrays @Titaye +* Fix names of arguments in Testing.Assert @zanaptak + ### 3.0.0 * Add `JsInterop.importValueDynamic` diff --git a/src/Fable.Transforms/AST/AST.Fable.fs b/src/Fable.Transforms/AST/AST.Fable.fs index 862eda14bd..0e485b83bb 100644 --- a/src/Fable.Transforms/AST/AST.Fable.fs +++ b/src/Fable.Transforms/AST/AST.Fable.fs @@ -4,9 +4,7 @@ open Fable open Fable.AST open FSharp.Compiler.SourceCodeServices open System -open System.Reflection -type EnumTypeKind = NumberEnumType | StringEnumType type FunctionTypeKind = LambdaType of Type | DelegateType of Type list type Type = @@ -19,7 +17,7 @@ type Type = | Regex | Expr of gen : Option | Number of NumberKind - | EnumType of kind: EnumTypeKind * fullName: string + | Enum of FSharpEntity | Option of genericArg: Type | Tuple of genericArgs: Type list | Array of genericArg: Type @@ -87,7 +85,8 @@ type ValueDeclarationInfo = IsPublic: bool IsMutable: bool IsEntryPoint: bool - HasSpread: bool } + HasSpread: bool + Range: SourceLocation option } type ClassImplicitConstructorInfo = { Name: string @@ -140,7 +139,6 @@ type File(sourcePath, decls, ?usedVarNames, ?inlineDependencies) = type IdentKind = | UserDeclared | CompilerGenerated - | InlinedArg | BaseValueIdent | ThisArgIdentDeclaration @@ -152,8 +150,6 @@ type Ident = Range: SourceLocation option } member x.IsCompilerGenerated = match x.Kind with CompilerGenerated -> true | _ -> false - member x.IsInlinedArg = - match x.Kind with InlinedArg -> true | _ -> false member x.IsBaseValue = match x.Kind with BaseValueIdent -> true | _ -> false member x.IsThisArgDeclaration = @@ -168,7 +164,6 @@ type ImportKind = | Library | CustomImport -type EnumKind = NumberEnum of Expr | StringEnum of Expr type NewArrayKind = ArrayValues of Expr list | ArrayAlloc of Expr type NewRecordKind = DeclaredRecord of FSharpEntity | AnonymousRecord of fieldNames: string[] @@ -181,7 +176,7 @@ type ValueKind = | StringConstant of string | NumberConstant of float * NumberKind | RegexConstant of source: string * flags: RegexFlag list - | Enum of EnumKind * enumFullName: string + | EnumConstant of Expr * FSharpEntity | NewOption of value: Expr option * Type | NewArray of NewArrayKind * Type | NewList of headAndTail: (Expr * Expr) option * Type @@ -199,12 +194,7 @@ type ValueKind = | StringConstant _ -> String | NumberConstant(_,kind) -> Number kind | RegexConstant _ -> Regex - | Enum(kind, fullName) -> - let kind = - match kind with - | NumberEnum _ -> NumberEnumType - | StringEnum _ -> StringEnumType - EnumType(kind, fullName) + | EnumConstant(_, ent) -> Enum ent | NewOption(_, t) -> Option t | NewArray(_, t) -> Array t | NewList(_, t) -> List t @@ -279,7 +269,7 @@ type OperationKind = type GetKind = | ExprGet of Expr | TupleGet of int - | FieldGet of string * hasDoubleEvalRisk: bool * fieldType: Type + | FieldGet of string * isFieldMutable: bool * fieldType: Type | UnionField of FSharpField * FSharpUnionCase * fieldType: Type | UnionTag | ListHead diff --git a/src/Fable.Transforms/FSharp2Fable.Util.fs b/src/Fable.Transforms/FSharp2Fable.Util.fs index 9052299dfe..b9d2a6b619 100644 --- a/src/Fable.Transforms/FSharp2Fable.Util.fs +++ b/src/Fable.Transforms/FSharp2Fable.Util.fs @@ -49,7 +49,10 @@ type IFableCompiler = module Helpers = let rec nonAbbreviatedType (t: FSharpType) = - if t.IsAbbreviation then nonAbbreviatedType t.AbbreviatedType + let isSameType (t1: FSharpType) (t2: FSharpType) = + t1.HasTypeDefinition && t2.HasTypeDefinition && (t1.TypeDefinition = t2.TypeDefinition) + if t.IsAbbreviation && not (isSameType t t.AbbreviatedType) then + nonAbbreviatedType t.AbbreviatedType elif t.HasTypeDefinition then let abbr = t.AbbreviatedType // .IsAbbreviation doesn't eval to true for generic numbers @@ -161,6 +164,12 @@ module Helpers = if fullName = fullName' then Some att else None | None -> None) + let hasAtt fullName (atts: #seq) = + atts |> Seq.exists (fun att -> + match att.AttributeType.TryFullName with + | Some fullName' -> fullName = fullName' + | _ -> false) + let tryDefinition (typ: FSharpType) = let typ = nonAbbreviatedType typ if typ.HasTypeDefinition then @@ -197,8 +206,8 @@ module Helpers = else not memb.Accessibility.IsPrivate let makeRange (r: Range.range) = - { start = { line = r.StartLine; column = r.StartColumn+1 } - ``end``= { line = r.EndLine; column = r.EndColumn+1 } + { start = { line = r.StartLine; column = r.StartColumn } + ``end``= { line = r.EndLine; column = r.EndColumn } identifierName = None } let makeRangeFrom (fsExpr: FSharpExpr) = @@ -221,13 +230,10 @@ module Helpers = |> Option.map (fun att -> att.ConstructorArguments.[0] |> snd |> string) /// Apply case rules to case name if there's no explicit compiled name - let applyCaseRule (rule: CaseRules) (unionCase: FSharpUnionCase) = + let transformStringEnum (rule: CaseRules) (unionCase: FSharpUnionCase) = match unionCaseCompiledName unionCase with | Some name -> name - | None -> - match rule with - | CaseRules.LowerFirst -> Naming.lowerFirst unionCase.Name - | CaseRules.None | _ -> unionCase.Name + | None -> Naming.applyCaseRule rule unionCase.Name |> makeStrConst // let isModuleMember (memb: FSharpMemberOrFunctionOrValue) = @@ -253,14 +259,17 @@ module Helpers = | None -> false | _ -> false + let rec getAllInterfaceMembers (ent: FSharpEntity) = + seq { + yield! ent.MembersFunctionsAndValues + for parent in ent.DeclaredInterfaces do + match tryDefinition parent with + | Some(e, _) -> yield! getAllInterfaceMembers e + | None -> () + } + let rec isInterfaceEmpty (ent: FSharpEntity) = - ent.MembersFunctionsAndValues.Count = 0 - && (if ent.DeclaredInterfaces.Count > 0 then - ent.DeclaredInterfaces |> Seq.forall (fun ifc -> - match tryDefinition ifc with - | Some(e, _) -> isInterfaceEmpty e - | None -> true) - else true) + getAllInterfaceMembers ent |> Seq.isEmpty /// Test if the name corresponds to this interface or anyone in its hierarchy let rec testInterfaceHierarcy interfaceFullname interfaceType = @@ -281,8 +290,8 @@ module Helpers = let hasParamSeq (memb: FSharpMemberOrFunctionOrValue) = Seq.tryLast memb.CurriedParameterGroups |> Option.bind Seq.tryLast - |> Option.bind (fun lastParam -> tryFindAtt Atts.paramList lastParam.Attributes) - |> Option.isSome + |> Option.map (fun lastParam -> hasAtt Atts.paramList lastParam.Attributes) + |> Option.defaultValue false hasParamArray memb || hasParamSeq memb @@ -427,16 +436,25 @@ module Patterns = /// This matches the boilerplate generated to wrap .NET events from F# let (|CreateEvent|_|) = function - | Call(Some(Call(None, createEvent,_,_, - [Lambda(_eventDelegate, Call(Some callee, addEvent,[],[],[Value _eventDelegate'])); - Lambda(_eventDelegate2, Call(Some _callee2, _removeEvent,[],[],[Value _eventDelegate2'])); - Lambda(_callback, NewDelegate(_, Lambda(_delegateArg0, Lambda(_delegateArg1, Application(Value _callback',[],[Value _delegateArg0'; Value _delegateArg1'])))))])), - memb, typArgs, methTypArgs, args) - when createEvent.FullName = Types.createEvent -> + | Call(None,createEvent,_,_, + [Lambda(_eventDelegate, Call(Some callee, addEvent,[],[],[Value _eventDelegate'])); + Lambda(_eventDelegate2, Call(Some _callee2, _removeEvent,[],[],[Value _eventDelegate2'])); + Lambda(_callback, NewDelegate(_, Lambda(_delegateArg0, Lambda(_delegateArg1, Application(Value _callback',[],[Value _delegateArg0'; Value _delegateArg1'])))))]) + when createEvent.FullName = Types.createEvent -> let eventName = addEvent.CompiledName.Replace("add_","") + Some (callee, eventName) + | _ -> None + + let (|CallCreateEvent|_|) = function + | Call(Some(CreateEvent(callee, eventName)), memb, typArgs, methTypArgs, args) -> Some (callee, eventName, memb, typArgs, methTypArgs, args) | _ -> None + let (|BindCreateEvent|_|) = function + | Let((var, CreateEvent(value, eventName)), body) -> + Some (var, value, eventName, body) + | _ -> None + let (|ConstructorCall|_|) = function | NewObject(baseCall, genArgs, baseArgs) -> Some(baseCall, genArgs, baseArgs) | Call(None, baseCall, genArgs1, genArgs2, baseArgs) when baseCall.IsConstructor -> @@ -522,9 +540,15 @@ module TypeHelpers = open Helpers open Patterns + // Sometimes the names of user-declared and compiler-generated clash, see #1900 + let genParamName (genParam: FSharpGenericParameter) = + if genParam.IsCompilerGenerated then genParam.Name + "$" + else genParam.Name + let resolveGenParam ctxTypeArgs (genParam: FSharpGenericParameter) = - match Map.tryFind genParam.Name ctxTypeArgs with - | None -> Fable.GenericParam genParam.Name + let name = genParamName genParam + match Map.tryFind name ctxTypeArgs with + | None -> Fable.GenericParam name | Some typ -> typ let rec makeGenArgs (com: ICompiler) ctxTypeArgs (genArgs: IList) = @@ -545,35 +569,39 @@ module TypeHelpers = |> Seq.find (fun f -> f.DisplayName = "Invoke") invokeMember.CurriedParameterGroups.[0] |> Seq.map (fun p -> p.Type), invokeMember.ReturnParameter.Type - let genArgs = Seq.zip (tdef.GenericParameters |> Seq.map (fun x -> x.Name)) genArgs |> Map + let genArgs = Seq.zip (tdef.GenericParameters |> Seq.map genParamName) genArgs |> Map let resolveType (t: FSharpType) = - if t.IsGenericParameter then Map.find t.GenericParameter.Name genArgs else t + if t.IsGenericParameter then Map.find (genParamName t.GenericParameter) genArgs else t let argTypes = argTypes |> Seq.map (resolveType >> makeType com ctxTypeArgs) |> Seq.toList let returnType = returnType |> resolveType |> makeType com ctxTypeArgs Fable.FunctionType(Fable.DelegateType argTypes, returnType) and makeTypeFromDef (com: ICompiler) ctxTypeArgs (genArgs: IList) (tdef: FSharpEntity) = - match getEntityFullName tdef, tdef with - | _ when tdef.IsArrayType -> makeGenArgs com ctxTypeArgs genArgs |> List.head |> Fable.Array - | _ when tdef.IsDelegate -> makeTypeFromDelegate com ctxTypeArgs genArgs tdef - | fullName, _ when tdef.IsEnum -> Fable.EnumType(Fable.NumberEnumType, fullName) - // Fable "primitives" - | Types.object, _ -> Fable.Any - | Types.unit, _ -> Fable.Unit - | Types.bool, _ -> Fable.Boolean - | Types.char, _ -> Fable.Char - | Types.string, _ -> Fable.String - | Types.regex, _ -> Fable.Regex - | Types.valueOption, _ - | Types.option, _ -> makeGenArgs com ctxTypeArgs genArgs |> List.head |> Fable.Option - | Types.resizeArray, _ -> makeGenArgs com ctxTypeArgs genArgs |> List.head |> Fable.Array - | Types.list, _ -> makeGenArgs com ctxTypeArgs genArgs |> List.head |> Fable.List - | NumberKind kind, _ -> Fable.Number kind - // Special attributes - | fullName, ContainsAtt Atts.stringEnum _ -> Fable.EnumType(Fable.StringEnumType, fullName) - | _, ContainsAtt Atts.erase _ -> makeGenArgs com ctxTypeArgs genArgs |> Fable.ErasedUnion - // Rest of declared types - | _ -> Fable.DeclaredType(tdef, makeGenArgs com ctxTypeArgs genArgs) + if tdef.IsArrayType then + makeGenArgs com ctxTypeArgs genArgs |> List.head |> Fable.Array + elif tdef.IsDelegate then + makeTypeFromDelegate com ctxTypeArgs genArgs tdef + elif tdef.IsEnum then + Fable.Enum tdef + else + match getEntityFullName tdef with + // Fable "primitives" + | Types.object -> Fable.Any + | Types.unit -> Fable.Unit + | Types.bool -> Fable.Boolean + | Types.char -> Fable.Char + | Types.string -> Fable.String + | Types.regex -> Fable.Regex + | Types.valueOption + | Types.option -> makeGenArgs com ctxTypeArgs genArgs |> List.head |> Fable.Option + | Types.resizeArray -> makeGenArgs com ctxTypeArgs genArgs |> List.head |> Fable.Array + | Types.list -> makeGenArgs com ctxTypeArgs genArgs |> List.head |> Fable.List + | NumberKind kind -> Fable.Number kind + // Special attributes + | _ when hasAtt Atts.stringEnum tdef.Attributes -> Fable.String + | _ when hasAtt Atts.erase tdef.Attributes -> makeGenArgs com ctxTypeArgs genArgs |> Fable.ErasedUnion + // Rest of declared types + | _ -> Fable.DeclaredType(tdef, makeGenArgs com ctxTypeArgs genArgs) and makeType (com: ICompiler) (ctxTypeArgs: Map) (NonAbbreviatedType t) = // Generic parameter (try to resolve for inline functions) @@ -630,7 +658,7 @@ module TypeHelpers = |> Seq.toList let isAbstract (ent: FSharpEntity) = - tryFindAtt Atts.abstractClass ent.Attributes |> Option.isSome + hasAtt Atts.abstractClass ent.Attributes let tryGetInterfaceTypeFromMethod (meth: FSharpMemberOrFunctionOrValue) = if meth.ImplementedAbstractSignatures.Count > 0 @@ -777,7 +805,7 @@ module Util = Fable.TryCatch(body, catchClause, finalizer, r) let matchGenericParams (genArgs: Fable.Type seq) (genParams: FSharpGenericParameter seq) = - Seq.zip (genParams |> Seq.map (fun x -> x.Name)) genArgs + Seq.zip (genParams |> Seq.map genParamName) genArgs let matchGenericParamsFrom (memb: FSharpMemberOrFunctionOrValue) (genArgs: Fable.Type seq) = let genArgsLen = Seq.length genArgs @@ -1082,10 +1110,11 @@ module Util = let inExpr = com.GetInlineExpr(memb) let ctx, bindings = ((ctx, []), foldArgs [] (inExpr.Args, args)) ||> List.fold (fun (ctx, bindings) (argId, arg) -> - // Change type and mark ident as compiler-generated so it can be optimized + // Change type and mark ident as compiler-generated so Fable also + // tries to inline it in DEBUG mode (some patterns depend on this) let ident = { makeIdentFrom com ctx argId with Type = arg.Type - Kind = Fable.InlinedArg } + Kind = Fable.CompilerGenerated } let ctx = putIdentInScope ctx argId ident (Some arg) ctx, (ident, arg)::bindings) let ctx = { ctx with GenericArgs = genArgs.Value |> Map @@ -1167,8 +1196,9 @@ module Util = || memb.IsDispatchSlot -> callInstanceMember com r typ argInfo memb | _ -> - if isModuleValue - then memberRefTyped com ctx r typ memb + if isModuleValue then + let typ = makeType com ctx.GenericArgs memb.FullType + memberRefTyped com ctx r typ memb else let argInfo = if not argInfo.IsBaseOrSelfConstructorCall && isSelfConstructorCall ctx memb @@ -1180,7 +1210,7 @@ module Util = let typ = makeType com ctx.GenericArgs v.FullType match v, v.DeclaringEntity with | _ when typ = Fable.Unit -> - if com.Options.verbose && not v.IsCompilerGenerated then // See #1516 + if com.Options.verbosity = Verbosity.Verbose && not v.IsCompilerGenerated then // See #1516 sprintf "Value %s is replaced with unit constant" v.DisplayName |> addWarning com ctx.InlinePath r Fable.Value(Fable.UnitConstant, r) diff --git a/src/Fable.Transforms/FSharp2Fable.fs b/src/Fable.Transforms/FSharp2Fable.fs index d1bece643c..08f9fbc5d7 100644 --- a/src/Fable.Transforms/FSharp2Fable.fs +++ b/src/Fable.Transforms/FSharp2Fable.fs @@ -1,7 +1,7 @@ module rec Fable.Transforms.FSharp2Fable.Compiler open System.Collections.Generic -open FSharp.Compiler.Ast +open FSharp.Compiler.SyntaxTree open FSharp.Compiler.SourceCodeServices open Fable @@ -59,10 +59,9 @@ let private transformNewUnion com ctx r (fsType : FSharpType) | _ -> "Erased Union Cases must have one single field: " + (getFsTypeFullName fsType) |> addErrorAndReturnNull com ctx.InlinePath r | StringEnum(tdef, rule) -> - let enumName = defaultArg tdef.TryFullName Naming.unknown match argExprs with - | [] -> Fable.Enum(applyCaseRule rule unionCase |> Fable.StringEnum, enumName) |> makeValue r - | _ -> "StringEnum types cannot have fields: " + enumName + | [] -> transformStringEnum rule unionCase + | _ -> sprintf "StringEnum types cannot have fields: %O" tdef.TryFullName |> addErrorAndReturnNull com ctx.InlinePath r | OptionUnion typ -> let typ = makeType com ctx.GenericArgs typ @@ -116,13 +115,17 @@ let private transformTraitCall com (ctx: Context) r typ (sourceTypes: FSharpType | thisArg::args, _::argTypes when isInstance -> Some thisArg, args, argTypes | args, argTypes -> None, args, argTypes - sourceTypes |> Seq.tryPick (fun t -> - match makeType com ctx.GenericArgs t with + sourceTypes |> Seq.tryPick (fun sourceType -> + let t = makeType com ctx.GenericArgs sourceType + match t with // Types with specific entry in Fable.AST // TODO: Check other types like booleans or numbers? | Fable.String -> let info = makeCallInfo traitName Types.string argTypes [] Replacements.strings com ctx r typ info thisArg args + | Fable.Tuple genArgs -> + let info = makeCallInfo traitName (getTypeFullName false t) argTypes genArgs + Replacements.tuples com ctx r typ info thisArg args | Fable.Option genArg -> let info = makeCallInfo traitName Types.option argTypes [genArg] Replacements.options com ctx r typ info thisArg args @@ -244,7 +247,7 @@ let private transformUnionCaseTest (com: IFableCompiler) (ctx: Context) r let fi = unionCase.UnionCaseFields.[0] let typ = if fi.FieldType.IsGenericParameter then - let name = fi.FieldType.GenericParameter.Name + let name = genParamName fi.FieldType.GenericParameter let index = tdef.GenericParameters |> Seq.findIndex (fun arg -> arg.Name = name) @@ -259,7 +262,7 @@ let private transformUnionCaseTest (com: IFableCompiler) (ctx: Context) r let kind = Fable.ListTest(unionCase.CompiledName <> "Empty") return Fable.Test(unionExpr, kind, r) | StringEnum(_, rule) -> - return makeEqOp r unionExpr (applyCaseRule rule unionCase) BinaryEqualStrict + return makeEqOp r unionExpr (transformStringEnum rule unionCase) BinaryEqualStrict | DiscriminatedUnion(tdef,_) -> let kind = Fable.UnionCaseTest(unionCase, tdef) return Fable.Test(unionExpr, kind, r) @@ -308,7 +311,7 @@ let private transformAttribute (com: IFableCompiler) (ctx : Context) (a : FSharp match ctor with | Some ctor -> let args = - a.ConstructorArguments |> Seq.toList |> List.map (fun (t,v) -> + a.ConstructorArguments |> Seq.toList |> List.map (fun (_,v) -> match v with | :? string as str -> Fable.Value(Fable.StringConstant str, None) | :? int8 as v -> Fable.Value(Fable.NumberConstant(float v, NumberKind.Int8), None) @@ -550,8 +553,10 @@ let private transformExpr (com: IFableCompiler) (ctx: Context) fsExpr = let! (inpExpr: Fable.Expr) = transformExpr com ctx inpExpr let t = makeType com ctx.GenericArgs targetType match tryDefinition targetType with - | Some(_, Some (Types.ienumerableGeneric | Types.ienumerable)) -> - return Replacements.toSeq t inpExpr + | Some(_, Some fullName) -> + match fullName with + | Types.ienumerableGeneric | Types.ienumerable -> return Replacements.toSeq t inpExpr + | _ -> return Fable.TypeCast(inpExpr, t) | _ -> return Fable.TypeCast(inpExpr, t) // TypeLambda is a local generic lambda @@ -618,7 +623,7 @@ let private transformExpr (com: IFableCompiler) (ctx: Context) fsExpr = let body = Fable.Let([ident1, id1Expr], Fable.Let([ident2, id2Expr], restExpr)) return Fable.Let([tupleIdent, tupleExpr], body) - | CreateEvent (callee, eventName, memb, ownerGenArgs, membGenArgs, membArgs) -> + | CallCreateEvent (callee, eventName, memb, ownerGenArgs, membGenArgs, membArgs) -> let! callee = transformExpr com ctx callee let! args = transformExprList com ctx membArgs let callee = get None Fable.Any callee eventName @@ -626,6 +631,13 @@ let private transformExpr (com: IFableCompiler) (ctx: Context) fsExpr = let typ = makeType com ctx.GenericArgs fsExpr.Type return makeCallFrom com ctx (makeRangeFrom fsExpr) typ false genArgs (Some callee) args memb + | BindCreateEvent (var, value, eventName, body) -> + let! value = transformExpr com ctx value + let value = get None Fable.Any value eventName + let ctx, ident = putBindingInScope com ctx var value + let! body = transformExpr com ctx body + return Fable.Let([ident, value], body) + // TODO: Detect if it's ResizeArray and compile as FastIntegerForLoop? | ForOf (PutArgInScope com ctx (newContext, ident), value, body) -> let! value = transformExpr com ctx value @@ -651,7 +663,9 @@ let private transformExpr (com: IFableCompiler) (ctx: Context) fsExpr = |> makeLoop (makeRangeFrom fsExpr) // Values - | BasicPatterns.Const(value, FableType com ctx typ) -> + | BasicPatterns.Const(value, typ) -> + let typ = nonAbbreviatedType typ + let typ = makeType com ctx.GenericArgs typ return Replacements.makeTypeConst (makeRangeFrom fsExpr) typ value | BasicPatterns.BaseValue typ -> @@ -693,7 +707,7 @@ let private transformExpr (com: IFableCompiler) (ctx: Context) fsExpr = return makeValueFrom com ctx r var | BasicPatterns.DefaultValue (FableType com ctx typ) -> - return Replacements.defaultof typ + return Replacements.defaultof com ctx typ // Assignments | BasicPatterns.Let((var, value), body) -> @@ -1063,7 +1077,7 @@ let private transformExpr (com: IFableCompiler) (ctx: Context) fsExpr = let mem = transformMemberInfo com ctx m |> Option.get let margs = margs |> List.toArray |> Array.map (makeType com ctx.GenericArgs) d, t, mem, margs - | QuotationPickler.MemberDescription.UnionCase (c, targs) -> + | QuotationPickler.MemberDescription.UnionCase (c, _targs) -> let d = c.ReturnType.TypeDefinition let t = makeType com ctx.GenericArgs c.ReturnType let mem = transformUnionCaseAsMember com ctx c @@ -1115,7 +1129,9 @@ let private isIgnoredNonAttachedMember (meth: FSharpMemberOrFunctionOrValue) = let private isRecordLike (ent: FSharpEntity) = ent.IsFSharpRecord || ent.IsFSharpExceptionDeclaration - || ((ent.IsClass || ent.IsValueType) && not ent.IsMeasure && not (hasImplicitConstructor ent)) + || ((ent.IsClass || ent.IsValueType) && not ent.IsMeasure + && not ent.IsEnum + && not (hasImplicitConstructor ent)) let private checkAttachedMemberConflicts com isRecordLike (ent: FSharpEntity) = let attachedMembers = @@ -1274,7 +1290,8 @@ let private transformImport com r typ isMutable isPublic name selector path = // TODO: Check if they're mutable, see #1314 IsMutable = isMutable IsEntryPoint = false - HasSpread = false } + HasSpread = false + Range = None} let fableValue = Fable.Import(selector, path, Fable.CustomImport, typ, r) [Fable.ValueDeclaration(fableValue, info)] @@ -1298,7 +1315,8 @@ let private transformMemberValue (com: IFableCompiler) ctx isPublic name (memb: IsPublic = isPublic IsMutable = memb.IsMutable IsEntryPoint = false - HasSpread = false } + HasSpread = false + Range = makeRange memb.DeclarationLocation |> Some } [Fable.ValueDeclaration(fableValue, info)] let private functionDeclarationInfo name isPublic (memb: FSharpMemberOrFunctionOrValue): Fable.ValueDeclarationInfo = @@ -1306,7 +1324,8 @@ let private functionDeclarationInfo name isPublic (memb: FSharpMemberOrFunctionO IsPublic = isPublic IsMutable = memb.IsMutable IsEntryPoint = memb.Attributes |> hasAttribute Atts.entryPoint - HasSpread = hasSeqSpread memb } + HasSpread = hasSeqSpread memb + Range = makeRange memb.DeclarationLocation |> Some } let private transformMemberFunction (com: IFableCompiler) ctx isPublic name (memb: FSharpMemberOrFunctionOrValue) args (body: FSharpExpr) = let bodyCtx, args = bindMemberArgs com ctx args diff --git a/src/Fable.Transforms/Fable.Transforms.fsproj b/src/Fable.Transforms/Fable.Transforms.fsproj index 1743f290c1..67fc5c3d5e 100644 --- a/src/Fable.Transforms/Fable.Transforms.fsproj +++ b/src/Fable.Transforms/Fable.Transforms.fsproj @@ -25,7 +25,9 @@ - + + + \ No newline at end of file diff --git a/src/Fable.Transforms/Fable2Babel.fs b/src/Fable.Transforms/Fable2Babel.fs index bfc93ba95a..b858018d92 100644 --- a/src/Fable.Transforms/Fable2Babel.fs +++ b/src/Fable.Transforms/Fable2Babel.fs @@ -6,8 +6,6 @@ open Fable.AST open Fable.AST.Babel open System.Collections.Generic open FSharp.Compiler.SourceCodeServices -open System.Linq.Expressions -open Fable.AST.Babel type ReturnStrategy = | Return @@ -23,7 +21,6 @@ type Import = type ITailCallOpportunity = abstract Label: string abstract Args: string list - abstract ReplaceArgs: bool abstract IsRecursiveRef: Fable.Expr -> bool type Context = @@ -59,27 +56,14 @@ module Util = | args -> args type NamedTailCallOpportunity(com: ICompiler, name, args: Fable.Ident list) = - let getTailCallArgIds (com: ICompiler) (args: Fable.Ident list) = - // If some arguments are functions we need to capture the current values to - // prevent delayed references from getting corrupted, for that we use block-scoped - // ES2015 variable declarations. See #681 - let replaceArgs = - args |> List.exists (fun arg -> - match arg.Type with - | Fable.FunctionType _ -> true - | _ -> false) - replaceArgs, args |> List.map (fun arg -> - if replaceArgs - then com.GetUniqueVar("arg") - else arg.Name) - let replaceArgs, argIds = - discardUnitArg args |> getTailCallArgIds com + // Capture the current argument values to prevent delayed references from getting corrupted, + // for that we use block-scoped ES2015 variable declarations. See #681, #1859 + let argIds = discardUnitArg args |> List.map (fun arg -> com.GetUniqueVar(arg.Name)) interface ITailCallOpportunity with member __.Label = name member __.Args = argIds - member __.ReplaceArgs = replaceArgs member __.IsRecursiveRef(e) = - match e with Fable.IdentExpr id -> name = id.Name | _ -> false + match e with Fable.IdentExpr id -> name = id.Name | _ -> false let prepareBoundThis (boundThis: string) (args: Fable.Ident list) = match args with @@ -140,8 +124,8 @@ module Util = let memberFromName memberName: Expression * bool = if Naming.hasIdentForbiddenChars memberName - then upcast StringLiteral memberName, true - else upcast Identifier memberName, false + then upcast StringLiteral(memberName), true + else upcast Identifier(memberName), false let memberFromExpr (com: IBabelCompiler) ctx memberExpr: Expression * bool = match memberExpr with @@ -301,7 +285,7 @@ module Util = | :? NumericLiteral, _ -> e // TODO: Unsigned ints seem to cause problems, should we check only Int32 here? | _, Fable.Number(Int8 | Int16 | Int32) - | _, Fable.EnumType(Fable.NumberEnumType, _) -> + | _, Fable.Enum _ -> BinaryExpression(BinaryOrBitwise, e, NumericLiteral(0.)) :> Expression | _ -> e @@ -313,7 +297,7 @@ module Util = | U2.Case2 e -> BlockStatement [|ReturnStatement(e, ?loc=e.Loc)|] upcast FunctionExpression(args, body, ?id=id) - let optimizeTailCall (com: IBabelCompiler) (ctx: Context) (tc: ITailCallOpportunity) args = + let optimizeTailCall (com: IBabelCompiler) (ctx: Context) range (tc: ITailCallOpportunity) args = let rec checkCrossRefs tempVars allArgs = function | [] -> tempVars | (argId, _arg)::rest -> @@ -339,7 +323,7 @@ module Util = let arg = FableTransforms.replaceValues tempVarReplacements arg let arg = com.TransformAsExpr(ctx, arg) yield assign None (Identifier argId) arg |> ExpressionStatement :> Statement - yield upcast ContinueStatement(Identifier tc.Label) + yield upcast ContinueStatement(Identifier tc.Label, ?loc=range) |] let transformImport (com: IBabelCompiler) ctx r (selector: Fable.Expr) (path: Fable.Expr) kind = @@ -354,9 +338,12 @@ module Util = let transformCast (com: IBabelCompiler) (ctx: Context) t e: Expression = match t with - | Fable.DeclaredType(ent,[_]) when ent.TryFullName = Some Types.ienumerableGeneric -> - match e with - | Fable.Value(Replacements.ListLiteral(exprs, _),_) -> + // Optimization for (numeric) array or list literals casted to seq + // Done at the very end of the compile pipeline to get more opportunities + // of matching cast and literal expressions after resolving pipes, inlining... + | Fable.DeclaredType(ent,[_]) -> + match ent.TryFullName, e with + | Some Types.ienumerableGeneric, Replacements.ArrayOrListLiteral(exprs, _) -> makeArray com ctx exprs | _ -> com.TransformAsExpr(ctx, e) | _ -> com.TransformAsExpr(ctx, e) @@ -368,19 +355,19 @@ module Util = let rec transformMemberReflectionInfosNew (com : IBabelCompiler) ctx r (self : Expression) (generics : Expression) (ent: FSharpEntity) (mems : Fable.MemberInfo[]) = let genMap = ent.GenericParameters |> Seq.mapi (fun i x -> x.Name, i) |> Map.ofSeq - + let genMap (name : string) : Option = match Map.tryFind name genMap with - | Some i -> + | Some i -> MemberExpression(generics, NumericLiteral(float i), true) :> Expression |> Some | None -> - None + None let newUnionCase (self : Expression) (tag : int) (name : string) (attributes : ArrayExpression) (fields : array) (invoke : ArrowFunctionExpression) = let info = coreValue com ctx "Reflection" "NUnionCaseInfo" let fields = fields |> Array.map (fun (n,t) -> ArrayExpression [| StringLiteral n; transformTypeInfo com ctx r [||] genMap t |] :> Expression) NewExpression(info, [|self; NumericLiteral(float tag); StringLiteral(name); attributes; ArrayExpression fields; invoke|]) :> Expression - + let newParameter (p : Fable.ParameterInfo) = let par = coreValue com ctx "Reflection" "NParameterInfo" NewExpression(par, [| StringLiteral p.Name; transformTypeInfo com ctx r [||] genMap p.Type |]) :> Expression @@ -403,9 +390,9 @@ module Util = let prop = coreValue com ctx "Reflection" "NPropertyInfo" let ret = transformTypeInfo com ctx r [||] genMap ret - let args = [|self; StringLiteral name :> Expression; ret; BooleanLiteral isStatic :> Expression; BooleanLiteral isFSharp :> Expression; attributes :> Expression|] + let args = [|self; StringLiteral name :> Expression; ret; BooleanLiteral isStatic :> Expression; BooleanLiteral isFSharp :> Expression; attributes :> Expression|] - let args = + let args = match get, set with | Some get, Some set -> Array.append args [| get; set |] | Some get, None -> Array.append args [| get |] @@ -414,18 +401,17 @@ module Util = NewExpression(prop, args) :> Expression - let newField (self : Expression) (isStatic : bool) (ret : Fable.Type) (name : string) (attributes : ArrayExpression) (get : Option) = let fld = coreValue com ctx "Reflection" "NFieldInfo" let ret = transformTypeInfo com ctx r [||] genMap ret match get with - | Some get -> + | Some get -> NewExpression(fld, [|self; StringLiteral name; ret; BooleanLiteral isStatic; attributes; get|]) :> Expression | None -> NewExpression(fld, [|self; StringLiteral name; ret; BooleanLiteral isStatic; attributes|]) :> Expression mems |> Array.map (fun x -> - let attributes = ArrayExpression (x.Attributes |> Array.map (fun (fullname, e) -> + let attributes = ArrayExpression (x.Attributes |> Array.map (fun (fullname, e) -> let value = com.TransformAsExpr(ctx, e) let typ = StringLiteral(fullname) //com.TransformAsExpr(ctx, Fable.Value(Fable.TypeInfo e.Type, None)) @@ -440,12 +426,12 @@ module Util = let invoke = let args = pars |> Array.mapi (fun i _ -> Identifier(sprintf "a%d" i)) let allArgs = - Array.append + Array.append [| NumericLiteral(float tag) :> Expression; StringLiteral(mangledName) :> Expression |] (Array.map (fun a -> a :> Expression) args) let body = NewExpression(Identifier(mangledTypeName), allArgs) :> Expression - ArrowFunctionExpression(Array.map toPattern args, U2.Case2 body) + ArrowFunctionExpression(Array.map toPattern args, U2.Case2 body) newUnionCase self tag name attributes pars invoke | Fable.MemberInfoKind.Constructor(pars, invoke) -> @@ -453,13 +439,13 @@ module Util = newConstructor self attributes pars invoke | Fable.MemberInfoKind.Method(genericParameters, name, pars, ret, isStatic, invoke) -> - let invoke = - match invoke with - | Some invoke -> com.TransformAsExpr(ctx, invoke) - | _ -> + let invoke = + match invoke with + | Some invoke -> com.TransformAsExpr(ctx, invoke) + | _ -> ArrowFunctionExpression([||], U2.Case1 (BlockStatement [| ThrowStatement(NewExpression(Identifier "Error", [| StringLiteral "cannot invoke method" :> Expression |])) :> Statement - |])) :> Expression + |])) :> Expression newMethod self genericParameters isStatic ret name attributes pars invoke @@ -472,6 +458,7 @@ module Util = let get = get |> Option.map (fun g -> com.TransformAsExpr(ctx, g)) newField self isStatic typ name attributes get ) + and transformRecordReflectionInfo (com : IBabelCompiler) ctx r (ent: FSharpEntity) declaringName (mems : Fable.MemberInfo[]) generics = // TODO: Refactor these three bindings to reuse in transformUnionReflectionInfo let fullname = defaultArg ent.TryFullName Naming.unknown @@ -485,12 +472,12 @@ module Util = let fields = FunctionExpression([|toPattern self; toPattern gen|], BlockStatement [| ReturnStatement(ArrayExpression nMembers) :> Statement |]) :> Expression let decl = match declaringName with - | Some decl -> + | Some decl -> let reflName = decl + "$" + Naming.reflectionSuffix CallExpression(Identifier reflName, [||]) :> Expression - | None -> + | None -> NullLiteral() :> Expression - + [|fullnameExpr; genParamNames; upcast ArrayExpression generics; fields; decl|] |> coreLibCall com ctx None "Reflection" "ntype" // let members = transformMemberReflectionInfos com ctx r ent mems generics @@ -507,17 +494,25 @@ module Util = // Array.zip genParamNames generics |> Map // let cases = // ent.UnionCases |> Seq.map (fun uci -> - // let fieldTypes = - // uci.UnionCaseFields |> Seq.map (fun fi -> - // FSharp2Fable.TypeHelpers.makeType com Map.empty fi.FieldType - // |> transformTypeInfo com ctx r mems genMap) |> Seq.toArray + // let fieldInfos = + // uci.UnionCaseFields + // |> Seq.map (fun fi -> + // let fieldType = + // FSharp2Fable.TypeHelpers.makeType com Map.empty fi.FieldType + // |> transformTypeInfo com ctx r genMap + // ArrayExpression [| + // fi.Name |> StringLiteral :> Expression + // fieldType + // |] :> Expression + // ) + // |> Seq.toArray // let caseInfo = - // if fieldTypes.Length = 0 then + // if fieldInfos.Length = 0 then // getUnionCaseName uci |> StringLiteral :> Expression // else // ArrayExpression [| // getUnionCaseName uci |> StringLiteral :> Expression - // ArrayExpression fieldTypes :> Expression + // ArrayExpression fieldInfos :> Expression // |] :> Expression // caseInfo) |> Seq.toArray // let cases = ArrowFunctionExpression([||], ArrayExpression cases :> Expression |> U2.Case2) :> Expression @@ -527,6 +522,17 @@ module Util = and transformTypeInfo (com: IBabelCompiler) ctx r (mems : Fable.MemberInfo[]) (genMap: string -> Option) t: Expression = let primitiveTypeInfo name = coreValue com ctx "Reflection" name + let numberInfo kind = + match kind with + | Int8 -> "int8" + | UInt8 -> "uint8" + | Int16 -> "int16" + | UInt16 -> "uint16" + | Int32 -> "int32" + | UInt32 -> "uint32" + | Float32 -> "float32" + | Float64 -> "float64" + |> primitiveTypeInfo let nonGenericTypeInfo fullname = [| StringLiteral fullname :> Expression |] |> coreLibCall com ctx None "Reflection" "ntype" @@ -551,22 +557,28 @@ module Util = | Fable.Unit -> primitiveTypeInfo "unit" | Fable.Boolean -> primitiveTypeInfo "bool" | Fable.Char -> primitiveTypeInfo "char" - | Fable.String - | Fable.EnumType(Fable.StringEnumType, _) -> - primitiveTypeInfo "string" - | Fable.EnumType(Fable.NumberEnumType, _) -> - primitiveTypeInfo "int32" + | Fable.String -> primitiveTypeInfo "string" + | Fable.Enum ent -> + let fullName = defaultArg ent.TryFullName Naming.unknown + let mutable numberKind = Int32 + let cases = + ent.FSharpFields |> Seq.choose (fun fi -> + // F# seems to include a field with this name with the underlying type + match fi.Name with + | "value__" -> + match FSharp2Fable.TypeHelpers.makeType com Map.empty fi.FieldType with + | Fable.Number kind -> numberKind <- kind + | _ -> () + None + | name -> + let value = match fi.LiteralValue with Some v -> System.Convert.ToDouble v | None -> 0. + ArrayExpression [|StringLiteral name; NumericLiteral value|] :> Expression |> Some) + |> Seq.toArray + |> ArrayExpression + [|StringLiteral fullName :> Expression; numberInfo numberKind; cases :> _|] + |> coreLibCall com ctx None "Reflection" "enumType" | Fable.Number kind -> - match kind with - | Int8 -> "int8" - | UInt8 -> "uint8" - | Int16 -> "int16" - | UInt16 -> "uint16" - | Int32 -> "int32" - | UInt32 -> "uint32" - | Float32 -> "float32" - | Float64 -> "float64" - |> primitiveTypeInfo + numberInfo kind | Fable.FunctionType(Fable.LambdaType argType, returnType) -> genericTypeInfo "lambda" [|argType; returnType|] | Fable.FunctionType(Fable.DelegateType argTypes, returnType) -> @@ -588,8 +600,8 @@ module Util = match ent, generics with | Replacements.BuiltinEntity kind -> match kind with - | Replacements.BclGuid -> primitiveTypeInfo "string" - | Replacements.BclTimeSpan -> primitiveTypeInfo "float64" + | Replacements.BclGuid + | Replacements.BclTimeSpan | Replacements.BclDateTime | Replacements.BclDateTimeOffset | Replacements.BclTimer @@ -601,13 +613,14 @@ module Util = | Replacements.FSharpSet gen -> genericEntity ent [|transformTypeInfo com ctx r [||] genMap gen|] | Replacements.BclDictionary(key, value) + | Replacements.BclKeyValuePair(key, value) | Replacements.FSharpMap(key, value) -> genericEntity ent [| transformTypeInfo com ctx r [||] genMap key transformTypeInfo com ctx r [||] genMap value |] | Replacements.FSharpResult(ok, err) -> - let resultCases = + let resultCases = [| { Fable.Kind = Fable.MemberInfoKind.UnionCaseConstructor(0, "Ok", [|"value", ok|], "Ok", "_Option.Result"); Fable.Attributes = [||] } { Fable.Kind = Fable.MemberInfoKind.UnionCaseConstructor(1, "Error", [|"value", err|], "Error", "_Option.Result"); Fable.Attributes = [||] } @@ -622,7 +635,7 @@ module Util = garr |> Array.mapi (fun i t -> let name = sprintf "Choice%dOf%d" i garr.Length { Fable.Kind = Fable.MemberInfoKind.UnionCaseConstructor(i, name, [|"value", t|], name, "_Option.Choice"); Fable.Attributes = [||] } - ) + ) let gen = List.map (transformTypeInfo com ctx r [||] genMap) gen List.toArray gen |> transformRecordReflectionInfo com ctx r ent None cases @@ -640,14 +653,14 @@ module Util = match ent.TryFullName with | Some fullname -> let args = args |> List.map (fun a -> Fable.Value(Fable.TypeInfo(a), None)) - let call = + let call = com.Options.precompiledLib |> Option.bind (fun tryLib -> tryLib fullname) |> Option.map (Replacements.precompiledLibReflection r args) - + match call with | Some call -> com.TransformAsExpr(ctx, call) - | None -> genericEntity ent generics + | None -> genericEntity ent generics | _ -> genericEntity ent generics | _ -> @@ -704,10 +717,8 @@ module Util = then coreLibCall com ctx r "Option" "some" [|e|] else e | None -> upcast NullLiteral () - | Fable.Enum(kind,_) -> - match kind with - | Fable.NumberEnum x - | Fable.StringEnum x -> com.TransformAsExpr(ctx, x) + | Fable.EnumConstant(x,_) -> + com.TransformAsExpr(ctx, x) | Fable.NewRecord(values, kind, _) -> let values = List.mapToArray (fun x -> com.TransformAsExpr(ctx, x)) values match kind with @@ -721,9 +732,9 @@ module Util = |> coreLibCall com ctx r "Types" "anonRecord" | Fable.NewUnion(values, uci, ent, _) -> // Union cases with EraseAttribute are used for `Custom`-like cases in unions meant for `keyValueList` - match FSharp2Fable.Helpers.tryFindAtt Atts.erase uci.Attributes with - | Some _ -> Fable.ArrayValues values |> makeTypedArray com ctx Fable.Any - | None -> + if FSharp2Fable.Helpers.hasAtt Atts.erase uci.Attributes then + Fable.ArrayValues values |> makeTypedArray com ctx Fable.Any + else let name = getUnionCaseName uci let consRef = jsConstructor com ctx ent let tag = FSharp2Fable.Helpers.unionCaseTag ent uci @@ -751,7 +762,7 @@ module Util = let prop, computed = match key with // Compile ToString in lower case for compatibity with JS (and debugger tools) - | Fable.Value(Fable.StringConstant "ToString",_) -> memberFromName "toString" + | Fable.Value(Fable.StringConstant "ToString", _) -> memberFromName "toString" | key -> memberFromExpr com ctx key makeObjMethod ObjectMeth prop computed hasSpread args body | Fable.ObjectIterator, Fable.Function(Fable.Delegate args, body, _) -> @@ -871,11 +882,11 @@ module Util = match argInfo.ThisArg with | Some thisArg -> thisArg::argInfo.Args | None -> argInfo.Args - optimizeTailCall com ctx tc args + optimizeTailCall com ctx range tc args | Some(Return|ReturnUnit), Some tc, Fable.CurriedApply(funcExpr, args) when tc.IsRecursiveRef(funcExpr) && List.sameLength args tc.Args -> - optimizeTailCall com ctx tc args + optimizeTailCall com ctx range tc args | _ -> [|transformOperation com ctx range opKind |> resolveExpr t returnStrategy|] @@ -1002,13 +1013,13 @@ module Util = | Fable.Any -> upcast BooleanLiteral true | Fable.Unit -> upcast BinaryExpression(BinaryEqual, com.TransformAsExpr(ctx, expr), NullLiteral(), ?loc=range) | Fable.Boolean -> jsTypeof "boolean" expr - | Fable.Char | Fable.String _ | Fable.EnumType(Fable.StringEnumType, _) -> jsTypeof "string" expr - | Fable.Number _ | Fable.EnumType(Fable.NumberEnumType, _) -> jsTypeof "number" expr + | Fable.Char | Fable.String _ -> jsTypeof "string" expr + | Fable.Number _ | Fable.Enum _ -> jsTypeof "number" expr | Fable.Regex -> jsInstanceof (Identifier "RegExp") expr // TODO: Fail for functions, arrays, tuples and list because we cannot check generics? | Fable.FunctionType _ -> jsTypeof "function" expr | Fable.Array _ | Fable.Tuple _ -> - coreLibCall com ctx None "Util" "isArray" [|com.TransformAsExpr(ctx, expr)|] + coreLibCall com ctx None "Util" "isArrayLike" [|com.TransformAsExpr(ctx, expr)|] | Fable.List _ -> jsInstanceof (coreValue com ctx "Types" "List") expr @@ -1029,6 +1040,7 @@ module Util = | Replacements.BclBigInt -> coreLibCall com ctx None "BigInt" "isBigInt" [|com.TransformAsExpr(ctx, expr)|] | Replacements.BclHashSet _ | Replacements.BclDictionary _ + | Replacements.BclKeyValuePair _ | Replacements.FSharpSet _ | Replacements.FSharpMap _ -> fail "set/maps" | Replacements.FSharpResult _ @@ -1036,20 +1048,20 @@ module Util = | Replacements.FSharpReference _ -> fail "result/choice/reference" | Fable.AnonymousRecordType _ -> "Type testing is not yet supported for anonymous records" // TODO - |> addWarning com [] range + |> addWarning com [] range upcast BooleanLiteral false | Fable.DeclaredType (ent, genArgs) -> match ent.TryFullName with - | Some "Microsoft.FSharp.Quotations.FSharpExpr" + | Some "Microsoft.FSharp.Quotations.FSharpExpr" | Some "Microsoft.FSharp.Quotations.FSharpExpr`1" -> jsInstanceof (coreValue com ctx "Quotations" "FSharpExpr") expr //coreLibCall com ctx None "ExprUtils" "isExpr" [| com.TransformAsExpr(ctx, expr) |] - | Some "System.Type" -> coreLibCall com ctx None "Reflection" "isType" [|com.TransformAsExpr(ctx, expr)|] - | Some "System.Reflection.MemberInfo" -> coreLibCall com ctx None "Reflection" "isMemberInfo" [|com.TransformAsExpr(ctx, expr)|] - | Some "System.Reflection.MethodBase" -> coreLibCall com ctx None "Reflection" "isMethodBase" [|com.TransformAsExpr(ctx, expr)|] - | Some "System.Reflection.MethodInfo" -> coreLibCall com ctx None "Reflection" "isMethodInfo" [|com.TransformAsExpr(ctx, expr)|] - | Some "System.Reflection.ConstructorInfo" -> coreLibCall com ctx None "Reflection" "isConstructorInfo" [|com.TransformAsExpr(ctx, expr)|] - | Some "System.Reflection.FieldInfo" -> coreLibCall com ctx None "Reflection" "isFieldInfo" [|com.TransformAsExpr(ctx, expr)|] - | Some "System.Reflection.PropertyInfo" -> coreLibCall com ctx None "Reflection" "isPropertyInfo" [|com.TransformAsExpr(ctx, expr)|] - | Some "Microsoft.FSharp.Reflection.UnionCaseInfo" -> coreLibCall com ctx None "Reflection" "isUnionCaseInfo" [|com.TransformAsExpr(ctx, expr)|] + | Some "System.Type" -> coreLibCall com ctx None "Reflection" "isType" [|com.TransformAsExpr(ctx, expr)|] + | Some "System.Reflection.MemberInfo" -> coreLibCall com ctx None "Reflection" "isMemberInfo" [|com.TransformAsExpr(ctx, expr)|] + | Some "System.Reflection.MethodBase" -> coreLibCall com ctx None "Reflection" "isMethodBase" [|com.TransformAsExpr(ctx, expr)|] + | Some "System.Reflection.MethodInfo" -> coreLibCall com ctx None "Reflection" "isMethodInfo" [|com.TransformAsExpr(ctx, expr)|] + | Some "System.Reflection.ConstructorInfo" -> coreLibCall com ctx None "Reflection" "isConstructorInfo" [|com.TransformAsExpr(ctx, expr)|] + | Some "System.Reflection.FieldInfo" -> coreLibCall com ctx None "Reflection" "isFieldInfo" [|com.TransformAsExpr(ctx, expr)|] + | Some "System.Reflection.PropertyInfo" -> coreLibCall com ctx None "Reflection" "isPropertyInfo" [|com.TransformAsExpr(ctx, expr)|] + | Some "Microsoft.FSharp.Reflection.UnionCaseInfo" -> coreLibCall com ctx None "Reflection" "isUnionCaseInfo" [|com.TransformAsExpr(ctx, expr)|] | Some Types.idisposable -> match expr.Type with // In F# AST this is coerced to obj, but the cast should have been removed @@ -1058,6 +1070,8 @@ module Util = | _ -> coreLibCall com ctx None "Util" "isDisposable" [|com.TransformAsExpr(ctx, expr)|] | Some Types.ienumerable -> [|com.TransformAsExpr(ctx, expr)|] |> coreLibCall com ctx None "Util" "isIterable" + | Some Types.array -> + [|com.TransformAsExpr(ctx, expr)|] |> coreLibCall com ctx None "Util" "isArrayLike" | _ when ent.IsInterface -> fail (sprintf "interface %A" ent.FullName) | _ when FSharp2Fable.Util.isReplacementCandidate ent -> @@ -1123,19 +1137,24 @@ module Util = elif List.sameLength idents values then List.zip idents values else failwith "Target idents/values lengths differ" - let getDecisionTargetAndBindValues (ctx: Context) targetIndex boundValues = + let getDecisionTargetAndBindValues (com: IBabelCompiler) (ctx: Context) targetIndex boundValues = let idents, target = getDecisionTarget ctx targetIndex - let bindings, replacements = - (([], Map.empty), matchTargetIdentAndValues idents boundValues) - ||> List.fold (fun (bindings, replacements) (ident, expr) -> - if hasDoubleEvalRisk expr // && isReferencedMoreThan 1 ident.Name body - then (ident, expr)::bindings, replacements - else bindings, Map.add ident.Name expr replacements) - let target = FableTransforms.replaceValues replacements target - bindings, target + let identsAndValues = matchTargetIdentAndValues idents boundValues + if not com.Options.debugMode then + let bindings, replacements = + (([], Map.empty), identsAndValues) + ||> List.fold (fun (bindings, replacements) (ident, expr) -> + if canHaveSideEffects expr then + (ident, expr)::bindings, replacements + else + bindings, Map.add ident.Name expr replacements) + let target = FableTransforms.replaceValues replacements target + List.rev bindings, target + else + identsAndValues, target let transformDecisionTreeSuccessAsExpr (com: IBabelCompiler) (ctx: Context) targetIndex boundValues = - let bindings, target = getDecisionTargetAndBindValues ctx targetIndex boundValues + let bindings, target = getDecisionTargetAndBindValues com ctx targetIndex boundValues match bindings with | [] -> com.TransformAsExpr(ctx, target) | bindings -> com.TransformAsExpr(ctx, Fable.Let(bindings, target)) @@ -1151,8 +1170,8 @@ module Util = let targetAssignment = assign None targetId (ofInt targetIndex) |> ExpressionStatement :> Statement Array.append [|targetAssignment|] assignments | ret -> - let bindings, target = getDecisionTargetAndBindValues ctx targetIndex boundValues - let bindings = bindings |> List.rev |> Seq.collect (fun (i, v) -> transformBindingAsStatements com ctx i v) |> Seq.toArray + let bindings, target = getDecisionTargetAndBindValues com ctx targetIndex boundValues + let bindings = bindings |> Seq.collect (fun (i, v) -> transformBindingAsStatements com ctx i v) |> Seq.toArray Array.append bindings (com.TransformAsStatements(ctx, ret, target)) let transformDecisionTreeAsSwitch expr = @@ -1261,8 +1280,19 @@ module Util = (targets: (Fable.Ident list * Fable.Expr) list) (treeExpr: Fable.Expr): Statement[] = // If some targets are referenced multiple times, host bound idents, // resolve the decision index and compile the targets as a switch - let targetsWithMultiRefs = getTargetsWithMultipleReferences treeExpr - if not(List.isEmpty targetsWithMultiRefs) then + match getTargetsWithMultipleReferences treeExpr with + | [] -> + let ctx = { ctx with DecisionTargets = targets } + match transformDecisionTreeAsSwitch treeExpr with + | Some(evalExpr, cases, (defaultIndex, defaultBoundValues)) -> + let t = treeExpr.Type + let cases = cases |> List.map (fun (caseExpr, targetIndex, boundValues) -> + [caseExpr], Fable.DecisionTreeSuccess(targetIndex, boundValues, t)) + let defaultCase = Fable.DecisionTreeSuccess(defaultIndex, defaultBoundValues, t) + [|transformSwitch com ctx true returnStrategy evalExpr cases (Some defaultCase)|] + | None -> + com.TransformAsStatements(ctx, returnStrategy, treeExpr) + | targetsWithMultiRefs -> // If the bound idents are not referenced in the target, remove them let targets = targets |> List.map (fun (idents, expr) -> @@ -1286,17 +1316,6 @@ module Util = transformDecisionTreeWithTwoSwitches com ctx returnStrategy targets treeExpr else transformDecisionTreeWithTwoSwitches com ctx returnStrategy targets treeExpr - else - let ctx = { ctx with DecisionTargets = targets } - match transformDecisionTreeAsSwitch treeExpr with - | Some(evalExpr, cases, (defaultIndex, defaultBoundValues)) -> - let t = treeExpr.Type - let cases = cases |> List.map (fun (caseExpr, targetIndex, boundValues) -> - [caseExpr], Fable.DecisionTreeSuccess(targetIndex, boundValues, t)) - let defaultCase = Fable.DecisionTreeSuccess(defaultIndex, defaultBoundValues, t) - [|transformSwitch com ctx true returnStrategy evalExpr cases (Some defaultCase)|] - | None -> - com.TransformAsStatements(ctx, returnStrategy, treeExpr) let rec transformAsExpr (com: IBabelCompiler) ctx (expr: Fable.Expr): Expression = match expr with @@ -1358,17 +1377,17 @@ module Util = | Fable.Quote(_,data, r) -> let obj (values : list) = values |> List.toArray |> Array.map (fun (n,v) -> U3.Case1 (ObjectProperty(StringLiteral n, v))) |> ObjectExpression :> Expression - let values = + let values = data.values |> Array.map (fun v -> - obj [ - "name", StringLiteral v.name :> Expression - "typ", transformAsExpr com ctx (Fable.Value(Fable.TypeInfo v.typ, None)) + obj [ + "name", StringLiteral v.name :> Expression + "typ", transformAsExpr com ctx (Fable.Value(Fable.TypeInfo v.typ, None)) "value", transformAsExpr com ctx v.expr - ] + ] ) - let vars = data.variables |> Array.map (fun (v : Fable.VarData) -> - obj [ + let vars = data.variables |> Array.map (fun (v : Fable.VarData) -> + obj [ "name", StringLiteral v.name :> Expression "typ", transformAsExpr com ctx (Fable.Value(Fable.TypeInfo v.typ, None)) "isMutable", BooleanLiteral v.isMutable :> Expression @@ -1380,37 +1399,37 @@ module Util = ) let members = data.members |> Array.map (fun (ent, t, m, margs) -> - let self = transformAsExpr com ctx (Fable.Value(Fable.TypeInfo t, None)) + let self = transformAsExpr com ctx (Fable.Value(Fable.TypeInfo t, None)) let minst = margs |> Array.map (fun t -> transformAsExpr com ctx (Fable.Value(Fable.TypeInfo t, None))) - + let arr = transformMemberReflectionInfosNew com ctx None self (ArrayExpression [||]) ent [|m|] let meth = arr.[0] - if margs.Length > 0 then + if margs.Length > 0 then CallExpression(MemberExpression(meth, Identifier "MakeGenericMethod"), [| ArrayExpression minst |]) :> Expression else meth ) - let literals = + let literals = data.literals |> Array.map (fun e -> - obj [ + obj [ "value", transformAsExpr com ctx e - "typ", transformAsExpr com ctx (Fable.Value(Fable.TypeInfo e.Type, None)) - ] + "typ", transformAsExpr com ctx (Fable.Value(Fable.TypeInfo e.Type, None)) + ] ) // let arrName = getTypedArrayName com NumberKind.UInt8 // let expr = NewExpression(Identifier arrName, [| data.data |> Array.map (fun v -> NumericLiteral (float v) :> Expression) |> ArrayExpression |]) - coreLibCall com ctx r "ExprUtils" "deserialize" [| + coreLibCall com ctx r "ExprUtils" "deserialize" [| ArrayExpression values ArrayExpression vars ArrayExpression types ArrayExpression members ArrayExpression literals - StringLiteral (System.Convert.ToBase64String data.data) + StringLiteral (System.Convert.ToBase64String data.data) |] - + let rec transformAsStatements (com: IBabelCompiler) ctx returnStrategy (expr: Fable.Expr): Statement array = match expr with @@ -1536,14 +1555,13 @@ module Util = let args, body = match isTailCallOptimized, tailcallChance, body with | true, Some tc, U2.Case1 body -> + // Replace args, see NamedTailCallOpportunity constructor let args, body = - if tc.ReplaceArgs then - let varDeclaration = - List.zip args tc.Args |> List.map (fun (arg, tempVar) -> - arg.Name, Some(Identifier tempVar :> Expression)) - |> multiVarDeclaration Const - tc.Args |> List.map Identifier, BlockStatement(Array.append [|varDeclaration|] body.Body) - else args, body + let varDeclaration = + List.zip args tc.Args |> List.map (fun (arg, tempVar) -> + arg.Name, Some(Identifier tempVar :> Expression)) + |> multiVarDeclaration Const + tc.Args |> List.map Identifier, BlockStatement(Array.append [|varDeclaration|] body.Body) // Make sure we don't get trapped in an infinite loop, see #1624 let body = BlockStatement(Array.append body.Body [|BreakStatement()|]) args, LabeledStatement(Identifier tc.Label, WhileStatement(BooleanLiteral true, body)) @@ -1569,15 +1587,15 @@ module Util = // ExpressionStatement(macroExpression funcExpr.loc "process.exit($0)" [main], ?loc=funcExpr.loc) ExpressionStatement(main) :> Statement - let declareModuleMember isPublic name isMutable (expr: Expression) = + let declareModuleMember r isPublic name isMutable (expr: Expression) = let privateIdent = Identifier name let decl: Declaration = match expr with | :? ClassExpression as e -> upcast ClassDeclaration(e.Body, privateIdent, - ?superClass=e.SuperClass, ?typeParameters=e.TypeParameters) + ?superClass=e.SuperClass, ?typeParameters=e.TypeParameters, ?loc=r) | :? FunctionExpression as e -> - upcast FunctionDeclaration(privateIdent, e.Params, e.Body) + upcast FunctionDeclaration(privateIdent, e.Params, e.Body, ?loc=r) | _ -> upcast varDeclaration privateIdent isMutable expr if not isPublic then U2.Case1 (decl :> Statement) @@ -1596,12 +1614,12 @@ module Util = | Some e -> [|consFunction; e|] | None -> [|consFunction|] |> coreLibCall com ctx None "Types" "declare" - |> declareModuleMember isPublic name false + |> declareModuleMember r isPublic name false let reflectionDeclaration = let genArgs = Array.init ent.GenericParameters.Count (fun _ -> makeIdentUnique com "gen" |> ident) let body = transformReflectionInfo com ctx r ent declaringName mems (Array.map (fun x -> x :> _) genArgs) makeFunctionExpression None (Array.map (fun x -> U2.Case2(upcast x)) genArgs) (U2.Case2 body) - |> declareModuleMember isPublic (Naming.appendSuffix name Naming.reflectionSuffix) false + |> declareModuleMember None isPublic (Naming.appendSuffix name Naming.reflectionSuffix) false [typeDeclaration; reflectionDeclaration] let transformModuleFunction (com: IBabelCompiler) ctx (info: Fable.ValueDeclarationInfo) args body = @@ -1611,7 +1629,7 @@ module Util = if info.IsEntryPoint then declareEntryPoint com ctx expr |> U2.Case1 else - declareModuleMember info.IsPublic info.Name false expr + declareModuleMember info.Range info.IsPublic info.Name false expr let transformAction (com: IBabelCompiler) ctx expr = let statements = transformAsStatements com ctx None expr @@ -1734,7 +1752,7 @@ module Util = | None -> None [ yield! declareType com ctx r info.IsEntityPublic declaringName info.Members info.Entity info.EntityName args body baseExpr - yield declareModuleMember info.IsConstructorPublic info.Name false exposedCons + yield declareModuleMember r info.IsConstructorPublic info.Name false exposedCons ] let rec transformDeclarations (com: IBabelCompiler) ctx decls transformed = @@ -1753,13 +1771,13 @@ module Util = | value when info.IsMutable && info.IsPublic -> Replacements.createAtom value |> transformAsExpr com ctx - |> declareModuleMember true info.Name false + |> declareModuleMember info.Range true info.Name false |> List.singleton | Fable.Function(Fable.Delegate args, body, _) -> [transformModuleFunction com ctx info args body] | _ -> let value = transformAsExpr com ctx value - [declareModuleMember info.IsPublic info.Name info.IsMutable value] + [declareModuleMember info.Range info.IsPublic info.Name info.IsMutable value] |> List.append transformed |> transformDeclarations com ctx restDecls | Fable.ConstructorDeclaration(declaringName, kind, r) -> @@ -1799,9 +1817,10 @@ module Util = let reflectionDeclaration = let body = transformRecordReflectionInfo com ctx None ent declaringName mems [||] makeFunctionExpression None [||] (U2.Case2 body) - |> declareModuleMember true (Naming.appendSuffix name Naming.reflectionSuffix) false + |> declareModuleMember None true (Naming.appendSuffix name Naming.reflectionSuffix) false List.append transformed [reflectionDeclaration] |> transformDeclarations com ctx restDecls + let transformImports (imports: Import seq): U2 list = imports |> Seq.map (fun import -> let specifier = @@ -1904,7 +1923,7 @@ module Compiler = member __.RemoveLastError() = com.RemoveLastError() - let makeCompiler com = new BabelCompiler(com) + let makeCompiler com = BabelCompiler(com) let createFacade (sourceFiles: string[]) (facadeFile: string) = // Remove signature files so fable-splitter doesn't try to compile them diff --git a/src/Fable.Transforms/FableTransforms.fs b/src/Fable.Transforms/FableTransforms.fs index 3784c4d9b3..9141928a30 100644 --- a/src/Fable.Transforms/FableTransforms.fs +++ b/src/Fable.Transforms/FableTransforms.fs @@ -16,10 +16,7 @@ let visit f e = | TypeInfo _ | Null _ | UnitConstant | BoolConstant _ | CharConstant _ | StringConstant _ | NumberConstant _ | RegexConstant _ -> e - | Enum(kind, name) -> - match kind with - | NumberEnum e -> Enum(NumberEnum(f e), name) |> makeValue r - | StringEnum e -> Enum(StringEnum(f e), name) |> makeValue r + | EnumConstant(exp, ent) -> EnumConstant(f exp, ent) |> makeValue r | NewOption(e, t) -> NewOption(Option.map f e, t) |> makeValue r | NewTuple exprs -> NewTuple(List.map f exprs) |> makeValue r | NewArray(kind, t) -> @@ -119,10 +116,7 @@ let getSubExpressions = function | TypeInfo _ | Null _ | UnitConstant | BoolConstant _ | CharConstant _ | StringConstant _ | NumberConstant _ | RegexConstant _ -> [] - | Enum(kind, _) -> - match kind with - | NumberEnum e -> [e] - | StringEnum e -> [e] + | EnumConstant(e, _) -> [e] | NewOption(e, _) -> Option.toList e | NewTuple exprs -> exprs | NewArray(kind, _) -> @@ -209,39 +203,10 @@ let countReferences limit identName body = | _ -> false) |> ignore count -/// Values with risk of double evaluation must be captured. If it appears in the body -/// of a function it can leak, so consider as it had exceeded the references limit. -let countReferencesPreventingLeak limit identName body = - let rec traverse f (insideFunction: bool) (exprs: Expr list) = - (false, exprs) ||> List.fold (fun stop expr -> - stop || - let stop, insideFunction', exprs = f insideFunction expr - stop || - match exprs with - | [] -> false - | exprs -> traverse f (insideFunction || insideFunction') exprs) - let mutable count = 0 - (false, [body]) ||> traverse (fun insideFunction expr -> - match expr with - | IdentExpr id2 when id2.Name = identName -> - count <- (if insideFunction then limit else count) + 1 - count > limit, false, [] - // If the function is immediately applied we don't have to worry about leaks - // | NestedApply(NestedLambda(args, body, _), argExprs, _, _) when List.sameLength args argExprs -> - // false, false, argExprs @ [body] - | Function(_,body,_) -> - false, true, [body] - | e -> - false, false, getSubExpressions e) |> ignore - count - let canInlineArg identName value body = - // Don't erase expressions referenced 0 times, they may have side-effects - if not(hasDoubleEvalRisk value) then true - else - match value with - | Function _ -> countReferences 1 identName body = 1 - | _ -> countReferencesPreventingLeak 1 identName body = 1 + match value with + | Function _ -> countReferences 1 identName body <= 1 + | value -> canHaveSideEffects value |> not module private Transforms = let (|LambdaOrDelegate|_|) = function @@ -249,12 +214,29 @@ module private Transforms = | Function(Delegate args, body, name) -> Some(args, body, name) | _ -> None - let lambdaBetaReduction (_: ICompiler) e = + let lambdaBetaReduction (com: ICompiler) e = + // Sometimes the F# compiler creates a lot of binding closures, as with printfn + let (|NestedLetsAndLambdas|_|) expr = + let rec inner accBindings accArgs body name = + match body with + | Function(Lambda arg, body, None) -> + inner accBindings (arg::accArgs) body name + | Let(bindings, body) -> + inner (accBindings @ bindings) accArgs body name + | _ when not(List.isEmpty accArgs) -> + Some(List.rev accArgs, Let(accBindings, body), name) + | _ -> None + match expr with + | Let(bindings, body) -> + inner bindings [] body None + | Function(Lambda arg, body, name) -> + inner [] [arg] body name + | _ -> None let applyArgs (args: Ident list) argExprs body = let bindings, replacements = (([], Map.empty), args, argExprs) |||> List.fold2 (fun (bindings, replacements) ident expr -> - if canInlineArg ident.Name expr body + if (not com.Options.debugMode) && canInlineArg ident.Name expr body then bindings, Map.add ident.Name expr replacements else (ident, expr)::bindings, replacements) match bindings with @@ -264,22 +246,9 @@ module private Transforms = // TODO: Other binary operations and numeric types, also recursive? | Operation(BinaryOperation(AST.BinaryPlus, Value(StringConstant str1, r1), Value(StringConstant str2, r2)),_,_) -> Value(StringConstant(str1 + str2), addRanges [r1; r2]) - // The F# compiler converts non-curried module and class members to curried lambdas when necessary - // but we can remove all the wrapping if the result is immediately applied - // We assume the compiler generated bindings/args can be inlined - | NestedApply(NestedCompilerGeneratedLetsAndLambdas(identValues, lambdaArgs, body), appliedArgs,_,_) - when List.sameLength lambdaArgs appliedArgs -> - let replacements = - List.zip lambdaArgs appliedArgs - |> List.map (fun (i,v) -> i.Name,v) |> Map - let replacements = - (replacements, identValues) - ||> List.fold (fun replacements (i,v) -> - Map.add i.Name (replaceValues replacements v) replacements) - replaceValues replacements body - | Operation(CurriedApply(NestedLambda(args, body, None) as lambda, argExprs), _, _) -> - if List.sameLength args argExprs - then applyArgs args argExprs body + | NestedApply(NestedLetsAndLambdas(lambdaArgs, body, _) as lambda, argExprs,_,_) -> + if List.sameLength lambdaArgs argExprs then + applyArgs lambdaArgs argExprs body else // Partial apply match List.length argExprs, lambda with @@ -301,31 +270,29 @@ module private Transforms = | e -> e let bindingBetaReduction (com: ICompiler) e = - let isTuple = function - | Tuple _ -> true - | _ -> false + // Don't erase user-declared bindings in debug mode for better source maps + let isErasingCandidate (ident: Ident) = + (not com.Options.debugMode) || ident.IsCompilerGenerated match e with // Don't try to optimize bindings with multiple ident-value pairs as they can reference each other - | Let([ident, value], letBody) when not ident.IsMutable -> - match value with - // Erase bindings for getters of compiler-generated tuples (as in pattern matching or lambdas destructuring tuple args) - | Get(IdentExpr tupleIdent, TupleGet _, _, _) as value when tupleIdent.IsCompilerGenerated -> - replaceValues (Map [ident.Name, value]) letBody - | Function(args, funBody, currentName) when ident.IsCompilerGenerated - && (countReferences 1 ident.Name letBody <= 1) -> - if Option.isSome currentName then - sprintf "Unexpected named function when erasing binding (%s > %s)" currentName.Value ident.Name - |> addWarning com [] ident.Range - let replacement = Function(args, funBody, Some ident.Name) - replaceValues (Map [ident.Name, replacement]) letBody - | value when (ident.IsInlinedArg || ident.IsCompilerGenerated) - // Don't erase the binding if the compiler-generated ident is a tuple, because the getters - // will be erased later (see above) and there's a risk the expression gets totally removed - && not (isTuple ident.Type) - && not (ident.Name.StartsWith("patternInput")) // tuple may be split into multiple getters - && canInlineArg ident.Name value letBody -> + | Let([ident, value], letBody) when (not ident.IsMutable) && isErasingCandidate ident -> + let canEraseBinding = + match value with + | NestedLambda(_, lambdaBody, _) -> + match lambdaBody with + | Import _ -> false + // Check the lambda doesn't reference itself recursively + | _ -> countReferences 0 ident.Name lambdaBody = 0 + && canInlineArg ident.Name value letBody + | _ -> canInlineArg ident.Name value letBody + if canEraseBinding then + let value = + match value with + // Ident becomes the name of the function (mainly used for tail call optimizations) + | Function(args, funBody, _) -> Function(args, funBody, Some ident.Name) + | value -> value replaceValues (Map [ident.Name, value]) letBody - | _ -> e + else e | e -> e /// Returns arity of lambda (or lambda option) types @@ -381,7 +348,7 @@ module private Transforms = // For function arguments check if the arity of their own function arguments is expected or not // TODO: Do we need to do this recursively, and check options and delegates too? - let checkSubArguments com expectedType (expr: Expr) = + let checkSubArguments _com expectedType (expr: Expr) = match expectedType, expr with | NestedLambdaType(expectedArgs,_), ExprType(NestedLambdaType(actualArgs,_)) when List.sameLength expectedArgs actualArgs -> @@ -435,12 +402,12 @@ module private Transforms = let curryIdentInBody identName (args: Ident list) body = curryIdentsInBody (Map [identName, List.length args]) body match e with - | Let([ident, NestedLambda(args, fnBody, _)], letBody) when List.isMultiple args -> + | Let([ident, NestedLambdaWithSameArity(args, fnBody, _)], letBody) when List.isMultiple args -> let fnBody = curryIdentInBody ident.Name args fnBody let letBody = curryIdentInBody ident.Name args letBody Let([ident, Function(Delegate args, fnBody, None)], letBody) // Anonymous lambda immediately applied - | Operation(CurriedApply((NestedLambda(args, fnBody, Some name)), argExprs), t, r) + | Operation(CurriedApply((NestedLambdaWithSameArity(args, fnBody, Some name)), argExprs), t, r) when List.isMultiple args && List.sameLength args argExprs -> let fnBody = curryIdentInBody name args fnBody let info = argInfo None argExprs (args |> List.map (fun a -> a.Type) |> Typed) diff --git a/src/Fable.Transforms/Global/Compiler.fs b/src/Fable.Transforms/Global/Compiler.fs index 9f3551babd..654b8a7cc6 100644 --- a/src/Fable.Transforms/Global/Compiler.fs +++ b/src/Fable.Transforms/Global/Compiler.fs @@ -1,9 +1,16 @@ namespace Fable +[] +type Verbosity = + | Normal + | Verbose + | Silent + type CompilerOptions = { typedArrays: bool clampByteArrays: bool - verbose: bool + debugMode: bool + verbosity: Verbosity /// Meant for precompiled libraries (like the Repl Lib) /// to make public inlined functions part of the JS outputPublicInlinedFunctions: bool diff --git a/src/Fable.Transforms/Global/Fable.Core.fs b/src/Fable.Transforms/Global/Fable.Core.fs index fc6050b410..3d5655edb6 100644 --- a/src/Fable.Transforms/Global/Fable.Core.fs +++ b/src/Fable.Transforms/Global/Fable.Core.fs @@ -6,7 +6,14 @@ open System type CaseRules = | None = 0 + /// FooBar -> fooBar | LowerFirst = 1 + /// FooBar -> foo_bar + | SnakeCase = 2 + /// FooBar -> FOO_BAR + | SnakeCaseAllCaps = 3 + /// FooBar -> foo-bar + | KebabCase = 4 [] type StringEnumAttribute() = diff --git a/src/Fable.Transforms/Global/Prelude.fs b/src/Fable.Transforms/Global/Prelude.fs index 806f4e105d..7df8d37f80 100644 --- a/src/Fable.Transforms/Global/Prelude.fs +++ b/src/Fable.Transforms/Global/Prelude.fs @@ -111,6 +111,8 @@ module Patterns = if Set.contains item set then Some SetContains else None module Naming = + open Fable.Core + open System.Text.RegularExpressions let (|StartsWith|_|) (pattern: string) (txt: string) = if txt.StartsWith(pattern) @@ -192,6 +194,19 @@ module Naming = let upperFirst (s: string) = s.Substring(0,1).ToUpperInvariant() + s.Substring(1) + let private dashify (separator: string) (input: string) = + Regex.Replace(input, "[a-z]?[A-Z]", fun m -> + if m.Value.Length = 1 then m.Value.ToLowerInvariant() + else m.Value.Substring(0,1) + separator + m.Value.Substring(1,1).ToLowerInvariant()) + + let applyCaseRule caseRule name = + match caseRule with + | CaseRules.LowerFirst -> lowerFirst name + | CaseRules.SnakeCase -> dashify "_" name + | CaseRules.SnakeCaseAllCaps -> (dashify "_" name).ToUpperInvariant() + | CaseRules.KebabCase -> dashify "-" name + | CaseRules.None | _ -> name + let jsKeywords = System.Collections.Generic.HashSet [ // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords diff --git a/src/Fable.Transforms/OverloadSuffix.fs b/src/Fable.Transforms/OverloadSuffix.fs index 3b67f26729..abd4889ac0 100644 --- a/src/Fable.Transforms/OverloadSuffix.fs +++ b/src/Fable.Transforms/OverloadSuffix.fs @@ -37,17 +37,52 @@ let private tryFindAttributeArgs fullName (atts: #seq) = // -------- End of helper functions +let private hashToString (i: int) = + if i < 0 + then "Z" + (abs i).ToString("X") + else i.ToString("X") + +// Not perfect but hopefully covers most of the cases +// Using only common constrains from https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/generics/constraints +let rec private getGenericParamConstrainsHash genParams (p: FSharpGenericParameter) = + let getConstrainHash (c: FSharpGenericParameterConstraint) = + if c.IsCoercesToConstraint then + ":>" + getTypeFastFullName genParams c.CoercesToTarget + elif c.IsSupportsNullConstraint then + "null" + elif c.IsMemberConstraint then + let d = c.MemberConstraintData // TODO: Full member signature hash? + (if d.MemberIsStatic then "static " else "") + "member " + d.MemberName + elif c.IsRequiresDefaultConstructorConstraint then + "new" + elif c.IsNonNullableValueTypeConstraint then + "struct" + elif c.IsReferenceTypeConstraint then + "not struct" + elif c.IsComparisonConstraint then + "comparison" + elif c.IsEqualityConstraint then + "equality" + elif c.IsUnmanagedConstraint then + "unmanaged" + else "" + p.Constraints |> Seq.map getConstrainHash |> String.concat "," + // Attention: we need to keep this similar to FSharp2Fable.TypeHelpers.makeType -let rec private getTypeFastFullName (genParams: IDictionary<_,_>) (t: FSharpType) = +and private getTypeFastFullName (genParams: IDictionary<_,_>) (t: FSharpType) = let t = nonAbbreviatedType t if t.IsGenericParameter then match genParams.TryGetValue(t.GenericParameter.Name) with | true, i -> i - | false, _ -> "" + | false, _ -> getGenericParamConstrainsHash genParams t.GenericParameter elif t.IsTupleType then t.GenericArguments |> Seq.map (getTypeFastFullName genParams) |> String.concat " * " elif t.IsFunctionType then t.GenericArguments |> Seq.map (getTypeFastFullName genParams) |> String.concat " -> " + elif t.IsAnonRecordType then + Seq.zip t.AnonRecordTypeDetails.SortedFieldNames t.GenericArguments + |> Seq.map (fun (key, typ) -> key + " : " + getTypeFastFullName genParams typ) + |> String.concat "; " elif t.HasTypeDefinition then let tdef = t.TypeDefinition @@ -81,11 +116,6 @@ let private stringHash (s: string) = h <- (h * 33) ^^^ (int s.[i]) h -let private hashToString (i: int) = - if i < 0 - then "Z" + (abs i).ToString("X") - else i.ToString("X") - let private getHashPrivate (m: FSharpMemberOrFunctionOrValue) (curriedParams: Params) genParams = match tryFindAttributeArgs Atts.overloadSuffix m.Attributes with | Some [:? string as overloadSuffix] -> overloadSuffix diff --git a/src/Fable.Transforms/Replacements.fs b/src/Fable.Transforms/Replacements.fs index 7c1a1a2954..354bffbe9e 100644 --- a/src/Fable.Transforms/Replacements.fs +++ b/src/Fable.Transforms/Replacements.fs @@ -134,6 +134,7 @@ type BuiltinType = | BclBigInt | BclHashSet of Type | BclDictionary of key:Type * value:Type + | BclKeyValuePair of key:Type * value:Type | FSharpSet of Type | FSharpMap of key:Type * value:Type | FSharpChoice of Type list @@ -158,6 +159,7 @@ let (|BuiltinEntity|_|) (ent: FSharpEntity, genArgs) = | Some Types.fsharpMap, [k;v] -> Some(FSharpMap(k,v)) | Some Types.hashset, [t] -> Some(BclHashSet(t)) | Some Types.dictionary, [k;v] -> Some(BclDictionary(k,v)) + | Some Types.keyValuePair, [k;v] -> Some(BclKeyValuePair(k,v)) | Some Types.result, [k;v] -> Some(FSharpResult(k,v)) | Some Types.reference, [v] -> Some(FSharpReference(v)) | Some (Naming.StartsWith Types.choiceNonGeneric _), gen -> Some(FSharpChoice gen) @@ -196,7 +198,25 @@ let (|NumberExt|_|) = function | Builtin BclBigInt -> Some BigInt | _ -> None -let (|Nameof|_|) = function +let genericTypeInfoError name = + sprintf "Cannot get type info of generic parameter %s, please inline or inject a type resolver" name + +let getTypeName com (ctx: Context) r t = + match t with + | GenericParam name -> + genericTypeInfoError name + |> addError com ctx.InlinePath r + | _ -> () + let fullname = getTypeFullName false t + let fullname = + match fullname.IndexOf("[") with + | -1 -> fullname + | i -> fullname.[..i - 1] + match fullname.LastIndexOf(".") with + | -1 -> fullname + | i -> fullname.Substring(i + 1) + +let (|Nameof|_|) com ctx = function | IdentExpr ident -> Some ident.DisplayName | Get(_, ExprGet(Value(StringConstant prop,_)), _, _) -> Some prop | Get(_, FieldGet(fi,_,_), _, _) -> Some fi @@ -205,6 +225,7 @@ let (|Nameof|_|) = function match a2 with IdentExpr id2 -> a1.Name = id2.Name | _ -> false) then Some ident.DisplayName else None + | Value(TypeInfo t, r) -> getTypeName com ctx r t |> Some | _ -> None let (|ReplaceName|_|) (namesAndReplacements: (string*string) list) name = @@ -239,6 +260,10 @@ let (|ListLiteral|_|) e = | NewList(Some(head, tail), t) -> untail t [head] tail | _ -> None +let (|ArrayOrListLiteral|_|) = function + | Value((NewArray(ArrayValues vals, t)|ListLiteral(vals, t)),_) -> Some(vals, t) + | _ -> None + let (|IDictionary|IEqualityComparer|Other|) = function | DeclaredType(ent,_) -> match ent.TryFullName with @@ -255,6 +280,15 @@ let (|IEnumerable|IEqualityComparer|Other|) = function | _ -> Other | _ -> Other +let (|NewAnonymousRecord|_|) e = + let rec inner bindings = function + // The F# compiler may create some bindings of expression arguments to fix https://github.com/dotnet/fsharp/issues/6487 + | Let(newBindings, body) -> inner (bindings @ newBindings) body + | Value(NewRecord(exprs, AnonymousRecord fieldNames, genArgs), r) -> + Some(List.rev bindings, exprs, fieldNames, genArgs, r) + | _ -> None + inner [] e + let coreModFor = function | BclGuid -> "String" | BclDateTime -> "Date" @@ -269,17 +303,9 @@ let coreModFor = function | FSharpResult _ -> "Option" | FSharpChoice _ -> "Option" | FSharpReference _ -> "Types" - | BclHashSet _ - | BclDictionary _ -> failwith "Cannot decide core module" - -let genericTypeInfoError name = - sprintf "Cannot get type info of generic parameter %s, please inline or inject a type resolver" name - -let defaultof (t: Type) = - match t with - | Number _ -> makeIntConst 0 - | Boolean -> makeBoolConst false - | _ -> Null t |> makeValue None + | BclHashSet _ -> "MutableSet" + | BclDictionary _ -> "MutableMap" + | BclKeyValuePair _ -> failwith "Cannot decide core module" let makeLongInt r t signed (x: uint64) = let lowBits = NumberConstant (float (uint32 x), Float64) @@ -319,14 +345,14 @@ let makeTypeConst r (typ: Type) (value: obj) = | Number Float32, (:? float32 as x) -> makeFloat32 r x | Number Float64, (:? float as x) -> NumberConstant (float x, Float64) |> makeValue r // Enums - | EnumType _, (:? int64) - | EnumType _, (:? uint64) -> failwith "int64 enums are not supported" - | EnumType(_, name), (:? byte as x) -> Enum(NumberEnum(makeIntConst(int x)), name) |> makeValue r - | EnumType(_, name), (:? sbyte as x) -> Enum(NumberEnum(makeIntConst(int x)), name) |> makeValue r - | EnumType(_, name), (:? int16 as x) -> Enum(NumberEnum(makeIntConst(int x)), name) |> makeValue r - | EnumType(_, name), (:? uint16 as x) -> Enum(NumberEnum(makeIntConst(int x)), name) |> makeValue r - | EnumType(_, name), (:? int as x) -> Enum(NumberEnum(makeIntConst x), name) |> makeValue r - | EnumType(_, name), (:? uint32 as x) -> Enum(NumberEnum(makeIntConst(int x)), name) |> makeValue r + | Enum _, (:? int64) + | Enum _, (:? uint64) -> failwith "int64 enums are not supported" + | Enum e, (:? byte as x) -> EnumConstant(NumberConstant(float x, UInt8) |> makeValue None, e) |> makeValue r + | Enum e, (:? sbyte as x) -> EnumConstant(NumberConstant(float x, Int8) |> makeValue None, e) |> makeValue r + | Enum e, (:? int16 as x) -> EnumConstant(NumberConstant(float x, Int16) |> makeValue None, e) |> makeValue r + | Enum e, (:? uint16 as x) -> EnumConstant(NumberConstant(float x, UInt16) |> makeValue None, e) |> makeValue r + | Enum e, (:? int as x) -> EnumConstant(NumberConstant(float x, Int32) |> makeValue None, e) |> makeValue r + | Enum e, (:? uint32 as x) -> EnumConstant(NumberConstant(float x, UInt32) |> makeValue None, e) |> makeValue r // TODO: Regex | Unit, _ -> UnitConstant |> makeValue r // Arrays with small data type (ushort, byte) are represented @@ -355,12 +381,12 @@ let makeTypeDefinitionInfo r t = let genArgs = names |> List.map GenericParam DeclaredType(ent, genArgs) | FunctionType(kind,r) -> - let kind, ret = + let kind, ret = match kind with | LambdaType(a) -> LambdaType (GenericParam "a0"), "a1" | DelegateType(a) -> DelegateType (a |> List.mapi (fun i _ -> GenericParam (sprintf "a%d" i))), sprintf "a%d" a.Length - FunctionType(kind, GenericParam ret) - | ErasedUnion a -> ErasedUnion a + FunctionType(kind, GenericParam ret) + | ErasedUnion a -> ErasedUnion a // TODO: Do something with FunctionType and ErasedUnion? | t -> t TypeInfo t |> makeValue r @@ -381,7 +407,8 @@ let toString com (ctx: Context) r (args: Expr list) = |> addErrorAndReturnNull com ctx.InlinePath r | head::tail -> match head.Type with - | Char | String -> head + | Char | String + | Builtin BclGuid -> head | Builtin (BclTimeSpan|BclInt64|BclUInt64 as t) -> Helper.CoreCall(coreModFor t, "toString", String, args) | Number Int16 -> Helper.CoreCall("Util", "int16ToString", String, args) @@ -456,7 +483,7 @@ let toFloat com (ctx: Context) r targetType (args: Expr list): Expr = | Long _ -> Helper.CoreCall("Long", "toNumber", targetType, args) | Decimal -> Helper.CoreCall("Decimal", "toNumber", targetType, args) | JsNumber _ -> TypeCast(args.Head, targetType) - | EnumType(NumberEnumType,_) -> TypeCast(args.Head, targetType) + | Enum _ -> TypeCast(args.Head, targetType) | _ -> addWarning com ctx.InlinePath r "Cannot make conversion because source type is unknown" TypeCast(args.Head, targetType) @@ -474,7 +501,7 @@ let toDecimal com (ctx: Context) r targetType (args: Expr list): Expr = |> makeDecimalFromExpr r targetType | Decimal -> args.Head | JsNumber _ -> makeDecimalFromExpr r targetType args.Head - | EnumType(NumberEnumType,_) -> makeDecimalFromExpr r targetType args.Head + | Enum _ -> makeDecimalFromExpr r targetType args.Head | _ -> addWarning com ctx.InlinePath r "Cannot make conversion because source type is unknown" TypeCast(args.Head, targetType) @@ -514,14 +541,14 @@ let toLong com (ctx: Context) r (unsigned: bool) targetType (args: Expr list): E Helper.CoreCall("Long", "fromNumber", targetType, [n; makeBoolConst unsigned]) | JsNumber (Integer as kind) -> fromInteger kind args.Head | JsNumber Float -> Helper.CoreCall("Long", "fromNumber", targetType, args @ [makeBoolConst unsigned]) - | EnumType(NumberEnumType,_) -> fromInteger Int32 args.Head + | Enum _ -> fromInteger Int32 args.Head | _ -> addWarning com ctx.InlinePath r "Cannot make conversion because source type is unknown" TypeCast(args.Head, targetType) /// Conversion to integers (excluding longs and bigints) let toInt com (ctx: Context) r targetType (args: Expr list) = - let transformEnumType = function EnumType(NumberEnumType, _) -> Number Int32 | t -> t + let transformEnumType = function Enum _ -> Number Int32 | t -> t let sourceType = transformEnumType args.Head.Type let targetType = transformEnumType targetType let emitCast typeTo arg = @@ -566,9 +593,8 @@ let arrayCons (com: ICompiler) genArg = getTypedArrayName com numberKind |> makeIdentExprNonMangled | _ -> makeIdentExprNonMangled "Array" -// TODO: Should we pass the empty list representation here? let toList returnType expr = - Helper.CoreCall("Seq", "toList", returnType, [expr]) + Helper.CoreCall("List", "ofSeq", returnType, [expr]) let toArray (com: ICompiler) returnType expr = // match expr, returnType with @@ -693,7 +719,7 @@ let isCompatibleWithJsComparison = function | GenericParam _ -> false | AnonymousRecordType _ -> false | Any | Unit | Boolean | Number _ | String | Char | Regex - | EnumType _ | ErasedUnion _ | FunctionType _ -> true + | Enum _ | ErasedUnion _ | FunctionType _ -> true // Overview of hash rules: // * `hash`, `Unchecked.hash` first check if GetHashCode is implemented and then default to structural hash. @@ -701,7 +727,7 @@ let isCompatibleWithJsComparison = function // * `LanguagePrimitive.PhysicalHash` creates an identity hash no matter whether GetHashCode is implemented or not. let identityHash r (arg: Expr) = match arg.Type with - | Boolean | Char | String | Number _ | EnumType _ + | Boolean | Char | String | Number _ | Enum _ | Builtin(BclInt64|BclUInt64|BclBigInt) | Builtin(BclDateTime|BclDateTimeOffset) | Builtin(BclGuid|BclTimeSpan) -> @@ -727,7 +753,7 @@ let rec equals (com: ICompiler) r equal (left: Expr) (right: Expr) = else makeUnOp None Boolean expr UnaryNot match left.Type with | Builtin(BclGuid|BclTimeSpan) - | Boolean | Char | String | Number _ | EnumType _ -> + | Boolean | Char | String | Number _ | Enum _ -> let op = if equal then BinaryEqualStrict else BinaryUnequalStrict makeBinOp r Boolean left right op | Builtin(BclDateTime|BclDateTimeOffset) -> @@ -777,7 +803,7 @@ let rec equals (com: ICompiler) r equal (left: Expr) (right: Expr) = and compare (com: ICompiler) r (left: Expr) (right: Expr) = match left.Type with | Builtin(BclGuid|BclTimeSpan) - | Boolean | Char | String | Number _ | EnumType _ -> + | Boolean | Char | String | Number _ | Enum _ -> Helper.CoreCall("Util", "comparePrimitives", Number Int32, [left; right], ?loc=r) | Builtin(BclDateTime|BclDateTimeOffset) -> Helper.CoreCall("Date", "compare", Number Int32, [left; right], ?loc=r) @@ -803,7 +829,7 @@ and compare (com: ICompiler) r (left: Expr) (right: Expr) = and compareIf (com: ICompiler) r (left: Expr) (right: Expr) op = match left.Type with | Builtin(BclGuid|BclTimeSpan) - | Boolean | Char | String | Number _ | EnumType _ -> + | Boolean | Char | String | Number _ | Enum _ -> makeEqOp r left right op | _ -> let comparison = compare com r left right @@ -831,7 +857,8 @@ let makeEqualityComparer (com: ICompiler) typArg = // TODO: Try to detect at compile-time if the object already implements `Compare`? let inline makeComparerFromEqualityComparer e = - Helper.CoreCall("Util", "comparerFromEqualityComparer", Any, [e]) + e // leave it as is, if implementation supports it + // Helper.CoreCall("Util", "comparerFromEqualityComparer", Any, [e]) /// Adds comparer as last argument for set creator methods let makeSet (com: ICompiler) r t methName args genArg = @@ -849,7 +876,9 @@ let makeDictionaryWithComparer r t sourceSeq comparer = let makeDictionary (com: ICompiler) r t sourceSeq = match t with | DeclaredType(_,[key;_]) when not(isCompatibleWithJsComparison key) -> - makeComparer com key |> makeDictionaryWithComparer r t sourceSeq + // makeComparer com key + makeEqualityComparer com key + |> makeDictionaryWithComparer r t sourceSeq | _ -> Helper.GlobalCall("Map", t, [sourceSeq], isConstructor=true, ?loc=r) let makeHashSetWithComparer r t sourceSeq comparer = @@ -858,12 +887,16 @@ let makeHashSetWithComparer r t sourceSeq comparer = let makeHashSet (com: ICompiler) r t sourceSeq = match t with | DeclaredType(_,[key]) when not(isCompatibleWithJsComparison key) -> - makeComparer com key |> makeHashSetWithComparer r t sourceSeq + // makeComparer com key + makeEqualityComparer com key + |> makeHashSetWithComparer r t sourceSeq | _ -> Helper.GlobalCall("Set", t, [sourceSeq], isConstructor=true, ?loc=r) -let getZero (com: ICompiler) ctx (t: Type) = +let rec getZero (com: ICompiler) ctx (t: Type) = match t with - | Char | String -> makeStrConst "" + | Boolean -> makeBoolConst false + | Number _ -> makeIntConst 0 + | Char | String -> makeStrConst "" // TODO: Use null for string? | Builtin BclTimeSpan -> makeIntConst 0 | Builtin BclDateTime as t -> Helper.CoreCall("Date", "minValue", t, []) | Builtin BclDateTimeOffset as t -> Helper.CoreCall("DateOffset", "minValue", t, []) @@ -871,9 +904,11 @@ let getZero (com: ICompiler) ctx (t: Type) = | Builtin (BclInt64|BclUInt64) as t -> Helper.CoreCall("Long", "fromInt", t, [makeIntConst 0]) | Builtin BclBigInt as t -> Helper.CoreCall("BigInt", "fromInt32", t, [makeIntConst 0]) | Builtin BclDecimal as t -> makeIntConst 0 |> makeDecimalFromExpr None t + | Builtin (BclKeyValuePair(k,v)) -> + Value(NewTuple[getZero com ctx k; getZero com ctx v], None) | ListSingleton(CustomOp com ctx "get_Zero" [] m) -> FSharp2Fable.Util.makeCallFrom com ctx None t false [] None [] m - | _ -> makeIntConst 0 + | _ -> Value(Null Any, None) // null let getOne (com: ICompiler) ctx (t: Type) = match t with @@ -926,11 +961,6 @@ let makePojoFromLambda arg = |> Option.map (fun members -> ObjectExpr(members, Any, None)) |> Option.defaultWith (fun () -> Helper.CoreCall("Util", "jsOptions", Any, [arg])) -let changeCase caseRule name = - match caseRule with - | CaseRules.LowerFirst -> Naming.lowerFirst name - | CaseRules.None | _ -> name - let makePojo (com: Fable.ICompiler) r caseRule keyValueList = let makeObjMember caseRule name values = let value = @@ -938,26 +968,25 @@ let makePojo (com: Fable.ICompiler) r caseRule keyValueList = | [] -> makeBoolConst true | [value] -> value | values -> Value(NewArray(ArrayValues values, Any), None) - ObjectMember(changeCase caseRule name |> makeStrConst, value, ObjectValue) + ObjectMember(Naming.applyCaseRule caseRule name |> makeStrConst, value, ObjectValue) match caseRule with | Value(NumberConstant(rule, _),_) - | Value(Enum(NumberEnum(Value(NumberConstant(rule,_),_)),_),_) -> + | Value(EnumConstant(Value(NumberConstant(rule,_),_),_),_) -> let caseRule = enum(int rule) match keyValueList with - | MaybeCasted(Value((NewArray(ArrayValues ms, _)|ListLiteral(ms, _)),_)) -> + | MaybeCasted(ArrayOrListLiteral(ms,_)) -> (ms, Some []) ||> List.foldBack (fun m acc -> match acc, m with // Try to get the member key and value at compile time for unions and tuples | Some acc, MaybeCasted(Value(NewUnion(values, uci, _, _),_)) -> // Union cases with EraseAttribute are used for `Custom`-like cases - match FSharp2Fable.Helpers.tryFindAtt Atts.erase uci.Attributes with - | Some _ -> + if FSharp2Fable.Helpers.hasAtt Atts.erase uci.Attributes then match values with | (Value(StringConstant name,_))::values -> // Don't change the case for erased cases makeObjMember CaseRules.None name values::acc |> Some | _ -> None - | None -> + else let name = defaultArg (FSharp2Fable.Helpers.unionCaseCompiledName uci) uci.Name makeObjMember caseRule name values::acc |> Some | Some acc, Value(NewTuple((Value(StringConstant name,_))::values),_) -> @@ -1003,28 +1032,59 @@ let injectArg com (ctx: Context) r moduleName methName (genArgs: (string * Type) // TODO!!! How to add other entities? let tryEntityRef (com: Fable.ICompiler) (ent: FSharpEntity) = - match ent.FullName with - | Types.reference -> makeCoreRef Any "FSharpRef" "Types" |> Some - | Types.matchFail -> makeCoreRef Any "MatchFailureException" "Types" |> Some - | Types.result -> makeCoreRef Any "Result" "Option" |> Some - | Naming.StartsWith Types.choiceNonGeneric _ -> makeCoreRef Any "Choice" "Option" |> Some - | entFullName -> + match ent.TryFullName with + | Some Types.reference -> makeCoreRef Any "FSharpRef" "Types" |> Some + | Some Types.matchFail -> makeCoreRef Any "MatchFailureException" "Types" |> Some + | Some Types.result -> makeCoreRef Any "Result" "Option" |> Some + | Some (Naming.StartsWith Types.choiceNonGeneric _) -> makeCoreRef Any "Choice" "Option" |> Some + | Some entFullName -> com.Options.precompiledLib |> Option.bind (fun tryLib -> tryLib entFullName) |> Option.map (fun (entityName, importPath) -> let entityName = Naming.sanitizeIdentForbiddenChars entityName |> Naming.checkJsKeywords makeCustomImport Any entityName importPath) + | None -> None + +let tryJsConstructor com ent = + if FSharp2Fable.Util.isReplacementCandidate ent then tryEntityRef com ent + else FSharp2Fable.Util.entityRefMaybeGlobalOrImported com ent |> Some let jsConstructor com ent = - if FSharp2Fable.Util.isReplacementCandidate ent then - match tryEntityRef com ent with - | Some entRef -> entRef - | None -> - defaultArg ent.TryFullName ent.CompiledName - |> sprintf "Cannot find %s constructor" - |> addErrorAndReturnNull com [] None - else - FSharp2Fable.Util.entityRefMaybeGlobalOrImported com ent + match tryJsConstructor com ent with + | Some e -> e + | None -> + defaultArg ent.TryFullName ent.CompiledName + |> sprintf "Cannot find %s constructor" + |> addErrorAndReturnNull com [] None + +let tryOp r t op args = + Helper.CoreCall("Option", "tryOp", t, op::args, ?loc=r) + +let tryCoreOp r t coreModule coreMember args = + let op = Helper.CoreValue(coreModule, coreMember, Any) + tryOp r t op args + +let emptyGuid () = + makeStrConst "00000000-0000-0000-0000-000000000000" + +let defaultof com ctx (t: Type) = + match t with + | Number _ -> makeIntConst 0 + | Boolean -> makeBoolConst false + | Builtin BclTimeSpan + | Builtin BclDateTime + | Builtin BclDateTimeOffset + | Builtin (BclInt64|BclUInt64) + | Builtin BclBigInt + | Builtin BclDecimal -> getZero com ctx t + | Builtin BclGuid -> emptyGuid() + | DeclaredType(ent,_) when ent.IsValueType -> + match tryJsConstructor com ent with + | Some e -> Helper.ConstructorCall(e, t, []) + // TODO: This usually happens with BCL types, raise error or warning? + | None -> Null t |> makeValue None + // TODO: Fail (or raise warning) if this is an unresolved generic parameter? + | _ -> Null t |> makeValue None let fableCoreLib (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Expr list) = match i.DeclaringEntityFullName, i.CompiledName with @@ -1038,7 +1098,7 @@ let fableCoreLib (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Exp Throw(error runtimeMsg, t, r) |> Some | _, ("nameof"|"nameof2" as meth) -> match args with - | [Nameof name as arg] -> + | [Nameof com ctx name as arg] -> if meth = "nameof2" then NewTuple [makeStrConst name; arg] |> makeValue r |> Some else makeStrConst name |> Some @@ -1047,7 +1107,7 @@ let fableCoreLib (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Exp makeStrConst Naming.unknown |> Some | _, "nameofLambda" -> match args with - | [Function(_, Nameof name, _)] -> name + | [Function(_, (Nameof com ctx name), _)] -> name | _ -> "Cannot infer name of expression" |> addError com ctx.InlinePath r; Naming.unknown |> makeStrConst |> Some @@ -1102,17 +1162,15 @@ let fableCoreLib (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Exp | "op_BangHat", [arg] -> Some arg | "op_BangBang", [arg] -> match arg, i.GenericArgs with - | Value(NewRecord(exprs, Fable.AnonymousRecord fieldNames, _),_), + | NewAnonymousRecord(_, exprs, fieldNames, _, _), [_; (_,DeclaredType(ent, []))] when ent.IsInterface -> // TODO: Check also if there are extra fields in the record not present in the interface? - (None, ent.MembersFunctionsAndValues) ||> Seq.fold (fun err memb -> + (None, FSharp2Fable.Helpers.getAllInterfaceMembers ent |> Seq.filter (fun memb -> memb.IsPropertyGetterMethod)) + ||> Seq.fold (fun err memb -> match err with | Some _ -> err | None -> - let expectedType = - if memb.IsPropertyGetterMethod then memb.ReturnParameter.Type - else memb.FullType - |> makeType com + let expectedType = memb.ReturnParameter.Type |> makeType com Array.tryFindIndex ((=) memb.DisplayName) fieldNames |> function | None -> @@ -1135,8 +1193,7 @@ let fableCoreLib (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Exp | Some errMsg -> addWarning com ctx.InlinePath r errMsg Some arg - | None -> - List.zip (Array.toList fieldNames) exprs |> objExpr t |> Some + | None -> Some arg | _ -> Some arg | "op_Dynamic", [left; memb] -> getExpr r t left memb |> Some | "op_DynamicAssignment", [callee; prop; MaybeLambdaUncurriedAtCompileTime value] -> @@ -1297,7 +1354,7 @@ let operators (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr o // KeyValuePair is already compiled as a tuple | ("KeyValuePattern"|"Identity"|"Box"|"Unbox"|"ToEnum"), [arg] -> TypeCast(arg, t) |> Some // Cast to unit to make sure nothing is returned when wrapped in a lambda, see #1360 - | "Ignore", _ -> "($0, null)" |> emitJs r t args |> Some + | "Ignore", _ -> "void ($0)" |> emitJs r t args |> Some // Number and String conversions | ("ToSByte"|"ToByte"|"ToInt8"|"ToUInt8"|"ToInt16"|"ToUInt16"|"ToInt"|"ToUInt"|"ToInt32"|"ToUInt32"), _ -> toInt com ctx r t args |> Some @@ -1317,14 +1374,15 @@ let operators (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr o match args with | [first; last] -> [first; getOne com ctx genArg; last] | _ -> args - let meth, args = + let modul, meth, args = match genArg with - // TODO: BigInt? - | Char -> "rangeChar", args - | Builtin BclInt64 -> "rangeLong", (addStep args) @ [makeBoolConst false] - | Builtin BclUInt64 -> "rangeLong", (addStep args) @ [makeBoolConst true] - | _ -> "rangeNumber", addStep args - Helper.CoreCall("Seq", meth, t, args, i.SignatureArgTypes, ?loc=r) |> Some + | Char -> "Seq", "rangeChar", args + | Builtin BclInt64 -> "Seq", "rangeLong", (addStep args) @ [makeBoolConst false] + | Builtin BclUInt64 -> "Seq", "rangeLong", (addStep args) @ [makeBoolConst true] + | Builtin BclDecimal -> "Seq", "rangeDecimal", addStep args + | Builtin BclBigInt -> "BigInt", "range", addStep args + | _ -> "Seq", "rangeNumber", addStep args + Helper.CoreCall(modul, meth, t, args, i.SignatureArgTypes, ?loc=r) |> Some // Pipes and composition | "op_PipeRight", [x; f] | "op_PipeLeft", [f; x] -> curriedApply r t f [x] |> Some @@ -1350,6 +1408,7 @@ let operators (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr o | "LazyPattern" // (|Lazy|_|) | "Lock" // lock | "NullArg" // nullArg + | "Using" // using ), _ -> fsharpModule com ctx r t i thisArg args // Exceptions | "FailWith", [msg] | "InvalidOp", [msg] -> @@ -1461,8 +1520,11 @@ let chars (com: ICompiler) (ctx: Context) r t (i: CallInfo) (_: Expr option) (ar | "GetUnicodeCategory" | "IsControl" | "IsDigit" | "IsLetter" | "IsLetterOrDigit" | "IsUpper" | "IsLower" | "IsNumber" | "IsPunctuation" | "IsSeparator" | "IsSymbol" | "IsWhiteSpace" - | "IsHighSurrogate" | "IsLowSurrogate" | "IsSurrogate" | "IsSurrogatePair" - | "Parse" -> + | "IsHighSurrogate" | "IsLowSurrogate" | "IsSurrogate" -> + let methName = Naming.lowerFirst i.CompiledName + let methName = if List.length args > 1 then methName + "2" else methName + Helper.CoreCall("Char", methName, t, args, i.SignatureArgTypes, ?loc=r) |> Some + | "IsSurrogatePair" | "Parse" -> let methName = Naming.lowerFirst i.CompiledName Helper.CoreCall("Char", methName, t, args, i.SignatureArgTypes, ?loc=r) |> Some | _ -> None @@ -1480,16 +1542,10 @@ let implementedStringFunctions = "PadRight" "Remove" "Replace" + "Substring" |] let strings (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Expr list) = - let join nonDelimiterArgType args = - let hasSpread = - match i.Spread, nonDelimiterArgType with - | SeqSpread, _ -> true - | _, EntFullName Types.ienumerableGeneric -> true - | _ -> false - Helper.CoreCall("String", "join", t, args, hasSpread=hasSpread, ?loc=r) match i.CompiledName, thisArg, args with | ".ctor", _, fstArg::_ -> match fstArg.Type with @@ -1524,8 +1580,7 @@ let strings (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr opt makeEqOp r left (makeIntConst 0) BinaryEqualStrict |> Some | "StartsWith", Some c, [_str; _comp] -> Helper.CoreCall("String", "startsWith", t, args, i.SignatureArgTypes, c, ?loc=r) |> Some - | ReplaceName [ "Substring", "substr" - "ToUpper", "toLocaleUpperCase" + | ReplaceName [ "ToUpper", "toLocaleUpperCase" "ToUpperInvariant", "toUpperCase" "ToLower", "toLocaleLowerCase" "ToLowerInvariant", "toLowerCase" ] methName, Some c, args -> @@ -1559,7 +1614,7 @@ let strings (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr opt | [Value(StringConstant _,_) as separator] | [Value(NewArray(ArrayValues [separator],_),_)] -> Helper.InstanceCall(c, "split", t, [separator]) |> Some - | [arg1; ExprType(EnumType _) as arg2] -> + | [arg1; ExprType(Enum _) as arg2] -> let arg1 = match arg1.Type with | Array _ -> arg1 @@ -1568,12 +1623,18 @@ let strings (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr opt Helper.CoreCall("String", "split", t, c::args, ?loc=r) |> Some | args -> Helper.CoreCall("String", "split", t, args, i.SignatureArgTypes, ?thisArg=thisArg, ?loc=r) |> Some - | "Join", None, [_delimiter; _parts; ExprType(Number _); ExprType(Number _)] -> - Helper.CoreCall("String", "joinWithIndices", t, args, ?loc=r) |> Some | "Join", None, _ -> - join (List.item 1 i.SignatureArgTypes) args |> Some + let methName = + match i.SignatureArgTypes with + | [_; Array _; Number _; Number _] -> "joinWithIndices" + | _ -> "join" + Helper.CoreCall("String", methName, t, args, ?loc=r) |> Some | "Concat", None, _ -> - join (List.head i.SignatureArgTypes) ((makeStrConst "")::args) |> Some + match i.SignatureArgTypes with + | [Array _ | IEnumerable] -> + Helper.CoreCall("String", "join", t, ((makeStrConst "")::args), ?loc=r) |> Some + | _ -> + Helper.CoreCall("String", "concat", t, args, hasSpread=true, ?loc=r) |> Some | "CompareOrdinal", None, _ -> Helper.CoreCall("String", "compareOrdinal", t, args, ?loc=r) |> Some | Patterns.SetContains implementedStringFunctions, thisArg, args -> @@ -1595,7 +1656,7 @@ let stringModule (com: ICompiler) (ctx: Context) r t (i: CallInfo) (_: Expr opti let name = Naming.lowerFirst i.CompiledName emitJs r t [Helper.CoreCall("Seq", name, Any, args, i.SignatureArgTypes)] "Array.from($0).join('')" |> Some | "Concat", _ -> - Helper.CoreCall("String", "join", t, args, hasSpread=true, ?loc=r) |> Some + Helper.CoreCall("String", "join", t, args, ?loc=r) |> Some // Rest of StringModule methods | meth, args -> Helper.CoreCall("String", Naming.lowerFirst meth, t, args, i.SignatureArgTypes, ?loc=r) |> Some @@ -1651,6 +1712,8 @@ let seqs (com: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (thisArg: Exp let meth = Naming.lowerFirst meth let args = injectArg com ctx r "Set" meth i.GenericArgs args Helper.CoreCall("Set", meth, t, args, i.SignatureArgTypes, ?loc=r) |> Some + | "TryExactlyOne", args -> + tryCoreOp r t "Seq" "exactlyOne" args |> Some | meth, _ -> let meth = Naming.lowerFirst meth let args = injectArg com ctx r "Seq" meth i.GenericArgs args @@ -1665,14 +1728,14 @@ let resizeArrays (com: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (this | ".ctor", _, [ExprType(Number _)] -> makeArray Any [] |> Some // Optimize expressions like `ResizeArray [|1|]` or `ResizeArray [1]` - | ".ctor", _, [Value((NewArray(ArrayValues vals, _)|ListLiteral(vals, _)),_)] -> + | ".ctor", _, [MaybeCasted(ArrayOrListLiteral(vals,_))] -> makeArray Any vals |> Some | ".ctor", _, args -> Helper.GlobalCall("Array", t, args, memb="from", ?loc=r) |> Some | "get_Item", Some ar, [idx] -> getExpr r t ar idx |> Some | "set_Item", Some ar, [idx; value] -> Set(ar, ExprSet idx, value, r) |> Some - | "Add", Some ar, args -> - Helper.InstanceCall(ar, "push", t, args, ?loc=r) |> Some + | "Add", Some ar, [arg] -> + "void ($0)" |> emitJs r t [Helper.InstanceCall(ar, "push", t, [arg])] |> Some | "Remove", Some ar, [arg] -> Helper.CoreCall("Array", "removeInPlace", t, [arg; ar], ?loc=r) |> Some | "RemoveAll", Some ar, [arg] -> @@ -1692,23 +1755,24 @@ let resizeArrays (com: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (this | "Clear", Some ar, _ -> Helper.CoreCall("Util", "clear", t, [ar], ?loc=r) |> Some | "Find", Some ar, [arg] -> - Helper.CoreCall("Option", "value", t, - [ Helper.CoreCall("Seq", "tryFind", t, [arg; ar; defaultof t], ?loc=r) - Value(BoolConstant true, None) ], ?loc=r) |> Some + let opt = Helper.CoreCall("Seq", "tryFind", t, [arg; ar; defaultof com ctx t], ?loc=r) + Helper.CoreCall("Option", "value", t, [opt], ?loc=r) |> Some | "Exists", Some ar, [arg] -> let left = Helper.InstanceCall(ar, "findIndex", Number Int32, [arg], ?loc=r) makeEqOp r left (makeIntConst -1) BinaryGreater |> Some | "FindLast", Some ar, [arg] -> - Helper.CoreCall("Option", "value", t, - [ Helper.CoreCall("Seq", "tryFindBack", t, [arg; ar; defaultof t], ?loc=r) - Value(BoolConstant true, None) ], ?loc=r) |> Some + let opt = Helper.CoreCall("Seq", "tryFindBack", t, [arg; ar; defaultof com ctx t], ?loc=r) + Helper.CoreCall("Option", "value", t, [opt], ?loc=r) |> Some | "FindAll", Some ar, [arg] -> Helper.CoreCall("Seq", "filter", t, [arg; ar], ?loc=r) |> toArray com t |> Some | "AddRange", Some ar, [arg] -> Helper.CoreCall("Array", "addRangeInPlace", t, [arg; ar], ?loc=r) |> Some - | "Contains", Some ar, [arg] -> - let left = Helper.InstanceCall(ar, "indexOf", Number Int32, [arg], ?loc=r) - makeEqOp r left (makeIntConst 0) BinaryGreaterOrEqual |> Some + | "Contains", Some (MaybeCasted(ar)), [arg] -> + match ar.Type with + | Array _ -> + let left = Helper.InstanceCall(ar, "indexOf", Number Int32, [arg], ?loc=r) + makeEqOp r left (makeIntConst 0) BinaryGreaterOrEqual |> Some + | _ -> Helper.InstanceCall(ar, "has", t, args, ?loc=r) |> Some | "IndexOf", Some ar, args -> Helper.InstanceCall(ar, "indexOf", t, args, ?loc=r) |> Some | "Insert", Some ar, [idx; arg] -> @@ -1740,6 +1804,18 @@ let nativeArrayFunctions = "SortInPlace", "sort" "SortInPlaceWith", "sort" |] +let tuples (_: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (thisArg: Expr option) (args: Expr list) = + match i.CompiledName, thisArg with + | "get_Item1", Some x -> Get(x, TupleGet 0, t, r) |> Some + | "get_Item2", Some x -> Get(x, TupleGet 1, t, r) |> Some + | "get_Item3", Some x -> Get(x, TupleGet 2, t, r) |> Some + | "get_Item4", Some x -> Get(x, TupleGet 3, t, r) |> Some + | "get_Item5", Some x -> Get(x, TupleGet 4, t, r) |> Some + | "get_Item6", Some x -> Get(x, TupleGet 5, t, r) |> Some + | "get_Item7", Some x -> Get(x, TupleGet 6, t, r) |> Some + | "get_Rest", Some x -> Get(x, TupleGet 7, t, r) |> Some + | _ -> None + let arrays (_: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (thisArg: Expr option) (args: Expr list) = match i.CompiledName, thisArg, args with | "get_Length", Some ar, _ -> get r t ar "length" |> Some @@ -1749,6 +1825,7 @@ let arrays (_: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (thisArg: Exp Helper.CoreCall("Array", "copyTo", t, [source; makeIntConst 0; target; makeIntConst 0; count], i.SignatureArgTypes, ?loc=r) |> Some | "Copy", None, [source; sourceIndex; target; targetIndex; count] -> Helper.CoreCall("Array", "copyTo", t, args, i.SignatureArgTypes, ?loc=r) |> Some + | "GetEnumerator", Some ar, _ -> getEnumerator r t ar |> Some | _ -> None let arrayModule (com: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (_: Expr option) (args: Expr list) = @@ -1757,9 +1834,8 @@ let arrayModule (com: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (_: Ex let createArray size value = match t, value with | Array(Number _ as t2), None -> newArray size t2 - | Array(Number _ as t2), Some value - | Array(Boolean as t2), OrDefault (makeBoolConst false) value - | Array t2, OrDefault (Value(Null Any, None)) value -> + | Array t2, value -> + let value = value |> Option.defaultWith (fun () -> getZero com ctx t2) // If we don't fill the array some operations may behave unexpectedly, like Array.prototype.reduce Helper.CoreCall("Array", "fill", t, [newArray size t2; makeIntConst 0; size; value]) | _ -> sprintf "Expecting an array type but got %A" t @@ -1779,6 +1855,11 @@ let arrayModule (com: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (_: Ex newArray (makeIntConst 0) t |> Some | "IsEmpty", [ar] -> eq (get r (Number Int32) ar "length") (makeIntConst 0) |> Some + | "AllPairs", args -> + let allPairs = Helper.CoreCall("Seq", "allPairs", t, args, i.SignatureArgTypes, ?loc=r) + toArray com t allPairs |> Some + | "TryExactlyOne", args -> + tryCoreOp r t "Array" "exactlyOne" args |> Some | Patterns.DicContains nativeArrayFunctions meth, _ -> let args, thisArg = List.splitLast args let argTypes = List.take (List.length args) i.SignatureArgTypes @@ -1816,6 +1897,11 @@ let listModule (com: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (_: Exp // literals to arrays) after the beta reduction pass | "ToSeq", [x] -> toSeq t x |> Some | "ToArray", [x] -> listToArray com r t x |> Some + | "AllPairs", args -> + let allPairs = Helper.CoreCall("Seq", "allPairs", t, args, i.SignatureArgTypes, ?loc=r) + toList t allPairs |> Some + | "TryExactlyOne", args -> + tryCoreOp r t "List" "exactlyOne" args |> Some | meth, _ -> let meth = Naming.lowerFirst meth let args = injectArg com ctx r "List" meth i.GenericArgs args @@ -1866,49 +1952,35 @@ let options (_: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (thisArg: Ex let optionModule (com: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (_: Expr option) (args: Expr list) = let toArray r t arg = - let ident = makeIdentUnique com "x" - let f = - [IdentExpr ident] - |> makeArray Any - |> makeDelegate [ident] - // Prevent functions being run twice, see #198 - Helper.CoreCall("Option", "defaultArg", t, [arg; makeArray Any []; f], ?loc=r) + Helper.CoreCall("Option", "toArray", Array t, [arg], ?loc=r) match i.CompiledName, args with | "None", _ -> NewOption(None, t) |> makeValue r |> Some | "GetValue", [c] -> Get(c, OptionValue, t, r) |> Some | ("OfObj" | "OfNullable"), [c] -> TypeCast(c, t) |> Some | ("ToObj" | "ToNullable" | "Flatten"), [c] -> - Helper.CoreCall("Option", "value", t, [c; makeBoolConst true], ?loc=r) |> Some + Helper.CoreCall("Option", "tryValue", t, args, ?loc=r) |> Some | "IsSome", [c] -> Test(c, OptionTest true, r) |> Some | "IsNone", [c] -> Test(c, OptionTest false, r) |> Some - | ("Map" | "Bind"), [f; arg] -> - let fType, argType = - match i.SignatureArgTypes with - | [fType; argType] -> fType, argType - | _ -> f.Type, arg.Type // unexpected - let args = [arg; Value(NewOption(None, argType), None); f] - Helper.CoreCall("Option", "defaultArg", t, args, [argType; Option argType; fType], ?loc=r) |> Some - | "Filter", _ -> - Helper.CoreCall("Option", "filter", t, args, i.SignatureArgTypes, ?loc=r) |> Some + | ("Filter" | "Map" | "Map2" | "Map3" | "Bind" as meth), args -> + Helper.CoreCall("Option", Naming.lowerFirst meth, t, args, i.SignatureArgTypes, ?loc=r) |> Some | "ToArray", [arg] -> toArray r t arg |> Some | "FoldBack", [folder; opt; state] -> - Helper.CoreCall("Seq", "foldBack", t, [folder; toArray None Any opt; state], i.SignatureArgTypes, ?loc=r) |> Some + Helper.CoreCall("Seq", "foldBack", t, [folder; toArray None t opt; state], i.SignatureArgTypes, ?loc=r) |> Some | ("DefaultValue" | "OrElse"), _ -> Helper.CoreCall("Option", "defaultArg", t, List.rev args, ?loc=r) |> Some | ("DefaultWith" | "OrElseWith"), _ -> Helper.CoreCall("Option", "defaultArgWith", t, List.rev args, List.rev i.SignatureArgTypes, ?loc=r) |> Some | ("Count" | "Contains" | "Exists" | "Fold" | "ForAll" | "Iterate" | "ToList" as meth), _ -> - let args = args |> List.replaceLast (toArray None Any) + let args = args |> List.replaceLast (toArray None t) let moduleName, meth = if meth = "ToList" then "List", "ofArray" else "Seq", Naming.lowerFirst meth Helper.CoreCall(moduleName, meth, t, args, i.SignatureArgTypes, ?loc=r) |> Some - // | "map2" | "map3" -> failwith "TODO" | _ -> None -let parse (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Expr list) = +let parseNum (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Expr list) = let parseCall meth str style = let kind = match i.DeclaringEntityFullName with @@ -1933,7 +2005,7 @@ let parse (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr optio | "IsInfinity", [_] when isFloat -> Helper.CoreCall("Double", "isInfinity", t, args, i.SignatureArgTypes, ?loc=r) |> Some | ("Parse" | "TryParse") as meth, - str::Value(Enum(NumberEnum(Value(NumberConstant(style, Int32),_)),_),_)::_ -> + str::Value(EnumConstant(Value(NumberConstant(style, _),_),_),_)::_ -> let style = int style let hexConst = int System.Globalization.NumberStyles.HexNumber let intConst = int System.Globalization.NumberStyles.Integer @@ -1976,7 +2048,7 @@ let decimals (com: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (thisArg: | "GetBits", _ -> Helper.CoreCall("Decimal", "getBits", t, args, i.SignatureArgTypes, ?loc=r) |> Some | ("Parse" | "TryParse"), _ -> - parse com ctx r t i thisArg args + parseNum com ctx r t i thisArg args | Operators.lessThan, [left; right] -> compareIf com r left right BinaryLess |> Some | Operators.lessThanOrEqual, [left; right] -> compareIf com r left right BinaryLessOrEqual |> Some | Operators.greaterThan, [left; right] -> compareIf com r left right BinaryGreater |> Some @@ -2026,6 +2098,9 @@ let bigints (com: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (thisArg: | Decimal -> toDecimal com ctx r t args |> Some | BigInt -> None | _ -> None + | None, "DivRem" -> + let args = List.take 2 args // implementation takes 2 args, ignore the third arg + Helper.CoreCall("BigInt", "divRem", t, args, i.SignatureArgTypes, ?loc=r) |> Some | None, meth when meth.StartsWith("get_") -> Helper.CoreValue("BigInt", meth, t) |> Some | callee, meth -> @@ -2045,14 +2120,22 @@ let languagePrimitives (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisAr | "DivideByInt", _ -> applyOp com ctx r t i.CompiledName args i.SignatureArgTypes i.GenericArgs |> Some | "GenericZero", _ -> getZero com ctx t |> Some | "GenericOne", _ -> getOne com ctx t |> Some + | ("SByteWithMeasure" + | "Int16WithMeasure" + | "Int32WithMeasure" + | "Int64WithMeasure" + | "Float32WithMeasure" + | "FloatWithMeasure" + | "DecimalWithMeasure"), [arg] -> arg |> Some | "EnumOfValue", [arg] -> match t with - | EnumType(_, fullName) -> Enum(NumberEnum arg, fullName) |> makeValue r |> Some - | _ -> Enum(NumberEnum arg, Naming.unknown) |> makeValue r |> Some + | Enum e -> EnumConstant(arg, e) |> makeValue r |> Some + | _ -> "EnumOfValue only works if the enum type is known at compile time, try inlining the function" + |> addErrorAndReturnNull com ctx.InlinePath r |> Some | "EnumToValue", [arg] -> match arg with | IdentExpr _ -> arg |> Some - | Value(Enum(NumberEnum(v),_),_) -> v |> Some + | Value(EnumConstant(v,_),_) -> v |> Some | _ -> None | ("GenericHash" | "GenericHashIntrinsic"), [arg] -> structuralHash r arg |> Some @@ -2155,7 +2238,8 @@ let runtimeHelpers (_: ICompiler) (ctx: Context) r t (i: CallInfo) thisArg args let funcs (_: ICompiler) (ctx: Context) r t (i: CallInfo) thisArg args = match i.CompiledName, thisArg with - | "Adapt", _ -> List.tryHead args // TODO: What's this used for? + // Just use Emit to change the type of the arg, Fable will automatically uncurry the function + | "Adapt", _ -> emitJs r t args "$0" |> Some | "Invoke", Some callee -> Helper.Application(callee, t, args, i.SignatureArgTypes, ?loc=r) |> Some | _ -> None @@ -2276,19 +2360,27 @@ let valueTypes (_: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr op let unchecked (com: ICompiler) (ctx: Context) r t (i: CallInfo) (_: Expr option) (args: Expr list) = match i.CompiledName with - | "DefaultOf" -> (genArg com ctx r 0 i.GenericArgs) |> defaultof |> Some + | "DefaultOf" -> (genArg com ctx r 0 i.GenericArgs) |> defaultof com ctx |> Some | "Hash" -> structuralHash r args.Head |> Some | "Equals" -> Helper.CoreCall("Util", "equals", t, args, i.SignatureArgTypes, ?loc=r) |> Some | "Compare" -> Helper.CoreCall("Util", "compare", t, args, i.SignatureArgTypes, ?loc=r) |> Some | _ -> None -let enums (_: ICompiler) (ctx: Context) r _ (i: CallInfo) (thisArg: Expr option) (args: Expr list) = +let enums (_: ICompiler) (_: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Expr list) = match thisArg, i.CompiledName, args with | Some this, "HasFlag", [arg] -> // x.HasFlags(y) => (int x) &&& (int y) <> 0 makeBinOp r (Number Int32) this arg BinaryAndBitwise |> fun bitwise -> makeEqOp r bitwise (makeIntConst 0) BinaryUnequal |> Some + | None, Patterns.DicContains (dict ["Parse", "parseEnum" + "TryParse", "tryParseEnum" + "IsDefined", "isEnumDefined" + "GetName", "getEnumName" + "GetNames", "getEnumNames" + "GetValues", "getEnumValues" + "GetUnderlyingType", "getEnumUnderlyingType"]) meth, args -> + Helper.CoreCall("Reflection", meth, t, args, ?loc=r) |> Some | _ -> None let log (_: ICompiler) r t (i: CallInfo) (_: Expr option) (args: Expr list) = @@ -2300,23 +2392,28 @@ let log (_: ICompiler) r t (i: CallInfo) (_: Expr option) (args: Expr list) = | _ -> [args.Head] Helper.GlobalCall("console", t, args, memb="log", ?loc=r) -let bitConvert (_: ICompiler) (ctx: Context) r (_: Type) (i: CallInfo) (_: Expr option) (args: Expr list) = - let memberName = - if i.CompiledName = "GetBytes" then +let bitConvert (com: ICompiler) (ctx: Context) r t (i: CallInfo) (_: Expr option) (args: Expr list) = + match i.CompiledName with + | "GetBytes" -> + let memberName = match args.Head.Type with | Boolean -> "getBytesBoolean" | Char | String -> "getBytesChar" | Number Int16 -> "getBytesInt16" | Number Int32 -> "getBytesInt32" - | Builtin BclInt64 -> "getBytesInt64" | Number UInt16 -> "getBytesUInt16" - | Builtin BclUInt64 -> "getBytesUInt64" | Number UInt32 -> "getBytesUInt32" | Number Float32 -> "getBytesSingle" | Number Float64 -> "getBytesDouble" + | Builtin BclInt64 -> "getBytesInt64" + | Builtin BclUInt64 -> "getBytesUInt64" | x -> failwithf "Unsupported type in BitConverter.GetBytes(): %A" x - else Naming.lowerFirst i.CompiledName - Helper.CoreCall("BitConverter", memberName, Boolean, args, i.SignatureArgTypes, ?loc=r) |> Some + let expr = Helper.CoreCall("BitConverter", memberName, Boolean, args, i.SignatureArgTypes, ?loc=r) + if com.Options.typedArrays then expr |> Some + else toArray com t expr |> Some // convert to dynamic array + | _ -> + let memberName = Naming.lowerFirst i.CompiledName + Helper.CoreCall("BitConverter", memberName, Boolean, args, i.SignatureArgTypes, ?loc=r) |> Some let convert (com: ICompiler) (ctx: Context) r t (i: CallInfo) (_: Expr option) (args: Expr list) = match i.CompiledName with @@ -2376,7 +2473,7 @@ let dates (_: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) | _ -> let last = List.last args match args.Length, last.Type with - | 7, EnumType(_, "System.DateTimeKind") -> + | 7, Enum ent when ent.TryFullName = Some "System.DateTimeKind" -> let args = (List.take 6 args) @ [makeIntConst 0; last] let argTypes = (List.take 6 i.SignatureArgTypes) @ [Number Int32; last.Type] Helper.CoreCall("Date", "create", t, args, argTypes, ?loc=r) |> Some @@ -2428,7 +2525,9 @@ let dates (_: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) let timeSpans (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Expr list) = // let callee = match i.callee with Some c -> c | None -> i.args.Head match i.CompiledName with - | ".ctor" -> Helper.CoreCall("TimeSpan", "create", t, args, i.SignatureArgTypes, ?loc=r) |> Some + | ".ctor" -> + let meth = match args with [ticks] -> "fromTicks" | _ -> "create" + Helper.CoreCall("TimeSpan", meth, t, args, i.SignatureArgTypes, ?loc=r) |> Some | "FromMilliseconds" -> TypeCast(args.Head, t) |> Some | "get_TotalMilliseconds" -> TypeCast(thisArg.Value, t) |> Some | "ToString" when (args.Length = 1) -> @@ -2555,11 +2654,16 @@ let regex com (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Exp let meth = Naming.removeGetSetPrefix meth |> Naming.lowerFirst Helper.CoreCall("RegExp", meth, t, args, i.SignatureArgTypes, ?thisArg=thisArg, ?loc=r) |> Some -let encoding (_: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Expr list) = +let encoding (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Expr list) = match i.CompiledName, thisArg, args.Length with | ("get_Unicode" | "get_UTF8"), _, _ -> Helper.CoreCall("Encoding", i.CompiledName, t, args, i.SignatureArgTypes, ?loc=r) |> Some - | ("GetBytes" | "GetString"), Some callee, (1 | 3) -> + | "GetBytes", Some callee, (1 | 3) -> + let meth = Naming.lowerFirst i.CompiledName + let expr = Helper.InstanceCall(callee, meth, t, args, i.SignatureArgTypes, ?loc=r) + if com.Options.typedArrays then expr |> Some + else toArray com t expr |> Some // convert to dynamic array + | "GetString", Some callee, (1 | 3) -> let meth = Naming.lowerFirst i.CompiledName Helper.InstanceCall(callee, meth, t, args, i.SignatureArgTypes, ?loc=r) |> Some | _ -> None @@ -2603,15 +2707,15 @@ let exprs (name : string) (_: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo | [a;n] -> Helper.CoreCall("Quotations", name, t, [a; makeTypeInfo None a.Type; n], i.SignatureArgTypes, ?loc=r) |> Some | _ -> Helper.CoreCall("Quotations", name, t, args, i.SignatureArgTypes, ?loc=r) |> Some - - | meth, Some x,_ -> + + | meth, Some x,_ -> let _,name = getMangledNames i (Some x) Helper.CoreCall("Quotations", name, t, x :: args, i.SignatureArgTypes, ?loc=r) |> Some - | meth, None,_ -> + | meth, None,_ -> //match t with - // | Fable.Expr _ -> + // | Fable.Expr _ -> // let hash = match i.Original with | Some o -> lazy (OverloadSuffix.getExtensionHash o) | _ -> lazy "" // let _,name = getMangledNames { i with OverloadSuffix = hash } None // Helper.CoreCall("Quotations", name, t, args, i.SignatureArgTypes, ?loc=r) |> Some @@ -2672,7 +2776,7 @@ let guids (_: ICompiler) (ctx: Context) (_: SourceLocation option) t (i: CallInf | "ToByteArray" -> Helper.CoreCall("String", "guidToArray", t, [thisArg.Value], [thisArg.Value.Type]) |> Some | ".ctor" -> match args with - | [] -> makeStrConst "00000000-0000-0000-0000-000000000000" |> Some + | [] -> emptyGuid() |> Some | [ExprType (Array _)] -> Helper.CoreCall("String", "arrayToGuid", t, args, i.SignatureArgTypes) |> Some | [ExprType String] -> Helper.CoreCall("String", "validateGuid", t, args, i.SignatureArgTypes) |> Some | _ -> None @@ -2722,16 +2826,16 @@ let controlExtensions (_: ICompiler) (ctx: Context) (_: SourceLocation option) t |> fun (args, argTypes) -> List.rev args, List.rev argTypes Helper.CoreCall("Observable", meth, t, args, argTypes)) - let callTypeInfoMethod (this : Expr) (name : string) (typ : Type) (args : list) = // let self = com.TranslateExpr this // let ex = Babel.MemberExpression(self, Identifier "NewInfo", computed, ?loc=r) :> Expression //Helper.InstanceCall(Helper.InstanceField(this, "NewInfo", Type.Any), name, typ, args) Helper.InstanceCall(this, name, typ, args) + let types (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Expr list) = let returnString r x = StringConstant x |> makeValue r |> Some - + // TODO!!! Optimizations when the type is known at compile time (see commented code from master below) match thisArg, i.CompiledName with | Some this, "get_IsGenericParameter" -> callTypeInfoMethod this "get_IsGenericParameter" t [] |> Some | Some this, "get_FullName" -> callTypeInfoMethod this "get_FullName" t [] |> Some @@ -2754,74 +2858,78 @@ let types (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr optio | Some this, "GetConstructors" -> callTypeInfoMethod this "GetConstructors" t args |> Some | Some this, "GetProperty" -> callTypeInfoMethod this "GetProperty" t [List.head args] |> Some - | Some this, "GetMethod" -> + | Some this, "GetMethod" -> match args with | [a] when a.Type = Fable.String -> callTypeInfoMethod this "GetMethod" t [a] |> Some | [a;b] when a.Type = Fable.String -> callTypeInfoMethod this "GetMethod" t [a; b] |> Some | a::_::_::b::_ when a.Type = Fable.String && b.Type = Fable.Array (Fable.MetaType) -> callTypeInfoMethod this "GetMethod" t [a; b] |> Some | _ -> None | Some this, "GetField" -> callTypeInfoMethod this "GetField" t [List.head args] |> Some - - | Some this, "GetConstructor" -> + + | Some this, "GetConstructor" -> match args with | [] -> callTypeInfoMethod this "GetConstructor" t [] |> Some | [ts] -> callTypeInfoMethod this "GetConstructor" t [ts] |> Some | _ -> None - + | Some this, "MakeGenericType" -> callTypeInfoMethod this "MakeGenericType" t args |> Some + | Some this, "get_IsEnum" -> Helper.CoreCall("Reflection", "isEnum", t, [this], ?loc=r) |> Some + | Some this, "GetEnumUnderlyingType" -> Helper.CoreCall("Reflection", "getEnumUnderlyingType", t, [this], ?loc=r) |> Some + | Some this, "GetEnumValues" -> Helper.CoreCall("Reflection", "getEnumValues", t, [this], ?loc=r) |> Some + | Some this, "GetEnumNames" -> Helper.CoreCall("Reflection", "getEnumNames", t, [this], ?loc=r) |> Some + | _ -> None - // match thisArg with - // | Some(Value(TypeInfo exprType, exprRange) as thisArg) -> - // match exprType with - // | GenericParam name -> genericTypeInfoError name |> addError com ctx.InlinePath exprRange - // | _ -> () - // match i.CompiledName with - // | "get_FullName" -> getTypeFullName false exprType |> returnString r - // | "get_Namespace" -> - // let fullname = getTypeFullName false exprType - // match fullname.LastIndexOf(".") with - // | -1 -> "" |> returnString r - // | i -> fullname.Substring(0, i) |> returnString r - // | "get_IsArray" -> - // match exprType with Array _ -> true | _ -> false - // |> BoolConstant |> makeValue r |> Some - // | "GetElementType" -> + // let resolved = + // // Some optimizations when the type is known at compile time + // match thisArg with + // | Some(Value(TypeInfo exprType, exprRange) as thisArg) -> // match exprType with - // | Array t -> TypeInfo t |> makeValue r |> Some - // | _ -> Null t |> makeValue r |> Some - // | "get_IsGenericType" -> - // List.isEmpty exprType.Generics |> not |> BoolConstant |> makeValue r |> Some - // | "get_GenericTypeArguments" | "GetGenericArguments" -> - // let arVals = exprType.Generics |> List.map (makeTypeInfo r) |> ArrayValues - // NewArray(arVals, Any) |> makeValue r |> Some - // | "GetTypeInfo" -> Some thisArg - // | "GetGenericTypeDefinition" -> - // let newGen = exprType.Generics |> List.map (fun _ -> Any) - // exprType.ReplaceGenerics(newGen) |> TypeInfo |> makeValue exprRange |> Some - // | "GetProperties" -> Helper.CoreCall("Reflection", "getTypeProperties", t, [thisArg], ?loc=r) |> Some - // | "GetFields" -> Helper.CoreCall("Reflection", "getTypeFields", t, [thisArg], ?loc=r) |> Some - // | "GetMembers" -> Helper.CoreCall("Reflection", "getTypeMembers", t, [thisArg], ?loc=r) |> Some - - // | "GetMethods" -> callTypeInfoMethod thisArg "GetMethods" t args |> Some - - // | _ -> None - // | Some thisArg -> + // | GenericParam name -> genericTypeInfoError name |> addError com ctx.InlinePath exprRange + // | _ -> () + // match i.CompiledName with + // | "get_FullName" -> getTypeFullName false exprType |> returnString r + // | "get_Namespace" -> + // let fullname = getTypeFullName false exprType + // match fullname.LastIndexOf(".") with + // | -1 -> "" |> returnString r + // | i -> fullname.Substring(0, i) |> returnString r + // | "get_IsArray" -> + // match exprType with Array _ -> true | _ -> false + // |> BoolConstant |> makeValue r |> Some + // | "get_IsEnum" -> + // match exprType with + // | Enum t -> true | _ -> false + // |> BoolConstant |> makeValue r |> Some + // | "GetElementType" -> + // match exprType with + // | Array t -> TypeInfo t |> makeValue r |> Some + // | _ -> Null t |> makeValue r |> Some + // | "get_IsGenericType" -> + // List.isEmpty exprType.Generics |> not |> BoolConstant |> makeValue r |> Some + // | "get_GenericTypeArguments" | "GetGenericArguments" -> + // let arVals = exprType.Generics |> List.map (makeTypeInfo r) |> ArrayValues + // NewArray(arVals, Any) |> makeValue r |> Some + // | "GetGenericTypeDefinition" -> + // let newGen = exprType.Generics |> List.map (fun _ -> Any) + // exprType.ReplaceGenerics(newGen) |> TypeInfo |> makeValue exprRange |> Some + // | _ -> None + // | _ -> None + // match resolved, thisArg with + // | Some _, _ -> resolved + // | None, Some thisArg -> // match i.CompiledName with + // | "GetTypeInfo" -> Some thisArg // | "get_GenericTypeArguments" | "GetGenericArguments" -> // Helper.CoreCall("Reflection", "getGenerics", t, [thisArg], ?loc=r) |> Some - // | "get_FullName" | "get_Namespace" | "get_IsArray" | "GetElementType" - // | "get_IsGenericType" | "GetGenericTypeDefinition" -> + // | "get_FullName" | "get_Namespace" + // | "get_IsArray" | "GetElementType" + // | "get_IsGenericType" | "GetGenericTypeDefinition" + // | "get_IsEnum" | "GetEnumUnderlyingType" | "GetEnumValues" | "GetEnumNames" -> // let meth = Naming.removeGetSetPrefix i.CompiledName |> Naming.lowerFirst // Helper.CoreCall("Reflection", meth, t, [thisArg], ?loc=r) |> Some - // | "GetTypeInfo" -> Some thisArg - // | "GetProperties" -> Helper.CoreCall("Reflection", "getTypeProperties", t, [thisArg], ?loc=r) |> Some - // | "GetFields" -> Helper.CoreCall("Reflection", "getTypeFields", t, [thisArg], ?loc=r) |> Some - // | "GetMembers" -> Helper.CoreCall("Reflection", "getTypeMembers", t, [thisArg], ?loc=r) |> Some - - // | "GetMethods" -> callTypeInfoMethod thisArg "GetMethods" t args |> Some // | _ -> None - // | None -> None + // | None, None -> None let fsharpType methName (r: SourceLocation option) t (i: CallInfo) (args: Expr list) = match methName with @@ -2861,7 +2969,7 @@ let tryField returnTyp ownerTyp fieldName = | Builtin BclDecimal, _ -> Helper.CoreValue(coreModFor BclDecimal, "get_" + fieldName, returnTyp) |> Some | String, "Empty" -> makeStrConst "" |> Some - | Builtin BclGuid, "Empty" -> makeStrConst "00000000-0000-0000-0000-000000000000" |> Some + | Builtin BclGuid, "Empty" -> emptyGuid() |> Some | Builtin BclTimeSpan, "Zero" -> makeIntConst 0 |> Some | Builtin BclDateTime, ("MaxValue" | "MinValue") -> Helper.CoreCall(coreModFor BclDateTime, Naming.lowerFirst fieldName, returnTyp, []) |> Some @@ -2878,9 +2986,9 @@ let private replacedModules = dict [ "Microsoft.FSharp.Quotations.FSharpExpr", exprs "Expr" "Microsoft.FSharp.Quotations.FSharpVar", exprs "Var" - "Microsoft.FSharp.Quotations.PatternsModule", exprs "Patterns" - "Microsoft.FSharp.Quotations.DerivedPatternsModule", exprs "DerivedPatterns" - "Microsoft.FSharp.Quotations.ExprShapeModule", exprs "ExprShape" + "Microsoft.FSharp.Quotations.PatternsModule", exprs "Patterns" + "Microsoft.FSharp.Quotations.DerivedPatternsModule", exprs "DerivedPatterns" + "Microsoft.FSharp.Quotations.ExprShapeModule", exprs "ExprShape" "System.Math", operators "Microsoft.FSharp.Core.Operators", operators "Microsoft.FSharp.Core.Operators.Checked", operators @@ -2905,6 +3013,8 @@ let private replacedModules = "Microsoft.FSharp.Core.CompilerServices.RuntimeHelpers", seqs "Microsoft.FSharp.Collections.SeqModule", seqs "System.Collections.Generic.KeyValuePair`2", keyValuePairs + "System.Collections.Generic.Comparer`1", bclType + "System.Collections.Generic.EqualityComparer`1", bclType Types.dictionary, dictionaries Types.idictionary, dictionaries Types.ienumerableGeneric, enumerables @@ -2918,6 +3028,8 @@ let private replacedModules = Types.resizeArray, resizeArrays "System.Collections.Generic.IList`1", resizeArrays "System.Collections.Generic.ICollection`1", resizeArrays + "System.Collections.IList", resizeArrays + "System.Collections.ICollection", resizeArrays Types.hashset, hashSets Types.iset, hashSets Types.option, options @@ -2931,16 +3043,16 @@ let private replacedModules = Types.valueType, valueTypes "System.Enum", enums "System.BitConverter", bitConvert - Types.int8, parse - Types.uint8, parse - Types.int16, parse - Types.uint16, parse - Types.int32, parse - Types.uint32, parse - Types.int64, parse - Types.uint64, parse - Types.float32, parse - Types.float64, parse + Types.int8, parseNum + Types.uint8, parseNum + Types.int16, parseNum + Types.uint16, parseNum + Types.int32, parseNum + Types.uint32, parseNum + Types.int64, parseNum + Types.uint64, parseNum + Types.float32, parseNum + Types.float64, parseNum Types.decimal, decimals "System.Convert", convert "System.Console", console @@ -3018,7 +3130,7 @@ let tryCall (com: ICompiler) (ctx: Context) r t (info: CallInfo) (thisArg: Expr if isFSharpType then fsharpType methName r t info args else fsharpValue methName r t info args - | "System.Reflection.MemberInfo" + | "System.Reflection.MemberInfo" | "System.Reflection.MethodBase" | "System.Reflection.ConstructorInfo" | "System.Reflection.PropertyInfo" @@ -3065,7 +3177,7 @@ let tryCall (com: ICompiler) (ctx: Context) r t (info: CallInfo) (thisArg: Expr | [a;i] -> Helper.InstanceCall(c, "GetValue", t, [a; i]) |> Some | a::_::_::i::_ -> Helper.InstanceCall(c, "GetValue", t, [a; i]) |> Some | _ -> None - | _ -> + | _ -> let isStatic = Option.isNone thisArg sprintf "UNKNOWN reflection member: { isStatic: %A; name: %A; args: %A }" isStatic info.CompiledName args |> addError com [] None None @@ -3074,24 +3186,15 @@ let tryCall (com: ICompiler) (ctx: Context) r t (info: CallInfo) (thisArg: Expr // match thisArg, info.CompiledName with // | Some c, "GetCustomAttributes" -> Helper.CoreCall("Reflection", "customAttributes", t, [c], ?loc=r) |> Some // | Some c, "get_IsStatic" -> Helper.CoreCall("Reflection", "isStatic", t, [c], ?loc=r) |> Some - // | Some c, "get_Tag" -> makeStrConst "tag" |> getExpr r t c |> Some // | Some c, "get_PropertyType" -> makeIntConst 1 |> getExpr r t c |> Some + // | Some c, "get_Tag" -> makeStrConst "tag" |> getExpr r t c |> Some // | Some c, "GetFields" -> Helper.CoreCall("Reflection", "getUnionCaseFields", t, [c], ?loc=r) |> Some + // | Some c, "GetValue" -> Helper.CoreCall("Reflection", "getValue", t, c::args, ?loc=r) |> Some // | Some c, "get_Name" -> // match c with // | Value(TypeInfo exprType, loc) -> - // match exprType with - // | GenericParam name -> genericTypeInfoError name |> addWarning com ctx.InlinePath loc - // | _ -> () - - // let fullname = getTypeFullName false exprType - // let fullname = - // match fullname.IndexOf("[") with - // | -1 -> fullname - // | i -> fullname.[..i - 1] - // match fullname.LastIndexOf(".") with - // | -1 -> fullname |> StringConstant |> makeValue r |> Some - // | i -> fullname.Substring(i + 1) |> StringConstant |> makeValue r |> Some + // getTypeName com ctx loc exprType + // |> StringConstant |> makeValue r |> Some // | c -> // Helper.CoreCall("Reflection", "name", t, [c], ?loc=r) |> Some // | _ -> None @@ -3109,27 +3212,29 @@ let tryBaseConstructor com (ent: FSharpEntity) (memb: FSharpMemberOrFunctionOrVa let args = match FSharp2Fable.TypeHelpers.getArgTypes com memb, args with | ([]|[Number _]), _ -> - [makeArray Any []; makeComparer com (Seq.head genArgs)] + [makeArray Any []; makeEqualityComparer com (Seq.head genArgs)] | [IDictionary], [arg] -> - [arg; makeComparer com (Seq.head genArgs)] + [arg; makeEqualityComparer com (Seq.head genArgs)] | [IDictionary; IEqualityComparer], [arg; eqComp] -> [arg; makeComparerFromEqualityComparer eqComp] | [IEqualityComparer], [eqComp] | [Number _; IEqualityComparer], [_; eqComp] -> [makeArray Any []; makeComparerFromEqualityComparer eqComp] | _ -> failwith "Unexpected dictionary constructor" - Some(makeCoreRef Any "Dictionary" "DictTypes", args) + let entityName = Naming.sanitizeIdentForbiddenChars "MutableMap`2" + Some(makeCoreRef Any entityName "MutableMap", args) | Types.hashset -> let args = match FSharp2Fable.TypeHelpers.getArgTypes com memb, args with | [], _ -> - [makeArray Any []; makeComparer com (Seq.head genArgs)] + [makeArray Any []; makeEqualityComparer com (Seq.head genArgs)] | [IEnumerable], [arg] -> - [arg; makeComparer com (Seq.head genArgs)] + [arg; makeEqualityComparer com (Seq.head genArgs)] | [IEnumerable; IEqualityComparer], [arg; eqComp] -> [arg; makeComparerFromEqualityComparer eqComp] | [IEqualityComparer], [eqComp] -> [makeArray Any []; makeComparerFromEqualityComparer eqComp] | _ -> failwith "Unexpected hashset constructor" - Some(makeCoreRef Any "HashSet" "DictTypes", args) + let entityName = Naming.sanitizeIdentForbiddenChars "MutableSet`1" + Some(makeCoreRef Any entityName "MutableSet", args) | _ -> None diff --git a/src/Fable.Transforms/ReplacementsInject.fs b/src/Fable.Transforms/ReplacementsInject.fs index 24e781a2f1..3face0de70 100644 --- a/src/Fable.Transforms/ReplacementsInject.fs +++ b/src/Fable.Transforms/ReplacementsInject.fs @@ -20,7 +20,7 @@ let fableReplacementsModules = "mapIndexed2", [(Types.arrayCons, 2)] "map2", [(Types.arrayCons, 2)] "mapIndexed3", [(Types.arrayCons, 3)] - "map3", [(Types.arrayCons, 2)] + "map3", [(Types.arrayCons, 3)] "mapFold", [(Types.arrayCons, 2)] "mapFoldBack", [(Types.arrayCons, 2)] "concat", [(Types.arrayCons, 0)] @@ -60,6 +60,7 @@ let fableReplacementsModules = "averageBy", [("Fable.Core.IGenericAverager`1", 1)] "ofSeq", [(Types.arrayCons, 0)] "ofList", [(Types.arrayCons, 0)] + "transpose", [(Types.arrayCons, 0)] ] "List", Map [ "contains", [(Types.equalityComparer, 0)] @@ -82,7 +83,7 @@ let fableReplacementsModules = "countBy", [(Types.equalityComparer, 1)] ] "Set", Map [ - "FSharpSet$$Map$$38806891", [(Types.comparer, 1)] + "FSharpSet$$Map$$7597B8F7", [(Types.comparer, 1)] "singleton", [(Types.comparer, 0)] "unionMany", [(Types.comparer, 0)] "empty", [(Types.comparer, 0)] @@ -91,9 +92,9 @@ let fableReplacementsModules = "ofArray", [(Types.comparer, 0)] "toArray", [(Types.arrayCons, 0)] "ofSeq", [(Types.comparer, 0)] - "createMutable", [(Types.comparer, 0)] - "distinct", [(Types.comparer, 0)] - "distinctBy", [(Types.comparer, 1)] + "createMutable", [(Types.equalityComparer, 0)] + "distinct", [(Types.equalityComparer, 0)] + "distinctBy", [(Types.equalityComparer, 1)] "intersectWith", [(Types.comparer, 0)] "isSubsetOf", [(Types.comparer, 0)] "isSupersetOf", [(Types.comparer, 0)] @@ -105,9 +106,9 @@ let fableReplacementsModules = "ofSeq", [(Types.comparer, 0)] "ofArray", [(Types.comparer, 0)] "empty", [(Types.comparer, 0)] - "createMutable", [(Types.comparer, 0)] - "groupBy", [(Types.comparer, 1)] - "countBy", [(Types.comparer, 1)] + "createMutable", [(Types.equalityComparer, 0)] + "groupBy", [(Types.equalityComparer, 1)] + "countBy", [(Types.equalityComparer, 1)] ] ] diff --git a/src/Fable.Transforms/Transforms.Util.fs b/src/Fable.Transforms/Transforms.Util.fs index f9deccd0e2..91d70444c1 100644 --- a/src/Fable.Transforms/Transforms.Util.fs +++ b/src/Fable.Transforms/Transforms.Util.fs @@ -64,10 +64,13 @@ module Types = let [] idictionary = "System.Collections.Generic.IDictionary`2" let [] hashset = "System.Collections.Generic.HashSet`1" let [] iset = "System.Collections.Generic.ISet`1" + let [] keyValuePair = "System.Collections.Generic.KeyValuePair`2" let [] fsharpMap = "Microsoft.FSharp.Collections.FSharpMap`2" let [] fsharpSet = "Microsoft.FSharp.Collections.FSharpSet`1" let [] ienumerableGeneric = "System.Collections.Generic.IEnumerable`1" let [] ienumerable = "System.Collections.IEnumerable" + let [] iequatableGeneric = "System.IEquatable`1" + let [] iequatable = "System.IEquatable" let [] icomparable = "System.IComparable" let [] idisposable = "System.IDisposable" let [] reference = "Microsoft.FSharp.Core.FSharpRef`1" @@ -206,20 +209,6 @@ module AST = let inline (|ExprType|) (e: Expr) = e.Type let inline (|IdentType|) (id: Ident) = id.Type - /// ATTENTION: Only intended to be used in lambdaBetaReduction - let rec (|NestedCompilerGeneratedLetsAndLambdas|_|) expr = - let rec nestedLetsAndLambdas identValues lambdaArgs body = - match body with - | Let([ident, value], body) when ident.IsCompilerGenerated -> - nestedLetsAndLambdas ((ident, value)::identValues) lambdaArgs body - | Function(Lambda arg, body, None) when arg.IsCompilerGenerated -> - nestedLetsAndLambdas identValues (arg::lambdaArgs) body - | _ -> List.rev identValues, List.rev lambdaArgs, body - match expr with - | Let([ident, value], body) when ident.IsCompilerGenerated -> - nestedLetsAndLambdas [ident, value] [] body |> Some - | _ -> None - let (|NestedLambdaType|_|) t = let rec nestedLambda acc = function | FunctionType(LambdaType arg, returnType) -> @@ -230,20 +219,31 @@ module AST = | _ -> None /// Only matches lambda immediately nested within each other - let rec (|NestedLambda|_|) expr = - let rec nestedLambda accArgs body name = + let rec nestedLambda checkArity expr = + let rec inner accArgs body name = match body with | Function(Lambda arg, body, None) -> - nestedLambda (arg::accArgs) body name + inner (arg::accArgs) body name | _ -> List.rev accArgs, body, name match expr with | Function(Lambda arg, body, name) -> - let args, body, name = nestedLambda [arg] body name - match expr.Type with - | NestedLambdaType(argTypes, _) when List.sameLength args argTypes -> Some(args, body, name) - | _ -> None + let args, body, name = inner [arg] body name + if checkArity then + match expr.Type with + | NestedLambdaType(argTypes, _) + when List.sameLength args argTypes -> Some(args, body, name) + | _ -> None + else + Some(args, body, name) | _ -> None + let (|NestedLambdaWithSameArity|_|) expr = + nestedLambda true expr + + /// Doesn't check the type of lambda body has same arity as discovered arguments + let (|NestedLambda|_|) expr = + nestedLambda false expr + let (|NestedApply|_|) expr = let rec nestedApply r t accArgs applied = match applied with @@ -285,30 +285,30 @@ module AST = | MaybeCasted(LambdaUncurriedAtCompileTime None lambda) -> lambda | e -> e - /// When referenced multiple times, is there a risk of double evaluation? - /// Functions return true because we don't want to duplicate them in the code + // Functions return yes because we don't want to duplicate them in the code // TODO: Improve this, see https://github.com/fable-compiler/Fable/issues/1659#issuecomment-445071965 - let rec hasDoubleEvalRisk = function + let rec canHaveSideEffects = function | Import _ -> false - | IdentExpr id -> id.IsMutable | Value((Null _ | UnitConstant | NumberConstant _ | StringConstant _ | BoolConstant _),_) -> false - | Value(NewTuple exprs,_) -> exprs |> List.exists hasDoubleEvalRisk - | Value(Enum(kind, _),_) -> - match kind with NumberEnum e | StringEnum e -> hasDoubleEvalRisk e - | Get(_,kind,_,_) -> + | Value(NewTuple exprs,_) -> + (false, exprs) ||> List.fold (fun result e -> result || canHaveSideEffects e) + | Value(EnumConstant(e, _),_) -> canHaveSideEffects e + | IdentExpr id -> id.IsMutable + | Get(e,kind,_,_) -> match kind with // OptionValue has a runtime check | ListHead | ListTail | TupleGet _ - | UnionTag | UnionField _ -> false - | FieldGet(_,hasDoubleEvalRisk,_) -> hasDoubleEvalRisk + | UnionTag | UnionField _ -> canHaveSideEffects e + | FieldGet(_,isFieldMutable,_) -> + if isFieldMutable then true + else canHaveSideEffects e | _ -> true | _ -> true - /// TODO: Add string and other nullable types? - /// For unit, unresolved generics or nested options, create a runtime wrapper - /// See fable-library/Option.ts for more info + /// For unit, unresolved generics or nested options or unknown types, + /// create a runtime wrapper. See fable-library/Option.ts for more info. let rec mustWrapOption = function - | Unit | GenericParam _ | Option _ -> true + | Any | Unit | GenericParam _ | Option _ -> true | _ -> false /// ATTENTION: Make sure the ident name will be unique within the file @@ -403,6 +403,17 @@ module AST = let get r t left membName = makeStrConst membName |> getExpr r t left + let getNumberKindName kind = + match kind with + | Int8 -> "int8" + | UInt8 -> "uint8" + | Int16 -> "int16" + | UInt16 -> "uint16" + | Int32 -> "int32" + | UInt32 -> "uint32" + | Float32 -> "float32" + | Float64 -> "float64" + let getTypedArrayName (com: ICompiler) numberKind = match numberKind with | Int8 -> "Int8Array" @@ -433,6 +444,10 @@ module AST = /// When strict is false doesn't take generic params into account (e.g. when solving SRTP) let rec typeEquals strict typ1 typ2 = + let entEquals (ent1: FSharp.Compiler.SourceCodeServices.FSharpEntity) gen1 (ent2: FSharp.Compiler.SourceCodeServices.FSharpEntity) gen2 = + match ent1.TryFullName, ent2.TryFullName with + | Some n1, Some n2 when n1 = n2 -> listEquals (typeEquals strict) gen1 gen2 + | _ -> false match typ1, typ2 with | Any, Any | Unit, Unit @@ -441,7 +456,7 @@ module AST = | String, String | Regex, Regex -> true | Number kind1, Number kind2 -> kind1 = kind2 - | EnumType(kind1, name1), EnumType(kind2, name2) -> kind1 = kind2 && name1 = name2 + | Enum ent1, Enum ent2 -> entEquals ent1 [] ent2 [] | Option t1, Option t2 | Array t1, Array t2 | List t1, List t2 -> typeEquals strict t1 t2 @@ -459,10 +474,25 @@ module AST = | GenericParam name1, GenericParam name2 -> name1 = name2 | _ -> false - let rec getTypeFullName prettify = function + let rec getTypeFullName prettify t = + let getEntityFullName (ent: FSharp.Compiler.SourceCodeServices.FSharpEntity) gen = + match ent.TryFullName with + | None -> Naming.unknown + | Some fullname when List.isEmpty gen -> fullname + | Some fullname -> + let gen = (List.map (getTypeFullName prettify) gen |> String.concat ",") + let fullname = + if prettify then + match fullname with + | Types.result -> "Result" + | Naming.StartsWith Types.choiceNonGeneric _ -> "Choice" + | _ -> fullname // TODO: Prettify other types? + else fullname + fullname + "[" + gen + "]" + match t with | AnonymousRecordType _ -> "" | GenericParam name -> "'" + name - | EnumType(_, fullname) -> fullname + | Enum ent -> getEntityFullName ent [] | Regex -> Types.regex | MetaType -> Types.type_ | Unit -> Types.unit @@ -507,19 +537,7 @@ module AST = let gen = getTypeFullName prettify gen if prettify then gen + " list" else Types.list + "[" + gen + "]" | DeclaredType(ent, gen) -> - match ent.TryFullName with - | None -> Naming.unknown - | Some fullname when List.isEmpty gen -> fullname - | Some fullname -> - let gen = (List.map (getTypeFullName prettify) gen |> String.concat ",") - let fullname = - if prettify then - match fullname with - | Types.result -> "Result" - | Naming.StartsWith Types.choiceNonGeneric _ -> "Choice" - | _ -> fullname // TODO: Prettify other types? - else fullname - fullname + "[" + gen + "]" + getEntityFullName ent gen let addRanges (locs: SourceLocation option seq) = let addTwo (r1: SourceLocation option) (r2: SourceLocation option) = diff --git a/src/fable-babel-plugins/RELEASE_NOTES.md b/src/fable-babel-plugins/RELEASE_NOTES.md index 38867b60a8..fa0ffe5848 100644 --- a/src/fable-babel-plugins/RELEASE_NOTES.md +++ b/src/fable-babel-plugins/RELEASE_NOTES.md @@ -1,3 +1,7 @@ +### 2.3.0 + +* Fix #1982: Fix assigning nulls through Babel macro (by @inosik) + ### 2.2.0 * Enable literal string arguments in Emit macros diff --git a/src/fable-babel-plugins/index.js b/src/fable-babel-plugins/index.js index f017c7ff1d..64121de043 100644 --- a/src/fable-babel-plugins/index.js +++ b/src/fable-babel-plugins/index.js @@ -86,7 +86,7 @@ function getTransformMacroExpressions(babelTemplate) { }) .replace(/\{\{([^\}]*\$(\d+).*?)\}\}/g, (_, g1, g2) => { const i = parseInt(g2, 10); - return typeof args[i] === "object" && args[i].type !== "NullLiteral" ? g1 : ""; + return typeof args[i] === "object" ? g1 : ""; }) .replace(/\$(\d+)!/, (_, i) => { const arg = args[parseInt(i, 10)] diff --git a/src/fable-babel-plugins/package-lock.json b/src/fable-babel-plugins/package-lock.json new file mode 100644 index 0000000000..6f37134813 --- /dev/null +++ b/src/fable-babel-plugins/package-lock.json @@ -0,0 +1,5 @@ +{ + "name": "fable-babel-plugins", + "version": "2.3.0", + "lockfileVersion": 1 +} diff --git a/src/fable-babel-plugins/package.json b/src/fable-babel-plugins/package.json index 1d027650a5..0419f3e0f8 100644 --- a/src/fable-babel-plugins/package.json +++ b/src/fable-babel-plugins/package.json @@ -1,6 +1,6 @@ { "name": "fable-babel-plugins", - "version": "2.2.0", + "version": "2.3.0", "main": "index.js", "description": "Fable compiler", "keywords": [ diff --git a/src/fable-compiler-js/.gitignore b/src/fable-compiler-js/.gitignore index d764045219..4cce4fabe9 100644 --- a/src/fable-compiler-js/.gitignore +++ b/src/fable-compiler-js/.gitignore @@ -1,2 +1,3 @@ lib/ -dist/ \ No newline at end of file +dist/ +out/ \ No newline at end of file diff --git a/src/fable-compiler-js/.npmignore b/src/fable-compiler-js/.npmignore index 659626ed76..8168316724 100644 --- a/src/fable-compiler-js/.npmignore +++ b/src/fable-compiler-js/.npmignore @@ -1,4 +1,5 @@ # Override .gitignore to include the `dist` folder src/bin/ src/obj/ -test/ \ No newline at end of file +test/ +out/ \ No newline at end of file diff --git a/src/fable-compiler-js/README.md b/src/fable-compiler-js/README.md index dc400e5675..2cb535442d 100644 --- a/src/fable-compiler-js/README.md +++ b/src/fable-compiler-js/README.md @@ -1,6 +1,6 @@ # fable-compiler-js -[Fable](http://fable.io/) (F# to JS compiler) running entirely on node.js (no dotnet installation required). This version is still **experimental**. For example, packages are not yet supported. +[Fable](http://fable.io/) (F# to JS compiler) running entirely on node.js (no dotnet installation required). This version is somewhat experimental but it's catching up with the official [fable-compiler](https://www.npmjs.com/package/fable-compiler). Since v1.2 Nuget packages are supported. ## Global installation diff --git a/src/fable-compiler-js/RELEASE_NOTES.md b/src/fable-compiler-js/RELEASE_NOTES.md index 5e50274c03..c1fae1bcee 100644 --- a/src/fable-compiler-js/RELEASE_NOTES.md +++ b/src/fable-compiler-js/RELEASE_NOTES.md @@ -1,6 +1,59 @@ +### 1.3.1 + +* Improve globbing support (by @ncave) + +### 1.3.0 + +* Add globbing support in fsproj + +### 1.2.4 + +* fable-metadata 1.4.0 + +### 1.2.3 + +* Update to fable-babel-plugins 2.3.0 + +### 1.2.2 + +* fable-metadata 1.3.0 + +### 1.2.1 + +* fable-standalone 1.3.0 +* Removed perf_hooks dependency +* Added support for source maps + +### 1.2.0 + +* Added NuGet packages support + +### 1.1.1 + +* Update to fable-metadata 1.2.0 & fable-standalone 1.2.3 + +### 1.1.0 + +* fable-standalone 1.2.0 +* Define FABLE_COMPILER_JS constant + +### 1.0.6 + +* fable-standalone 1.1.8 + +### 1.0.5 + +* fable-standalone 1.1.5 + +### 1.0.4 + +* fable-metadata 1.1.2 +* fable-standalone 1.1.4 + ### 1.0.3 -* Update dependencies +* fable-metadata 1.0.1 +* fable-standalone 1.0.3 ### 1.0.2 diff --git a/src/fable-compiler-js/package-lock.json b/src/fable-compiler-js/package-lock.json index 3d8da0271b..874ddf8df2 100644 --- a/src/fable-compiler-js/package-lock.json +++ b/src/fable-compiler-js/package-lock.json @@ -1,179 +1,214 @@ { "name": "fable-compiler-js", - "version": "1.0.3", + "version": "1.3.1", "lockfileVersion": 1, "requires": true, "dependencies": { "@babel/code-frame": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz", - "integrity": "sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.8.3.tgz", + "integrity": "sha512-a9gxpmdXtZEInkCSHUJDLHZVBgb1QS0jhss4cPP93EW7s+uC5bikET2twEF3KV+7rDblJcmNvTR7VJejqd2C2g==", "requires": { - "@babel/highlight": "^7.0.0" + "@babel/highlight": "^7.8.3" } }, "@babel/core": { - "version": "7.3.4", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.3.4.tgz", - "integrity": "sha512-jRsuseXBo9pN197KnDwhhaaBzyZr2oIcLHHTt2oDdQrej5Qp57dCCJafWx5ivU8/alEYDpssYqv1MUqcxwQlrA==", - "requires": { - "@babel/code-frame": "^7.0.0", - "@babel/generator": "^7.3.4", - "@babel/helpers": "^7.2.0", - "@babel/parser": "^7.3.4", - "@babel/template": "^7.2.2", - "@babel/traverse": "^7.3.4", - "@babel/types": "^7.3.4", - "convert-source-map": "^1.1.0", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.9.0.tgz", + "integrity": "sha512-kWc7L0fw1xwvI0zi8OKVBuxRVefwGOrKSQMvrQ3dW+bIIavBY3/NpXmpjMy7bQnLgwgzWQZ8TlM57YHpHNHz4w==", + "requires": { + "@babel/code-frame": "^7.8.3", + "@babel/generator": "^7.9.0", + "@babel/helper-module-transforms": "^7.9.0", + "@babel/helpers": "^7.9.0", + "@babel/parser": "^7.9.0", + "@babel/template": "^7.8.6", + "@babel/traverse": "^7.9.0", + "@babel/types": "^7.9.0", + "convert-source-map": "^1.7.0", "debug": "^4.1.0", - "json5": "^2.1.0", - "lodash": "^4.17.11", + "gensync": "^1.0.0-beta.1", + "json5": "^2.1.2", + "lodash": "^4.17.13", "resolve": "^1.3.2", "semver": "^5.4.1", "source-map": "^0.5.0" } }, "@babel/generator": { - "version": "7.3.4", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.3.4.tgz", - "integrity": "sha512-8EXhHRFqlVVWXPezBW5keTiQi/rJMQTg/Y9uVCEZ0CAF3PKtCCaVRnp64Ii1ujhkoDhhF1fVsImoN4yJ2uz4Wg==", + "version": "7.9.5", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.9.5.tgz", + "integrity": "sha512-GbNIxVB3ZJe3tLeDm1HSn2AhuD/mVcyLDpgtLXa5tplmWrJdF/elxB56XNqCuD6szyNkDi6wuoKXln3QeBmCHQ==", "requires": { - "@babel/types": "^7.3.4", + "@babel/types": "^7.9.5", "jsesc": "^2.5.1", - "lodash": "^4.17.11", - "source-map": "^0.5.0", - "trim-right": "^1.0.1" + "lodash": "^4.17.13", + "source-map": "^0.5.0" } }, "@babel/helper-function-name": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.1.0.tgz", - "integrity": "sha512-A95XEoCpb3TO+KZzJ4S/5uW5fNe26DjBGqf1o9ucyLyCmi1dXq/B3c8iaWTfBk3VvetUxl16e8tIrd5teOCfGw==", + "version": "7.9.5", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.9.5.tgz", + "integrity": "sha512-JVcQZeXM59Cd1qanDUxv9fgJpt3NeKUaqBqUEvfmQ+BCOKq2xUgaWZW2hr0dkbyJgezYuplEoh5knmrnS68efw==", "requires": { - "@babel/helper-get-function-arity": "^7.0.0", - "@babel/template": "^7.1.0", - "@babel/types": "^7.0.0" + "@babel/helper-get-function-arity": "^7.8.3", + "@babel/template": "^7.8.3", + "@babel/types": "^7.9.5" } }, "@babel/helper-get-function-arity": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0.tgz", - "integrity": "sha512-r2DbJeg4svYvt3HOS74U4eWKsUAMRH01Z1ds1zx8KNTPtpTL5JAsdFv8BNyOpVqdFhHkkRDIg5B4AsxmkjAlmQ==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.8.3.tgz", + "integrity": "sha512-FVDR+Gd9iLjUMY1fzE2SR0IuaJToR4RkCDARVfsBBPSP53GEqSFjD8gNyxg246VUyc/ALRxFaAK8rVG7UT7xRA==", + "requires": { + "@babel/types": "^7.8.3" + } + }, + "@babel/helper-member-expression-to-functions": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.8.3.tgz", + "integrity": "sha512-fO4Egq88utkQFjbPrSHGmGLFqmrshs11d46WI+WZDESt7Wu7wN2G2Iu+NMMZJFDOVRHAMIkB5SNh30NtwCA7RA==", "requires": { - "@babel/types": "^7.0.0" + "@babel/types": "^7.8.3" } }, "@babel/helper-module-imports": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.0.0.tgz", - "integrity": "sha512-aP/hlLq01DWNEiDg4Jn23i+CXxW/owM4WpDLFUbpjxe4NS3BhLVZQ5i7E0ZrxuQ/vwekIeciyamgB1UIYxxM6A==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.8.3.tgz", + "integrity": "sha512-R0Bx3jippsbAEtzkpZ/6FIiuzOURPcMjHp+Z6xPe6DtApDJx+w7UYyOLanZqO8+wKR9G10s/FmHXvxaMd9s6Kg==", "requires": { - "@babel/types": "^7.0.0" + "@babel/types": "^7.8.3" } }, "@babel/helper-module-transforms": { - "version": "7.2.2", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.2.2.tgz", - "integrity": "sha512-YRD7I6Wsv+IHuTPkAmAS4HhY0dkPobgLftHp0cRGZSdrRvmZY8rFvae/GVu3bD00qscuvK3WPHB3YdNpBXUqrA==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.9.0.tgz", + "integrity": "sha512-0FvKyu0gpPfIQ8EkxlrAydOWROdHpBmiCiRwLkUiBGhCUPRRbVD2/tm3sFr/c/GWFrQ/ffutGUAnx7V0FzT2wA==", "requires": { - "@babel/helper-module-imports": "^7.0.0", - "@babel/helper-simple-access": "^7.1.0", - "@babel/helper-split-export-declaration": "^7.0.0", - "@babel/template": "^7.2.2", - "@babel/types": "^7.2.2", - "lodash": "^4.17.10" + "@babel/helper-module-imports": "^7.8.3", + "@babel/helper-replace-supers": "^7.8.6", + "@babel/helper-simple-access": "^7.8.3", + "@babel/helper-split-export-declaration": "^7.8.3", + "@babel/template": "^7.8.6", + "@babel/types": "^7.9.0", + "lodash": "^4.17.13" + } + }, + "@babel/helper-optimise-call-expression": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.8.3.tgz", + "integrity": "sha512-Kag20n86cbO2AvHca6EJsvqAd82gc6VMGule4HwebwMlwkpXuVqrNRj6CkCV2sKxgi9MyAUnZVnZ6lJ1/vKhHQ==", + "requires": { + "@babel/types": "^7.8.3" } }, "@babel/helper-plugin-utils": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.0.0.tgz", - "integrity": "sha512-CYAOUCARwExnEixLdB6sDm2dIJ/YgEAKDM1MOeMeZu9Ld/bDgVo8aiWrXwcY7OBh+1Ea2uUcVRcxKk0GJvW7QA==" + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.8.3.tgz", + "integrity": "sha512-j+fq49Xds2smCUNYmEHF9kGNkhbet6yVIBp4e6oeQpH1RUs/Ir06xUKzDjDkGcaaokPiTNs2JBWHjaE4csUkZQ==" + }, + "@babel/helper-replace-supers": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.8.6.tgz", + "integrity": "sha512-PeMArdA4Sv/Wf4zXwBKPqVj7n9UF/xg6slNRtZW84FM7JpE1CbG8B612FyM4cxrf4fMAMGO0kR7voy1ForHHFA==", + "requires": { + "@babel/helper-member-expression-to-functions": "^7.8.3", + "@babel/helper-optimise-call-expression": "^7.8.3", + "@babel/traverse": "^7.8.6", + "@babel/types": "^7.8.6" + } }, "@babel/helper-simple-access": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.1.0.tgz", - "integrity": "sha512-Vk+78hNjRbsiu49zAPALxTb+JUQCz1aolpd8osOF16BGnLtseD21nbHgLPGUwrXEurZgiCOUmvs3ExTu4F5x6w==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.8.3.tgz", + "integrity": "sha512-VNGUDjx5cCWg4vvCTR8qQ7YJYZ+HBjxOgXEl7ounz+4Sn7+LMD3CFrCTEU6/qXKbA2nKg21CwhhBzO0RpRbdCw==", "requires": { - "@babel/template": "^7.1.0", - "@babel/types": "^7.0.0" + "@babel/template": "^7.8.3", + "@babel/types": "^7.8.3" } }, "@babel/helper-split-export-declaration": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.0.0.tgz", - "integrity": "sha512-MXkOJqva62dfC0w85mEf/LucPPS/1+04nmmRMPEBUB++hiiThQ2zPtX/mEWQ3mtzCEjIJvPY8nuwxXtQeQwUag==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.8.3.tgz", + "integrity": "sha512-3x3yOeyBhW851hroze7ElzdkeRXQYQbFIb7gLK1WQYsw2GWDay5gAJNw1sWJ0VFP6z5J1whqeXH/WCdCjZv6dA==", "requires": { - "@babel/types": "^7.0.0" + "@babel/types": "^7.8.3" } }, + "@babel/helper-validator-identifier": { + "version": "7.9.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.9.5.tgz", + "integrity": "sha512-/8arLKUFq882w4tWGj9JYzRpAlZgiWUJ+dtteNTDqrRBz9Iguck9Rn3ykuBDoUwh2TO4tSAJlrxDUOXWklJe4g==" + }, "@babel/helpers": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.3.1.tgz", - "integrity": "sha512-Q82R3jKsVpUV99mgX50gOPCWwco9Ec5Iln/8Vyu4osNIOQgSrd9RFrQeUvmvddFNoLwMyOUWU+5ckioEKpDoGA==", + "version": "7.9.2", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.9.2.tgz", + "integrity": "sha512-JwLvzlXVPjO8eU9c/wF9/zOIN7X6h8DYf7mG4CiFRZRvZNKEF5dQ3H3V+ASkHoIB3mWhatgl5ONhyqHRI6MppA==", "requires": { - "@babel/template": "^7.1.2", - "@babel/traverse": "^7.1.5", - "@babel/types": "^7.3.0" + "@babel/template": "^7.8.3", + "@babel/traverse": "^7.9.0", + "@babel/types": "^7.9.0" } }, "@babel/highlight": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0.tgz", - "integrity": "sha512-UFMC4ZeFC48Tpvj7C8UgLvtkaUuovQX+5xNWrsIoMG8o2z+XFKjKaN9iVmS84dPwVN00W4wPmqvYoZF3EGAsfw==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.9.0.tgz", + "integrity": "sha512-lJZPilxX7Op3Nv/2cvFdnlepPXDxi29wxteT57Q965oc5R9v86ztx0jfxVrTcBk8C2kcPkkDa2Z4T3ZsPPVWsQ==", "requires": { + "@babel/helper-validator-identifier": "^7.9.0", "chalk": "^2.0.0", - "esutils": "^2.0.2", "js-tokens": "^4.0.0" } }, "@babel/parser": { - "version": "7.3.4", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.3.4.tgz", - "integrity": "sha512-tXZCqWtlOOP4wgCp6RjRvLmfuhnqTLy9VHwRochJBCP2nDm27JnnuFEnXFASVyQNHk36jD1tAammsCEEqgscIQ==" + "version": "7.9.4", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.9.4.tgz", + "integrity": "sha512-bC49otXX6N0/VYhgOMh4gnP26E9xnDZK3TmbNpxYzzz9BQLBosQwfyOe9/cXUU3txYhTzLCbcqd5c8y/OmCjHA==" }, "@babel/plugin-transform-modules-commonjs": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.2.0.tgz", - "integrity": "sha512-V6y0uaUQrQPXUrmj+hgnks8va2L0zcZymeU7TtWEgdRLNkceafKXEduv7QzgQAE4lT+suwooG9dC7LFhdRAbVQ==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.9.0.tgz", + "integrity": "sha512-qzlCrLnKqio4SlgJ6FMMLBe4bySNis8DFn1VkGmOcxG9gqEyPIOzeQrA//u0HAKrWpJlpZbZMPB1n/OPa4+n8g==", "requires": { - "@babel/helper-module-transforms": "^7.1.0", - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/helper-simple-access": "^7.1.0" + "@babel/helper-module-transforms": "^7.9.0", + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/helper-simple-access": "^7.8.3", + "babel-plugin-dynamic-import-node": "^2.3.0" } }, "@babel/template": { - "version": "7.2.2", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.2.2.tgz", - "integrity": "sha512-zRL0IMM02AUDwghf5LMSSDEz7sBCO2YnNmpg3uWTZj/v1rcG2BmQUvaGU8GhU8BvfMh1k2KIAYZ7Ji9KXPUg7g==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.8.6.tgz", + "integrity": "sha512-zbMsPMy/v0PWFZEhQJ66bqjhH+z0JgMoBWuikXybgG3Gkd/3t5oQ1Rw2WQhnSrsOmsKXnZOx15tkC4qON/+JPg==", "requires": { - "@babel/code-frame": "^7.0.0", - "@babel/parser": "^7.2.2", - "@babel/types": "^7.2.2" + "@babel/code-frame": "^7.8.3", + "@babel/parser": "^7.8.6", + "@babel/types": "^7.8.6" } }, "@babel/traverse": { - "version": "7.3.4", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.3.4.tgz", - "integrity": "sha512-TvTHKp6471OYEcE/91uWmhR6PrrYywQntCHSaZ8CM8Vmp+pjAusal4nGB2WCCQd0rvI7nOMKn9GnbcvTUz3/ZQ==", - "requires": { - "@babel/code-frame": "^7.0.0", - "@babel/generator": "^7.3.4", - "@babel/helper-function-name": "^7.1.0", - "@babel/helper-split-export-declaration": "^7.0.0", - "@babel/parser": "^7.3.4", - "@babel/types": "^7.3.4", + "version": "7.9.5", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.9.5.tgz", + "integrity": "sha512-c4gH3jsvSuGUezlP6rzSJ6jf8fYjLj3hsMZRx/nX0h+fmHN0w+ekubRrHPqnMec0meycA2nwCsJ7dC8IPem2FQ==", + "requires": { + "@babel/code-frame": "^7.8.3", + "@babel/generator": "^7.9.5", + "@babel/helper-function-name": "^7.9.5", + "@babel/helper-split-export-declaration": "^7.8.3", + "@babel/parser": "^7.9.0", + "@babel/types": "^7.9.5", "debug": "^4.1.0", "globals": "^11.1.0", - "lodash": "^4.17.11" + "lodash": "^4.17.13" } }, "@babel/types": { - "version": "7.3.4", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.3.4.tgz", - "integrity": "sha512-WEkp8MsLftM7O/ty580wAmZzN1nDmCACc5+jFzUt+GUFNNIi3LdRlueYz0YIlmJhlZx1QYDMZL5vdWCL0fNjFQ==", + "version": "7.9.5", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.9.5.tgz", + "integrity": "sha512-XjnvNqenk818r5zMaba+sLQjnbda31UfUURv3ei0qPQw4u+j2jMyJ5b11y8ZHYTRSI3NnInQkkkRT4fLqqPdHg==", "requires": { - "esutils": "^2.0.2", - "lodash": "^4.17.11", + "@babel/helper-validator-identifier": "^7.9.5", + "lodash": "^4.17.13", "to-fast-properties": "^2.0.0" } }, @@ -185,6 +220,28 @@ "color-convert": "^1.9.0" } }, + "babel-plugin-dynamic-import-node": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/babel-plugin-dynamic-import-node/-/babel-plugin-dynamic-import-node-2.3.0.tgz", + "integrity": "sha512-o6qFkpeQEBxcqt0XYlWzAVxNCSCZdUgcR8IRlhD/8DylxjjO4foPcvTW0GGKa/cVt3rvxZ7o5ippJ+/0nvLhlQ==", + "requires": { + "object.assign": "^4.1.0" + } + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, "chalk": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", @@ -208,10 +265,15 @@ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, "convert-source-map": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.6.0.tgz", - "integrity": "sha512-eFu7XigvxdZ1ETfbgPBohgyQ/Z++C0eEhTor0qRwBw9unw+L0/6V8wkSuGgzdThkiS5lSpdptOQPD8Ak40a+7A==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.7.0.tgz", + "integrity": "sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA==", "requires": { "safe-buffer": "~5.1.1" } @@ -224,41 +286,91 @@ "ms": "^2.1.1" } }, + "define-properties": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", + "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", + "requires": { + "object-keys": "^1.0.12" + } + }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" }, - "esutils": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", - "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=" - }, "fable-babel-plugins": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fable-babel-plugins/-/fable-babel-plugins-2.1.0.tgz", - "integrity": "sha512-5ZUVrlflbvgA3saIyGJhB1ANqoyZ8UJo12iYSROivql1x9PfKjv16pteNoDFCe6UC1Tn+HaQX46BxyllzLsBTw==" + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/fable-babel-plugins/-/fable-babel-plugins-2.3.0.tgz", + "integrity": "sha512-alGBNw5HZJzTEznXKfypFEkD5aWsspbCcoVDu9j8Mqdi77dgp4BSjhYSg61mQEg9UluIAZxRM5lhGARYbU97DQ==" }, "fable-metadata": { - "version": "1.0.0-beta-002", - "resolved": "https://registry.npmjs.org/fable-metadata/-/fable-metadata-1.0.0-beta-002.tgz", - "integrity": "sha512-PVDgurXItCEYLjzJAQRls/e5mfXsPbo7LrGIj5m2Iy8gztQMXHI4i1Tc3rY+kLAcLd9wgMGgaMBxAbahwQclWA==" + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/fable-metadata/-/fable-metadata-1.4.0.tgz", + "integrity": "sha512-8r/jLuCTAS2KqHb3vdGZCpOba8CNpR8p8uYmfD59np/LWK2/KST7OOv7t2vkSgc0tnbMUsh1FhW1MTgcpvz4eQ==" }, "fable-standalone": { - "version": "1.0.0-beta-009", - "resolved": "https://registry.npmjs.org/fable-standalone/-/fable-standalone-1.0.0-beta-009.tgz", - "integrity": "sha512-UOFe90YDKhX0RmHhnqbRH63NrxKT1NRCy1XQL7LqWc7ponKdd77GwmVN3Ymb3n3oNdTN0GQ+QxOwBKiVstC0YA==" + "version": "1.3.10", + "resolved": "https://registry.npmjs.org/fable-standalone/-/fable-standalone-1.3.10.tgz", + "integrity": "sha512-ooCdO7CinjlrO6+guFi1yiLQxgOhc/aCbRCXRUGIWV9EWZEWVY2vG3I8bFtEnNUMnAzq6rbYNtjPjUxErIGCaQ==" + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "gensync": { + "version": "1.0.0-beta.1", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.1.tgz", + "integrity": "sha512-r8EC6NO1sngH/zdD9fiRDLdcgnbayXah+mLgManTaIZJqEC1MZstmnox8KpnI2/fxQwrp5OpCOYWLp4rBl4Jcg==" + }, + "glob": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } }, "globals": { - "version": "11.11.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.11.0.tgz", - "integrity": "sha512-WHq43gS+6ufNOEqlrDBxVEbb8ntfXrfAUU2ZOpCxrBdGKW3gyv8mCxAfIBD0DroPKGrJ2eSsXsLtY9MPntsyTw==" + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==" }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" }, + "has-symbols": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", + "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==" + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, "js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -270,27 +382,64 @@ "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==" }, "json5": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.0.tgz", - "integrity": "sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.3.tgz", + "integrity": "sha512-KXPvOm8K9IJKFM0bmdn8QXh7udDh1g/giieX0NLCaMnb4hEiVFqnop2ImTXCc5e0/oHz3LTqmHGtExn5hfMkOA==", "requires": { - "minimist": "^1.2.0" + "minimist": "^1.2.5" } }, "lodash": { - "version": "4.17.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==" + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "requires": { + "brace-expansion": "^1.1.7" + } }, "minimist": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=" + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" }, "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==" + }, + "object.assign": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.0.tgz", + "integrity": "sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w==", + "requires": { + "define-properties": "^1.1.2", + "function-bind": "^1.1.1", + "has-symbols": "^1.0.0", + "object-keys": "^1.0.11" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "requires": { + "wrappy": "1" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" }, "path-parse": { "version": "1.0.6", @@ -298,9 +447,9 @@ "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==" }, "resolve": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.10.0.tgz", - "integrity": "sha512-3sUr9aq5OfSg2S9pNtPA9hL1FVEAjvfOC4leW0SNf/mpnaakz2a9femSd6LqAww2RaFctwyf1lCqnTHuF1rxDg==", + "version": "1.15.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.15.1.tgz", + "integrity": "sha512-84oo6ZTtoTUpjgNEr5SJyzQhzL72gaRodsSfyxC/AXRvwu0Yse9H8eF9IpGo7b8YetZhlI6v7ZQ6bKBFV/6S7w==", "requires": { "path-parse": "^1.0.6" } @@ -311,9 +460,9 @@ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" }, "semver": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.6.0.tgz", - "integrity": "sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==" + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" }, "source-map": { "version": "0.5.7", @@ -333,10 +482,10 @@ "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=" }, - "trim-right": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", - "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=" + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" } } } diff --git a/src/fable-compiler-js/package.json b/src/fable-compiler-js/package.json index 62e50de235..ceb9cfb1e3 100644 --- a/src/fable-compiler-js/package.json +++ b/src/fable-compiler-js/package.json @@ -1,6 +1,6 @@ { "name": "fable-compiler-js", - "version": "1.0.3", + "version": "1.3.1", "main": "index.js", "bin": { "fable": "index.js" @@ -22,10 +22,11 @@ }, "homepage": "https://github.com/fable-compiler/Fable#readme", "dependencies": { - "@babel/core": "^7.4.3", - "@babel/plugin-transform-modules-commonjs": "^7.4.3", - "fable-babel-plugins": "^2.2.0", - "fable-metadata": "^1.0.1", - "fable-standalone": "^1.0.3" + "@babel/core": "^7.9.0", + "@babel/plugin-transform-modules-commonjs": "^7.9.0", + "fable-babel-plugins": "^2.3.0", + "fable-metadata": "^1.4.0", + "fable-standalone": "^1.3.10", + "glob": "^7.1.6" } } diff --git a/src/fable-compiler-js/splitter.config.js b/src/fable-compiler-js/splitter.config.js index 5757ba7324..b0033f92bc 100644 --- a/src/fable-compiler-js/splitter.config.js +++ b/src/fable-compiler-js/splitter.config.js @@ -1,17 +1,7 @@ -const path = require("path"); - -const testLocal = process.argv.find(v => v === "--test-local"); -if (testLocal) { - console.log("Using local fable-standalone and fable-metadata...") -} +const resolve = (path) => require("path").join(__dirname, path); module.exports = { - entry: path.join(__dirname, "./src/fable-compiler-js.fsproj"), - outDir: path.join(__dirname, "./dist"), - babel: { - plugins: ["@babel/plugin-transform-modules-commonjs"], - }, - fable: { - define: testLocal ? ["TEST_LOCAL"] : [] - } + cli: { path: resolve("../Fable.Cli") }, + entry: resolve("./src/fable-compiler-js.fsproj"), + outDir: resolve("../../build/fable-compiler-js/out"), }; diff --git a/src/fable-compiler-js/src/Glob.fs b/src/fable-compiler-js/src/Glob.fs new file mode 100644 index 0000000000..0514d01e4d --- /dev/null +++ b/src/fable-compiler-js/src/Glob.fs @@ -0,0 +1,10 @@ +module rec Glob + +// Really minimal bindings for node-glob + +open Fable.Core + +let [] glob: IExports = jsNative + +type [] IExports = + abstract sync: pattern: string * ?options: obj -> array diff --git a/src/fable-compiler-js/src/Platform.fs b/src/fable-compiler-js/src/Platform.fs index a340d4881a..edb85f2f45 100644 --- a/src/fable-compiler-js/src/Platform.fs +++ b/src/fable-compiler-js/src/Platform.fs @@ -2,12 +2,25 @@ module Fable.Compiler.Platform open Fable.Core.JsInterop +type CmdLineOptions = { + commonjs: bool + optimize: bool + watchMode: bool + sourceMaps: bool +} + module JS = type IFileSystem = abstract readFileSync: string -> byte[] abstract readFileSync: string * string -> string abstract writeFileSync: string * string -> unit + type IOperSystem = + abstract homedir: unit -> string + abstract tmpdir: unit -> string + abstract platform: unit -> string + abstract arch: unit -> string + type IProcess = abstract hrtime: unit -> float [] abstract hrtime: float[] -> float[] @@ -20,35 +33,47 @@ module JS = abstract getVersion: unit -> string abstract ensureDirExists: dir: string -> unit abstract copyFolder: from: string * dest: string -> unit - abstract transformAndSaveBabelAst: babelAst: obj * outPath: string * projDir: string * outDir: string * libDir: string * commonjs: bool -> unit + abstract transformAndSaveBabelAst: babelAst: obj * outPath: string * projDir: string * outDir: string * libDir: string * options: CmdLineOptions -> unit abstract runCmdAndExitIfFails: cmd: string -> unit + abstract getDirFiles: dir: string -> string[] - let FileSystem: IFileSystem = importAll "fs" - let Process: IProcess = importAll "process" - let Path: IPath = importAll "path" - let Util: IUtil = importAll "./util.js" + let fs: IFileSystem = importAll "fs" + let os: IOperSystem = importAll "os" + let proc: IProcess = importAll "process" + let path: IPath = importAll "path" + let util: IUtil = importAll "./util.js" -let readAllBytes (filePath: string) = JS.FileSystem.readFileSync(filePath) -let readAllText (filePath: string) = JS.FileSystem.readFileSync(filePath, "utf8").TrimStart('\uFEFF') -let writeAllText (filePath: string) (text: string) = JS.FileSystem.writeFileSync(filePath, text) +let readAllBytes (filePath: string) = JS.fs.readFileSync(filePath) +let readAllText (filePath: string) = JS.fs.readFileSync(filePath, "utf8").TrimStart('\uFEFF') +let writeAllText (filePath: string) (text: string) = JS.fs.writeFileSync(filePath, text) let measureTime (f: 'a -> 'b) x = - let startTime = JS.Process.hrtime() + let startTime = JS.proc.hrtime() let res = f x - let elapsed = JS.Process.hrtime(startTime) - int64 (elapsed.[0] * 1e3 + elapsed.[1] / 1e6), res + let elapsed = JS.proc.hrtime(startTime) + res, int64 (elapsed.[0] * 1e3 + elapsed.[1] / 1e6) -let getVersion = JS.Util.getVersion -let ensureDirExists = JS.Util.ensureDirExists -let copyFolder = JS.Util.copyFolder -let transformAndSaveBabelAst = JS.Util.transformAndSaveBabelAst -let runCmdAndExitIfFails = JS.Util.runCmdAndExitIfFails +let getVersion = JS.util.getVersion +let ensureDirExists = JS.util.ensureDirExists +let copyFolder = JS.util.copyFolder +let transformAndSaveBabelAst = JS.util.transformAndSaveBabelAst +let runCmdAndExitIfFails = JS.util.runCmdAndExitIfFails let normalizeFullPath (path: string) = - JS.Path.resolve(path).Replace('\\', '/') + JS.path.resolve(path).Replace('\\', '/') + +let getRelativePath (path: string) (pathTo: string) = + JS.path.relative(path, pathTo).Replace('\\', '/') + +let getHomePath () = + JS.os.homedir() + +let getDirFiles (path: string) (extension: string) = + JS.util.getDirFiles(path) + |> Array.filter (fun x -> x.EndsWith(extension)) + |> Array.map (fun x -> x.Replace('\\', '/')) + |> Array.sort -let getRelativePath (pathFrom: string) (pathTo: string) = - JS.Path.relative(pathFrom, pathTo).Replace('\\', '/') module Path = @@ -58,18 +83,23 @@ module Path = else (path1.TrimEnd [|'\\';'/'|]) + "/" path1 + (path2.TrimStart [|'\\';'/'|]) + let ChangeExtension (path: string, ext: string) = + let i = path.LastIndexOf(".") + if i < 0 then path + else path.Substring(0, i) + ext + let GetFileName (path: string) = - let normPath = path.Replace("\\", "/").TrimEnd('/') - let i = normPath.LastIndexOf("/") + let normPath = path.Replace('\\', '/').TrimEnd('/') + let i = normPath.LastIndexOf('/') normPath.Substring(i + 1) let GetFileNameWithoutExtension (path: string) = let path = GetFileName path - let i = path.LastIndexOf(".") + let i = path.LastIndexOf('.') path.Substring(0, i) let GetDirectoryName (path: string) = - let normPath = path.Replace("\\", "/") - let i = normPath.LastIndexOf("/") + let normPath = path.Replace('\\', '/') + let i = normPath.LastIndexOf('/') if i < 0 then "" else normPath.Substring(0, i) diff --git a/src/fable-compiler-js/src/ProjectParser.fs b/src/fable-compiler-js/src/ProjectParser.fs index 20a4e05342..46bee13381 100644 --- a/src/fable-compiler-js/src/ProjectParser.fs +++ b/src/fable-compiler-js/src/ProjectParser.fs @@ -3,35 +3,99 @@ module Fable.Compiler.ProjectParser open Fable.Compiler.Platform open System.Collections.Generic open System.Text.RegularExpressions +open Fable.Core +open Fable.Core.JsInterop + +type ReferenceType = + | ProjectReference of string + | PackageReference of string * string let (|Regex|_|) (pattern: string) (input: string) = let m = Regex.Match(input, pattern) - if m.Success then - let mutable groups = [] - for i = m.Groups.Count - 1 downto 0 do - groups <- m.Groups.[i].Value::groups - Some groups + if m.Success then Some [for x in m.Groups -> x.Value] else None -let parseCompilerOptions projectText = +let getXmlWithoutComments xml = + Regex.Replace(xml, @"", "") + +let getXmlTagContents tag xml = + let pattern = sprintf @"<%s[^>]*>([^<]*)<\/%s[^>]*>" tag tag + Regex.Matches(xml, pattern) + |> Seq.map (fun m -> m.Groups.[1].Value.Trim()) + +let getXmlTagContentsFirstOrDefault tag defaultValue xml = + defaultArg (getXmlTagContents tag xml |> Seq.tryHead) defaultValue + +let getXmlTagAttributes1 tag attr1 xml = + let pattern = sprintf """<%s\s+[^>]*%s\s*=\s*("[^"]*|'[^']*)""" tag attr1 + Regex.Matches(xml, pattern) + |> Seq.map (fun m -> m.Groups.[1].Value.TrimStart('"').TrimStart(''').Trim()) - // get project type - let m = Regex.Match(projectText, @"]*>([^<]*)<\/OutputType[^>]*>") - let target = if m.Success then m.Groups.[1].Value.Trim().ToLowerInvariant() else "" +let getXmlTagAttributes2 tag attr1 attr2 xml = + let pattern = sprintf """<%s\s+[^>]*%s\s*=\s*("[^"]*|'[^']*)[^>]*%s\s*=\s*("[^"]*|'[^']*)""" tag attr1 attr2 + Regex.Matches(xml, pattern) + |> Seq.map (fun m -> + m.Groups.[1].Value.TrimStart('"').TrimStart(''').Trim(), + m.Groups.[2].Value.TrimStart('"').TrimStart(''').Trim()) + +let isSystemPackage (pkgName: string) = + pkgName.StartsWith("System.") + || pkgName.StartsWith("Microsoft.") + || pkgName.StartsWith("runtime.") + || pkgName = "NETStandard.Library" + || pkgName = "FSharp.Core" + || pkgName = "Fable.Core" + +let parsePackageSpec nuspecPath = + // get package spec xml + let packageXml = readAllText nuspecPath + // get package dependencies + let references = + packageXml + |> getXmlWithoutComments + |> getXmlTagAttributes2 "dependency" "id" "version" + |> Seq.map PackageReference + |> Seq.toArray + references - // get warning level - let m = Regex.Match(projectText, @"]*>([^<]*)<\/WarningLevel[^>]*>") - let warnLevel = if m.Success then m.Groups.[1].Value.Trim() else "" +let resolvePackage (pkgName, pkgVersion) = + if not (isSystemPackage pkgName) then + let homePath = getHomePath().Replace('\\', '/') + let nugetPath = sprintf ".nuget/packages/%s/%s" pkgName pkgVersion + let pkgPath = Path.Combine(homePath, nugetPath.ToLowerInvariant()) + let libPath = Path.Combine(pkgPath, "lib") + let fablePath = Path.Combine(pkgPath, "fable") + let binaryPaths = getDirFiles libPath ".dll" + let nuspecPaths = getDirFiles pkgPath ".nuspec" + let fsprojPaths = getDirFiles fablePath ".fsproj" + if Array.isEmpty nuspecPaths then + printfn "ERROR: Cannot find package %s" pkgPath + let binaryOpt = binaryPaths |> Array.tryLast + let dependOpt = nuspecPaths |> Array.tryLast |> Option.map parsePackageSpec + let fsprojOpt = fsprojPaths |> Array.tryLast |> Option.map ProjectReference + let pkgRefs, dllPaths = + match binaryOpt, dependOpt, fsprojOpt with + | _, _, Some projRef -> + [| projRef |], [||] + | Some dllRef, Some dependencies, _ -> + dependencies, [| dllRef |] + | _, _, _ -> [||], [||] + pkgRefs, dllPaths + else [||], [||] - // get treat warnings as errors - let m = Regex.Match(projectText, @"]*>([^<]*)<\/TreatWarningsAsErrors[^>]*>") - let treatWarningsAsErrors = m.Success && m.Groups.[1].Value.Trim().ToLowerInvariant() = "true" +let parseCompilerOptions projectXml = + // get project settings, + let target = projectXml |> getXmlTagContentsFirstOrDefault "OutputType" "" + let langVersion = projectXml |> getXmlTagContentsFirstOrDefault "LangVersion" "" + let warnLevel = projectXml |> getXmlTagContentsFirstOrDefault "WarningLevel" "" + let treatWarningsAsErrors = projectXml |> getXmlTagContentsFirstOrDefault "TreatWarningsAsErrors" "" // get conditional defines let defines = - Regex.Matches(projectText, @"]*>([^<]*)<\/DefineConstants[^>]*>") - |> Seq.collect (fun m -> m.Groups.[1].Value.Split(';')) - |> Seq.append ["FABLE_COMPILER"] + projectXml + |> getXmlTagContents "DefineConstants" + |> Seq.collect (fun s -> s.Split(';')) + |> Seq.append ["FABLE_COMPILER"; "FABLE_COMPILER_JS"] |> Seq.map (fun s -> s.Trim()) |> Seq.distinct |> Seq.except ["$(DefineConstants)"; ""] @@ -39,8 +103,9 @@ let parseCompilerOptions projectText = // get disabled warnings let nowarns = - Regex.Matches(projectText, @"]*>([^<]*)<\/NoWarn[^>]*>") - |> Seq.collect (fun m -> m.Groups.[1].Value.Split(';')) + projectXml + |> getXmlTagContents "NoWarn" + |> Seq.collect (fun s -> s.Split(';')) |> Seq.map (fun s -> s.Trim()) |> Seq.distinct |> Seq.except ["$(NoWarn)"; ""] @@ -48,8 +113,9 @@ let parseCompilerOptions projectText = // get warnings as errors let warnAsErrors = - Regex.Matches(projectText, @"]*>([^<]*)<\/WarningsAsErrors[^>]*>") - |> Seq.collect (fun m -> m.Groups.[1].Value.Split(';')) + projectXml + |> getXmlTagContents "WarningsAsErrors" + |> Seq.collect (fun s -> s.Split(';')) |> Seq.map (fun s -> s.Trim()) |> Seq.distinct |> Seq.except ["$(WarningsAsErrors)"; ""] @@ -57,8 +123,9 @@ let parseCompilerOptions projectText = // get other flags let otherFlags = - Regex.Matches(projectText, @"]*>([^<]*)<\/OtherFlags[^>]*>") - |> Seq.collect (fun m -> m.Groups.[1].Value.Split(' ')) + projectXml + |> getXmlTagContents "OtherFlags" + |> Seq.collect (fun s -> s.Split(' ')) |> Seq.map (fun s -> s.Trim()) |> Seq.distinct |> Seq.except ["$(OtherFlags)"; ""] @@ -67,9 +134,11 @@ let parseCompilerOptions projectText = let otherOptions = [| if target.Length > 0 then yield "--target:" + target + if langVersion.Length > 0 then + yield "--langversion:" + langVersion if warnLevel.Length > 0 then yield "--warn:" + warnLevel - if treatWarningsAsErrors then + if treatWarningsAsErrors = "true" then yield "--warnaserror+" for d in defines do yield "-d:" + d for n in nowarns do yield "--nowarn:" + n @@ -78,55 +147,73 @@ let parseCompilerOptions projectText = |] otherOptions -let parseProjectScript projectPath = - let projectFileName = Path.GetFileName projectPath - let projectText = readAllText projectPath - let projectDir = Path.GetDirectoryName projectPath +let makeFullPath projectFileDir (path: string) = + let path = path.Replace('\\', '/') + let isAbsolutePath (path: string) = + path.StartsWith('/') || path.IndexOf(':') = 1 + if isAbsolutePath path then path + else Path.Combine(projectFileDir, path) + |> normalizeFullPath + +let parseProjectScript projectFilePath = + let projectXml = readAllText projectFilePath + let projectDir = Path.GetDirectoryName projectFilePath let dllRefs, srcFiles = - (([||], [||]), projectText.Split('\n')) + (([||], [||]), projectXml.Split('\n')) ||> Array.fold (fun (dllRefs, srcFiles) line -> - let line = line.Trim() match line.Trim() with | Regex @"^#r\s+""(.*?)""$" [_;path] when not(path.EndsWith("Fable.Core.dll")) -> - Array.append [|Path.Combine(projectDir, path)|] dllRefs, srcFiles + Array.append [| Path.Combine(projectDir, path) |] dllRefs, srcFiles | Regex @"^#load\s+""(.*?)""$" [_;path] -> - dllRefs, Array.append [|Path.Combine(projectDir, path)|] srcFiles + dllRefs, Array.append [| Path.Combine(projectDir, path) |] srcFiles | _ -> dllRefs, srcFiles) let projectRefs = [||] - let sourceFiles = Array.append srcFiles [|Path.GetFileName projectPath|] - let otherOptions = [| "--define:FABLE_COMPILER" |] - (projectFileName, dllRefs, projectRefs, sourceFiles, otherOptions) + let sourceFiles = Array.append srcFiles [| Path.GetFileName projectFilePath |] + let otherOptions = [| "--define:FABLE_COMPILER"; "--define:FABLE_COMPILER_JS" |] + (projectRefs, dllRefs, sourceFiles, otherOptions) -let parseProjectFile projectPath = - let projectFileName = Path.GetFileName projectPath - let projectText = readAllText projectPath +let parseProjectFile projectFilePath = + // get project xml without any comments + let projectXml = readAllText projectFilePath |> getXmlWithoutComments + let projectDir = Path.GetDirectoryName projectFilePath - // remove all comments - let projectText = Regex.Replace(projectText, @"", "") + // get package references + let packageRefs = + projectXml + |> getXmlTagAttributes2 "PackageReference" "Include" "Version" + |> Seq.map PackageReference + |> Seq.toArray // get project references let projectRefs = - Regex.Matches(projectText, @"]*Include\s*=\s*(""[^""]*|'[^']*)") - |> Seq.map (fun m -> m.Groups.[1].Value.TrimStart('"').TrimStart(''').Trim().Replace("\\", "/")) + projectXml + |> getXmlTagAttributes1 "ProjectReference" "Include" + |> Seq.map (makeFullPath projectDir >> ProjectReference) |> Seq.toArray // replace some variables - let projectText = projectText.Replace(@"$(MSBuildProjectDirectory)", ".") - let m = Regex.Match(projectText, @"]*>([^<]*)<\/FSharpSourcesRoot[^>]*>") - let sourcesRoot = if m.Success then m.Groups.[1].Value.Replace("\\", "/") else "" - let projectText = projectText.Replace(@"$(FSharpSourcesRoot)", sourcesRoot) + let projectXml = projectXml.Replace("$(MSBuildProjectDirectory)", ".") + let sourceRoot = projectXml |> getXmlTagContentsFirstOrDefault "FSharpSourcesRoot" "" + let projectXml = projectXml.Replace("$(FSharpSourcesRoot)", sourceRoot.Replace('\\', '/')) // get source files - let sourceFilesRegex = @"]*Include\s*=\s*(""[^""]*|'[^']*)" let sourceFiles = - Regex.Matches(projectText, sourceFilesRegex) - |> Seq.map (fun m -> m.Groups.[1].Value.TrimStart('"').TrimStart(''').Trim().Replace("\\", "/")) + projectXml + |> getXmlTagAttributes1 "Compile" "Include" + |> Seq.map (makeFullPath projectDir) + |> Seq.collect (fun path -> + if (path.Contains("*") || path.Contains("?")) then + Glob.glob.sync(path) + else + [| path |] + ) |> Seq.toArray let dllRefs = [||] - let otherOptions = parseCompilerOptions projectText - (projectFileName, dllRefs, projectRefs, sourceFiles, otherOptions) + let projectRefs = Array.append projectRefs packageRefs + let otherOptions = parseCompilerOptions projectXml + (projectRefs, dllRefs, sourceFiles, otherOptions) let makeHashSetIgnoreCase () = let equalityComparerIgnoreCase = @@ -135,45 +222,38 @@ let makeHashSetIgnoreCase () = member __.GetHashCode(x) = hash (x.ToLowerInvariant()) } HashSet(equalityComparerIgnoreCase) -let dedupProjectRefs (projSet: HashSet) projectRefs = - let newRefs = projectRefs |> Array.filter (fun x -> projSet.Contains(x) |> not) - projSet.UnionWith(newRefs) +let dedupReferences (refSet: HashSet) references = + let refName = function + | ProjectReference path -> path + | PackageReference (pkgName, pkgVersion) -> pkgName + "," + pkgVersion + let newRefs = references |> Array.filter (refName >> refSet.Contains >> not) + refSet.UnionWith(newRefs |> Array.map refName) newRefs -let dedupFileNames (fileSet: HashSet) fileNames = - let padName (fileName: string) = - let pos = fileName.LastIndexOf(".") - let nm = if pos < 0 then fileName else fileName.Substring(0, pos) - let ext = if pos < 0 then "" else fileName.Substring(pos) - nm + "_" + ext - let rec dedup fileName = - if fileSet.Contains(fileName) then - dedup (padName fileName) - else - fileSet.Add(fileName) |> ignore - fileName - fileNames |> Array.map dedup - -let rec parseProject (projSet: HashSet) (projectPath: string) = - let (projectFileName, dllRefs, projectRefs, sourceFiles, otherOptions) = - if projectPath.EndsWith(".fsx") - then parseProjectScript projectPath - else parseProjectFile projectPath - - let projectFileDir = Path.GetDirectoryName projectPath - let isAbsolutePath (path: string) = path.StartsWith("/") || path.IndexOf(":") = 1 - let makePath path = - if isAbsolutePath path then path - else Path.Combine(projectFileDir, path) - |> normalizeFullPath - - let sourcePaths = sourceFiles |> Array.map makePath - let sourceTexts = sourcePaths |> Array.map readAllText - - // parse and combine all referenced projects into one big project - let parsedProjects = projectRefs |> Array.map makePath |> dedupProjectRefs projSet |> Array.map (parseProject projSet) - let sourcePaths = sourcePaths |> Array.append (parsedProjects |> Array.collect (fun (_,_,x,_,_) -> x)) - let sourceTexts = sourceTexts |> Array.append (parsedProjects |> Array.collect (fun (_,_,_,x,_) -> x)) - let otherOptions = otherOptions |> Array.append (parsedProjects |> Array.collect (fun (_,_,_,_,x) -> x)) - - (projectFileName, dllRefs, sourcePaths, sourceTexts, otherOptions |> Array.distinct) +let parseProject projectFilePath = + + let rec parseProject (refSet: HashSet) (projectRef: ReferenceType) = + let projectRefs, dllPaths, sourcePaths, otherOptions = + match projectRef with + | ProjectReference path -> + if path.EndsWith(".fsx") + then parseProjectScript path + else parseProjectFile path + | PackageReference (pkgName, pkgVersion) -> + let pkgRefs, dllPaths = resolvePackage (pkgName, pkgVersion) + pkgRefs, dllPaths, [||], [||] + + // parse and combine all referenced projects into one big project + let parseResult = projectRefs |> dedupReferences refSet |> Array.map (parseProject refSet) + let dllPaths = dllPaths |> Array.append (parseResult |> Array.collect (fun (x,_,_) -> x)) + let sourcePaths = sourcePaths |> Array.append (parseResult |> Array.collect (fun (_,x,_) -> x)) + let otherOptions = otherOptions |> Array.append (parseResult |> Array.collect (fun (_,_,x) -> x)) + + (dllPaths, sourcePaths, otherOptions) + + let refSet = makeHashSetIgnoreCase () + let projectRef = ProjectReference projectFilePath + let dllPaths, sourcePaths, otherOptions = parseProject refSet projectRef + (dllPaths |> Array.distinct, + sourcePaths |> Array.distinct, + otherOptions |> Array.distinct) diff --git a/src/fable-compiler-js/src/app.fs b/src/fable-compiler-js/src/app.fs index 3dd57634ec..7067618e2e 100644 --- a/src/fable-compiler-js/src/app.fs +++ b/src/fable-compiler-js/src/app.fs @@ -5,16 +5,9 @@ open Fable.Compiler.ProjectParser open Fable.Core open Fable.Core.JsInterop -#if TEST_LOCAL -let [] __dirname: string = jsNative -let initFable (): Fable.Standalone.IFableManager = import "init" "${entryDir}../../fable-standalone" -let getMetadataDir(): string = __dirname + "/" + "${entryDir}../../fable-metadata/lib" -let getFableLibDir(): string = __dirname + "/" + "${entryDir}../../../build/fable-library" -#else let initFable (): Fable.Standalone.IFableManager = import "init" "fable-standalone" let getMetadataDir(): string = importDefault "fable-metadata" let getFableLibDir(): string = importMember "./util.js" -#endif let references = Fable.Standalone.Metadata.references_core let metadataPath = getMetadataDir().TrimEnd('\\', '/') + "/" // .NET BCL binaries (metadata) @@ -22,8 +15,7 @@ let metadataPath = getMetadataDir().TrimEnd('\\', '/') + "/" // .NET BCL binarie let printErrors showWarnings (errors: Fable.Standalone.Error[]) = let printError (e: Fable.Standalone.Error) = let errorType = (if e.IsWarning then "Warning" else "Error") - printfn "%s (%d,%d--%d,%d): %s: %s" e.FileName e.EndLineAlternate - e.StartColumn e.EndLineAlternate e.EndColumn errorType e.Message + printfn "%s (%d,%d): %s: %s" e.FileName e.StartLineAlternate e.StartColumn errorType e.Message let warnings, errors = errors |> Array.partition (fun e -> e.IsWarning) let hasErrors = not (Array.isEmpty errors) if showWarnings then @@ -32,24 +24,16 @@ let printErrors showWarnings (errors: Fable.Standalone.Error[]) = errors |> Array.iter printError failwith "Too many errors." -type CmdLineOptions = { - commonjs: bool - optimize: bool - watchMode: bool -} - -let parseFiles projectPath outDir options = +let parseFiles projectFileName outDir options = // parse project - let projSet = makeHashSetIgnoreCase () - let (projectFileName, dllRefs, fileNames, sources, otherOptions) = parseProject projSet projectPath - - // dedup file names - let fileSet = makeHashSetIgnoreCase () - let fileNames = dedupFileNames fileSet fileNames - - // find reference dlls - let dllRefMap = dllRefs |> Seq.map (fun x -> Path.GetFileName x, x) |> Map - let references = dllRefs |> Array.map Path.GetFileNameWithoutExtension |> Array.append references + let (dllRefs, fileNames, otherOptions) = parseProject projectFileName + let sources = fileNames |> Array.map readAllText + let nugetPath = Path.Combine(getHomePath().Replace('\\', '/'), ".nuget") + let fileNames = fileNames |> Array.map (fun x -> x.Replace(nugetPath, "")) + + // find referenced dlls + let dllRefMap = dllRefs |> Array.rev |> Array.map (fun x -> Path.GetFileName x, x) |> Map + let references = Map.toArray dllRefMap |> Array.map fst |> Array.append references let findDllPath dllName = Map.tryFind dllName dllRefMap |> Option.defaultValue (metadataPath + dllName) let readAllBytes dllName = findDllPath dllName |> readAllBytes @@ -58,14 +42,14 @@ let parseFiles projectPath outDir options = let optimizeFlag = "--optimize" + (if options.optimize then "+" else "-") let otherOptions = otherOptions |> Array.append [| optimizeFlag |] let createChecker () = fable.CreateChecker(references, readAllBytes, otherOptions) - let ms0, checker = measureTime createChecker () + let checker, ms0 = measureTime createChecker () printfn "fable-compiler-js v%s" (getVersion()) printfn "--------------------------------------------" printfn "InteractiveChecker created in %d ms" ms0 // parse F# files to AST let parseFSharpProject () = fable.ParseFSharpProject(checker, projectFileName, fileNames, sources) - let ms1, parseRes = measureTime parseFSharpProject () + let parseRes, ms1 = measureTime parseFSharpProject () printfn "Project: %s, FCS time: %d ms" projectFileName ms1 printfn "--------------------------------------------" let showWarnings = true @@ -80,34 +64,35 @@ let parseFiles projectPath outDir options = // Fable (F# to Babel) let fableLibraryDir = "fable-library" - let parseFable (res, fileName) = fable.CompileToBabelAst(fableLibraryDir, res, fileName, options.optimize) + let parseFable (res, fileName) = fable.CompileToBabelAst(fableLibraryDir, res, fileName) let trimPath (path: string) = path.Replace("../", "").Replace("./", "").Replace(":", "") - let projDir = projectPath |> normalizeFullPath |> Path.GetDirectoryName + let projDir = projectFileName |> normalizeFullPath |> Path.GetDirectoryName let libDir = getFableLibDir() |> normalizeFullPath for fileName in fileNames do // transform F# AST to Babel AST - let ms2, res = measureTime parseFable (parseRes, fileName) + let res, ms2 = measureTime parseFable (parseRes, fileName) printfn "File: %s, Fable time: %d ms" fileName ms2 res.FableErrors |> printErrors showWarnings // transform and save Babel AST let outPath = getRelativePath projDir fileName |> trimPath - transformAndSaveBabelAst(res.BabelAst, outPath, projDir, outDir, libDir, options.commonjs) + transformAndSaveBabelAst(res.BabelAst, outPath, projDir, outDir, libDir, options) -let run opts projectPath outDir = +let run opts projectFileName outDir = let commandToRun = opts |> Array.tryFindIndex ((=) "--run") |> Option.map (fun i -> // TODO: This only works if the project is an .fsx file - let scriptFile = Path.Combine(outDir, Path.GetFileNameWithoutExtension(projectPath) + ".js") + let scriptFile = Path.Combine(outDir, Path.GetFileNameWithoutExtension(projectFileName) + ".js") let runArgs = opts.[i+1..] |> String.concat " " sprintf "node %s %s" scriptFile runArgs) let options = { commonjs = Option.isSome commandToRun || opts |> Array.contains "--commonjs" optimize = opts |> Array.contains "--optimize-fcs" watchMode = opts |> Array.contains "--watch" + sourceMaps = opts |> Array.contains "--sourceMaps" } - parseFiles projectPath outDir options + parseFiles projectFileName outDir options commandToRun |> Option.iter runCmdAndExitIfFails let parseArguments (argv: string[]) = @@ -120,11 +105,11 @@ let parseArguments (argv: string[]) = match opts, args with | [| "--help" |], _ -> printfn "%s" usage | [| "--version" |], _ -> printfn "v%s" (getVersion()) - | _, [| projectPath |] -> - Path.Combine(Path.GetDirectoryName(projectPath), "bin") - |> run opts projectPath - | _, [| projectPath; outDir |] -> - run opts projectPath outDir + | _, [| projectFileName |] -> + Path.Combine(Path.GetDirectoryName(projectFileName), "bin") + |> run opts projectFileName + | _, [| projectFileName; outDir |] -> + run opts projectFileName outDir | _ -> printfn "%s" usage [] diff --git a/src/fable-compiler-js/src/fable-compiler-js.fsproj b/src/fable-compiler-js/src/fable-compiler-js.fsproj index cfad1181f7..62f4f68822 100644 --- a/src/fable-compiler-js/src/fable-compiler-js.fsproj +++ b/src/fable-compiler-js/src/fable-compiler-js.fsproj @@ -3,6 +3,7 @@ Exe netcoreapp2.1 + Major @@ -10,11 +11,12 @@ - - - - - + + + + + + diff --git a/src/fable-compiler-js/src/util.js b/src/fable-compiler-js/src/util.js index 46a3f9a027..2321a8e6cf 100644 --- a/src/fable-compiler-js/src/util.js +++ b/src/fable-compiler-js/src/util.js @@ -1,156 +1,177 @@ -const fs = require("fs"); -const Path = require("path"); -const Babel = require("@babel/core"); -const BabelPlugins = require("fable-babel-plugins"); +import * as fs from "fs"; +import * as Path from "path"; +import Babel from "@babel/core"; +import BabelPlugins from "fable-babel-plugins"; const customPlugins = [ - BabelPlugins.getRemoveUnneededNulls(), - BabelPlugins.getTransformMacroExpressions(Babel.template) + BabelPlugins.getRemoveUnneededNulls(), + BabelPlugins.getTransformMacroExpressions(Babel.template) ]; const FSHARP_EXT = /\.(fs|fsx)$/i; const JAVASCRIPT_EXT = /\.js$/i; export function getVersion() { - return require("../package.json").version; + return require("../package.json").version; } export function getFableLibDir() { - return Path.join(Path.dirname(require.resolve("fable-standalone")), "fable-library"); + return Path.join(Path.dirname(require.resolve("fable-standalone")), "fable-library"); +} + +export function getDirFiles(dir) { + if (!fs.existsSync(dir)) return []; + const files = fs.readdirSync(dir).map((subdir) => { + const res = Path.resolve(dir, subdir); + return fs.statSync(res).isDirectory() ? getDirFiles(res) : res; + }); + return files.reduce((a, f) => a.concat(f), []); } export function serializeToJson(data) { - return JSON.stringify(data, (key, value) => { - if (value === Infinity) { - return "Infinity"; - } else if (value === -Infinity) { - return "-Infinity"; - } else if (value !== value) { - return "NaN"; - } - return value; - }); + return JSON.stringify(data, (key, value) => { + if (value === Infinity) { + return "Infinity"; + } else if (value === -Infinity) { + return "-Infinity"; + } else if (value !== value) { + return "NaN"; + } + return value; + }); } function ensureArray(obj) { - return (Array.isArray(obj) ? obj : obj != null ? [obj] : []); + return (Array.isArray(obj) ? obj : obj != null ? [obj] : []); } export function ensureDirExists(dir, cont) { - if (fs.existsSync(dir)) { - if (typeof cont === "function") { cont(); } - } else { - ensureDirExists(Path.dirname(dir), () => { - if (!fs.existsSync(dir)) { fs.mkdirSync(dir); } - if (typeof cont === "function") { cont(); } - }); - } + if (fs.existsSync(dir)) { + if (typeof cont === "function") { cont(); } + } else { + ensureDirExists(Path.dirname(dir), () => { + if (!fs.existsSync(dir)) { fs.mkdirSync(dir); } + if (typeof cont === "function") { cont(); } + }); + } } const uniquePaths = new Map(); function ensureUniquePath(sourcePath, outPath) { - while (uniquePaths.has(outPath) && uniquePaths.get(outPath) !== sourcePath) { - var i = outPath.lastIndexOf("."); - outPath = (i < 0) ? outPath + "_" : outPath.substr(0, i) + "_" + outPath.substr(i); - } - if (!uniquePaths.has(outPath)) { uniquePaths.set(outPath, sourcePath); } - return outPath; + while (uniquePaths.has(outPath) && uniquePaths.get(outPath) !== sourcePath) { + var i = outPath.lastIndexOf("."); + outPath = (i < 0) ? outPath + "_" : outPath.substr(0, i) + "_" + outPath.substr(i); + } + if (!uniquePaths.has(outPath)) { uniquePaths.set(outPath, sourcePath); } + return outPath; } function isRelativePath(path) { - return path.startsWith("./") || path.startsWith("../"); + return path.startsWith("./") || path.startsWith("../"); } function getRelPath(sourcePath, importPath, outPath, projDir, outDir) { - if (isRelativePath(importPath)) { - importPath = Path.resolve(Path.dirname(sourcePath), importPath); - } - let relPath = Path.relative(projDir, importPath).replace(/\\/g, "/"); - relPath = relPath.replace(/\.\.\//g, "").replace(/\.\//g, "").replace(/\:/g, ""); - relPath = Path.relative(Path.dirname(outPath), Path.join(outDir, relPath)); - relPath = relPath.replace(/\\/g, "/").replace(FSHARP_EXT, ".js"); - relPath = relPath.match(JAVASCRIPT_EXT) ? relPath : relPath + ".js"; - relPath = relPath.startsWith("..") ? relPath : "./" + relPath; - return relPath; + if (isRelativePath(importPath)) { + importPath = Path.resolve(Path.dirname(sourcePath), importPath); + } + let relPath = Path.relative(projDir, importPath).replace(/\\/g, "/"); + relPath = relPath.replace(/\.\.\//g, "").replace(/\.\//g, "").replace(/\:/g, ""); + relPath = Path.relative(Path.dirname(outPath), Path.join(outDir, relPath)); + relPath = relPath.replace(/\\/g, "/").replace(FSHARP_EXT, ".js"); + relPath = relPath.match(JAVASCRIPT_EXT) ? relPath : relPath + ".js"; + relPath = relPath.startsWith("..") ? relPath : "./" + relPath; + return relPath; } function getJsImport(sourcePath, importPath, outPath, projDir, outDir, babelOptions) { - const relPath = getRelPath(sourcePath, importPath, outPath, projDir, outDir); - let jsPath = isRelativePath(importPath) ? - Path.resolve(Path.dirname(sourcePath), importPath) : importPath; - jsPath = jsPath.match(JAVASCRIPT_EXT) ? jsPath : jsPath + ".js"; - outPath = Path.resolve(Path.dirname(outPath), relPath); - // if not already done, transform and save javascript imports - if (!uniquePaths.has(outPath) || uniquePaths.get(outPath) !== jsPath) { - outPath = ensureUniquePath(jsPath, outPath); - const resAst = Babel.transformFileSync(jsPath, { ast: true, code: false }); - fixImportPaths(resAst.ast.program, jsPath, outPath, projDir, outDir, outDir, babelOptions); - const resCode = Babel.transformFromAstSync(resAst.ast, null, babelOptions); - ensureDirExists(Path.dirname(outPath)); - fs.writeFileSync(outPath, resCode.code); - } - return relPath; + const relPath = getRelPath(sourcePath, importPath, outPath, projDir, outDir); + let jsPath = isRelativePath(importPath) ? + Path.resolve(Path.dirname(sourcePath), importPath) : importPath; + jsPath = jsPath.match(JAVASCRIPT_EXT) ? jsPath : jsPath + ".js"; + outPath = Path.resolve(Path.dirname(outPath), relPath); + // if not already done, transform and save javascript imports + if (!uniquePaths.has(outPath) || uniquePaths.get(outPath) !== jsPath) { + outPath = ensureUniquePath(jsPath, outPath); + const resAst = Babel.transformFileSync(jsPath, { ast: true, code: false }); + fixImportPaths(resAst.ast.program, jsPath, outPath, projDir, outDir, outDir, babelOptions); + const resCode = Babel.transformFromAstSync(resAst.ast, null, babelOptions); + ensureDirExists(Path.dirname(outPath)); + fs.writeFileSync(outPath, resCode.code); + } + return relPath; } function fixImportPaths(babelAst, sourcePath, outPath, projDir, outDir, libDir, babelOptions) { - const decls = ensureArray(babelAst.body); - for (const decl of decls) { - if (decl.source != null && typeof decl.source.value === "string") { - let importPath = decl.source.value; - if (importPath.startsWith("fable-library/")) { - importPath = Path.join(libDir, importPath.replace(/^fable-library\//, "")); - decl.source.value = getJsImport(sourcePath, importPath, outPath, Path.dirname(libDir), outDir, babelOptions); - } else if (importPath.match(FSHARP_EXT)) { - decl.source.value = getRelPath(sourcePath, importPath, outPath, projDir, outDir); - } else if (isRelativePath(importPath) || Path.isAbsolute(importPath)) { - decl.source.value = getJsImport(sourcePath, importPath, outPath, projDir, outDir, babelOptions); - } - } + const decls = ensureArray(babelAst.body); + for (const decl of decls) { + if (decl.source != null && typeof decl.source.value === "string") { + let importPath = decl.source.value; + if (importPath.startsWith("fable-library/")) { + importPath = Path.join(libDir, importPath.replace(/^fable-library\//, "")); + decl.source.value = getJsImport(sourcePath, importPath, outPath, Path.dirname(libDir), outDir, babelOptions); + } else if (importPath.match(FSHARP_EXT)) { + decl.source.value = getRelPath(sourcePath, importPath, outPath, projDir, outDir); + } else if (isRelativePath(importPath) || Path.isAbsolute(importPath)) { + decl.source.value = getJsImport(sourcePath, importPath, outPath, projDir, outDir, babelOptions); + } } + } } export function copyFolder(from, dest) { - if (!fs.existsSync(dest)) { - ensureDirExists(dest); + if (!fs.existsSync(dest)) { + ensureDirExists(dest); + } + fs.readdirSync(from).forEach(element => { + if (fs.lstatSync(Path.join(from, element)).isDirectory()) { + copyFolder(Path.join(from, element), Path.join(dest, element)); + } else { + fs.copyFileSync(Path.join(from, element), Path.join(dest, element)); } - fs.readdirSync(from).forEach(element => { - if (fs.lstatSync(Path.join(from, element)).isDirectory()) { - copyFolder(Path.join(from, element), Path.join(dest, element)); - } else { - fs.copyFileSync(Path.join(from, element), Path.join(dest, element)); - } - }); + }); } -export function transformAndSaveBabelAst(babelAst, filePath, projDir, outDir, libDir, commonjs) { - try { - // this solves a weird commonjs issue where some imports are not properly qualified - babelAst = JSON.parse(serializeToJson(babelAst)); // somehow this helps with that - const sourcePath = babelAst.fileName; - const jsPath = filePath.replace(FSHARP_EXT, ".js"); - let outPath = Path.resolve(outDir, jsPath); - outPath = ensureUniquePath(sourcePath, outPath); - ensureDirExists(Path.dirname(outPath)); - const babelOptions = commonjs ? - { plugins: customPlugins.concat("@babel/plugin-transform-modules-commonjs") } : - { plugins: customPlugins }; - fixImportPaths(babelAst, sourcePath, outPath, projDir, outDir, libDir, babelOptions); - const res = Babel.transformFromAstSync(babelAst, null, babelOptions); - fs.writeFileSync(outPath, res.code); - } catch (err) { - console.error(err); +export function transformAndSaveBabelAst(babelAst, filePath, projDir, outDir, libDir, options) { + try { + // this solves a weird commonjs issue where some imports are not properly qualified + babelAst = JSON.parse(serializeToJson(babelAst)); // somehow this helps with that + const sourcePath = babelAst.fileName; + const jsPath = filePath.replace(FSHARP_EXT, ".js"); + let outPath = Path.resolve(outDir, jsPath); + outPath = ensureUniquePath(sourcePath, outPath); + ensureDirExists(Path.dirname(outPath)); + const babelOptions = options.commonjs ? + { plugins: customPlugins.concat("@babel/plugin-transform-modules-commonjs") } : + { plugins: customPlugins }; + if (options.sourceMaps) { + babelOptions.sourceMaps = true; } + fixImportPaths(babelAst, sourcePath, outPath, projDir, outDir, libDir, babelOptions); + const babelOpts = Object.assign({}, babelOptions); + if (babelOpts.sourceMaps) { + const relPath = Path.relative(Path.dirname(outPath), sourcePath); + babelOpts.sourceFileName = relPath.replace(/\\/g, "/"); + } + const result = Babel.transformFromAstSync(babelAst, null, babelOpts); + fs.writeFileSync(outPath, result.code); + if (result.map) { + fs.appendFileSync(outPath, "\n//# sourceMappingURL=" + Path.basename(outPath) + ".map"); + fs.writeFileSync(outPath + ".map", JSON.stringify(result.map)); + } +} catch (err) { + console.error(err); + } } export function runCmdAndExitIfFails(cmd) { - var child_process = require("child_process"); - console.log(">", cmd); - try { - child_process.execSync(cmd, { - stdio: "inherit" - }); - } catch (error) { - process.exit(-1); - } + var child_process = require("child_process"); + console.log(">", cmd); + try { + child_process.execSync(cmd, { + stdio: "inherit" + }); + } catch (error) { + process.exit(-1); + } } \ No newline at end of file diff --git a/src/fable-compiler/RELEASE_NOTES.md b/src/fable-compiler/RELEASE_NOTES.md index b267f0336f..af3398d98c 100644 --- a/src/fable-compiler/RELEASE_NOTES.md +++ b/src/fable-compiler/RELEASE_NOTES.md @@ -1,3 +1,226 @@ +### 2.8.1 + +* Fix #2030: Fix Array.map3 implementation (by @ncave) + +### 2.8.0 + +* Add support for `using` function (by @ThisFunctionalTom) + +### 2.7.0 + +* Fix #2015: Add `PropertyInfo.GetValue` support + +### 2.6.0 + +* Fixed `List.init` to match `FSharp.Core` behavior (when initializing with side effects). (by @ncave) +* Update FCS to latest F# master (by @ncave) +* Fix #2017: Fix field name reflection for union case (by @anchann) +* Add `Length` member to `StringBuilder` (by @ThisFunctionalTom) +* Add `ToString(firstIndex, length)` override to `StringBuilder` (by @ThisFunctionalTom) + +### 2.5.1 + +* Improve globbing support (by @ncave) +* Fix #2010: Remove cycle dependencies in fable-library code (by @ncave) + +### 2.5.0 + +* Add globbing support in fsproj (by @Shmew) + +### 2.4.23 + +* Fixed buffer usage in fable-library encoding. (by @ncave) + +### 2.4.22 + +* Fix #1999: Add support for Uri toString (by @ncave) + +### 2.4.21 + +* Fix #1996: Storing result of Seq.tail and printing the result several times works (by @ncave) + +### 2.4.20 + +* Added missing `Tuple.Rest` (by @ncave) + +### 2.4.19 + +* Fix #1991: Trait calls for Tuple getters don't work (by @ncave) +* Minor update to fable-library (by @ncave) + +### 2.4.18 + +* Minor update to fable-library (by @ncave) +* Minor update to Replacements.fs making it easier to read some methods (by @ncave) + +### 2.4.17 + +* Fix #1988: Allow to use `printfn "%A"` against `seq` (by @ncave) +* Minor update to fable-library (by @ncave) + +### 2.4.16 + +* PR #1984: Minor update to fable-library, rewrite `Seq.pairwise` implementation (by @ncave) + +### 2.4.15 + +* Fix #1979: Add support for LanguagePrimitives.xxxWithMeasure (by @ncave) + +### 2.4.14 + +* Fix #1975: Fix endless loop (by @ncave) +* Made ResizeArray.Add void (by @ncave) +* Updated option and numeric types (by @ncave) +* Minor update to fable-library (by @ncave) + +### 2.4.13 + +* Use strict mode in fable-library +* Fix #1964: Add AppendLine to StringBuiler +* Fix #1971: Trim in String.js fails for leading/following brackets +* Fix #1972: Add back Item member to Typed arrays +* Fixed error message formatting +* Fixed tryEntityRef + +### 2.4.12 + +* Fix #1959: Uncurry args passed to point-free methods +* Fix #1955: Substring throws with invalid index and/or length arguments +* Fix #1948: Wrap Option.Some in runtime to avoid null ambiguity +* Fix #1895: Check also member of parent interfaces when casting an anonymous record + +### 2.4.11 + +* Fix #1937 (again): sign in sprintf for long @ncave + +### 2.4.10 + +* Fix #1937: sign in sprintf +* Fix #1938: tryExactlyOne + +### 2.4.9 + +* Fix #1932: regression with sprintf and 0 precision for floats + +### 2.4.8 + +* Support Array.splitInto & List.splitInto @kerams +* Fix #1931: sprint formatting combining sign and padding + +### 2.4.7 + +* Fix compilation of .fsx files @nojaf +* Add more CaseRules + +### 2.4.6 + +* Adjust timezone offset when adding local dates +* Fix #1923: Option.map ignore generates Some () + +### 2.4.5 + +* Fix #1918: Enum reflection support @MangelMaxime +* Fix #1919: Path of .fsi files @krauthaufen + +### 2.4.3 + +* Fix #1908: Overloads only distinguished by argument generic constrains +* Parse LangVersion from .fsproj + +### 2.4.2 + +* Build Fable.Cli with dotnet SDK 3 (but still target netcoreapp2.1) + +### 2.4.0 + +* Support F# 4.7 (implicit yields) @ncave +* Fix #1910: Roll forward major version to run on dotnet SDK 3 @forki + +### 2.3.25 + +* Fix #1900: gen param names conflict +* Fixed large String.join and concat @ncave + +### 2.3.24 + +* Fix #1896: Don't dupe casting to untyped array @zanaptak +* Fix #1895: anonymous record !! casting warnings @giulioungaretti +* Moar cleanup for beta reduction optimization + +### 2.3.23 + +* Fix #1894: Seq.distinct with infinite sequence @et1975 +* Fix #1891: Overloads with anonymous records @Zaid-Ajaj +* Fix #1886: Handle .fsx file with dotnet core 3 @rfrerebe + +### 2.3.22 + +* Fix `Count` on ICollection @forki + +### 2.3.21 + +* Added O(1) mutable map and set, with equality comparer (using native JS Map/Set) @ncave +* Reduced fable-library module inter-dependency @ncave +* Fixed Array.zeroCreate issue in REPL build @ncave + +### 2.3.20 + +* Fix `Array.zeroCreate` with KeyValuePair @ncave +* Fixes for untyped arrays (System.Array) +* Fix optimization of ResizeArray constructor +* Fix optimization of Guid and StringEnum string conversion +* Fix `nameof(typeof)` + +### 2.3.19 + +* Fix #1876 (bis): script (fsx) compilation @nojaf +* Fix #1880: parsing uint64 +* Support RegexOptions.Singleline +* Minor optimization and sourcemaps improvement + +### 2.3.18 + +* Fix #1876: script (fsx) compilation @nojaf +* Fix struct without explicit constructor @0x53A + +### 2.3.17 + +* Update FSharp.Compiler.Services and Dotnet.ProjInfo +* Fix #1868: Type provider ResolutionFolder is empty @ncave + +### 2.3.16 + +* Fix #1871: comparing anonymous record types +* Fix `TimeSpan.ToString` for negative values @MangelMaxime +* Some more source map improvements + +### 2.3.15 + +* Fix negative timespan + milliseconds value when parsing a string @MangelMaxime +* Improve source maps @matthid + +### 2.3.14 + +* Fix Timespan and Guid reflection info @MangelMaxime +* Fix #1864: npm security issues +* Fix #1863: Binding event to a value +* Fix #1862: Add `--silent` option + +* Fix #1859: Binding optimization vs tailcalls +* Fix #1857, #1729: Maps casted to IDictionary +* Fix #1856: Decimal and BigInt ranges + +### 2.3.12 + +* Fix #1848: decimal should round up .5 + +### 2.3.11 + +* Fix #1845: Seq/Array/List.allPairs +* Fix #1844: DateTime.SpecifyKind +* Fix #1843: Remove project.assets.json check +* Fix #1842: Add Option.map2/map3 + ### 2.3.10 * Fix #1836: Partial Applying caches side-effects @@ -22,7 +245,7 @@ ### 2.3.4 -* Fix #1821: decimal devision @ncave +* Fix #1821: decimal division @ncave * Fix #1817: List slicing ### 2.3.3 diff --git a/src/fable-compiler/package-lock.json b/src/fable-compiler/package-lock.json index 7531dad34d..02f33113cd 100644 --- a/src/fable-compiler/package-lock.json +++ b/src/fable-compiler/package-lock.json @@ -1,6 +1,6 @@ { "name": "fable-compiler", - "version": "2.3.10", + "version": "2.8.1", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/src/fable-compiler/src/index.ts b/src/fable-compiler/src/index.ts index f6da94a7a4..1085d562bc 100644 --- a/src/fable-compiler/src/index.ts +++ b/src/fable-compiler/src/index.ts @@ -6,6 +6,12 @@ import * as readline from "readline"; const BIN_PATH = path.join(__dirname, "../bin/fable-cli/Fable.Cli.dll"); +function log(args: {[x: string]: any} | undefined, msg: string) { + if (!(args && args.silent)) { + console.log(msg); + } +} + // From https://gist.github.com/LeverOne/1308368 /* tslint:disable:no-bitwise */ function uuid() { @@ -32,7 +38,7 @@ function processArgs(args?: {[x: string]: any}) { if (args != null) { if (args.path) { const filePath = path.resolve(args.path); - console.log(`dotnet binary: ${filePath}`); + log(args, `dotnet binary: ${filePath}`); cliArgs = filePath.endsWith(".dll") ? [filePath, "start-stdin", "--force-pkgs"] : ["run", "-c", "Release", "-p", filePath, "start-stdin", "--force-pkgs"]; @@ -56,7 +62,7 @@ export interface ICompilerProxy { } export default function start(cliArgs?: {}): ICompilerProxy { - console.log(`fable-compiler ${getVersion()}`); + log(cliArgs, `fable-compiler ${getVersion()}`); const child = spawn("dotnet", processArgs(cliArgs)); // Error handling @@ -67,7 +73,7 @@ export default function start(cliArgs?: {}): ICompilerProxy { console.error(`child proccess errored: ${data}`); }); // child.on("close", (code) => { - // console.log(`child process exited with code ${code}`); + // log(cliArgs, `child process exited with code ${code}`); // }); // Pending promises @@ -86,7 +92,7 @@ export default function start(cliArgs?: {}): ICompilerProxy { resolve(JSON.parse(data.substr(pattern[0].length))); } } else { // LOG - console.log(data); + log(cliArgs, data); } }); diff --git a/src/fable-library/Array.fs b/src/fable-library/Array.fs index 5d135a0690..5710ffd995 100644 --- a/src/fable-library/Array.fs +++ b/src/fable-library/Array.fs @@ -17,18 +17,18 @@ type IArrayCons<'T> = let [] DynamicArrayCons<'T> : IArrayCons<'T> = jsNative module Helpers = - /// Creates an empty array with the same type and length as another - [] - let createArrayFromImpl (_: 'T[]): 'T[] = jsNative let inline newDynamicArrayImpl (len: int): 'T[] = DynamicArrayCons.Create(len) + let inline isDynamicArrayImpl arr = + JS.Constructors.Array.isArray arr + let inline isTypedArrayImpl arr = - JS.ArrayBuffer.isView arr + JS.Constructors.ArrayBuffer.isView arr - let inline typedArraySetImpl (target: obj) (source: obj) (offset: int): unit = - !!target?set(source, offset) + // let inline typedArraySetImpl (target: obj) (source: obj) (offset: int): unit = + // !!target?set(source, offset) let inline appendImpl (array1: 'T[]) (array2: 'T[]): 'T[] = !!array1?concat(array2) @@ -122,7 +122,8 @@ module Helpers = open Helpers -let private indexNotFound() = failwith "An index satisfying the predicate was not found in the collection." +let private indexNotFoundMsg = "An index satisfying the predicate was not found in the collection." +let inline indexNotFound() = failwith indexNotFoundMsg // Pay attention when benchmarking to append and filter functions below // if implementing via native JS array .concat() and .filter() do not fall behind due to js-native transitions. @@ -201,35 +202,35 @@ let mapIndexed3 (f: int->'T1->'T2->'T3->'U) (source1: 'T1[]) (source2: 'T2[]) (s result.[i] <- f i source1.[i] source2.[i] source3.[i] result -let map3 f (source1: 'T[]) (source2: 'U[]) (source3: 'U[]) ([] cons: IArrayCons<'W>): 'W[] = +let map3 (f: 'T1->'T2->'T3->'U) (source1: 'T1[]) (source2: 'T2[]) (source3: 'T3[]) ([] cons: IArrayCons<'U>): 'U[] = if source1.Length <> source2.Length || source2.Length <> source3.Length then failwith "Arrays had different lengths" let result = cons.Create(source1.Length) for i = 0 to source1.Length - 1 do result.[i] <- f source1.[i] source2.[i] source3.[i] result -let mapFold<'T,'State,'Result> (mapping: 'State -> 'T -> 'Result * 'State) state (array: 'T[]) ([] cons: IArrayCons<'Result>) = +let mapFold<'T, 'State, 'Result> (mapping: 'State -> 'T -> 'Result * 'State) state (array: 'T[]) ([] cons: IArrayCons<'Result>) = match array.Length with | 0 -> [| |], state | len -> let mutable acc = state let res = cons.Create len for i = 0 to array.Length-1 do - let h',s' = mapping acc array.[i] - res.[i] <- h' - acc <- s' + let h,s = mapping acc array.[i] + res.[i] <- h + acc <- s res, acc -let mapFoldBack<'T,'State,'Result> (mapping: 'T -> 'State -> 'Result * 'State) (array: 'T[]) state ([] cons: IArrayCons<'Result>) = +let mapFoldBack<'T, 'State, 'Result> (mapping: 'T -> 'State -> 'Result * 'State) (array: 'T[]) state ([] cons: IArrayCons<'Result>) = match array.Length with | 0 -> [| |], state | len -> let mutable acc = state let res = cons.Create len for i = array.Length-1 downto 0 do - let h',s' = mapping array.[i] acc - res.[i] <- h' - acc <- s' + let h,s = mapping array.[i] acc + res.[i] <- h + acc <- s res, acc let indexed (source: 'T[]) = @@ -243,8 +244,10 @@ let truncate (count: int) (array: 'T[]): 'T[] = let count = max 0 count subArrayImpl array 0 count -let concat<'T> (arrays: 'T[] seq) ([] cons: IArrayCons<'T>): 'T[] = - let arrays = DynamicArrayCons.FromSequence arrays +let concat (arrays: 'T[] seq) ([] cons: IArrayCons<'T>): 'T[] = + let arrays = + if isDynamicArrayImpl arrays then arrays :?> 'T[][] // avoid extra copy + else DynamicArrayCons.FromSequence arrays match arrays.Length with | 0 -> cons.Create 0 | 1 -> arrays.[0] @@ -270,19 +273,18 @@ let collect (mapping: 'T -> 'U[]) (array: 'T[]) ([] cons: IArrayCons<'U> let countBy (projection: 'T -> 'Key) (array: 'T[]) ([] eq: IEqualityComparer<'Key>) = let dict = Dictionary<'Key, int>(eq) - + let keys: 'Key[] = [||] for value in array do let key = projection value match dict.TryGetValue(key) with - | true, prev -> dict.[key] <- prev + 1 - | false, _ -> dict.[key] <- 1 - - let res = newDynamicArrayImpl dict.Count - let mutable i = 0 - for group in dict do - res.[i] <- group.Key, group.Value - i <- i + 1 - res + | true, prev -> + dict.[key] <- prev + 1 + | false, _ -> + dict.[key] <- 1 + pushImpl keys key |> ignore + let result = + map (fun key -> key, dict.[key]) keys DynamicArrayCons + result let distinctBy (projection: 'T -> 'Key) (array: 'T[]) ([] eq: IEqualityComparer<'Key>) = let hashSet = HashSet<'Key>(eq) @@ -302,7 +304,6 @@ let contains<'T> (value: 'T) (array: 'T[]) ([] eq: IEqualityComparer<'T> else loop (i + 1) loop 0 - let except (itemsToExclude: seq<'T>) (array: 'T[]) ([] eq: IEqualityComparer<'T>): 'T[] = if array.Length = 0 then array @@ -312,7 +313,7 @@ let except (itemsToExclude: seq<'T>) (array: 'T[]) ([] eq: IEqualityComp let groupBy (projection: 'T -> 'Key) (array: 'T[]) ([] cons: IArrayCons<'T>) ([] eq: IEqualityComparer<'Key>) = let dict = Dictionary<'Key, 'T list>(eq) - let keys = ResizeArray() + let keys: 'Key[] = [||] for v in array do let key = projection v match dict.TryGetValue(key) with @@ -320,10 +321,9 @@ let groupBy (projection: 'T -> 'Key) (array: 'T[]) ([] cons: IArrayCons< dict.[key] <- v::prev | false, _ -> dict.Add(key, [v]) - keys.Add(key) - let result = newDynamicArrayImpl keys.Count - keys |> Seq.iteri (fun i key -> - result.[i] <- key, (cons.FromSequence dict.[key] |> reverseImpl)) + pushImpl keys key |> ignore + let result = + map (fun key -> key, (cons.FromSequence dict.[key] |> reverseImpl)) keys DynamicArrayCons result let inline private emptyImpl (cons: IArrayCons<'T>) = cons.Create(0) @@ -343,13 +343,12 @@ let initialize count initializer ([] cons: IArrayCons<'T>) = result let pairwise (array: 'T[]) = - if array.Length < 2 - then [||] + if array.Length < 2 then [||] else let count = array.Length - 1 let result = newDynamicArrayImpl count for i = 0 to count - 1 do - result.[i] <- array.[i], array.[i+1] + result.[i] <- array.[i], array.[i+1] result let replicate count initial ([] cons: IArrayCons<'T>) = @@ -428,6 +427,10 @@ let takeWhile predicate (array: 'T[]) ([] cons: IArrayCons<'T>) = else subArrayImpl array 0 count +let addInPlace (x: 'T) (array: 'T[]) = + // if isTypedArrayImpl array then invalidArg "array" "Typed arrays not supported" + pushImpl array x |> ignore + let addRangeInPlace (range: seq<'T>) (array: 'T[]) = // if isTypedArrayImpl array then invalidArg "array" "Typed arrays not supported" Seq.iter (fun x -> pushImpl array x |> ignore) range @@ -451,6 +454,7 @@ let removeAllInPlace predicate (array: 'T[]) = count countRemoveAll 0 +// TODO: Check array lengths let copyTo (source: 'T[]) sourceIndex (target: 'T[]) targetIndex count = let diff = targetIndex - sourceIndex for i = sourceIndex to sourceIndex + count - 1 do @@ -600,15 +604,15 @@ let forAll predicate (array: 'T[]) = let permute f (array: 'T[]) = let size = array.Length - let res = createArrayFromImpl array - let checkFlags = newDynamicArrayImpl size + let res = copyImpl array + let checkFlags = Array.zeroCreate size iterateIndexed (fun i x -> let j = f i if j < 0 || j >= size then invalidOp "Not a valid permutation" res.[j] <- x checkFlags.[j] <- 1) array - let isValid = forAll ((=) 1) checkFlags + let isValid = checkFlags |> forAllImpl ((=) 1) if not isValid then invalidOp "Not a valid permutation" res @@ -617,11 +621,12 @@ let setSlice (target: 'T[]) (lower: int option) (upper: int option) (source: 'T[ let lower = defaultArg lower 0 let upper = defaultArg upper 0 let length = (if upper > 0 then upper else target.Length - 1) - lower - if isTypedArrayImpl target && source.Length <= length then - typedArraySetImpl target source lower - else - for i = 0 to length do - target.[i + lower] <- source.[i] + // can't cast to TypedArray, so can't use TypedArray-specific methods + // if isTypedArrayImpl target && source.Length <= length then + // typedArraySetImpl target source lower + // else + for i = 0 to length do + target.[i + lower] <- source.[i] let sortInPlaceBy (projection: 'a->'b) (xs: 'a[]) ([] comparer: IComparer<'b>): unit = sortInPlaceWithImpl (fun x y -> comparer.Compare(projection x, projection y)) xs @@ -633,35 +638,29 @@ let inline internal sortInPlaceWith (comparer: 'T -> 'T -> int) (xs: 'T[]) = sortInPlaceWithImpl comparer xs xs -let private copyArray (array: 'T[]) = - let result = createArrayFromImpl array - for i = 0 to array.Length - 1 do - result.[i] <- array.[i] - result - let sort (xs: 'T[]) ([] comparer: IComparer<'T>): 'T[] = - sortInPlaceWith (fun x y -> comparer.Compare(x, y)) (copyArray xs) + sortInPlaceWith (fun x y -> comparer.Compare(x, y)) (copyImpl xs) let sortBy (projection: 'a->'b) (xs: 'a[]) ([] comparer: IComparer<'b>): 'a[] = - sortInPlaceWith (fun x y -> comparer.Compare(projection x, projection y)) (copyArray xs) + sortInPlaceWith (fun x y -> comparer.Compare(projection x, projection y)) (copyImpl xs) let sortDescending (xs: 'T[]) ([] comparer: IComparer<'T>): 'T[] = - sortInPlaceWith (fun x y -> comparer.Compare(x, y) * -1) (copyArray xs) + sortInPlaceWith (fun x y -> comparer.Compare(x, y) * -1) (copyImpl xs) let sortByDescending (projection: 'a->'b) (xs: 'a[]) ([] comparer: IComparer<'b>): 'a[] = - sortInPlaceWith (fun x y -> comparer.Compare(projection x, projection y) * -1) (copyArray xs) + sortInPlaceWith (fun x y -> comparer.Compare(projection x, projection y) * -1) (copyImpl xs) let sortWith (comparer: 'T -> 'T -> int) (xs: 'T[]): 'T[] = - sortInPlaceWith comparer (copyArray xs) + sortInPlaceWith comparer (copyImpl xs) -let unfold<'T,'State> (generator: 'State -> ('T*'State) option) (state: 'State): 'State[] = - let res = [||] +let unfold<'T, 'State> (generator: 'State -> ('T*'State) option) (state: 'State): 'T[] = + let res: 'T[] = [||] let rec loop state = match generator state with | None -> () - | Some (x,s') -> + | Some (x, s) -> pushImpl res x |> ignore - loop s' + loop s loop state res @@ -766,7 +765,7 @@ let tryItem index (array: 'T[]) = if index < 0 || index >= array.Length then None else Some array.[index] -let foldBackIndexed<'T,'State> folder (array: 'T[]) (state: 'State) = +let foldBackIndexed<'T, 'State> folder (array: 'T[]) (state: 'State) = // if isTypedArrayImpl array then // let mutable acc = state // let size = array.Length @@ -776,7 +775,7 @@ let foldBackIndexed<'T,'State> folder (array: 'T[]) (state: 'State) = // else foldBackIndexedImpl (fun acc x i -> folder i x acc) state array -let foldBack<'T,'State> folder (array: 'T[]) (state: 'State) = +let foldBack<'T, 'State> folder (array: 'T[]) (state: 'State) = // if isTypedArrayImpl array then // foldBackIndexed (fun _ x acc -> folder x acc) array state // else @@ -860,14 +859,16 @@ let min (xs: 'a[]) ([] comparer: IComparer<'a>): 'a = reduce (fun x y -> if comparer.Compare(y, x) > 0 then x else y) xs let average (array: 'T []) ([] averager: IGenericAverager<'T>): 'T = - if array.Length = 0 then invalidArg "array" LanguagePrimitives.ErrorStrings.InputArrayEmptyString + if array.Length = 0 then + invalidArg "array" LanguagePrimitives.ErrorStrings.InputArrayEmptyString let mutable total = averager.GetZero() for i = 0 to array.Length - 1 do total <- averager.Add(total, array.[i]) averager.DivideByInt(total, array.Length) let averageBy (projection: 'T -> 'T2) (array: 'T[]) ([] averager: IGenericAverager<'T2>): 'T2 = - if array.Length = 0 then invalidArg "array" LanguagePrimitives.ErrorStrings.InputArrayEmptyString + if array.Length = 0 then + invalidArg "array" LanguagePrimitives.ErrorStrings.InputArrayEmptyString let mutable total = averager.GetZero() for i = 0 to array.Length - 1 do total <- averager.Add(total, projection array.[i]) @@ -890,7 +891,42 @@ let toList (source: 'T[]) = let windowed (windowSize: int) (source: 'T[]): 'T[][] = if windowSize <= 0 then failwith "windowSize must be positive" - let res = FSharp.Core.Operators.max 0 (source.Length - windowSize) |> Helpers.newDynamicArrayImpl + let res = FSharp.Core.Operators.max 0 (source.Length - windowSize) |> newDynamicArrayImpl for i = windowSize to source.Length do res.[i - windowSize] <- source.[i-windowSize..i-1] res + +let splitInto (chunks: int) (array: 'T[]): 'T[][] = + if chunks < 1 then + invalidArg "chunks" "The input must be positive." + if array.Length = 0 then + [| [||] |] + else + let result: 'T[][] = [||] + let chunks = FSharp.Core.Operators.min chunks array.Length + let minChunkSize = array.Length / chunks + let chunksWithExtraItem = array.Length % chunks + for i = 0 to chunks - 1 do + let chunkSize = if i < chunksWithExtraItem then minChunkSize + 1 else minChunkSize + let start = i * minChunkSize + (FSharp.Core.Operators.min chunksWithExtraItem i) + let slice = subArrayImpl array start chunkSize + pushImpl result slice |> ignore + result + +let transpose (arrays: 'T[] seq) ([] cons: IArrayCons<'T>): 'T[][] = + let arrays = + if isDynamicArrayImpl arrays then arrays :?> 'T[][] // avoid extra copy + else DynamicArrayCons.FromSequence arrays + let len = arrays.Length + match len with + | 0 -> newDynamicArrayImpl 0 + | _ -> + let lenInner = arrays.[0].Length + if arrays |> forAll (fun a -> a.Length = lenInner) |> not then + failwith "Arrays had different lengths" + let result: 'T[][] = newDynamicArrayImpl lenInner + for i in 0..lenInner-1 do + result.[i] <- cons.Create len + for j in 0..len-1 do + result.[i].[j] <- arrays.[j].[i] + result diff --git a/src/fable-library/Async.ts b/src/fable-library/Async.ts index a782fb382b..2187cf06d7 100644 --- a/src/fable-library/Async.ts +++ b/src/fable-library/Async.ts @@ -10,10 +10,10 @@ import { choice1, choice2 } from "./Option"; import { map } from "./Seq"; // Implemented just for type references -export default class Async { +export default class Async<_T> { } -function emptyContinuation(x: T) { +function emptyContinuation(_x: T) { // NOP } @@ -34,10 +34,10 @@ export function bind(ctx: IAsyncContext, part1: IAsync, part2: (x: U return protectedBind(part1, part2)(ctx); } -export function createCancellationToken(arg?: boolean|number): CancellationToken { +export function createCancellationToken(arg?: boolean | number): CancellationToken { const token = new CancellationToken(typeof arg === "boolean" ? arg : false); if (typeof arg === "number") { - setTimeout(() => { token.cancel(); }, arg); + setTimeout(() => { token.cancel(); }, arg); } return token; } @@ -66,7 +66,7 @@ export function awaitPromise(p: Promise) { return fromContinuations((conts: Continuations) => p.then(conts[0]).catch((err) => (err instanceof OperationCanceledError - ? conts[2] : conts[1])(err))); + ? conts[2] : conts[1])(err))); } export function cancellationToken() { @@ -93,7 +93,7 @@ export function fromContinuations(f: (conts: Continuations) => void) { } export function ignore(computation: IAsync) { - return protectedBind(computation, (x) => protectedReturn(void 0)); + return protectedBind(computation, (_x) => protectedReturn(void 0)); } export function parallel(computations: Iterable>) { @@ -101,24 +101,24 @@ export function parallel(computations: Iterable>) { } export function sleep(millisecondsDueTime: number) { - return protectedCont((ctx: IAsyncContext) => { - let tokenId: number; - const timeoutId = setTimeout(() => { - ctx.cancelToken.removeListener(tokenId); - ctx.onSuccess(void 0); - }, millisecondsDueTime); - tokenId = ctx.cancelToken.addListener(() => { - clearTimeout(timeoutId); - ctx.onCancel(new OperationCanceledError()); - }); + return protectedCont((ctx: IAsyncContext) => { + let tokenId: number; + const timeoutId = setTimeout(() => { + ctx.cancelToken.removeListener(tokenId); + ctx.onSuccess(void 0); + }, millisecondsDueTime); + tokenId = ctx.cancelToken.addListener(() => { + clearTimeout(timeoutId); + ctx.onCancel(new OperationCanceledError()); }); + }); } -export function start(computation: IAsync, cancellationToken?: CancellationToken) { +export function start(computation: IAsync, cancellationToken?: CancellationToken) { return startWithContinuations(computation, cancellationToken); } -export function startImmediate(computation: IAsync, cancellationToken?: CancellationToken) { +export function startImmediate(computation: IAsync, cancellationToken?: CancellationToken) { return start(computation, cancellationToken); } @@ -130,7 +130,7 @@ export function startWithContinuations( cancelToken?: CancellationToken) { if (typeof continuation !== "function") { cancelToken = continuation as CancellationToken; - continuation = null; + continuation = undefined; } const trampoline = new Trampoline(); computation({ diff --git a/src/fable-library/AsyncBuilder.ts b/src/fable-library/AsyncBuilder.ts index 4813e71b6d..d0ccc6a6a1 100644 --- a/src/fable-library/AsyncBuilder.ts +++ b/src/fable-library/AsyncBuilder.ts @@ -9,38 +9,38 @@ export type Continuations = [ ]; export class CancellationToken { - private _id: number; - private _cancelled: boolean; - private _listeners: Map void>; - constructor(cancelled = false) { - this._id = 0; - this._cancelled = cancelled; - this._listeners = new Map(); - } - get isCancelled() { - return this._cancelled; - } - cancel() { - if (!this._cancelled) { - this._cancelled = true; - for (const [, listener] of this._listeners) { - listener(); - } - } - } - addListener(f: () => void) { - const id = this._id; - this._listeners.set(this._id++, f); - return id; - } - removeListener(id: number) { - return this._listeners.delete(id); - } - register(f: (state?: any)=>void, state?: any) { - const $ = this; - const id = this.addListener(state == null ? f : () => f(state)); - return { Dispose() { $.removeListener(id); } } + private _id: number; + private _cancelled: boolean; + private _listeners: Map void>; + constructor(cancelled = false) { + this._id = 0; + this._cancelled = cancelled; + this._listeners = new Map(); + } + get isCancelled() { + return this._cancelled; + } + public cancel() { + if (!this._cancelled) { + this._cancelled = true; + for (const [, listener] of this._listeners) { + listener(); + } } + } + public addListener(f: () => void) { + const id = this._id; + this._listeners.set(this._id++, f); + return id; + } + public removeListener(id: number) { + return this._listeners.delete(id); + } + public register(f: (state?: any) => void, state?: any) { + const $ = this; + const id = this.addListener(state == null ? f : () => f(state)); + return { Dispose() { $.removeListener(id); } }; + } } export class OperationCanceledError extends Error { @@ -118,7 +118,7 @@ export function protectedBind(computation: IAsync, binder: (x: T) => IA }); } -export function protectedReturn(value?: T) { +export function protectedReturn(value: T) { return protectedCont((ctx: IAsyncContext) => ctx.onSuccess(value)); } diff --git a/src/fable-library/BigInt.fs b/src/fable-library/BigInt.fs index 6518ce79fd..84b1af869a 100644 --- a/src/fable-library/BigInt.fs +++ b/src/fable-library/BigInt.fs @@ -166,3 +166,19 @@ let fromByteArray (bytes:byte array) = ||| (uint32 b3 <<< 24) loop (value :: accumUInt32) (currIndex + bytesToProcess) (bytesRemaining - bytesToProcess) lowBitFound loop [] 0 bytes.Length false + +let makeRangeStepFunction (step: bigint) (last: bigint) = + let stepComparedWithZero = compare step zero + if stepComparedWithZero = 0 then + failwith "The step of a range cannot be zero" + let stepGreaterThanZero = stepComparedWithZero > 0 + fun (x: bigint) -> + let comparedWithLast = compare x last + if (stepGreaterThanZero && comparedWithLast <= 0) + || (not stepGreaterThanZero && comparedWithLast >= 0) then + Some (x, x + step) + else None + +let range (first: bigint) (step: bigint) (last: bigint) = + let stepFn = makeRangeStepFunction step last + Seq.delay(fun () -> Seq.unfold stepFn first) diff --git a/src/fable-library/BitConverter.ts b/src/fable-library/BitConverter.ts index 9dd9df43b1..530d3d3fc6 100644 --- a/src/fable-library/BitConverter.ts +++ b/src/fable-library/BitConverter.ts @@ -1,4 +1,5 @@ -import { fromBits, getHighBits, getHighBitsUnsigned, getLowBits, getLowBitsUnsigned } from "./Long"; +import { uint8 } from "./Int32"; +import Long, { fromBits, getHighBits, getHighBitsUnsigned, getLowBits, getLowBitsUnsigned } from "./Long"; const littleEndian = true; @@ -34,7 +35,7 @@ export function getBytesInt32(value: number) { return bytes; } -export function getBytesInt64(value: number /* Long */) { +export function getBytesInt64(value: Long) { const bytes = new Uint8Array(8); const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); view.setInt32(littleEndian ? 0 : 4, getLowBits(value), littleEndian); @@ -56,7 +57,7 @@ export function getBytesUInt32(value: number) { return bytes; } -export function getBytesUInt64(value: number /* Long */) { +export function getBytesUInt64(value: Long) { const bytes = new Uint8Array(8); const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); view.setUint32(littleEndian ? 0 : 4, getLowBitsUnsigned(value), littleEndian); @@ -78,7 +79,7 @@ export function getBytesDouble(value: number) { return bytes; } -export function int64BitsToDouble(value: number /* Long */) { +export function int64BitsToDouble(value: Long) { const buffer = new ArrayBuffer(8); const view = new DataView(buffer); view.setInt32(littleEndian ? 0 : 4, getLowBits(value), littleEndian); @@ -95,67 +96,78 @@ export function doubleToInt64Bits(value: number) { return fromBits(lowBits, highBits, false); } -export function toBoolean(bytes: Uint8Array, offset: number): boolean { - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); +export function toBoolean(bytes: ArrayLike, offset: number): boolean { + const array = ArrayBuffer.isView(bytes) ? bytes : Uint8Array.from(bytes); + const view = new DataView(array.buffer, array.byteOffset, array.byteLength); return view.getUint8(offset) === 1 ? true : false; } -export function toChar(bytes: Uint8Array, offset: number) { - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); +export function toChar(bytes: ArrayLike, offset: number) { + const array = ArrayBuffer.isView(bytes) ? bytes : Uint8Array.from(bytes); + const view = new DataView(array.buffer, array.byteOffset, array.byteLength); const code = view.getUint16(offset, littleEndian); return String.fromCharCode(code); } -export function toInt16(bytes: Uint8Array, offset: number) { - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); +export function toInt16(bytes: ArrayLike, offset: number) { + const array = ArrayBuffer.isView(bytes) ? bytes : Uint8Array.from(bytes); + const view = new DataView(array.buffer, array.byteOffset, array.byteLength); return view.getInt16(offset, littleEndian); } -export function toInt32(bytes: Uint8Array, offset: number) { - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); +export function toInt32(bytes: ArrayLike, offset: number) { + const array = ArrayBuffer.isView(bytes) ? bytes : Uint8Array.from(bytes); + const view = new DataView(array.buffer, array.byteOffset, array.byteLength); return view.getInt32(offset, littleEndian); } -export function toInt64(bytes: Uint8Array, offset: number) { - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); +export function toInt64(bytes: ArrayLike, offset: number) { + const array = ArrayBuffer.isView(bytes) ? bytes : Uint8Array.from(bytes); + const view = new DataView(array.buffer, array.byteOffset, array.byteLength); const lowBits = view.getInt32(offset + (littleEndian ? 0 : 4), littleEndian); const highBits = view.getInt32(offset + (littleEndian ? 4 : 0), littleEndian); return fromBits(lowBits, highBits, false); } -export function toUInt16(bytes: Uint8Array, offset: number) { - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); +export function toUInt16(bytes: ArrayLike, offset: number) { + const array = ArrayBuffer.isView(bytes) ? bytes : Uint8Array.from(bytes); + const view = new DataView(array.buffer, array.byteOffset, array.byteLength); return view.getUint16(offset, littleEndian); } -export function toUInt32(bytes: Uint8Array, offset: number) { - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); +export function toUInt32(bytes: ArrayLike, offset: number) { + const array = ArrayBuffer.isView(bytes) ? bytes : Uint8Array.from(bytes); + const view = new DataView(array.buffer, array.byteOffset, array.byteLength); return view.getUint32(offset, littleEndian); } -export function toUInt64(bytes: Uint8Array, offset: number) { - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); +export function toUInt64(bytes: ArrayLike, offset: number) { + const array = ArrayBuffer.isView(bytes) ? bytes : Uint8Array.from(bytes); + const view = new DataView(array.buffer, array.byteOffset, array.byteLength); const lowBits = view.getUint32(offset + (littleEndian ? 0 : 4), littleEndian); const highBits = view.getUint32(offset + (littleEndian ? 4 : 0), littleEndian); return fromBits(lowBits, highBits, true); } -export function toSingle(bytes: Uint8Array, offset: number) { - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); +export function toSingle(bytes: ArrayLike, offset: number) { + const array = ArrayBuffer.isView(bytes) ? bytes : Uint8Array.from(bytes); + const view = new DataView(array.buffer, array.byteOffset, array.byteLength); return view.getFloat32(offset, littleEndian); } -export function toDouble(bytes: Uint8Array, offset: number) { - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); +export function toDouble(bytes: ArrayLike, offset: number) { + const array = ArrayBuffer.isView(bytes) ? bytes : Uint8Array.from(bytes); + const view = new DataView(array.buffer, array.byteOffset, array.byteLength); return view.getFloat64(offset, littleEndian); } -export function toString(bytes: Uint8Array, offset?: number, count?: number) { - let ar = bytes; - if (typeof offset !== "undefined" && typeof count !== "undefined") { - ar = bytes.subarray(offset, offset + count); - } else if (typeof offset !== "undefined") { - ar = bytes.subarray(offset); +export function toString(bytes: ArrayLike, offset?: number, count?: number) { + const array = ArrayBuffer.isView(bytes) ? bytes : Uint8Array.from(bytes); + let buffer = new Uint8Array(array.buffer, array.byteOffset, array.byteLength); + if (offset != null && count != null) { + buffer = buffer.subarray(offset, offset + count); + } else if (offset != null) { + buffer = buffer.subarray(offset); } - return Array.from(ar).map((b) => ("0" + b.toString(16)).slice(-2)).join("-"); + return Array.from(buffer).map((b) => ("0" + b.toString(16)).slice(-2)).join("-"); } diff --git a/src/fable-library/Char.ts b/src/fable-library/Char.ts index b10d9a3e68..8a071ddb7d 100644 --- a/src/fable-library/Char.ts +++ b/src/fable-library/Char.ts @@ -18,7 +18,7 @@ function decodeVByteToIntegerArray(buffer: Uint8Array) { return ret; } -function getCategory() { +function getCategoryFunc() { // unpack Unicode ranges and categories (delta encoded, vbyte encoded, utf8 encoded) const unicodeBuffer = Encoding.get_UTF8().getBytes(packedUnicode); const unicodeDeltas = decodeVByteToIntegerArray(unicodeBuffer); @@ -32,8 +32,7 @@ function getCategory() { categories[i / 2] = unicodeDeltas[i + 1]; } // binary search in unicode ranges - return (s: string, index?: number) => { - const cp = s.charCodeAt(index || 0); + return (cp: number) => { let hi = codepoints.length; let lo = 0; while (hi - lo > 1) { @@ -122,87 +121,116 @@ const isWhiteSpaceMask = 0 | 1 << UnicodeCategory.LineSeparator | 1 << UnicodeCategory.ParagraphSeparator; -export const getUnicodeCategory = getCategory(); +const unicodeCategoryFunc = getCategoryFunc(); -export function isControl(s: string, index?: number) { - const test = 1 << getUnicodeCategory(s, index); +function charCodeAt(s: string, index: number) { + if (index >= 0 && index < s.length) { + return s.charCodeAt(index); + } else { + throw Error("Index out of range."); + } +} + +export const getUnicodeCategory = (s: string) => getUnicodeCategory2(s, 0); +export const isControl = (s: string) => isControl2(s, 0); +export const isDigit = (s: string) => isDigit2(s, 0); +export const isLetter = (s: string) => isLetter2(s, 0); +export const isLetterOrDigit = (s: string) => isLetterOrDigit2(s, 0); +export const isUpper = (s: string) => isUpper2(s, 0); +export const isLower = (s: string) => isLower2(s, 0); +export const isNumber = (s: string) => isNumber2(s, 0); +export const isPunctuation = (s: string) => isPunctuation2(s, 0); +export const isSeparator = (s: string) => isSeparator2(s, 0); +export const isSymbol = (s: string) => isSymbol2(s, 0); +export const isWhiteSpace = (s: string) => isWhiteSpace2(s, 0); +export const isHighSurrogate = (s: string) => isHighSurrogate2(s, 0); +export const isLowSurrogate = (s: string) => isLowSurrogate2(s, 0); +export const isSurrogate = (s: string) => isSurrogate2(s, 0); + +export function getUnicodeCategory2(s: string, index: number) { + const cp = charCodeAt(s, index); + return unicodeCategoryFunc(cp); +} + +export function isControl2(s: string, index: number) { + const test = 1 << getUnicodeCategory2(s, index); return (test & isControlMask) !== 0; } -export function isDigit(s: string, index?: number) { - const test = 1 << getUnicodeCategory(s, index); +export function isDigit2(s: string, index: number) { + const test = 1 << getUnicodeCategory2(s, index); return (test & isDigitMask) !== 0; } -export function isLetter(s: string, index?: number) { - const test = 1 << getUnicodeCategory(s, index); +export function isLetter2(s: string, index: number) { + const test = 1 << getUnicodeCategory2(s, index); return (test & isLetterMask) !== 0; } -export function isLetterOrDigit(s: string, index?: number) { - const test = 1 << getUnicodeCategory(s, index); +export function isLetterOrDigit2(s: string, index: number) { + const test = 1 << getUnicodeCategory2(s, index); return (test & isLetterOrDigitMask) !== 0; } -export function isUpper(s: string, index?: number) { - const test = 1 << getUnicodeCategory(s, index); +export function isUpper2(s: string, index: number) { + const test = 1 << getUnicodeCategory2(s, index); return (test & isUpperMask) !== 0; } -export function isLower(s: string, index?: number) { - const test = 1 << getUnicodeCategory(s, index); +export function isLower2(s: string, index: number) { + const test = 1 << getUnicodeCategory2(s, index); return (test & isLowerMask) !== 0; } -export function isNumber(s: string, index?: number) { - const test = 1 << getUnicodeCategory(s, index); +export function isNumber2(s: string, index: number) { + const test = 1 << getUnicodeCategory2(s, index); return (test & isNumberMask) !== 0; } -export function isPunctuation(s: string, index?: number) { - const test = 1 << getUnicodeCategory(s, index); +export function isPunctuation2(s: string, index: number) { + const test = 1 << getUnicodeCategory2(s, index); return (test & isPunctuationMask) !== 0; } -export function isSeparator(s: string, index?: number) { - const test = 1 << getUnicodeCategory(s, index); +export function isSeparator2(s: string, index: number) { + const test = 1 << getUnicodeCategory2(s, index); return (test & isSeparatorMask) !== 0; } -export function isSymbol(s: string, index?: number) { - const test = 1 << getUnicodeCategory(s, index); +export function isSymbol2(s: string, index: number) { + const test = 1 << getUnicodeCategory2(s, index); return (test & isSymbolMask) !== 0; } -export function isWhiteSpace(s: string, index?: number) { - const test = 1 << getUnicodeCategory(s, index); +export function isWhiteSpace2(s: string, index: number) { + const test = 1 << getUnicodeCategory2(s, index); if ((test & isWhiteSpaceMask) !== 0) { return true; } - const cp = s.charCodeAt(index || 0); + const cp = charCodeAt(s, index); return (0x09 <= cp && cp <= 0x0D) || cp === 0x85 || cp === 0xA0; } -export function isHighSurrogate(s: string, index?: number) { - const cp = s.charCodeAt(index || 0); +export function isHighSurrogate2(s: string, index: number) { + const cp = charCodeAt(s, index); return (0xD800 <= cp && cp <= 0xDBFF); } -export function isLowSurrogate(s: string, index?: number) { - const cp = s.charCodeAt(index || 0); +export function isLowSurrogate2(s: string, index: number) { + const cp = charCodeAt(s, index); return (0xDC00 <= cp && cp <= 0xDFFF); } -export function isSurrogate(s: string, index?: number) { - const cp = s.charCodeAt(index || 0); +export function isSurrogate2(s: string, index: number) { + const cp = charCodeAt(s, index); return (0xD800 <= cp && cp <= 0xDFFF); } -export function isSurrogatePair(s: string, index: string|number) { +export function isSurrogatePair(s: string, index: string | number) { return typeof index === "number" - ? isHighSurrogate(s, index) && isLowSurrogate(s, index + 1) + ? isHighSurrogate2(s, index) && isLowSurrogate2(s, index + 1) : isHighSurrogate(s) && isLowSurrogate(index); - } +} export function parse(input: string) { if (input.length === 1) { diff --git a/src/fable-library/Date.ts b/src/fable-library/Date.ts index 36f2f5121d..28cec305a0 100644 --- a/src/fable-library/Date.ts +++ b/src/fable-library/Date.ts @@ -8,7 +8,7 @@ * Basically; invariant: date.getTime() always return UTC time. */ -import { fromValue, ticksToUnixEpochMilliseconds, unixEpochMillisecondsToTicks } from "./Long"; +import { fromValue, Long, ticksToUnixEpochMilliseconds, unixEpochMillisecondsToTicks } from "./Long"; import { compareDates, DateKind, dateOffset, IDateTime, IDateTimeOffset, padWithZeros } from "./Util"; export const offsetRegex = /(?:Z|[+-](\d+):?([0-5]?\d)?)\s*$/; @@ -53,8 +53,8 @@ function dateToISOStringWithOffset(dateWithOffset: Date, offset: number) { } function dateToStringWithCustomFormat(date: Date, format: string, utc: boolean) { - return format.replace(/(\w)\1*/g, (match: any) => { - let rep = match; + return format.replace(/(\w)\1*/g, (match: string) => { + let rep = Number.NaN; switch (match.substring(0, 1)) { case "y": const y = utc ? date.getUTCFullYear() : date.getFullYear(); @@ -69,22 +69,23 @@ function dateToStringWithCustomFormat(date: Date, format: string, utc: boolean) case "s": rep = utc ? date.getUTCSeconds() : date.getSeconds(); break; case "f": rep = utc ? date.getUTCMilliseconds() : date.getMilliseconds(); break; } - if (rep !== match && rep < 10 && match.length > 1) { - rep = "0" + rep; + if (Number.isNaN(rep)) { + return match; + } else { + return (rep < 10 && match.length > 1) ? "0" + rep : "" + rep; } - return rep; }); } function dateToStringWithOffset(date: IDateTimeOffset, format?: string) { - const d = new Date(date.getTime() + date.offset); + const d = new Date(date.getTime() + (date.offset ?? 0)); if (typeof format !== "string") { - return d.toISOString().replace(/\.\d+/, "").replace(/[A-Z]|\.\d+/g, " ") + dateOffsetToString(date.offset); + return d.toISOString().replace(/\.\d+/, "").replace(/[A-Z]|\.\d+/g, " ") + dateOffsetToString((date.offset ?? 0)); } else if (format.length === 1) { switch (format) { case "D": case "d": return dateToHalfUTCString(d, "first"); case "T": case "t": return dateToHalfUTCString(d, "second"); - case "O": case "o": return dateToISOStringWithOffset(d, date.offset); + case "O": case "o": return dateToISOStringWithOffset(d, (date.offset ?? 0)); default: throw new Error("Unrecognized Date print format"); } } else { @@ -112,7 +113,7 @@ function dateToStringWithKind(date: IDateTime, format?: string) { } } -export function toString(date: IDateTime | IDateTimeOffset, format?: string) { +export function toString(date: IDateTime | IDateTimeOffset, format?: string, _provider?: any) { return (date as IDateTimeOffset).offset != null ? dateToStringWithOffset(date, format) : dateToStringWithKind(date, format); @@ -124,7 +125,7 @@ export default function DateTime(value: number, kind?: DateKind) { return d; } -export function fromTicks(ticks: number | any, kind?: DateKind) { +export function fromTicks(ticks: number | Long, kind?: DateKind) { ticks = fromValue(ticks); kind = kind != null ? kind : DateKind.Unspecified; let date = DateTime(ticksToUnixEpochMilliseconds(ticks), kind); @@ -144,7 +145,7 @@ export function fromDateTimeOffset(date: IDateTimeOffset, kind: DateKind) { case DateKind.UTC: return DateTime(date.getTime(), DateKind.UTC); case DateKind.Local: return DateTime(date.getTime(), DateKind.Local); default: - const d = DateTime(date.getTime() + date.offset, kind); + const d = DateTime(date.getTime() + (date.offset ?? 0), kind); return DateTime(d.getTime() - dateOffset(d), kind); } } @@ -170,13 +171,14 @@ export function parseRaw(str: string) { // tslint:disable-next-line:max-line-length const m = /^\s*(\d+[^\w\s:]\d+[^\w\s:]\d+)?\s*(\d+:\d+(?::\d+(?:\.\d+)?)?)?\s*([AaPp][Mm])?\s*([+-]\d+(?::\d+)?)?\s*$/.exec(str); if (m != null) { - let baseDate: Date = null; + let baseDate: Date; let timeInSeconds = 0; if (m[2] != null) { const timeParts = m[2].split(":"); - timeInSeconds = parseInt(timeParts[0], 10) * 3600 + - parseInt(timeParts[1] || "0", 10) * 60 + - parseFloat(timeParts[2] || "0"); + timeInSeconds = + parseInt(timeParts[0], 10) * 3600 + + parseInt(timeParts[1] || "0", 10) * 60 + + parseFloat(timeParts[2] || "0"); if (m[3] != null && m[3].toUpperCase() === "PM") { timeInSeconds += 720; } @@ -223,10 +225,10 @@ export function parse(str: string, detectUTC = false): IDateTime { return DateTime(date.getTime(), kind); } -export function tryParse(v: any): [boolean, IDateTime] { +export function tryParse(v: string, _refValue?: any): [boolean, IDateTime] { try { // if value is null or whitespace, parsing fails - if (v === null || v.trim() === "") { + if (v == null || v.trim() === "") { return [false, minValue()]; } return [true, parse(v)]; @@ -236,9 +238,9 @@ export function tryParse(v: any): [boolean, IDateTime] { } export function create( - year: number, month: number, day: number, - h: number = 0, m: number = 0, s: number = 0, - ms: number = 0, kind?: DateKind) { + year: number, month: number, day: number, + h: number = 0, m: number = 0, s: number = 0, + ms: number = 0, kind?: DateKind) { const dateValue = kind === DateKind.UTC ? Date.UTC(year, month - 1, day, h, m, s, ms) : new Date(year, month - 1, day, h, m, s, ms).getTime(); @@ -282,6 +284,10 @@ export function toLocalTime(date: IDateTime) { return date.kind === DateKind.Local ? date : DateTime(date.getTime(), DateKind.Local); } +export function specifyKind(d: IDateTime, kind: DateKind) { + return create(year(d), month(d), day(d), hour(d), minute(d), second(d), millisecond(d), kind); +} + export function timeOfDay(d: IDateTime) { return hour(d) * 3600000 + minute(d) * 60000 @@ -336,27 +342,36 @@ export function dayOfYear(d: IDateTime) { } export function add(d: IDateTime, ts: number) { - return DateTime(d.getTime() + ts, d.kind); + const newDate = DateTime(d.getTime() + ts, d.kind); + if (d.kind === DateKind.Local) { + const oldTzOffset = d.getTimezoneOffset(); + const newTzOffset = newDate.getTimezoneOffset(); + return oldTzOffset !== newTzOffset + ? DateTime(newDate.getTime() + (newTzOffset - oldTzOffset) * 60000, d.kind) + : newDate; + } else { + return newDate; + } } export function addDays(d: IDateTime, v: number) { - return DateTime(d.getTime() + v * 86400000, d.kind); + return add(d, v * 86400000); } export function addHours(d: IDateTime, v: number) { - return DateTime(d.getTime() + v * 3600000, d.kind); + return add(d, v * 3600000); } export function addMinutes(d: IDateTime, v: number) { - return DateTime(d.getTime() + v * 60000, d.kind); + return add(d, v * 60000); } export function addSeconds(d: IDateTime, v: number) { - return DateTime(d.getTime() + v * 1000, d.kind); + return add(d, v * 1000); } export function addMilliseconds(d: IDateTime, v: number) { - return DateTime(d.getTime() + v, d.kind); + return add(d, v); } export function addYears(d: IDateTime, v: number) { @@ -390,7 +405,7 @@ export function addMonths(d: IDateTime, v: number) { export function subtract(d: IDateTime, that: IDateTime | number) { return typeof that === "number" - ? DateTime(d.getTime() - that, d.kind) + ? add(d, -that) : d.getTime() - that.getTime(); } @@ -421,7 +436,7 @@ export function op_Addition(x: IDateTime, y: number) { return add(x, y); } -export function op_Subtraction(x: IDateTime, y: number | Date) { +export function op_Subtraction(x: IDateTime, y: number | IDateTime) { return subtract(x, y); } diff --git a/src/fable-library/DateOffset.ts b/src/fable-library/DateOffset.ts index 73edfb6f9c..9f0d222250 100644 --- a/src/fable-library/DateOffset.ts +++ b/src/fable-library/DateOffset.ts @@ -14,7 +14,7 @@ */ import { create as createDate, dateOffsetToString, daysInMonth, offsetRegex, parseRaw } from "./Date"; -import { fromValue, ticksToUnixEpochMilliseconds, unixEpochMillisecondsToTicks } from "./Long"; +import { fromValue, Long, ticksToUnixEpochMilliseconds, unixEpochMillisecondsToTicks } from "./Long"; import { compareDates, DateKind, IDateTime, IDateTimeOffset, padWithZeros } from "./Util"; export default function DateTimeOffset(value: number, offset?: number) { @@ -34,11 +34,9 @@ export function fromDate(date: IDateTime, offset?: number) { return DateTimeOffset(date.getTime(), offset2); } -export function fromTicks(ticks: number | any, offset: number) { +export function fromTicks(ticks: number | Long, offset: number) { ticks = fromValue(ticks); - const epoc = ticksToUnixEpochMilliseconds(ticks) - offset; - return DateTimeOffset(epoc, offset); } @@ -62,13 +60,13 @@ export function parse(str: string): IDateTimeOffset { const offset = offsetMatch == null ? date.getTimezoneOffset() * -60000 : (offsetMatch[0] === "Z" - ? 0 - : parseInt(offsetMatch[1], 10) * 3600000 - + parseInt(offsetMatch[2], 10) * 60000); + ? 0 + : parseInt(offsetMatch[1], 10) * 3600000 + + parseInt(offsetMatch[2], 10) * 60000); return DateTimeOffset(date.getTime(), offset); } -export function tryParse(v: any): [boolean, IDateTimeOffset] { +export function tryParse(v: string, _refValue?: any): [boolean, IDateTimeOffset] { try { return [true, parse(v)]; } catch (_err) { @@ -77,9 +75,9 @@ export function tryParse(v: any): [boolean, IDateTimeOffset] { } export function create( - year: number, month: number, day: number, - h: number, m: number, s: number, - ms: number, offset: number) { + year: number, month: number, day: number, + h: number, m: number, s: number, + ms: number, offset?: number) { if (offset == null) { offset = ms; ms = 0; @@ -99,14 +97,15 @@ export function create( date.setFullYear(year, month - 1, day); } } else { - const str = padWithZeros(year, 4) + "-" + - padWithZeros(month, 2) + "-" + - padWithZeros(day, 2) + "T" + - padWithZeros(h, 2) + ":" + - padWithZeros(m, 2) + ":" + - padWithZeros(s, 2) + "." + - padWithZeros(ms, 3) + - dateOffsetToString(offset); + const str = + padWithZeros(year, 4) + "-" + + padWithZeros(month, 2) + "-" + + padWithZeros(day, 2) + "T" + + padWithZeros(h, 2) + ":" + + padWithZeros(m, 2) + ":" + + padWithZeros(s, 2) + "." + + padWithZeros(ms, 3) + + dateOffsetToString(offset); date = new Date(str); } const dateValue = date.getTime(); @@ -136,7 +135,7 @@ export function toLocalTime(date: Date) { } export function timeOfDay(d: IDateTimeOffset) { - const d2 = new Date(d.getTime() + d.offset); + const d2 = new Date(d.getTime() + (d.offset ?? 0)); return d2.getUTCHours() * 3600000 + d2.getUTCMinutes() * 60000 + d2.getUTCSeconds() * 1000 @@ -144,44 +143,44 @@ export function timeOfDay(d: IDateTimeOffset) { } export function date(d: IDateTimeOffset) { - const d2 = new Date(d.getTime() + d.offset); + const d2 = new Date(d.getTime() + (d.offset ?? 0)); return createDate(d2.getUTCFullYear(), d2.getUTCMonth() + 1, d2.getUTCDate(), 0, 0, 0, 0); } export function day(d: IDateTimeOffset) { - return new Date(d.getTime() + d.offset).getUTCDate(); + return new Date(d.getTime() + (d.offset ?? 0)).getUTCDate(); } export function hour(d: IDateTimeOffset) { - return new Date(d.getTime() + d.offset).getUTCHours(); + return new Date(d.getTime() + (d.offset ?? 0)).getUTCHours(); } export function millisecond(d: IDateTimeOffset) { - return new Date(d.getTime() + d.offset).getUTCMilliseconds(); + return new Date(d.getTime() + (d.offset ?? 0)).getUTCMilliseconds(); } export function minute(d: IDateTimeOffset) { - return new Date(d.getTime() + d.offset).getUTCMinutes(); + return new Date(d.getTime() + (d.offset ?? 0)).getUTCMinutes(); } export function month(d: IDateTimeOffset) { - return new Date(d.getTime() + d.offset).getUTCMonth() + 1; + return new Date(d.getTime() + (d.offset ?? 0)).getUTCMonth() + 1; } export function second(d: IDateTimeOffset) { - return new Date(d.getTime() + d.offset).getUTCSeconds(); + return new Date(d.getTime() + (d.offset ?? 0)).getUTCSeconds(); } export function year(d: IDateTimeOffset) { - return new Date(d.getTime() + d.offset).getUTCFullYear(); + return new Date(d.getTime() + (d.offset ?? 0)).getUTCFullYear(); } export function dayOfWeek(d: IDateTimeOffset) { - return new Date(d.getTime() + d.offset).getUTCDay(); + return new Date(d.getTime() + (d.offset ?? 0)).getUTCDay(); } export function dayOfYear(d: IDateTimeOffset) { - const d2 = new Date(d.getTime() + d.offset); + const d2 = new Date(d.getTime() + (d.offset ?? 0)); const _year = d2.getUTCFullYear(); const _month = d2.getUTCMonth() + 1; let _day = d2.getUTCDate(); @@ -192,27 +191,27 @@ export function dayOfYear(d: IDateTimeOffset) { } export function add(d: IDateTimeOffset, ts: number) { - return DateTimeOffset(d.getTime() + ts, d.offset); + return DateTimeOffset(d.getTime() + ts, (d.offset ?? 0)); } export function addDays(d: IDateTimeOffset, v: number) { - return DateTimeOffset(d.getTime() + v * 86400000, d.offset); + return DateTimeOffset(d.getTime() + v * 86400000, (d.offset ?? 0)); } export function addHours(d: IDateTimeOffset, v: number) { - return DateTimeOffset(d.getTime() + v * 3600000, d.offset); + return DateTimeOffset(d.getTime() + v * 3600000, (d.offset ?? 0)); } export function addMinutes(d: IDateTimeOffset, v: number) { - return DateTimeOffset(d.getTime() + v * 60000, d.offset); + return DateTimeOffset(d.getTime() + v * 60000, (d.offset ?? 0)); } export function addSeconds(d: IDateTimeOffset, v: number) { - return DateTimeOffset(d.getTime() + v * 1000, d.offset); + return DateTimeOffset(d.getTime() + v * 1000, (d.offset ?? 0)); } export function addMilliseconds(d: IDateTimeOffset, v: number) { - return DateTimeOffset(d.getTime() + v, d.offset); + return DateTimeOffset(d.getTime() + v, (d.offset ?? 0)); } export function addYears(d: IDateTimeOffset, v: number) { @@ -221,11 +220,11 @@ export function addYears(d: IDateTimeOffset, v: number) { const _daysInMonth = daysInMonth(newYear, newMonth); const newDay = Math.min(_daysInMonth, d.getUTCDate()); return create(newYear, newMonth, newDay, d.getUTCHours(), d.getUTCMinutes(), - d.getUTCSeconds(), d.getUTCMilliseconds(), d.offset); + d.getUTCSeconds(), d.getUTCMilliseconds(), (d.offset ?? 0)); } export function addMonths(d: IDateTimeOffset, v: number) { - const d2 = new Date(d.getTime() + d.offset); + const d2 = new Date(d.getTime() + (d.offset ?? 0)); let newMonth = d2.getUTCMonth() + 1 + v; let newMonth_ = 0; let yearOffset = 0; @@ -242,12 +241,12 @@ export function addMonths(d: IDateTimeOffset, v: number) { const _daysInMonth = daysInMonth(newYear, newMonth); const newDay = Math.min(_daysInMonth, d2.getUTCDate()); return create(newYear, newMonth, newDay, d2.getUTCHours(), d2.getUTCMinutes(), - d2.getUTCSeconds(), d2.getUTCMilliseconds(), d.offset); + d2.getUTCSeconds(), d2.getUTCMilliseconds(), (d.offset ?? 0)); } export function subtract(d: IDateTimeOffset, that: IDateTimeOffset | number) { return typeof that === "number" - ? DateTimeOffset(d.getTime() - that, d.offset) + ? DateTimeOffset(d.getTime() - that, (d.offset ?? 0)) : d.getTime() - that.getTime(); } diff --git a/src/fable-library/Decimal.ts b/src/fable-library/Decimal.ts index 30d2a0ed9c..757f07ef5b 100644 --- a/src/fable-library/Decimal.ts +++ b/src/fable-library/Decimal.ts @@ -1,6 +1,7 @@ import Decimal from "./lib/big"; export default Decimal; +export type decimal = Decimal; export const get_Zero = new Decimal(0); export const get_One = new Decimal(1); @@ -21,7 +22,7 @@ export function abs(x: Decimal) { } export function round(x: Decimal, digits: number = 0) { - return x.round(digits, x.cmp(0) >= 0 ? 1 /* ROUND_HALF_UP */ : 2 /* ROUND_HALF_EVEN */); + return x.round(digits, 2 /* ROUND_HALF_EVEN */); } export function truncate(x: Decimal) { @@ -190,3 +191,20 @@ export function getBits(d: Decimal) { const signExp = ((scale & 0x7F) << 16) | (d.s < 0 ? 0x80000000 : 0); return [low, mid, high, signExp]; } + +export function makeRangeStepFunction(step: Decimal, last: Decimal) { + const stepComparedWithZero = step.cmp(get_Zero); + if (stepComparedWithZero === 0) { + throw new Error("The step of a range cannot be zero"); + } + const stepGreaterThanZero = stepComparedWithZero > 0; + return (x: Decimal) => { + const comparedWithLast = x.cmp(last); + if ((stepGreaterThanZero && comparedWithLast <= 0) + || (!stepGreaterThanZero && comparedWithLast >= 0)) { + return [x, op_Addition(x, step)]; + } else { + return null; + } + }; +} diff --git a/src/fable-library/DictTypes.js b/src/fable-library/DictTypes.js deleted file mode 100644 index 35bcc8a191..0000000000 --- a/src/fable-library/DictTypes.js +++ /dev/null @@ -1,32 +0,0 @@ -import { createMutable as createMutableMap } from "./Map"; -import { createMutable as createMutableSet } from "./Set"; -import { declare } from "./Types"; - -export const Dictionary = declare(function Dictionary(source, comparer) { - this.__mutableMap = createMutableMap(source, comparer); -}); -Object.defineProperty(Dictionary.prototype, "size", { get: function() { - return this.__mutableMap.size; -}}); -Dictionary.prototype.clear = function() { return this.__mutableMap.clear(); }; -Dictionary.prototype.delete = function(k) { return this.__mutableMap.delete(k); }; -Dictionary.prototype.entries = function() { return this.__mutableMap.entries(); }; -Dictionary.prototype.get = function(k) { return this.__mutableMap.get(k); }; -Dictionary.prototype.has = function(k) { return this.__mutableMap.has(k); }; -Dictionary.prototype.keys = function() { return this.__mutableMap.keys(); }; -Dictionary.prototype.set = function(k, v) { return this.__mutableMap.set(k, v); }; -Dictionary.prototype.values = function() { return this.__mutableMap.values(); }; -Dictionary.prototype[Symbol.iterator] = function() { return this.__mutableMap[Symbol.iterator](); }; - -export const HashSet = declare(function HashSet(source, comparer) { - this.__mutableSet = createMutableSet(source, comparer); -}); -Object.defineProperty(HashSet.prototype, "size", { get: function() { - return this.__mutableSet.size; -}}); -HashSet.prototype.add = function(v) { return this.__mutableSet.add(v); }; -HashSet.prototype.clear = function() { return this.__mutableSet.clear(); }; -HashSet.prototype.delete = function(k) { return this.__mutableSet.delete(k); }; -HashSet.prototype.has = function(k) { return this.__mutableSet.has(k); }; -HashSet.prototype.values = function() { return this.__mutableSet.values(); }; -HashSet.prototype[Symbol.iterator] = function() { return this.__mutableSet[Symbol.iterator](); }; diff --git a/src/fable-library/Encoding.ts b/src/fable-library/Encoding.ts index 9b9b85ba51..e1e078c240 100644 --- a/src/fable-library/Encoding.ts +++ b/src/fable-library/Encoding.ts @@ -1,4 +1,4 @@ -// Polyfills +import { uint8 } from "./Int32"; const littleEndian = true; @@ -12,8 +12,9 @@ function utf16le_encode(str: string) { return bytes; } -function utf16le_decode(bytes: Uint8Array) { - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); +function utf16le_decode(bytes: ArrayLike) { + const array = ArrayBuffer.isView(bytes) ? bytes : Uint8Array.from(bytes); + const view = new DataView(array.buffer, array.byteOffset, array.byteLength); const chars = new Array(view.byteLength / 2); for (let i = 0; i < chars.length; i++) { const code = view.getUint16(i * 2, littleEndian); @@ -58,7 +59,7 @@ function utf8_encode(str: string) { return buf; } -function utf8_decode(bytes: Uint8Array) { +function utf8_decode(bytes: ArrayLike) { let pos = 0; const decodeUtf8 = () => { const i1 = bytes[pos++]; @@ -91,20 +92,33 @@ function utf8_decode(bytes: Uint8Array) { class UTF16LE { public getBytes(str: string, index?: number, count?: number) { - if (index != null) { str = str.substring(index, index + count); } + if (index != null && count != null) { + str = str.substring(index, index + count); + } else if (index != null) { + str = str.substring(index); + } if (typeof Buffer !== "undefined") { - return Buffer.from(str, "utf16le"); + const bytes = Buffer.from(str, "utf16le"); + return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); } else { return utf16le_encode(str); // polyfill } } - public getString(bytes: Uint8Array, index?: number, count?: number) { - if (index != null) { bytes = bytes.subarray(index, index + count); } - if (typeof Buffer !== "undefined") { - return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("utf16le"); + public getString(bytes: ArrayLike, index?: number, count?: number) { + const array = ArrayBuffer.isView(bytes) ? bytes : Uint8Array.from(bytes); + let buffer = new Uint8Array(array.buffer, array.byteOffset, array.byteLength); + if (index != null && count != null) { + buffer = buffer.subarray(index, index + count); + } else if (index != null) { + buffer = buffer.subarray(index); + } + if (typeof TextDecoder !== "undefined") { + return new TextDecoder("utf-16le").decode(buffer); + } else if (typeof Buffer !== "undefined") { + return Buffer.from(buffer).toString("utf16le"); } else { - return utf16le_decode(bytes); // polyfill + return utf16le_decode(buffer); // polyfill } } @@ -113,24 +127,35 @@ class UTF16LE { class UTF8 { public getBytes(str: string, index?: number, count?: number) { - if (index != null) { str = str.substring(index, index + count); } + if (index != null && count != null) { + str = str.substring(index, index + count); + } else if (index != null) { + str = str.substring(index); + } if (typeof TextEncoder !== "undefined") { return new TextEncoder().encode(str); } else if (typeof Buffer !== "undefined") { - return Buffer.from(str, "utf8"); + const bytes = Buffer.from(str, "utf8"); + return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); } else { return utf8_encode(str); // polyfill } } - public getString(bytes: Uint8Array, index?: number, count?: number) { - if (index != null) { bytes = bytes.subarray(index, index + count); } + public getString(bytes: ArrayLike, index?: number, count?: number) { + const array = ArrayBuffer.isView(bytes) ? bytes : Uint8Array.from(bytes); + let buffer = new Uint8Array(array.buffer, array.byteOffset, array.byteLength); + if (index != null && count != null) { + buffer = buffer.subarray(index, index + count); + } else if (index != null) { + buffer = buffer.subarray(index); + } if (typeof TextDecoder !== "undefined") { - return new TextDecoder().decode(bytes); + return new TextDecoder().decode(buffer); } else if (typeof Buffer !== "undefined") { - return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("utf8"); + return Buffer.from(buffer).toString("utf8"); } else { - return utf8_decode(bytes); // polyfill + return utf8_decode(buffer); // polyfill } } diff --git a/src/fable-library/Event.ts b/src/fable-library/Event.ts index c1be63f75d..bcbb3e31ea 100644 --- a/src/fable-library/Event.ts +++ b/src/fable-library/Event.ts @@ -1,5 +1,5 @@ import { IObservable, IObserver, Observer, protect } from "./Observable"; -import { Choice, tryValueIfChoice1, tryValueIfChoice2, value } from "./Option"; +import { Choice, Option, some, tryValueIfChoice1, tryValueIfChoice2, value } from "./Option"; import { iterate as seqIterate } from "./Seq"; import { IDisposable } from "./Util"; @@ -18,8 +18,8 @@ export interface IEvent extends IObservable, IDelegateEvent { export default class Event implements IEvent { public delegates: Array>; - private _subscriber: (o: IObserver) => IDisposable; - private _dotnetDelegates: Map, Delegate>; + private _subscriber?: (o: IObserver) => IDisposable; + private _dotnetDelegates?: Map, Delegate>; constructor(_subscriber?: (o: IObserver) => IDisposable, delegates?: any[]) { this._subscriber = _subscriber; @@ -100,7 +100,7 @@ export function add(callback: (x: T) => void, sourceEvent: IEvent) { (sourceEvent as Event).Subscribe(new Observer(callback)); } -export function choose(chooser: (x: T) => U, sourceEvent: IEvent) { +export function choose(chooser: (x: T) => Option, sourceEvent: IEvent) { const source = sourceEvent as Event; return new Event((observer) => source.Subscribe(new Observer((t) => @@ -109,11 +109,11 @@ export function choose(chooser: (x: T) => U, sourceEvent: IEvent) { (u) => { if (u != null) { observer.OnNext(value(u)); } }, observer.OnError), observer.OnError, observer.OnCompleted)), - source.delegates) as IEvent; + source.delegates); } export function filter(predicate: (x: T) => boolean, sourceEvent: IEvent) { - return choose((x) => predicate(x) ? x : null, sourceEvent); + return choose((x) => predicate(x) ? some(x) : null, sourceEvent); } export function map(mapping: (x: T) => U, sourceEvent: IEvent) { @@ -125,7 +125,7 @@ export function map(mapping: (x: T) => U, sourceEvent: IEvent) { observer.OnNext, observer.OnError), observer.OnError, observer.OnCompleted)), - source.delegates) as IEvent; + source.delegates); } export function merge(event1: IEvent, event2: IEvent) { @@ -178,23 +178,23 @@ export function merge(event1: IEvent, event2: IEvent) { h2.Dispose(); }, } as IDisposable; - }, source1.delegates.concat(source2.delegates)) as IEvent; + }, source1.delegates.concat(source2.delegates)); } export function pairwise(sourceEvent: IEvent) { const source = sourceEvent as Event; return new Event<[T, T]>((observer) => { - let last: T = null; + let last: T; return source.Subscribe(new Observer((next) => { if (last != null) { observer.OnNext([last, next]); } last = next; }, observer.OnError, observer.OnCompleted)); - }, source.delegates) as IEvent<[T, T]>; + }, source.delegates); } -export function partition(predicate: (x: T) => boolean, sourceEvent: IEvent) { +export function partition(predicate: (x: T) => boolean, sourceEvent: IEvent): [IEvent, IEvent] { return [filter(predicate, sourceEvent), filter((x) => !predicate(x), sourceEvent)]; } @@ -207,10 +207,10 @@ export function scan(collector: (u: U, t: T) => U, state: U, sourceEvent: (u) => { state = u; observer.OnNext(u); }, observer.OnError); }, observer.OnError, observer.OnCompleted)); - }, source.delegates) as IEvent; + }, source.delegates); } -export function split(splitter: (x: T) => /* Choice */ any, sourceEvent: IEvent) { +export function split(splitter: (x: T) => Choice, sourceEvent: IEvent): [IEvent, IEvent] { return [ choose((v) => tryValueIfChoice1(splitter(v)), sourceEvent), choose((v) => tryValueIfChoice2(splitter(v)), sourceEvent), diff --git a/src/fable-library/ExprUtils.fs b/src/fable-library/ExprUtils.fs index 1290757d41..8c3ed7f922 100644 --- a/src/fable-library/ExprUtils.fs +++ b/src/fable-library/ExprUtils.fs @@ -26,7 +26,7 @@ type ILiteral = type BinaryStream(arr : byte[]) = - let view = DataView.Create(arr.buffer, arr?byteOffset, arr?byteLength) + let view = Constructors.DataView.Create(arr.buffer, arr?byteOffset, arr?byteLength) let mutable position = 0 member x.Position = position diff --git a/src/fable-library/FSharp.Collections.fs b/src/fable-library/FSharp.Collections.fs index 7ee4b6a4bd..25f13a04ef 100644 --- a/src/fable-library/FSharp.Collections.fs +++ b/src/fable-library/FSharp.Collections.fs @@ -5,16 +5,16 @@ open System.Collections.Generic module HashIdentity = let FromFunctions hash eq : IEqualityComparer<'T> = { new IEqualityComparer<'T> with - member __.GetHashCode(x) = hash x - member __.Equals(x,y) = eq x y } + member __.Equals(x, y) = eq x y + member __.GetHashCode(x) = hash x } let Structural<'T when 'T : equality> : IEqualityComparer<'T> = FromFunctions LanguagePrimitives.GenericHash LanguagePrimitives.GenericEquality let Reference<'T when 'T : not struct > : IEqualityComparer<'T> = FromFunctions LanguagePrimitives.PhysicalHash LanguagePrimitives.PhysicalEquality -module ComparisonIdentity = +module ComparisonIdentity = let FromFunction comparer : IComparer<'T> = { new IComparer<'T> with - member __.Compare(x,y) = comparer x y } + member __.Compare(x, y) = comparer x y } let Structural<'T when 'T : comparison> : IComparer<'T> = FromFunction LanguagePrimitives.GenericComparison diff --git a/src/fable-library/FSharp.Core.fs b/src/fable-library/FSharp.Core.fs index a0d35ddf33..2ffe2b8d26 100644 --- a/src/fable-library/FSharp.Core.fs +++ b/src/fable-library/FSharp.Core.fs @@ -3,12 +3,12 @@ namespace FSharp.Core module LanguagePrimitives = let GenericEqualityComparer = { new System.Collections.IEqualityComparer with - override __.Equals(x:obj,y:obj) = LanguagePrimitives.GenericEquality x y - override __.GetHashCode(x:obj) = LanguagePrimitives.GenericHash x } + override __.Equals(x: obj, y: obj) = LanguagePrimitives.GenericEquality x y + override __.GetHashCode(x: obj) = LanguagePrimitives.GenericHash x } let GenericEqualityERComparer = { new System.Collections.IEqualityComparer with - override __.Equals(x:obj,y:obj) = LanguagePrimitives.GenericEqualityER x y - override __.GetHashCode(x:obj) = LanguagePrimitives.GenericHash x } + override __.Equals(x: obj, y: obj) = LanguagePrimitives.GenericEqualityER x y + override __.GetHashCode(x: obj) = LanguagePrimitives.GenericHash x } let FastGenericComparer<'T when 'T : comparison> = FSharp.Collections.ComparisonIdentity.Structural<'T> let FastGenericComparerFromTable<'T when 'T : comparison> = @@ -28,19 +28,24 @@ module Operators = [] let nullArg x = raise(System.ArgumentNullException(x)) + [] + let using (resource : 'T when 'T :> System.IDisposable) (action: 'T -> 'a) = + try action(resource) + finally match (box resource) with null -> () | _ -> resource.Dispose() + [] let lock _lockObj action = action() // no locking, just invoke module ExtraTopLevelOperators = [] - let (|Lazy|) (input:Lazy<_>) = input.Force() + let (|Lazy|) (input: Lazy<_>) = input.Force() [] module Printf = [] let kbprintf continuation (builder: System.Text.StringBuilder) format = - let append (s:string) = builder.Append(s) |> ignore; continuation() + let append (s: string) = builder.Append(s) |> ignore; continuation() Printf.kprintf append format [] diff --git a/src/fable-library/Fable.Library.fsproj b/src/fable-library/Fable.Library.fsproj index e238578c5c..246c709239 100644 --- a/src/fable-library/Fable.Library.fsproj +++ b/src/fable-library/Fable.Library.fsproj @@ -10,8 +10,11 @@ + + + @@ -20,6 +23,6 @@ - + \ No newline at end of file diff --git a/src/fable-library/Int32.ts b/src/fable-library/Int32.ts index a9fa2559ab..3f9df2f214 100644 --- a/src/fable-library/Int32.ts +++ b/src/fable-library/Int32.ts @@ -1,3 +1,15 @@ +export type int8 = number; +export type uint8 = number; +export type int16 = number; +export type uint16 = number; +export type int32 = number; +export type uint32 = number; +// export type int64 = Long; +// export type uint64 = Long; +export type float32 = number; +export type float64 = number; +// export type decimal = Decimal; + export enum NumberStyles { // None = 0x00000000, // AllowLeadingWhite = 0x00000001, @@ -24,7 +36,7 @@ export enum NumberStyles { } function validResponse(regexMatch: RegExpExecArray, radix: number) { - const [_all, sign, prefix, digits] = regexMatch; + const [/*all*/, sign, prefix, digits] = regexMatch; return { sign: sign || "", prefix: prefix || "", @@ -68,9 +80,9 @@ function getRadix(prefix: string, style: number) { export function isValid(str: string, style: number, radix?: number) { const integerRegex = /^\s*([\+\-])?(0[xXoObB])?([0-9a-fA-F]+)\s*$/; - const res = integerRegex.exec(str.replace("_", "")); + const res = integerRegex.exec(str.replace(/_/g, "")); if (res != null) { - const [_all, sign, prefix, digits] = res; + const [/*all*/, /*sign*/, prefix, digits] = res; radix = radix || getRadix(prefix, style); const invalidDigits = getInvalidDigits(radix); if (!invalidDigits.test(digits)) { diff --git a/src/fable-library/List.fs b/src/fable-library/List.fs index 33ad09a165..9d1d7d14b2 100644 --- a/src/fable-library/List.fs +++ b/src/fable-library/List.fs @@ -68,7 +68,7 @@ let ofSeq (xs: 'a seq): 'a list = Seq.fold (fun acc x -> x::acc) [] xs |> reverse -let concat (lists : #seq<'a list>) = +let concat (lists: seq<'a list>) = Seq.fold (fold (fun acc x -> x::acc)) [] lists |> reverse @@ -100,7 +100,7 @@ let rec foldIndexed3Aux f i acc bs cs ds = | x::xs, y::ys, z::zs -> foldIndexed3Aux f (i+1) (f i acc x y z) xs ys zs | _ -> invalidOp "Lists had different lengths" -let foldIndexed3<'a, 'b, 'c, 'acc> f (seed:'acc) (xs: 'a list) (ys: 'b list) (zs: 'c list) = +let foldIndexed3<'a, 'b, 'c, 'acc> f (seed: 'acc) (xs: 'a list) (ys: 'b list) (zs: 'c list) = foldIndexed3Aux f 0 seed xs ys zs let fold3<'a, 'b, 'c, 'acc> f (state: 'acc) (xs: 'a list) (ys: 'b list) (zs: 'c list) = @@ -118,7 +118,7 @@ let length xs = let append xs ys = fold (fun acc x -> x::acc) ys (reverse xs) -let collect f (xs: 'a list) = +let collect (f: 'a -> 'b list) (xs: 'a list) = Seq.collect f xs |> ofSeq let map f xs = @@ -260,7 +260,6 @@ let choose f xs = | Some y -> y:: acc | None -> acc) [] xs |> reverse - let contains<'T> (value: 'T) (list: 'T list) ([] eq: IEqualityComparer<'T>) = let rec loop xs = match xs with @@ -279,8 +278,8 @@ let except (itemsToExclude: seq<'t>) (array: 't list) ([] eq: IEqualityC let initialize n f = let mutable xs = [] - for i = 1 to n do xs <- f (n - i):: xs - xs + for i = 0 to n-1 do xs <- (f i)::xs + reverse xs let replicate n x = initialize n (fun _ -> x) @@ -321,19 +320,19 @@ let zip xs ys = let zip3 xs ys zs = map3 (fun x y z -> x, y, z) xs ys zs -let sort (xs : 'T list) ([] comparer: IComparer<'T>): 'T list = +let sort (xs: 'T list) ([] comparer: IComparer<'T>): 'T list = Array.sortInPlaceWith (fun x y -> comparer.Compare(x, y)) (List.toArray xs) |> ofArray -let sortBy (projection:'a->'b) (xs : 'a list) ([] comparer: IComparer<'b>): 'a list = +let sortBy (projection: 'a -> 'b) (xs: 'a list) ([] comparer: IComparer<'b>): 'a list = Array.sortInPlaceWith (fun x y -> comparer.Compare(projection x, projection y)) (List.toArray xs) |> ofArray -let sortDescending (xs : 'T list) ([] comparer: IComparer<'T>): 'T list = +let sortDescending (xs: 'T list) ([] comparer: IComparer<'T>): 'T list = Array.sortInPlaceWith (fun x y -> comparer.Compare(x, y) * -1) (List.toArray xs) |> ofArray -let sortByDescending (projection:'a->'b) (xs : 'a list) ([] comparer: IComparer<'b>): 'a list = +let sortByDescending (projection: 'a -> 'b) (xs: 'a list) ([] comparer: IComparer<'b>): 'a list = Array.sortInPlaceWith (fun x y -> comparer.Compare(projection x, projection y) * -1) (List.toArray xs) |> ofArray -let sortWith (comparer: 'T -> 'T -> int) (xs : 'T list): 'T list = +let sortWith (comparer: 'T -> 'T -> int) (xs: 'T list): 'T list = Array.sortInPlaceWith comparer (List.toArray xs) |> ofArray let sum (xs: 'T list) ([] adder: IGenericAdder<'T>): 'T = @@ -342,16 +341,16 @@ let sum (xs: 'T list) ([] adder: IGenericAdder<'T>): 'T = let sumBy (f: 'T -> 'T2) (xs: 'T list) ([] adder: IGenericAdder<'T2>): 'T2 = fold (fun acc x -> adder.Add(acc, f x)) (adder.GetZero()) xs -let maxBy (projection:'a->'b) (xs:'a list) ([] comparer: IComparer<'b>): 'a = +let maxBy (projection: 'a -> 'b) (xs: 'a list) ([] comparer: IComparer<'b>): 'a = reduce (fun x y -> if comparer.Compare(projection y, projection x) > 0 then y else x) xs let max (li:'a list) ([] comparer: IComparer<'a>): 'a = reduce (fun x y -> if comparer.Compare(y, x) > 0 then y else x) li -let minBy (projection:'a->'b) (xs:'a list) ([] comparer: IComparer<'b>): 'a = +let minBy (projection: 'a -> 'b) (xs: 'a list) ([] comparer: IComparer<'b>): 'a = reduce (fun x y -> if comparer.Compare(projection y, projection x) > 0 then x else y) xs -let min (xs:'a list) ([] comparer: IComparer<'a>): 'a = +let min (xs: 'a list) ([] comparer: IComparer<'a>): 'a = reduce (fun x y -> if comparer.Compare(y, x) > 0 then x else y) xs let average (xs: 'T list) ([] averager: IGenericAverager<'T>): 'T = @@ -368,6 +367,13 @@ let permute f xs = |> Array.permute f |> ofArray +let chunkBySize (chunkSize: int) (xs: 'T list): 'T list list = + xs + |> List.toArray + |> Array.chunkBySize chunkSize + |> ofArray + |> map ofArray + let skip i xs = let rec skipInner i xs = match i, xs with @@ -442,7 +448,7 @@ let slice (lower: int option) (upper: int option) (xs: 'T list) = if lower > (lastIndex + 1) || (hasUpper && upper.Value > lastIndex) then outOfRange() reverse res -let distinctBy (projection: 'T -> 'Key) (xs:'T list) ([] eq: IEqualityComparer<'Key>) = +let distinctBy (projection: 'T -> 'Key) (xs: 'T list) ([] eq: IEqualityComparer<'Key>) = let hashSet = HashSet<'Key>(eq) xs |> filter (projection >> hashSet.Add) @@ -452,51 +458,45 @@ let distinct (xs: 'T list) ([] eq: IEqualityComparer<'T>) = let exactlyOne (xs: 'T list) = match xs with | [] -> invalidArg "list" LanguagePrimitives.ErrorStrings.InputSequenceEmptyString - | x::[] -> x + | [x] -> x | x1::x2::xs -> invalidArg "list" "Input list too long" let groupBy (projection: 'T -> 'Key) (xs: 'T list)([] eq: IEqualityComparer<'Key>): ('Key * 'T list) list = let dict = Dictionary<'Key, 'T list>(eq) - let keys = ResizeArray() - for v in xs do + let mutable keys = [] + xs |> iterate (fun v -> let key = projection v match dict.TryGetValue(key) with | true, prev -> dict.[key] <- v::prev | false, _ -> dict.Add(key, [v]) - keys.Add(key) - keys |> Seq.map (fun key -> key, reverse dict.[key]) |> ofSeq + keys <- key::keys ) + let mutable result = [] + keys |> iterate (fun key -> result <- (key, reverse dict.[key]) :: result) + result let countBy (projection: 'T -> 'Key) (xs: 'T list)([] eq: IEqualityComparer<'Key>) = - let dict = Dictionary<'Key, int ref>(eq) - iterate (fun v -> + let dict = Dictionary<'Key, int>(eq) + let mutable keys = [] + xs |> iterate (fun v -> let key = projection v match dict.TryGetValue(key) with - | true, prev -> prev.contents <- prev.contents + 1 + | true, prev -> + dict.[key] <- prev + 1 | false, _ -> - dict.[key] <- ref 1) xs - + dict.[key] <- 1 + keys <- key::keys ) let mutable result = [] - for group in dict do - result <- (group.Key, group.Value.contents)::result + keys |> iterate (fun key -> result <- (key, dict.[key]) :: result) result -let where predicate xs = filter predicate xs +let where predicate source = + filter predicate source -let pairwise xs = - let rec inner xs acc x1 = - match xs with - | [] -> ofArray acc - | x2::xs -> - acc.Add((x1, x2)) - inner xs acc x2 - match xs with - | [] | [_] -> [] - | x1::x2::xs -> - let acc = ResizeArray() - acc.Add((x1, x2)) - inner xs acc x2 +let pairwise source = + Seq.pairwise source + |> ofSeq let windowed (windowSize: int) (source: 'T list): 'T list list = if windowSize <= 0 then @@ -505,3 +505,16 @@ let windowed (windowSize: int) (source: 'T list): 'T list list = for i = length source downto windowSize do res <- (slice (Some(i-windowSize)) (Some(i-1)) source) :: res res + +let splitInto (chunks: int) (source: 'T list): 'T list list = + source + |> List.toArray + |> Array.splitInto chunks + |> ofArray + |> map ofArray + +let transpose (lists: seq<'T list>): 'T list list = + lists + |> Seq.transpose + |> Seq.map ofSeq + |> ofSeq diff --git a/src/fable-library/Long.ts b/src/fable-library/Long.ts new file mode 100644 index 0000000000..f01622dc8f --- /dev/null +++ b/src/fable-library/Long.ts @@ -0,0 +1,145 @@ +import { isValid } from "./Int32"; +import * as LongLib from "./lib/long"; + +export default LongLib.Long; +export type Long = LongLib.Long; +export type int64 = Long; +export type uint64 = Long; + +export const get_Zero = LongLib.ZERO; +export const get_One = LongLib.ONE; + +export const op_Addition = LongLib.add; +export const op_Subtraction = LongLib.subtract; +export const op_Multiply = LongLib.multiply; +export const op_Division = LongLib.divide; +export const op_Modulus = LongLib.modulo; +export const op_UnaryNegation = LongLib.negate; + +export const op_LeftShift = LongLib.shiftLeft; +export const op_RightShift = LongLib.shiftRight; +export const op_RightShiftUnsigned = LongLib.shiftRightUnsigned; +export const op_BitwiseAnd = LongLib.and; +export const op_BitwiseOr = LongLib.or; +export const op_ExclusiveOr = LongLib.xor; +export const op_LogicalNot = LongLib.not; + +export const op_LessThan = LongLib.lessThan; +export const op_LessThanOrEqual = LongLib.lessThanOrEqual; +export const op_GreaterThan = LongLib.greaterThan; +export const op_GreaterThanOrEqual = LongLib.greaterThanOrEqual; +export const op_Equality = LongLib.equals; +export const op_Inequality = LongLib.notEquals; + +export const equals = LongLib.equals; +export const compare = LongLib.compare; + +export const fromInt = LongLib.fromInt; +export const fromBits = LongLib.fromBits; +export const fromBytes = LongLib.fromBytes; +export const fromNumber = LongLib.fromNumber; +export const fromString = LongLib.fromString; +export const fromValue = LongLib.fromValue; + +export const toInt = LongLib.toInt; +export const toBytes = LongLib.toBytes; +export const toNumber = LongLib.toNumber; +export const toString = LongLib.toString; + +export const getLowBits = LongLib.getLowBits; +export const getHighBits = LongLib.getHighBits; +export const getLowBitsUnsigned = LongLib.getLowBitsUnsigned; +export const getHighBitsUnsigned = LongLib.getHighBitsUnsigned; + +function getMaxValue(unsigned: boolean, radix: number, isNegative: boolean) { + switch (radix) { + case 2: return unsigned ? + "1111111111111111111111111111111111111111111111111111111111111111" : + (isNegative ? "1000000000000000000000000000000000000000000000000000000000000000" + : "111111111111111111111111111111111111111111111111111111111111111"); + case 8: return unsigned ? + "1777777777777777777777" : + (isNegative ? "1000000000000000000000" : "777777777777777777777"); + case 10: return unsigned ? + "18446744073709551615" : + (isNegative ? "9223372036854775808" : "9223372036854775807"); + case 16: return unsigned ? + "FFFFFFFFFFFFFFFF" : + (isNegative ? "8000000000000000" : "7FFFFFFFFFFFFFFF"); + default: throw new Error("Invalid radix."); + } +} + +export function abs(x: Long) { + if (!x.unsigned && LongLib.isNegative(x)) { + return op_UnaryNegation(x); + } else { + return x; + } +} + +export function fromInteger(value: number, unsigned?: boolean, kind?: number) { + let x = value; + let xh = 0; + switch (kind) { + case 0: x = value << 24 >> 24; xh = x; break; + case 4: x = value << 24 >>> 24; break; + case 1: x = value << 16 >> 16; xh = x; break; + case 5: x = value << 16 >>> 16; break; + case 2: x = value >> 0; xh = x; break; + case 6: x = value >>> 0; break; + } + return LongLib.fromBits(x, xh >> 31, unsigned); +} + +export function parse(str: string, style: number, unsigned: boolean, _bitsize: number, radix?: number) { + const res = isValid(str, style, radix); + if (res != null) { + const lessOrEqual = (x: string, y: string) => { + const len = Math.max(x.length, y.length); + return x.padStart(len, "0") <= y.padStart(len, "0"); + }; + const isNegative = res.sign === "-"; + const maxValue = getMaxValue(unsigned || res.radix !== 10, res.radix, isNegative); + if (lessOrEqual(res.digits.toUpperCase(), maxValue)) { + str = isNegative ? res.sign + res.digits : res.digits; + return LongLib.fromString(str, unsigned, res.radix); + } + } + throw new Error("Input string was not in a correct format."); +} + +export function tryParse(str: string, style: number, unsigned: boolean, bitsize: number) { + try { + const v = parse(str, style, unsigned, bitsize); + return [true, v]; + } catch { + // supress error + } + return [false, LongLib.ZERO]; +} + +export function unixEpochMillisecondsToTicks(ms: number, offset: number) { + return op_Multiply(op_Addition(op_Addition(LongLib.fromNumber(ms), 62135596800000), offset), 10000); +} + +export function ticksToUnixEpochMilliseconds(ticks: Long) { + return LongLib.toNumber(op_Subtraction(op_Division(ticks, 10000), 62135596800000)); +} + +export function makeRangeStepFunction(step: Long, last: Long, unsigned: boolean) { + const stepComparedWithZero = LongLib.compare(step, unsigned ? LongLib.UZERO : LongLib.ZERO); + if (stepComparedWithZero === 0) { + throw new Error("The step of a range cannot be zero"); + } + const stepGreaterThanZero = stepComparedWithZero > 0; + return (x: Long) => { + const comparedWithLast = LongLib.compare(x, last); + if ((stepGreaterThanZero && comparedWithLast <= 0) + || (!stepGreaterThanZero && comparedWithLast >= 0)) { + return [x, op_Addition(x, step)]; + } else { + return null; + } + }; +} diff --git a/src/fable-library/MailboxProcessor.ts b/src/fable-library/MailboxProcessor.ts index 3a6f51f1c0..2d22998d8a 100644 --- a/src/fable-library/MailboxProcessor.ts +++ b/src/fable-library/MailboxProcessor.ts @@ -7,7 +7,7 @@ import { CancellationToken } from "./AsyncBuilder"; class QueueCell { public value: Msg; - public next: QueueCell; + public next?: QueueCell; constructor(message: Msg) { this.value = message; @@ -15,7 +15,7 @@ class QueueCell { } class MailboxQueue { - private firstAndLast: [QueueCell, QueueCell]; + private firstAndLast?: [QueueCell, QueueCell]; public add(message: Msg) { const itCell = new QueueCell(message); @@ -52,7 +52,7 @@ export default class MailboxProcessor { public cancellationToken: CancellationToken; public messages: MailboxQueue; - public continuation: Continuation; + public continuation?: Continuation; constructor(body: MailboxBody, cancellationToken?: CancellationToken) { this.body = body; @@ -99,7 +99,7 @@ export function postAndAsyncReply( let continuation: Continuation; function checkCompletion() { if (result !== void 0 && continuation !== void 0) { - continuation(result); + continuation(result); } } const reply = { diff --git a/src/fable-library/Map.d.ts b/src/fable-library/Map.d.ts new file mode 100644 index 0000000000..d1f97fbaa2 --- /dev/null +++ b/src/fable-library/Map.d.ts @@ -0,0 +1,7 @@ +import { IEqualityComparer } from "./Util"; + +declare module "./Map" { + export function createMutable( + source: ReadonlyArray | null, + comparer: IEqualityComparer): Map; +} diff --git a/src/fable-library/Map.fs b/src/fable-library/Map.fs index 8e2e589e86..5c4e11b757 100644 --- a/src/fable-library/Map.fs +++ b/src/fable-library/Map.fs @@ -16,6 +16,7 @@ module Map open System.Collections open System.Collections.Generic +open Fable.Collections open Fable.Core // [] @@ -385,6 +386,22 @@ module MapTree = then Some(en.Current, en) else None) +/// Fable uses JS Map to represent .NET Dictionary. However when keys are non-primitive, +/// we need to disguise an F# map as a mutable map. Thus, this interface matches JS Map prototype. +/// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map + +// type IMutableMap<'Key,'Value> = +// inherit IEnumerable> +// abstract size: int +// abstract clear: unit -> unit +// abstract delete: 'Key -> bool +// abstract entries: unit -> KeyValuePair<'Key,'Value> seq +// abstract get: 'Key -> 'Value +// abstract has: 'Key -> bool +// abstract keys: unit -> 'Key seq +// abstract set: 'Key * 'Value -> IMutableMap<'Key,'Value> +// abstract values: unit -> 'Value seq + [] type Map<[]'Key,[]'Value when 'Key : comparison >(comparer: IComparer<'Key>, tree: MapTree<'Key,'Value>) = member internal __.Comparer = comparer @@ -434,7 +451,9 @@ type Map<[]'Key,[ Seq.map (fun kv -> sprintf "(%A, %A)" kv.Key kv.Value) |> String.concat "; ") + "]" + let toStr (kv: KeyValuePair<'Key,'Value>) = System.String.Format("({0}, {1})", kv.Key, kv.Value) + let str = (this |> Seq.map toStr |> String.concat "; ") + "map [" + str + "]" override this.GetHashCode() = let combineHash x y = (x <<< 1) + y + 631 @@ -474,6 +493,16 @@ type Map<[]'Key,[ 0 then c else Unchecked.compare kvp1.Value kvp2.Value res + interface IMutableMap<'Key,'Value> with + member this.size = this.Count + member __.clear() = failwith "Map cannot be mutated" + member __.delete(_) = failwith "Map cannot be mutated" + member this.entries() = MapTree.toSeq this.Tree + member this.get(k) = this.Item(k) + member this.has(k) = this.ContainsKey(k) + member this.keys() = MapTree.toSeq this.Tree |> Seq.map (fun kv -> kv.Key) + member __.set(k, v) = failwith "Map cannot be mutated" + member this.values() = MapTree.toSeq this.Tree |> Seq.map (fun kv -> kv.Value) let isEmpty (m:Map<_,_>) = m.IsEmpty @@ -542,21 +571,6 @@ let toArray (m:Map<'Key,'Value>) = let empty<'Key,'Value when 'Key : comparison> ([] comparer: IComparer<'Key>) = new Map<'Key,'Value>(comparer, MapTree.MapEmpty) -/// Fable uses JS Map to represent .NET Dictionary. However when keys are non-primitive, -/// we need to disguise an F# map as a mutable map. Thus, this interface matches JS Map prototype. -/// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map -type IMutableMap<'Key,'Value> = - inherit IEnumerable> - abstract size: int - abstract clear: unit -> unit - abstract delete: 'Key -> bool - abstract entries: unit -> KeyValuePair<'Key,'Value> seq - abstract get: 'Key -> 'Value - abstract has: 'Key -> bool - abstract keys: unit -> 'Key seq - abstract set: 'Key * 'Value -> IMutableMap<'Key,'Value> - abstract values: unit -> 'Value seq - let private createMutablePrivate (comparer: IComparer<'Key>) tree' = let mutable tree = tree' { new IMutableMap<'Key,'Value> with @@ -588,12 +602,18 @@ let private createMutablePrivate (comparer: IComparer<'Key>) tree' = upcast MapTree.mkIEnumerator tree } -/// Emulate JS Set with custom comparer for non-primitive values -let createMutable (source: ('Key*'Value) seq) ([] comparer: IComparer<'Key>) = - MapTree.ofSeq comparer source - |> createMutablePrivate comparer +/// Emulate JS Map with custom comparer for non-primitive values + +// let createMutable (source: ('Key*'Value) seq) ([] comparer: IComparer<'Key>) = +// MapTree.ofSeq comparer source +// |> createMutablePrivate comparer + +let createMutable (source: KeyValuePair<'Key, 'Value> seq) ([] comparer: IEqualityComparer<'Key>) = + let map = MutableMap(source, comparer) + map :> IMutableMap<_,_> -let groupBy (projection: 'T -> 'Key) (xs: 'T seq) ([] comparer: IComparer<'Key>): ('Key * 'T seq) seq = +// let groupBy (projection: 'T -> 'Key) (xs: 'T seq) ([] comparer: IComparer<'Key>): ('Key * 'T seq) seq = +let groupBy (projection: 'T -> 'Key) (xs: 'T seq) ([] comparer: IEqualityComparer<'Key>): ('Key * 'T seq) seq = let dict: IMutableMap<_,ResizeArray<'T>> = createMutable Seq.empty comparer // Build the groupings @@ -607,7 +627,8 @@ let groupBy (projection: 'T -> 'Key) (xs: 'T seq) ([] comparer: ICompare // as a tuple, but let's do it just in case the implementation changes dict |> Seq.map (fun kv -> kv.Key, upcast kv.Value) -let countBy (projection: 'T -> 'Key) (xs: 'T seq) ([] comparer: IComparer<'Key>): ('Key * int) seq = +// let countBy (projection: 'T -> 'Key) (xs: 'T seq) ([] comparer: IComparer<'Key>): ('Key * int) seq = +let countBy (projection: 'T -> 'Key) (xs: 'T seq) ([] comparer: IEqualityComparer<'Key>): ('Key * int) seq = let dict = createMutable Seq.empty comparer for value in xs do diff --git a/src/fable-library/MutableMap.fs b/src/fable-library/MutableMap.fs new file mode 100644 index 0000000000..5f6e66eb3c --- /dev/null +++ b/src/fable-library/MutableMap.fs @@ -0,0 +1,155 @@ +// Fable .NET Dictionary implementation for non-primitive keys. +namespace Fable.Collections + +open System.Collections.Generic + +/// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map +type IMutableMap<'Key, 'Value> = + inherit IEnumerable> + abstract size: int + abstract clear: unit -> unit + abstract delete: 'Key -> bool + abstract entries: unit -> KeyValuePair<'Key,'Value> seq + abstract get: 'Key -> 'Value + abstract has: 'Key -> bool + abstract keys: unit -> 'Key seq + abstract set: 'Key * 'Value -> IMutableMap<'Key,'Value> + abstract values: unit -> 'Value seq + +[] +type MutableMap<'Key, 'Value when 'Key: equality>(pairs: KeyValuePair<'Key, 'Value> seq, comparer: IEqualityComparer<'Key>) as this = + + // Compiles to JS Map of key hashes pointing to dynamic arrays of KeyValuePair<'Key, 'Value>. + let hashMap = Dictionary>>() + do for pair in pairs do this.Add(pair.Key, pair.Value) + + // new () = MutableMap (Seq.empty, EqualityComparer.Default) + // new (comparer) = MutableMap (Seq.empty, comparer) + + member private this.TryFindIndex(k) = + let h = comparer.GetHashCode(k) + match hashMap.TryGetValue h with + | true, pairs -> + true, h, pairs.FindIndex (fun pair -> comparer.Equals(k, pair.Key)) + | false, _ -> + false, h, -1 + + member this.TryFind(k) = + match this.TryFindIndex(k) with + | true, h, i when i > -1 -> Some hashMap.[h].[i] + | _, _, _ -> None + + member this.Comparer = + comparer + + member this.Clear() = + hashMap.Clear() + + member this.Count = + hashMap.Values |> Seq.sumBy (fun pairs -> pairs.Count) + + member this.Item + with get (k: 'Key) = + match this.TryFind(k) with + | Some pair -> pair.Value + | _ -> raise (KeyNotFoundException("The item was not found in collection")) + and set (k: 'Key) (v: 'Value) = + match this.TryFindIndex(k) with + | true, h, i when i > -1 -> + hashMap.[h].[i] <- KeyValuePair(k, v) // replace + | true, h, _ -> + hashMap.[h].Add(KeyValuePair(k, v)) |> ignore // append + | false, h, _ -> + hashMap.[h] <- ResizeArray([| KeyValuePair(k, v) |]) // add new + + member this.Add(k, v) = + match this.TryFindIndex(k) with + | true, h, i when i > -1 -> + let msg = System.String.Format("An item with the same key has already been added. Key: {0}", k) + raise (System.ArgumentException(msg)) + | true, h, _ -> + hashMap.[h].Add(KeyValuePair(k, v)) |> ignore // append + | false, h, _ -> + hashMap.[h] <- ResizeArray([| KeyValuePair(k, v) |]) // add new + + member this.ContainsKey(k) = + match this.TryFindIndex(k) with + | true, h, i when i > -1 -> true + | _, _, _ -> false + + member this.Remove(k) = + match this.TryFindIndex(k) with + | true, h, i when i > -1 -> + hashMap.[h].RemoveAt(i) + true + | _, _, _ -> + false + + interface System.Collections.IEnumerable with + member this.GetEnumerator(): System.Collections.IEnumerator = + ((this :> IEnumerable>).GetEnumerator() :> System.Collections.IEnumerator) + + interface IEnumerable> with + member this.GetEnumerator(): IEnumerator> = + let elems = seq { + for pairs in hashMap.Values do + for pair in pairs do + yield pair } + elems.GetEnumerator() + + interface ICollection> with + member this.Add(item: KeyValuePair<'Key, 'Value>): unit = + this.Add(item.Key, item.Value) + member this.Clear(): unit = + this.Clear() + member this.Contains(item: KeyValuePair<'Key, 'Value>): bool = + match this.TryFind item.Key with + | Some p when Unchecked.equals p.Value item.Value -> true + | _ -> false + member this.CopyTo(array: KeyValuePair<'Key, 'Value> [], arrayIndex: int): unit = + this |> Seq.iteri (fun i e -> array.[arrayIndex + i] <- e) + member this.Count: int = + this.Count + member this.IsReadOnly: bool = + false + member this.Remove(item: KeyValuePair<'Key, 'Value>): bool = + match this.TryFind item.Key with + | Some pair -> + if Unchecked.equals pair.Value item.Value then + this.Remove(item.Key) |> ignore + true + | _ -> false + +#if !FABLE_COMPILER + interface IDictionary<'Key, 'Value> with + member this.Add(key: 'Key, value: 'Value): unit = + this.Add(key, value) + member this.ContainsKey(key: 'Key): bool = + this.ContainsKey(key) + member this.Item + with get (key: 'Key): 'Value = + this.[key] + and set (key: 'Key) (v: 'Value): unit = + this.[key] <- v + member this.Keys: ICollection<'Key> = + [| for pair in this -> pair.Key |] :> ICollection<'Key> + member this.Remove(key: 'Key): bool = + this.Remove(key) + member this.TryGetValue(key: 'Key, value: byref<'Value>): bool = + match this.TryFind key with + | Some pair -> value <- pair.Value; true + | _ -> false + member this.Values: ICollection<'Value> = + [| for pair in this -> pair.Value |] :> ICollection<'Value> +#endif + + interface IMutableMap<'Key, 'Value> with + member this.size = this.Count + member this.clear() = this.Clear() + member this.delete(k) = this.Remove(k) + member this.entries() = this |> Seq.map id + member this.get(k) = this.[k] + member this.has(k) = this.ContainsKey(k) + member this.keys() = this |> Seq.map (fun pair -> pair.Key) + member this.set(k, v) = this.[k] <- v; this :> IMutableMap<'Key, 'Value> + member this.values() = this |> Seq.map (fun pair -> pair.Value) diff --git a/src/fable-library/MutableSet.fs b/src/fable-library/MutableSet.fs new file mode 100644 index 0000000000..d744a49eaf --- /dev/null +++ b/src/fable-library/MutableSet.fs @@ -0,0 +1,141 @@ +// Fable .NET HashSet implementation for non-primitive keys. +namespace Fable.Collections + +open System.Collections.Generic + +/// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set +type IMutableSet<'T> = + inherit IEnumerable<'T> + abstract size: int + abstract add: 'T -> IMutableSet<'T> + /// Convenience method (not in JS Set prototype) to check if the element has actually been added + abstract add_: 'T -> bool + abstract clear: unit -> unit + abstract delete: 'T -> bool + abstract has: 'T -> bool + abstract keys: unit -> 'T seq + abstract values: unit -> 'T seq + abstract entries: unit -> ('T * 'T) seq + +[] +type MutableSet<'T when 'T: equality>(items: 'T seq, comparer: IEqualityComparer<'T>) as this = + + // Compiles to JS Map of key hashes pointing to dynamic arrays of 'T. + let hashMap = Dictionary>() + do for item in items do this.Add(item) |> ignore + + // new () = MutableSet (Seq.empty, EqualityComparer.Default) + // new (comparer) = MutableSet (Seq.empty, comparer) + + member private this.TryFindIndex(k) = + let h = comparer.GetHashCode(k) + match hashMap.TryGetValue h with + | true, values -> + true, h, values.FindIndex (fun v -> comparer.Equals(k, v)) + | false, _ -> + false, h, -1 + + member private this.TryFind(k) = + match this.TryFindIndex(k) with + | true, h, i when i > -1 -> Some hashMap.[h].[i] + | _, _, _ -> None + + member this.Comparer = + comparer + + member this.Clear() = + hashMap.Clear() + + member this.Count = + hashMap.Values |> Seq.sumBy (fun pairs -> pairs.Count) + + member this.Add(k) = + match this.TryFindIndex(k) with + | true, h, i when i > -1 -> + false + | true, h, _ -> + hashMap.[h].Add(k) |> ignore + true + | false, h, _ -> + hashMap.[h] <- ResizeArray([| k |]) + true + + member this.Contains(k) = + match this.TryFindIndex(k) with + | true, h, i when i > -1 -> true + | _, _, _ -> false + + member this.Remove(k) = + match this.TryFindIndex(k) with + | true, h, i when i > -1 -> + hashMap.[h].RemoveAt(i) + true + | _, _, _ -> + false + + interface System.Collections.IEnumerable with + member this.GetEnumerator(): System.Collections.IEnumerator = + ((this :> IEnumerable<'T>).GetEnumerator() :> System.Collections.IEnumerator) + + interface IEnumerable<'T> with + member this.GetEnumerator(): IEnumerator<'T> = + let elems = seq { + for values in hashMap.Values do + for value in values do + yield value } + elems.GetEnumerator() + + interface ICollection<'T> with + member this.Add(item: 'T): unit = + this.Add item |> ignore + member this.Clear(): unit = + this.Clear() + member this.Contains(item: 'T): bool = + this.Contains item + member this.CopyTo(array: 'T [], arrayIndex: int): unit = + this |> Seq.iteri (fun i e -> array.[arrayIndex + i] <- e) + member this.Count: int = + this.Count + member this.IsReadOnly: bool = + false + member this.Remove(item: 'T): bool = + this.Remove item + +#if !FABLE_COMPILER + interface ISet<'T> with + member this.Add(item: 'T): bool = + this.Add item + member this.ExceptWith(other: IEnumerable<'T>): unit = + for x in other do + this.Remove x |> ignore + member this.IntersectWith(other: IEnumerable<'T>): unit = + failwith "Not Implemented" + member this.IsProperSubsetOf(other: IEnumerable<'T>): bool = + failwith "Not Implemented" + member this.IsProperSupersetOf(other: IEnumerable<'T>): bool = + failwith "Not Implemented" + member this.IsSubsetOf(other: IEnumerable<'T>): bool = + failwith "Not Implemented" + member this.IsSupersetOf(other: IEnumerable<'T>): bool = + failwith "Not Implemented" + member this.Overlaps(other: IEnumerable<'T>): bool = + failwith "Not Implemented" + member this.SetEquals(other: IEnumerable<'T>): bool = + failwith "Not Implemented" + member this.SymmetricExceptWith(other: IEnumerable<'T>): unit = + failwith "Not Implemented" + member this.UnionWith(other: IEnumerable<'T>): unit = + for x in other do + this.Add x |> ignore +#endif + + interface IMutableSet<'T> with + member this.size = this.Count + member this.add(k) = this.Add(k) |> ignore; this :> IMutableSet<'T> + member this.add_(k) = this.Add(k) + member this.clear() = this.Clear() + member this.delete(k) = this.Remove(k) + member this.has(k) = this.Contains(k) + member this.keys() = this |> Seq.map id + member this.values() = this |> Seq.map id + member this.entries() = this |> Seq.map (fun v -> (v, v)) diff --git a/src/fable-library/Observable.ts b/src/fable-library/Observable.ts index cd36c08a87..f7cc2f0e87 100644 --- a/src/fable-library/Observable.ts +++ b/src/fable-library/Observable.ts @@ -14,7 +14,7 @@ export class Observer implements IObserver { constructor(onNext: (x: T) => void, onError?: (e: any) => void, onCompleted?: () => void) { this.OnNext = onNext; - this.OnError = onError || ((e: any) => { return; }); + this.OnError = onError || ((_e: any) => { return; }); this.OnCompleted = onCompleted || (() => { return; }); } } @@ -44,7 +44,7 @@ export function add(callback: (x: T) => void, source: IObservable) { } export function choose(chooser: (x: T) => U, source: IObservable) { - return new Observable((observer) => + return new Observable((observer) => source.Subscribe(new Observer((t) => protect( () => chooser(t), @@ -117,7 +117,7 @@ export function merge(source1: IObservable, source2: IObservable) { export function pairwise(source: IObservable) { return new Observable<[T, T]>((observer) => { - let last: T = null; + let last: T; return source.Subscribe(new Observer((next) => { if (last != null) { observer.OnNext([last, next]); @@ -142,7 +142,7 @@ export function scan(collector: (u: U, t: T) => U, state: U, source: IObse }) as IObservable; } -export function split(splitter: (x: T) => /* Choice */ any, source: IObservable) { +export function split(splitter: (x: T) => /* Choice */ any, source: IObservable) { return [choose((v) => tryValueIfChoice1(splitter(v)), source), choose((v) => tryValueIfChoice2(splitter(v)), source)]; } diff --git a/src/fable-library/Option.js b/src/fable-library/Option.js deleted file mode 100644 index fc8042ad83..0000000000 --- a/src/fable-library/Option.js +++ /dev/null @@ -1,120 +0,0 @@ -import { declare, Union } from "./Types"; -import { compare, equals, structuralHash } from "./Util"; - -// Options are erased in runtime by Fable, but we have -// the `Some` type below to wrap values that would evaluate -// to null in runtime. These two rules must be followed: - -// 1- None is always null in runtime, a non-strict null check -// (`x == null`) is enough to check the case of an option. -// 2- To get the value of an option the `getValue` helper -// below must **always** be used. - -// export type Option = T | Some; - -// Using a class here for better compatibility with TS files importing Some -export class Some { - constructor(value) { - this.value = value; - } - - // Don't add "Some" for consistency with erased options - toString() { - return String(this.value); - } - - toJSON() { - return this.value; - } - - GetHashCode() { - return structuralHash(this.value); - } - - Equals(other) { - return other == null - ? false - : equals(this.value, other instanceof Some ? other.value : other); - } - - CompareTo(other) { - return other == null - ? 1 - : compare(this.value, other instanceof Some ? other.value : other); - } -} - -export function some(x) { - return x == null || x instanceof Some ? new Some(x) : x; -} - -export function value(x, acceptNull) { - if (x == null) { - if (!acceptNull) { - throw new Error("Option has no value"); - } - return null; - } else { - return x instanceof Some ? x.value : x; - } -} - -export function defaultArg(arg, defaultValue, f) { - return arg == null ? defaultValue : (f != null ? f(value(arg)) : value(arg)); -} - -export function defaultArgWith(arg, defThunk) { - return arg == null ? defThunk() : value(arg); -} - -export function filter(predicate, arg) { - return arg != null ? (!predicate(value(arg)) ? null : arg) : arg; -} - -// CHOICE - -export const Choice = declare(function Choice(tag, name, field) { - Union.call(this, tag, name, field); -}, Union); - -export function choice1(x) { - return new Choice(0, "Choice1Of2", x); -} - -export function choice2(x) { - return new Choice(1, "Choice2Of2", x); -} - -export function tryValueIfChoice1(x) { - return x.tag === 0 ? some(x.fields[0]) : null; -} - -export function tryValueIfChoice2(x) { - return x.tag === 1 ? some(x.fields[0]) : null; -} - -// RESULT - -export const Result = declare(function Result(tag, name, field) { - Union.call(this, tag, name, field); -}, Union); - -export function ok(x) { - return new Result(0, "Ok", x); -} - -export function error(x) { - return new Result(1, "Error", x); -} - -export function mapOk(f, result) { - return result.tag === 0 ? ok(f(result.fields[0])) : result; -} - -export function mapError(f, result) { - return result.tag === 1 ? error(f(result.fields[0])) : result; -} - -export function bindOk(f, result) { - return result.tag === 0 ? f(result.fields[0]) : result; -} diff --git a/src/fable-library/Option.ts b/src/fable-library/Option.ts new file mode 100644 index 0000000000..ab4300bef5 --- /dev/null +++ b/src/fable-library/Option.ts @@ -0,0 +1,161 @@ +import { declare, Union } from "./Types"; +import { compare, equals, structuralHash } from "./Util"; + +// Options are erased in runtime by Fable, but we have +// the `Some` type below to wrap values that would evaluate +// to null in runtime. These two rules must be followed: + +// 1- None is always null in runtime, a non-strict null check +// (`x == null`) is enough to check the case of an option. +// 2- To get the value of an option the `getValue` helper +// below must **always** be used. + +export type Option = T | Some | null | undefined; + +// Using a class here for better compatibility with TS files importing Some +export class Some { + public value: T; + + constructor(value: T) { + this.value = value; + } + + // Don't add "Some" for consistency with erased options + public toString() { + return String(this.value); + } + + public toJSON() { + return this.value; + } + + public GetHashCode() { + return structuralHash(this.value); + } + + public Equals(other: Option): boolean { + if (other == null) { + return false; + } else { + return equals(this.value, other instanceof Some ? other.value : other); + } + } + + public CompareTo(other: Option) { + if (other == null) { + return 1; + } else { + return compare(this.value, other instanceof Some ? other.value : other); + } + } +} + +export function some(x: T): Option { + return x == null || x instanceof Some ? new Some(x) : x; +} + +export function value(x: Option) { + if (x == null) { + throw new Error("Option has no value"); + } else { + return x instanceof Some ? x.value : x; + } +} + +export function tryValue(x: Option) { + return x instanceof Some ? x.value : x; +} + +export function toArray(opt: Option) { + return (opt == null) ? [] : [value(opt)]; +} + +export function defaultArg(opt: Option, defaultValue: T) { + return (opt != null) ? value(opt) : defaultValue; +} + +export function defaultArgWith(opt: Option, defThunk: () => T) { + return (opt != null) ? value(opt) : defThunk(); +} + +export function filter(predicate: (arg: T) => boolean, opt: Option) { + return (opt != null) ? (predicate(value(opt)) ? opt : null) : opt; +} + +export function map(mapping: (arg: T) => U, opt: Option): Option { + return (opt != null) ? some(mapping(value(opt))) : null; +} + +export function map2( + mapping: (arg1: T1, arg2: T2) => Option, + opt1: Option, opt2: Option) { + return (opt1 != null && opt2 != null) ? mapping(value(opt1), value(opt2)) : null; +} + +export function map3( + mapping: (arg1: T1, arg2: T2, arg3: T3) => Option, + opt1: Option, opt2: Option, opt3: Option) { + return (opt1 != null && opt2 != null && opt3 != null) ? mapping(value(opt1), value(opt2), value(opt3)) : null; +} + +export function bind(binder: (arg: T) => Option, opt: Option): Option { + return opt != null ? binder(value(opt)) : null; +} + +export function tryOp(op: (x: T) => U, arg: T): Option { + try { + return some(op(arg)); + } catch { + return null; + } +} + +// CHOICE +export type Choice = Union; + +export const Choice = declare(function Choice(this: Choice, tag: number, name: string, field: T | U) { + Union.call(this, tag, name, field); +}, Union); + +export function choice1(x: T | U): Choice { + return new Choice(0, "Choice1Of2", x); +} + +export function choice2(x: T | U): Choice { + return new Choice(1, "Choice2Of2", x); +} + +export function tryValueIfChoice1(x: Choice): Option { + return x.tag === 0 ? some(x.fields[0]) : null; +} + +export function tryValueIfChoice2(x: Choice): Option { + return x.tag === 1 ? some(x.fields[0]) : null; +} + +// RESULT +export type Result = Union; + +export const Result = declare(function Result(this: Result, tag: number, name: string, field: T | U) { + Union.call(this, tag, name, field); +}, Union); + +export function ok(x: T | U): Result { + return new Result(0, "Ok", x); +} + +export function error(x: T | U): Result { + return new Result(1, "Error", x); +} + +export function mapOk(f: (arg: T) => T, result: Result) { + return result.tag === 0 ? ok(f(result.fields[0])) : result; +} + +export function mapError(f: (arg: U) => U, result: Result) { + return result.tag === 1 ? error(f(result.fields[0])) : result; +} + +export function bindOk(f: (arg: T) => Result, result: Result) { + return result.tag === 0 ? f(result.fields[0]) : result; +} diff --git a/src/fable-library/Reflection.ts b/src/fable-library/Reflection.ts index ea8046b590..5b1bde211f 100644 --- a/src/fable-library/Reflection.ts +++ b/src/fable-library/Reflection.ts @@ -94,7 +94,7 @@ export abstract class NMemberInfo { public get_DeclaringType() { return this.DeclaringType; } - public GetCustomAttributes(a: (boolean|NTypeInfo), b?: boolean) { + public GetCustomAttributes(a: (boolean|NTypeInfo), _?: boolean) { if (typeof a === "boolean") { return this.attributes.map((att) => att.AttributeValue); } else if (a.fullname) { @@ -355,7 +355,7 @@ export class NConstructorInfo extends NMethodBase { } export class NFieldInfo extends NMemberInfo { - public Type: NTypeInfo = null; + public Type: NTypeInfo; constructor( declaringType: NTypeInfo, name: string, @@ -432,7 +432,7 @@ export class NFieldInfo extends NMemberInfo { } export class NPropertyInfo extends NMemberInfo { - public Type: NTypeInfo = null; + public Type: NTypeInfo; constructor( DeclaringType: NTypeInfo, Name: string, @@ -542,7 +542,7 @@ export class NPropertyInfo extends NMemberInfo { } else { index = index || []; const s = this.get_SetMethod(); - s.Invoke(target, [...index, value]); + s?.Invoke(target, [...index, value]); } } @@ -586,7 +586,7 @@ export class NPropertyInfo extends NMemberInfo { } export class NUnionCaseInfo extends NMemberInfo { - public Fields: NPropertyInfo[] = null; + public Fields: NPropertyInfo[]; public constructor( DeclaringType: NTypeInfo, @@ -658,6 +658,8 @@ export class NUnionCaseInfo extends NMemberInfo { } +export type NEnumCase = [string, number]; + export class NTypeInfo { public static getParameter(i: string) { if (NTypeInfo.parameterCache[i]) { @@ -674,11 +676,11 @@ export class NTypeInfo { } private static parameterCache: {[i: string]: NTypeInfo} = {}; - public generics: NTypeInfo[] = null; - public GenericDeclaration: NTypeInfo = null; - public DeclaringType: NTypeInfo = null; - public mems: NMemberInfo[] = null; + public generics: NTypeInfo[]; + public GenericDeclaration: NTypeInfo | null; + public DeclaringType: NTypeInfo | null; + private cachedMembers: NMemberInfo[] | null = null; private instantiations: {[i: string]: NTypeInfo} = {}; private genericMap: {[name: string]: number} = {}; @@ -688,10 +690,10 @@ export class NTypeInfo { public isGenericParameter: boolean, _generics: NTypeInfo[], public members: (self: NTypeInfo) => NMemberInfo[], - genericDeclaration: NTypeInfo, - declaringType: NTypeInfo) { + genericDeclaration: NTypeInfo | null, + declaringType: NTypeInfo | null, + public enumCases?: NEnumCase[]) { if (!fullname) { throw new Error("cannot declare type without name"); } - members = members || ((_s) => []); _generics = _generics || []; isGenericParameter = isGenericParameter || false; genericCount = genericCount || 0; @@ -713,7 +715,7 @@ export class NTypeInfo { this.DeclaringType = declaringType; } - public get_DeclaringType(): NTypeInfo { + public get_DeclaringType(): NTypeInfo | null { return this.DeclaringType; } @@ -780,7 +782,7 @@ export class NTypeInfo { return this.fullname.endsWith("[]"); } - public GetElementType(): NTypeInfo { + public GetElementType(): NTypeInfo | null { return this.get_IsArray() ? this.generics[0] : null; } @@ -817,14 +819,14 @@ export class NTypeInfo { } public GetAllMembers() { - if (!this.mems) { + if (!this.cachedMembers) { if (this.members) { - this.mems = this.members(this); + this.cachedMembers = this.members(this); } else { - this.mems = []; + this.cachedMembers = []; } } - return this.mems; + return this.cachedMembers; } public GetMembers() { @@ -930,7 +932,7 @@ export interface CustomAttribute { const typeCache: { [fullname: string]: NTypeInfo } = {}; export function declareNType(fullname: string, generics: number, members: (self: NTypeInfo, gen: NTypeInfo[]) => NMemberInfo[]): NTypeInfo { - let gen: NTypeInfo = null; + let gen: NTypeInfo; if (fullname in typeCache) { gen = typeCache[fullname]; } else { @@ -982,6 +984,7 @@ function typesEqual(l: NTypeInfo[], r: NTypeInfo[]) { return false; } } + export function parameterEquals(l: NParameterInfo, r: NParameterInfo) { if (l === r) { return true; } else if (l == null && r != null) { return false; } else @@ -1016,16 +1019,7 @@ export function propertyEquals(l: NPropertyInfo, r: NPropertyInfo) { return l.Name === r.Name && l.IsFSharp === r.IsFSharp && l.IsStatic === r.IsStatic && equals(l.DeclaringType, r.DeclaringType); } } -function propertiesEqual(l: NPropertyInfo[], r: NPropertyInfo[]) { - if (l.length === r.length) { - for (let i = 0; i < l.length; i++) { - if (!propertyEquals(l[i], r[i])) { return false; } - } - return true; - } else { - return false; - } -} + export function constructorEquals(l: NConstructorInfo, r: NConstructorInfo) { if (l === r) { return true; } else if (l == null && r != null) { return false; } else @@ -1088,7 +1082,7 @@ export function compare(t1: NTypeInfo, t2: NTypeInfo): number { } export function ntype(fullname: string, genericNames?: string[], generics?: NTypeInfo[], members?: (self: NTypeInfo, pars: NTypeInfo[]) => NMemberInfo[], declaringType?: NTypeInfo): NTypeInfo { - let gen: NTypeInfo = null; + let gen: NTypeInfo; generics = generics || []; const a = generics.findIndex((t) => !t); if (a >= 0) { throw new Error("bad hate occured"); } @@ -1096,14 +1090,13 @@ export function ntype(fullname: string, genericNames?: string[], generics?: NTyp if (fullname in typeCache) { gen = typeCache[fullname]; } else { - members = members || ((_s, _g) => []); + const _members = members || ((_s, _g) => []); genericNames = genericNames || []; - declaringType = declaringType || null; const b = genericNames.findIndex((t) => !t); if (b >= 0) { throw new Error("bad hate occured"); } const pars = genericNames.map((n) => getGenericParameter(n)); - gen = new NTypeInfo(fullname, pars.length, false, pars, (s) => members(s, pars), null, declaringType); + gen = new NTypeInfo(fullname, pars.length, false, pars, (s) => _members(s, pars), null, declaringType || null); typeCache[fullname] = gen; } @@ -1154,17 +1147,17 @@ export function lambda(argType: NTypeInfo, returnType: NTypeInfo): NTypeInfo { return gen.MakeGenericType([argType, returnType]); } -export function option(generic?: NTypeInfo): NTypeInfo { +export function option(generic: NTypeInfo): NTypeInfo { const name = "Microsoft.FSharp.Core.FSharpOption`1"; const gen = declareNType(name, 1, (self, gen) => [ new NUnionCaseInfo(self, 0, "None", [], [], ((_) => null)), - new NUnionCaseInfo(self, 1, "Some", [], [["Value", gen[0]]], ((args, ...rest) => args)), + new NUnionCaseInfo(self, 1, "Some", [], [["Value", gen[0]]], ((args, ..._rest) => args)), ]); return gen.MakeGenericType([generic]); } -export function list(generic?: NTypeInfo): NTypeInfo { +export function list(generic: NTypeInfo): NTypeInfo { const gen = declareNType("Microsoft.FSharp.Collections.FSharpList`1", 1, (self, gen) => [ new NPropertyInfo(self, "Head", gen[0], false, false, []), new NMethodInfo(self, [], "get_Head", [], gen[0], false, ((l) => l[0]), []), @@ -1173,8 +1166,8 @@ export function list(generic?: NTypeInfo): NTypeInfo { // return new NTypeInfo("Microsoft.FSharp.Collections.FSharpList`1", 1, false, [generic], (_s) => []); } -export function array(generic?: NTypeInfo): NTypeInfo { - const gen = declareNType("_[]", 1, (self, gen) => [ +export function array(generic: NTypeInfo): NTypeInfo { + const gen = declareNType("_[]", 1, (self, _gen) => [ new NPropertyInfo(self, "Length", int32, false, false, []), new NMethodInfo(self, [], "get_Length", [], int32, false, ((l) => l.length), []), ]); @@ -1183,6 +1176,10 @@ export function array(generic?: NTypeInfo): NTypeInfo { // return new NTypeInfo(generic.fullname + "[]", 1, false, [generic], (_s) => []); } +export function enumType(fullname: string, underlyingType: NTypeInfo, enumCases: NEnumCase[]): NTypeInfo { + return new NTypeInfo(fullname, 1, false, [underlyingType], (_) => [], null, null, enumCases); +} + export const obj: NTypeInfo = NTypeInfo.Simple("System.Object"); export const unit: NTypeInfo = NTypeInfo.Simple("Microsoft.FSharp.Core.Unit"); export const char: NTypeInfo = NTypeInfo.Simple("System.Char"); @@ -1228,6 +1225,85 @@ export function isConstructorInfo(o: any) { return o != null && isMemberInfo(o) && o.getMemberKind() === NReflKind.Constructor; } +export function isEnum(t: NTypeInfo) { + return t.enumCases != null && t.enumCases.length > 0; +} + +export function getEnumUnderlyingType(t: NTypeInfo) { + return t.generics[0]; +} + +export function getEnumValues(t: NTypeInfo): number[] { + if (t.enumCases) { + return t.enumCases.map((kv) => kv[1]); + } else { + throw new Error(`${t.fullname} is not an enum type`); + } +} + +export function getEnumNames(t: NTypeInfo): string[] { + if (t.enumCases) { + return t.enumCases.map((kv) => kv[0]); + } else { + throw new Error(`${t.fullname} is not an enum type`); + } +} + +function getEnumCase(t: NTypeInfo, v: number | string): NEnumCase { + if (t.enumCases) { + if (typeof v === "string") { + for (const kv of t.enumCases) { + if (kv[0] === v) { + return kv; + } + } + throw new Error(`'${v}' was not found in ${t.fullname}`); + } else { + for (const kv of t.enumCases) { + if (kv[1] === v) { + return kv; + } + } + // .NET returns the number even if it doesn't match any of the cases + return ["", v]; + } + } else { + throw new Error(`${t.fullname} is not an enum type`); + } +} + +export function parseEnum(t: NTypeInfo, str: string): number { + // TODO: better int parsing here, parseInt ceils floats: "4.8" -> 4 + const value = parseInt(str, 10); + return getEnumCase(t, isNaN(value) ? str : value)[1]; +} + +export function tryParseEnum(t: NTypeInfo, str: string): [boolean, number] { + try { + const v = parseEnum(t, str); + return [true, v]; + } catch { + // supress error + } + return [false, NaN]; +} + +export function getEnumName(t: NTypeInfo, v: number): string { + return getEnumCase(t, v)[0]; +} + +export function isEnumDefined(t: NTypeInfo, v: string | number): boolean { + try { + const kv = getEnumCase(t, v); + return kv[0] != null && kv[0] !== ""; + } catch { + // supress error + } + return false; +} + +// FSharpType + export function getUnionCases(t: NTypeInfo): NUnionCaseInfo[] { const cases = t.GetAllMembers().filter((m) => isUnionCaseInfo(m)) as NUnionCaseInfo[]; if (cases.length > 0) { @@ -1346,11 +1422,13 @@ export function getTupleField(v: any, i: number): any { export function makeUnion(uci: NUnionCaseInfo, values: any[]): any { return uci.Invoke.apply(null, values); - // const expectedLength = (uci.fields || []).length; - // if (values.length !== expectedLength) { - // throw new Error(`Expected an array of length ${expectedLength} but got ${values.length}`); - // } - // return new uci.declaringType.constructor(uci.tag, uci.name, ...values); +// const expectedLength = (uci.fields || []).length; +// if (values.length !== expectedLength) { +// throw new Error(`Expected an array of length ${expectedLength} but got ${values.length}`); +// } +// return uci.declaringType.constructor != null +// ? new uci.declaringType.constructor(uci.tag, uci.name, ...values) +// : {}; } export function makeRecord(t: NTypeInfo, values: any[]): any { @@ -1362,7 +1440,7 @@ export function makeRecord(t: NTypeInfo, values: any[]): any { return ctor.Invoke(values); } -export function makeTuple(values: any[], t: NTypeInfo): any { +export function makeTuple(values: any[], _: NTypeInfo): any { return values; } @@ -1402,7 +1480,8 @@ export function createMethod(decl: NTypeInfo, name: string, mpars: string[], mar } else { const pp = mpars.map ((n) => getGenericParameter(n)); const meth = new NMethodInfo(decl, pp, name, declaredArgs.map((a, i) => new NParameterInfo("arg" + i, a)), ret, isStatic, ((_target, _args) => { throw new Error("cannot invoke " + decl.fullname + "." + name); }), []); - decl.mems.push(meth); + // TODO: Is this necessary? I don't see `createMethod` in use anywhere + // decl.cachedMembers.push(meth); return meth.get_IsGenericMethod() ? meth.MakeGenericMethod(margs) : meth; } } diff --git a/src/fable-library/RegExp.ts b/src/fable-library/RegExp.ts index a27cd77edc..8a76488ecb 100644 --- a/src/fable-library/RegExp.ts +++ b/src/fable-library/RegExp.ts @@ -1,26 +1,28 @@ export type MatchEvaluator = (match: any) => string; -export function create(pattern: string, options: number) { +export function create(pattern: string, options: number = 0) { // Supported RegexOptions // * IgnoreCase: 0x0001 // * Multiline: 0x0002 + // * Singleline: 0x0010 // * ECMAScript: 0x0100 (ignored) - if ((options & ~(1 ^ 2 ^ 256)) !== 0) { - throw new Error("RegexOptions only supports: IgnoreCase, Multiline and ECMAScript"); + if ((options & ~(1 ^ 2 ^ 16 ^ 256)) !== 0) { + throw new Error("RegexOptions only supports: IgnoreCase, Multiline, Singleline and ECMAScript"); } let flags = "g"; flags += options & 1 ? "i" : ""; // 0x0001 RegexOptions.IgnoreCase flags += options & 2 ? "m" : ""; + flags += options & 16 ? "s" : ""; return new RegExp(pattern, flags); } // From http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex export function escape(str: string) { - return str.replace(/[\-\[\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); + return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } export function unescape(str: string) { - return str.replace(/\\([\-\[\/\{\}\(\)\*\+\?\.\\\^\$\|])/g, "$1"); + return str.replace(/\\([\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|])/g, "$1"); } export function isMatch(str: string | RegExp, pattern: string, options: number = 0) { @@ -69,7 +71,7 @@ export function replace( limit?: number, offset: number = 0): string { function replacer() { let res = arguments[0]; - if (limit !== 0) { + if (limit) { limit--; const match: any = []; const len = arguments.length; @@ -84,7 +86,7 @@ export function replace( } if (typeof reg === "string") { const tmp = reg as string; - reg = create(input, limit); + reg = create(input, limit ?? 0); input = tmp; limit = undefined; } @@ -93,7 +95,7 @@ export function replace( return input.substring(0, offset) + input.substring(offset).replace(reg as RegExp, replacer); } else { // $0 doesn't work with JS regex, see #1155 - replacement = replacement.replace(/\$0/g, (s) => "$&"); + replacement = replacement.replace(/\$0/g, (_s) => "$&"); if (limit != null) { let m: RegExpExecArray; const sub1 = input.substring(offset); @@ -110,7 +112,7 @@ export function replace( export function split(reg: string | RegExp, input: string, limit?: number, offset: number = 0) { if (typeof reg === "string") { const tmp = reg as string; - reg = create(input, limit); + reg = create(input, limit ?? 0); input = tmp; limit = undefined; } diff --git a/src/fable-library/Seq.ts b/src/fable-library/Seq.ts index fbed97117d..cfc07b3c70 100644 --- a/src/fable-library/Seq.ts +++ b/src/fable-library/Seq.ts @@ -1,12 +1,10 @@ -import Long, { makeRangeStepFunction } from "./Long"; -import { Some, some, value } from "./Option"; -import { compare, equals, IComparer, IDisposable, isDisposable } from "./Util"; - -declare type Long = typeof Long; -type Option = T | Some; +import Decimal, { makeRangeStepFunction as makeDecimalRangeStepFunction } from "./Decimal"; +import Long, { makeRangeStepFunction as makeLongRangeStepFunction } from "./Long"; +import { Option, some, value } from "./Option"; +import { compare, equals, IComparer, IDisposable } from "./Util"; export interface IEnumerator { - Current: T; + Current: T | undefined; MoveNext(): boolean; // Dispose(): void; // Reset(): void; @@ -28,7 +26,7 @@ interface IGenericAverager { } export class Enumerator implements IEnumerator { - private current: T; + private current?: T; constructor(private iter: Iterator) { } public MoveNext() { const cur = this.iter.next(); @@ -75,28 +73,55 @@ function __failIfNone(res: Option) { return value(res); } +function makeSeq(f: () => Iterator): Iterable { + const seq = { + [Symbol.iterator]: f, + toString: () => "seq [" + Array.from(seq).join("; ") + "]", + }; + return seq; +} + export function ofArray(xs: ArrayLike) { - return delay(() => unfold((i) => i < xs.length ? [xs[i], i + 1] : null, 0)); + return delay(() => unfold((i) => i != null && i < xs.length ? [xs[i], i + 1] : null, 0)); +} + +export function allPairs(xs: Iterable, ys: Iterable): Iterable<[T1, T2]> { + let firstEl = true; + const ysCache: T2[] = []; + return collect((x: T1) => { + if (firstEl) { + firstEl = false; + return map((y: T2) => { + ysCache.push(y); + return [x, y]; + }, ys); + } else { + return ysCache.map((y) => [x, y]); + // return map(function (i) { + // return [x, ysCache[i]]; + // }, rangeNumber(0, 1, ysCache.length - 1)); + } + }, xs); } export function append(xs: Iterable, ys: Iterable) { return delay(() => { let firstDone = false; const i = xs[Symbol.iterator](); - let iters = [i, null as Iterator]; + let iters = [i, null]; return unfold(() => { - let cur: IteratorResult; + let cur: IteratorResult | undefined; if (!firstDone) { - cur = iters[0].next(); - if (!cur.done) { + cur = iters[0]?.next(); + if (cur != null && !cur.done) { return [cur.value, iters]; } else { firstDone = true; - iters = [null as Iterator, ys[Symbol.iterator]()]; + iters = [null, ys[Symbol.iterator]()]; } } - cur = iters[1].next(); - return !cur.done ? [cur.value, iters] : null; + cur = iters[1]?.next(); + return cur != null && !cur.done ? [cur.value, iters] : null; }, iters); }); } @@ -119,7 +144,7 @@ export function averageBy(f: (a: T) => T2, xs: Iterable, averager: IGe return averager.DivideByInt(total, count); } -export function concat(xs: Iterable>) { +export function concat(xs: Iterable>): Iterable { return delay(() => { const iter = xs[Symbol.iterator](); let output: any = { value: null }; @@ -144,11 +169,11 @@ export function concat(xs: Iterable>) { } } return innerIter != null && output != null ? [output.value, innerIter] : null; - }, null); + }, null as Iterator | null); }); } -export function collect(f: (x: T) => Iterable, xs: Iterable) { +export function collect(f: (x: T) => Iterable, xs: Iterable): Iterable { return concat(map(f, xs)); } @@ -171,18 +196,23 @@ export function compareWith(f: (x: T, y: T) => number, xs: Iterable, ys: I return nonZero != null ? value(nonZero) : length(xs) - length(ys); } -export function delay(f: () => Iterable) { - return { - [Symbol.iterator]: () => f()[Symbol.iterator](), - } as Iterable; +export function delay(f: () => Iterable): Iterable { + return makeSeq(() => f()[Symbol.iterator]()); } -export function empty() { - return unfold((): [T, T] => void 0); +export function empty(): Iterable { + return unfold(() => null, undefined); +} + +export function enumerateFromFunctions( + factory: () => Enumerator, + moveNext: (e: Enumerator) => boolean, + current: (e: Enumerator) => T) { + return delay(() => unfold((e) => moveNext(e) ? [current(e), e] : null, factory())); } export function enumerateWhile(cond: () => boolean, xs: Iterable) { - return concat(unfold(() => cond() ? [xs, true] : null)); + return concat(unfold(() => cond() ? [xs, true] : null, undefined)); } export function enumerateThenFinally(xs: Iterable, finalFn: () => void) { @@ -191,7 +221,7 @@ export function enumerateThenFinally(xs: Iterable, finalFn: () => void) { try { iter = xs[Symbol.iterator](); } catch (err) { - return void 0; + return empty(); } finally { finalFn(); } @@ -200,7 +230,7 @@ export function enumerateThenFinally(xs: Iterable, finalFn: () => void) { const cur = it.next(); return !cur.done ? [cur.value, it] : null; } catch (err) { - return void 0; + return null; } finally { finalFn(); } @@ -247,7 +277,7 @@ export function except(itemsToExclude: Iterable, source: Iterable) { export function exists(f: (x: T) => boolean, xs: Iterable) { let cur: IteratorResult; - for (const iter = xs[Symbol.iterator](); ; ) { + for (const iter = xs[Symbol.iterator](); ;) { cur = iter.next(); if (cur.done) { break; } if (f(cur.value)) { return true; } @@ -258,7 +288,7 @@ export function exists(f: (x: T) => boolean, xs: Iterable) { export function exists2(f: (x: T1, y: T2) => boolean, xs: Iterable, ys: Iterable) { let cur1: IteratorResult; let cur2: IteratorResult; - for (const iter1 = xs[Symbol.iterator](), iter2 = ys[Symbol.iterator](); ; ) { + for (const iter1 = xs[Symbol.iterator](), iter2 = ys[Symbol.iterator](); ;) { cur1 = iter1.next(); cur2 = iter2.next(); if (cur1.done || cur2.done) { break; } @@ -268,11 +298,11 @@ export function exists2(f: (x: T1, y: T2) => boolean, xs: Iterable, } export function forAll(f: (x: T) => boolean, xs: Iterable) { - return !exists((x) => !f(x), xs); + return !exists((x) => !f(x), xs); } export function forAll2(f: (x: T1, y: T2) => boolean, xs: Iterable, ys: Iterable) { - return !exists2((x, y) => !f(x, y), xs, ys); + return !exists2((x, y) => !f(x, y), xs, ys); } export function contains(i: T, xs: Iterable) { @@ -351,7 +381,7 @@ export function tryHead(xs: Iterable): Option { return cur.done ? null : some(cur.value); } -export function head(xs: Iterable): T { +export function head(xs: Iterable) { return __failIfNone(tryHead(xs)); } @@ -384,24 +414,24 @@ export function tryItem(i: number, xs: Iterable): Option { return null; } -export function item(i: number, xs: Iterable): T { +export function item(i: number, xs: Iterable) { return __failIfNone(tryItem(i, xs)); } export function iterate(f: (x: T) => void, xs: Iterable) { - fold((_, x) => f(x), null, xs); + fold((_, x) => (f(x), null), null, xs); } export function iterate2(f: (x: T1, y: T2) => void, xs: Iterable, ys: Iterable) { - fold2((_, x, y) => f(x, y), null, xs, ys); + fold2((_, x, y) => (f(x, y), null), null, xs, ys); } export function iterateIndexed(f: (i: number, x: T) => void, xs: Iterable) { - fold((_, x, i) => f(i, x), null, xs); + fold((_, x, i) => (f(i ?? 0, x), null), null, xs); } export function iterateIndexed2(f: (i: number, x: T1, y: T2) => void, xs: Iterable, ys: Iterable) { - fold2((_, x, y, i) => f(i, x, y), null, xs, ys); + fold2((_, x, y, i) => (f(i ?? 0, x, y), null), null, xs, ys); } export function isEmpty(xs: Iterable) { @@ -413,17 +443,17 @@ export function tryLast(xs: Iterable): Option { return isEmpty(xs) ? null : some(reduce((_, x) => x, xs)); } -export function last(xs: Iterable): T { +export function last(xs: Iterable): T | null { return __failIfNone(tryLast(xs)); } export function length(xs: Iterable) { return Array.isArray(xs) || ArrayBuffer.isView(xs) ? (xs as T[]).length - : fold((acc, x) => acc + 1, 0, xs); + : fold((acc, _x) => acc + 1, 0, xs); } -export function map(f: (x: T) => U, xs: Iterable) { +export function map(f: (x: T) => U, xs: Iterable): Iterable { return delay(() => unfold((iter) => { const cur = iter.next(); return !cur.done ? [f(cur.value), iter] : null; @@ -452,7 +482,7 @@ export function map2(f: (x: T1, y: T2) => U, xs: Iterable, ys: It const cur1 = iter1.next(); const cur2 = iter2.next(); return !cur1.done && !cur2.done ? [f(cur1.value, cur2.value), null] : null; - }); + }, undefined); }); } @@ -465,7 +495,7 @@ export function mapIndexed2(f: (i: number, x: T1, y: T2) => U, xs: It const cur1 = iter1.next(); const cur2 = iter2.next(); return !cur1.done && !cur2.done ? [f(i++, cur1.value, cur2.value), null] : null; - }); + }, undefined); }); } @@ -480,7 +510,7 @@ export function map3( const cur2 = iter2.next(); const cur3 = iter3.next(); return !cur1.done && !cur2.done && !cur3.done ? [f(cur1.value, cur2.value, cur3.value), null] : null; - }); + }, undefined); }); } @@ -514,36 +544,51 @@ export function mapFoldBack( return transform !== void 0 ? [transform(result), acc] : [result, acc]; } -export function max(xs: Iterable, comparer?: IComparer) { +export function max(xs: Iterable, comparer?: IComparer) { const compareFn = comparer != null ? comparer.Compare : compare; return reduce((acc: T, x: T) => compareFn(acc, x) === 1 ? acc : x, xs); } -export function maxBy(f: (x: T) => U, xs: Iterable, comparer?: IComparer) { +export function maxBy(f: (x: T) => U, xs: Iterable, comparer?: IComparer) { const compareFn = comparer != null ? comparer.Compare : compare; return reduce((acc: T, x: T) => compareFn(f(acc), f(x)) === 1 ? acc : x, xs); } -export function min(xs: Iterable, comparer?: IComparer) { +export function min(xs: Iterable, comparer?: IComparer) { const compareFn = comparer != null ? comparer.Compare : compare; return reduce((acc: T, x: T) => compareFn(acc, x) === -1 ? acc : x, xs); } -export function minBy(f: (x: T) => U, xs: Iterable, comparer?: IComparer) { +export function minBy(f: (x: T) => U, xs: Iterable, comparer?: IComparer) { const compareFn = comparer != null ? comparer.Compare : compare; return reduce((acc: T, x: T) => compareFn(f(acc), f(x)) === -1 ? acc : x, xs); } -export function pairwise(xs: Iterable) { - return skip(2, scan((last, next) => [last[1], next], [0, 0], xs)); +export function pairwise(xs: Iterable): Iterable<[T, T]> { + return delay(() => { + const iter = xs[Symbol.iterator](); + const cur = iter.next(); + if (cur.done) { + return empty<[T, T]>(); + } + const hd = cur.value; + const tl = tail(xs); + const ys = scan(([_, last], next) => [last, next], [hd, hd], tl); + return skip(1, ys); + }); } export function rangeChar(first: string, last: string) { return delay(() => unfold((x) => x <= last ? [x, String.fromCharCode(x.charCodeAt(0) + 1)] : null, first)); } -export function rangeLong(first: Long, step: Long, last: Long, unsigned: boolean) { - const stepFn = makeRangeStepFunction(step, last, unsigned); +export function rangeLong(first: Long, step: Long, last: Long, unsigned: boolean): Iterable { + const stepFn = makeLongRangeStepFunction(step, last, unsigned); + return delay(() => unfold(stepFn as any, first)); +} + +export function rangeDecimal(first: Decimal, step: Decimal, last: Decimal): Iterable { + const stepFn = makeDecimalRangeStepFunction(step, last); return delay(() => unfold(stepFn as any, first)); } @@ -611,8 +656,8 @@ export function scan(f: (st: ST, x: T) => ST, seed: ST, xs: Iterable) acc = f(acc, cur.value); return [acc, acc]; } - return void 0; - }, null as ST); + return null; + }, null as ST | null); }); } @@ -620,22 +665,20 @@ export function scanBack(f: (x: T, st: ST) => ST, xs: Iterable, seed: return reverse(scan((acc, x) => f(x, acc), seed, reverse(xs))); } -export function singleton(y: T) { +export function singleton(y: T): Iterable { return [y]; } -export function skip(n: number, xs: Iterable) { - return { - [Symbol.iterator]: () => { - const iter = xs[Symbol.iterator](); - for (let i = 1; i <= n; i++) { - if (iter.next().done) { - throw new Error("Seq has not enough elements"); - } +export function skip(n: number, xs: Iterable): Iterable { + return makeSeq(() => { + const iter = xs[Symbol.iterator](); + for (let i = 1; i <= n; i++) { + if (iter.next().done) { + throw new Error("Seq has not enough elements"); } - return iter; - }, - } as Iterable; + } + return iter; + }); } export function skipWhile(f: (x: T) => boolean, xs: Iterable) { @@ -658,15 +701,8 @@ export function sumBy(f: (x: T) => T2, xs: Iterable, adder: IGenericAd return fold((acc, x) => adder.Add(acc, f(x)), adder.GetZero(), xs); } -export function tail(xs: Iterable) { - const iter = xs[Symbol.iterator](); - const cur = iter.next(); - if (cur.done) { - throw new Error("Seq was empty"); - } - return { - [Symbol.iterator]: () => iter, - } as Iterable; +export function tail(xs: Iterable): Iterable { + return skip(1, xs); } export function take(n: number, xs: Iterable, truncate: boolean = false) { @@ -682,7 +718,7 @@ export function take(n: number, xs: Iterable, truncate: boolean = false) { throw new Error("Seq has not enough elements"); } } - return void 0; + return null; }, 0); }); } @@ -694,12 +730,12 @@ export function truncate(n: number, xs: Iterable) { export function takeWhile(f: (x: T) => boolean, xs: Iterable) { return delay(() => { const iter = xs[Symbol.iterator](); - return unfold((i) => { + return unfold(() => { const cur = iter.next(); if (!cur.done && f(cur.value)) { return [cur.value, null]; } - return void 0; + return null; }, 0); }); } @@ -717,7 +753,7 @@ export function tryFind(f: (x: T, i?: number) => boolean, xs: Iterable, de return defaultValue === void 0 ? null : some(defaultValue); } -export function find(f: (x: T, i?: number) => boolean, xs: Iterable): T { +export function find(f: (x: T, i?: number) => boolean, xs: Iterable) { return __failIfNone(tryFind(f, xs)); } @@ -726,11 +762,11 @@ export function tryFindBack(f: (x: T, i?: number) => boolean, xs: Iterable return tryFind(f, arr.reverse(), defaultValue); } -export function findBack(f: (x: T, i?: number) => boolean, xs: Iterable): T { +export function findBack(f: (x: T, i?: number) => boolean, xs: Iterable) { return __failIfNone(tryFindBack(f, xs)); } -export function tryFindIndex(f: (x: T, i?: number) => boolean, xs: Iterable) { +export function tryFindIndex(f: (x: T, i?: number) => boolean, xs: Iterable): Option { for (let i = 0, iter = xs[Symbol.iterator](); ; i++) { const cur = iter.next(); if (cur.done) { @@ -743,13 +779,13 @@ export function tryFindIndex(f: (x: T, i?: number) => boolean, xs: Iterable(f: (x: T, i?: number) => boolean, xs: Iterable): number { +export function findIndex(f: (x: T, i?: number) => boolean, xs: Iterable) { return __failIfNone(tryFindIndex(f, xs)); } -export function tryFindIndexBack(f: (x: T, i?: number) => boolean, xs: Iterable) { +export function tryFindIndexBack(f: (x: T, i?: number) => boolean, xs: Iterable): Option { const arr = Array.isArray(xs) || ArrayBuffer.isView(xs) ? (xs as T[]).slice(0) : Array.from(xs); - for (let i = arr.length - 1; i >= 0 ; i--) { + for (let i = arr.length - 1; i >= 0; i--) { if (f(arr[i], i)) { return i; } @@ -757,7 +793,7 @@ export function tryFindIndexBack(f: (x: T, i?: number) => boolean, xs: Iterab return null; } -export function findIndexBack(f: (x: T, i?: number) => boolean, xs: Iterable): number { +export function findIndexBack(f: (x: T, i?: number) => boolean, xs: Iterable) { return __failIfNone(tryFindIndexBack(f, xs)); } @@ -775,60 +811,88 @@ export function tryPick(f: (x: T, i?: number) => Option, xs: Iterable(f: (x: T, i?: number) => Option, xs: Iterable): U { +export function pick(f: (x: T, i?: number) => Option, xs: Iterable) { return __failIfNone(tryPick(f, xs)); } -export function unfold(f: (st: ST) => [T, ST], fst?: ST) { - return { - [Symbol.iterator]: () => { - // Capture a copy of the first value in the closure - // so the sequence is restarted every time, see #1230 - let acc = fst; - return { - next: () => { - const res = f(acc); - if (res != null) { - acc = res[1]; - return { done: false, value: res[0] }; +export function unfold(f: (st: ST) => Option<[T, ST]>, fst: ST): Iterable { + return makeSeq(() => { + // Capture a copy of the first value in the closure + // so the sequence is restarted every time, see #1230 + let acc = fst; + const iter: Iterator = { + next: () => { + const res = f(acc); + if (res != null) { + const v = value(res); + if (v != null) { + acc = v[1]; + return { done: false, value: v[0] }; } - return { done: true }; - }, - }; - }, - } as Iterable; + } + return { done: true, value: undefined }; + }, + }; + return iter; + }); } -export function zip(xs: Iterable, ys: Iterable) { +export function zip(xs: Iterable, ys: Iterable): Iterable<[T1, T2]> { return map2((x, y) => [x, y], xs, ys); } -export function zip3(xs: Iterable, ys: Iterable, zs: Iterable) { +export function zip3(xs: Iterable, ys: Iterable, zs: Iterable): Iterable<[T1, T2, T3]> { return map3((x, y, z) => [x, y, z], xs, ys, zs); } export function windowed(windowSize: number, source: Iterable): Iterable { - if (windowSize <= 0) { - throw new Error("windowSize must be positive"); - } - return { - [Symbol.iterator]: () => { - let window: T[] = []; - const iter = source[Symbol.iterator](); - return { - next: () => { - let cur: IteratorResult; - while (window.length < windowSize) { - if ((cur = iter.next()).done) { - return { done: true }; - } - window.push(cur.value); - } - const value = window; - window = window.slice(1); - return { done: false, value }; - }, - }; - }, - } as Iterable; + if (windowSize <= 0) { + throw new Error("windowSize must be positive"); + } + return makeSeq(() => { + let window: T[] = []; + const iter = source[Symbol.iterator](); + const iter2: Iterator = { + next: () => { + let cur: IteratorResult; + while (window.length < windowSize) { + if ((cur = iter.next()).done) { + return { done: true, value: undefined }; + } + window.push(cur.value); + } + const value = window; + window = window.slice(1); + return { done: false, value }; + }, + }; + return iter2; + }); +} + +export function transpose(source: Iterable>): Iterable> { + return makeSeq(() => { + const iters = Array.from(source, (x) => x[Symbol.iterator]()); + const iter: Iterator> = { + next: () => { + if (iters.length === 0) { + return { done: true, value: undefined }; // empty sequence + } + const results = Array.from(iters, (iter) => iter.next()); + if (results[0].done) { + if (!results.every((x) => x.done)) { + throw new Error("Sequences have different lengths"); + } + return { done: true, value: undefined }; + } else { + if (!results.every((x) => !x.done)) { + throw new Error("Sequences have different lengths"); + } + const values: T[] = results.map((x) => x.value); + return { done: false, value: values }; + } + }, + }; + return iter; + }); } diff --git a/src/fable-library/Set.d.ts b/src/fable-library/Set.d.ts new file mode 100644 index 0000000000..2ce1858f69 --- /dev/null +++ b/src/fable-library/Set.d.ts @@ -0,0 +1,7 @@ +import { IEqualityComparer } from "./Util"; + +declare module "./Set" { + export function createMutable( + source: ReadonlyArray | null, + comparer: IEqualityComparer): Set; +} diff --git a/src/fable-library/Set.fs b/src/fable-library/Set.fs index 4f441c1cf8..52bd579fea 100644 --- a/src/fable-library/Set.fs +++ b/src/fable-library/Set.fs @@ -16,6 +16,7 @@ module Set open System.Collections open System.Collections.Generic +open Fable.Collections open Fable.Core (* A classic functional language implementation of binary trees *) @@ -666,16 +667,19 @@ let maxElement (s: Set<'T>) = s.MaximumElement /// Fable uses JS Set to represent .NET HashSet. However when keys are non-primitive, /// we need to disguise an F# set as a mutable set. Thus, this interface matches JS Set prototype. /// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set -type IMutableSet<'T> = - inherit IEnumerable<'T> - abstract size: int - abstract add: 'T -> IMutableSet<'T> - /// Convenience method (not in JS Set prototype) to check if the element has actually been added - abstract add_: 'T -> bool - abstract clear: unit -> unit - abstract delete: 'T -> bool - abstract has: 'T -> bool - abstract values: unit -> 'T seq + +// type IMutableSet<'T> = +// inherit IEnumerable<'T> +// abstract size: int +// abstract add: 'T -> IMutableSet<'T> +// /// Convenience method (not in JS Set prototype) to check if the element has actually been added +// abstract add_: 'T -> bool +// abstract clear: unit -> unit +// abstract delete: 'T -> bool +// abstract has: 'T -> bool +// abstract keys: unit -> 'T seq +// abstract values: unit -> 'T seq +// abstract entries: unit -> ('T * 'T) seq let private createMutablePrivate (comparer: IComparer<'T>) tree' = let mutable tree = tree' @@ -696,8 +700,12 @@ let private createMutablePrivate (comparer: IComparer<'T>) tree' = else false member __.has x = SetTree.mem comparer x tree + member __.keys () = + SetTree.toSeq tree member __.values () = SetTree.toSeq tree + member __.entries () = + SetTree.toSeq tree |> Seq.map (fun v -> (v, v)) interface IEnumerable<_> with member __.GetEnumerator() = SetTree.mkIEnumerator tree @@ -707,20 +715,30 @@ let private createMutablePrivate (comparer: IComparer<'T>) tree' = } /// Emulate JS Set with custom comparer for non-primitive values -let createMutable (source: seq<'T>) ([] comparer: IComparer<'T>) = - SetTree.ofSeq comparer source - |> createMutablePrivate comparer - -let distinct (xs: seq<'T>) ([] comparer: IComparer<'T>) = - createMutable xs comparer :> _ seq - -let distinctBy (projection: 'T -> 'Key) (xs: seq<'T>) ([] comparer: IComparer<'Key>) = - let li = ResizeArray() - let hashSet = createMutable Seq.empty comparer - for x in xs do - if projection x |> hashSet.add_ then - li.Add(x) - li :> _ seq + +// let createMutable (source: seq<'T>) ([] comparer: IComparer<'T>) = +// SetTree.ofSeq comparer source +// |> createMutablePrivate comparer + +let createMutable (source: seq<'T>) ([] comparer: IEqualityComparer<'T>) = + let set = MutableSet(source, comparer) + set :> IMutableSet<_> + +let distinct (xs: seq<'T>) ([] comparer: IEqualityComparer<'T>) = + seq { + let set = MutableSet(Seq.empty, comparer) + for x in xs do + if set.Add(x) then + yield x + } + +let distinctBy (projection: 'T -> 'Key) (xs: seq<'T>) ([] comparer: IEqualityComparer<'Key>) = + seq { + let set = MutableSet(Seq.empty, comparer) + for x in xs do + if set.Add(projection x) then + yield x + } // Helpers to replicate HashSet methods diff --git a/src/fable-library/String.ts b/src/fable-library/String.ts index f880732341..aa434d4058 100644 --- a/src/fable-library/String.ts +++ b/src/fable-library/String.ts @@ -1,15 +1,66 @@ import { toString as dateToString } from "./Date"; import Decimal from "./Decimal"; -import Long, { fromBytes as longFromBytes, toBytes as longToBytes, toString as longToString } from "./Long"; +import Long, * as _Long from "./Long"; import { escape } from "./RegExp"; -const fsFormatRegExp = /(^|[^%])%([0+ ]*)(-?\d+)?(?:\.(\d+))?(\w)/; +const fsFormatRegExp = /(^|[^%])%([0+\- ]*)(\d+)?(?:\.(\d+))?(\w)/; const formatRegExp = /\{(\d+)(,-?\d+)?(?:\:([a-zA-Z])(\d{0,2})|\:(.+?))?\}/g; // RFC 4122 compliant. From https://stackoverflow.com/a/13653180/3922220 // const guidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; // Relax GUID parsing, see #1637 const guidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +type Numeric = number | Long | Decimal; + +// These are used for formatting and only take longs and decimals into account (no bigint) +function isNumeric(x: any) { + return typeof x === "number" || x instanceof Long || x instanceof Decimal; +} + +function isLessThan(x: Numeric, y: number) { + if (x instanceof Long) { + return _Long.compare(x, y) < 0; + } else if (x instanceof Decimal) { + return x.cmp(y) < 0; + } else { + return x < y; + } +} + +function multiply(x: Numeric, y: number) { + if (x instanceof Long) { + return _Long.op_Multiply(x, y); + } else if (x instanceof Decimal) { + return x.mul(y); + } else { + return x * y; + } +} + +function toFixed(x: Numeric, dp?: number) { + if (x instanceof Long) { + return String(x) + (0).toFixed(dp).substr(1); + } else { + return x.toFixed(dp); + } +} + +function toPrecision(x: Numeric, sd?: number) { + if (x instanceof Long) { + return String(x) + (0).toPrecision(sd).substr(1); + } else { + return x.toPrecision(sd); + } +} + +function toExponential(x: Numeric, dp?: number) { + if (x instanceof Long) { + return String(x) + (0).toExponential(dp).substr(1); + } else { + return x.toExponential(dp); + } +} + const enum StringComparison { CurrentCulture = 0, CurrentCultureIgnoreCase = 1, @@ -96,7 +147,7 @@ export function indexOfAny(str: string, anyOf: string[], ...args: number[]) { function toHex(x: any) { if (x instanceof Long) { - return longToString(x.unsigned ? x : longFromBytes(longToBytes(x), true), 16); + return _Long.toString(x.unsigned ? x : _Long.fromBytes(_Long.toBytes(x), true), 16); } else { return (Number(x) >>> 0).toString(16); } @@ -134,33 +185,62 @@ export function toFail(arg: IPrintfFormat) { return arg.cont((x) => { throw new Error(x); }); } -function formatOnce(str2: any, rep: any) { - return str2.replace(fsFormatRegExp, - (_: any, prefix: any, flags: any, pad: any, precision: any, format: any) => { +function formatOnce(str2: string, rep: any) { + return str2.replace(fsFormatRegExp, (_, prefix, flags, padLength, precision, format) => { + let sign = ""; + if (isNumeric(rep)) { + if (format.toLowerCase() !== "x") { + if (isLessThan(rep, 0)) { + rep = multiply(rep, -1); + sign = "-"; + } else { + if (flags.indexOf(" ") >= 0) { + sign = " "; + } else if (flags.indexOf("+") >= 0) { + sign = "+"; + } + } + } + precision = precision == null ? null : parseInt(precision, 10); switch (format) { case "f": case "F": - rep = Number(rep).toFixed(precision || 6); break; + precision = precision != null ? precision : 6; + rep = toFixed(rep, precision); + break; case "g": case "G": - rep = Number(rep).toPrecision(precision); break; + rep = precision != null ? toPrecision(rep, precision) : toPrecision(rep); + break; case "e": case "E": - rep = Number(rep).toExponential(precision); break; - case "O": - case "A": - rep = String(rep); break; + rep = precision != null ? toExponential(rep, precision) : toExponential(rep); + break; case "x": - rep = toHex(rep); break; + rep = toHex(rep); + break; case "X": - rep = toHex(rep).toUpperCase(); break; + rep = toHex(rep).toUpperCase(); + break; + default: // AOid + rep = String(rep); + break; } - const plusPrefix = flags.indexOf("+") >= 0 && parseInt(rep, 10) >= 0; - pad = parseInt(pad, 10); - if (!isNaN(pad)) { - const ch = pad >= 0 && flags.indexOf("0") >= 0 ? "0" : " "; - rep = padLeft(String(rep), Math.abs(pad) - (plusPrefix ? 1 : 0), ch, pad < 0); + } + padLength = parseInt(padLength, 10); + if (!isNaN(padLength)) { + const zeroFlag = flags.indexOf("0") >= 0; // Use '0' for left padding + const minusFlag = flags.indexOf("-") >= 0; // Right padding + const ch = minusFlag || !zeroFlag ? " " : "0"; + if (ch === "0") { + rep = padLeft(rep, padLength - sign.length, ch, minusFlag); + rep = sign + rep; + } else { + rep = padLeft(sign + rep, padLength, ch, minusFlag); } - const once = prefix + (plusPrefix ? "+" + rep : rep); - return once.replace(/%/g, "%%"); - }); + } else { + rep = sign + rep; + } + const once = prefix + rep; + return once.replace(/%/g, "%%"); + }); } function createPrinter(str: string, cont: (...args: any[]) => any) { @@ -191,55 +271,55 @@ export function format(str: string, ...args: any[]) { args.shift(); } - return str.replace(formatRegExp, - (match: any, idx: any, pad: any, format: any, precision: any, pattern: any) => { - let rep = args[idx]; - let padSymbol = " "; - const isNumericType = (typeof rep === "number") || (rep instanceof Long); - // TODO: || (rep instanceof Decimal) || (rep instanceof BigInt); - if (isNumericType) { - switch (format) { - case "f": case "F": - rep = precision ? rep.toFixed(precision) : rep.toFixed(2); - break; - case "g": case "G": - rep = precision ? rep.toPrecision(precision) : rep.toPrecision(); - break; - case "e": case "E": - rep = precision ? rep.toExponential(precision) : rep.toExponential(); - break; - case "p": case "P": - rep = (precision ? (rep * 100).toFixed(precision) : (rep * 100).toFixed(2)) + " %"; - break; - case "d": case "D": - rep = precision ? padLeft(rep.toString(), precision, "0") : rep.toString(); - break; - case "x": case "X": - rep = precision ? padLeft(toHex(rep), precision, "0") : toHex(rep); - if (format === "X") { rep = rep.toUpperCase(); } - break; - default: - const m = /^(0+)(\.0+)?$/.exec(pattern); - if (m != null) { - let decs = 0; - if (m[2] != null) { - rep = rep.toFixed(decs = m[2].length - 1); + return str.replace(formatRegExp, (_, idx, padLength, format, precision, pattern) => { + let rep = args[idx]; + if (isNumeric(rep)) { + precision = precision == null ? null : parseInt(precision, 10); + switch (format) { + case "f": case "F": + precision = precision != null ? precision : 2; + rep = toFixed(rep, precision); + break; + case "g": case "G": + rep = precision != null ? toPrecision(rep, precision) : toPrecision(rep); + break; + case "e": case "E": + rep = precision != null ? toExponential(rep, precision) : toExponential(rep); + break; + case "p": case "P": + precision = precision != null ? precision : 2; + rep = toFixed(multiply(rep, 100), precision) + " %"; + break; + case "d": case "D": + rep = precision != null ? padLeft(String(rep), precision, "0") : String(rep); + break; + case "x": case "X": + rep = precision != null ? padLeft(toHex(rep), precision, "0") : toHex(rep); + if (format === "X") { rep = rep.toUpperCase(); } + break; + default: + if (pattern) { + let sign = ""; + rep = (pattern as string).replace(/(0+)(\.0+)?/, (_, intPart, decimalPart) => { + if (isLessThan(rep, 0)) { + rep = multiply(rep, -1); + sign = "-"; } - pad = "," + (m[1].length + (decs ? decs + 1 : 0)).toString(); - padSymbol = "0"; - } else if (pattern) { - rep = pattern; - } - } - } else if (rep instanceof Date) { - rep = dateToString(rep, pattern || format); - } - pad = parseInt((pad || "").substring(1), 10); - if (!isNaN(pad)) { - rep = padLeft(String(rep), Math.abs(pad), padSymbol, pad < 0); + rep = toFixed(rep, decimalPart != null ? decimalPart.length - 1 : 0); + return padLeft(rep, (intPart || "").length - sign.length + (decimalPart != null ? decimalPart.length : 0), "0"); + }); + rep = sign + rep; + } } - return rep; - }); + } else if (rep instanceof Date) { + rep = dateToString(rep, pattern || format); + } + padLength = parseInt((padLength || " ").substring(1), 10); + if (!isNaN(padLength)) { + rep = padLeft(String(rep), Math.abs(padLength), " ", padLength < 0); + } + return rep; + }); } export function endsWith(str: string, search: string) { @@ -273,16 +353,24 @@ export function isNullOrWhiteSpace(str: string | any) { return typeof str !== "string" || /^\s*$/.test(str); } -export function join(delimiter: string, ...xs: any[]): string { - return xs.map((x) => String(x)).join(delimiter); +export function concat(...xs: any[]): string { + return xs.map((x) => String(x)).join(""); } -export function joinWithIndices(delimiter: string, xs: string[], startIndex: number, count: number) { +export function join(delimiter: string, xs: Iterable): string { + if (Array.isArray(xs)) { + return xs.join(delimiter); + } else { + return Array.from(xs).join(delimiter); + } +} + +export function joinWithIndices(delimiter: string, xs: string[], startIndex: number, count: number) { const endIndexPlusOne = startIndex + count; if (endIndexPlusOne > xs.length) { throw new Error("Index and count must refer to a location within the buffer."); } - return join(delimiter, ...xs.slice(startIndex, endIndexPlusOne)); + return xs.slice(startIndex, endIndexPlusOne).join(delimiter); } /** Validates UUID as specified in RFC4122 (versions 1-5). Trims braces. */ @@ -364,14 +452,16 @@ export function arrayToGuid(buf: ArrayLike) { if (!_convertMapsInitialized) { initConvertMaps(); } - return _byteToHex[buf[3]] + _byteToHex[buf[2]] + - _byteToHex[buf[1]] + _byteToHex[buf[0]] + "-" + - _byteToHex[buf[5]] + _byteToHex[buf[4]] + "-" + - _byteToHex[buf[7]] + _byteToHex[buf[6]] + "-" + - _byteToHex[buf[8]] + _byteToHex[buf[9]] + "-" + - _byteToHex[buf[10]] + _byteToHex[buf[11]] + - _byteToHex[buf[12]] + _byteToHex[buf[13]] + - _byteToHex[buf[14]] + _byteToHex[buf[15]]; + const guid = + _byteToHex[buf[3]] + _byteToHex[buf[2]] + + _byteToHex[buf[1]] + _byteToHex[buf[0]] + "-" + + _byteToHex[buf[5]] + _byteToHex[buf[4]] + "-" + + _byteToHex[buf[7]] + _byteToHex[buf[6]] + "-" + + _byteToHex[buf[8]] + _byteToHex[buf[9]] + "-" + + _byteToHex[buf[10]] + _byteToHex[buf[11]] + + _byteToHex[buf[12]] + _byteToHex[buf[13]] + + _byteToHex[buf[14]] + _byteToHex[buf[15]]; + return guid; } function valueToCharCode(c: number) { @@ -493,9 +583,9 @@ export function getCharAtIndex(input: string, index: number) { } export function split(str: string, splitters: string[], count?: number, removeEmpty?: number) { - count = typeof count === "number" ? count : null; - removeEmpty = typeof removeEmpty === "number" ? removeEmpty : null; - if (count < 0) { + count = typeof count === "number" ? count : undefined; + removeEmpty = typeof removeEmpty === "number" ? removeEmpty : undefined; + if (count && count < 0) { throw new Error("Count cannot be less than zero"); } if (count === 0) { @@ -554,3 +644,10 @@ export function trimEnd(str: string, ...chars: string[]) { export function filter(pred: (char: string) => boolean, x: string) { return x.split("").filter((c) => pred(c)).join(""); } + +export function substring(str: string, startIndex: number, length?: number) { + if ((startIndex + (length || 0) > str.length)) { + throw new Error("Invalid startIndex and/or length"); + } + return length != null ? str.substr(startIndex, length) : str.substr(startIndex); +} diff --git a/src/fable-library/System.Collections.Generic.fs b/src/fable-library/System.Collections.Generic.fs new file mode 100644 index 0000000000..e0b4e1065c --- /dev/null +++ b/src/fable-library/System.Collections.Generic.fs @@ -0,0 +1,17 @@ +namespace System.Collections.Generic + +type Comparer<'T when 'T : comparison>() = + static member Default = + { new IComparer<'T> with + member __.Compare(x, y) = LanguagePrimitives.GenericComparison x y } + interface IComparer<'T> with + member __.Compare(x, y) = LanguagePrimitives.GenericComparison x y + +type EqualityComparer<'T when 'T : equality>() = + static member Default = + { new IEqualityComparer<'T> with + member __.Equals(x, y) = LanguagePrimitives.GenericEquality x y + member __.GetHashCode(x) = LanguagePrimitives.GenericHash x } + interface IEqualityComparer<'T> with + member __.Equals(x, y) = LanguagePrimitives.GenericEquality x y + member __.GetHashCode(x) = LanguagePrimitives.GenericHash x diff --git a/src/fable-library/System.Text.fs b/src/fable-library/System.Text.fs index fd646b21bf..190cb21951 100644 --- a/src/fable-library/System.Text.fs +++ b/src/fable-library/System.Text.fs @@ -7,5 +7,12 @@ type StringBuilder(value: string, capacity: int) = new (value: string) = StringBuilder(value, 16) new () = StringBuilder(null, 16) member x.Append(s: string) = buf.Add(s); x + member x.Append(c: char) = buf.Add(string c); x member x.AppendFormat(fmt: string, o: obj) = buf.Add(System.String.Format(fmt, o)); x + member x.AppendLine() = buf.Add(System.Environment.NewLine); x + member x.AppendLine(s: string) = buf.Add(s); buf.Add(System.Environment.NewLine); x override __.ToString() = System.String.Concat(buf) + member x.Length = buf |> Seq.sumBy String.length + member x.ToString(firstIndex: int, length: int) = + let str = x.ToString() + str.Substring(firstIndex, length) diff --git a/src/fable-library/TimeSpan.ts b/src/fable-library/TimeSpan.ts index 7ed4482b47..c8b1616a62 100644 --- a/src/fable-library/TimeSpan.ts +++ b/src/fable-library/TimeSpan.ts @@ -1,8 +1,19 @@ -import { fromNumber, op_Division, op_Multiply, toNumber } from "./Long"; +// tslint:disable:max-line-length +import Long, { fromNumber, op_Division, op_Multiply, toNumber } from "./Long"; import { comparePrimitives, padLeftAndRightWithZeros, padWithZeros } from "./Util"; // TimeSpan in runtime just becomes a number representing milliseconds +/** + * Calls: + * - `Math.ceil` if the `value` is **negative** + * - `Math.floor` if the `value` is **positive** + * @param value Value to round + */ +function signedRound(value: number) { + return value < 0 ? Math.ceil(value) : Math.floor(value); +} + export function create(d: number = 0, h: number = 0, m: number = 0, s: number = 0, ms: number = 0) { switch (arguments.length) { case 1: @@ -19,7 +30,7 @@ export function create(d: number = 0, h: number = 0, m: number = 0, s: number = return d * 86400000 + h * 3600000 + m * 60000 + s * 1000 + ms; } -export function fromTicks(ticks: number /* Long */) { +export function fromTicks(ticks: Long) { return toNumber(op_Division(ticks, 10000)); } @@ -40,26 +51,26 @@ export function fromSeconds(s: number) { } export function days(ts: number) { - return Math.floor(ts / 86400000); + return signedRound(ts / 86400000); } export function hours(ts: number) { - return Math.floor(ts % 86400000 / 3600000); + return signedRound(ts % 86400000 / 3600000); } export function minutes(ts: number) { - return Math.floor(ts % 3600000 / 60000); + return signedRound(ts % 3600000 / 60000); } export function seconds(ts: number) { - return Math.floor(ts % 60000 / 1000); + return signedRound(ts % 60000 / 1000); } export function milliseconds(ts: number) { - return Math.floor(ts % 1000); + return signedRound(ts % 1000); } -export function ticks(ts: number /* Long */) { +export function ticks(ts: number) { return op_Multiply(fromNumber(ts), 10000); } @@ -101,55 +112,67 @@ export function duration(x: number) { return Math.abs(x); } -export function toString(ts: number, format = "c") { +export function toString(ts: number, format = "c", _provider?: any) { if (["c", "g", "G"].indexOf(format) === -1) { throw new Error("Custom formats are not supported"); } - const d = days(ts); - const h = hours(ts); - const m = minutes(ts); - const s = seconds(ts); - const ms = milliseconds(ts); - // tslint:disable-next-line:max-line-length - return `${d === 0 && (format === "c" || format === "g") ? "" : format === "c" ? d + "." : d + ":" }${format === "g" ? h : padWithZeros(h, 2)}:${padWithZeros(m, 2)}:${padWithZeros(s, 2)}${ms === 0 && (format === "c" || format === "g") ? "" : format === "g" ? "." + padWithZeros(ms, 3) : "." + padLeftAndRightWithZeros(ms, 3, 7)}`; + const d = Math.abs(days(ts)); + const h = Math.abs(hours(ts)); + const m = Math.abs(minutes(ts)); + const s = Math.abs(seconds(ts)); + const ms = Math.abs(milliseconds(ts)); + const sign = ts < 0 ? "-" : ""; + return `${sign}${d === 0 && (format === "c" || format === "g") ? "" : format === "c" ? d + "." : d + ":"}${format === "g" ? h : padWithZeros(h, 2)}:${padWithZeros(m, 2)}:${padWithZeros(s, 2)}${ms === 0 && (format === "c" || format === "g") ? "" : format === "g" ? "." + padWithZeros(ms, 3) : "." + padLeftAndRightWithZeros(ms, 3, 7)}`; } export function parse(str: string) { const firstDot = str.search("\\."); const firstColon = str.search("\\:"); - if (firstDot === -1 && firstColon === -1 ) { // There is only a day ex: 4 + if (firstDot === -1 && firstColon === -1) { // There is only a day ex: 4 const d = parseInt(str, 0); if (isNaN(d)) { - throw new Error("String was not recognized as a valid TimeSpan."); + throw new Error(`String '${str}' was not recognized as a valid TimeSpan.`); } else { return create(d, 0, 0, 0, 0); } } if (firstColon > 0) { // process time part - // tslint:disable-next-line:max-line-length - const r = /^((\d+)\.)?(?:0*)([0-9]|0[0-9]|1[0-9]|2[0-3]):(?:0*)([0-5][0-9]|[0-9])(:(?:0*)([0-5][0-9]|[0-9]))?\.?(\d+)?$/.exec(str); - if (r != null && r[3] != null && r[4] != null) { + // WIP: (-?)(((\d+)\.)?([0-9]|0[0-9]|1[0-9]|2[0-3]):(\d+)(:\d+(\.\d{1,7})?)?|\d+(?:(?!\.))) + const r = /^(-?)((\d+)\.)?(?:0*)([0-9]|0[0-9]|1[0-9]|2[0-3]):(?:0*)([0-5][0-9]|[0-9])(:(?:0*)([0-5][0-9]|[0-9]))?\.?(\d+)?$/.exec(str); + if (r != null && r[4] != null && r[5] != null) { let d = 0; let ms = 0; let s = 0; - const h = +r[3]; - const m = +r[4]; - if (r[2] != null) { - d = +r[2]; - } - if (r[6] != null) { - s = +r[6]; + const sign = r[1] != null && r[1] === "-" ? -1 : 1; + const h = +r[4]; + const m = +r[5]; + if (r[3] != null) { + d = +r[3]; } if (r[7] != null) { - ms = +r[7]; + s = +r[7]; + } + if (r[8] != null) { + // Depending on the number of decimals passed, we need to adapt the numbers + switch (r[8].length) { + case 1: ms = +r[8] * 100; break; + case 2: ms = +r[8] * 10; break; + case 3: ms = +r[8]; break; + case 4: ms = +r[8] / 10; break; + case 5: ms = +r[8] / 100; break; + case 6: ms = +r[8] / 1000; break; + case 7: ms = +r[8] / 10000; break; + default: + throw new Error(`String '${str}' was not recognized as a valid TimeSpan.`); + } } - return create(d, h, m, s, ms); + return sign * create(d, h, m, s, ms); } } - throw new Error("String was not recognized as a valid TimeSpan."); + throw new Error(`String '${str}' was not recognized as a valid TimeSpan.`); } -export function tryParse(v: any): [boolean, number] { +export function tryParse(v: string, _refValue?: any): [boolean, number] { try { return [true, parse(v)]; } catch (_err) { diff --git a/src/fable-library/Timer.ts b/src/fable-library/Timer.ts index 546c887571..f75a88b858 100644 --- a/src/fable-library/Timer.ts +++ b/src/fable-library/Timer.ts @@ -6,13 +6,13 @@ export default class Timer implements IDisposable { public AutoReset: boolean; private _elapsed: Event; - private _enabled: boolean; - private _isDisposed: boolean; - private _intervalId: number; - private _timeoutId: number; + private _enabled: boolean = false; + private _isDisposed: boolean = false; + private _intervalId: number = 0; + private _timeoutId: number = 0; constructor(interval?: number) { - this.Interval = interval > 0 ? interval : 100; + this.Interval = interval && interval > 0 ? interval : 100; this.AutoReset = true; this._elapsed = new Event(); } diff --git a/src/fable-library/Types.js b/src/fable-library/Types.js deleted file mode 100644 index 08652db54e..0000000000 --- a/src/fable-library/Types.js +++ /dev/null @@ -1,281 +0,0 @@ -import { combineHashCodes, compare, compareArrays, equals, equalArrays, identityHash, structuralHash, numberHash } from "./Util"; - -function sameType(x, y) { - return y != null && Object.getPrototypeOf(x).constructor === Object.getPrototypeOf(y).constructor; -} - -// Taken from Babel helpers -function inherits(subClass, superClass) { - // if (typeof superClass !== "function" && superClass !== null) { - // throw new TypeError( - // "Super expression must either be null or a function, not " + - // typeof superClass - // ); - // } - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true, - }, - }); - // if (superClass) - // Object.setPrototypeOf - // ? Object.setPrototypeOf(subClass, superClass) - // : (subClass.__proto__ = superClass); -} - -export function declare(cons, superClass) { - inherits(cons, superClass || SystemObject); - return cons; -} - -export function SystemObject() { -} - -SystemObject.prototype.toString = function() { - return "{" + Object.keys(this).map(k => k + " = " + String(this[k])).join(";\n ") + "}"; -}; - -SystemObject.prototype.GetHashCode = function() { - return identityHash(this); -}; - -SystemObject.prototype.Equals = function(other) { - return this === other; -}; - -function compareList(self, other) { - if (self === other) { - return 0; - } else { - if (other == null) { - return -1; - } - while (self.tail != null) { - if (other.tail == null) { return 1; } - const res = compare(self.head, other.head); - if (res !== 0) { return res; } - self = self.tail; - other = other.tail; - } - return other.tail == null ? 0 : -1; - } -} - -export function List(head, tail) { - this.head = head; - this.tail = tail; -} - -List.prototype.toString = function() { - return "[" + Array.from(this).map(x => String(x)).join("; ") + "]"; -}; - -List.prototype.toJSON = function() { - return Array.from(this); -}; - -List.prototype[Symbol.iterator] = function() { - let cur = this; - return { - next: () => { - const tmp = cur; - cur = cur.tail; - return { done: tmp.tail == null, value: tmp.head }; - }, - }; -}; - -List.prototype.GetHashCode = function() { - const hashes = Array.from(this).map(structuralHash); - return combineHashCodes(hashes); -}; - -List.prototype.Equals = function(other) { - return compareList(this, other) === 0; -}; - -List.prototype.CompareTo = function(other) { - return compareList(this, other); -}; - -export function Union(tag, name, ...fields) { - this.tag = tag | 0; - this.name = name; - this.fields = fields; -} - -Union.prototype.toString = function() { - const len = this.fields.length; - if (len === 0) { - return this.name; - } else if (len === 1) { - return this.name + " " + String(this.fields[0]); - } else { - return this.name + " (" + this.fields.map(x => String(x)).join(",") + ")"; - } -}; - -Union.prototype.toJSON = function() { - return this.fields.length === 0 - ? this.name - : [this.name].concat(this.fields); -}; - -Union.prototype.GetHashCode = function() { - let hashes = this.fields.map(x => structuralHash(x)); - hashes.splice(0, 0, numberHash(this.tag)); - return combineHashCodes(hashes); -}; - -Union.prototype.Equals = function(other) { - return this === other - || (sameType(this, other) - && this.tag === other.tag - && equalArrays(this.fields, other.fields)); -}; - -Union.prototype.CompareTo = function(other) { - if (this === other) { - return 0; - } else if (!sameType(this, other)) { - return -1; - } else if (this.tag === other.tag) { - return compareArrays(this.fields, other.fields); - } else { - return this.tag < other.tag ? -1 : 1; - } -}; - -function recordToJson(record, getFieldNames) { - const o = {}; - const keys = getFieldNames == null ? Object.keys(record) : getFieldNames(record); - for (let i = 0; i < keys.length; i++) { - o[keys[i]] = record[keys[i]]; - } - return o; -} - -function recordEquals(self, other, getFieldNames) { - if (self === other) { - return true; - } else if (!sameType(self, other)) { - return false; - } else { - const thisNames = getFieldNames == null ? Object.keys(self) : getFieldNames(self); - for (let i = 0; i < thisNames.length; i++) { - if (!equals(self[thisNames[i]], other[thisNames[i]])) { - return false; - } - } - return true; - } -} - -function recordCompare(self, other, getFieldNames) { - if (self === other) { - return 0; - } else if (!sameType(self, other)) { - return -1; - } else { - const thisNames = getFieldNames == null ? Object.keys(self) : getFieldNames(self); - for (let i = 0; i < thisNames.length; i++) { - const result = compare(self[thisNames[i]], other[thisNames[i]]); - if (result !== 0) { - return result; - } - } - return 0; - } -} - -export function Record() { -} - -Record.prototype.toString = function() { - return "{" + Object.keys(this).map(k => k + " = " + String(this[k])).join(";\n ") + "}"; -}; - -Record.prototype.toJSON = function() { - return recordToJson(this); -}; - -Record.prototype.GetHashCode = function() { - const hashes = Object.keys(this).map(k => structuralHash(this[k])); - return combineHashCodes(hashes); -}; - -Record.prototype.Equals = function(other) { - return recordEquals(this, other); -}; - -Record.prototype.CompareTo = function(other) { - return recordCompare(this, other); -}; - -export function anonRecord(o) { - return Object.assign(Object.create(Record.prototype), o); -} - -export const FSharpRef = declare(function FSharpRef(contents) { - this.contents = contents; -}, Record); - -// EXCEPTIONS - -export const Exception = declare(function Exception(msg) { - this.stack = Error().stack; - this.message = msg; -}); - -export function isException(x) { - return x instanceof Error || x instanceof Exception; -} - -function getFSharpExceptionFieldNames(self) { - return Object.keys(self).filter(k => k !== "message" && k !== "stack"); -} - -export const FSharpException = declare(function FSharpException() { - Exception.call(this); -}, Exception); - -FSharpException.prototype.toString = function() { - const fieldNames = getFSharpExceptionFieldNames(this); - const len = fieldNames.length; - if (len === 0) { - return this.message; - } else if (len === 1) { - return this.message + " " + String(this[fieldNames[0]]); - } else { - return this.message + " (" + fieldNames.map(k => String(this[k])).join(",") + ")"; - } -}; - -FSharpException.prototype.toJSON = function() { - return recordToJson(this, getFSharpExceptionFieldNames); -}; - -FSharpException.prototype.GetHashCode = function() { - const hashes = getFSharpExceptionFieldNames(this).map(k => structuralHash(this[k])); - return combineHashCodes(hashes); -}; - -FSharpException.prototype.Equals = function(other) { - return recordEquals(this, other, getFSharpExceptionFieldNames); -}; - -FSharpException.prototype.CompareTo = function(other) { - return recordCompare(this, other, getFSharpExceptionFieldNames); -}; - -export const MatchFailureException = declare(function MatchFailureException(arg1, arg2, arg3) { - this.arg1 = arg1; - this.arg2 = arg2 | 0; - this.arg3 = arg3 | 0; - this.message = "The match cases were incomplete"; -}, FSharpException); - -export const Attribute = declare(function Attribute() { }); diff --git a/src/fable-library/Types.ts b/src/fable-library/Types.ts new file mode 100644 index 0000000000..5d348490e5 --- /dev/null +++ b/src/fable-library/Types.ts @@ -0,0 +1,335 @@ +// tslint:disable: space-before-function-paren +import { combineHashCodes, compare, compareArrays, equalArrays, equals, identityHash, numberHash, structuralHash } from "./Util"; + +function sameType(x: any, y: any) { + return y != null && Object.getPrototypeOf(x).constructor === Object.getPrototypeOf(y).constructor; +} + +// Taken from Babel helpers +function inherits(subClass: any, superClass: any) { + // if (typeof superClass !== "function" && superClass !== null) { + // throw new TypeError( + // "Super expression must either be null or a function, not " + + // typeof superClass + // ); + // } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true, + }, + }); + // if (superClass) + // Object.setPrototypeOf + // ? Object.setPrototypeOf(subClass, superClass) + // : (subClass.__proto__ = superClass); +} + +export function declare(cons: any, superClass?: any) { + inherits(cons, superClass || SystemObject); + return cons; +} + +export interface IEquatable { + Equals(other: any): boolean; +} + +export interface IHashable { + GetHashCode(): number; +} + +export interface IComparable { + CompareTo(other: any): number; +} + +export interface SystemObject { + Equals(other: any): boolean; + GetHashCode(): number; +} + +export function SystemObject() { + return; +} + +SystemObject.prototype.toString = function () { + return "{" + Object.keys(this).map((k) => k + " = " + String(this[k])).join(";\n ") + "}"; +}; + +SystemObject.prototype.GetHashCode = function () { + return identityHash(this); +}; + +SystemObject.prototype.Equals = function (other: any) { + return this === other; +}; + +function compareList(self: List, other: List) { + if (self === other) { + return 0; + } else { + if (other == null) { + return -1; + } + while (self.tail != null) { + if (other.tail == null) { return 1; } + const res = compare(self.head, other.head); + if (res !== 0) { return res; } + self = self.tail; + other = other.tail; + } + return other.tail == null ? 0 : -1; + } +} + +export class List implements SystemObject, IComparable, Iterable { + public head: T; + public tail?: List; + + constructor(head?: T, tail?: List) { + this.head = head as T; + this.tail = tail; + } + + public toString() { + return "[" + Array.from(this).join("; ") + "]"; + } + + public toJSON() { + return Array.from(this); + } + + public [Symbol.iterator](): Iterator { + let cur: List | undefined = this; + return { + next: (): IteratorResult => { + const value = cur?.head as T; + const done = cur?.tail == null; + cur = cur?.tail; + return { done, value }; + }, + }; + } + + public GetHashCode() { + const hashes = Array.from(this).map(structuralHash); + return combineHashCodes(hashes); + } + + public Equals(other: List): boolean { + return compareList(this, other) === 0; + } + + public CompareTo(other: List): number { + return compareList(this, other); + } +} + +export interface Union extends SystemObject, IComparable { + tag: number; + name: string; + fields: any[]; +} + +export function Union(this: Union, tag: number, name: string, ...fields: any[]) { + this.tag = tag | 0; + this.name = name; + this.fields = fields; +} + +Union.prototype.toString = function () { + const len = this.fields.length; + if (len === 0) { + return this.name; + } else if (len === 1) { + return this.name + " " + String(this.fields[0]); + } else { + return this.name + " (" + this.fields.map((x: any) => String(x)).join(",") + ")"; + } +}; + +Union.prototype.toJSON = function () { + return this.fields.length === 0 + ? this.name + : [this.name].concat(this.fields); +}; + +Union.prototype.GetHashCode = function () { + const hashes = this.fields.map((x: any) => structuralHash(x)); + hashes.splice(0, 0, numberHash(this.tag)); + return combineHashCodes(hashes); +}; + +Union.prototype.Equals = function (other: any) { + return this === other + || (sameType(this, other) + && this.tag === other.tag + && equalArrays(this.fields, other.fields)); +}; + +Union.prototype.CompareTo = function (other: any) { + if (this === other) { + return 0; + } else if (!sameType(this, other)) { + return -1; + } else if (this.tag === other.tag) { + return compareArrays(this.fields, other.fields); + } else { + return this.tag < other.tag ? -1 : 1; + } +}; + +function recordToJson(record: any, getFieldNames?: (arg: any) => any) { + const o: any = {}; + const keys = getFieldNames == null ? Object.keys(record) : getFieldNames(record); + for (let i = 0; i < keys.length; i++) { + o[keys[i]] = record[keys[i]]; + } + return o; +} + +function recordEquals(self: any, other: any, getFieldNames?: (arg: any) => any) { + if (self === other) { + return true; + } else if (!sameType(self, other)) { + return false; + } else { + const thisNames = getFieldNames == null ? Object.keys(self) : getFieldNames(self); + for (let i = 0; i < thisNames.length; i++) { + if (!equals(self[thisNames[i]], other[thisNames[i]])) { + return false; + } + } + return true; + } +} + +function recordCompare(self: any, other: any, getFieldNames?: (arg: any) => any) { + if (self === other) { + return 0; + } else if (!sameType(self, other)) { + return -1; + } else { + const thisNames = getFieldNames == null ? Object.keys(self) : getFieldNames(self); + for (let i = 0; i < thisNames.length; i++) { + const result = compare(self[thisNames[i]], other[thisNames[i]]); + if (result !== 0) { + return result; + } + } + return 0; + } +} + +export interface Record extends SystemObject, IComparable { +} + +export function Record() { + return; +} + +Record.prototype.toString = function () { + return "{" + Object.keys(this).map((k) => k + " = " + String(this[k])).join(";\n ") + "}"; +}; + +Record.prototype.toJSON = function () { + return recordToJson(this); +}; + +Record.prototype.GetHashCode = function () { + const hashes = Object.keys(this).map((k) => structuralHash(this[k])); + return combineHashCodes(hashes); +}; + +Record.prototype.Equals = function (other: any) { + return recordEquals(this, other); +}; + +Record.prototype.CompareTo = function (other: any) { + return recordCompare(this, other); +}; + +export function anonRecord(o: any) { + return Object.assign(Object.create(Record.prototype), o); +} + +export interface FSharpRef extends Record { + contents: T; +} + +export const FSharpRef = declare(function FSharpRef(this: FSharpRef, contents: T) { + this.contents = contents; +}, Record); + +// EXCEPTIONS + +export interface Exception extends SystemObject { + stack?: string; + message?: string; +} + +export const Exception = declare(function Exception(this: Exception, message?: string) { + this.stack = Error().stack; + this.message = message; +}, SystemObject); + +export function isException(x: any) { + return x instanceof Error || x instanceof Exception; +} + +function getFSharpExceptionFieldNames(self: any) { + return Object.keys(self).filter((k) => k !== "message" && k !== "stack"); +} + +export interface FSharpException extends Exception, IComparable { +} + +export const FSharpException = declare(function FSharpException(this: FSharpException) { + Exception.call(this); +}, Exception); + +FSharpException.prototype.toString = function () { + const fieldNames = getFSharpExceptionFieldNames(this); + const len = fieldNames.length; + if (len === 0) { + return this.message; + } else if (len === 1) { + return this.message + " " + String(this[fieldNames[0]]); + } else { + return this.message + " (" + fieldNames.map((k) => String(this[k])).join(",") + ")"; + } +}; + +FSharpException.prototype.toJSON = function () { + return recordToJson(this, getFSharpExceptionFieldNames); +}; + +FSharpException.prototype.GetHashCode = function () { + const hashes = getFSharpExceptionFieldNames(this).map((k) => structuralHash(this[k])); + return combineHashCodes(hashes); +}; + +FSharpException.prototype.Equals = function (other: any) { + return recordEquals(this, other, getFSharpExceptionFieldNames); +}; + +FSharpException.prototype.CompareTo = function (other: any) { + return recordCompare(this, other, getFSharpExceptionFieldNames); +}; + +export interface MatchFailureException extends FSharpException { + arg1: string; + arg2: number; + arg3: number; +} + +export const MatchFailureException = declare( + function MatchFailureException(this: MatchFailureException, arg1: string, arg2: number, arg3: number) { + this.arg1 = arg1; + this.arg2 = arg2 | 0; + this.arg3 = arg3 | 0; + this.message = "The match cases were incomplete"; + }, FSharpException); + +export const Attribute = declare(function Attribute() { return; }, SystemObject); diff --git a/src/fable-library/Uri.ts b/src/fable-library/Uri.ts index b9c3209aaf..5f42ec38b5 100644 --- a/src/fable-library/Uri.ts +++ b/src/fable-library/Uri.ts @@ -5,8 +5,8 @@ export const enum UriKind { } export default class Uri { - private url: string | URL; - private kind: UriKind; + private url?: string | URL; + private kind?: UriKind; constructor( value: string | Uri, @@ -26,7 +26,7 @@ export default class Uri { let isRelativeUrl = false; try { const url = new URL(value); - isRelativeUrl = false; + isRelativeUrl = false && url; } catch (e) { isRelativeUrl = true; } @@ -61,6 +61,10 @@ export default class Uri { } } + public toString() { + return decodeURIComponent(this.parseUrl().toString()); + } + private parseUrl(): URL { if (this.kind === UriKind.Absolute) { return this.url as URL; @@ -76,7 +80,6 @@ export default class Uri { get isAbsoluteUri() { try { this.parseUrl(); - return true; } catch (e) { return false; diff --git a/src/fable-library/Util.ts b/src/fable-library/Util.ts index d3ecc848c0..87ed49f0eb 100644 --- a/src/fable-library/Util.ts +++ b/src/fable-library/Util.ts @@ -5,7 +5,8 @@ export function extend(target: any, ...sources: any[]) { for (const source of sources) { for (const key of Object.keys(source)) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + const descr = Object.getOwnPropertyDescriptor(source, key); + if (descr) { Object.defineProperty(target, key, descr); } } } return target; @@ -43,12 +44,40 @@ export interface IEquatable { Equals(x: T): boolean; } +export interface IHashable { + GetHashCode(): number; +} + export interface IDisposable { Dispose(): void; } -export function isDisposable(x: any) { - return x != null && typeof x.Dispose === "function"; +export function isIterable(x: T | Iterable): x is Iterable { + return x != null && typeof x === "object" && Symbol.iterator in x; +} + +export function isArrayLike(x: T | ArrayLike): x is ArrayLike { + return x != null && (Array.isArray(x) || ArrayBuffer.isView(x)); +} + +export function isComparer(x: T | IComparer): x is IComparer { + return x != null && typeof (x as IComparer).Compare === "function"; +} + +export function isComparable(x: T | IComparable): x is IComparable { + return x != null && typeof (x as IComparable).CompareTo === "function"; +} + +export function isEquatable(x: T | IEquatable): x is IEquatable { + return x != null && typeof (x as IEquatable).Equals === "function"; +} + +export function isHashable(x: T | IHashable): x is IHashable { + return x != null && typeof (x as IHashable).GetHashCode === "function"; +} + +export function isDisposable(x: T | IDisposable): x is IDisposable { + return x != null && typeof (x as IDisposable).Dispose === "function"; } export class Comparer implements IComparer { @@ -59,10 +88,10 @@ export class Comparer implements IComparer { } } -export function comparerFromEqualityComparer(comparer: IEqualityComparer) { +export function comparerFromEqualityComparer(comparer: IEqualityComparer): IComparer { // Sometimes IEqualityComparer also implements IComparer - if (typeof (comparer as any).Compare === "function") { - return new Comparer((comparer as any).Compare); + if (isComparer(comparer)) { + return new Comparer((comparer as any as IComparer).Compare); } else { return new Comparer((x: T, y: T) => { const xhash = comparer.GetHashCode(x); @@ -86,8 +115,8 @@ export function containsValue(v: V, map: Map) { return false; } -export function tryGetValue(map: Map, key: K, defaultValue: V): [boolean, V] { - return map.has(key) ? [true, map.get(key)] : [false, defaultValue]; +export function tryGetValue(map: Map, key: K, defaultValue: V | null): [boolean, V] { + return map.has(key) ? [true, map.get(key) as V] : [false, defaultValue as V]; } export function addToSet(v: T, set: Set) { @@ -120,7 +149,7 @@ export class Lazy { public factory: () => T; public isValueCreated: boolean; - private createdValue: T; + private createdValue?: T; constructor(factory: () => T) { this.factory = factory; @@ -214,7 +243,7 @@ export function combineHashCodes(hashes: number[]) { }); } -export function identityHash(x: any): number { +export function identityHash(x: T): number { if (x == null) { return 0; } @@ -230,7 +259,7 @@ export function identityHash(x: any): number { } } -export function structuralHash(x: any): number { +export function structuralHash(x: T): number { if (x == null) { return 0; } @@ -242,14 +271,13 @@ export function structuralHash(x: any): number { case "string": return stringHash(x); default: { - if (typeof x.GetHashCode === "function") { + if (isHashable(x)) { return x.GetHashCode(); - } else if (isArray(x)) { - const ar = (x as ArrayLike); - const len = ar.length; + } else if (isArrayLike(x)) { + const len = x.length; const hashes: number[] = new Array(len); for (let i = 0; i < len; i++) { - hashes[i] = structuralHash(ar[i]); + hashes[i] = structuralHash(x[i]); } return combineHashCodes(hashes); } else { @@ -259,14 +287,6 @@ export function structuralHash(x: any): number { } } -export function isArray(x: any) { - return Array.isArray(x) || ArrayBuffer.isView(x); -} - -export function isIterable(x: any) { - return x != null && typeof x === "object" && Symbol.iterator in x; -} - export function equalArraysWith(x: ArrayLike, y: ArrayLike, eq: (x: T, y: T) => boolean): boolean { if (x == null) { return y == null; } if (y == null) { return false; } @@ -299,7 +319,7 @@ export function equalArrays(x: ArrayLike, y: ArrayLike): boolean { // return true; // } -export function equals(x: any, y: any): boolean { +export function equals(x: T, y: T): boolean { if (x === y) { return true; } else if (x == null) { @@ -308,10 +328,10 @@ export function equals(x: any, y: any): boolean { return false; } else if (typeof x !== "object") { return false; - } else if (typeof x.Equals === "function") { + } else if (isEquatable(x)) { return x.Equals(y); - } else if (isArray(x)) { - return isArray(y) && equalArrays(x, y); + } else if (isArrayLike(x)) { + return isArrayLike(y) && equalArrays(x, y); } else if (x instanceof Date) { return (y instanceof Date) && compareDates(x, y) === 0; } else { @@ -378,7 +398,7 @@ export function compareObjects(x: { [k: string]: any }, y: { [k: string]: any }) return 0; } -export function compare(x: any, y: any): number { +export function compare(x: T, y: T): number { if (x === y) { return 0; } else if (x == null) { @@ -387,12 +407,12 @@ export function compare(x: any, y: any): number { return 1; } else if (typeof x !== "object") { return x < y ? -1 : 1; - } else if (typeof x.CompareTo === "function") { + } else if (isComparable(x)) { return x.CompareTo(y); - } else if (isArray(x)) { - return isArray(y) && compareArrays(x, y); - } else if (x instanceof Date) { - return (y instanceof Date) && compareDates(x, y); + } else if (isArrayLike(x) && isArrayLike(y)) { + return compareArrays(x, y); + } else if (x instanceof Date && y instanceof Date) { + return compareDates(x, y); } else { return 1; } @@ -408,7 +428,7 @@ export function max(comparer: (x: T, y: T) => number, x: T, y: T) { export function createAtom(value: T): (v?: T) => T | void { let atom = value; - return (value: T) => { + return (value?: T) => { if (value === void 0) { return atom; } else { @@ -421,12 +441,27 @@ export function createAtom(value: T): (v?: T) => T | void { const CaseRules = { None: 0, LowerFirst: 1, + SnakeCase: 2, + SnakeCaseAllCaps: 3, + KebabCase: 4, }; +function dashify(str: string, separator: string) { + return str.replace(/[a-z]?[A-Z]/g, (m) => m.length === 1 + ? m.toLowerCase() + : m.charAt(0) + separator + m.charAt(1).toLowerCase()); +} + function changeCase(str: string, caseRule: number) { switch (caseRule) { case CaseRules.LowerFirst: return str.charAt(0).toLowerCase() + str.slice(1); + case CaseRules.SnakeCase: + return dashify(str, "_"); + case CaseRules.SnakeCaseAllCaps: + return dashify(str, "_").toUpperCase(); + case CaseRules.KebabCase: + return dashify(str, "-"); case CaseRules.None: default: return str; @@ -529,12 +564,20 @@ export function escapeUriString(s: string): string { // ICollection.Clear and Count members can be called on Arrays // or Dictionaries so we need a runtime check (see #1120) export function count(col: Iterable): number { - return isArray(col) ? (col as any).length : (col as any).size; + if (isArrayLike(col)) { + return col.length; + } else { + let count = 0; + for (const _ of col) { + count++; + } + return count; + } } export function clear(col: Iterable) { - if (isArray(col)) { - (col as any).splice(0); + if (isArrayLike(col)) { + (col as any as T[]).splice(0); } else { (col as any).clear(); } @@ -548,7 +591,7 @@ export function uncurry(arity: number, f: Function) { // The function is already uncurried if (f.length > 1) { -// if (CURRIED_KEY in f) { // This doesn't always work + // if (CURRIED_KEY in f) { // This doesn't always work return f; } @@ -584,10 +627,10 @@ export function uncurry(arity: number, f: Function) { return uncurriedFn; } -export function curry(arity: number, f: Function): Function { - if (f == null) { return null; } +export function curry(arity: number, f: Function): Function | undefined { + if (f == null) { return undefined; } if (CURRIED_KEY in f) { - return (f as any)[CURRIED_KEY]; + return (f as any)[CURRIED_KEY]; } switch (arity) { case 2: @@ -618,8 +661,8 @@ export function partialApply(arity: number, f: Function, args: any[]): any { return null; } else if (CURRIED_KEY in f) { f = (f as any)[CURRIED_KEY]; - for (var i = 0; i < args.length; i++) { - f = f(args[i]); + for (let i = 0; i < args.length; i++) { + f = f(args[i]); } return f; } else { @@ -656,30 +699,26 @@ export function partialApply(arity: number, f: Function, args: any[]): any { type CurriedArgMapping = [number, number] | 0; export function mapCurriedArgs(fn: Function, mappings: CurriedArgMapping[]) { - function mapArg(fn: Function, arg: any, mappings: CurriedArgMapping[], idx: number) { - const mapping = mappings[idx]; - if (mapping !== 0) { - const expectedArity = mapping[0]; - const actualArity = mapping[1]; - if (expectedArity > 1) { - arg = curry(expectedArity, arg); - } - if (actualArity > 1) { - arg = uncurry(actualArity, arg); - } - } - const res = fn(arg); - if (idx + 1 === mappings.length) { - return res; - } else { - return function(arg: any) { - return mapArg(res, arg, mappings, idx + 1) - } - } + function mapArg(fn: Function, arg: any, mappings: CurriedArgMapping[], idx: number) { + const mapping = mappings[idx]; + if (mapping !== 0) { + const expectedArity = mapping[0]; + const actualArity = mapping[1]; + if (expectedArity > 1) { + arg = curry(expectedArity, arg); + } + if (actualArity > 1) { + arg = uncurry(actualArity, arg); + } } - return function (arg: any) { - return mapArg(fn, arg, mappings, 0); + const res = fn(arg); + if (idx + 1 === mappings.length) { + return res; + } else { + return (arg: any) => mapArg(res, arg, mappings, idx + 1); } + } + return (arg: any) => mapArg(fn, arg, mappings, 0); } export function addToDict(dict: Map, k: K, v: V) { @@ -689,9 +728,9 @@ export function addToDict(dict: Map, k: K, v: V) { dict.set(k, v); } -export function getItemFromDict(map: Map, key: K): V { +export function getItemFromDict(map: Map, key: K) { if (map.has(key)) { - return map.get(key); + return map.get(key) as V; } else { throw new Error(`The given key '${key}' was not present in the dictionary.`); } diff --git a/src/fable-library/lib/long.d.ts b/src/fable-library/lib/long.d.ts new file mode 100644 index 0000000000..a7455eb273 --- /dev/null +++ b/src/fable-library/lib/long.d.ts @@ -0,0 +1,392 @@ +// Type definitions for long.js 4.0.0 +// Project: https://github.com/dcodeIO/long.js +// Definitions by: Peter Kooijmans +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions by: Denis Cappellin + +export default Long; + +export declare class Long { + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as signed integers. See the from* functions below for more convenient ways of constructing Longs. + */ + constructor(low: number, high?: number, unsigned?: boolean); + + /** + * The high 32 bits as a signed value. + */ + high: number; + + /** + * The low 32 bits as a signed value. + */ + low: number; + + /** + * Whether unsigned or not. + */ + unsigned: boolean; +} + +/** + * Maximum unsigned value. + */ +export const MAX_UNSIGNED_VALUE: Long; + +/** + * Maximum signed value. + */ +export const MAX_VALUE: Long; + +/** + * Minimum signed value. + */ +export const MIN_VALUE: Long; + +/** + * Signed negative one. + */ +export const NEG_ONE: Long; + +/** + * Signed one. + */ +export const ONE: Long; + +/** + * Unsigned one. + */ +export const UONE: Long; + +/** + * Unsigned zero. + */ +export const UZERO: Long; + +/** + * Signed zero + */ +export const ZERO: Long; + +/** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits. + */ +export function fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long; + +/** + * Returns a Long representing the given 32 bit integer value. + */ +export function fromInt(value: number, unsigned?: boolean): Long; + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + */ +export function fromNumber(value: number, unsigned?: boolean): Long; + +/** + * Returns a Long representation of the given string, written using the specified radix. + */ +export function fromString(str: string, unsigned?: boolean | number, radix?: number): Long; + +/** + * Creates a Long from its byte representation. + */ +export function fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long; + +/** + * Creates a Long from its little endian byte representation. + */ +export function fromBytesLE(bytes: number[], unsigned?: boolean): Long; + +/** + * Creates a Long from its little endian byte representation. + */ +export function fromBytesBE(bytes: number[], unsigned?: boolean): Long; + +/** + * Tests if the specified object is a Long. + */ +export function isLong(obj: any): boolean; + +/** + * Converts the specified value to a Long. + */ +export function fromValue(val: Long | number | string | { low: number, high: number, unsigned: boolean }, unsigned?: boolean): Long; + +/** + * Returns the sum of this and the specified Long. + */ +export function add($this: Long, addend: number | Long | string): Long; + +/** + * Returns the bitwise AND of this Long and the specified. + */ +export function and($this: Long, other: Long | number | string): Long; + +/** + * Compares this Long's value with the specified's. + */ +export function compare($this: Long, other: Long | number | string): number; + +/** + * Compares this Long's value with the specified's. + */ +// export function comp($this: Long, other: Long | number | string): number; + +/** + * Returns this Long divided by the specified. + */ +export function divide($this: Long, divisor: Long | number | string): Long; + +/** + * Returns this Long divided by the specified. + */ +// export function div($this: Long, divisor: Long | number | string): Long; + +/** + * Tests if this Long's value equals the specified's. + */ +export function equals($this: Long, other: Long | number | string): boolean; + +/** + * Tests if this Long's value equals the specified's. + */ +// export function eq($this: Long, other: Long | number | string): boolean; + +/** + * Gets the high 32 bits as a signed integer. + */ +export function getHighBits($this: Long): number; + +/** + * Gets the high 32 bits as an unsigned integer. + */ +export function getHighBitsUnsigned($this: Long): number; + +/** + * Gets the low 32 bits as a signed integer. + */ +export function getLowBits($this: Long): number; + +/** + * Gets the low 32 bits as an unsigned integer. + */ +export function getLowBitsUnsigned($this: Long): number; + +/** + * Gets the number of bits needed to represent the absolute value of this Long. + */ +export function getNumBitsAbs($this: Long): number; + +/** + * Tests if this Long's value is greater than the specified's. + */ +export function greaterThan($this: Long, other: Long | number | string): boolean; + +/** + * Tests if this Long's value is greater than the specified's. + */ +// export function gt($this: Long, other: Long | number | string): boolean; + +/** + * Tests if this Long's value is greater than or equal the specified's. + */ +export function greaterThanOrEqual($this: Long, other: Long | number | string): boolean; + +/** + * Tests if this Long's value is greater than or equal the specified's. + */ +// export function gte($this: Long, other: Long | number | string): boolean; + +/** + * Tests if this Long's value is even. + */ +export function isEven($this: Long): boolean; + +/** + * Tests if this Long's value is negative. + */ +export function isNegative($this: Long): boolean; + +/** + * Tests if this Long's value is odd. + */ +export function isOdd($this: Long): boolean; + +/** + * Tests if this Long's value is positive. + */ +export function isPositive($this: Long): boolean; + +/** + * Tests if this Long's value equals zero. + */ +export function isZero(): boolean; + +/** + * Tests if this Long's value is less than the specified's. + */ +export function lessThan($this: Long, other: Long | number | string): boolean; + +/** + * Tests if this Long's value is less than the specified's. + */ +// export function lt($this: Long, other: Long | number | string): boolean; + +/** + * Tests if this Long's value is less than or equal the specified's. + */ +export function lessThanOrEqual($this: Long, other: Long | number | string): boolean; + +/** + * Tests if this Long's value is less than or equal the specified's. + */ +// export function lte($this: Long, other: Long | number | string): boolean; + +/** + * Returns this Long modulo the specified. + */ +export function modulo($this: Long, other: Long | number | string): Long; + +/** + * Returns this Long modulo the specified. + */ +// export function mod($this: Long, other: Long | number | string): Long; + +/** + * Returns the product of this and the specified Long. + */ +export function multiply($this: Long, multiplier: Long | number | string): Long; + +/** + * Returns the product of this and the specified Long. + */ +// export function mul($this: Long, multiplier: Long | number | string): Long; + +/** + * Negates this Long's value. + */ +export function negate($this: Long): Long; + +/** + * Negates this Long's value. + */ +// export function neg($this: Long): Long; + +/** + * Returns the bitwise NOT of this Long. + */ +export function not($this: Long): Long; + +/** + * Tests if this Long's value differs from the specified's. + */ +export function notEquals($this: Long, other: Long | number | string): boolean; + +/** + * Tests if this Long's value differs from the specified's. + */ +// export function neq($this: Long, other: Long | number | string): boolean; + +/** + * Returns the bitwise OR of this Long and the specified. + */ +export function or($this: Long, other: Long | number | string): Long; + +/** + * Returns this Long with bits shifted to the left by the given amount. + */ +export function shiftLeft($this: Long, numBits: number | Long): Long; + +/** + * Returns this Long with bits shifted to the left by the given amount. + */ +// export function shl($this: Long, numBits: number | Long): Long; + +/** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + */ +export function shiftRight($this: Long, numBits: number | Long): Long; + +/** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + */ +// export function shr($this: Long, numBits: number | Long): Long; + +/** + * Returns this Long with bits logically shifted to the right by the given amount. + */ +export function shiftRightUnsigned($this: Long, numBits: number | Long): Long; + +/** + * Returns this Long with bits logically shifted to the right by the given amount. + */ +// export function shru($this: Long, numBits: number | Long): Long; + +/** + * Returns the difference of this and the specified Long. + */ +export function subtract($this: Long, subtrahend: number | Long | string): Long; + +/** + * Returns the difference of this and the specified Long. + */ +// export function sub($this: Long, subtrahend: number | Long | string): Long; + +/** + * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. + */ +export function toInt($this: Long): number; + +/** + * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). + */ +export function toNumber($this: Long): number; + +/** + * Converts this Long to its byte representation. + */ + +export function toBytes($this: Long, le?: boolean): number[]; + +/** + * Converts this Long to its little endian byte representation. + */ + +export function toBytesLE($this: Long): number[]; + +/** + * Converts this Long to its big endian byte representation. + */ + +export function toBytesBE($this: Long): number[]; + +/** + * Converts this Long to signed. + */ +export function toSigned($this: Long): Long; + +/** + * Converts the Long to a string written in the specified radix. + */ +export function toString($this: Long, radix?: number): string; + +/** + * Converts this Long to unsigned. + */ +export function toUnsigned($this: Long): Long; + +/** + * Returns the bitwise XOR of this Long and the given one. + */ +export function xor($this: Long, other: Long | number | string): Long; + +/** + * Returns this Long with bits rotated to the left by the given amount. + */ +export function rotateLeft($this: Long, numBits: number): Long; + +/** + * Returns this Long with bits rotated to the right by the given amount. + */ +export function rotateRight($this: Long, numBits: number): Long; diff --git a/src/fable-library/Long.js b/src/fable-library/lib/long.js similarity index 68% rename from src/fable-library/Long.js rename to src/fable-library/lib/long.js index 75ea93f721..6247c3e2f1 100644 --- a/src/fable-library/Long.js +++ b/src/fable-library/lib/long.js @@ -1,9 +1,6 @@ -// Adapted from: https://github.com/dcodeIO/long.js/blob/f572e3a17d313730cf11eb838f6d2a5e31626f8a/src/long.js +// Adapted from: https://github.com/dcodeIO/long.js/blob/master/src/long.js // Apache License 2.0: https://github.com/dcodeIO/long.js/blob/master/LICENSE - -/* tslint:disable */ -import { isValid } from "./Int32"; -import { combineHashCodes } from "./Util"; +export default Long; /** * wasm optimizations, to do native i64 multiplication and divide @@ -28,7 +25,7 @@ try { * @param {boolean=} unsigned Whether unsigned or not, defaults to signed * @constructor */ -export default function Long(low, high, unsigned) { +export function Long(low, high, unsigned) { /** * The low 32 bits as a signed value. @@ -50,26 +47,16 @@ export default function Long(low, high, unsigned) { } Long.prototype.GetHashCode = function () { - return combineHashCodes([this.unsigned ? 1 : 0, this.high, this.low]); + let h1 = this.unsigned ? 1 : 0; + h1 = ((h1 << 5) + h1) ^ this.high; + h1 = ((h1 << 5) + h1) ^ this.low; + return h1; } Long.prototype.Equals = function (x) { return equals(this, x); } Long.prototype.CompareTo = function (x) { return compare(this, x); } Long.prototype.toString = function (radix) { return toString(this, radix); } Long.prototype.toJSON = function () { return toString(this); } -export const neg = op_UnaryNegation; -export const not = op_LogicalNot; -export const add = op_Addition; -export const sub = op_Subtraction; -export const mul = op_Multiply; -export const div = op_Division; -export const mod = op_Modulus; -export const shl = op_LeftShift; -export const shr = op_RightShift; -export const and = op_BitwiseAnd; -export const or = op_BitwiseOr; -export const xor = op_ExclusiveOr; - // The internal representation of a long is the two given signed, 32-bit values. // We use 32-bit pieces because these are the size of integers on which // Javascript performs bit-operations. For operations like addition and @@ -103,10 +90,18 @@ Object.defineProperty(Long.prototype, "__isLong__", { value: true }); * @returns {boolean} * @inner */ -function isLong(obj) { +export function isLong(obj) { return (obj && obj["__isLong__"]) === true; } +/** + * Tests if the specified object is a Long. + * @function + * @param {*} obj Object + * @returns {boolean} + */ +// Long.isLong = isLong; + /** * A cache of the Long representations of small integer values. * @type {!Object} @@ -154,6 +149,14 @@ export function fromInt(value, unsigned) { } } +/** + * Returns a Long representing the given 32 bit integer value. + * @function + * @param {number} value The 32 bit integer in question + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ +// Long.fromInt = fromInt; /** * @param {number} value @@ -176,32 +179,18 @@ export function fromNumber(value, unsigned) { return MAX_VALUE; } if (value < 0) - return op_UnaryNegation(fromNumber(-value, unsigned)); + return negate(fromNumber(-value, unsigned)); return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); } /** - * @param {number} value - * @param {boolean} unsigned - * @param {number} kind - * @returns {!Long} - * @inner + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @function + * @param {number} value The number in question + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value */ -export function fromInteger(value, unsigned, kind) { - var x; - var xh = 0; - switch (kind) { - case 0: x = value << 24 >> 24; xh = x; break; - case 4: x = value << 24 >>> 24; break; - case 1: x = value << 16 >> 16; xh = x; break; - case 5: x = value << 16 >>> 16; break; - case 2: x = value >> 0; xh = x; break; - case 6: x = value >>> 0; - } - return fromBits(x, xh >> 31, unsigned); -} - - +// Long.fromNumber = fromNumber; /** * @param {number} lowBits @@ -214,6 +203,17 @@ export function fromBits(lowBits, highBits, unsigned) { return new Long(lowBits, highBits, unsigned); } +/** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is + * assumed to use 32 bits. + * @function + * @param {number} lowBits The low 32 bits + * @param {number} highBits The high 32 bits + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ +// Long.fromBits = fromBits; + /** * @function * @param {number} base @@ -250,7 +250,7 @@ export function fromString(str, unsigned, radix) { if (p > 0) throw Error('interior hyphen'); else if (p === 0) { - return op_UnaryNegation(fromString(str.substring(1), unsigned, radix)); + return negate(fromString(str.substring(1), unsigned, radix)); } // Do several (8) digits each time through the loop, so as to @@ -263,61 +263,25 @@ export function fromString(str, unsigned, radix) { value = parseInt(str.substring(i, i + size), radix); if (size < 8) { var power = fromNumber(pow_dbl(radix, size)); - result = op_Addition(op_Multiply(result, power), fromNumber(value)); + result = add(multiply(result, power), fromNumber(value)); } else { - result = op_Multiply(result, radixToPower); - result = op_Addition(result, fromNumber(value)); + result = multiply(result, radixToPower); + result = add(result, fromNumber(value)); } } result.unsigned = unsigned; return result; } -function getMaxValue(unsigned, radix, isNegative) { - switch (radix) { - case 2: return unsigned ? - "1111111111111111111111111111111111111111111111111111111111111111" : - (isNegative ? "1000000000000000000000000000000000000000000000000000000000000000" - : "111111111111111111111111111111111111111111111111111111111111111"); - case 8: return unsigned ? - "1777777777777777777777" : - (isNegative ? "1000000000000000000000" : "777777777777777777777"); - case 10: return unsigned ? - "18446744073709551615" : - (isNegative ? "9223372036854775808" : "9223372036854775807"); - case 16: return unsigned ? - "FFFFFFFFFFFFFFFF" : - (isNegative ? "8000000000000000" : "7FFFFFFFFFFFFFFF"); - default: throw new Error("Invalid radix."); - } -} - -export function parse(str, style, unsigned, bitsize, radix) { - const res = isValid(str, style, radix); - if (res != null) { - const lessOrEqual = (x, y) => { - const len = Math.max(x.length, y.length); - return x.padStart(len, "0") <= maxValue.padStart(len, "0"); - } - const isNegative = res.sign === "-"; - const maxValue = getMaxValue(unsigned || res.radix !== 10, res.radix, isNegative); - if (lessOrEqual(res.digits, maxValue)) { - str = isNegative ? res.sign + res.digits : res.digits; - return fromString(str, unsigned, res.radix); - } - } - throw new Error("Input string was not in a correct format."); -} - -export function tryParse(str, style, unsigned, bitsize) { - try { - const v = parse(str, style, unsigned, bitsize); - return [true, v]; - } catch { - // supress error - } - return [false, ZERO]; -} +/** + * Returns a Long representation of the given string, written using the specified radix. + * @function + * @param {string} str The textual representation of the Long + * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed + * @param {number=} radix The radix in which the text is written (2-36), defaults to 10 + * @returns {!Long} The corresponding Long value + */ +// Long.fromString = fromString; /** * @function @@ -335,6 +299,15 @@ export function fromValue(val, unsigned) { return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); } +/** + * Converts the specified value to a Long using the appropriate from* function for its type. + * @function + * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} + */ +// Long.fromValue = fromValue; + // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be // no runtime penalty for these. @@ -386,50 +359,105 @@ var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); */ export var ZERO = fromInt(0); +/** + * Signed zero. + * @type {!Long} + */ +// Long.ZERO = ZERO; + /** * @type {!Long} * @inner */ export var UZERO = fromInt(0, true); +/** + * Unsigned zero. + * @type {!Long} + */ +// Long.UZERO = UZERO; + /** * @type {!Long} * @inner */ export var ONE = fromInt(1); +/** + * Signed one. + * @type {!Long} + */ +// Long.ONE = ONE; + /** * @type {!Long} * @inner */ export var UONE = fromInt(1, true); +/** + * Unsigned one. + * @type {!Long} + */ +// Long.UONE = UONE; + /** * @type {!Long} * @inner */ export var NEG_ONE = fromInt(-1); +/** + * Signed negative one. + * @type {!Long} + */ +// Long.NEG_ONE = NEG_ONE; + /** * @type {!Long} * @inner */ export var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false); +/** + * Maximum signed value. + * @type {!Long} + */ +// Long.MAX_VALUE = MAX_VALUE; + /** * @type {!Long} * @inner */ export var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true); +/** + * Maximum unsigned value. + * @type {!Long} + */ +// Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; + /** * @type {!Long} * @inner */ export var MIN_VALUE = fromBits(0, 0x80000000|0, false); +/** + * Minimum signed value. + * @type {!Long} + */ +// Long.MIN_VALUE = MIN_VALUE; + +/** + * @alias Long.prototype + * @inner + */ +// var LongPrototype = Long.prototype; + /** * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. + * @this {!Long} * @returns {number} */ export function toInt($this) { @@ -438,6 +466,7 @@ export function toInt($this) { /** * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). + * @this {!Long} * @returns {number} */ export function toNumber($this) { @@ -448,6 +477,7 @@ export function toNumber($this) { /** * Converts the Long to a string written in the specified radix. + * @this {!Long} * @param {number=} radix Radix (2-36), defaults to 10 * @returns {string} * @override @@ -464,11 +494,11 @@ export function toString($this, radix) { // We need to change the Long value before it can be negated, so we remove // the bottom-most digit in this base and then recurse to do the rest. var radixLong = fromNumber(radix), - div = op_Division($this, radixLong), - rem1 = op_Subtraction(op_Multiply(div, radixLong), $this); + div = divide($this, radixLong), + rem1 = subtract(multiply(div, radixLong), $this); return toString(div, radix) + toInt(rem1).toString(radix); } else - return '-' + toString(op_UnaryNegation($this), radix); + return '-' + toString(negate($this), radix); } // Do several (6) digits each time through the loop, so as to @@ -477,8 +507,8 @@ export function toString($this, radix) { rem = $this; var result = ''; while (true) { - var remDiv = op_Division(rem, radixToPower), - intval = toInt(op_Subtraction(rem, op_Multiply(remDiv, radixToPower))) >>> 0, + var remDiv = divide(rem, radixToPower), + intval = toInt(subtract(rem, multiply(remDiv, radixToPower))) >>> 0, digits = intval.toString(radix); rem = remDiv; if (isZero(rem)) @@ -493,6 +523,7 @@ export function toString($this, radix) { /** * Gets the high 32 bits as a signed integer. + * @this {!Long} * @returns {number} Signed high bits */ export function getHighBits($this) { @@ -501,6 +532,7 @@ export function getHighBits($this) { /** * Gets the high 32 bits as an unsigned integer. + * @this {!Long} * @returns {number} Unsigned high bits */ export function getHighBitsUnsigned($this) { @@ -509,6 +541,7 @@ export function getHighBitsUnsigned($this) { /** * Gets the low 32 bits as a signed integer. + * @this {!Long} * @returns {number} Signed low bits */ export function getLowBits($this) { @@ -517,6 +550,7 @@ export function getLowBits($this) { /** * Gets the low 32 bits as an unsigned integer. + * @this {!Long} * @returns {number} Unsigned low bits */ export function getLowBitsUnsigned($this) { @@ -525,11 +559,12 @@ export function getLowBitsUnsigned($this) { /** * Gets the number of bits needed to represent the absolute value of this Long. + * @this {!Long} * @returns {number} */ export function getNumBitsAbs($this) { if (isNegative($this)) // Unsigned Longs are never negative - return equals($this, MIN_VALUE) ? 64 : getNumBitsAbs(op_UnaryNegation($this)); + return equals($this, MIN_VALUE) ? 64 : getNumBitsAbs(negate($this)); var val = $this.high != 0 ? $this.high : $this.low; for (var bit = 31; bit > 0; bit--) if ((val & (1 << bit)) != 0) @@ -539,14 +574,22 @@ export function getNumBitsAbs($this) { /** * Tests if this Long's value equals zero. + * @this {!Long} * @returns {boolean} */ export function isZero($this) { return $this.high === 0 && $this.low === 0; }; +/** + * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}. + * @returns {boolean} + */ +// LongPrototype.eqz = LongPrototype.isZero; + /** * Tests if this Long's value is negative. + * @this {!Long} * @returns {boolean} */ export function isNegative($this) { @@ -555,6 +598,7 @@ export function isNegative($this) { /** * Tests if this Long's value is positive. + * @this {!Long} * @returns {boolean} */ export function isPositive($this) { @@ -563,6 +607,7 @@ export function isPositive($this) { /** * Tests if this Long's value is odd. + * @this {!Long} * @returns {boolean} */ export function isOdd($this) { @@ -571,6 +616,7 @@ export function isOdd($this) { /** * Tests if this Long's value is even. + * @this {!Long} * @returns {boolean} */ export function isEven($this) { @@ -579,6 +625,7 @@ export function isEven($this) { /** * Tests if this Long's value equals the specified's. + * @this {!Long} * @param {!Long|number|string} other Other value * @returns {boolean} */ @@ -590,8 +637,17 @@ export function equals($this, other) { return $this.high === other.high && $this.low === other.low; }; +/** + * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +// LongPrototype.eq = LongPrototype.equals; + /** * Tests if this Long's value differs from the specified's. + * @this {!Long} * @param {!Long|number|string} other Other value * @returns {boolean} */ @@ -599,8 +655,25 @@ export function notEquals($this, other) { return !equals($this, /* validates */ other); }; +/** + * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +// LongPrototype.neq = LongPrototype.notEquals; + +/** + * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +// LongPrototype.ne = LongPrototype.notEquals; + /** * Tests if this Long's value is less than the specified's. + * @this {!Long} * @param {!Long|number|string} other Other value * @returns {boolean} */ @@ -608,8 +681,17 @@ export function lessThan($this, other) { return compare($this, /* validates */ other) < 0; }; +/** + * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +// LongPrototype.lt = LongPrototype.lessThan; + /** * Tests if this Long's value is less than or equal the specified's. + * @this {!Long} * @param {!Long|number|string} other Other value * @returns {boolean} */ @@ -617,8 +699,25 @@ export function lessThanOrEqual($this, other) { return compare($this, /* validates */ other) <= 0; }; +/** + * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +// LongPrototype.lte = LongPrototype.lessThanOrEqual; + +/** + * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +// LongPrototype.le = LongPrototype.lessThanOrEqual; + /** * Tests if this Long's value is greater than the specified's. + * @this {!Long} * @param {!Long|number|string} other Other value * @returns {boolean} */ @@ -626,8 +725,17 @@ export function greaterThan($this, other) { return compare($this, /* validates */ other) > 0; }; +/** + * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +// LongPrototype.gt = LongPrototype.greaterThan; + /** * Tests if this Long's value is greater than or equal the specified's. + * @this {!Long} * @param {!Long|number|string} other Other value * @returns {boolean} */ @@ -635,8 +743,25 @@ export function greaterThanOrEqual($this, other) { return compare($this, /* validates */ other) >= 0; }; +/** + * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +// LongPrototype.gte = LongPrototype.greaterThanOrEqual; + +/** + * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +// LongPrototype.ge = LongPrototype.greaterThanOrEqual; + /** * Compares this Long's value with the specified's. + * @this {!Long} * @param {!Long|number|string} other Other value * @returns {number} 0 if they are the same, 1 if the this is greater and -1 * if the given one is greater @@ -654,37 +779,45 @@ export function compare($this, other) { return 1; // At this point the sign bits are the same if (!$this.unsigned) - return isNegative(op_Subtraction($this, other)) ? -1 : 1; + return isNegative(subtract($this, other)) ? -1 : 1; // Both are positive if at least one is unsigned return (other.high >>> 0) > ($this.high >>> 0) || (other.high === $this.high && (other.low >>> 0) > ($this.low >>> 0)) ? -1 : 1; }; /** - * Absolute value of the given number. + * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}. + * @function + * @param {!Long|number|string} other Other value + * @returns {number} 0 if they are the same, 1 if the this is greater and -1 + * if the given one is greater */ -export function abs($this) { - if (!$this.unsigned && isNegative($this)) - return op_UnaryNegation($this); - else - return $this; -} +// LongPrototype.comp = LongPrototype.compare; /** * Negates this Long's value. + * @this {!Long} * @returns {!Long} Negated Long */ -export function op_UnaryNegation($this) { +export function negate($this) { if (!$this.unsigned && equals($this, MIN_VALUE)) return MIN_VALUE; - return op_Addition(op_LogicalNot($this), ONE); + return add(not($this), ONE); }; +/** + * Negates this Long's value. This is an alias of {@link Long#negate}. + * @function + * @returns {!Long} Negated Long + */ +// LongPrototype.neg = LongPrototype.negate; + /** * Returns the sum of this and the specified Long. + * @this {!Long} * @param {!Long|number|string} addend Addend * @returns {!Long} Sum */ -export function op_Addition($this, addend) { +export function add($this, addend) { if (!isLong(addend)) addend = fromValue(addend); @@ -717,21 +850,31 @@ export function op_Addition($this, addend) { /** * Returns the difference of this and the specified Long. + * @this {!Long} * @param {!Long|number|string} subtrahend Subtrahend * @returns {!Long} Difference */ -export function op_Subtraction($this, subtrahend) { +export function subtract($this, subtrahend) { if (!isLong(subtrahend)) subtrahend = fromValue(subtrahend); - return op_Addition($this, op_UnaryNegation(subtrahend)); + return add($this, negate(subtrahend)); }; +/** + * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}. + * @function + * @param {!Long|number|string} subtrahend Subtrahend + * @returns {!Long} Difference + */ +// LongPrototype.sub = LongPrototype.subtract; + /** * Returns the product of this and the specified Long. + * @this {!Long} * @param {!Long|number|string} multiplier Multiplier * @returns {!Long} Product */ -export function op_Multiply($this, multiplier) { +export function multiply($this, multiplier) { if (isZero($this)) return $this.unsigned ? UZERO : ZERO; if (!isLong(multiplier)) @@ -755,11 +898,11 @@ export function op_Multiply($this, multiplier) { if (isNegative($this)) { if (isNegative(multiplier)) - return op_Multiply(op_UnaryNegation($this), op_UnaryNegation(multiplier)); + return multiply(negate($this), negate(multiplier)); else - return op_UnaryNegation(op_Multiply(op_UnaryNegation($this), multiplier)); + return negate(multiply(negate($this), multiplier)); } else if (isNegative(multiplier)) - return op_UnaryNegation(op_Multiply($this, op_UnaryNegation(multiplier))); + return negate(multiply($this, negate(multiplier))); // If both longs are small, use float multiplication if (lessThan($this, TWO_PWR_24) && lessThan(multiplier, TWO_PWR_24)) @@ -802,13 +945,22 @@ export function op_Multiply($this, multiplier) { return fromBits((c16 << 16) | c00, (c48 << 16) | c32, $this.unsigned); }; +/** + * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}. + * @function + * @param {!Long|number|string} multiplier Multiplier + * @returns {!Long} Product + */ +// LongPrototype.mul = LongPrototype.multiply; + /** * Returns this Long divided by the specified. The result is signed if this Long is signed or * unsigned if this Long is unsigned. + * @this {!Long} * @param {!Long|number|string} divisor Divisor * @returns {!Long} Quotient */ -export function op_Division($this, divisor) { +export function divide($this, divisor) { if (!isLong(divisor)) divisor = fromValue(divisor); if (isZero(divisor)) @@ -847,13 +999,13 @@ export function op_Division($this, divisor) { return ONE; else { // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = op_RightShift($this, 1); - approx = op_LeftShift(op_Division(halfThis, divisor), 1); + var halfThis = shiftRight($this, 1); + approx = shiftLeft(divide(halfThis, divisor), 1); if (equals(approx, ZERO)) { return isNegative(divisor) ? ONE : NEG_ONE; } else { - rem = op_Subtraction($this, op_Multiply(divisor, approx)); - res = op_Addition(approx, op_Division(rem, divisor)); + rem = subtract($this, multiply(divisor, approx)); + res = add(approx, divide(rem, divisor)); return res; } } @@ -861,10 +1013,10 @@ export function op_Division($this, divisor) { return $this.unsigned ? UZERO : ZERO; if (isNegative($this)) { if (isNegative(divisor)) - return op_Division(op_UnaryNegation($this), op_UnaryNegation(divisor)); - return op_UnaryNegation(op_Division(op_UnaryNegation($this), divisor)); + return divide(negate($this), negate(divisor)); + return negate(divide(negate($this), divisor)); } else if (isNegative(divisor)) - return op_UnaryNegation(op_Division($this, op_UnaryNegation(divisor))); + return negate(divide($this, negate(divisor))); res = ZERO; } else { // The algorithm below has not been made for unsigned longs. It's therefore @@ -873,7 +1025,7 @@ export function op_Division($this, divisor) { divisor = toUnsigned(divisor); if (greaterThan(divisor, $this)) return UZERO; - if (greaterThan(divisor, op_RightShiftUnsigned($this, 1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true + if (greaterThan(divisor, shiftRightUnsigned($this, 1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true return UONE; res = UZERO; } @@ -897,11 +1049,11 @@ export function op_Division($this, divisor) { // Decrease the approximation until it is smaller than the remainder. Note // that if it is too large, the product overflows and is negative. approxRes = fromNumber(approx), - approxRem = op_Multiply(approxRes, divisor); + approxRem = multiply(approxRes, divisor); while (isNegative(approxRem) || greaterThan(approxRem, rem)) { approx -= delta; approxRes = fromNumber(approx, $this.unsigned); - approxRem = op_Multiply(approxRes, divisor); + approxRem = multiply(approxRes, divisor); } // We know the answer can't be zero... and actually, zero would cause @@ -909,18 +1061,27 @@ export function op_Division($this, divisor) { if (isZero(approxRes)) approxRes = ONE; - res = op_Addition(res, approxRes); - rem = op_Subtraction(rem, approxRem); + res = add(res, approxRes); + rem = subtract(rem, approxRem); } return res; }; +/** + * Returns this Long divided by the specified. This is an alias of {@link Long#divide}. + * @function + * @param {!Long|number|string} divisor Divisor + * @returns {!Long} Quotient + */ +// LongPrototype.div = LongPrototype.divide; + /** * Returns this Long modulo the specified. + * @this {!Long} * @param {!Long|number|string} divisor Divisor * @returns {!Long} Remainder */ -export function op_Modulus($this, divisor) { +export function modulo($this, divisor) { if (!isLong(divisor)) divisor = fromValue(divisor); @@ -935,23 +1096,41 @@ export function op_Modulus($this, divisor) { return fromBits(low, wasm.get_high(), $this.unsigned); } - return op_Subtraction($this, op_Multiply(op_Division($this, divisor), divisor)); + return subtract($this, multiply(divide($this, divisor), divisor)); }; +/** + * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. + * @function + * @param {!Long|number|string} divisor Divisor + * @returns {!Long} Remainder + */ +// LongPrototype.mod = LongPrototype.modulo; + +/** + * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. + * @function + * @param {!Long|number|string} divisor Divisor + * @returns {!Long} Remainder + */ +// LongPrototype.rem = LongPrototype.modulo; + /** * Returns the bitwise NOT of this Long. + * @this {!Long} * @returns {!Long} */ -export function op_LogicalNot($this) { +export function not($this) { return fromBits(~$this.low, ~$this.high, $this.unsigned); }; /** * Returns the bitwise AND of this Long and the specified. + * @this {!Long} * @param {!Long|number|string} other Other Long * @returns {!Long} */ -export function op_BitwiseAnd($this, other) { +export function and($this, other) { if (!isLong(other)) other = fromValue(other); return fromBits($this.low & other.low, $this.high & other.high, $this.unsigned); @@ -959,10 +1138,11 @@ export function op_BitwiseAnd($this, other) { /** * Returns the bitwise OR of this Long and the specified. + * @this {!Long} * @param {!Long|number|string} other Other Long * @returns {!Long} */ -export function op_BitwiseOr($this, other) { +export function or($this, other) { if (!isLong(other)) other = fromValue(other); return fromBits($this.low | other.low, $this.high | other.high, $this.unsigned); @@ -970,10 +1150,11 @@ export function op_BitwiseOr($this, other) { /** * Returns the bitwise XOR of this Long and the given one. + * @this {!Long} * @param {!Long|number|string} other Other Long * @returns {!Long} */ -export function op_ExclusiveOr($this, other) { +export function xor($this, other) { if (!isLong(other)) other = fromValue(other); return fromBits($this.low ^ other.low, $this.high ^ other.high, $this.unsigned); @@ -981,10 +1162,11 @@ export function op_ExclusiveOr($this, other) { /** * Returns this Long with bits shifted to the left by the given amount. + * @this {!Long} * @param {number|!Long} numBits Number of bits * @returns {!Long} Shifted Long */ -export function op_LeftShift($this, numBits) { +export function shiftLeft($this, numBits) { if (isLong(numBits)) numBits = toInt(numBits); if ((numBits &= 63) === 0) @@ -995,12 +1177,21 @@ export function op_LeftShift($this, numBits) { return fromBits(0, $this.low << (numBits - 32), $this.unsigned); }; +/** + * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +// LongPrototype.shl = LongPrototype.shiftLeft; + /** * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @this {!Long} * @param {number|!Long} numBits Number of bits * @returns {!Long} Shifted Long */ -export function op_RightShift($this, numBits) { +export function shiftRight($this, numBits) { if (isLong(numBits)) numBits = toInt(numBits); if ((numBits &= 63) === 0) @@ -1011,12 +1202,21 @@ export function op_RightShift($this, numBits) { return fromBits($this.high >> (numBits - 32), $this.high >= 0 ? 0 : -1, $this.unsigned); }; +/** + * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +// LongPrototype.shr = LongPrototype.shiftRight; + /** * Returns this Long with bits logically shifted to the right by the given amount. + * @this {!Long} * @param {number|!Long} numBits Number of bits * @returns {!Long} Shifted Long */ -export function op_RightShiftUnsigned($this, numBits) { +export function shiftRightUnsigned($this, numBits) { if (isLong(numBits)) numBits = toInt(numBits); numBits &= 63; @@ -1034,8 +1234,79 @@ export function op_RightShiftUnsigned($this, numBits) { } }; +/** + * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +// LongPrototype.shru = LongPrototype.shiftRightUnsigned; + +/** + * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +// LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; + +/** + * Returns this Long with bits rotated to the left by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +export const rotateLeft = function rotateLeft(numBits) { + var b; + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = (32 - numBits); + return fromBits(((this.low << numBits) | (this.high >>> b)), ((this.high << numBits) | (this.low >>> b)), this.unsigned); + } + numBits -= 32; + b = (32 - numBits); + return fromBits(((this.high << numBits) | (this.low >>> b)), ((this.low << numBits) | (this.high >>> b)), this.unsigned); +} +/** + * Returns this Long with bits rotated to the left by the given amount. This is an alias of {@link Long#rotateLeft}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +// LongPrototype.rotl = LongPrototype.rotateLeft; + +/** + * Returns this Long with bits rotated to the right by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +export const rotateRight = function rotateRight(numBits) { + var b; + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = (32 - numBits); + return fromBits(((this.high << b) | (this.low >>> numBits)), ((this.low << b) | (this.high >>> numBits)), this.unsigned); + } + numBits -= 32; + b = (32 - numBits); + return fromBits(((this.low << b) | (this.high >>> numBits)), ((this.high << b) | (this.low >>> numBits)), this.unsigned); +} +/** + * Returns this Long with bits rotated to the right by the given amount. This is an alias of {@link Long#rotateRight}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +// LongPrototype.rotr = LongPrototype.rotateRight; + /** * Converts this Long to signed. + * @this {!Long} * @returns {!Long} Signed long */ export function toSigned($this) { @@ -1046,6 +1317,7 @@ export function toSigned($this) { /** * Converts this Long to unsigned. + * @this {!Long} * @returns {!Long} Unsigned long */ export function toUnsigned($this) { @@ -1057,6 +1329,7 @@ export function toUnsigned($this) { /** * Converts this Long to its byte representation. * @param {boolean=} le Whether little or big endian, defaults to big endian + * @this {!Long} * @returns {!Array.} Byte representation */ export function toBytes($this, le) { @@ -1065,6 +1338,7 @@ export function toBytes($this, le) { /** * Converts this Long to its little endian byte representation. + * @this {!Long} * @returns {!Array.} Little endian byte representation */ export function toBytesLE($this) { @@ -1084,6 +1358,7 @@ export function toBytesLE($this) { /** * Converts this Long to its big endian byte representation. + * @this {!Long} * @returns {!Array.} Big endian byte representation */ export function toBytesBE($this) { @@ -1151,18 +1426,3 @@ export function fromBytesBE(bytes, unsigned) { unsigned ); }; -export function unixEpochMillisecondsToTicks(ms, offset) { - return op_Multiply(op_Addition(op_Addition(fromNumber(ms), 62135596800000), offset), 10000); -} - -export function ticksToUnixEpochMilliseconds(ticks) { - return toNumber(op_Subtraction(op_Division(ticks, 10000), 62135596800000)); -} - -export function makeRangeStepFunction(step, last, unsigned) { - const zero = unsigned ? UZERO : ZERO; - return (x) => - greaterThan(step, zero) && lessThanOrEqual(x, last) - || lessThan(step, zero) && greaterThanOrEqual(x, last) - ? [x, op_Addition(x, step)] : null -} diff --git a/src/fable-library/splitter.config.js b/src/fable-library/splitter.config.js index 57a7f11b49..c87595117b 100644 --- a/src/fable-library/splitter.config.js +++ b/src/fable-library/splitter.config.js @@ -5,7 +5,7 @@ console.log("Compiling to " + (useCommonjs ? "commonjs" : "ES2015 modules") + ". const babelOptions = useCommonjs ? { plugins: ["@babel/plugin-transform-modules-commonjs"] } - : {}; + : { }; const fableOptions = { define: [ diff --git a/src/fable-library/tsconfig.json b/src/fable-library/tsconfig.json index 688d6166db..4f2348d543 100644 --- a/src/fable-library/tsconfig.json +++ b/src/fable-library/tsconfig.json @@ -5,16 +5,20 @@ "compilerOptions": { /* Basic Options */ "outDir": "../../build/fable-library", /* Redirect output structure to the directory. */ - "target": "es2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */ - "module": "es2015", /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */ + "target": "es2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ + "module": "es2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ "allowJs": true, /* Allow javascript files to be compiled. */ - // "lib": [], /* Specify library files to be included in the compilation: */ + // "lib": [], /* Specify library files to be included in the compilation. */ // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ // "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "sourceMap": true, /* Generates corresponding '.map' file. */ + // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "composite": true, /* Enable project compilation */ + // "incremental": true, /* Enable incremental compilation */ + // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ // "removeComments": true, /* Do not emit comments to output. */ // "noEmit": true, /* Do not emit outputs. */ // "importHelpers": true, /* Import emit helpers from 'tslib'. */ @@ -22,15 +26,18 @@ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ /* Strict Type-Checking Options */ - // "strict": true, /* Enable all strict type-checking options. */ - "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ + "strict": true, /* Enable all strict type-checking options. */ + // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ // "strictNullChecks": true, /* Enable strict null checks. */ - "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ + // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ /* Additional Checks */ - // "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ + "noUnusedLocals": true, /* Report errors on unused locals. */ + "noUnusedParameters": true, /* Report errors on unused parameters. */ "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ @@ -41,7 +48,10 @@ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ /* Source Map Options */ // "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ @@ -53,6 +63,9 @@ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ "noEmitOnError": true, - "newLine": "LF" + "newLine": "lf", + + /* Advanced Options */ + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ } -} \ No newline at end of file +} diff --git a/src/fable-loader/README.md b/src/fable-loader/README.md index 7621ca614f..4c5f06fe08 100644 --- a/src/fable-loader/README.md +++ b/src/fable-loader/README.md @@ -49,3 +49,4 @@ These are the options that can be passed to `fable-loader`: - **define**: Array of compilation constants passed to the F# compiler. Fable automatically defines `FABLE_COMPILER` and fable-loader will also define `DEBUG` in Webpack "development" mode. - **typedArrays**: Translate numeric arrays as JS [Typed Arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray). True by default. - **clampByteArrays**: If true, Fable will translate byte arrays as [Uint8ClampedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray). +- **silent**: If true, Fable won't output any log (requires fable-compiler >=2.3.14). diff --git a/src/fable-loader/RELEASE_NOTES.md b/src/fable-loader/RELEASE_NOTES.md index 4a8fedf833..85e856c631 100644 --- a/src/fable-loader/RELEASE_NOTES.md +++ b/src/fable-loader/RELEASE_NOTES.md @@ -1,3 +1,11 @@ +### 2.1.9 + +* Update to fable-babel-plugins 2.3.0 + +### 2.1.8 + +* Add `silent` option + ### 2.1.7 * Enable different compiler implementations diff --git a/src/fable-loader/index.js b/src/fable-loader/index.js index ff6bca8f5d..343014865a 100644 --- a/src/fable-loader/index.js +++ b/src/fable-loader/index.js @@ -22,6 +22,12 @@ var customPlugins = [ var compilerCache = null; +function log(opts, msg) { + if (!opts.silent) { + console.log(msg); + } +} + function getTcpPort(opts) { if (opts.port != null) { return opts.port; @@ -61,6 +67,8 @@ var Loader = function(buffer) { var callback = this.async(); var opts = this.loaders[0].options || {}; + opts.cli = opts.cli || {}; + opts.cli.silent = opts.silent; var babelOptions = opts.babel || {}; babelOptions.plugins = customPlugins.concat(babelOptions.plugins || []); @@ -111,7 +119,7 @@ var Loader = function(buffer) { this.emitWarning(new Error(msg)); break; default: - console.log(msg) + log(opts, msg) } }); }); @@ -125,7 +133,7 @@ var Loader = function(buffer) { if (err) { callback(err); } else { - console.log("fable: Compiled " + path.relative(process.cwd(), msg.path)); + log(opts, "fable: Compiled " + path.relative(process.cwd(), msg.path)); callback(null, babelParsed.code, babelParsed.map); } }); diff --git a/src/fable-loader/package-lock.json b/src/fable-loader/package-lock.json index 6609388e79..24a682f6cc 100644 --- a/src/fable-loader/package-lock.json +++ b/src/fable-loader/package-lock.json @@ -1,6 +1,6 @@ { "name": "fable-loader", - "version": "2.1.7", + "version": "2.1.9", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -38,14 +38,14 @@ "dev": true }, "fable-babel-plugins": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/fable-babel-plugins/-/fable-babel-plugins-2.2.0.tgz", - "integrity": "sha512-4g8CIyXCILk5LLiwNPtvtrPy3YuV5eJV18SYJCZxu3A1BSKNvPGHLSg5YcFJ2zt4qmBvSkBewlQ2bVQYG+TnrQ==" + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/fable-babel-plugins/-/fable-babel-plugins-2.3.0.tgz", + "integrity": "sha512-alGBNw5HZJzTEznXKfypFEkD5aWsspbCcoVDu9j8Mqdi77dgp4BSjhYSg61mQEg9UluIAZxRM5lhGARYbU97DQ==" }, "lodash": { - "version": "4.17.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==", + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==", "dev": true }, "to-fast-properties": { diff --git a/src/fable-loader/package.json b/src/fable-loader/package.json index c1cff68bda..3a2e72cefe 100644 --- a/src/fable-loader/package.json +++ b/src/fable-loader/package.json @@ -1,6 +1,6 @@ { "name": "fable-loader", - "version": "2.1.7", + "version": "2.1.9", "main": "index.js", "description": "Webpack loader for Fable compiler", "keywords": [ @@ -28,6 +28,6 @@ "@types/babel__core": "^7.0.3" }, "dependencies": { - "fable-babel-plugins": "^2.2.0" + "fable-babel-plugins": "^2.3.0" } } diff --git a/src/fable-metadata/RELEASE_NOTES.md b/src/fable-metadata/RELEASE_NOTES.md index a909502fee..5103443a7b 100644 --- a/src/fable-metadata/RELEASE_NOTES.md +++ b/src/fable-metadata/RELEASE_NOTES.md @@ -1,3 +1,19 @@ +### 1.4.0 + +* Update FSharp.Core to 4.7.1 +* Updated .NET Core to 3.1.201 + +### 1.3.0 + +* Updated Fable.Core to 3.1.5 +* Fix #1972 +* Updated .NET Core to 3.1.101 + +### 1.2.0 + +* Update FSharp.Core to 4.7.0 +* Add System.Net.Requests & System.Net.WebClient + ### 1.1.2 * Add Recharts to Fable.Repl.Lib diff --git a/src/fable-metadata/lib/FSharp.Core.dll b/src/fable-metadata/lib/FSharp.Core.dll index aeba06d113..b89a7ed60a 100644 Binary files a/src/fable-metadata/lib/FSharp.Core.dll and b/src/fable-metadata/lib/FSharp.Core.dll differ diff --git a/src/fable-metadata/lib/Fable.Core.dll b/src/fable-metadata/lib/Fable.Core.dll index 64e35336db..9063475936 100644 Binary files a/src/fable-metadata/lib/Fable.Core.dll and b/src/fable-metadata/lib/Fable.Core.dll differ diff --git a/src/fable-metadata/lib/System.Collections.Concurrent.dll b/src/fable-metadata/lib/System.Collections.Concurrent.dll index ce2b67b043..3f715ff344 100644 Binary files a/src/fable-metadata/lib/System.Collections.Concurrent.dll and b/src/fable-metadata/lib/System.Collections.Concurrent.dll differ diff --git a/src/fable-metadata/lib/System.Collections.dll b/src/fable-metadata/lib/System.Collections.dll index ea6c062327..1b9ea9f4a3 100644 Binary files a/src/fable-metadata/lib/System.Collections.dll and b/src/fable-metadata/lib/System.Collections.dll differ diff --git a/src/fable-metadata/lib/System.ComponentModel.Primitives.dll b/src/fable-metadata/lib/System.ComponentModel.Primitives.dll index 99beca1716..4da4e0b390 100644 Binary files a/src/fable-metadata/lib/System.ComponentModel.Primitives.dll and b/src/fable-metadata/lib/System.ComponentModel.Primitives.dll differ diff --git a/src/fable-metadata/lib/System.ComponentModel.TypeConverter.dll b/src/fable-metadata/lib/System.ComponentModel.TypeConverter.dll index 1d92544ab8..ebdc7b21e8 100644 Binary files a/src/fable-metadata/lib/System.ComponentModel.TypeConverter.dll and b/src/fable-metadata/lib/System.ComponentModel.TypeConverter.dll differ diff --git a/src/fable-metadata/lib/System.ComponentModel.dll b/src/fable-metadata/lib/System.ComponentModel.dll index 028ed741e7..cc74ab523b 100644 Binary files a/src/fable-metadata/lib/System.ComponentModel.dll and b/src/fable-metadata/lib/System.ComponentModel.dll differ diff --git a/src/fable-metadata/lib/System.Console.dll b/src/fable-metadata/lib/System.Console.dll index dc58418cf5..a64380691c 100644 Binary files a/src/fable-metadata/lib/System.Console.dll and b/src/fable-metadata/lib/System.Console.dll differ diff --git a/src/fable-metadata/lib/System.Core.dll b/src/fable-metadata/lib/System.Core.dll index 84f553fe41..73a0143136 100644 Binary files a/src/fable-metadata/lib/System.Core.dll and b/src/fable-metadata/lib/System.Core.dll differ diff --git a/src/fable-metadata/lib/System.Diagnostics.Debug.dll b/src/fable-metadata/lib/System.Diagnostics.Debug.dll index c0c273e652..0057c681f7 100644 Binary files a/src/fable-metadata/lib/System.Diagnostics.Debug.dll and b/src/fable-metadata/lib/System.Diagnostics.Debug.dll differ diff --git a/src/fable-metadata/lib/System.Diagnostics.Tools.dll b/src/fable-metadata/lib/System.Diagnostics.Tools.dll new file mode 100644 index 0000000000..c866957d95 Binary files /dev/null and b/src/fable-metadata/lib/System.Diagnostics.Tools.dll differ diff --git a/src/fable-metadata/lib/System.Diagnostics.Tracing.dll b/src/fable-metadata/lib/System.Diagnostics.Tracing.dll index 8a3f885668..71c4832556 100644 Binary files a/src/fable-metadata/lib/System.Diagnostics.Tracing.dll and b/src/fable-metadata/lib/System.Diagnostics.Tracing.dll differ diff --git a/src/fable-metadata/lib/System.Globalization.dll b/src/fable-metadata/lib/System.Globalization.dll index b60ad7417d..867b6e17a0 100644 Binary files a/src/fable-metadata/lib/System.Globalization.dll and b/src/fable-metadata/lib/System.Globalization.dll differ diff --git a/src/fable-metadata/lib/System.IO.dll b/src/fable-metadata/lib/System.IO.dll index f6327d192e..de2a6bca88 100644 Binary files a/src/fable-metadata/lib/System.IO.dll and b/src/fable-metadata/lib/System.IO.dll differ diff --git a/src/fable-metadata/lib/System.Net.Requests.dll b/src/fable-metadata/lib/System.Net.Requests.dll new file mode 100644 index 0000000000..2c1e8cefb9 Binary files /dev/null and b/src/fable-metadata/lib/System.Net.Requests.dll differ diff --git a/src/fable-metadata/lib/System.Net.WebClient.dll b/src/fable-metadata/lib/System.Net.WebClient.dll new file mode 100644 index 0000000000..12278d5960 Binary files /dev/null and b/src/fable-metadata/lib/System.Net.WebClient.dll differ diff --git a/src/fable-metadata/lib/System.Numerics.dll b/src/fable-metadata/lib/System.Numerics.dll index 87e236d975..2984e97f2d 100644 Binary files a/src/fable-metadata/lib/System.Numerics.dll and b/src/fable-metadata/lib/System.Numerics.dll differ diff --git a/src/fable-metadata/lib/System.Reflection.Extensions.dll b/src/fable-metadata/lib/System.Reflection.Extensions.dll index 311f878dff..2c3086c1bc 100644 Binary files a/src/fable-metadata/lib/System.Reflection.Extensions.dll and b/src/fable-metadata/lib/System.Reflection.Extensions.dll differ diff --git a/src/fable-metadata/lib/System.Reflection.Metadata.dll b/src/fable-metadata/lib/System.Reflection.Metadata.dll index baf6c33db4..bcae371ddc 100644 Binary files a/src/fable-metadata/lib/System.Reflection.Metadata.dll and b/src/fable-metadata/lib/System.Reflection.Metadata.dll differ diff --git a/src/fable-metadata/lib/System.Reflection.Primitives.dll b/src/fable-metadata/lib/System.Reflection.Primitives.dll index c2cb95727e..a54fa20a22 100644 Binary files a/src/fable-metadata/lib/System.Reflection.Primitives.dll and b/src/fable-metadata/lib/System.Reflection.Primitives.dll differ diff --git a/src/fable-metadata/lib/System.Reflection.TypeExtensions.dll b/src/fable-metadata/lib/System.Reflection.TypeExtensions.dll index 3228325251..670c4e4f99 100644 Binary files a/src/fable-metadata/lib/System.Reflection.TypeExtensions.dll and b/src/fable-metadata/lib/System.Reflection.TypeExtensions.dll differ diff --git a/src/fable-metadata/lib/System.Reflection.dll b/src/fable-metadata/lib/System.Reflection.dll index 9503415284..6ef74fb27d 100644 Binary files a/src/fable-metadata/lib/System.Reflection.dll and b/src/fable-metadata/lib/System.Reflection.dll differ diff --git a/src/fable-metadata/lib/System.Runtime.Extensions.dll b/src/fable-metadata/lib/System.Runtime.Extensions.dll index ced231d14a..4c59172570 100644 Binary files a/src/fable-metadata/lib/System.Runtime.Extensions.dll and b/src/fable-metadata/lib/System.Runtime.Extensions.dll differ diff --git a/src/fable-metadata/lib/System.Runtime.Numerics.dll b/src/fable-metadata/lib/System.Runtime.Numerics.dll index 40a9470206..84f933d01c 100644 Binary files a/src/fable-metadata/lib/System.Runtime.Numerics.dll and b/src/fable-metadata/lib/System.Runtime.Numerics.dll differ diff --git a/src/fable-metadata/lib/System.Runtime.dll b/src/fable-metadata/lib/System.Runtime.dll index a2691095f8..cd096cd5ed 100644 Binary files a/src/fable-metadata/lib/System.Runtime.dll and b/src/fable-metadata/lib/System.Runtime.dll differ diff --git a/src/fable-metadata/lib/System.Text.Encoding.Extensions.dll b/src/fable-metadata/lib/System.Text.Encoding.Extensions.dll index a1991988d0..8625d925ba 100644 Binary files a/src/fable-metadata/lib/System.Text.Encoding.Extensions.dll and b/src/fable-metadata/lib/System.Text.Encoding.Extensions.dll differ diff --git a/src/fable-metadata/lib/System.Text.Encoding.dll b/src/fable-metadata/lib/System.Text.Encoding.dll index 09830abf40..b567d41a57 100644 Binary files a/src/fable-metadata/lib/System.Text.Encoding.dll and b/src/fable-metadata/lib/System.Text.Encoding.dll differ diff --git a/src/fable-metadata/lib/System.Text.RegularExpressions.dll b/src/fable-metadata/lib/System.Text.RegularExpressions.dll index a27e078e59..51f9444b45 100644 Binary files a/src/fable-metadata/lib/System.Text.RegularExpressions.dll and b/src/fable-metadata/lib/System.Text.RegularExpressions.dll differ diff --git a/src/fable-metadata/lib/System.Threading.Tasks.dll b/src/fable-metadata/lib/System.Threading.Tasks.dll index cc010955f8..49c54f5559 100644 Binary files a/src/fable-metadata/lib/System.Threading.Tasks.dll and b/src/fable-metadata/lib/System.Threading.Tasks.dll differ diff --git a/src/fable-metadata/lib/System.Threading.dll b/src/fable-metadata/lib/System.Threading.dll index 5417d23c32..d721faca9c 100644 Binary files a/src/fable-metadata/lib/System.Threading.dll and b/src/fable-metadata/lib/System.Threading.dll differ diff --git a/src/fable-metadata/lib/System.ValueTuple.dll b/src/fable-metadata/lib/System.ValueTuple.dll index e3f4f3ca94..35c7159ce4 100644 Binary files a/src/fable-metadata/lib/System.ValueTuple.dll and b/src/fable-metadata/lib/System.ValueTuple.dll differ diff --git a/src/fable-metadata/lib/System.dll b/src/fable-metadata/lib/System.dll index e9dcfb8298..1270097d4c 100644 Binary files a/src/fable-metadata/lib/System.dll and b/src/fable-metadata/lib/System.dll differ diff --git a/src/fable-metadata/lib/mscorlib.dll b/src/fable-metadata/lib/mscorlib.dll index e96a76befd..0fcd28b127 100644 Binary files a/src/fable-metadata/lib/mscorlib.dll and b/src/fable-metadata/lib/mscorlib.dll differ diff --git a/src/fable-metadata/lib/netstandard.dll b/src/fable-metadata/lib/netstandard.dll index 0e24b9bba2..8069807fbc 100644 Binary files a/src/fable-metadata/lib/netstandard.dll and b/src/fable-metadata/lib/netstandard.dll differ diff --git a/src/fable-metadata/package-lock.json b/src/fable-metadata/package-lock.json new file mode 100644 index 0000000000..787ba16021 --- /dev/null +++ b/src/fable-metadata/package-lock.json @@ -0,0 +1,5 @@ +{ + "name": "fable-metadata", + "version": "1.4.0", + "lockfileVersion": 1 +} diff --git a/src/fable-metadata/package.json b/src/fable-metadata/package.json index 8cfd8d81de..efa1d6819a 100644 --- a/src/fable-metadata/package.json +++ b/src/fable-metadata/package.json @@ -1,6 +1,6 @@ { "name": "fable-metadata", - "version": "1.1.2", + "version": "1.4.0", "description": "Assemblies needed to compile F# projects with Fable", "main": "index.js", "directories": { diff --git a/src/fable-publish-utils/PublishUtils.fs b/src/fable-publish-utils/PublishUtils.fs index d8dc1e7b03..4ae367e24a 100644 --- a/src/fable-publish-utils/PublishUtils.fs +++ b/src/fable-publish-utils/PublishUtils.fs @@ -125,17 +125,24 @@ let rec removeDirRecursive (p: string): unit = let mkDirRecursive (p: string): unit = fs?mkdirSync(p, %["recursive" ==> true]) -let rec copyDirRecursive (source: string) (target: string): unit = +let rec copyDir (source: string) (target: string) (recursive: bool): unit = if fs?existsSync(target) |> not then mkDirRecursive target for file in dirFiles source do let source = source file let target = target file if isDirectory source then - copyDirRecursive source target + if recursive then + copyDir source target recursive else fs?copyFileSync(source, target) +let copyDirNonRecursive (source: string) (target: string): unit = + copyDir source target false + +let copyDirRecursive (source: string) (target: string): unit = + copyDir source target true + let copyFile (source: string) (target: string): unit = if isDirectory source then failwith "Source is a directory, use copyDirRecursive" @@ -342,7 +349,7 @@ module Publish = |> replaceRegex NUGET_PACKAGE_VERSION ["$1"; releaseVersion; "$3"] |> writeFile projFile try - let tempDir = projDir "temp" + let tempDir = fullPath(projDir "temp") removeDirRecursive tempDir runList ["dotnet pack"; projDir; sprintf "-c Release -o %s" tempDir] let pkgName = filenameWithoutExtension projFile @@ -366,6 +373,11 @@ module Publish = (JS.JSON.parse json)?version |> Option.ofObj let releaseVersion = loadReleaseVersion projDir if needsPublishing checkPkgVersion releaseVersion (projDir "package.json") then + let nugetKey = + match envVarOrNone "NPM_TOKEN" with + | Some nugetKey -> nugetKey + | None -> failwith "The npm token key must be set in a NPM_TOKEN environmental variable" + runInDir projDir @"npm config set '//registry.npmjs.org/:_authToken' ""${NPM_TOKEN}""" buildAction() bumpNpmVersion projDir releaseVersion try diff --git a/src/fable-publish-utils/PublishUtils.fsproj b/src/fable-publish-utils/PublishUtils.fsproj index b937b5f1cb..0cd7fe877e 100644 --- a/src/fable-publish-utils/PublishUtils.fsproj +++ b/src/fable-publish-utils/PublishUtils.fsproj @@ -7,6 +7,6 @@ - + diff --git a/src/fable-publish-utils/RELEASE_NOTES.md b/src/fable-publish-utils/RELEASE_NOTES.md index e6888f5116..bb78455d91 100644 --- a/src/fable-publish-utils/RELEASE_NOTES.md +++ b/src/fable-publish-utils/RELEASE_NOTES.md @@ -1,3 +1,15 @@ +### 1.2.1 + +* Update to Fable.Core 3.1.5 + +### 1.2.0 + +* Use npm token when publishing an npm package + +### 1.1.1 + +* Several additions for Fable build + ### 1.0.5 * First publish \ No newline at end of file diff --git a/src/fable-publish-utils/package-lock.json b/src/fable-publish-utils/package-lock.json new file mode 100644 index 0000000000..d2cfc97fcd --- /dev/null +++ b/src/fable-publish-utils/package-lock.json @@ -0,0 +1,5 @@ +{ + "name": "fable-publish-utils", + "version": "1.2.1", + "lockfileVersion": 1 +} diff --git a/src/fable-publish-utils/package.json b/src/fable-publish-utils/package.json index 06d986e7b9..505f221dbb 100644 --- a/src/fable-publish-utils/package.json +++ b/src/fable-publish-utils/package.json @@ -1,6 +1,6 @@ { "name": "fable-publish-utils", - "version": "1.0.5", + "version": "1.2.1", "description": "Utilities for publishing NPM packages using an F#/Fable script", "main": "index.js", "scripts": { @@ -10,7 +10,10 @@ "type": "git", "url": "git+https://github.com/fable-compiler/fable-publish-utils.git" }, - "keywords": ["fable", "f#"], + "keywords": [ + "fable", + "f#" + ], "author": "Alfonso García-Caro", "license": "ISC", "bugs": { diff --git a/src/fable-splitter/README.md b/src/fable-splitter/README.md index 909ba6a69b..9b8248a18a 100644 --- a/src/fable-splitter/README.md +++ b/src/fable-splitter/README.md @@ -46,6 +46,10 @@ module.exports = { babel: { presets: [["@babel/preset-env", { modules: "commonjs" }]], sourceMaps: false, + }, + // The `onCompiled` hook (optional) is raised after each compilation + onCompiled() { + console.log("Compilation finished!") } } ``` diff --git a/src/fable-splitter/RELEASE_NOTES.md b/src/fable-splitter/RELEASE_NOTES.md index 1771e1b5e8..33754db342 100644 --- a/src/fable-splitter/RELEASE_NOTES.md +++ b/src/fable-splitter/RELEASE_NOTES.md @@ -1,3 +1,19 @@ +### 2.1.13 + +* Update to fable-babel-plugins 2.3.0 + +### 2.1.12 + +* Pass `--inspect` option to node, when running script in debug mode + +### 2.1.11 + +* Add --usePolling flag @drk-mtr + +### 2.1.10 + +* Add `onCompiled` hook + ### 2.1.8 * Add back possibility to connect to TCP port diff --git a/src/fable-splitter/build.js b/src/fable-splitter/build.js index 066a81f28a..800c6a125d 100644 --- a/src/fable-splitter/build.js +++ b/src/fable-splitter/build.js @@ -1,11 +1,40 @@ -const util = require("../tools/build-utils"); +const path = require("path"); +const shell = require("shelljs"); -util.runTargets({ +shell.config.verbose = true; +const REPO_ROOT_DIR = path.join(__dirname, "../.."); + +runTargets({ async test() { - await util.runNpmBin("ava", "tests/index.js"); + await runNpmBin("ava", "tests/index.js"); }, async build() { - await util.runNpmBin("tslint", "--project ."); - await util.runNpmBin("tsc"); + // await runNpmBin("tslint", "--project ."); + await runNpmBin("tsc"); } }); + +// UTILS --------------------------- + +async function runNpmBin(name, args) { + const isWin = process.platform === "win32"; + const res = await shell.exec(`${path.join(REPO_ROOT_DIR, "node_modules/.bin", name + (isWin ? ".cmd" : ""))} ${args || ""}`); + if (res.code !== 0) { + throw new Error(`${name} failed with code ${res.code}`); + } +} + +function runTargets(targets) { + const args = process.argv.slice(2); + const [target, restArgs] = + typeof args[0] === "string" && !args[0].startsWith("--") + ? [args[0].toLowerCase(), args.splice(1)] + : ["build", args]; + const res = targets[target].apply(targets, restArgs); + if (res instanceof Promise) { + res.then(() => {}, er => { + console.error(er); + process.exit(1); + }) + } +} \ No newline at end of file diff --git a/src/fable-splitter/package-lock.json b/src/fable-splitter/package-lock.json index fa1c8cc26c..e6d021a822 100644 --- a/src/fable-splitter/package-lock.json +++ b/src/fable-splitter/package-lock.json @@ -1,195 +1,499 @@ { "name": "fable-splitter", - "version": "2.1.8", + "version": "2.1.13", "lockfileVersion": 1, "requires": true, "dependencies": { + "@ava/babel-plugin-throws-helper": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@ava/babel-plugin-throws-helper/-/babel-plugin-throws-helper-3.0.0.tgz", + "integrity": "sha512-mN9UolOs4WX09QkheU1ELkVy2WPnwonlO3XMdN8JF8fQqRVgVTR21xDbvEOUsbwz6Zwjq7ji9yzyjuXqDPalxg==", + "dev": true + }, + "@ava/babel-preset-stage-4": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@ava/babel-preset-stage-4/-/babel-preset-stage-4-2.0.0.tgz", + "integrity": "sha512-OWqMYeTSZ16AfLx0Vn0Uj7tcu+uMRlbKmks+DVCFlln7vomVsOtst+Oz+HCussDSFGpE+30VtHAUHLy6pLDpHQ==", + "dev": true, + "requires": { + "@babel/plugin-proposal-async-generator-functions": "^7.0.0", + "@babel/plugin-proposal-object-rest-spread": "^7.0.0", + "@babel/plugin-proposal-optional-catch-binding": "^7.0.0", + "@babel/plugin-transform-async-to-generator": "^7.0.0", + "@babel/plugin-transform-dotall-regex": "^7.0.0", + "@babel/plugin-transform-exponentiation-operator": "^7.0.0", + "@babel/plugin-transform-modules-commonjs": "^7.0.0" + } + }, + "@ava/babel-preset-transform-test-files": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@ava/babel-preset-transform-test-files/-/babel-preset-transform-test-files-5.0.0.tgz", + "integrity": "sha512-rqgyQwkT0+j2JzYP51dOv80u33rzAvjBtXRzUON+7+6u26mjoudRXci2+1s18rat8r4uOlZfbzm114YS6pwmYw==", + "dev": true, + "requires": { + "@ava/babel-plugin-throws-helper": "^3.0.0", + "babel-plugin-espower": "^3.0.1" + } + }, + "@ava/write-file-atomic": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@ava/write-file-atomic/-/write-file-atomic-2.2.0.tgz", + "integrity": "sha512-BTNB3nGbEfJT+69wuqXFr/bQH7Vr7ihx2xGOMNqPgDGhwspoZhiWumDDZNjBy7AScmqS5CELIOGtPVXESyrnDA==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.11", + "imurmurhash": "^0.1.4", + "slide": "^1.1.5" + } + }, "@babel/code-frame": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz", - "integrity": "sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.8.3.tgz", + "integrity": "sha512-a9gxpmdXtZEInkCSHUJDLHZVBgb1QS0jhss4cPP93EW7s+uC5bikET2twEF3KV+7rDblJcmNvTR7VJejqd2C2g==", "requires": { - "@babel/highlight": "^7.0.0" + "@babel/highlight": "^7.8.3" } }, "@babel/core": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.1.6.tgz", - "integrity": "sha512-Hz6PJT6e44iUNpAn8AoyAs6B3bl60g7MJQaI0rZEar6ECzh6+srYO1xlIdssio34mPaUtAb1y+XlkkSJzok3yw==", - "requires": { - "@babel/code-frame": "^7.0.0", - "@babel/generator": "^7.1.6", - "@babel/helpers": "^7.1.5", - "@babel/parser": "^7.1.6", - "@babel/template": "^7.1.2", - "@babel/traverse": "^7.1.6", - "@babel/types": "^7.1.6", - "convert-source-map": "^1.1.0", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.9.0.tgz", + "integrity": "sha512-kWc7L0fw1xwvI0zi8OKVBuxRVefwGOrKSQMvrQ3dW+bIIavBY3/NpXmpjMy7bQnLgwgzWQZ8TlM57YHpHNHz4w==", + "requires": { + "@babel/code-frame": "^7.8.3", + "@babel/generator": "^7.9.0", + "@babel/helper-module-transforms": "^7.9.0", + "@babel/helpers": "^7.9.0", + "@babel/parser": "^7.9.0", + "@babel/template": "^7.8.6", + "@babel/traverse": "^7.9.0", + "@babel/types": "^7.9.0", + "convert-source-map": "^1.7.0", "debug": "^4.1.0", - "json5": "^2.1.0", - "lodash": "^4.17.10", + "gensync": "^1.0.0-beta.1", + "json5": "^2.1.2", + "lodash": "^4.17.13", "resolve": "^1.3.2", "semver": "^5.4.1", "source-map": "^0.5.0" } }, "@babel/generator": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.1.6.tgz", - "integrity": "sha512-brwPBtVvdYdGxtenbQgfCdDPmtkmUBZPjUoK5SXJEBuHaA5BCubh9ly65fzXz7R6o5rA76Rs22ES8Z+HCc0YIQ==", + "version": "7.9.5", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.9.5.tgz", + "integrity": "sha512-GbNIxVB3ZJe3tLeDm1HSn2AhuD/mVcyLDpgtLXa5tplmWrJdF/elxB56XNqCuD6szyNkDi6wuoKXln3QeBmCHQ==", "requires": { - "@babel/types": "^7.1.6", + "@babel/types": "^7.9.5", "jsesc": "^2.5.1", - "lodash": "^4.17.10", - "source-map": "^0.5.0", - "trim-right": "^1.0.1" + "lodash": "^4.17.13", + "source-map": "^0.5.0" + } + }, + "@babel/helper-annotate-as-pure": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.8.3.tgz", + "integrity": "sha512-6o+mJrZBxOoEX77Ezv9zwW7WV8DdluouRKNY/IR5u/YTMuKHgugHOzYWlYvYLpLA9nPsQCAAASpCIbjI9Mv+Uw==", + "dev": true, + "requires": { + "@babel/types": "^7.8.3" + } + }, + "@babel/helper-builder-binary-assignment-operator-visitor": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.8.3.tgz", + "integrity": "sha512-5eFOm2SyFPK4Rh3XMMRDjN7lBH0orh3ss0g3rTYZnBQ+r6YPj7lgDyCvPphynHvUrobJmeMignBr6Acw9mAPlw==", + "dev": true, + "requires": { + "@babel/helper-explode-assignable-expression": "^7.8.3", + "@babel/types": "^7.8.3" + } + }, + "@babel/helper-create-regexp-features-plugin": { + "version": "7.8.8", + "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.8.8.tgz", + "integrity": "sha512-LYVPdwkrQEiX9+1R29Ld/wTrmQu1SSKYnuOk3g0CkcZMA1p0gsNxJFj/3gBdaJ7Cg0Fnek5z0DsMULePP7Lrqg==", + "dev": true, + "requires": { + "@babel/helper-annotate-as-pure": "^7.8.3", + "@babel/helper-regex": "^7.8.3", + "regexpu-core": "^4.7.0" + } + }, + "@babel/helper-explode-assignable-expression": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-explode-assignable-expression/-/helper-explode-assignable-expression-7.8.3.tgz", + "integrity": "sha512-N+8eW86/Kj147bO9G2uclsg5pwfs/fqqY5rwgIL7eTBklgXjcOJ3btzS5iM6AitJcftnY7pm2lGsrJVYLGjzIw==", + "dev": true, + "requires": { + "@babel/traverse": "^7.8.3", + "@babel/types": "^7.8.3" } }, "@babel/helper-function-name": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.1.0.tgz", - "integrity": "sha512-A95XEoCpb3TO+KZzJ4S/5uW5fNe26DjBGqf1o9ucyLyCmi1dXq/B3c8iaWTfBk3VvetUxl16e8tIrd5teOCfGw==", + "version": "7.9.5", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.9.5.tgz", + "integrity": "sha512-JVcQZeXM59Cd1qanDUxv9fgJpt3NeKUaqBqUEvfmQ+BCOKq2xUgaWZW2hr0dkbyJgezYuplEoh5knmrnS68efw==", "requires": { - "@babel/helper-get-function-arity": "^7.0.0", - "@babel/template": "^7.1.0", - "@babel/types": "^7.0.0" + "@babel/helper-get-function-arity": "^7.8.3", + "@babel/template": "^7.8.3", + "@babel/types": "^7.9.5" } }, "@babel/helper-get-function-arity": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0.tgz", - "integrity": "sha512-r2DbJeg4svYvt3HOS74U4eWKsUAMRH01Z1ds1zx8KNTPtpTL5JAsdFv8BNyOpVqdFhHkkRDIg5B4AsxmkjAlmQ==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.8.3.tgz", + "integrity": "sha512-FVDR+Gd9iLjUMY1fzE2SR0IuaJToR4RkCDARVfsBBPSP53GEqSFjD8gNyxg246VUyc/ALRxFaAK8rVG7UT7xRA==", + "requires": { + "@babel/types": "^7.8.3" + } + }, + "@babel/helper-member-expression-to-functions": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.8.3.tgz", + "integrity": "sha512-fO4Egq88utkQFjbPrSHGmGLFqmrshs11d46WI+WZDESt7Wu7wN2G2Iu+NMMZJFDOVRHAMIkB5SNh30NtwCA7RA==", "requires": { - "@babel/types": "^7.0.0" + "@babel/types": "^7.8.3" } }, "@babel/helper-module-imports": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.0.0.tgz", - "integrity": "sha512-aP/hlLq01DWNEiDg4Jn23i+CXxW/owM4WpDLFUbpjxe4NS3BhLVZQ5i7E0ZrxuQ/vwekIeciyamgB1UIYxxM6A==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.8.3.tgz", + "integrity": "sha512-R0Bx3jippsbAEtzkpZ/6FIiuzOURPcMjHp+Z6xPe6DtApDJx+w7UYyOLanZqO8+wKR9G10s/FmHXvxaMd9s6Kg==", "requires": { - "@babel/types": "^7.0.0" + "@babel/types": "^7.8.3" } }, "@babel/helper-module-transforms": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.1.0.tgz", - "integrity": "sha512-0JZRd2yhawo79Rcm4w0LwSMILFmFXjugG3yqf+P/UsKsRS1mJCmMwwlHDlMg7Avr9LrvSpp4ZSULO9r8jpCzcw==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.9.0.tgz", + "integrity": "sha512-0FvKyu0gpPfIQ8EkxlrAydOWROdHpBmiCiRwLkUiBGhCUPRRbVD2/tm3sFr/c/GWFrQ/ffutGUAnx7V0FzT2wA==", + "requires": { + "@babel/helper-module-imports": "^7.8.3", + "@babel/helper-replace-supers": "^7.8.6", + "@babel/helper-simple-access": "^7.8.3", + "@babel/helper-split-export-declaration": "^7.8.3", + "@babel/template": "^7.8.6", + "@babel/types": "^7.9.0", + "lodash": "^4.17.13" + } + }, + "@babel/helper-optimise-call-expression": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.8.3.tgz", + "integrity": "sha512-Kag20n86cbO2AvHca6EJsvqAd82gc6VMGule4HwebwMlwkpXuVqrNRj6CkCV2sKxgi9MyAUnZVnZ6lJ1/vKhHQ==", "requires": { - "@babel/helper-module-imports": "^7.0.0", - "@babel/helper-simple-access": "^7.1.0", - "@babel/helper-split-export-declaration": "^7.0.0", - "@babel/template": "^7.1.0", - "@babel/types": "^7.0.0", - "lodash": "^4.17.10" + "@babel/types": "^7.8.3" } }, "@babel/helper-plugin-utils": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.0.0.tgz", - "integrity": "sha512-CYAOUCARwExnEixLdB6sDm2dIJ/YgEAKDM1MOeMeZu9Ld/bDgVo8aiWrXwcY7OBh+1Ea2uUcVRcxKk0GJvW7QA==" + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.8.3.tgz", + "integrity": "sha512-j+fq49Xds2smCUNYmEHF9kGNkhbet6yVIBp4e6oeQpH1RUs/Ir06xUKzDjDkGcaaokPiTNs2JBWHjaE4csUkZQ==" + }, + "@babel/helper-regex": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-regex/-/helper-regex-7.8.3.tgz", + "integrity": "sha512-BWt0QtYv/cg/NecOAZMdcn/waj/5P26DR4mVLXfFtDokSR6fyuG0Pj+e2FqtSME+MqED1khnSMulkmGl8qWiUQ==", + "dev": true, + "requires": { + "lodash": "^4.17.13" + } + }, + "@babel/helper-remap-async-to-generator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.8.3.tgz", + "integrity": "sha512-kgwDmw4fCg7AVgS4DukQR/roGp+jP+XluJE5hsRZwxCYGg+Rv9wSGErDWhlI90FODdYfd4xG4AQRiMDjjN0GzA==", + "dev": true, + "requires": { + "@babel/helper-annotate-as-pure": "^7.8.3", + "@babel/helper-wrap-function": "^7.8.3", + "@babel/template": "^7.8.3", + "@babel/traverse": "^7.8.3", + "@babel/types": "^7.8.3" + } + }, + "@babel/helper-replace-supers": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.8.6.tgz", + "integrity": "sha512-PeMArdA4Sv/Wf4zXwBKPqVj7n9UF/xg6slNRtZW84FM7JpE1CbG8B612FyM4cxrf4fMAMGO0kR7voy1ForHHFA==", + "requires": { + "@babel/helper-member-expression-to-functions": "^7.8.3", + "@babel/helper-optimise-call-expression": "^7.8.3", + "@babel/traverse": "^7.8.6", + "@babel/types": "^7.8.6" + } }, "@babel/helper-simple-access": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.1.0.tgz", - "integrity": "sha512-Vk+78hNjRbsiu49zAPALxTb+JUQCz1aolpd8osOF16BGnLtseD21nbHgLPGUwrXEurZgiCOUmvs3ExTu4F5x6w==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.8.3.tgz", + "integrity": "sha512-VNGUDjx5cCWg4vvCTR8qQ7YJYZ+HBjxOgXEl7ounz+4Sn7+LMD3CFrCTEU6/qXKbA2nKg21CwhhBzO0RpRbdCw==", "requires": { - "@babel/template": "^7.1.0", - "@babel/types": "^7.0.0" + "@babel/template": "^7.8.3", + "@babel/types": "^7.8.3" } }, "@babel/helper-split-export-declaration": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.0.0.tgz", - "integrity": "sha512-MXkOJqva62dfC0w85mEf/LucPPS/1+04nmmRMPEBUB++hiiThQ2zPtX/mEWQ3mtzCEjIJvPY8nuwxXtQeQwUag==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.8.3.tgz", + "integrity": "sha512-3x3yOeyBhW851hroze7ElzdkeRXQYQbFIb7gLK1WQYsw2GWDay5gAJNw1sWJ0VFP6z5J1whqeXH/WCdCjZv6dA==", + "requires": { + "@babel/types": "^7.8.3" + } + }, + "@babel/helper-validator-identifier": { + "version": "7.9.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.9.5.tgz", + "integrity": "sha512-/8arLKUFq882w4tWGj9JYzRpAlZgiWUJ+dtteNTDqrRBz9Iguck9Rn3ykuBDoUwh2TO4tSAJlrxDUOXWklJe4g==" + }, + "@babel/helper-wrap-function": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.8.3.tgz", + "integrity": "sha512-LACJrbUET9cQDzb6kG7EeD7+7doC3JNvUgTEQOx2qaO1fKlzE/Bf05qs9w1oXQMmXlPO65lC3Tq9S6gZpTErEQ==", + "dev": true, "requires": { - "@babel/types": "^7.0.0" + "@babel/helper-function-name": "^7.8.3", + "@babel/template": "^7.8.3", + "@babel/traverse": "^7.8.3", + "@babel/types": "^7.8.3" } }, "@babel/helpers": { - "version": "7.1.5", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.1.5.tgz", - "integrity": "sha512-2jkcdL02ywNBry1YNFAH/fViq4fXG0vdckHqeJk+75fpQ2OH+Az6076tX/M0835zA45E0Cqa6pV5Kiv9YOqjEg==", + "version": "7.9.2", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.9.2.tgz", + "integrity": "sha512-JwLvzlXVPjO8eU9c/wF9/zOIN7X6h8DYf7mG4CiFRZRvZNKEF5dQ3H3V+ASkHoIB3mWhatgl5ONhyqHRI6MppA==", "requires": { - "@babel/template": "^7.1.2", - "@babel/traverse": "^7.1.5", - "@babel/types": "^7.1.5" + "@babel/template": "^7.8.3", + "@babel/traverse": "^7.9.0", + "@babel/types": "^7.9.0" } }, "@babel/highlight": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0.tgz", - "integrity": "sha512-UFMC4ZeFC48Tpvj7C8UgLvtkaUuovQX+5xNWrsIoMG8o2z+XFKjKaN9iVmS84dPwVN00W4wPmqvYoZF3EGAsfw==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.9.0.tgz", + "integrity": "sha512-lJZPilxX7Op3Nv/2cvFdnlepPXDxi29wxteT57Q965oc5R9v86ztx0jfxVrTcBk8C2kcPkkDa2Z4T3ZsPPVWsQ==", "requires": { + "@babel/helper-validator-identifier": "^7.9.0", "chalk": "^2.0.0", - "esutils": "^2.0.2", "js-tokens": "^4.0.0" } }, "@babel/parser": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.1.6.tgz", - "integrity": "sha512-dWP6LJm9nKT6ALaa+bnL247GHHMWir3vSlZ2+IHgHgktZQx0L3Uvq2uAWcuzIe+fujRsYWBW2q622C5UvGK9iQ==" + "version": "7.9.4", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.9.4.tgz", + "integrity": "sha512-bC49otXX6N0/VYhgOMh4gnP26E9xnDZK3TmbNpxYzzz9BQLBosQwfyOe9/cXUU3txYhTzLCbcqd5c8y/OmCjHA==" + }, + "@babel/plugin-proposal-async-generator-functions": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.8.3.tgz", + "integrity": "sha512-NZ9zLv848JsV3hs8ryEh7Uaz/0KsmPLqv0+PdkDJL1cJy0K4kOCFa8zc1E3mp+RHPQcpdfb/6GovEsW4VDrOMw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/helper-remap-async-to-generator": "^7.8.3", + "@babel/plugin-syntax-async-generators": "^7.8.0" + } + }, + "@babel/plugin-proposal-object-rest-spread": { + "version": "7.9.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.9.5.tgz", + "integrity": "sha512-VP2oXvAf7KCYTthbUHwBlewbl1Iq059f6seJGsxMizaCdgHIeczOr7FBqELhSqfkIl04Fi8okzWzl63UKbQmmg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/plugin-syntax-object-rest-spread": "^7.8.0", + "@babel/plugin-transform-parameters": "^7.9.5" + } + }, + "@babel/plugin-proposal-optional-catch-binding": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-optional-catch-binding/-/plugin-proposal-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-0gkX7J7E+AtAw9fcwlVQj8peP61qhdg/89D5swOkjYbkboA2CVckn3kiyum1DE0wskGb7KJJxBdyEBApDLLVdw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.0" + } + }, + "@babel/plugin-syntax-async-generators": { + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", + "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-object-rest-spread": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", + "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-optional-catch-binding": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-transform-async-to-generator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.8.3.tgz", + "integrity": "sha512-imt9tFLD9ogt56Dd5CI/6XgpukMwd/fLGSrix2httihVe7LOGVPhyhMh1BU5kDM7iHD08i8uUtmV2sWaBFlHVQ==", + "dev": true, + "requires": { + "@babel/helper-module-imports": "^7.8.3", + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/helper-remap-async-to-generator": "^7.8.3" + } + }, + "@babel/plugin-transform-dotall-regex": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.8.3.tgz", + "integrity": "sha512-kLs1j9Nn4MQoBYdRXH6AeaXMbEJFaFu/v1nQkvib6QzTj8MZI5OQzqmD83/2jEM1z0DLilra5aWO5YpyC0ALIw==", + "dev": true, + "requires": { + "@babel/helper-create-regexp-features-plugin": "^7.8.3", + "@babel/helper-plugin-utils": "^7.8.3" + } + }, + "@babel/plugin-transform-exponentiation-operator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.8.3.tgz", + "integrity": "sha512-zwIpuIymb3ACcInbksHaNcR12S++0MDLKkiqXHl3AzpgdKlFNhog+z/K0+TGW+b0w5pgTq4H6IwV/WhxbGYSjQ==", + "dev": true, + "requires": { + "@babel/helper-builder-binary-assignment-operator-visitor": "^7.8.3", + "@babel/helper-plugin-utils": "^7.8.3" + } }, "@babel/plugin-transform-modules-commonjs": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.1.0.tgz", - "integrity": "sha512-wtNwtMjn1XGwM0AXPspQgvmE6msSJP15CX2RVfpTSTNPLhKhaOjaIfBaVfj4iUZ/VrFSodcFedwtPg/NxwQlPA==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.9.0.tgz", + "integrity": "sha512-qzlCrLnKqio4SlgJ6FMMLBe4bySNis8DFn1VkGmOcxG9gqEyPIOzeQrA//u0HAKrWpJlpZbZMPB1n/OPa4+n8g==", "requires": { - "@babel/helper-module-transforms": "^7.1.0", - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/helper-simple-access": "^7.1.0" + "@babel/helper-module-transforms": "^7.9.0", + "@babel/helper-plugin-utils": "^7.8.3", + "@babel/helper-simple-access": "^7.8.3", + "babel-plugin-dynamic-import-node": "^2.3.0" + } + }, + "@babel/plugin-transform-parameters": { + "version": "7.9.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.9.5.tgz", + "integrity": "sha512-0+1FhHnMfj6lIIhVvS4KGQJeuhe1GI//h5uptK4PvLt+BGBxsoUJbd3/IW002yk//6sZPlFgsG1hY6OHLcy6kA==", + "dev": true, + "requires": { + "@babel/helper-get-function-arity": "^7.8.3", + "@babel/helper-plugin-utils": "^7.8.3" } }, "@babel/template": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.1.2.tgz", - "integrity": "sha512-SY1MmplssORfFiLDcOETrW7fCLl+PavlwMh92rrGcikQaRq4iWPVH0MpwPpY3etVMx6RnDjXtr6VZYr/IbP/Ag==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.8.6.tgz", + "integrity": "sha512-zbMsPMy/v0PWFZEhQJ66bqjhH+z0JgMoBWuikXybgG3Gkd/3t5oQ1Rw2WQhnSrsOmsKXnZOx15tkC4qON/+JPg==", "requires": { - "@babel/code-frame": "^7.0.0", - "@babel/parser": "^7.1.2", - "@babel/types": "^7.1.2" + "@babel/code-frame": "^7.8.3", + "@babel/parser": "^7.8.6", + "@babel/types": "^7.8.6" } }, "@babel/traverse": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.1.6.tgz", - "integrity": "sha512-CXedit6GpISz3sC2k2FsGCUpOhUqKdyL0lqNrImQojagnUMXf8hex4AxYFRuMkNGcvJX5QAFGzB5WJQmSv8SiQ==", - "requires": { - "@babel/code-frame": "^7.0.0", - "@babel/generator": "^7.1.6", - "@babel/helper-function-name": "^7.1.0", - "@babel/helper-split-export-declaration": "^7.0.0", - "@babel/parser": "^7.1.6", - "@babel/types": "^7.1.6", + "version": "7.9.5", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.9.5.tgz", + "integrity": "sha512-c4gH3jsvSuGUezlP6rzSJ6jf8fYjLj3hsMZRx/nX0h+fmHN0w+ekubRrHPqnMec0meycA2nwCsJ7dC8IPem2FQ==", + "requires": { + "@babel/code-frame": "^7.8.3", + "@babel/generator": "^7.9.5", + "@babel/helper-function-name": "^7.9.5", + "@babel/helper-split-export-declaration": "^7.8.3", + "@babel/parser": "^7.9.0", + "@babel/types": "^7.9.5", "debug": "^4.1.0", "globals": "^11.1.0", - "lodash": "^4.17.10" + "lodash": "^4.17.13" } }, "@babel/types": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.1.6.tgz", - "integrity": "sha512-DMiUzlY9DSjVsOylJssxLHSgj6tWM9PRFJOGW/RaOglVOK9nzTxoOMfTfRQXGUCUQ/HmlG2efwC+XqUEJ5ay4w==", + "version": "7.9.5", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.9.5.tgz", + "integrity": "sha512-XjnvNqenk818r5zMaba+sLQjnbda31UfUURv3ei0qPQw4u+j2jMyJ5b11y8ZHYTRSI3NnInQkkkRT4fLqqPdHg==", "requires": { - "esutils": "^2.0.2", - "lodash": "^4.17.10", + "@babel/helper-validator-identifier": "^7.9.5", + "lodash": "^4.17.13", "to-fast-properties": "^2.0.0" } }, + "@concordance/react": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@concordance/react/-/react-2.0.0.tgz", + "integrity": "sha512-huLSkUuM2/P+U0uy2WwlKuixMsTODD8p4JVQBI4VKeopkiN0C7M3N9XYVawb4M+4spN5RrO/eLhk7KoQX6nsfA==", + "dev": true, + "requires": { + "arrify": "^1.0.1" + } + }, + "@types/events": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/events/-/events-3.0.0.tgz", + "integrity": "sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g==", + "dev": true + }, "@types/fs-extra": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-5.0.4.tgz", - "integrity": "sha512-DsknoBvD8s+RFfSGjmERJ7ZOP1HI0UZRA3FSI+Zakhrc/Gy26YQsLI+m5V5DHxroHRJqCDLKJp7Hixn8zyaF7g==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-5.1.0.tgz", + "integrity": "sha512-AInn5+UBFIK9FK5xc9yP5e3TQSPNNgjHByqYcj9g5elVBnDQcQL7PlO1CIRy2gWlbwK7UPYqi7vRvFA44dCmYQ==", "dev": true, "requires": { "@types/node": "*" } }, + "@types/glob": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/@types/glob/-/glob-7.1.1.tgz", + "integrity": "sha512-1Bh06cbWJUHMC97acuD6UMG29nMt0Aqz1vF3guLfG+kHHJhy3AyohZFFxYk2f7Q1SQIrNwvncxAE0N/9s70F2w==", + "dev": true, + "requires": { + "@types/events": "*", + "@types/minimatch": "*", + "@types/node": "*" + } + }, + "@types/minimatch": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", + "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==", + "dev": true + }, "@types/node": { - "version": "10.12.9", - "resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.9.tgz", - "integrity": "sha512-eajkMXG812/w3w4a1OcBlaTwsFPO5F7fJ/amy+tieQxEMWBlbV1JGSjkFM+zkHNf81Cad+dfIRA+IBkvmvdAeA==", + "version": "13.11.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-13.11.1.tgz", + "integrity": "sha512-eWQGP3qtxwL8FGneRrC5DwrJLGN4/dH1clNTuLfN81HCrxVtxRjygDTUoZJ5ASlDEeo0ppYFQjQIlXhtXpOn6g==", + "dev": true + }, + "ansi-align": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ansi-align/-/ansi-align-2.0.0.tgz", + "integrity": "sha1-w2rsy6VjuJzrVW82kPCx2eNUf38=", + "dev": true, + "requires": { + "string-width": "^2.0.0" + } + }, + "ansi-escapes": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==", + "dev": true + }, + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", "dev": true }, "ansi-styles": { @@ -207,6 +511,25 @@ "requires": { "micromatch": "^3.1.4", "normalize-path": "^2.1.1" + }, + "dependencies": { + "normalize-path": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", + "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", + "requires": { + "remove-trailing-separator": "^1.0.1" + } + } + } + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "requires": { + "sprintf-js": "~1.0.2" } }, "arr-diff": { @@ -224,26 +547,196 @@ "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=" }, + "array-differ": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/array-differ/-/array-differ-2.1.0.tgz", + "integrity": "sha512-KbUpJgx909ZscOc/7CLATBFam7P1Z1QRQInvgT0UztM9Q72aGKCunKASAl7WNW0tnPmPyEMeMhdsfWhfmW037w==", + "dev": true + }, + "array-find-index": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz", + "integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=", + "dev": true + }, + "array-union": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", + "integrity": "sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=", + "dev": true, + "requires": { + "array-uniq": "^1.0.1" + }, + "dependencies": { + "array-uniq": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", + "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=", + "dev": true + } + } + }, + "array-uniq": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-2.1.0.tgz", + "integrity": "sha512-bdHxtev7FN6+MXI1YFW0Q8mQ8dTJc2S8AMfju+ZR77pbg2yAdVyDlwkaUI7Har0LyOMRFPHrJ9lYdyjZZswdlQ==", + "dev": true + }, "array-unique": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=" }, + "arrify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", + "dev": true + }, "assign-symbols": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz", "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=" }, "async-each": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.1.tgz", - "integrity": "sha1-GdOGodntxufByF04iu28xW0zYC0=" + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.3.tgz", + "integrity": "sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ==" }, "atob": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==" }, + "ava": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/ava/-/ava-1.4.1.tgz", + "integrity": "sha512-wKpgOPTL7hJSBWpfbU4SA8rlsTZrph9g9g7qYDV7M6uK1rKeW8oCUJWRwCd8B24S4N0Y5myf6cTEnA66WIk0sA==", + "dev": true, + "requires": { + "@ava/babel-preset-stage-4": "^2.0.0", + "@ava/babel-preset-transform-test-files": "^5.0.0", + "@ava/write-file-atomic": "^2.2.0", + "@babel/core": "^7.4.0", + "@babel/generator": "^7.4.0", + "@babel/plugin-syntax-async-generators": "^7.2.0", + "@babel/plugin-syntax-object-rest-spread": "^7.2.0", + "@babel/plugin-syntax-optional-catch-binding": "^7.2.0", + "@concordance/react": "^2.0.0", + "ansi-escapes": "^3.2.0", + "ansi-styles": "^3.2.1", + "arr-flatten": "^1.1.0", + "array-union": "^1.0.1", + "array-uniq": "^2.0.0", + "arrify": "^1.0.0", + "bluebird": "^3.5.3", + "chalk": "^2.4.2", + "chokidar": "^2.1.5", + "chunkd": "^1.0.0", + "ci-parallel-vars": "^1.0.0", + "clean-stack": "^2.0.0", + "clean-yaml-object": "^0.1.0", + "cli-cursor": "^2.1.0", + "cli-truncate": "^1.1.0", + "code-excerpt": "^2.1.1", + "common-path-prefix": "^1.0.0", + "concordance": "^4.0.0", + "convert-source-map": "^1.6.0", + "currently-unhandled": "^0.4.1", + "debug": "^4.1.1", + "del": "^4.0.0", + "dot-prop": "^4.2.0", + "emittery": "^0.4.1", + "empower-core": "^1.2.0", + "equal-length": "^1.0.0", + "escape-string-regexp": "^1.0.5", + "esm": "^3.2.20", + "figures": "^2.0.0", + "find-up": "^3.0.0", + "get-port": "^4.2.0", + "globby": "^7.1.1", + "ignore-by-default": "^1.0.0", + "import-local": "^2.0.0", + "indent-string": "^3.2.0", + "is-ci": "^2.0.0", + "is-error": "^2.2.1", + "is-observable": "^1.1.0", + "is-plain-object": "^2.0.4", + "is-promise": "^2.1.0", + "lodash.clone": "^4.5.0", + "lodash.clonedeep": "^4.5.0", + "lodash.clonedeepwith": "^4.5.0", + "lodash.debounce": "^4.0.3", + "lodash.difference": "^4.3.0", + "lodash.flatten": "^4.2.0", + "loud-rejection": "^1.2.0", + "make-dir": "^2.1.0", + "matcher": "^1.1.1", + "md5-hex": "^2.0.0", + "meow": "^5.0.0", + "ms": "^2.1.1", + "multimatch": "^3.0.0", + "observable-to-promise": "^0.5.0", + "ora": "^3.2.0", + "package-hash": "^3.0.0", + "pkg-conf": "^3.0.0", + "plur": "^3.0.1", + "pretty-ms": "^4.0.0", + "require-precompiled": "^0.1.0", + "resolve-cwd": "^2.0.0", + "slash": "^2.0.0", + "source-map-support": "^0.5.11", + "stack-utils": "^1.0.2", + "strip-ansi": "^5.2.0", + "strip-bom-buf": "^1.0.0", + "supertap": "^1.0.0", + "supports-color": "^6.1.0", + "trim-off-newlines": "^1.0.1", + "trim-right": "^1.0.1", + "unique-temp-dir": "^1.0.0", + "update-notifier": "^2.5.0" + }, + "dependencies": { + "supports-color": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", + "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "babel-plugin-dynamic-import-node": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/babel-plugin-dynamic-import-node/-/babel-plugin-dynamic-import-node-2.3.0.tgz", + "integrity": "sha512-o6qFkpeQEBxcqt0XYlWzAVxNCSCZdUgcR8IRlhD/8DylxjjO4foPcvTW0GGKa/cVt3rvxZ7o5ippJ+/0nvLhlQ==", + "requires": { + "object.assign": "^4.1.0" + } + }, + "babel-plugin-espower": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/babel-plugin-espower/-/babel-plugin-espower-3.0.1.tgz", + "integrity": "sha512-Ms49U7VIAtQ/TtcqRbD6UBmJBUCSxiC3+zPc+eGqxKUIFO1lTshyEDRUjhoAbd2rWfwYf3cZ62oXozrd8W6J0A==", + "dev": true, + "requires": { + "@babel/generator": "^7.0.0", + "@babel/parser": "^7.0.0", + "call-matcher": "^1.0.0", + "core-js": "^2.0.0", + "espower-location-detector": "^1.0.0", + "espurify": "^1.6.0", + "estraverse": "^4.1.1" + } + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, "base": { "version": "0.11.2", "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", @@ -295,9 +788,49 @@ } }, "binary-extensions": { - "version": "1.12.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-1.12.0.tgz", - "integrity": "sha512-DYWGk01lDcxeS/K9IHPGWfT8PsJmbXRtRd2Sx72Tnb8pcYZQFF1oSDb8hJtS1vhp212q1Rzi5dUf9+nq0o9UIg==" + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-1.13.1.tgz", + "integrity": "sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw==" + }, + "bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "optional": true, + "requires": { + "file-uri-to-path": "1.0.0" + } + }, + "bluebird": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==", + "dev": true + }, + "boxen": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/boxen/-/boxen-1.3.0.tgz", + "integrity": "sha512-TNPjfTr432qx7yOjQyaXm3dSR0MH9vXp7eT1BFSl/C51g+EFnOR9hTg1IreahGBmDNCehscshe45f+C1TBZbLw==", + "dev": true, + "requires": { + "ansi-align": "^2.0.0", + "camelcase": "^4.0.0", + "chalk": "^2.0.1", + "cli-boxes": "^1.0.0", + "string-width": "^2.0.0", + "term-size": "^1.2.0", + "widest-line": "^2.0.0" + } + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } }, "braces": { "version": "2.3.2", @@ -326,6 +859,12 @@ } } }, + "buffer-from": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", + "dev": true + }, "cache-base": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", @@ -342,10 +881,51 @@ "unset-value": "^1.0.0" } }, + "call-matcher": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/call-matcher/-/call-matcher-1.1.0.tgz", + "integrity": "sha512-IoQLeNwwf9KTNbtSA7aEBb1yfDbdnzwjCetjkC8io5oGeOmK2CBNdg0xr+tadRYKO0p7uQyZzvon0kXlZbvGrw==", + "dev": true, + "requires": { + "core-js": "^2.0.0", + "deep-equal": "^1.0.0", + "espurify": "^1.6.0", + "estraverse": "^4.0.0" + } + }, + "call-signature": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/call-signature/-/call-signature-0.0.2.tgz", + "integrity": "sha1-qEq8glpV70yysCi9dOIFpluaSZY=", + "dev": true + }, + "camelcase": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz", + "integrity": "sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0=", + "dev": true + }, + "camelcase-keys": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-4.2.0.tgz", + "integrity": "sha1-oqpfsa9oh1glnDLBQUJteJI7m3c=", + "dev": true, + "requires": { + "camelcase": "^4.1.0", + "map-obj": "^2.0.0", + "quick-lru": "^1.0.0" + } + }, + "capture-stack-trace": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/capture-stack-trace/-/capture-stack-trace-1.0.1.tgz", + "integrity": "sha512-mYQLZnx5Qt1JgB1WEiMCf2647plpGeQ2NMR/5L0HNZzGQo4fuSPnK+wjfPnKZV0aiJDgzmWqqkV/g7JD+DW0qw==", + "dev": true + }, "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", @@ -353,508 +933,119 @@ } }, "chokidar": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-2.0.4.tgz", - "integrity": "sha512-z9n7yt9rOvIJrMhvDtDictKrkFHeihkNl6uWMmZlmL6tJtX9Cs+87oK+teBx+JIgzvbX3yZHT3eF8vpbDxHJXQ==", + "version": "2.1.8", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-2.1.8.tgz", + "integrity": "sha512-ZmZUazfOzf0Nve7duiCKD23PFSCs4JPoYyccjUFF3aQkQadqBhfzhjkwBH2mNOG9cTBwhamM37EIsIkZw3nRgg==", "requires": { "anymatch": "^2.0.0", - "async-each": "^1.0.0", - "braces": "^2.3.0", - "fsevents": "^1.2.2", + "async-each": "^1.0.1", + "braces": "^2.3.2", + "fsevents": "^1.2.7", "glob-parent": "^3.1.0", - "inherits": "^2.0.1", + "inherits": "^2.0.3", "is-binary-path": "^1.0.0", "is-glob": "^4.0.0", - "lodash.debounce": "^4.0.8", - "normalize-path": "^2.1.1", + "normalize-path": "^3.0.0", "path-is-absolute": "^1.0.0", - "readdirp": "^2.0.0", - "upath": "^1.0.5" + "readdirp": "^2.2.1", + "upath": "^1.1.1" + } + }, + "chunkd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/chunkd/-/chunkd-1.0.0.tgz", + "integrity": "sha512-xx3Pb5VF9QaqCotolyZ1ywFBgyuJmu6+9dLiqBxgelEse9Xsr3yUlpoX3O4Oh11M00GT2kYMsRByTKIMJW2Lkg==", + "dev": true + }, + "ci-info": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", + "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==", + "dev": true + }, + "ci-parallel-vars": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/ci-parallel-vars/-/ci-parallel-vars-1.0.0.tgz", + "integrity": "sha512-u6dx20FBXm+apMi+5x7UVm6EH7BL1gc4XrcnQewjcB7HWRcor/V5qWc3RG2HwpgDJ26gIi2DSEu3B7sXynAw/g==", + "dev": true + }, + "class-utils": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", + "integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==", + "requires": { + "arr-union": "^3.1.0", + "define-property": "^0.2.5", + "isobject": "^3.0.0", + "static-extend": "^0.1.1" }, "dependencies": { - "fsevents": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.4.tgz", - "integrity": "sha512-z8H8/diyk76B7q5wg+Ud0+CqzcAF3mBBI/bA5ne5zrRUUIvNkJY//D3BqyH571KuAC4Nr7Rw7CjWX4r0y9DvNg==", - "optional": true, + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", "requires": { - "nan": "^2.9.2", - "node-pre-gyp": "^0.10.0" - }, - "dependencies": { - "abbrev": { - "version": "1.1.1", - "bundled": true, - "optional": true - }, - "ansi-regex": { - "version": "2.1.1", - "bundled": true - }, - "aproba": { - "version": "1.2.0", - "bundled": true, - "optional": true - }, - "are-we-there-yet": { - "version": "1.1.4", - "bundled": true, - "optional": true, - "requires": { - "delegates": "^1.0.0", - "readable-stream": "^2.0.6" - } - }, - "balanced-match": { - "version": "1.0.0", - "bundled": true - }, - "brace-expansion": { - "version": "1.1.11", - "bundled": true, - "requires": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "chownr": { - "version": "1.0.1", - "bundled": true, - "optional": true - }, - "code-point-at": { - "version": "1.1.0", - "bundled": true - }, - "concat-map": { - "version": "0.0.1", - "bundled": true - }, - "console-control-strings": { - "version": "1.1.0", - "bundled": true - }, - "core-util-is": { - "version": "1.0.2", - "bundled": true, - "optional": true - }, - "debug": { - "version": "2.6.9", - "bundled": true, - "optional": true, - "requires": { - "ms": "2.0.0" - } - }, - "deep-extend": { - "version": "0.5.1", - "bundled": true, - "optional": true - }, - "delegates": { - "version": "1.0.0", - "bundled": true, - "optional": true - }, - "detect-libc": { - "version": "1.0.3", - "bundled": true, - "optional": true - }, - "fs-minipass": { - "version": "1.2.5", - "bundled": true, - "optional": true, - "requires": { - "minipass": "^2.2.1" - } - }, - "fs.realpath": { - "version": "1.0.0", - "bundled": true, - "optional": true - }, - "gauge": { - "version": "2.7.4", - "bundled": true, - "optional": true, - "requires": { - "aproba": "^1.0.3", - "console-control-strings": "^1.0.0", - "has-unicode": "^2.0.0", - "object-assign": "^4.1.0", - "signal-exit": "^3.0.0", - "string-width": "^1.0.1", - "strip-ansi": "^3.0.1", - "wide-align": "^1.1.0" - } - }, - "glob": { - "version": "7.1.2", - "bundled": true, - "optional": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "has-unicode": { - "version": "2.0.1", - "bundled": true, - "optional": true - }, - "iconv-lite": { - "version": "0.4.21", - "bundled": true, - "optional": true, - "requires": { - "safer-buffer": "^2.1.0" - } - }, - "ignore-walk": { - "version": "3.0.1", - "bundled": true, - "optional": true, - "requires": { - "minimatch": "^3.0.4" - } - }, - "inflight": { - "version": "1.0.6", - "bundled": true, - "optional": true, - "requires": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "inherits": { - "version": "2.0.3", - "bundled": true - }, - "ini": { - "version": "1.3.5", - "bundled": true, - "optional": true - }, - "is-fullwidth-code-point": { - "version": "1.0.0", - "bundled": true, - "requires": { - "number-is-nan": "^1.0.0" - } - }, - "isarray": { - "version": "1.0.0", - "bundled": true, - "optional": true - }, - "minimatch": { - "version": "3.0.4", - "bundled": true, - "requires": { - "brace-expansion": "^1.1.7" - } - }, - "minimist": { - "version": "0.0.8", - "bundled": true - }, - "minipass": { - "version": "2.2.4", - "bundled": true, - "requires": { - "safe-buffer": "^5.1.1", - "yallist": "^3.0.0" - } - }, - "minizlib": { - "version": "1.1.0", - "bundled": true, - "optional": true, - "requires": { - "minipass": "^2.2.1" - } - }, - "mkdirp": { - "version": "0.5.1", - "bundled": true, - "requires": { - "minimist": "0.0.8" - } - }, - "ms": { - "version": "2.0.0", - "bundled": true, - "optional": true - }, - "needle": { - "version": "2.2.0", - "bundled": true, - "optional": true, - "requires": { - "debug": "^2.1.2", - "iconv-lite": "^0.4.4", - "sax": "^1.2.4" - } - }, - "node-pre-gyp": { - "version": "0.10.0", - "bundled": true, - "optional": true, - "requires": { - "detect-libc": "^1.0.2", - "mkdirp": "^0.5.1", - "needle": "^2.2.0", - "nopt": "^4.0.1", - "npm-packlist": "^1.1.6", - "npmlog": "^4.0.2", - "rc": "^1.1.7", - "rimraf": "^2.6.1", - "semver": "^5.3.0", - "tar": "^4" - } - }, - "nopt": { - "version": "4.0.1", - "bundled": true, - "optional": true, - "requires": { - "abbrev": "1", - "osenv": "^0.1.4" - } - }, - "npm-bundled": { - "version": "1.0.3", - "bundled": true, - "optional": true - }, - "npm-packlist": { - "version": "1.1.10", - "bundled": true, - "optional": true, - "requires": { - "ignore-walk": "^3.0.1", - "npm-bundled": "^1.0.1" - } - }, - "npmlog": { - "version": "4.1.2", - "bundled": true, - "optional": true, - "requires": { - "are-we-there-yet": "~1.1.2", - "console-control-strings": "~1.1.0", - "gauge": "~2.7.3", - "set-blocking": "~2.0.0" - } - }, - "number-is-nan": { - "version": "1.0.1", - "bundled": true - }, - "object-assign": { - "version": "4.1.1", - "bundled": true, - "optional": true - }, - "once": { - "version": "1.4.0", - "bundled": true, - "requires": { - "wrappy": "1" - } - }, - "os-homedir": { - "version": "1.0.2", - "bundled": true, - "optional": true - }, - "os-tmpdir": { - "version": "1.0.2", - "bundled": true, - "optional": true - }, - "osenv": { - "version": "0.1.5", - "bundled": true, - "optional": true, - "requires": { - "os-homedir": "^1.0.0", - "os-tmpdir": "^1.0.0" - } - }, - "path-is-absolute": { - "version": "1.0.1", - "bundled": true, - "optional": true - }, - "process-nextick-args": { - "version": "2.0.0", - "bundled": true, - "optional": true - }, - "rc": { - "version": "1.2.7", - "bundled": true, - "optional": true, - "requires": { - "deep-extend": "^0.5.1", - "ini": "~1.3.0", - "minimist": "^1.2.0", - "strip-json-comments": "~2.0.1" - }, - "dependencies": { - "minimist": { - "version": "1.2.0", - "bundled": true, - "optional": true - } - } - }, - "readable-stream": { - "version": "2.3.6", - "bundled": true, - "optional": true, - "requires": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - } - }, - "rimraf": { - "version": "2.6.2", - "bundled": true, - "optional": true, - "requires": { - "glob": "^7.0.5" - } - }, - "safe-buffer": { - "version": "5.1.1", - "bundled": true - }, - "safer-buffer": { - "version": "2.1.2", - "bundled": true, - "optional": true - }, - "sax": { - "version": "1.2.4", - "bundled": true, - "optional": true - }, - "semver": { - "version": "5.5.0", - "bundled": true, - "optional": true - }, - "set-blocking": { - "version": "2.0.0", - "bundled": true, - "optional": true - }, - "signal-exit": { - "version": "3.0.2", - "bundled": true, - "optional": true - }, - "string-width": { - "version": "1.0.2", - "bundled": true, - "requires": { - "code-point-at": "^1.0.0", - "is-fullwidth-code-point": "^1.0.0", - "strip-ansi": "^3.0.0" - } - }, - "string_decoder": { - "version": "1.1.1", - "bundled": true, - "optional": true, - "requires": { - "safe-buffer": "~5.1.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "bundled": true, - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "strip-json-comments": { - "version": "2.0.1", - "bundled": true, - "optional": true - }, - "tar": { - "version": "4.4.1", - "bundled": true, - "optional": true, - "requires": { - "chownr": "^1.0.1", - "fs-minipass": "^1.2.5", - "minipass": "^2.2.4", - "minizlib": "^1.1.0", - "mkdirp": "^0.5.0", - "safe-buffer": "^5.1.1", - "yallist": "^3.0.2" - } - }, - "util-deprecate": { - "version": "1.0.2", - "bundled": true, - "optional": true - }, - "wide-align": { - "version": "1.1.2", - "bundled": true, - "optional": true, - "requires": { - "string-width": "^1.0.2" - } - }, - "wrappy": { - "version": "1.0.2", - "bundled": true - }, - "yallist": { - "version": "3.0.2", - "bundled": true - } + "is-descriptor": "^0.1.0" } } } }, - "class-utils": { - "version": "0.3.6", - "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", - "integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==", + "clean-stack": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", + "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", + "dev": true + }, + "clean-yaml-object": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/clean-yaml-object/-/clean-yaml-object-0.1.0.tgz", + "integrity": "sha1-Y/sRDcLOGoTcIfbZM0h20BCui2g=", + "dev": true + }, + "cli-boxes": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", + "integrity": "sha1-T6kXw+WclKAEzWH47lCdplFocUM=", + "dev": true + }, + "cli-cursor": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", + "integrity": "sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU=", + "dev": true, "requires": { - "arr-union": "^3.1.0", - "define-property": "^0.2.5", - "isobject": "^3.0.0", - "static-extend": "^0.1.1" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "requires": { - "is-descriptor": "^0.1.0" - } - } + "restore-cursor": "^2.0.0" + } + }, + "cli-spinners": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.3.0.tgz", + "integrity": "sha512-Xs2Hf2nzrvJMFKimOR7YR0QwZ8fc0u98kdtwN1eNAZzNQgH3vK2pXzff6GJtKh7S5hoJ87ECiAiZFS2fb5Ii2w==", + "dev": true + }, + "cli-truncate": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-1.1.0.tgz", + "integrity": "sha512-bAtZo0u82gCfaAGfSNxUdTI9mNyza7D8w4CVCcaOsy7sgwDzvx6ekr6cuWJqY3UGzgnQ1+4wgENup5eIhgxEYA==", + "dev": true, + "requires": { + "slice-ansi": "^1.0.0", + "string-width": "^2.0.0" + } + }, + "clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha1-2jCcwmPfFZlMaIypAheco8fNfH4=", + "dev": true + }, + "code-excerpt": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/code-excerpt/-/code-excerpt-2.1.1.tgz", + "integrity": "sha512-tJLhH3EpFm/1x7heIW0hemXJTUU5EWl2V0EIX558jp05Mt1U6DVryCgkp3l37cxqs+DNbNgxG43SkwJXpQ14Jw==", + "dev": true, + "requires": { + "convert-to-spaces": "^1.0.1" } }, "collection-visit": { @@ -879,42 +1070,221 @@ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, + "common-path-prefix": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/common-path-prefix/-/common-path-prefix-1.0.0.tgz", + "integrity": "sha1-zVL28HEuC6q5fW+XModPIvR3UsA=", + "dev": true + }, "component-emitter": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz", - "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=" + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", + "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==" + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "concordance": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/concordance/-/concordance-4.0.0.tgz", + "integrity": "sha512-l0RFuB8RLfCS0Pt2Id39/oCPykE01pyxgAFypWTlaGRgvLkZrtczZ8atEHpTeEIW+zYWXTBuA9cCSeEOScxReQ==", + "dev": true, + "requires": { + "date-time": "^2.1.0", + "esutils": "^2.0.2", + "fast-diff": "^1.1.2", + "js-string-escape": "^1.0.1", + "lodash.clonedeep": "^4.5.0", + "lodash.flattendeep": "^4.4.0", + "lodash.islength": "^4.0.1", + "lodash.merge": "^4.6.1", + "md5-hex": "^2.0.0", + "semver": "^5.5.1", + "well-known-symbols": "^2.0.0" + } + }, + "configstore": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/configstore/-/configstore-3.1.2.tgz", + "integrity": "sha512-vtv5HtGjcYUgFrXc6Kx747B83MRRVS5R1VTEQoXvuP+kMI+if6uywV0nDGoiydJRy4yk7h9od5Og0kxx4zUXmw==", + "dev": true, + "requires": { + "dot-prop": "^4.1.0", + "graceful-fs": "^4.1.2", + "make-dir": "^1.0.0", + "unique-string": "^1.0.0", + "write-file-atomic": "^2.0.0", + "xdg-basedir": "^3.0.0" + }, + "dependencies": { + "make-dir": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.3.0.tgz", + "integrity": "sha512-2w31R7SJtieJJnQtGc7RVL2StM2vGYVfqUOvUDxH6bC6aJTxPxTF0GnIgCyu7tjockiUWAYQRbxa7vKn34s5sQ==", + "dev": true, + "requires": { + "pify": "^3.0.0" + } + }, + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "dev": true + } + } }, "convert-source-map": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.6.0.tgz", - "integrity": "sha512-eFu7XigvxdZ1ETfbgPBohgyQ/Z++C0eEhTor0qRwBw9unw+L0/6V8wkSuGgzdThkiS5lSpdptOQPD8Ak40a+7A==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.7.0.tgz", + "integrity": "sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA==", "requires": { "safe-buffer": "~5.1.1" } }, + "convert-to-spaces": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/convert-to-spaces/-/convert-to-spaces-1.0.2.tgz", + "integrity": "sha1-fj5Iu+bZl7FBfdyihoIEtNPYVxU=", + "dev": true + }, "copy-descriptor": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=" }, + "core-js": { + "version": "2.6.11", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.11.tgz", + "integrity": "sha512-5wjnpaT/3dV+XB4borEsnAYQchn00XSgTAWKDkEqv+K8KevjbzmofK6hfJ9TZIlpj2N0xQpazy7PiRQiWHqzWg==", + "dev": true + }, "core-util-is": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" }, + "create-error-class": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/create-error-class/-/create-error-class-3.0.2.tgz", + "integrity": "sha1-Br56vvlHo/FKMP1hBnHUAbyot7Y=", + "dev": true, + "requires": { + "capture-stack-trace": "^1.0.0" + } + }, + "cross-spawn": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-5.1.0.tgz", + "integrity": "sha1-6L0O/uWPz/b4+UUQoKVUu/ojVEk=", + "dev": true, + "requires": { + "lru-cache": "^4.0.1", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "crypto-random-string": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-1.0.0.tgz", + "integrity": "sha1-ojD2T1aDEOFJgAmUB5DsmVRbyn4=", + "dev": true + }, + "currently-unhandled": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/currently-unhandled/-/currently-unhandled-0.4.1.tgz", + "integrity": "sha1-mI3zP+qxke95mmE2nddsF635V+o=", + "dev": true, + "requires": { + "array-find-index": "^1.0.1" + } + }, + "date-time": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/date-time/-/date-time-2.1.0.tgz", + "integrity": "sha512-/9+C44X7lot0IeiyfgJmETtRMhBidBYM2QFFIkGa0U1k+hSyY87Nw7PY3eDqpvCBm7I3WCSfPeZskW/YYq6m4g==", + "dev": true, + "requires": { + "time-zone": "^1.0.0" + } + }, "debug": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.0.tgz", - "integrity": "sha512-heNPJUJIqC+xB6ayLAMHaIrmN9HKa7aQO8MGqKpvCA+uJYVcvR6l5kgdrhRuwPFHU7P5/A1w0BjByPHwpfTDKg==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", "requires": { "ms": "^2.1.1" } }, + "decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", + "dev": true + }, + "decamelize-keys": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/decamelize-keys/-/decamelize-keys-1.1.0.tgz", + "integrity": "sha1-0XGoeTMlKAfrPLYdwcFEXQeN8tk=", + "dev": true, + "requires": { + "decamelize": "^1.1.0", + "map-obj": "^1.0.0" + }, + "dependencies": { + "map-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", + "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=", + "dev": true + } + } + }, "decode-uri-component": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=" }, + "deep-equal": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.1.1.tgz", + "integrity": "sha512-yd9c5AdiqVcR+JjcwUQb9DkhJc8ngNr0MahEBGvDiJw8puWab2yZlh+nkasOnZP+EGTAP6rRp2JzJhJZzvNF8g==", + "dev": true, + "requires": { + "is-arguments": "^1.0.4", + "is-date-object": "^1.0.1", + "is-regex": "^1.0.4", + "object-is": "^1.0.1", + "object-keys": "^1.1.1", + "regexp.prototype.flags": "^1.2.0" + } + }, + "deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "dev": true + }, + "defaults": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.3.tgz", + "integrity": "sha1-xlYFHpgX2f8I7YgUd/P+QBnz730=", + "dev": true, + "requires": { + "clone": "^1.0.2" + } + }, + "define-properties": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", + "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", + "requires": { + "object-keys": "^1.0.12" + } + }, "define-property": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", @@ -952,15 +1322,199 @@ } } }, + "del": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/del/-/del-4.1.1.tgz", + "integrity": "sha512-QwGuEUouP2kVwQenAsOof5Fv8K9t3D8Ca8NxcXKrIpEHjTXK5J2nXLdP+ALI1cgv8wj7KuwBhTwBkOZSJKM5XQ==", + "dev": true, + "requires": { + "@types/glob": "^7.1.1", + "globby": "^6.1.0", + "is-path-cwd": "^2.0.0", + "is-path-in-cwd": "^2.0.0", + "p-map": "^2.0.0", + "pify": "^4.0.1", + "rimraf": "^2.6.3" + }, + "dependencies": { + "globby": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-6.1.0.tgz", + "integrity": "sha1-9abXDoOV4hyFj7BInWTfAkJNUGw=", + "dev": true, + "requires": { + "array-union": "^1.0.1", + "glob": "^7.0.3", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + }, + "dependencies": { + "pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true + } + } + } + } + }, + "dir-glob": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-2.2.2.tgz", + "integrity": "sha512-f9LBi5QWzIW3I6e//uxZoLBlUt9kcp66qo0sSCxL6YZKc75R1c4MFCoe/LaZiBGmgujvQdxc5Bn3QhfyvK5Hsw==", + "dev": true, + "requires": { + "path-type": "^3.0.0" + } + }, + "dot-prop": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-4.2.0.tgz", + "integrity": "sha512-tUMXrxlExSW6U2EXiiKGSBVdYgtV8qlHL+C10TsW4PURY/ic+eaysnSkwB4kA/mBlCyy/IKDJ+Lc3wbWeaXtuQ==", + "dev": true, + "requires": { + "is-obj": "^1.0.0" + } + }, + "duplexer3": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer3/-/duplexer3-0.1.4.tgz", + "integrity": "sha1-7gHdHKwO08vH/b6jfcCo8c4ALOI=", + "dev": true + }, + "emittery": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.4.1.tgz", + "integrity": "sha512-r4eRSeStEGf6M5SKdrQhhLK5bOwOBxQhIE3YSTnZE3GpKiLfnnhE+tPtrJE79+eDJgm39BM6LSoI8SCx4HbwlQ==", + "dev": true + }, + "empower-core": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/empower-core/-/empower-core-1.2.0.tgz", + "integrity": "sha512-g6+K6Geyc1o6FdXs9HwrXleCFan7d66G5xSCfSF7x1mJDCes6t0om9lFQG3zOrzh3Bkb/45N0cZ5Gqsf7YrzGQ==", + "dev": true, + "requires": { + "call-signature": "0.0.2", + "core-js": "^2.0.0" + } + }, + "equal-length": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/equal-length/-/equal-length-1.0.1.tgz", + "integrity": "sha1-IcoRLUirJLTh5//A5TOdMf38J0w=", + "dev": true + }, + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "requires": { + "is-arrayish": "^0.2.1" + } + }, + "es-abstract": { + "version": "1.17.5", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.17.5.tgz", + "integrity": "sha512-BR9auzDbySxOcfog0tLECW8l28eRGpDpU3Dm3Hp4q/N+VtLTmyj4EUN088XZWQDW/hzj6sYRDXeOFsaAODKvpg==", + "dev": true, + "requires": { + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1", + "is-callable": "^1.1.5", + "is-regex": "^1.0.5", + "object-inspect": "^1.7.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.0", + "string.prototype.trimleft": "^2.1.1", + "string.prototype.trimright": "^2.1.1" + } + }, + "es-to-primitive": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "dev": true, + "requires": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + } + }, + "es6-error": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz", + "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==", + "dev": true + }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" }, + "esm": { + "version": "3.2.25", + "resolved": "https://registry.npmjs.org/esm/-/esm-3.2.25.tgz", + "integrity": "sha512-U1suiZ2oDVWv4zPO56S0NcR5QriEahGtdN2OR6FiOG4WJvcjBVFB0qI4+eKoWFH483PKGuLuu6V8Z4T5g63UVA==", + "dev": true + }, + "espower-location-detector": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/espower-location-detector/-/espower-location-detector-1.0.0.tgz", + "integrity": "sha1-oXt+zFnTDheeK+9z+0E3cEyzMbU=", + "dev": true, + "requires": { + "is-url": "^1.2.1", + "path-is-absolute": "^1.0.0", + "source-map": "^0.5.0", + "xtend": "^4.0.0" + } + }, + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true + }, + "espurify": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/espurify/-/espurify-1.8.1.tgz", + "integrity": "sha512-ZDko6eY/o+D/gHCWyHTU85mKDgYcS4FJj7S+YD6WIInm7GQ6AnOjmcL4+buFV/JOztVLELi/7MmuGU5NHta0Mg==", + "dev": true, + "requires": { + "core-js": "^2.0.0" + } + }, + "estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true + }, "esutils": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", - "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=" + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true + }, + "execa": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-0.7.0.tgz", + "integrity": "sha1-lEvs00zEHuMqY6n68nrVpl/Fl3c=", + "dev": true, + "requires": { + "cross-spawn": "^5.0.1", + "get-stream": "^3.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + } }, "expand-brackets": { "version": "2.1.4", @@ -1086,9 +1640,30 @@ } }, "fable-babel-plugins": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fable-babel-plugins/-/fable-babel-plugins-2.1.0.tgz", - "integrity": "sha512-5ZUVrlflbvgA3saIyGJhB1ANqoyZ8UJo12iYSROivql1x9PfKjv16pteNoDFCe6UC1Tn+HaQX46BxyllzLsBTw==" + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/fable-babel-plugins/-/fable-babel-plugins-2.3.0.tgz", + "integrity": "sha512-alGBNw5HZJzTEznXKfypFEkD5aWsspbCcoVDu9j8Mqdi77dgp4BSjhYSg61mQEg9UluIAZxRM5lhGARYbU97DQ==" + }, + "fast-diff": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.2.0.tgz", + "integrity": "sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w==", + "dev": true + }, + "figures": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", + "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", + "dev": true, + "requires": { + "escape-string-regexp": "^1.0.5" + } + }, + "file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "optional": true }, "fill-range": { "version": "4.0.0", @@ -1111,8 +1686,17 @@ } } }, - "for-in": { - "version": "1.0.2", + "find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "dev": true, + "requires": { + "locate-path": "^3.0.0" + } + }, + "for-in": { + "version": "1.0.2", "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=" }, @@ -1134,11 +1718,537 @@ "universalify": "^0.1.0" } }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "fsevents": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.12.tgz", + "integrity": "sha512-Ggd/Ktt7E7I8pxZRbGIs7vwqAPscSESMrCSkx2FtWeqmheJgCo2R74fTsZFCifr0VTPwqRpPv17+6b8Zp7th0Q==", + "optional": true, + "requires": { + "bindings": "^1.5.0", + "nan": "^2.12.1", + "node-pre-gyp": "*" + }, + "dependencies": { + "abbrev": { + "version": "1.1.1", + "bundled": true, + "optional": true + }, + "ansi-regex": { + "version": "2.1.1", + "bundled": true, + "optional": true + }, + "aproba": { + "version": "1.2.0", + "bundled": true, + "optional": true + }, + "are-we-there-yet": { + "version": "1.1.5", + "bundled": true, + "optional": true, + "requires": { + "delegates": "^1.0.0", + "readable-stream": "^2.0.6" + } + }, + "balanced-match": { + "version": "1.0.0", + "bundled": true, + "optional": true + }, + "brace-expansion": { + "version": "1.1.11", + "bundled": true, + "optional": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "chownr": { + "version": "1.1.4", + "bundled": true, + "optional": true + }, + "code-point-at": { + "version": "1.1.0", + "bundled": true, + "optional": true + }, + "concat-map": { + "version": "0.0.1", + "bundled": true, + "optional": true + }, + "console-control-strings": { + "version": "1.1.0", + "bundled": true, + "optional": true + }, + "core-util-is": { + "version": "1.0.2", + "bundled": true, + "optional": true + }, + "debug": { + "version": "3.2.6", + "bundled": true, + "optional": true, + "requires": { + "ms": "^2.1.1" + } + }, + "deep-extend": { + "version": "0.6.0", + "bundled": true, + "optional": true + }, + "delegates": { + "version": "1.0.0", + "bundled": true, + "optional": true + }, + "detect-libc": { + "version": "1.0.3", + "bundled": true, + "optional": true + }, + "fs-minipass": { + "version": "1.2.7", + "bundled": true, + "optional": true, + "requires": { + "minipass": "^2.6.0" + } + }, + "fs.realpath": { + "version": "1.0.0", + "bundled": true, + "optional": true + }, + "gauge": { + "version": "2.7.4", + "bundled": true, + "optional": true, + "requires": { + "aproba": "^1.0.3", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.0", + "object-assign": "^4.1.0", + "signal-exit": "^3.0.0", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wide-align": "^1.1.0" + } + }, + "glob": { + "version": "7.1.6", + "bundled": true, + "optional": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "has-unicode": { + "version": "2.0.1", + "bundled": true, + "optional": true + }, + "iconv-lite": { + "version": "0.4.24", + "bundled": true, + "optional": true, + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "ignore-walk": { + "version": "3.0.3", + "bundled": true, + "optional": true, + "requires": { + "minimatch": "^3.0.4" + } + }, + "inflight": { + "version": "1.0.6", + "bundled": true, + "optional": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "bundled": true, + "optional": true + }, + "ini": { + "version": "1.3.5", + "bundled": true, + "optional": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "bundled": true, + "optional": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "isarray": { + "version": "1.0.0", + "bundled": true, + "optional": true + }, + "minimatch": { + "version": "3.0.4", + "bundled": true, + "optional": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "1.2.5", + "bundled": true, + "optional": true + }, + "minipass": { + "version": "2.9.0", + "bundled": true, + "optional": true, + "requires": { + "safe-buffer": "^5.1.2", + "yallist": "^3.0.0" + } + }, + "minizlib": { + "version": "1.3.3", + "bundled": true, + "optional": true, + "requires": { + "minipass": "^2.9.0" + } + }, + "mkdirp": { + "version": "0.5.3", + "bundled": true, + "optional": true, + "requires": { + "minimist": "^1.2.5" + } + }, + "ms": { + "version": "2.1.2", + "bundled": true, + "optional": true + }, + "needle": { + "version": "2.3.3", + "bundled": true, + "optional": true, + "requires": { + "debug": "^3.2.6", + "iconv-lite": "^0.4.4", + "sax": "^1.2.4" + } + }, + "node-pre-gyp": { + "version": "0.14.0", + "bundled": true, + "optional": true, + "requires": { + "detect-libc": "^1.0.2", + "mkdirp": "^0.5.1", + "needle": "^2.2.1", + "nopt": "^4.0.1", + "npm-packlist": "^1.1.6", + "npmlog": "^4.0.2", + "rc": "^1.2.7", + "rimraf": "^2.6.1", + "semver": "^5.3.0", + "tar": "^4.4.2" + } + }, + "nopt": { + "version": "4.0.3", + "bundled": true, + "optional": true, + "requires": { + "abbrev": "1", + "osenv": "^0.1.4" + } + }, + "npm-bundled": { + "version": "1.1.1", + "bundled": true, + "optional": true, + "requires": { + "npm-normalize-package-bin": "^1.0.1" + } + }, + "npm-normalize-package-bin": { + "version": "1.0.1", + "bundled": true, + "optional": true + }, + "npm-packlist": { + "version": "1.4.8", + "bundled": true, + "optional": true, + "requires": { + "ignore-walk": "^3.0.1", + "npm-bundled": "^1.0.1", + "npm-normalize-package-bin": "^1.0.1" + } + }, + "npmlog": { + "version": "4.1.2", + "bundled": true, + "optional": true, + "requires": { + "are-we-there-yet": "~1.1.2", + "console-control-strings": "~1.1.0", + "gauge": "~2.7.3", + "set-blocking": "~2.0.0" + } + }, + "number-is-nan": { + "version": "1.0.1", + "bundled": true, + "optional": true + }, + "object-assign": { + "version": "4.1.1", + "bundled": true, + "optional": true + }, + "once": { + "version": "1.4.0", + "bundled": true, + "optional": true, + "requires": { + "wrappy": "1" + } + }, + "os-homedir": { + "version": "1.0.2", + "bundled": true, + "optional": true + }, + "os-tmpdir": { + "version": "1.0.2", + "bundled": true, + "optional": true + }, + "osenv": { + "version": "0.1.5", + "bundled": true, + "optional": true, + "requires": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "bundled": true, + "optional": true + }, + "process-nextick-args": { + "version": "2.0.1", + "bundled": true, + "optional": true + }, + "rc": { + "version": "1.2.8", + "bundled": true, + "optional": true, + "requires": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + } + }, + "readable-stream": { + "version": "2.3.7", + "bundled": true, + "optional": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "rimraf": { + "version": "2.7.1", + "bundled": true, + "optional": true, + "requires": { + "glob": "^7.1.3" + } + }, + "safe-buffer": { + "version": "5.1.2", + "bundled": true, + "optional": true + }, + "safer-buffer": { + "version": "2.1.2", + "bundled": true, + "optional": true + }, + "sax": { + "version": "1.2.4", + "bundled": true, + "optional": true + }, + "semver": { + "version": "5.7.1", + "bundled": true, + "optional": true + }, + "set-blocking": { + "version": "2.0.0", + "bundled": true, + "optional": true + }, + "signal-exit": { + "version": "3.0.2", + "bundled": true, + "optional": true + }, + "string-width": { + "version": "1.0.2", + "bundled": true, + "optional": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "string_decoder": { + "version": "1.1.1", + "bundled": true, + "optional": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "bundled": true, + "optional": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "strip-json-comments": { + "version": "2.0.1", + "bundled": true, + "optional": true + }, + "tar": { + "version": "4.4.13", + "bundled": true, + "optional": true, + "requires": { + "chownr": "^1.1.1", + "fs-minipass": "^1.2.5", + "minipass": "^2.8.6", + "minizlib": "^1.2.1", + "mkdirp": "^0.5.0", + "safe-buffer": "^5.1.2", + "yallist": "^3.0.3" + } + }, + "util-deprecate": { + "version": "1.0.2", + "bundled": true, + "optional": true + }, + "wide-align": { + "version": "1.1.3", + "bundled": true, + "optional": true, + "requires": { + "string-width": "^1.0.2 || 2" + } + }, + "wrappy": { + "version": "1.0.2", + "bundled": true, + "optional": true + }, + "yallist": { + "version": "3.1.1", + "bundled": true, + "optional": true + } + } + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "gensync": { + "version": "1.0.0-beta.1", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.1.tgz", + "integrity": "sha512-r8EC6NO1sngH/zdD9fiRDLdcgnbayXah+mLgManTaIZJqEC1MZstmnox8KpnI2/fxQwrp5OpCOYWLp4rBl4Jcg==" + }, + "get-port": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/get-port/-/get-port-4.2.0.tgz", + "integrity": "sha512-/b3jarXkH8KJoOMQc3uVGHASwGLPq3gSFJ7tgJm2diza+bydJPTGOibin2steecKeOylE8oY2JERlVWkAJO6yw==", + "dev": true + }, + "get-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz", + "integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ=", + "dev": true + }, "get-value": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=" }, + "glob": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, "glob-parent": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz", @@ -1158,21 +2268,91 @@ } } }, + "global-dirs": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/global-dirs/-/global-dirs-0.1.1.tgz", + "integrity": "sha1-sxnA3UYH81PzvpzKTHL8FIxJ9EU=", + "dev": true, + "requires": { + "ini": "^1.3.4" + } + }, "globals": { - "version": "11.9.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.9.0.tgz", - "integrity": "sha512-5cJVtyXWH8PiJPVLZzzoIizXx944O4OmRro5MWKx5fT4MgcN7OfaMutPeaTdJCCURwbWdhhcCWcKIffPnmTzBg==" + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==" + }, + "globby": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/globby/-/globby-7.1.1.tgz", + "integrity": "sha1-+yzP+UAfhgCUXfral0QMypcrhoA=", + "dev": true, + "requires": { + "array-union": "^1.0.1", + "dir-glob": "^2.0.0", + "glob": "^7.1.2", + "ignore": "^3.3.5", + "pify": "^3.0.0", + "slash": "^1.0.0" + }, + "dependencies": { + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "dev": true + }, + "slash": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-1.0.0.tgz", + "integrity": "sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU=", + "dev": true + } + } + }, + "got": { + "version": "6.7.1", + "resolved": "https://registry.npmjs.org/got/-/got-6.7.1.tgz", + "integrity": "sha1-JAzQV4WpoY5WHcG0S0HHY+8ejbA=", + "dev": true, + "requires": { + "create-error-class": "^3.0.0", + "duplexer3": "^0.1.4", + "get-stream": "^3.0.0", + "is-redirect": "^1.0.0", + "is-retry-allowed": "^1.0.0", + "is-stream": "^1.0.0", + "lowercase-keys": "^1.0.0", + "safe-buffer": "^5.0.1", + "timed-out": "^4.0.0", + "unzip-response": "^2.0.1", + "url-parse-lax": "^1.0.0" + } }, "graceful-fs": { - "version": "4.1.15", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", - "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==" + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.3.tgz", + "integrity": "sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ==" + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1" + } }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" }, + "has-symbols": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", + "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==" + }, "has-value": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", @@ -1202,10 +2382,93 @@ } } }, + "hasha": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hasha/-/hasha-3.0.0.tgz", + "integrity": "sha1-UqMvq4Vp1BymmmH/GiFPjrfIvTk=", + "dev": true, + "requires": { + "is-stream": "^1.0.1" + } + }, + "hosted-git-info": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.8.tgz", + "integrity": "sha512-f/wzC2QaWBs7t9IYqB4T3sR1xviIViXJRJTWBlx2Gf3g0Xi5vI7Yy4koXQ1c9OYDGHN9sBy1DQ2AB8fqZBWhUg==", + "dev": true + }, + "ignore": { + "version": "3.3.10", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.10.tgz", + "integrity": "sha512-Pgs951kaMm5GXP7MOvxERINe3gsaVjUWFm+UZPSq9xYriQAksyhg0csnS0KXSNRD5NmNdapXEpjxG49+AKh/ug==", + "dev": true + }, + "ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha1-SMptcvbGo68Aqa1K5odr44ieKwk=", + "dev": true + }, + "import-lazy": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/import-lazy/-/import-lazy-2.1.0.tgz", + "integrity": "sha1-BWmOPUXIjo1+nZLLBYTnfwlvPkM=", + "dev": true + }, + "import-local": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-2.0.0.tgz", + "integrity": "sha512-b6s04m3O+s3CGSbqDIyP4R6aAwAeYlVq9+WUWep6iHa8ETRf9yei1U48C5MmfJmV9AiLYYBKPMq/W+/WRpQmCQ==", + "dev": true, + "requires": { + "pkg-dir": "^3.0.0", + "resolve-cwd": "^2.0.0" + } + }, + "imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "dev": true + }, + "indent-string": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-3.2.0.tgz", + "integrity": "sha1-Sl/W0nzDMvN+VBmlBNu4NxBckok=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "ini": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz", + "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==", + "dev": true + }, + "interpret": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.2.0.tgz", + "integrity": "sha512-mT34yGKMNceBQUoVn7iCDKDntA7SC6gycMAWzGx1z/CMCTV7b2AAtXlo3nRyHZ1FelRkQbQjprHSYGwzLtkVbw==", + "dev": true + }, + "irregular-plurals": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/irregular-plurals/-/irregular-plurals-2.0.0.tgz", + "integrity": "sha512-Y75zBYLkh0lJ9qxeHlMjQ7bSbyiSqNW/UOPWDmzC7cXskL1hekSITh1Oc6JV0XCWWZ9DE8VYSB71xocLk3gmGw==", + "dev": true }, "is-accessor-descriptor": { "version": "0.1.6", @@ -1225,6 +2488,18 @@ } } }, + "is-arguments": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.0.4.tgz", + "integrity": "sha512-xPh0Rmt8NE65sNzvyUmWgI1tz3mKq74lGA0mL8LYZcoIzKOzDh6HmrYm3d18k60nHerC8A9Km8kYu87zfSFnLA==", + "dev": true + }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", + "dev": true + }, "is-binary-path": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-1.0.1.tgz", @@ -1238,6 +2513,21 @@ "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==" }, + "is-callable": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.5.tgz", + "integrity": "sha512-ESKv5sMCJB2jnHTWZ3O5itG+O128Hsus4K4Qh1h2/cgn2vbgnLSVqfV46AeJA9D5EeeLa9w81KUXMtn34zhX+Q==", + "dev": true + }, + "is-ci": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz", + "integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==", + "dev": true, + "requires": { + "ci-info": "^2.0.0" + } + }, "is-data-descriptor": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", @@ -1256,6 +2546,12 @@ } } }, + "is-date-object": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.2.tgz", + "integrity": "sha512-USlDT524woQ08aoZFzh3/Z6ch9Y/EWXEHQ/AaRN0SkKq4t2Jw2R2339tSXmwuVoY7LLlBCbOIlx2myP/L5zk0g==", + "dev": true + }, "is-descriptor": { "version": "0.1.6", "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", @@ -1273,6 +2569,12 @@ } } }, + "is-error": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/is-error/-/is-error-2.2.2.tgz", + "integrity": "sha512-IOQqts/aHWbiisY5DuPJQ0gcbvaLFCa7fBa9xoLfxBZvQ+ZI/Zh9xoI7Gk+G64N0FdK4AbibytHht2tWgpJWLg==", + "dev": true + }, "is-extendable": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", @@ -1283,14 +2585,47 @@ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=" }, + "is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "dev": true + }, "is-glob": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.0.tgz", - "integrity": "sha1-lSHHaEXMJhCoUgPd8ICpWML/q8A=", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", + "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", "requires": { "is-extglob": "^2.1.1" } }, + "is-installed-globally": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-installed-globally/-/is-installed-globally-0.1.0.tgz", + "integrity": "sha1-Df2Y9akRFxbdU13aZJL2e/PSWoA=", + "dev": true, + "requires": { + "global-dirs": "^0.1.0", + "is-path-inside": "^1.0.0" + }, + "dependencies": { + "is-path-inside": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-1.0.1.tgz", + "integrity": "sha1-jvW33lBDej/cprToZe96pVy0gDY=", + "dev": true, + "requires": { + "path-is-inside": "^1.0.1" + } + } + } + }, + "is-npm": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-npm/-/is-npm-1.0.0.tgz", + "integrity": "sha1-8vtjpl5JBbQGyGBydloaTceTufQ=", + "dev": true + }, "is-number": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", @@ -1309,6 +2644,51 @@ } } }, + "is-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", + "integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=", + "dev": true + }, + "is-observable": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-observable/-/is-observable-1.1.0.tgz", + "integrity": "sha512-NqCa4Sa2d+u7BWc6CukaObG3Fh+CU9bvixbpcXYhy2VvYS7vVGIdAgnIS5Ks3A/cqk4rebLJ9s8zBstT2aKnIA==", + "dev": true, + "requires": { + "symbol-observable": "^1.1.0" + } + }, + "is-path-cwd": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-2.2.0.tgz", + "integrity": "sha512-w942bTcih8fdJPJmQHFzkS76NEP8Kzzvmw92cXsazb8intwLqPibPPdXf4ANdKV3rYMuuQYGIWtvz9JilB3NFQ==", + "dev": true + }, + "is-path-in-cwd": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-path-in-cwd/-/is-path-in-cwd-2.1.0.tgz", + "integrity": "sha512-rNocXHgipO+rvnP6dk3zI20RpOtrAM/kzbB258Uw5BWr3TpXi861yzjo16Dn4hUox07iw5AyeMLHWsujkjzvRQ==", + "dev": true, + "requires": { + "is-path-inside": "^2.1.0" + } + }, + "is-path-inside": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-2.1.0.tgz", + "integrity": "sha512-wiyhTzfDWsvwAW53OBWF5zuvaOGlZ6PwYxAbPVDhpm+gM09xKQGjBq/8uYN12aDvMxnAnq3dxTyoSoRNmg5YFg==", + "dev": true, + "requires": { + "path-is-inside": "^1.0.2" + } + }, + "is-plain-obj": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-1.1.0.tgz", + "integrity": "sha1-caUMhCnfync8kqOQpKA7OfzVHT4=", + "dev": true + }, "is-plain-object": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", @@ -1317,6 +2697,60 @@ "isobject": "^3.0.1" } }, + "is-promise": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", + "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=", + "dev": true + }, + "is-redirect": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-redirect/-/is-redirect-1.0.0.tgz", + "integrity": "sha1-HQPd7VO9jbDzDCbk+V02/HyH3CQ=", + "dev": true + }, + "is-regex": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.5.tgz", + "integrity": "sha512-vlKW17SNq44owv5AQR3Cq0bQPEb8+kF3UKZ2fiZNOWtztYE5i0CzCZxFDwO58qAOWtxdBRVO/V5Qin1wjCqFYQ==", + "dev": true, + "requires": { + "has": "^1.0.3" + } + }, + "is-retry-allowed": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-1.2.0.tgz", + "integrity": "sha512-RUbUeKwvm3XG2VYamhJL1xFktgjvPzL0Hq8C+6yrWIswDy3BIXGqCxhxkc30N9jqK311gVU137K8Ei55/zVJRg==", + "dev": true + }, + "is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", + "dev": true + }, + "is-symbol": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.3.tgz", + "integrity": "sha512-OwijhaRSgqvhm/0ZdAcXNZt9lYdKFpcRDT5ULUuYXPoT794UNOdU+gpT6Rzo7b4V2HUl/op6GqY894AZwv9faQ==", + "dev": true, + "requires": { + "has-symbols": "^1.0.1" + } + }, + "is-url": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/is-url/-/is-url-1.2.4.tgz", + "integrity": "sha512-ITvGim8FhRiYe4IQ5uHSkj7pVaPDrCTkNd3yq3cV7iZAcJdHTUMPMEHcqSOy9xZ9qFenQCvi+2wjH9a1nXqHww==", + "dev": true + }, + "is-utf8": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", + "integrity": "sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=", + "dev": true + }, "is-windows": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", @@ -1327,27 +2761,55 @@ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", + "dev": true + }, "isobject": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=" }, + "js-string-escape": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/js-string-escape/-/js-string-escape-1.0.1.tgz", + "integrity": "sha1-4mJbrbwNZ8dTPp7cEGjFh65BN+8=", + "dev": true + }, "js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" }, + "js-yaml": { + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, "jsesc": { "version": "2.5.2", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==" }, + "json-parse-better-errors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", + "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "dev": true + }, "json5": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.0.tgz", - "integrity": "sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.3.tgz", + "integrity": "sha512-KXPvOm8K9IJKFM0bmdn8QXh7udDh1g/giieX0NLCaMnb4hEiVFqnop2ImTXCc5e0/oHz3LTqmHGtExn5hfMkOA==", "requires": { - "minimist": "^1.2.0" + "minimist": "^1.2.5" } }, "jsonfile": { @@ -1359,25 +2821,164 @@ } }, "kind-of": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", - "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==" + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==" + }, + "latest-version": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/latest-version/-/latest-version-3.1.0.tgz", + "integrity": "sha1-ogU4P+oyKzO1rjsYq+4NwvNW7hU=", + "dev": true, + "requires": { + "package-json": "^4.0.0" + } + }, + "load-json-file": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", + "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "parse-json": "^4.0.0", + "pify": "^3.0.0", + "strip-bom": "^3.0.0" + }, + "dependencies": { + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "dev": true + } + } + }, + "locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "dev": true, + "requires": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + } }, "lodash": { - "version": "4.17.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==" + }, + "lodash.clone": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.clone/-/lodash.clone-4.5.0.tgz", + "integrity": "sha1-GVhwRQ9aExkkeN9Lw9I9LeoZB7Y=", + "dev": true + }, + "lodash.clonedeep": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", + "integrity": "sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=", + "dev": true + }, + "lodash.clonedeepwith": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.clonedeepwith/-/lodash.clonedeepwith-4.5.0.tgz", + "integrity": "sha1-buMFc6A6GmDWcKYu8zwQzxr9vdQ=", + "dev": true }, "lodash.debounce": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", - "integrity": "sha1-gteb/zCmfEAF/9XiUVMArZyk168=" + "integrity": "sha1-gteb/zCmfEAF/9XiUVMArZyk168=", + "dev": true + }, + "lodash.difference": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.difference/-/lodash.difference-4.5.0.tgz", + "integrity": "sha1-nMtOUF1Ia5FlE0V3KIWi3yf9AXw=", + "dev": true + }, + "lodash.flatten": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz", + "integrity": "sha1-8xwiIlqWMtK7+OSt2+8kCqdlph8=", + "dev": true + }, + "lodash.flattendeep": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/lodash.flattendeep/-/lodash.flattendeep-4.4.0.tgz", + "integrity": "sha1-+wMJF/hqMTTlvJvsDWngAT3f7bI=", + "dev": true + }, + "lodash.islength": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.islength/-/lodash.islength-4.0.1.tgz", + "integrity": "sha1-Tpho1FJXXXUK/9NYyXlUPcIO1Xc=", + "dev": true + }, + "lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true + }, + "log-symbols": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-2.2.0.tgz", + "integrity": "sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg==", + "dev": true, + "requires": { + "chalk": "^2.0.1" + } + }, + "loud-rejection": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/loud-rejection/-/loud-rejection-1.6.0.tgz", + "integrity": "sha1-W0b4AUft7leIcPCG0Eghz5mOVR8=", + "dev": true, + "requires": { + "currently-unhandled": "^0.4.1", + "signal-exit": "^3.0.0" + } + }, + "lowercase-keys": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.1.tgz", + "integrity": "sha512-G2Lj61tXDnVFFOi8VZds+SoQjtQC3dgokKdDG2mTm1tx4m50NUHBOZSBwQQHyy0V12A0JTG4icfZQH+xPyh8VA==", + "dev": true + }, + "lru-cache": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", + "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", + "dev": true, + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "dev": true, + "requires": { + "pify": "^4.0.1", + "semver": "^5.6.0" + } }, "map-cache": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=" }, + "map-obj": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-2.0.0.tgz", + "integrity": "sha1-plzSkIepJZi4eRJXpSPgISIqwfk=", + "dev": true + }, "map-visit": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", @@ -1386,6 +2987,47 @@ "object-visit": "^1.0.0" } }, + "matcher": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/matcher/-/matcher-1.1.1.tgz", + "integrity": "sha512-+BmqxWIubKTRKNWx/ahnCkk3mG8m7OturVlqq6HiojGJTd5hVYbgZm6WzcYPCoB+KBT4Vd6R7WSRG2OADNaCjg==", + "dev": true, + "requires": { + "escape-string-regexp": "^1.0.4" + } + }, + "md5-hex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/md5-hex/-/md5-hex-2.0.0.tgz", + "integrity": "sha1-0FiOnxx0lUSS7NJKwKxs6ZfZLjM=", + "dev": true, + "requires": { + "md5-o-matic": "^0.1.1" + } + }, + "md5-o-matic": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/md5-o-matic/-/md5-o-matic-0.1.1.tgz", + "integrity": "sha1-givM1l4RfFFPqxdrJZRdVBAKA8M=", + "dev": true + }, + "meow": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/meow/-/meow-5.0.0.tgz", + "integrity": "sha512-CbTqYU17ABaLefO8vCU153ZZlprKYWDljcndKKDCFcYQITzWCXZAVk4QMFZPgvzrnUQ3uItnIE/LoUOwrT15Ig==", + "dev": true, + "requires": { + "camelcase-keys": "^4.0.0", + "decamelize-keys": "^1.0.0", + "loud-rejection": "^1.0.0", + "minimist-options": "^3.0.1", + "normalize-package-data": "^2.3.4", + "read-pkg-up": "^3.0.0", + "redent": "^2.0.0", + "trim-newlines": "^2.0.0", + "yargs-parser": "^10.0.0" + } + }, "micromatch": { "version": "3.1.10", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", @@ -1406,15 +3048,40 @@ "to-regex": "^3.0.2" } }, + "mimic-fn": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", + "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==", + "dev": true + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, "minimist": { - "version": "1.2.0", - "resolved": "http://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=" + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" + }, + "minimist-options": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/minimist-options/-/minimist-options-3.0.2.tgz", + "integrity": "sha512-FyBrT/d0d4+uiZRbqznPXqw3IpZZG3gl3wKWiX784FycUKVwBt0uLBFkQrtE4tZOrgo78nZp2jnKz3L65T5LdQ==", + "dev": true, + "requires": { + "arrify": "^1.0.1", + "is-plain-obj": "^1.1.0" + } }, "mixin-deep": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.1.tgz", - "integrity": "sha512-8ZItLHeEgaqEvd5lYBXfm4EZSFCX29Jb9K+lAHhDKzReKBQKj3R+7NOF6tjqYi9t4oI8VUfaWITJQm86wnXGNQ==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.2.tgz", + "integrity": "sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA==", "requires": { "for-in": "^1.0.2", "is-extendable": "^1.0.1" @@ -1430,15 +3097,36 @@ } } }, + "mkdirp": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", + "dev": true, + "requires": { + "minimist": "^1.2.5" + } + }, "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "multimatch": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/multimatch/-/multimatch-3.0.0.tgz", + "integrity": "sha512-22foS/gqQfANZ3o+W7ST2x25ueHDVNWl/b9OlGcLpy/iKxjCpvcNCM51YCenUi7Mt/jAjjqv8JwZRs8YP5sRjA==", + "dev": true, + "requires": { + "array-differ": "^2.0.3", + "array-union": "^1.0.2", + "arrify": "^1.0.1", + "minimatch": "^3.0.4" + } }, "nan": { - "version": "2.11.1", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.11.1.tgz", - "integrity": "sha512-iji6k87OSXa0CcrLl9z+ZiYSuR2o+c0bGuNmXdrhTQTakxytAFsC56SArGYoiHlJlFoHSnvmhpceZJaXkVuOtA==", + "version": "2.14.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.0.tgz", + "integrity": "sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg==", "optional": true }, "nanomatch": { @@ -1459,14 +3147,38 @@ "to-regex": "^3.0.1" } }, + "normalize-package-data": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", + "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", + "dev": true, + "requires": { + "hosted-git-info": "^2.1.4", + "resolve": "^1.10.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, "normalize-path": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", - "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==" + }, + "npm-run-path": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", + "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", + "dev": true, "requires": { - "remove-trailing-separator": "^1.0.1" + "path-key": "^2.0.0" } }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "dev": true + }, "object-copy": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz", @@ -1495,6 +3207,23 @@ } } }, + "object-inspect": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.7.0.tgz", + "integrity": "sha512-a7pEHdh1xKIAgTySUGgLMx/xwDZskN1Ud6egYYN3EdRW4ZMPNEDUTF+hwy2LUC+Bl+SyLXANnwz/jyh/qutKUw==", + "dev": true + }, + "object-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.0.2.tgz", + "integrity": "sha512-Epah+btZd5wrrfjkJZq1AOB9O6OxUQto45hzFd7lXGrpHPGE0W1k+426yrZV+k6NJOzLNNW/nVsmZdIWsAqoOQ==", + "dev": true + }, + "object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==" + }, "object-visit": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", @@ -1503,6 +3232,17 @@ "isobject": "^3.0.0" } }, + "object.assign": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.0.tgz", + "integrity": "sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w==", + "requires": { + "define-properties": "^1.1.2", + "function-bind": "^1.1.1", + "has-symbols": "^1.0.0", + "object-keys": "^1.0.11" + } + }, "object.pick": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", @@ -1511,6 +3251,149 @@ "isobject": "^3.0.1" } }, + "observable-to-promise": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/observable-to-promise/-/observable-to-promise-0.5.0.tgz", + "integrity": "sha1-yCjw8NxH6fhq+KSXfF1VB2znqR8=", + "dev": true, + "requires": { + "is-observable": "^0.2.0", + "symbol-observable": "^1.0.4" + }, + "dependencies": { + "is-observable": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/is-observable/-/is-observable-0.2.0.tgz", + "integrity": "sha1-s2ExHYPG5dcmyr9eJQsCNxBvWuI=", + "dev": true, + "requires": { + "symbol-observable": "^0.2.2" + }, + "dependencies": { + "symbol-observable": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-0.2.4.tgz", + "integrity": "sha1-lag9smGG1q9+ehjb2XYKL4bQj0A=", + "dev": true + } + } + } + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "onetime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", + "integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=", + "dev": true, + "requires": { + "mimic-fn": "^1.0.0" + } + }, + "ora": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/ora/-/ora-3.4.0.tgz", + "integrity": "sha512-eNwHudNbO1folBP3JsZ19v9azXWtQZjICdr3Q0TDPIaeBQ3mXLrh54wM+er0+hSp+dWKf+Z8KM58CYzEyIYxYg==", + "dev": true, + "requires": { + "chalk": "^2.4.2", + "cli-cursor": "^2.1.0", + "cli-spinners": "^2.0.0", + "log-symbols": "^2.2.0", + "strip-ansi": "^5.2.0", + "wcwidth": "^1.0.1" + } + }, + "os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", + "dev": true + }, + "p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=", + "dev": true + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "dev": true, + "requires": { + "p-limit": "^2.0.0" + } + }, + "p-map": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-2.1.0.tgz", + "integrity": "sha512-y3b8Kpd8OAN444hxfBbFfj1FY/RjtTd8tzYwhUqNYXx0fXx2iX4maP4Qr6qhIKbQXI02wTLAda4fYUbDagTUFw==", + "dev": true + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true + }, + "package-hash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/package-hash/-/package-hash-3.0.0.tgz", + "integrity": "sha512-lOtmukMDVvtkL84rJHI7dpTYq+0rli8N2wlnqUcBuDWCfVhRUfOmnR9SsoHFMLpACvEV60dX7rd0rFaYDZI+FA==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.15", + "hasha": "^3.0.0", + "lodash.flattendeep": "^4.4.0", + "release-zalgo": "^1.0.0" + } + }, + "package-json": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/package-json/-/package-json-4.0.1.tgz", + "integrity": "sha1-iGmgQBJTZhxMTKPabCEh7VVfXu0=", + "dev": true, + "requires": { + "got": "^6.7.1", + "registry-auth-token": "^3.0.1", + "registry-url": "^3.0.3", + "semver": "^5.1.0" + } + }, + "parse-json": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", + "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", + "dev": true, + "requires": { + "error-ex": "^1.3.1", + "json-parse-better-errors": "^1.0.1" + } + }, + "parse-ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-2.1.0.tgz", + "integrity": "sha512-kHt7kzLoS9VBZfUsiKjv43mr91ea+U05EyKkEtqp7vNbHxmaVuEqN7XxeEVnGrMtYOAxGrDElSi96K7EgO1zCA==", + "dev": true + }, "pascalcase": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", @@ -1521,30 +3404,234 @@ "resolved": "https://registry.npmjs.org/path-dirname/-/path-dirname-1.0.2.tgz", "integrity": "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=" }, + "path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", + "dev": true + }, "path-is-absolute": { "version": "1.0.1", - "resolved": "http://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" }, + "path-is-inside": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz", + "integrity": "sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM=", + "dev": true + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", + "dev": true + }, "path-parse": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==" }, + "path-type": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", + "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", + "dev": true, + "requires": { + "pify": "^3.0.0" + }, + "dependencies": { + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "dev": true + } + } + }, + "pify": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "dev": true + }, + "pinkie": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", + "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", + "dev": true + }, + "pinkie-promise": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", + "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", + "dev": true, + "requires": { + "pinkie": "^2.0.0" + } + }, + "pkg-conf": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/pkg-conf/-/pkg-conf-3.1.0.tgz", + "integrity": "sha512-m0OTbR/5VPNPqO1ph6Fqbj7Hv6QU7gR/tQW40ZqrL1rjgCU85W6C1bJn0BItuJqnR98PWzw7Z8hHeChD1WrgdQ==", + "dev": true, + "requires": { + "find-up": "^3.0.0", + "load-json-file": "^5.2.0" + }, + "dependencies": { + "load-json-file": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-5.3.0.tgz", + "integrity": "sha512-cJGP40Jc/VXUsp8/OrnyKyTZ1y6v/dphm3bioS+RrKXjK2BB6wHUd6JptZEFDGgGahMT+InnZO5i1Ei9mpC8Bw==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.15", + "parse-json": "^4.0.0", + "pify": "^4.0.1", + "strip-bom": "^3.0.0", + "type-fest": "^0.3.0" + } + } + } + }, + "pkg-dir": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", + "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", + "dev": true, + "requires": { + "find-up": "^3.0.0" + } + }, + "plur": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/plur/-/plur-3.1.1.tgz", + "integrity": "sha512-t1Ax8KUvV3FFII8ltczPn2tJdjqbd1sIzu6t4JL7nQ3EyeL/lTrj5PWKb06ic5/6XYDr65rQ4uzQEGN70/6X5w==", + "dev": true, + "requires": { + "irregular-plurals": "^2.0.0" + } + }, "posix-character-classes": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=" }, + "prepend-http": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", + "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=", + "dev": true + }, + "pretty-ms": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-4.0.0.tgz", + "integrity": "sha512-qG66ahoLCwpLXD09ZPHSCbUWYTqdosB7SMP4OffgTgL2PBKXMuUsrk5Bwg8q4qPkjTXsKBMr+YK3Ltd/6F9s/Q==", + "dev": true, + "requires": { + "parse-ms": "^2.0.0" + } + }, "process-nextick-args": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", - "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==" + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" + }, + "pseudomap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", + "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=", + "dev": true + }, + "quick-lru": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-1.1.0.tgz", + "integrity": "sha1-Q2CxfGETatOAeDl/8RQW4Ybc+7g=", + "dev": true + }, + "rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "dev": true, + "requires": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + } + }, + "read-pkg": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", + "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", + "dev": true, + "requires": { + "load-json-file": "^4.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^3.0.0" + } + }, + "read-pkg-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-3.0.0.tgz", + "integrity": "sha1-PtSWaF26D4/hGNBpHcUfSh/5bwc=", + "dev": true, + "requires": { + "find-up": "^2.0.0", + "read-pkg": "^3.0.0" + }, + "dependencies": { + "find-up": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", + "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", + "dev": true, + "requires": { + "locate-path": "^2.0.0" + } + }, + "locate-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", + "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", + "dev": true, + "requires": { + "p-locate": "^2.0.0", + "path-exists": "^3.0.0" + } + }, + "p-limit": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", + "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", + "dev": true, + "requires": { + "p-try": "^1.0.0" + } + }, + "p-locate": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", + "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", + "dev": true, + "requires": { + "p-limit": "^1.1.0" + } + }, + "p-try": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", + "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", + "dev": true + } + } }, "readable-stream": { - "version": "2.3.6", - "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", - "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", "requires": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", @@ -1565,6 +3652,40 @@ "readable-stream": "^2.0.2" } }, + "rechoir": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz", + "integrity": "sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q=", + "dev": true, + "requires": { + "resolve": "^1.1.6" + } + }, + "redent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-2.0.0.tgz", + "integrity": "sha1-wbIAe0LVfrE4kHmzyDM2OdXhzKo=", + "dev": true, + "requires": { + "indent-string": "^3.0.0", + "strip-indent": "^2.0.0" + } + }, + "regenerate": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.0.tgz", + "integrity": "sha512-1G6jJVDWrt0rK99kBjvEtziZNCICAuvIPkSiUFIQxVP06RCVpq3dmDo2oi6ABpYaDYaTRr67BEhL8r1wgEZZKg==", + "dev": true + }, + "regenerate-unicode-properties": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-8.2.0.tgz", + "integrity": "sha512-F9DjY1vKLo/tPePDycuH3dn9H1OTPIkVD9Kz4LODu+F2C75mgjAJ7x/gwy6ZcSNRAAkhNlJSOHRe8k3p+K9WhA==", + "dev": true, + "requires": { + "regenerate": "^1.4.0" + } + }, "regex-not": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz", @@ -1574,6 +3695,81 @@ "safe-regex": "^1.1.0" } }, + "regexp.prototype.flags": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.3.0.tgz", + "integrity": "sha512-2+Q0C5g951OlYlJz6yu5/M33IcsESLlLfsyIaLJaG4FA2r4yP8MvVMJUUP/fVBkSpbbbZlS5gynbEWLipiiXiQ==", + "dev": true, + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.0-next.1" + } + }, + "regexpu-core": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-4.7.0.tgz", + "integrity": "sha512-TQ4KXRnIn6tz6tjnrXEkD/sshygKH/j5KzK86X8MkeHyZ8qst/LZ89j3X4/8HEIfHANTFIP/AbXakeRhWIl5YQ==", + "dev": true, + "requires": { + "regenerate": "^1.4.0", + "regenerate-unicode-properties": "^8.2.0", + "regjsgen": "^0.5.1", + "regjsparser": "^0.6.4", + "unicode-match-property-ecmascript": "^1.0.4", + "unicode-match-property-value-ecmascript": "^1.2.0" + } + }, + "registry-auth-token": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", + "dev": true, + "requires": { + "rc": "^1.1.6", + "safe-buffer": "^5.0.1" + } + }, + "registry-url": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/registry-url/-/registry-url-3.1.0.tgz", + "integrity": "sha1-PU74cPc93h138M+aOBQyRE4XSUI=", + "dev": true, + "requires": { + "rc": "^1.0.1" + } + }, + "regjsgen": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/regjsgen/-/regjsgen-0.5.1.tgz", + "integrity": "sha512-5qxzGZjDs9w4tzT3TPhCJqWdCc3RLYwy9J2NB0nm5Lz+S273lvWcpjaTGHsT1dc6Hhfq41uSEOw8wBmxrKOuyg==", + "dev": true + }, + "regjsparser": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.6.4.tgz", + "integrity": "sha512-64O87/dPDgfk8/RQqC4gkZoGyyWFIEUTTh80CU6CWuK5vkCGyekIx+oKcEIYtP/RAxSQltCZHCNu/mdd7fqlJw==", + "dev": true, + "requires": { + "jsesc": "~0.5.0" + }, + "dependencies": { + "jsesc": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", + "integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=", + "dev": true + } + } + }, + "release-zalgo": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/release-zalgo/-/release-zalgo-1.0.0.tgz", + "integrity": "sha1-CXALflB0Mpc5Mw5TXFqQ+2eFFzA=", + "dev": true, + "requires": { + "es6-error": "^4.0.1" + } + }, "remove-trailing-separator": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", @@ -1589,24 +3785,64 @@ "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=" }, + "require-precompiled": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/require-precompiled/-/require-precompiled-0.1.0.tgz", + "integrity": "sha1-WhtS63Dr7UPrmC6XTIWrWVceVvo=", + "dev": true + }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.15.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.15.1.tgz", + "integrity": "sha512-84oo6ZTtoTUpjgNEr5SJyzQhzL72gaRodsSfyxC/AXRvwu0Yse9H8eF9IpGo7b8YetZhlI6v7ZQ6bKBFV/6S7w==", + "requires": { + "path-parse": "^1.0.6" + } + }, + "resolve-cwd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-2.0.0.tgz", + "integrity": "sha1-AKn3OHVW4nA46uIyyqNypqWbZlo=", + "dev": true, "requires": { - "path-parse": "^1.0.5" + "resolve-from": "^3.0.0" } }, + "resolve-from": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-3.0.0.tgz", + "integrity": "sha1-six699nWiBvItuZTM17rywoYh0g=", + "dev": true + }, "resolve-url": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=" }, + "restore-cursor": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", + "integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=", + "dev": true, + "requires": { + "onetime": "^2.0.0", + "signal-exit": "^3.0.2" + } + }, "ret": { "version": "0.1.15", "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==" }, + "rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, "safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", @@ -1614,21 +3850,36 @@ }, "safe-regex": { "version": "1.1.0", - "resolved": "http://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", + "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", "requires": { "ret": "~0.1.10" } }, "semver": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.6.0.tgz", - "integrity": "sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==" + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" + }, + "semver-diff": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/semver-diff/-/semver-diff-2.1.0.tgz", + "integrity": "sha1-S7uEN8jTfksM8aaP1ybsbWRdbTY=", + "dev": true, + "requires": { + "semver": "^5.0.3" + } + }, + "serialize-error": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-2.1.0.tgz", + "integrity": "sha1-ULZ51WNc34Rme9yOWa9OW4HV9go=", + "dev": true }, "set-value": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.0.tgz", - "integrity": "sha512-hw0yxk9GT/Hr5yJEYnHNKYXkIA8mVJgd9ditYZCe16ZczcaELYYcfvaXesNACk2O8O0nTiPQcQhGUQj8JLzeeg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.1.tgz", + "integrity": "sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw==", "requires": { "extend-shallow": "^2.0.1", "is-extendable": "^0.1.1", @@ -1646,6 +3897,59 @@ } } }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "dev": true, + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", + "dev": true + }, + "shelljs": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.8.3.tgz", + "integrity": "sha512-fc0BKlAWiLpwZljmOvAOTE/gXawtCoNrP5oaY7KIaQbbyHeQVg01pSEuEGvGh3HEdBU4baCD7wQBwADmM/7f7A==", + "dev": true, + "requires": { + "glob": "^7.0.0", + "interpret": "^1.0.0", + "rechoir": "^0.6.2" + } + }, + "signal-exit": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", + "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==", + "dev": true + }, + "slash": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", + "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", + "dev": true + }, + "slice-ansi": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-1.0.0.tgz", + "integrity": "sha512-POqxBK6Lb3q6s047D/XsDVNPnF9Dl8JSaqe9h9lURl0OdNqy/ujDrOiIHtsqXMGbWWTIomRzAMaTyawAU//Reg==", + "dev": true, + "requires": { + "is-fullwidth-code-point": "^2.0.0" + } + }, + "slide": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/slide/-/slide-1.1.6.tgz", + "integrity": "sha1-VusCfWW00tzmyy4tMsTUr8nh1wc=", + "dev": true + }, "snapdragon": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", @@ -1762,22 +4066,72 @@ "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" }, "source-map-resolve": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.2.tgz", - "integrity": "sha512-MjqsvNwyz1s0k81Goz/9vRBe9SZdB09Bdw+/zYyO+3CuPk6fouTaxscHkgtE8jKvf01kVfl8riHzERQ/kefaSA==", + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.3.tgz", + "integrity": "sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw==", "requires": { - "atob": "^2.1.1", + "atob": "^2.1.2", "decode-uri-component": "^0.2.0", "resolve-url": "^0.2.1", "source-map-url": "^0.4.0", "urix": "^0.1.0" } }, + "source-map-support": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.16.tgz", + "integrity": "sha512-efyLRJDr68D9hBBNIPWFjhpFzURh+KJykQwvMyW5UiZzYwoF6l4YMMDIJJEyFWxWCqfyxLzz6tSfUFR+kXXsVQ==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, "source-map-url": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz", "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=" }, + "spdx-correct": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.0.tgz", + "integrity": "sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q==", + "dev": true, + "requires": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-exceptions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz", + "integrity": "sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA==", + "dev": true + }, + "spdx-expression-parse": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz", + "integrity": "sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg==", + "dev": true, + "requires": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-license-ids": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.5.tgz", + "integrity": "sha512-J+FWzZoynJEXGphVIS+XEh3kFSjZX/1i9gFBaWQcB+/tmpe2qUsSBABpcxqxnAxFdiUFEgAX1bjYGQvIZmoz9Q==", + "dev": true + }, "split-string": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", @@ -1786,6 +4140,18 @@ "extend-shallow": "^3.0.0" } }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", + "dev": true + }, + "stack-utils": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-1.0.2.tgz", + "integrity": "sha512-MTX+MeG5U994cazkjd/9KNAapsHnibjMLnfXodlkXw76JEea0UiNzrqidzo1emMwk7w5Qhc9jd4Bn9TBb1MFwA==", + "dev": true + }, "static-extend": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", @@ -1805,6 +4171,69 @@ } } }, + "string-width": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "dev": true, + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + }, + "dependencies": { + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "dev": true, + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "string.prototype.trimend": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.1.tgz", + "integrity": "sha512-LRPxFUaTtpqYsTeNKaFOw3R4bxIzWOnbQ837QfBylo8jIxtcbK/A/sMV7Q+OAV/vWo+7s25pOE10KYSjaSO06g==", + "dev": true, + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5" + } + }, + "string.prototype.trimleft": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/string.prototype.trimleft/-/string.prototype.trimleft-2.1.2.tgz", + "integrity": "sha512-gCA0tza1JBvqr3bfAIFJGqfdRTyPae82+KTnm3coDXkZN9wnuW3HjGgN386D7hfv5CHQYCI022/rJPVlqXyHSw==", + "dev": true, + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5", + "string.prototype.trimstart": "^1.0.0" + } + }, + "string.prototype.trimright": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/string.prototype.trimright/-/string.prototype.trimright-2.1.2.tgz", + "integrity": "sha512-ZNRQ7sY3KroTaYjRS6EbNiiHrOkjihL9aQE/8gfQ4DtAC/aEBRHFJa44OmoWxGGqXuJlfKkZW4WcXErGr+9ZFg==", + "dev": true, + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5", + "string.prototype.trimend": "^1.0.0" + } + }, + "string.prototype.trimstart": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.1.tgz", + "integrity": "sha512-XxZn+QpvrBI1FOcg6dIpxUPgWCPuNXvMD72aaRaUQv1eD4e/Qy8i/hFTe0BUmD60p/QA6bh1avmuPTfNjqVWRw==", + "dev": true, + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5" + } + }, "string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", @@ -1813,6 +4242,80 @@ "safe-buffer": "~5.1.0" } }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "requires": { + "ansi-regex": "^4.1.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true + } + } + }, + "strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", + "dev": true + }, + "strip-bom-buf": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-bom-buf/-/strip-bom-buf-1.0.0.tgz", + "integrity": "sha1-HLRar1dTD0yvhsf3UXnSyaUd1XI=", + "dev": true, + "requires": { + "is-utf8": "^0.2.1" + } + }, + "strip-eof": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", + "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=", + "dev": true + }, + "strip-indent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-2.0.0.tgz", + "integrity": "sha1-XvjbKV0B5u1sv3qrlpmNeCJSe2g=", + "dev": true + }, + "strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", + "dev": true + }, + "supertap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supertap/-/supertap-1.0.0.tgz", + "integrity": "sha512-HZJ3geIMPgVwKk2VsmO5YHqnnJYl6bV5A9JW2uzqV43WmpgliNEYbuvukfor7URpaqpxuw3CfZ3ONdVbZjCgIA==", + "dev": true, + "requires": { + "arrify": "^1.0.1", + "indent-string": "^3.2.0", + "js-yaml": "^3.10.0", + "serialize-error": "^2.1.0", + "strip-ansi": "^4.0.0" + }, + "dependencies": { + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "dev": true, + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, "supports-color": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", @@ -1821,6 +4324,33 @@ "has-flag": "^3.0.0" } }, + "symbol-observable": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-1.2.0.tgz", + "integrity": "sha512-e900nM8RRtGhlV36KGEU9k65K3mPb1WV70OdjfxlG2EAuM1noi/E/BaW/uMhL7bPEssK8QV57vN3esixjUvcXQ==", + "dev": true + }, + "term-size": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/term-size/-/term-size-1.2.0.tgz", + "integrity": "sha1-RYuDiH8oj8Vtb/+/rSYuJmOO+mk=", + "dev": true, + "requires": { + "execa": "^0.7.0" + } + }, + "time-zone": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/time-zone/-/time-zone-1.0.0.tgz", + "integrity": "sha1-mcW/VZWJZq9tBtg73zgA3IL67F0=", + "dev": true + }, + "timed-out": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/timed-out/-/timed-out-4.0.1.tgz", + "integrity": "sha1-8y6srFoXW+ol1/q1Zas+2HQe9W8=", + "dev": true + }, "to-fast-properties": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", @@ -1864,41 +4394,93 @@ "repeat-string": "^1.6.1" } }, + "trim-newlines": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-2.0.0.tgz", + "integrity": "sha1-tAPQuRvlDDMd/EuC7s6yLD3hbSA=", + "dev": true + }, + "trim-off-newlines": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-off-newlines/-/trim-off-newlines-1.0.1.tgz", + "integrity": "sha1-n5up2e+odkw4dpi8v+sshI8RrbM=", + "dev": true + }, "trim-right": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", - "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=" + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=", + "dev": true + }, + "type-fest": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.3.1.tgz", + "integrity": "sha512-cUGJnCdr4STbePCgqNFbpVNCepa+kAVohJs1sLhxzdH+gnEoOd8VhbYa7pD3zZYGiURWM2xzEII3fQcRizDkYQ==", + "dev": true + }, + "uid2": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/uid2/-/uid2-0.0.3.tgz", + "integrity": "sha1-SDEm4Rd03y9xuLY53NeZw3YWK4I=", + "dev": true + }, + "unicode-canonical-property-names-ecmascript": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-1.0.4.tgz", + "integrity": "sha512-jDrNnXWHd4oHiTZnx/ZG7gtUTVp+gCcTTKr8L0HjlwphROEW3+Him+IpvC+xcJEFegapiMZyZe02CyuOnRmbnQ==", + "dev": true + }, + "unicode-match-property-ecmascript": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/unicode-match-property-ecmascript/-/unicode-match-property-ecmascript-1.0.4.tgz", + "integrity": "sha512-L4Qoh15vTfntsn4P1zqnHulG0LdXgjSO035fEpdtp6YxXhMT51Q6vgM5lYdG/5X3MjS+k/Y9Xw4SFCY9IkR0rg==", + "dev": true, + "requires": { + "unicode-canonical-property-names-ecmascript": "^1.0.4", + "unicode-property-aliases-ecmascript": "^1.0.4" + } + }, + "unicode-match-property-value-ecmascript": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-1.2.0.tgz", + "integrity": "sha512-wjuQHGQVofmSJv1uVISKLE5zO2rNGzM/KCYZch/QQvez7C1hUhBIuZ701fYXExuufJFMPhv2SyL8CyoIfMLbIQ==", + "dev": true + }, + "unicode-property-aliases-ecmascript": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-1.1.0.tgz", + "integrity": "sha512-PqSoPh/pWetQ2phoj5RLiaqIk4kCNwoV3CI+LfGmWLKI3rE3kl1h59XpX2BjgDrmbxD9ARtQobPGU1SguCYuQg==", + "dev": true }, "union-value": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.0.tgz", - "integrity": "sha1-XHHDTLW61dzr4+oM0IIHulqhrqQ=", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.1.tgz", + "integrity": "sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg==", "requires": { "arr-union": "^3.1.0", "get-value": "^2.0.6", "is-extendable": "^0.1.1", - "set-value": "^0.4.3" - }, - "dependencies": { - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "requires": { - "is-extendable": "^0.1.0" - } - }, - "set-value": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/set-value/-/set-value-0.4.3.tgz", - "integrity": "sha1-fbCPnT0i3H945Trzw79GZuzfzPE=", - "requires": { - "extend-shallow": "^2.0.1", - "is-extendable": "^0.1.1", - "is-plain-object": "^2.0.1", - "to-object-path": "^0.3.0" - } - } + "set-value": "^2.0.1" + } + }, + "unique-string": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-1.0.0.tgz", + "integrity": "sha1-nhBXzKhRq7kzmPizOuGHuZyuwRo=", + "dev": true, + "requires": { + "crypto-random-string": "^1.0.0" + } + }, + "unique-temp-dir": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unique-temp-dir/-/unique-temp-dir-1.0.0.tgz", + "integrity": "sha1-bc6VsmgcoAPuv7MEpBX5y6vMU4U=", + "dev": true, + "requires": { + "mkdirp": "^0.5.1", + "os-tmpdir": "^1.0.1", + "uid2": "0.0.3" } }, "universalify": { @@ -1942,16 +4524,66 @@ } } }, + "unzip-response": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/unzip-response/-/unzip-response-2.0.1.tgz", + "integrity": "sha1-0vD3N9FrBhXnKmk17QQhRXLVb5c=", + "dev": true + }, "upath": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/upath/-/upath-1.1.0.tgz", - "integrity": "sha512-bzpH/oBhoS/QI/YtbkqCg6VEiPYjSZtrHQM6/QnJS6OL9pKUFLqb3aFh4Scvwm45+7iAgiMkLhSbaZxUqmrprw==" + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/upath/-/upath-1.2.0.tgz", + "integrity": "sha512-aZwGpamFO61g3OlfT7OQCHqhGnW43ieH9WZeP7QxN/G/jS4jfqUkZxoryvJgVPEcrl5NL/ggHsSmLMHuH64Lhg==" + }, + "update-notifier": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/update-notifier/-/update-notifier-2.5.0.tgz", + "integrity": "sha512-gwMdhgJHGuj/+wHJJs9e6PcCszpxR1b236igrOkUofGhqJuG+amlIKwApH1IW1WWl7ovZxsX49lMBWLxSdm5Dw==", + "dev": true, + "requires": { + "boxen": "^1.2.1", + "chalk": "^2.0.1", + "configstore": "^3.0.0", + "import-lazy": "^2.1.0", + "is-ci": "^1.0.10", + "is-installed-globally": "^0.1.0", + "is-npm": "^1.0.0", + "latest-version": "^3.0.0", + "semver-diff": "^2.0.0", + "xdg-basedir": "^3.0.0" + }, + "dependencies": { + "ci-info": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", + "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==", + "dev": true + }, + "is-ci": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-1.2.1.tgz", + "integrity": "sha512-s6tfsaQaQi3JNciBH6shVqEDvhGut0SUXr31ag8Pd8BBbVVlcGfWhpPmEOoM6RJ5TFhbypvf5yyRw/VXW1IiWg==", + "dev": true, + "requires": { + "ci-info": "^1.5.0" + } + } + } }, "urix": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=" }, + "url-parse-lax": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/url-parse-lax/-/url-parse-lax-1.0.0.tgz", + "integrity": "sha1-evjzA2Rem9eaJy56FKxovAYJ2nM=", + "dev": true, + "requires": { + "prepend-http": "^1.0.1" + } + }, "use": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", @@ -1961,6 +4593,93 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" + }, + "validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "dev": true, + "requires": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "wcwidth": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", + "integrity": "sha1-8LDc+RW8X/FSivrbLA4XtTLaL+g=", + "dev": true, + "requires": { + "defaults": "^1.0.3" + } + }, + "well-known-symbols": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/well-known-symbols/-/well-known-symbols-2.0.0.tgz", + "integrity": "sha512-ZMjC3ho+KXo0BfJb7JgtQ5IBuvnShdlACNkKkdsqBmYw3bPAaJfPeYUo6tLUaT5tG/Gkh7xkpBhKRQ9e7pyg9Q==", + "dev": true + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "widest-line": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-2.0.1.tgz", + "integrity": "sha512-Ba5m9/Fa4Xt9eb2ELXt77JxVDV8w7qQrH0zS/TWSJdLyAwQjWoOzpzj5lwVftDz6n/EOu3tNACS84v509qwnJA==", + "dev": true, + "requires": { + "string-width": "^2.1.1" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "write-file-atomic": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.11", + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.2" + } + }, + "xdg-basedir": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-3.0.0.tgz", + "integrity": "sha1-SWsswQnsqNus/i3HK2A8F8WHCtQ=", + "dev": true + }, + "xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "dev": true + }, + "yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", + "dev": true + }, + "yargs-parser": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-10.1.0.tgz", + "integrity": "sha512-VCIyR1wJoEBZUqk5PA+oOBF6ypbwh5aNB3I50guxAL/quggdfs4TtNHQrSazFA3fYZ+tEqfs0zIGlv0c/rgjbQ==", + "dev": true, + "requires": { + "camelcase": "^4.1.0" + } } } } diff --git a/src/fable-splitter/package.json b/src/fable-splitter/package.json index 8a0602ffd8..f0c0c01d7a 100644 --- a/src/fable-splitter/package.json +++ b/src/fable-splitter/package.json @@ -1,6 +1,6 @@ { "name": "fable-splitter", - "version": "2.1.8", + "version": "2.1.13", "description": "File splitter for Fable (F# to JavaScript compiler)", "author": "ncave", "license": "Apache-2.0", @@ -8,8 +8,8 @@ "bin": { "fable-splitter": "./dist/cli.js" }, - "homepage": "https://github.com/fable-compiler/Fable/tree/master/src/typescript/fable-splitter#readme", - "repository": "https://github.com/fable-compiler/Fable/tree/master/src/typescript/fable-splitter", + "homepage": "https://github.com/fable-compiler/Fable/tree/master/src/fable-splitter#readme", + "repository": "https://github.com/fable-compiler/Fable/blob/master/src/fable-splitter", "keywords": [ "fable", "fsharp", @@ -26,17 +26,20 @@ "test": "node build.js test" }, "peerDependencies": { - "fable-compiler": "^2.1.0" + "fable-compiler": "^2.5.1" }, "dependencies": { - "@babel/core": "^7.1.6", - "@babel/plugin-transform-modules-commonjs": "^7.1.0", + "@babel/core": "^7.9.0", + "@babel/plugin-transform-modules-commonjs": "^7.9.0", + "chalk": "^2.4.1", "chokidar": "^2.0.4", - "fable-babel-plugins": "^2.2.0", - "fs-extra": "^7.0.0", - "chalk": "^2.4.1" + "fable-babel-plugins": "^2.3.0", + "fs-extra": "^7.0.0" }, "devDependencies": { - "@types/fs-extra": "^5.0.4" + "@types/fs-extra": "^5.0.4", + "@types/node": "^13.11.1", + "ava": "^1.4.1", + "shelljs": "^0.8.3" } } diff --git a/src/fable-splitter/src/cli.ts b/src/fable-splitter/src/cli.ts index bdaa6b9ea3..f0b4486f06 100644 --- a/src/fable-splitter/src/cli.ts +++ b/src/fable-splitter/src/cli.ts @@ -2,7 +2,7 @@ import * as fs from "fs"; import * as path from "path"; -import fableSplitter from "./index"; +import fableSplitter, { CompilationInfo } from "./index"; import runScript from "./run"; const chokidarLazy = requireLazy("chokidar"); @@ -53,6 +53,8 @@ Arguments: --commonjs [FLAG] Compile to commonjs modules --run [FLAG] Run script with node after compilation Arguments after --run will be passed to the script + --usePolling [FLAG] Option for watch mode, may help capture file + save events in certain editors (suboptimal) Examples: fable-splitter src/App.fsproj -o dist/ @@ -102,7 +104,7 @@ function objectAssignNonNull(target, source) { return target; } -function concatIfNotExists(ar, item): any[] { +function concatSafe(ar, item): any[] { if (ar == null) { return [item]; } else { @@ -146,6 +148,28 @@ function mustRun(args: string[]): [boolean, string[]] { return i >= 0 ? [true, args.slice(i + 1)] : [false, []]; } +function onCompiled(args: string[], opts: any, info: CompilationInfo, mustFinish = false) { + const hasError = Array.isArray(info.logs.error) && info.logs.error.length > 0; + if (!hasError) { + if (typeof opts.onCompiled === "function") { + opts.onCompiled(); + } + const [isRun, runArgs] = mustRun(args); + if (isRun) { + const isDebug = ((opts.fable || {}).define || []).indexOf("DEBUG") >= 0; + const job = runScript(getMainScriptPath(opts, info), runArgs, isDebug); + if (mustFinish) { + job.then((code) => { process.exit(code); }); + return; + } + } + } + if (mustFinish) { + process.exit(hasError ? 1 : 0); + } + +} + function run(entry, args) { const cfgFile = findArgValue(args, ["-c", "--config"]); @@ -164,7 +188,7 @@ function run(entry, args) { if (findFlag(args, ["-d", "--debug"])) { const fableOpts = opts.fable || {}; - fableOpts.define = concatIfNotExists(fableOpts.define, "DEBUG"); + fableOpts.define = concatSafe(fableOpts.define, "DEBUG"); opts.fable = fableOpts; } @@ -172,7 +196,7 @@ function run(entry, args) { // TODO: In the future, we may want to use ES2015 modules and .mjs files if (findFlag(args, ["--commonjs", "--run"])) { const babelOpts = opts.babel || {}; - babelOpts.plugins = concatIfNotExists(babelOpts.define, "@babel/plugin-transform-modules-commonjs"); + babelOpts.plugins = concatSafe(babelOpts.define, "@babel/plugin-transform-modules-commonjs"); opts.babel = babelOpts; } @@ -180,10 +204,7 @@ function run(entry, args) { console.log(`fable-splitter ${getVersion()}`); fableSplitter(opts).then((info) => { if (findFlag(args, ["-w", "--watch"])) { - const [isRun, runArgs] = mustRun(args); - if (isRun) { - runScript(getMainScriptPath(opts, info), runArgs); - } + onCompiled(args, opts, info); let cachedInfo = info; let ready = false; let next: [string, Date]|null = null; @@ -192,6 +213,7 @@ function run(entry, args) { .watch(Array.from(info.compiledPaths), { ignored: /node_modules/, persistent: true, + usePolling: findFlag(args, ["--usePolling"]) }) .on("ready", () => { console.log("fable: Watching..."); @@ -213,23 +235,13 @@ function run(entry, args) { watcher.add(newFiles); } cachedInfo = info2; - if (isRun) { - runScript(getMainScriptPath(opts, info2), runArgs); - } + onCompiled(args, opts, info2); }); } } }); } else { - const [isRun, runArgs] = mustRun(args); - const hasError = Array.isArray(info.logs.error) && info.logs.error.length > 0; - if (!hasError && isRun) { - runScript(getMainScriptPath(opts, info), runArgs).then((code) => { - process.exit(code); - }); - } else { - process.exit(hasError ? 1 : 0); - } + onCompiled(args, opts, info, true); } }); } diff --git a/src/fable-splitter/src/run.ts b/src/fable-splitter/src/run.ts index 7512bb9a2d..c3593e54e8 100644 --- a/src/fable-splitter/src/run.ts +++ b/src/fable-splitter/src/run.ts @@ -2,11 +2,12 @@ import { ChildProcess, spawn } from "child_process"; let childCache: ChildProcess|null = null; -export default function runScript(path: string, args: string[]): Promise { +export default function runScript(path: string, args: string[], debug = false): Promise { if (childCache != null) { childCache.kill(); } - const child = spawn("node", [path].concat(args), { + const defaultArgs = debug ? ['--inspect', path] : [path]; + const child = spawn("node", defaultArgs.concat(args), { stdio: "inherit", }); childCache = child; diff --git a/src/fable-splitter/tests/index.js b/src/fable-splitter/tests/index.js index a9f7346f7f..bb6303395c 100644 --- a/src/fable-splitter/tests/index.js +++ b/src/fable-splitter/tests/index.js @@ -1,7 +1,7 @@ const shell = require("shelljs"); -const ava = require("ava"); +const test = require("ava").default; -ava.test("allFiles in config works", (t) => { +test("allFiles in config works", (t) => { shell.cd(__dirname); shell.rm("-rf", "temp") shell.exec("node ../dist/cli allFiles -o temp -c allFiles/config.js"); diff --git a/src/fable-standalone/README.md b/src/fable-standalone/README.md index 4a1fb1bd2d..a59566c768 100644 --- a/src/fable-standalone/README.md +++ b/src/fable-standalone/README.md @@ -1,3 +1,3 @@ # fable-standalone -Fable bootstrapping itself to compile F# code in JS-only environments (browser, node.js). Note this doesn't output JS code, but a JSON AST that must be transformed using Babel. \ No newline at end of file +Fable bootstrapping itself to compile F# code in JS-only environments (browser, node.js). Note this doesn't output JS code, but a JSON AST that must be transformed using Babel. diff --git a/src/fable-standalone/RELEASE_NOTES.md b/src/fable-standalone/RELEASE_NOTES.md index e8e64a1b3f..41d8393ee3 100644 --- a/src/fable-standalone/RELEASE_NOTES.md +++ b/src/fable-standalone/RELEASE_NOTES.md @@ -1,3 +1,104 @@ +### 1.3.14 + +* fable-compiler 2.8.1 + +### 1.3.13 + +* fable-compiler 2.8.0 + +### 1.3.12 + +* fable-compiler 2.7.0 + +### 1.3.11 + +* fable-compiler 2.6.0 + +### 1.3.10 + +* fable-compiler 2.5.1 + +### 1.3.9 + +* fable-compiler 2.4.23 +* Use fable-splitter and rollup to generate the bundles + +### 1.3.8 + +* fable-compiler 2.4.22 + +### 1.3.8 + +* fable-compiler 2.4.21 + +### 1.3.7 + +* fable-compiler 2.4.20 + +### 1.3.6 + +* fable-compiler 2.4.19 + +### 1.3.5 + +* fable-compiler 2.4.18 + +### 1.3.4 + +* fable-compiler 2.4.17 + +### 1.3.3 + +* fable-compiler 2.4.16 + +### 1.3.2 + +* fable-compiler 2.4.15 + +### 1.3.1 + +* fable-compiler 2.4.14 + +### 1.3.0 + +* Catch up with fable-compiler 2.4.11 + +### 1.2.3 + +* Include System.Net.Requests & System.Net.WebClient in references + +### 1.2.2 + +* Enable passing otherFSharpOptions + +### 1.2.0 + +* fable-compiler 2.4.2 + +### 1.1.8 + +* fable-compiler 2.3.25 + +### 1.1.7 + +* fable-compiler 2.3.24 + +### 1.1.6 + +* fable-compiler 2.3.21 + +### 1.1.5 + +* fable-compiler 2.3.19 + +### 1.1.4 + +* fable-compiler 2.3.12 + +### 1.1.3 + +* Don't crash REPL compilation on Babel errors + ### 1.1.2 * fable-compiler 2.3.10 diff --git a/src/fable-standalone/package-lock.json b/src/fable-standalone/package-lock.json new file mode 100644 index 0000000000..a9a1fe0a64 --- /dev/null +++ b/src/fable-standalone/package-lock.json @@ -0,0 +1,5 @@ +{ + "name": "fable-standalone", + "version": "1.3.14", + "lockfileVersion": 1 +} diff --git a/src/fable-standalone/package.json b/src/fable-standalone/package.json index c44981b294..3fa114b536 100644 --- a/src/fable-standalone/package.json +++ b/src/fable-standalone/package.json @@ -1,6 +1,6 @@ { "name": "fable-standalone", - "version": "1.1.2", + "version": "1.3.14", "main": "dist/bundle.min.js", "description": "Fable compiler", "keywords": [ diff --git a/src/fable-standalone/splitter.config.js b/src/fable-standalone/splitter.config.js new file mode 100644 index 0000000000..414c26a58e --- /dev/null +++ b/src/fable-standalone/splitter.config.js @@ -0,0 +1,32 @@ +const resolve = (path) => require("path").join(__dirname, path); + +const useCommonjs = process.argv.find(v => v === "--commonjs"); +console.log("Compiling to " + (useCommonjs ? "commonjs" : "ES2015 modules") + "...") + +const babelOptions = useCommonjs + ? { plugins: ["@babel/plugin-transform-modules-commonjs"] } + : {}; + +const fableOptions = { + define: [ + "FX_NO_CORHOST_SIGNER", + "FX_NO_LINKEDRESOURCES", + "FX_NO_PDB_READER", + "FX_NO_PDB_WRITER", + "FX_NO_WEAKTABLE", + "FX_REDUCED_EXCEPTIONS", + "NO_COMPILER_BACKEND", + "NO_EXTENSIONTYPING", + "NO_INLINE_IL_PARSER" + ], + // extra: { saveAst: "./ast" } +}; + +module.exports = { + cli: { path: resolve("../Fable.Cli") }, + entry: resolve("./src/Fable.Standalone.fsproj"), + outDir: resolve("../../build/fable-standalone/out-bundle"), + // port: 61225, + babel: babelOptions, + fable: fableOptions, +}; diff --git a/src/fable-standalone/src/Fable.Standalone.fsproj b/src/fable-standalone/src/Fable.Standalone.fsproj index 142341b1a6..7b540d9e93 100644 --- a/src/fable-standalone/src/Fable.Standalone.fsproj +++ b/src/fable-standalone/src/Fable.Standalone.fsproj @@ -7,7 +7,7 @@ - + diff --git a/src/fable-standalone/src/Interfaces.fs b/src/fable-standalone/src/Interfaces.fs index 13a817b12f..bdcdcc77e8 100644 --- a/src/fable-standalone/src/Interfaces.fs +++ b/src/fable-standalone/src/Interfaces.fs @@ -40,6 +40,7 @@ type IChecker = interface end type IParseResults = + abstract OtherFSharpOptions: string[] abstract Errors: Error[] type IBabelResult = @@ -47,15 +48,14 @@ type IBabelResult = abstract FableErrors: Error[] type IFableManager = - abstract CreateChecker: references: string[] * readAllBytes: (string -> byte[]) * defines: string[] * optimize: bool -> IChecker abstract CreateChecker: references: string[] * readAllBytes: (string -> byte[]) * otherOptions: string[] -> IChecker abstract ClearParseCaches: checker: IChecker -> unit - abstract ParseFSharpScript: checker: IChecker * fileName: string * source: string -> IParseResults - abstract ParseFSharpProject: checker: IChecker * projectFileName: string * fileNames: string[] * sources: string[] -> IParseResults - abstract ParseFSharpFileInProject: checker: IChecker * fileName: string * projectFileName: string * fileNames: string[] * sources: string[] -> IParseResults + abstract ParseFSharpScript: checker: IChecker * fileName: string * source: string * ?otherFSharpOptions: string[] -> IParseResults + abstract ParseFSharpProject: checker: IChecker * projectFileName: string * fileNames: string[] * sources: string[] * ?otherFSharpOptions: string[] -> IParseResults + abstract ParseFSharpFileInProject: checker: IChecker * fileName: string * projectFileName: string * fileNames: string[] * sources: string[] * ?otherFSharpOptions: string[] -> IParseResults abstract GetParseErrors: parseResults: IParseResults -> Error[] abstract GetDeclarationLocation: parseResults: IParseResults * line: int * col: int * lineText: string -> Async abstract GetToolTipText: parseResults: IParseResults * line: int * col: int * lineText: string -> Async abstract GetCompletionsAtLocation: parseResults: IParseResults * line: int * col: int * lineText: string -> Async - abstract CompileToBabelAst: fableLibrary: string * parseResults: IParseResults * fileName: string * optimized: bool * ?precompiledLib: (string->(string*string) option) -> IBabelResult - abstract FSharpAstToString: parseResults: IParseResults * fileName: string * optimized: bool -> string + abstract CompileToBabelAst: fableLibrary: string * parseResults: IParseResults * fileName: string * ?precompiledLib: (string->(string*string) option) -> IBabelResult + abstract FSharpAstToString: parseResults: IParseResults * fileName: string -> string diff --git a/src/fable-standalone/src/Main.fs b/src/fable-standalone/src/Main.fs index 1f8a8bb485..24f8934bce 100644 --- a/src/fable-standalone/src/Main.fs +++ b/src/fable-standalone/src/Main.fs @@ -25,22 +25,19 @@ let mapError (error: FSharpErrorInfo) = | FSharpErrorSeverity.Warning -> true } -type ParseResults (optimizedProject: Lazy, - unoptimizedProject: Lazy, +type ParseResults (project: Lazy, parseFileResultsOpt: FSharpParseFileResults option, checkFileResultsOpt: FSharpCheckFileResults option, - checkProjectResults: FSharpCheckProjectResults) = - - member __.GetProject (optimized: bool) = - if optimized - then optimizedProject.Force() - else unoptimizedProject.Force() + checkProjectResults: FSharpCheckProjectResults, + otherFSharpOptions: string[]) = + member __.GetProject () = project.Force() member __.ParseFileResultsOpt = parseFileResultsOpt member __.CheckFileResultsOpt = checkFileResultsOpt member __.CheckProjectResults = checkProjectResults interface IParseResults with + member __.OtherFSharpOptions = otherFSharpOptions member __.Errors = checkProjectResults.Errors |> Array.map mapError let inline private tryGetLexerSymbolIslands (sym: Lexer.LexerSymbol) = @@ -104,12 +101,12 @@ let convertGlyph glyph = | FSharpGlyph.Event -> Glyph.Event -let makeProjOptions projectFileName fileNames = +let makeProjOptions projectFileName fileNames otherFSharpOptions = let projOptions: FSharpProjectOptions = { ProjectFileName = projectFileName ProjectId = None SourceFiles = fileNames - OtherOptions = [| |] + OtherOptions = otherFSharpOptions ReferencedProjects = [| |] IsIncompleteTypeCheckEnvironment = false UseScriptResolutionRules = false @@ -120,9 +117,10 @@ let makeProjOptions projectFileName fileNames = Stamp = None } projOptions -let makeProject projectOptions (projectResults: FSharpCheckProjectResults) optimized = +let makeProject (projectOptions: FSharpProjectOptions) (projectResults: FSharpCheckProjectResults) = // let errors = com.GetFormattedLogs() |> Map.tryFind "error" // if errors.IsSome then failwith (errors.Value |> String.concat "\n") + let optimized = projectOptions.OtherOptions |> Array.exists ((=) "--optimize+") let implFiles = (if optimized then projectResults.GetOptimizedAssemblyContents() @@ -131,27 +129,24 @@ let makeProject projectOptions (projectResults: FSharpCheckProjectResults) optim implFiles |> Seq.map (fun file -> Fable.Path.normalizePathAndEnsureFsExtension file.FileName, file) |> dict Project(projectOptions, implFilesMap, projectResults.Errors) -let parseFSharpScript (checker: InteractiveChecker) projectFileName fileName source = +let parseFSharpScript (checker: InteractiveChecker) projectFileName fileName source otherFSharpOptions = let parseResults, checkResults, projectResults = checker.ParseAndCheckScript (projectFileName, fileName, source) - let projectOptions = makeProjOptions projectFileName [| fileName |] - let optimizedProject = lazy (makeProject projectOptions projectResults true) - let unoptimizedProject = lazy (makeProject projectOptions projectResults false) - ParseResults (optimizedProject, unoptimizedProject, Some parseResults, Some checkResults, projectResults) + let projectOptions = makeProjOptions projectFileName [| fileName |] otherFSharpOptions + let project = lazy (makeProject projectOptions projectResults) + ParseResults (project, Some parseResults, Some checkResults, projectResults, otherFSharpOptions) -let parseFSharpProject (checker: InteractiveChecker) projectFileName fileNames sources = +let parseFSharpProject (checker: InteractiveChecker) projectFileName fileNames sources otherFSharpOptions = let projectResults = checker.ParseAndCheckProject (projectFileName, fileNames, sources) - let projectOptions = makeProjOptions projectFileName fileNames - let optimizedProject = lazy (makeProject projectOptions projectResults true) - let unoptimizedProject = lazy (makeProject projectOptions projectResults false) - ParseResults (optimizedProject, unoptimizedProject, None, None, projectResults) + let projectOptions = makeProjOptions projectFileName fileNames otherFSharpOptions + let project = lazy (makeProject projectOptions projectResults) + ParseResults (project, None, None, projectResults, otherFSharpOptions) -let parseFSharpFileInProject (checker: InteractiveChecker) fileName projectFileName fileNames sources = +let parseFSharpFileInProject (checker: InteractiveChecker) fileName projectFileName fileNames sources otherFSharpOptions = let parseResults, checkResultsOpt, projectResults = checker.ParseAndCheckFileInProject (fileName, projectFileName, fileNames, sources) - let projectOptions = makeProjOptions projectFileName fileNames - let optimizedProject = lazy (makeProject projectOptions projectResults true) - let unoptimizedProject = lazy (makeProject projectOptions projectResults false) - ParseResults (optimizedProject, unoptimizedProject, Some parseResults, checkResultsOpt, projectResults) + let projectOptions = makeProjOptions projectFileName fileNames otherFSharpOptions + let project = lazy (makeProject projectOptions projectResults) + ParseResults (project, Some parseResults, checkResultsOpt, projectResults, otherFSharpOptions) let tooltipToString (el: FSharpToolTipElement): string[] = let dataToString (data: FSharpToolTipElementData) = @@ -218,11 +213,12 @@ let getCompletionsAtLocation (parseResults: ParseResults) (line: int) (col: int) return [||] } -let makeCompiler fableLibrary fileName (project: Project) precompiledLib = +let makeCompiler fableLibrary fileName (project: Project) precompiledLib (otherFSharpOptions: string[]) = let options: Fable.CompilerOptions = { typedArrays = true clampByteArrays = false - verbose = false + debugMode = otherFSharpOptions |> Array.exists (fun x -> x = "--define:DEBUG" || x = "-d:DEBUG") + verbosity = Fable.Verbosity.Normal outputPublicInlinedFunctions = false quotations = true precompiledLib = precompiledLib } @@ -236,10 +232,6 @@ let compileAst (com: Compiler) (project: Project) = let init () = { new IFableManager with - member __.CreateChecker(references, readAllBytes, defines, optimize) = - InteractiveChecker.Create(references, readAllBytes, defines, optimize) - |> CheckerImpl :> IChecker - member __.CreateChecker(references, readAllBytes, otherOptions) = InteractiveChecker.Create(references, readAllBytes, otherOptions) |> CheckerImpl :> IChecker @@ -248,18 +240,21 @@ let init () = let c = checker :?> CheckerImpl c.Checker.ClearCache() - member __.ParseFSharpScript(checker, fileName, source) = + member __.ParseFSharpScript(checker, fileName, source, ?otherFSharpOptions) = let c = checker :?> CheckerImpl + let otherFSharpOptions = defaultArg otherFSharpOptions [||] let projectFileName = "project" // TODO: make it an argument - parseFSharpScript c.Checker projectFileName fileName source :> IParseResults + parseFSharpScript c.Checker projectFileName fileName source otherFSharpOptions :> IParseResults - member __.ParseFSharpProject(checker, projectFileName, fileNames, sources) = + member __.ParseFSharpProject(checker, projectFileName, fileNames, sources, ?otherFSharpOptions) = let c = checker :?> CheckerImpl - parseFSharpProject c.Checker projectFileName fileNames sources :> IParseResults + let otherFSharpOptions = defaultArg otherFSharpOptions [||] + parseFSharpProject c.Checker projectFileName fileNames sources otherFSharpOptions :> IParseResults - member __.ParseFSharpFileInProject(checker, fileName, projectFileName, fileNames, sources) = + member __.ParseFSharpFileInProject(checker, fileName, projectFileName, fileNames, sources, ?otherFSharpOptions) = let c = checker :?> CheckerImpl - parseFSharpFileInProject c.Checker fileName projectFileName fileNames sources :> IParseResults + let otherFSharpOptions = defaultArg otherFSharpOptions [||] + parseFSharpFileInProject c.Checker fileName projectFileName fileNames sources otherFSharpOptions :> IParseResults member __.GetParseErrors(parseResults:IParseResults) = parseResults.Errors @@ -276,10 +271,10 @@ let init () = let res = parseResults :?> ParseResults getCompletionsAtLocation res line col lineText - member __.CompileToBabelAst(fableLibrary:string, parseResults:IParseResults, fileName:string, optimized: bool, ?precompiledLib) = + member __.CompileToBabelAst(fableLibrary:string, parseResults:IParseResults, fileName:string, ?precompiledLib) = let res = parseResults :?> ParseResults - let project = res.GetProject (optimized) - let com = makeCompiler fableLibrary fileName project precompiledLib + let project = res.GetProject() + let com = makeCompiler fableLibrary fileName project precompiledLib parseResults.OtherFSharpOptions let ast = compileAst com project let errors = com.GetLogs() @@ -305,9 +300,9 @@ let init () = member __.BabelAst = ast :> obj member __.FableErrors = errors } - member __.FSharpAstToString(parseResults:IParseResults, fileName:string, optimized: bool) = + member __.FSharpAstToString(parseResults:IParseResults, fileName:string) = let res = parseResults :?> ParseResults - let project = res.GetProject (optimized) + let project = res.GetProject() let implFile = project.ImplementationFiles.Item(fileName) AstPrint.printFSharpDecls "" implFile.Declarations |> String.concat "\n" } diff --git a/src/fable-standalone/src/Metadata.fs b/src/fable-standalone/src/Metadata.fs index 84707e79ac..b78f5f0753 100644 --- a/src/fable-standalone/src/Metadata.fs +++ b/src/fable-standalone/src/Metadata.fs @@ -13,10 +13,13 @@ let references_core = [| "System.Console" "System.Core" "System.Diagnostics.Debug" + "System.Diagnostics.Tools" "System.Diagnostics.Tracing" "System.Globalization" "System" "System.IO" + "System.Net.Requests" + "System.Net.WebClient" "System.Numerics" "System.Reflection" "System.Reflection.Extensions" @@ -32,167 +35,173 @@ let references_core = [| "System.Threading" "System.Threading.Tasks" "System.ValueTuple" -|] + |] -let references use_net45_meta = - if use_net45_meta then - [|"Fable.Core" - "Fable.Import.Browser" - "FSharp.Core" - "mscorlib" - "System" - "System.Core" - "System.Data" - "System.IO" - "System.Xml" - "System.Numerics" - |] - else - [|"Fable.Core" - "Fable.Import.Browser" - "FSharp.Core" - "Microsoft.CSharp" - "Microsoft.VisualBasic" - "Microsoft.Win32.Primitives" - "mscorlib" - "netstandard" - "System.AppContext" - "System.Buffers" - "System.Collections.Concurrent" - "System.Collections" - "System.Collections.Immutable" - "System.Collections.NonGeneric" - "System.Collections.Specialized" - "System.ComponentModel.Annotations" - //"System.ComponentModel.Composition" // removed in 2.1.300 - "System.ComponentModel.DataAnnotations" - "System.ComponentModel" - "System.ComponentModel.EventBasedAsync" - "System.ComponentModel.Primitives" - "System.ComponentModel.TypeConverter" - "System.Configuration" - "System.Console" - "System.Core" - "System.Data.Common" - "System.Data" - "System.Diagnostics.Contracts" - "System.Diagnostics.Debug" - "System.Diagnostics.DiagnosticSource" - "System.Diagnostics.FileVersionInfo" - "System.Diagnostics.Process" - "System.Diagnostics.StackTrace" - "System.Diagnostics.TextWriterTraceListener" - "System.Diagnostics.Tools" - "System.Diagnostics.TraceSource" - "System.Diagnostics.Tracing" - "System" - "System.Drawing" - "System.Drawing.Primitives" - "System.Dynamic.Runtime" - "System.Globalization.Calendars" - "System.Globalization" - "System.Globalization.Extensions" - //"System.IO.Compression.Brotli" // added in 2.1.300 - "System.IO.Compression" - "System.IO.Compression.FileSystem" - "System.IO.Compression.ZipFile" - "System.IO" - "System.IO.FileSystem" - "System.IO.FileSystem.DriveInfo" - "System.IO.FileSystem.Primitives" - "System.IO.FileSystem.Watcher" - "System.IO.IsolatedStorage" - "System.IO.MemoryMappedFiles" - "System.IO.Pipes" - "System.IO.UnmanagedMemoryStream" - "System.Linq" - "System.Linq.Expressions" - "System.Linq.Parallel" - "System.Linq.Queryable" - //"System.Memory" // added in 2.1.300 - "System.Net" - "System.Net.Http" - "System.Net.HttpListener" - "System.Net.Mail" - "System.Net.NameResolution" - "System.Net.NetworkInformation" - "System.Net.Ping" - "System.Net.Primitives" - "System.Net.Requests" - "System.Net.Security" - "System.Net.ServicePoint" - "System.Net.Sockets" - "System.Net.WebClient" - "System.Net.WebHeaderCollection" - "System.Net.WebProxy" - "System.Net.WebSockets.Client" - "System.Net.WebSockets" - "System.Numerics" - "System.Numerics.Vectors" - "System.ObjectModel" - "System.Reflection.DispatchProxy" - "System.Reflection" - "System.Reflection.Emit" - "System.Reflection.Emit.ILGeneration" - "System.Reflection.Emit.Lightweight" - "System.Reflection.Extensions" - "System.Reflection.Metadata" - "System.Reflection.Primitives" - "System.Reflection.TypeExtensions" - "System.Resources.Reader" - "System.Resources.ResourceManager" - "System.Resources.Writer" - "System.Runtime.CompilerServices.VisualC" - "System.Runtime" - "System.Runtime.Extensions" - "System.Runtime.Handles" - "System.Runtime.InteropServices" - "System.Runtime.InteropServices.RuntimeInformation" - "System.Runtime.InteropServices.WindowsRuntime" - "System.Runtime.Loader" - "System.Runtime.Numerics" - "System.Runtime.Serialization" - "System.Runtime.Serialization.Formatters" - "System.Runtime.Serialization.Json" - "System.Runtime.Serialization.Primitives" - "System.Runtime.Serialization.Xml" - "System.Security.Claims" - "System.Security.Cryptography.Algorithms" - "System.Security.Cryptography.Csp" - "System.Security.Cryptography.Encoding" - "System.Security.Cryptography.Primitives" - "System.Security.Cryptography.X509Certificates" - "System.Security" - "System.Security.Principal" - "System.Security.SecureString" - "System.ServiceModel.Web" - "System.ServiceProcess" - "System.Text.Encoding" - "System.Text.Encoding.Extensions" - "System.Text.RegularExpressions" - "System.Threading" - "System.Threading.Overlapped" - "System.Threading.Tasks.Dataflow" - "System.Threading.Tasks" - "System.Threading.Tasks.Extensions" - "System.Threading.Tasks.Parallel" - "System.Threading.Thread" - "System.Threading.ThreadPool" - "System.Threading.Timer" - "System.Transactions" - "System.Transactions.Local" - "System.ValueTuple" - "System.Web" - "System.Web.HttpUtility" - "System.Windows" - "System.Xml" - "System.Xml.Linq" - "System.Xml.ReaderWriter" - "System.Xml.Serialization" - "System.Xml.XDocument" - "System.Xml.XmlDocument" - "System.Xml.XmlSerializer" - "System.Xml.XPath" - "System.Xml.XPath.XDocument" - "WindowsBase" - |] +let references_net45 = [| + "Fable.Core" + "Fable.Import.Browser" + "FSharp.Core" + "mscorlib" + "System" + "System.Core" + "System.Data" + "System.IO" + "System.Xml" + "System.Numerics" + |] + +let references_full = [| + "Fable.Core" + "FSharp.Core" + "Microsoft.CSharp" + "Microsoft.VisualBasic.Core" + "Microsoft.VisualBasic" + "Microsoft.Win32.Primitives" + "mscorlib" + "netstandard" + "System.AppContext" + "System.Buffers" + "System.Collections.Concurrent" + "System.Collections" + "System.Collections.Immutable" + "System.Collections.NonGeneric" + "System.Collections.Specialized" + "System.ComponentModel.Annotations" + "System.ComponentModel.DataAnnotations" + "System.ComponentModel" + "System.ComponentModel.EventBasedAsync" + "System.ComponentModel.Primitives" + "System.ComponentModel.TypeConverter" + "System.Configuration" + "System.Console" + "System.Core" + "System.Data.Common" + "System.Data.DataSetExtensions" + "System.Data" + "System.Diagnostics.Contracts" + "System.Diagnostics.Debug" + "System.Diagnostics.DiagnosticSource" + "System.Diagnostics.FileVersionInfo" + "System.Diagnostics.Process" + "System.Diagnostics.StackTrace" + "System.Diagnostics.TextWriterTraceListener" + "System.Diagnostics.Tools" + "System.Diagnostics.TraceSource" + "System.Diagnostics.Tracing" + "System" + "System.Drawing" + "System.Drawing.Primitives" + "System.Dynamic.Runtime" + "System.Globalization.Calendars" + "System.Globalization" + "System.Globalization.Extensions" + "System.IO.Compression.Brotli" + "System.IO.Compression" + "System.IO.Compression.FileSystem" + "System.IO.Compression.ZipFile" + "System.IO" + "System.IO.FileSystem" + "System.IO.FileSystem.DriveInfo" + "System.IO.FileSystem.Primitives" + "System.IO.FileSystem.Watcher" + "System.IO.IsolatedStorage" + "System.IO.MemoryMappedFiles" + "System.IO.Pipes" + "System.IO.UnmanagedMemoryStream" + "System.Linq" + "System.Linq.Expressions" + "System.Linq.Parallel" + "System.Linq.Queryable" + "System.Memory" + "System.Net" + "System.Net.Http" + "System.Net.HttpListener" + "System.Net.Mail" + "System.Net.NameResolution" + "System.Net.NetworkInformation" + "System.Net.Ping" + "System.Net.Primitives" + "System.Net.Requests" + "System.Net.Security" + "System.Net.ServicePoint" + "System.Net.Sockets" + "System.Net.WebClient" + "System.Net.WebHeaderCollection" + "System.Net.WebProxy" + "System.Net.WebSockets.Client" + "System.Net.WebSockets" + "System.Numerics" + "System.Numerics.Vectors" + "System.ObjectModel" + "System.Reflection.DispatchProxy" + "System.Reflection" + "System.Reflection.Emit" + "System.Reflection.Emit.ILGeneration" + "System.Reflection.Emit.Lightweight" + "System.Reflection.Extensions" + "System.Reflection.Metadata" + "System.Reflection.Primitives" + "System.Reflection.TypeExtensions" + "System.Resources.Reader" + "System.Resources.ResourceManager" + "System.Resources.Writer" + "System.Runtime.CompilerServices.Unsafe" + "System.Runtime.CompilerServices.VisualC" + "System.Runtime" + "System.Runtime.Extensions" + "System.Runtime.Handles" + "System.Runtime.InteropServices" + "System.Runtime.InteropServices.RuntimeInformation" + "System.Runtime.InteropServices.WindowsRuntime" + "System.Runtime.Intrinsics" + "System.Runtime.Loader" + "System.Runtime.Numerics" + "System.Runtime.Serialization" + "System.Runtime.Serialization.Formatters" + "System.Runtime.Serialization.Json" + "System.Runtime.Serialization.Primitives" + "System.Runtime.Serialization.Xml" + "System.Security.Claims" + "System.Security.Cryptography.Algorithms" + "System.Security.Cryptography.Csp" + "System.Security.Cryptography.Encoding" + "System.Security.Cryptography.Primitives" + "System.Security.Cryptography.X509Certificates" + "System.Security" + "System.Security.Principal" + "System.Security.SecureString" + "System.ServiceModel.Web" + "System.ServiceProcess" + "System.Text.Encoding.CodePages" + "System.Text.Encoding" + "System.Text.Encoding.Extensions" + "System.Text.Encodings.Web" + "System.Text.Json" + "System.Text.RegularExpressions" + "System.Threading.Channels" + "System.Threading" + "System.Threading.Overlapped" + "System.Threading.Tasks.Dataflow" + "System.Threading.Tasks" + "System.Threading.Tasks.Extensions" + "System.Threading.Tasks.Parallel" + "System.Threading.Thread" + "System.Threading.ThreadPool" + "System.Threading.Timer" + "System.Transactions" + "System.Transactions.Local" + "System.ValueTuple" + "System.Web" + "System.Web.HttpUtility" + "System.Windows" + "System.Xml" + "System.Xml.Linq" + "System.Xml.ReaderWriter" + "System.Xml.Serialization" + "System.Xml.XDocument" + "System.Xml.XmlDocument" + "System.Xml.XmlSerializer" + "System.Xml.XPath" + "System.Xml.XPath.XDocument" + "WindowsBase" + |] diff --git a/src/fable-standalone/src/Worker/Shared.fs b/src/fable-standalone/src/Worker/Shared.fs index 8b13c2782d..ebf2e48d17 100644 --- a/src/fable-standalone/src/Worker/Shared.fs +++ b/src/fable-standalone/src/Worker/Shared.fs @@ -8,9 +8,9 @@ open Thoth.Json type WorkerRequest = /// * refsExtraSuffix: e.g. add .txt extension to enable gzipping in Github Pages - | CreateChecker of refsDirUrl: string * extraRefs: string[] * refsExtraSuffix: string option * libJsonUrl: string option - | ParseCode of fsharpCode: string - | CompileCode of fsharpCode: string * optimize: bool + | CreateChecker of refsDirUrl: string * extraRefs: string[] * refsExtraSuffix: string option * libJsonUrl: string option * otherFSharpOptions: string[] + | ParseCode of fsharpCode: string * otherFSharpOptions: string[] + | CompileCode of fsharpCode: string * otherFSharpOptions: string[] | GetTooltip of id: Guid * line: int * column: int * lineText: string | GetCompletions of id: Guid * line: int * column: int * lineText: string | GetDeclarationLocation of id: Guid * line: int * column: int * lineText: string diff --git a/src/fable-standalone/src/Worker/Worker.fs b/src/fable-standalone/src/Worker/Worker.fs index 678ce48c5b..d3bff5eb3b 100644 --- a/src/fable-standalone/src/Worker/Worker.fs +++ b/src/fable-standalone/src/Worker/Worker.fs @@ -23,7 +23,7 @@ let resolveLibCall(libMap: obj, entityName: string): (string*string) option = im let getAssemblyReader(getBlobUrl: string->string, _refs: string[]): JS.Promisebyte[]> = importMember "./util.js" let getBabelAstCompiler(): JS.Promisestring> = importMember "./util.js" -let measureTime msg f arg = +let measureTime f arg = let before: float = self?performance?now() let res = f arg let after: float = self?performance?now() @@ -34,20 +34,26 @@ type FableState = Checker: IChecker BabelAstCompiler: obj->string LoadTime: float - LibMap: obj } + LibMap: obj + References: string[] + Reader: string->byte[] + OtherFSharpOptions: string[] } + +type FableStateConfig = + | Init of refsDirUrl: string * extraRefs: string[] * refsExtraSuffix: string option * libJsonUrl: string option + | Initialized of FableState type State = { Fable: FableState option Worker: ObservableWorker CurrentResults: IParseResults option } -let rec loop (box: MailboxProcessor) (state: State) = async { - let! msg = box.Receive() - match state.Fable, msg with - | None, CreateChecker(refsDirUrl, extraRefs, refsExtraSuffix, libJsonUrl) -> - let getBlobUrl name = - refsDirUrl.TrimEnd('/') + "/" + name + ".dll" + (defaultArg refsExtraSuffix "") - try +let makeFableState (config: FableStateConfig) otherFSharpOptions = + async { + match config with + | Init(refsDirUrl, extraRefs, refsExtraSuffix, libJsonUrl) -> + let getBlobUrl name = + refsDirUrl.TrimEnd('/') + "/" + name + ".dll" + (defaultArg refsExtraSuffix "") let manager = FableInit.init() let! babelCompiler = getBabelAstCompiler() |> Async.AwaitPromise let! libMap = @@ -56,14 +62,37 @@ let rec loop (box: MailboxProcessor) (state: State) = async { | None -> async.Return null let references = Array.append Fable.Standalone.Metadata.references_core extraRefs let! reader = getAssemblyReader(getBlobUrl, references) |> Async.AwaitPromise - let (checker, checkerTime) = measureTime "FCS checker" (fun () -> - manager.CreateChecker(references, reader, [||], false)) () + let (checker, checkerTime) = measureTime (fun () -> + manager.CreateChecker(references, reader, otherFSharpOptions)) () + return { Manager = manager + Checker = checker + BabelAstCompiler = babelCompiler + LoadTime = checkerTime + LibMap = libMap + References = references + Reader = reader + OtherFSharpOptions = otherFSharpOptions } + + | Initialized fable -> + // We don't need to recreate the checker + if fable.OtherFSharpOptions = otherFSharpOptions then + return fable + else + let (checker, checkerTime) = measureTime (fun () -> + fable.Manager.CreateChecker(fable.References, fable.Reader, otherFSharpOptions)) () + return { fable with Checker = checker + LoadTime = checkerTime + OtherFSharpOptions = otherFSharpOptions } + } + +let rec loop (box: MailboxProcessor) (state: State) = async { + let! msg = box.Receive() + match state.Fable, msg with + | None, CreateChecker(refsDirUrl, extraRefs, refsExtraSuffix, libJsonUrl, otherFSharpOptions) -> + try + let! fable = makeFableState (Init(refsDirUrl, extraRefs, refsExtraSuffix, libJsonUrl)) otherFSharpOptions state.Worker.Post Loaded - return! loop box { state with Fable = Some { Manager = manager - Checker = checker - BabelAstCompiler = babelCompiler - LoadTime = checkerTime - LibMap = libMap } } + return! loop box { state with Fable = Some fable } with err -> JS.console.error("Cannot create F# checker", err) state.Worker.Post LoadFailed @@ -73,17 +102,34 @@ let rec loop (box: MailboxProcessor) (state: State) = async { | None, _ | Some _, CreateChecker _ -> return! loop box state - | Some fable, ParseCode fsharpCode -> - let res = fable.Manager.ParseFSharpScript(fable.Checker, FILE_NAME, fsharpCode) + | Some fable, ParseCode(fsharpCode, otherFSharpOptions) -> + // Check if we need to recreate the FableState because otherFSharpOptions have changed + let! fable = makeFableState (Initialized fable) otherFSharpOptions + let res = fable.Manager.ParseFSharpScript(fable.Checker, FILE_NAME, fsharpCode, otherFSharpOptions) ParsedCode res.Errors |> state.Worker.Post return! loop box { state with CurrentResults = Some res } - | Some fable, CompileCode(fsharpCode, optimize) -> + | Some fable, CompileCode(fsharpCode, otherFSharpOptions) -> try - let (parseResults, parsingTime) = measureTime "FCS parsing" fable.Manager.ParseFSharpScript (fable.Checker, FILE_NAME, fsharpCode) - let (res, fableTransformTime) = measureTime "Fable transform" (fun () -> - fable.Manager.CompileToBabelAst("fable-library", parseResults, FILE_NAME, optimize, fun x -> resolveLibCall(fable.LibMap, x))) () - let (jsCode, babelTime) = measureTime "Babel generation" fable.BabelAstCompiler res.BabelAst + // Check if we need to recreate the FableState because otherFSharpOptions have changed + let! fable = makeFableState (Initialized fable) otherFSharpOptions + let (parseResults, parsingTime) = measureTime (fun () -> fable.Manager.ParseFSharpScript(fable.Checker, FILE_NAME, fsharpCode, otherFSharpOptions)) () + let (res, fableTransformTime) = measureTime (fun () -> + fable.Manager.CompileToBabelAst("fable-library", parseResults, FILE_NAME, fun x -> resolveLibCall(fable.LibMap, x))) () + let (jsCode, babelTime, babelErrors) = + try + let code, t = measureTime fable.BabelAstCompiler res.BabelAst + code, t, [||] + with ex -> + let error = + { FileName = FILE_NAME + StartLineAlternate = 1 + StartColumn = 0 + EndLineAlternate = 1 + EndColumn = 0 + Message = "BABEL: " + ex.Message + IsWarning = false } + "", 0., [|error|] let stats : CompileStats = { FCS_checker = fable.LoadTime @@ -91,7 +137,7 @@ let rec loop (box: MailboxProcessor) (state: State) = async { Fable_transform = fableTransformTime Babel_generation = babelTime } - let errors = Array.append (parseResults.Errors) res.FableErrors + let errors = Array.concat [parseResults.Errors; res.FableErrors; babelErrors] CompilationFinished (jsCode, errors, stats) |> state.Worker.Post with er -> JS.console.error er diff --git a/src/fable-standalone/src/Worker/Worker.fsproj b/src/fable-standalone/src/Worker/Worker.fsproj index 2d640e24e7..372e7cdc0b 100644 --- a/src/fable-standalone/src/Worker/Worker.fsproj +++ b/src/fable-standalone/src/Worker/Worker.fsproj @@ -11,8 +11,8 @@ - - - + + + diff --git a/src/fable-standalone/src/Worker/splitter.config.js b/src/fable-standalone/src/Worker/splitter.config.js new file mode 100644 index 0000000000..9003cffe49 --- /dev/null +++ b/src/fable-standalone/src/Worker/splitter.config.js @@ -0,0 +1,23 @@ +const resolve = (path) => require("path").join(__dirname, path); + +const useCommonjs = process.argv.find(v => v === "--commonjs"); +console.log("Compiling to " + (useCommonjs ? "commonjs" : "ES2015 modules") + "...") + +const babelOptions = useCommonjs + ? { plugins: ["@babel/plugin-transform-modules-commonjs"] } + : {}; + +const fableOptions = { + // define: [ + // ], + // extra: { saveAst: "./ast" } +}; + +module.exports = { + cli: { path: resolve("../../../Fable.Cli") }, + entry: resolve("./Worker.fsproj"), + outDir: resolve("../../../../build/fable-standalone/out-worker"), + // port: 61225, + babel: babelOptions, + fable: fableOptions, +}; diff --git a/src/fable-standalone/src/Worker/util.js b/src/fable-standalone/src/Worker/util.js index b9286c90f1..88a4584945 100644 --- a/src/fable-standalone/src/Worker/util.js +++ b/src/fable-standalone/src/Worker/util.js @@ -61,13 +61,9 @@ export function getBabelAstCompiler() { // an asynchronous chunk if necessary return new Promise(function (resolve) { resolve(function(ast) { - try { - var optionsES2015 = babelOptions(template); - var codeES2015 = transformFromAstSync(ast, null, optionsES2015).code; - return codeES2015; - } catch (err) { - console.error(err.message + "\n" + err.stack); - } + var optionsES2015 = babelOptions(template); + var codeES2015 = transformFromAstSync(ast, null, optionsES2015).code; + return codeES2015; }); }); } \ No newline at end of file diff --git a/src/fable-standalone/src/Worker/webpack.config.js b/src/fable-standalone/src/Worker/webpack.config.js index 7b875ac2da..bc0e90e361 100644 --- a/src/fable-standalone/src/Worker/webpack.config.js +++ b/src/fable-standalone/src/Worker/webpack.config.js @@ -1,3 +1,5 @@ +const resolve = (path) => require("path").join(__dirname, path); + module.exports = { target: "webworker", entry: resolve('Worker.fsproj'), @@ -26,7 +28,3 @@ module.exports = { ] } }; - -function resolve(x) { - return require("path").join(__dirname, x); -} \ No newline at end of file diff --git a/src/fable-standalone/test/bench-compiler/Platform.fs b/src/fable-standalone/test/bench-compiler/Platform.fs index 3a9c8f2e1d..13a5d15dc0 100644 --- a/src/fable-standalone/test/bench-compiler/Platform.fs +++ b/src/fable-standalone/test/bench-compiler/Platform.fs @@ -12,7 +12,7 @@ let measureTime (f: 'a -> 'b) x = let sw = System.Diagnostics.Stopwatch.StartNew() let res = f x sw.Stop() - sw.ElapsedMilliseconds, res + res, sw.ElapsedMilliseconds module Json = open Newtonsoft.Json @@ -51,14 +51,25 @@ module Json = let serializeToJson = Json.serializeToJson -let ensureDirExists (dir: string): unit = - Directory.CreateDirectory(dir) |> ignore +let ensureDirExists (path: string): unit = + Directory.CreateDirectory(path) |> ignore let normalizeFullPath (path: string) = + let path = if System.String.IsNullOrWhiteSpace path then "." else path Path.GetFullPath(path).Replace('\\', '/') -let getRelativePath (pathFrom: string) (pathTo: string) = - Path.GetRelativePath(pathFrom, pathTo).Replace('\\', '/') +let getRelativePath (path: string) (pathTo: string) = + let path = if System.String.IsNullOrWhiteSpace path then "." else path + Path.GetRelativePath(path, pathTo).Replace('\\', '/') + +let getHomePath () = + System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile) + +let getDirFiles (path: string) (extension: string) = + if not (Directory.Exists(path)) then [||] + else Directory.GetFiles(path, "*" + extension, SearchOption.AllDirectories) + |> Array.map (fun x -> x.Replace('\\', '/')) + |> Array.sort #else @@ -70,6 +81,12 @@ module JS = abstract readFileSync: string * string -> string abstract writeFileSync: string * string -> unit + type IOperSystem = + abstract homedir: unit -> string + abstract tmpdir: unit -> string + abstract platform: unit -> string + abstract arch: unit -> string + type IProcess = abstract hrtime: unit -> float [] abstract hrtime: float[] -> float[] @@ -81,30 +98,51 @@ module JS = type IUtil = abstract serializeToJson: data: obj -> string abstract ensureDirExists: dir: string -> unit + abstract getDirFiles: dir: string -> string[] + + // type IPerformance = + // abstract now: unit -> float - let FileSystem: IFileSystem = importAll "fs" - let Process: IProcess = importAll "process" - let Path: IPath = importAll "path" - let Util: IUtil = importAll "./util.js" + let fs: IFileSystem = importAll "fs" + let os: IOperSystem = importAll "os" + let proc: IProcess = importAll "process" + let path: IPath = importAll "path" + let util: IUtil = importAll "./util.js" + // let performance: IPerformance = importMember "perf_hooks" -let readAllBytes (filePath: string) = JS.FileSystem.readFileSync(filePath) -let readAllText (filePath: string) = JS.FileSystem.readFileSync(filePath, "utf8").TrimStart('\uFEFF') -let writeAllText (filePath: string) (text: string) = JS.FileSystem.writeFileSync(filePath, text) +let readAllBytes (filePath: string) = JS.fs.readFileSync(filePath) +let readAllText (filePath: string) = JS.fs.readFileSync(filePath, "utf8").TrimStart('\uFEFF') +let writeAllText (filePath: string) (text: string) = JS.fs.writeFileSync(filePath, text) + +// let measureTime (f: 'a -> 'b) x = +// let t0 = JS.performance.now() +// let res = f x +// let t1 = JS.performance.now() +// res, int64 (t1 - t0) let measureTime (f: 'a -> 'b) x = - let startTime = JS.Process.hrtime() + let startTime = JS.proc.hrtime() let res = f x - let elapsed = JS.Process.hrtime(startTime) - int64 (elapsed.[0] * 1e3 + elapsed.[1] / 1e6), res + let elapsed = JS.proc.hrtime(startTime) + res, int64 (elapsed.[0] * 1e3 + elapsed.[1] / 1e6) -let serializeToJson = JS.Util.serializeToJson -let ensureDirExists = JS.Util.ensureDirExists +let serializeToJson = JS.util.serializeToJson +let ensureDirExists = JS.util.ensureDirExists let normalizeFullPath (path: string) = - JS.Path.resolve(path).Replace('\\', '/') + JS.path.resolve(path).Replace('\\', '/') + +let getRelativePath (path: string) (pathTo: string) = + JS.path.relative(path, pathTo).Replace('\\', '/') -let getRelativePath (pathFrom: string) (pathTo: string) = - JS.Path.relative(pathFrom, pathTo).Replace('\\', '/') +let getHomePath () = + JS.os.homedir() + +let getDirFiles (path: string) (extension: string) = + JS.util.getDirFiles(path) + |> Array.filter (fun x -> x.EndsWith(extension)) + |> Array.map (fun x -> x.Replace('\\', '/')) + |> Array.sort #endif @@ -122,17 +160,17 @@ module Path = else path.Substring(0, i) + ext let GetFileName (path: string) = - let normPath = path.Replace("\\", "/").TrimEnd('/') - let i = normPath.LastIndexOf("/") + let normPath = path.Replace('\\', '/').TrimEnd('/') + let i = normPath.LastIndexOf('/') normPath.Substring(i + 1) let GetFileNameWithoutExtension (path: string) = let path = GetFileName path - let i = path.LastIndexOf(".") + let i = path.LastIndexOf('.') path.Substring(0, i) let GetDirectoryName (path: string) = - let normPath = path.Replace("\\", "/") - let i = normPath.LastIndexOf("/") + let normPath = path.Replace('\\', '/') + let i = normPath.LastIndexOf('/') if i < 0 then "" else normPath.Substring(0, i) diff --git a/src/fable-standalone/test/bench-compiler/ProjectParser.fs b/src/fable-standalone/test/bench-compiler/ProjectParser.fs index 20a4e05342..0ca4233965 100644 --- a/src/fable-standalone/test/bench-compiler/ProjectParser.fs +++ b/src/fable-standalone/test/bench-compiler/ProjectParser.fs @@ -4,34 +4,96 @@ open Fable.Compiler.Platform open System.Collections.Generic open System.Text.RegularExpressions +type ReferenceType = + | ProjectReference of string + | PackageReference of string * string + let (|Regex|_|) (pattern: string) (input: string) = let m = Regex.Match(input, pattern) - if m.Success then - let mutable groups = [] - for i = m.Groups.Count - 1 downto 0 do - groups <- m.Groups.[i].Value::groups - Some groups + if m.Success then Some [for x in m.Groups -> x.Value] else None -let parseCompilerOptions projectText = - - // get project type - let m = Regex.Match(projectText, @"]*>([^<]*)<\/OutputType[^>]*>") - let target = if m.Success then m.Groups.[1].Value.Trim().ToLowerInvariant() else "" - - // get warning level - let m = Regex.Match(projectText, @"]*>([^<]*)<\/WarningLevel[^>]*>") - let warnLevel = if m.Success then m.Groups.[1].Value.Trim() else "" - - // get treat warnings as errors - let m = Regex.Match(projectText, @"]*>([^<]*)<\/TreatWarningsAsErrors[^>]*>") - let treatWarningsAsErrors = m.Success && m.Groups.[1].Value.Trim().ToLowerInvariant() = "true" +let getXmlWithoutComments xml = + Regex.Replace(xml, @"", "") + +let getXmlTagContents tag xml = + let pattern = sprintf @"<%s[^>]*>([^<]*)<\/%s[^>]*>" tag tag + Regex.Matches(xml, pattern) + |> Seq.map (fun m -> m.Groups.[1].Value.Trim()) + +let getXmlTagContentsFirstOrDefault tag defaultValue xml = + defaultArg (getXmlTagContents tag xml |> Seq.tryHead) defaultValue + +let getXmlTagAttributes1 tag attr1 xml = + let pattern = sprintf """<%s\s+[^>]*%s\s*=\s*("[^"]*|'[^']*)""" tag attr1 + Regex.Matches(xml, pattern) + |> Seq.map (fun m -> m.Groups.[1].Value.TrimStart('"').TrimStart(''').Trim()) + +let getXmlTagAttributes2 tag attr1 attr2 xml = + let pattern = sprintf """<%s\s+[^>]*%s\s*=\s*("[^"]*|'[^']*)[^>]*%s\s*=\s*("[^"]*|'[^']*)""" tag attr1 attr2 + Regex.Matches(xml, pattern) + |> Seq.map (fun m -> + m.Groups.[1].Value.TrimStart('"').TrimStart(''').Trim(), + m.Groups.[2].Value.TrimStart('"').TrimStart(''').Trim()) + +let isSystemPackage (pkgName: string) = + pkgName.StartsWith("System.") + || pkgName.StartsWith("Microsoft.") + || pkgName.StartsWith("runtime.") + || pkgName = "NETStandard.Library" + || pkgName = "FSharp.Core" + || pkgName = "Fable.Core" + +let parsePackageSpec nuspecPath = + // get package spec xml + let packageXml = readAllText nuspecPath + // get package dependencies + let references = + packageXml + |> getXmlWithoutComments + |> getXmlTagAttributes2 "dependency" "id" "version" + |> Seq.map PackageReference + |> Seq.toArray + references + +let resolvePackage (pkgName, pkgVersion) = + if not (isSystemPackage pkgName) then + let homePath = getHomePath().Replace('\\', '/') + let nugetPath = sprintf ".nuget/packages/%s/%s" pkgName pkgVersion + let pkgPath = Path.Combine(homePath, nugetPath.ToLowerInvariant()) + let libPath = Path.Combine(pkgPath, "lib") + let fablePath = Path.Combine(pkgPath, "fable") + let binaryPaths = getDirFiles libPath ".dll" + let nuspecPaths = getDirFiles pkgPath ".nuspec" + let fsprojPaths = getDirFiles fablePath ".fsproj" + if Array.isEmpty nuspecPaths then + printfn "ERROR: Cannot find package %s" pkgPath + let binaryOpt = binaryPaths |> Array.tryLast + let dependOpt = nuspecPaths |> Array.tryLast |> Option.map parsePackageSpec + let fsprojOpt = fsprojPaths |> Array.tryLast |> Option.map ProjectReference + let pkgRefs, dllPaths = + match binaryOpt, dependOpt, fsprojOpt with + | _, _, Some projRef -> + [| projRef |], [||] + | Some dllRef, Some dependencies, _ -> + dependencies, [| dllRef |] + | _, _, _ -> [||], [||] + pkgRefs, dllPaths + else [||], [||] + +let parseCompilerOptions projectXml = + // get project settings, + let target = projectXml |> getXmlTagContentsFirstOrDefault "OutputType" "" + let langVersion = projectXml |> getXmlTagContentsFirstOrDefault "LangVersion" "" + let warnLevel = projectXml |> getXmlTagContentsFirstOrDefault "WarningLevel" "" + let treatWarningsAsErrors = projectXml |> getXmlTagContentsFirstOrDefault "TreatWarningsAsErrors" "" // get conditional defines let defines = - Regex.Matches(projectText, @"]*>([^<]*)<\/DefineConstants[^>]*>") - |> Seq.collect (fun m -> m.Groups.[1].Value.Split(';')) - |> Seq.append ["FABLE_COMPILER"] + projectXml + |> getXmlTagContents "DefineConstants" + |> Seq.collect (fun s -> s.Split(';')) + |> Seq.append ["FABLE_COMPILER"; "FABLE_COMPILER_JS"] |> Seq.map (fun s -> s.Trim()) |> Seq.distinct |> Seq.except ["$(DefineConstants)"; ""] @@ -39,8 +101,9 @@ let parseCompilerOptions projectText = // get disabled warnings let nowarns = - Regex.Matches(projectText, @"]*>([^<]*)<\/NoWarn[^>]*>") - |> Seq.collect (fun m -> m.Groups.[1].Value.Split(';')) + projectXml + |> getXmlTagContents "NoWarn" + |> Seq.collect (fun s -> s.Split(';')) |> Seq.map (fun s -> s.Trim()) |> Seq.distinct |> Seq.except ["$(NoWarn)"; ""] @@ -48,8 +111,9 @@ let parseCompilerOptions projectText = // get warnings as errors let warnAsErrors = - Regex.Matches(projectText, @"]*>([^<]*)<\/WarningsAsErrors[^>]*>") - |> Seq.collect (fun m -> m.Groups.[1].Value.Split(';')) + projectXml + |> getXmlTagContents "WarningsAsErrors" + |> Seq.collect (fun s -> s.Split(';')) |> Seq.map (fun s -> s.Trim()) |> Seq.distinct |> Seq.except ["$(WarningsAsErrors)"; ""] @@ -57,8 +121,9 @@ let parseCompilerOptions projectText = // get other flags let otherFlags = - Regex.Matches(projectText, @"]*>([^<]*)<\/OtherFlags[^>]*>") - |> Seq.collect (fun m -> m.Groups.[1].Value.Split(' ')) + projectXml + |> getXmlTagContents "OtherFlags" + |> Seq.collect (fun s -> s.Split(' ')) |> Seq.map (fun s -> s.Trim()) |> Seq.distinct |> Seq.except ["$(OtherFlags)"; ""] @@ -67,9 +132,11 @@ let parseCompilerOptions projectText = let otherOptions = [| if target.Length > 0 then yield "--target:" + target + if langVersion.Length > 0 then + yield "--langversion:" + langVersion if warnLevel.Length > 0 then yield "--warn:" + warnLevel - if treatWarningsAsErrors then + if treatWarningsAsErrors = "true" then yield "--warnaserror+" for d in defines do yield "-d:" + d for n in nowarns do yield "--nowarn:" + n @@ -78,55 +145,67 @@ let parseCompilerOptions projectText = |] otherOptions -let parseProjectScript projectPath = - let projectFileName = Path.GetFileName projectPath - let projectText = readAllText projectPath - let projectDir = Path.GetDirectoryName projectPath +let makeFullPath projectFileDir (path: string) = + let path = path.Replace('\\', '/') + let isAbsolutePath (path: string) = + path.StartsWith('/') || path.IndexOf(':') = 1 + if isAbsolutePath path then path + else Path.Combine(projectFileDir, path) + |> normalizeFullPath + +let parseProjectScript projectFilePath = + let projectXml = readAllText projectFilePath + let projectDir = Path.GetDirectoryName projectFilePath let dllRefs, srcFiles = - (([||], [||]), projectText.Split('\n')) + (([||], [||]), projectXml.Split('\n')) ||> Array.fold (fun (dllRefs, srcFiles) line -> - let line = line.Trim() match line.Trim() with | Regex @"^#r\s+""(.*?)""$" [_;path] when not(path.EndsWith("Fable.Core.dll")) -> - Array.append [|Path.Combine(projectDir, path)|] dllRefs, srcFiles + Array.append [| Path.Combine(projectDir, path) |] dllRefs, srcFiles | Regex @"^#load\s+""(.*?)""$" [_;path] -> - dllRefs, Array.append [|Path.Combine(projectDir, path)|] srcFiles + dllRefs, Array.append [| Path.Combine(projectDir, path) |] srcFiles | _ -> dllRefs, srcFiles) let projectRefs = [||] - let sourceFiles = Array.append srcFiles [|Path.GetFileName projectPath|] - let otherOptions = [| "--define:FABLE_COMPILER" |] - (projectFileName, dllRefs, projectRefs, sourceFiles, otherOptions) - -let parseProjectFile projectPath = - let projectFileName = Path.GetFileName projectPath - let projectText = readAllText projectPath - - // remove all comments - let projectText = Regex.Replace(projectText, @"", "") + let sourceFiles = Array.append srcFiles [| Path.GetFileName projectFilePath |] + let otherOptions = [| "--define:FABLE_COMPILER"; "--define:FABLE_COMPILER_JS" |] + (projectRefs, dllRefs, sourceFiles, otherOptions) + +let parseProjectFile projectFilePath = + // get project xml without any comments + let projectXml = readAllText projectFilePath |> getXmlWithoutComments + let projectDir = Path.GetDirectoryName projectFilePath + + // get package references + let packageRefs = + projectXml + |> getXmlTagAttributes2 "PackageReference" "Include" "Version" + |> Seq.map PackageReference + |> Seq.toArray // get project references let projectRefs = - Regex.Matches(projectText, @"]*Include\s*=\s*(""[^""]*|'[^']*)") - |> Seq.map (fun m -> m.Groups.[1].Value.TrimStart('"').TrimStart(''').Trim().Replace("\\", "/")) + projectXml + |> getXmlTagAttributes1 "ProjectReference" "Include" + |> Seq.map (makeFullPath projectDir >> ProjectReference) |> Seq.toArray // replace some variables - let projectText = projectText.Replace(@"$(MSBuildProjectDirectory)", ".") - let m = Regex.Match(projectText, @"]*>([^<]*)<\/FSharpSourcesRoot[^>]*>") - let sourcesRoot = if m.Success then m.Groups.[1].Value.Replace("\\", "/") else "" - let projectText = projectText.Replace(@"$(FSharpSourcesRoot)", sourcesRoot) + let projectXml = projectXml.Replace("$(MSBuildProjectDirectory)", ".") + let sourceRoot = projectXml |> getXmlTagContentsFirstOrDefault "FSharpSourcesRoot" "" + let projectXml = projectXml.Replace("$(FSharpSourcesRoot)", sourceRoot.Replace('\\', '/')) // get source files - let sourceFilesRegex = @"]*Include\s*=\s*(""[^""]*|'[^']*)" let sourceFiles = - Regex.Matches(projectText, sourceFilesRegex) - |> Seq.map (fun m -> m.Groups.[1].Value.TrimStart('"').TrimStart(''').Trim().Replace("\\", "/")) + projectXml + |> getXmlTagAttributes1 "Compile" "Include" + |> Seq.map (makeFullPath projectDir) |> Seq.toArray let dllRefs = [||] - let otherOptions = parseCompilerOptions projectText - (projectFileName, dllRefs, projectRefs, sourceFiles, otherOptions) + let projectRefs = Array.append projectRefs packageRefs + let otherOptions = parseCompilerOptions projectXml + (projectRefs, dllRefs, sourceFiles, otherOptions) let makeHashSetIgnoreCase () = let equalityComparerIgnoreCase = @@ -135,45 +214,38 @@ let makeHashSetIgnoreCase () = member __.GetHashCode(x) = hash (x.ToLowerInvariant()) } HashSet(equalityComparerIgnoreCase) -let dedupProjectRefs (projSet: HashSet) projectRefs = - let newRefs = projectRefs |> Array.filter (fun x -> projSet.Contains(x) |> not) - projSet.UnionWith(newRefs) +let dedupReferences (refSet: HashSet) references = + let refName = function + | ProjectReference path -> path + | PackageReference (pkgName, pkgVersion) -> pkgName + "," + pkgVersion + let newRefs = references |> Array.filter (refName >> refSet.Contains >> not) + refSet.UnionWith(newRefs |> Array.map refName) newRefs -let dedupFileNames (fileSet: HashSet) fileNames = - let padName (fileName: string) = - let pos = fileName.LastIndexOf(".") - let nm = if pos < 0 then fileName else fileName.Substring(0, pos) - let ext = if pos < 0 then "" else fileName.Substring(pos) - nm + "_" + ext - let rec dedup fileName = - if fileSet.Contains(fileName) then - dedup (padName fileName) - else - fileSet.Add(fileName) |> ignore - fileName - fileNames |> Array.map dedup - -let rec parseProject (projSet: HashSet) (projectPath: string) = - let (projectFileName, dllRefs, projectRefs, sourceFiles, otherOptions) = - if projectPath.EndsWith(".fsx") - then parseProjectScript projectPath - else parseProjectFile projectPath - - let projectFileDir = Path.GetDirectoryName projectPath - let isAbsolutePath (path: string) = path.StartsWith("/") || path.IndexOf(":") = 1 - let makePath path = - if isAbsolutePath path then path - else Path.Combine(projectFileDir, path) - |> normalizeFullPath - - let sourcePaths = sourceFiles |> Array.map makePath - let sourceTexts = sourcePaths |> Array.map readAllText - - // parse and combine all referenced projects into one big project - let parsedProjects = projectRefs |> Array.map makePath |> dedupProjectRefs projSet |> Array.map (parseProject projSet) - let sourcePaths = sourcePaths |> Array.append (parsedProjects |> Array.collect (fun (_,_,x,_,_) -> x)) - let sourceTexts = sourceTexts |> Array.append (parsedProjects |> Array.collect (fun (_,_,_,x,_) -> x)) - let otherOptions = otherOptions |> Array.append (parsedProjects |> Array.collect (fun (_,_,_,_,x) -> x)) - - (projectFileName, dllRefs, sourcePaths, sourceTexts, otherOptions |> Array.distinct) +let parseProject projectFilePath = + + let rec parseProject (refSet: HashSet) (projectRef: ReferenceType) = + let projectRefs, dllPaths, sourcePaths, otherOptions = + match projectRef with + | ProjectReference path -> + if path.EndsWith(".fsx") + then parseProjectScript path + else parseProjectFile path + | PackageReference (pkgName, pkgVersion) -> + let pkgRefs, dllPaths = resolvePackage (pkgName, pkgVersion) + pkgRefs, dllPaths, [||], [||] + + // parse and combine all referenced projects into one big project + let parseResult = projectRefs |> dedupReferences refSet |> Array.map (parseProject refSet) + let dllPaths = dllPaths |> Array.append (parseResult |> Array.collect (fun (x,_,_) -> x)) + let sourcePaths = sourcePaths |> Array.append (parseResult |> Array.collect (fun (_,x,_) -> x)) + let otherOptions = otherOptions |> Array.append (parseResult |> Array.collect (fun (_,_,x) -> x)) + + (dllPaths, sourcePaths, otherOptions) + + let refSet = makeHashSetIgnoreCase () + let projectRef = ProjectReference projectFilePath + let dllPaths, sourcePaths, otherOptions = parseProject refSet projectRef + (dllPaths |> Array.distinct, + sourcePaths |> Array.distinct, + otherOptions |> Array.distinct) diff --git a/src/fable-standalone/test/bench-compiler/app.fs b/src/fable-standalone/test/bench-compiler/app.fs index 3436474bbf..7a910f63a1 100644 --- a/src/fable-standalone/test/bench-compiler/app.fs +++ b/src/fable-standalone/test/bench-compiler/app.fs @@ -4,13 +4,12 @@ open Fable.Compiler.Platform open Fable.Compiler.ProjectParser let references = Fable.Standalone.Metadata.references_core -let metadataPath = Path.Combine(__SOURCE_DIRECTORY__, "../../../fable-metadata/lib/") // .NET BCL binaries +let metadataPath = "../../../fable-metadata/lib/" // .NET BCL binaries let printErrors showWarnings (errors: Fable.Standalone.Error[]) = let printError (e: Fable.Standalone.Error) = let errorType = (if e.IsWarning then "Warning" else "Error") - printfn "%s (%d,%d--%d,%d): %s: %s" e.FileName e.EndLineAlternate - e.StartColumn e.EndLineAlternate e.EndColumn errorType e.Message + printfn "%s (%d,%d): %s: %s" e.FileName e.StartLineAlternate e.StartColumn errorType e.Message let warnings, errors = errors |> Array.partition (fun e -> e.IsWarning) let hasErrors = not (Array.isEmpty errors) if showWarnings then @@ -23,20 +22,19 @@ type CmdLineOptions = { commonjs: bool optimize: bool watchMode: bool + sourceMaps: bool } -let parseFiles projectPath outDir options = +let parseFiles projectFileName outDir options = // parse project - let projSet = makeHashSetIgnoreCase () - let (projectFileName, dllRefs, fileNames, sources, otherOptions) = parseProject projSet projectPath - - // dedup file names - let fileSet = makeHashSetIgnoreCase () - let fileNames = dedupFileNames fileSet fileNames - - // find reference dlls - let dllRefMap = dllRefs |> Seq.map (fun x -> Path.GetFileName x, x) |> Map - let references = dllRefs |> Array.map Path.GetFileNameWithoutExtension |> Array.append references + let (dllRefs, fileNames, otherOptions) = parseProject projectFileName + let sources = fileNames |> Array.map readAllText + let nugetPath = Path.Combine(getHomePath().Replace('\\', '/'), ".nuget") + let fileNames = fileNames |> Array.map (fun x -> x.Replace(nugetPath, "")) + + // find referenced dlls + let dllRefMap = dllRefs |> Array.rev |> Array.map (fun x -> Path.GetFileName x, x) |> Map + let references = Map.toArray dllRefMap |> Array.map fst |> Array.append references let findDllPath dllName = Map.tryFind dllName dllRefMap |> Option.defaultValue (metadataPath + dllName) let readAllBytes dllName = findDllPath dllName |> readAllBytes @@ -45,13 +43,13 @@ let parseFiles projectPath outDir options = let optimizeFlag = "--optimize" + (if options.optimize then "+" else "-") let otherOptions = otherOptions |> Array.append [| optimizeFlag |] let createChecker () = fable.CreateChecker(references, readAllBytes, otherOptions) - let ms0, checker = measureTime createChecker () + let checker, ms0 = measureTime createChecker () printfn "--------------------------------------------" printfn "InteractiveChecker created in %d ms" ms0 // parse F# files to AST let parseFSharpProject () = fable.ParseFSharpProject(checker, projectFileName, fileNames, sources) - let ms1, parseRes = measureTime parseFSharpProject () + let parseRes, ms1 = measureTime parseFSharpProject () printfn "Project: %s, FCS time: %d ms" projectFileName ms1 printfn "--------------------------------------------" let showWarnings = true // turning off warnings for cleaner output @@ -66,19 +64,19 @@ let parseFiles projectPath outDir options = // Fable (F# to Babel) let fableLibraryDir = "fable-library" - let parseFable (res, fileName) = fable.CompileToBabelAst(fableLibraryDir, res, fileName, options.optimize) + let parseFable (res, fileName) = fable.CompileToBabelAst(fableLibraryDir, res, fileName) let trimPath (path: string) = path.Replace("../", "").Replace("./", "").Replace(":", "") - let projDir = projectPath |> normalizeFullPath |> Path.GetDirectoryName + let projDir = projectFileName |> normalizeFullPath |> Path.GetDirectoryName for fileName in fileNames do // print F# AST if false then - let fsAstStr = fable.FSharpAstToString(parseRes, fileName, options.optimize) + let fsAstStr = fable.FSharpAstToString(parseRes, fileName) printfn "%s Typed AST: %s" fileName fsAstStr // transform F# AST to Babel AST - let ms2, res = measureTime parseFable (parseRes, fileName) + let res, ms2 = measureTime parseFable (parseRes, fileName) printfn "File: %s, Fable time: %d ms" fileName ms2 res.FableErrors |> printErrors showWarnings @@ -96,13 +94,14 @@ let parseArguments (argv: string[]) = let usage = "Usage: fable [--options]" let opts, args = argv |> Array.partition (fun s -> s.StartsWith("--")) match args with - | [| projectPath; outDir |] -> + | [| projectFileName; outDir |] -> let options = { commonjs = opts |> Array.contains "--commonjs" optimize = opts |> Array.contains "--optimize-fcs" watchMode = opts |> Array.contains "--watch" + sourceMaps = opts |> Array.contains "--sourceMaps" } - parseFiles projectPath outDir options + parseFiles projectFileName outDir options | _ -> printfn "%s" usage [] diff --git a/src/fable-standalone/test/bench-compiler/bench-compiler.fsproj b/src/fable-standalone/test/bench-compiler/bench-compiler.fsproj index e748402337..491b1d651c 100644 --- a/src/fable-standalone/test/bench-compiler/bench-compiler.fsproj +++ b/src/fable-standalone/test/bench-compiler/bench-compiler.fsproj @@ -3,27 +3,30 @@ Exe netcoreapp2.1 + Major $(DefineConstants);DOTNET_FILE_SYSTEM $(OtherFlags) --crossoptimize- true - + - - + + diff --git a/src/fable-standalone/test/bench-compiler/package-lock.json b/src/fable-standalone/test/bench-compiler/package-lock.json new file mode 100644 index 0000000000..48e341a095 --- /dev/null +++ b/src/fable-standalone/test/bench-compiler/package-lock.json @@ -0,0 +1,3 @@ +{ + "lockfileVersion": 1 +} diff --git a/src/fable-standalone/test/bench-compiler/package.json b/src/fable-standalone/test/bench-compiler/package.json index e7b91a299a..93d29de38e 100644 --- a/src/fable-standalone/test/bench-compiler/package.json +++ b/src/fable-standalone/test/bench-compiler/package.json @@ -1,5 +1,6 @@ { "private": true, + "type": "module", "scripts": { "babel": "node ../../../../node_modules/@babel/cli/bin/babel --plugins @babel/plugin-transform-modules-commonjs", "build-library": "npm run babel -- ../../../../build/fable-library --out-dir out-lib/fable-library", @@ -7,28 +8,36 @@ "build-fable-js": "fable bench-compiler.fsproj out-node --commonjs", "build-dotnet": "dotnet run -c Release bench-compiler.fsproj out-node && npm run build-transform", "build-dotnet-opt": "dotnet run -c Release bench-compiler.fsproj out-node --optimize-fcs && npm run build-transform", - "build-transform": "node transform bench-compiler.fsproj out-node ../../../../build/fable-library --commonjs", - "build-node": "node out-node/app bench-compiler.fsproj out-node2 && npm run build-node-transform", - "build-node-transform": "node transform bench-compiler.fsproj out-node2 ../../../../build/fable-library --commonjs", + "build-transform": "node transform bench-compiler.fsproj out-node ../../../../build/fable-library --sourceMaps", + "postbuild-transform": "npm run rollup-bundle", + "build-node": "node dist/bundle.js bench-compiler.fsproj out-node2 && npm run build-node-transform", + "build-node-es": "node out-node/app.js bench-compiler.fsproj out-node2 && npm run build-node-transform", + "build-node-transform": "node transform bench-compiler.fsproj out-node2 ../../../../build/fable-library --sourceMaps", "compile-native": "dotnet publish -c Release -r win-x64", - "build-native": "bin/Release/netcoreapp2.1/win-x64/native/bench-compiler bench-compiler.fsproj out-node && npm run build-transform", - "build-test-native": "bin/Release/netcoreapp2.1/win-x64/native/bench-compiler ../../../../../fable-test/fable-test.fsproj out-test && npm run build-test-transform", - "build-tests-native": "bin/Release/netcoreapp2.1/win-x64/native/bench-compiler ../../../../tests/Main/Fable.Tests.fsproj out-tests && npm run build-tests-transform", + "native": "cd . && \"bin/Release/netcoreapp2.1/win-x64/native/bench-compiler\"", + "build-native": "npm run native bench-compiler.fsproj out-node && npm run build-transform", + "build-test-native": "npm run native ../../../../../fable-test/fable-test.fsproj out-test && npm run build-test-transform", + "build-tests-native": "npm run native ../../../../tests/Main/Fable.Tests.fsproj out-tests && npm run build-tests-transform", "splitter": "node ../../../../node_modules/fable-splitter/dist/cli --commonjs", - "webpack": "node ../../../../node_modules/webpack-cli/bin/cli.js -p --entry ./out-node/app.js --output ./out/bundle.js --target node", - "build-test-node": "node out-node/app ../../../../../fable-test/fable-test.fsproj out-test && npm run build-test-transform", + "rollup-bundle": "npx rollup out-node/app.js --file dist/bundle.js --format esm", + "terser-bundle": "npx terser dist/bundle.js -o dist/bundle.min.js --mangle --compress", + "webpack-bundle": "node ../../../../node_modules/webpack-cli/bin/cli.js -p --entry ./dist/bundle.js --output ./dist/bundle.min.js --target node", + "build-test-node": "node out-node/app.js ../../../../../fable-test/fable-test.fsproj out-test && npm run build-test-transform", "build-test-dotnet": "dotnet run -c Release ../../../../../fable-test/fable-test.fsproj out-test && npm run build-test-transform", "build-test-dotnet-opt": "dotnet run -c Release ../../../../../fable-test/fable-test.fsproj out-test --optimize-fcs && npm run build-test-transform", - "build-test-transform": "node transform ../../../../../fable-test/fable-test.fsproj out-test ../../../../build/fable-library --commonjs", + "build-test-transform": "node transform ../../../../../fable-test/fable-test.fsproj out-test ../../../../build/fable-library --sourceMaps", "test-node": "node ./out-test/src/test.js", - "build-tests-node": "node out-node/app ../../../../tests/Main/Fable.Tests.fsproj out-tests && npm run build-tests-transform", + "build-tests-node": "node out-node/app.js ../../../../tests/Main/Fable.Tests.fsproj out-tests && npm run build-tests-transform", "build-tests-dotnet": "dotnet run -c Release ../../../../tests/Main/Fable.Tests.fsproj out-tests && npm run build-tests-transform", "build-tests-dotnet-opt": "dotnet run -c Release ../../../../tests/Main/Fable.Tests.fsproj out-tests --optimize-fcs && npm run build-tests-transform", - "build-tests-transform": "node transform ../../../../tests/Main/Fable.Tests.fsproj out-tests ../../../../build/fable-library --commonjs", + "build-tests-transform": "node transform ../../../../tests/Main/Fable.Tests.fsproj out-tests ../../../../build/fable-library --sourceMaps", "mocha": "node ../../../../node_modules/mocha/bin/mocha --colors", "tests": "npm run mocha out-tests/Main.js", - "profile": "node --prof out-node/app bench-compiler.fsproj out-node2", - "process": "node --prof-process --preprocess -j isolate-*.log > profile.v8log.json", + "profile": "node --prof dist/bundle.js bench-compiler.fsproj out-node2", + "cpu-prof": "node --cpu-prof --cpu-prof-dir=out-prof dist/bundle.js bench-compiler.fsproj out-node2", + "heap-prof": "node --heap-prof dist/bundle.js bench-compiler.fsproj out-node2", + "prof-process": "node --prof-process isolate-*.log > profile.log", + "prof-preprocess": "node --prof-process --preprocess isolate-*.log > profile.v8log.json", "flamegraph": "speedscope profile.v8log.json", "trace": "node --trace-deopt out-node/app bench-compiler.fsproj out-node2 > deopt.txt" } diff --git a/src/fable-standalone/test/bench-compiler/transform.js b/src/fable-standalone/test/bench-compiler/transform.js index 9cf451ba63..4db1e78ffd 100644 --- a/src/fable-standalone/test/bench-compiler/transform.js +++ b/src/fable-standalone/test/bench-compiler/transform.js @@ -1,132 +1,144 @@ -const fs = require("fs"); -const Path = require("path"); -const Babel = require("@babel/core"); -const BabelPlugins = require("fable-babel-plugins"); +import * as fs from "fs"; +import * as Path from "path"; +import Babel from "@babel/core"; +import BabelPlugins from "fable-babel-plugins"; const customPlugins = [ - BabelPlugins.getRemoveUnneededNulls(), - BabelPlugins.getTransformMacroExpressions(Babel.template) + BabelPlugins.getRemoveUnneededNulls(), + BabelPlugins.getTransformMacroExpressions(Babel.template) ]; const FSHARP_EXT = /\.(fs|fsx)$/i; const JAVASCRIPT_EXT = /\.js$/i; function ensureArray(obj) { - return (Array.isArray(obj) ? obj : obj != null ? [obj] : []); + return (Array.isArray(obj) ? obj : obj != null ? [obj] : []); } function ensureDirExists(dir, cont) { - if (fs.existsSync(dir)) { - if (typeof cont === "function") { cont(); } - } else { - ensureDirExists(Path.dirname(dir), () => { - if (!fs.existsSync(dir)) { fs.mkdirSync(dir); } - if (typeof cont === "function") { cont(); } - }); - } + if (fs.existsSync(dir)) { + if (typeof cont === "function") { cont(); } + } else { + ensureDirExists(Path.dirname(dir), () => { + if (!fs.existsSync(dir)) { fs.mkdirSync(dir); } + if (typeof cont === "function") { cont(); } + }); + } } const uniquePaths = new Map(); function ensureUniquePath(sourcePath, outPath) { - while (uniquePaths.has(outPath) && uniquePaths.get(outPath) !== sourcePath) { - var i = outPath.lastIndexOf("."); - outPath = (i < 0) ? outPath + "_" : outPath.substr(0, i) + "_" + outPath.substr(i); - } - if (!uniquePaths.has(outPath)) { uniquePaths.set(outPath, sourcePath); } - return outPath; + while (uniquePaths.has(outPath) && uniquePaths.get(outPath) !== sourcePath) { + var i = outPath.lastIndexOf("."); + outPath = (i < 0) ? outPath + "_" : outPath.substr(0, i) + "_" + outPath.substr(i); + } + if (!uniquePaths.has(outPath)) { uniquePaths.set(outPath, sourcePath); } + return outPath; } function isRelativePath(path) { - return path.startsWith("./") || path.startsWith("../"); + return path.startsWith("./") || path.startsWith("../"); } function getRelPath(sourcePath, importPath, outPath, projDir, outDir) { - if (isRelativePath(importPath)) { - importPath = Path.resolve(Path.dirname(sourcePath), importPath); - } - let relPath = Path.relative(projDir, importPath).replace(/\\/g, "/"); - relPath = relPath.replace(/\.\.\//g, "").replace(/\.\//g, "").replace(/\:/g, ""); - relPath = Path.relative(Path.dirname(outPath), Path.join(outDir, relPath)); - relPath = relPath.replace(/\\/g, "/").replace(FSHARP_EXT, ".js"); - relPath = relPath.match(JAVASCRIPT_EXT) ? relPath : relPath + ".js"; - relPath = relPath.startsWith("..") ? relPath : "./" + relPath; - return relPath; + if (isRelativePath(importPath)) { + importPath = Path.resolve(Path.dirname(sourcePath), importPath); + } + let relPath = Path.relative(projDir, importPath).replace(/\\/g, "/"); + relPath = relPath.replace(/\.\.\//g, "").replace(/\.\//g, "").replace(/\:/g, ""); + relPath = Path.relative(Path.dirname(outPath), Path.join(outDir, relPath)); + relPath = relPath.replace(/\\/g, "/").replace(FSHARP_EXT, ".js"); + relPath = relPath.match(JAVASCRIPT_EXT) ? relPath : relPath + ".js"; + relPath = relPath.startsWith("..") ? relPath : "./" + relPath; + return relPath; } function getJsImport(sourcePath, importPath, outPath, projDir, outDir, babelOptions) { - const relPath = getRelPath(sourcePath, importPath, outPath, projDir, outDir); - let jsPath = isRelativePath(importPath) ? - Path.resolve(Path.dirname(sourcePath), importPath) : importPath; - jsPath = jsPath.match(JAVASCRIPT_EXT) ? jsPath : jsPath + ".js"; - outPath = Path.resolve(Path.dirname(outPath), relPath); - // if not already done, transform and save javascript imports - if (!uniquePaths.has(outPath) || uniquePaths.get(outPath) !== jsPath) { - outPath = ensureUniquePath(jsPath, outPath); - const resAst = Babel.transformFileSync(jsPath, { ast: true, code: false }); - fixImportPaths(resAst.ast.program, jsPath, outPath, projDir, outDir, outDir, babelOptions); - const resCode = Babel.transformFromAstSync(resAst.ast, null, babelOptions); - ensureDirExists(Path.dirname(outPath)); - fs.writeFileSync(outPath, resCode.code); - } - return relPath; + const relPath = getRelPath(sourcePath, importPath, outPath, projDir, outDir); + let jsPath = isRelativePath(importPath) ? + Path.resolve(Path.dirname(sourcePath), importPath) : importPath; + jsPath = jsPath.match(JAVASCRIPT_EXT) ? jsPath : jsPath + ".js"; + outPath = Path.resolve(Path.dirname(outPath), relPath); + // if not already done, transform and save javascript imports + if (!uniquePaths.has(outPath) || uniquePaths.get(outPath) !== jsPath) { + outPath = ensureUniquePath(jsPath, outPath); + const resAst = Babel.transformFileSync(jsPath, { ast: true, code: false }); + fixImportPaths(resAst.ast.program, jsPath, outPath, projDir, outDir, outDir, babelOptions); + const resCode = Babel.transformFromAstSync(resAst.ast, null, babelOptions); + ensureDirExists(Path.dirname(outPath)); + fs.writeFileSync(outPath, resCode.code); + } + return relPath; } function fixImportPaths(babelAst, sourcePath, outPath, projDir, outDir, libDir, babelOptions) { - const decls = ensureArray(babelAst.body); - for (const decl of decls) { - if (decl.source != null && typeof decl.source.value === "string") { - let importPath = decl.source.value; - if (importPath.startsWith("fable-library/")) { - importPath = Path.join(libDir, importPath.replace(/^fable-library\//, "")); - decl.source.value = getJsImport(sourcePath, importPath, outPath, Path.dirname(libDir), outDir, babelOptions); - } else if (importPath.match(FSHARP_EXT)) { - decl.source.value = getRelPath(sourcePath, importPath, outPath, projDir, outDir); - } else if (isRelativePath(importPath) || Path.isAbsolute(importPath)) { - decl.source.value = getJsImport(sourcePath, importPath, outPath, projDir, outDir, babelOptions); - } - } + const decls = ensureArray(babelAst.body); + for (const decl of decls) { + if (decl.source != null && typeof decl.source.value === "string") { + let importPath = decl.source.value; + if (importPath.startsWith("fable-library/")) { + importPath = Path.join(libDir, importPath.replace(/^fable-library\//, "")); + decl.source.value = getJsImport(sourcePath, importPath, outPath, Path.dirname(libDir), outDir, babelOptions); + } else if (importPath.match(FSHARP_EXT)) { + decl.source.value = getRelPath(sourcePath, importPath, outPath, projDir, outDir); + } else if (isRelativePath(importPath) || Path.isAbsolute(importPath)) { + decl.source.value = getJsImport(sourcePath, importPath, outPath, projDir, outDir, babelOptions); + } } + } } function getFilePaths(dir) { - const subdirs = fs.readdirSync(dir); - const files = subdirs.map((subdir) => { - const res = Path.resolve(dir, subdir); - return fs.statSync(res).isDirectory() ? getFilePaths(res) : res; - }); - return files.reduce((acc, file) => acc.concat(file), []); + const subdirs = fs.readdirSync(dir); + const files = subdirs.map((subdir) => { + const res = Path.resolve(dir, subdir); + return fs.statSync(res).isDirectory() ? getFilePaths(res) : res; + }); + return files.reduce((acc, file) => acc.concat(file), []); } function main() { - if (process.argv.length < 5) { - console.log("Usage: node transform [--commonjs]"); - return; - } - const projPath = Path.resolve(process.argv[2]); - const projDir = Path.dirname(projPath) - const outDir = Path.resolve(process.argv[3]); - const libDir = Path.resolve(process.argv[4]); - const commonjs = process.argv.find(v => v === "--commonjs"); - const babelOptions = commonjs ? - { plugins: customPlugins.concat("@babel/plugin-transform-modules-commonjs") } : - { plugins: customPlugins }; - - console.log("Compiling to " + (commonjs ? "commonjs" : "ES2015 modules") + "...") - - const outPaths = getFilePaths(outDir); - for (const outPath of outPaths) { - if (outPath.endsWith(".json")) { - const babelJson = fs.readFileSync(outPath, "utf8"); - const babelAst = JSON.parse(babelJson); - const sourcePath = babelAst.fileName; - fixImportPaths(babelAst, sourcePath, outPath, projDir, outDir, libDir, babelOptions); - const res = Babel.transformFromAstSync(babelAst, null, babelOptions); - const jsPath = outPath.replace(/\.json$/, ".js") - fs.renameSync(outPath, jsPath); - fs.writeFileSync(jsPath, res.code); - } + if (process.argv.length < 5) { + console.log("Usage: node transform [--commonjs]"); + return; + } + const projPath = Path.resolve(process.argv[2]); + const projDir = Path.dirname(projPath) + const outDir = Path.resolve(process.argv[3]); + const libDir = Path.resolve(process.argv[4]); + const commonjs = process.argv.find(v => v === "--commonjs"); + const sourceMaps = process.argv.find(v => v === "--sourceMaps"); + + const babelOptions = commonjs ? + { plugins: customPlugins.concat("@babel/plugin-transform-modules-commonjs") } : + { plugins: customPlugins }; + if (sourceMaps) { babelOptions.sourceMaps = true; } + + console.log("Compiling to " + (commonjs ? "commonjs" : "ES2015 modules") + "...") + + const filePaths = getFilePaths(outDir); + for (const filePath of filePaths) { + if (filePath.endsWith(".json")) { + const babelJson = fs.readFileSync(filePath, "utf8"); + const babelAst = JSON.parse(babelJson); + const sourcePath = babelAst.fileName; + const outPath = filePath.replace(/\.json$/, ".js"); + fixImportPaths(babelAst, sourcePath, outPath, projDir, outDir, libDir, babelOptions); + const babelOpts = Object.assign({}, babelOptions); + if (babelOpts.sourceMaps) { + const relPath = Path.relative(Path.dirname(outPath), sourcePath); + babelOpts.sourceFileName = relPath.replace(/\\/g, "/"); + } + const result = Babel.transformFromAstSync(babelAst, null, babelOpts); + fs.renameSync(filePath, outPath); + fs.writeFileSync(outPath, result.code); + if (result.map) { + fs.appendFileSync(outPath, "\n//# sourceMappingURL=" + Path.basename(outPath) + ".map"); + fs.writeFileSync(outPath + ".map", JSON.stringify(result.map)); + } } + } } main() diff --git a/src/fable-standalone/test/bench-compiler/util.js b/src/fable-standalone/test/bench-compiler/util.js index a9b477e86a..7babd334a2 100644 --- a/src/fable-standalone/test/bench-compiler/util.js +++ b/src/fable-standalone/test/bench-compiler/util.js @@ -1,26 +1,35 @@ -const fs = require("fs"); -const Path = require("path"); +import * as fs from "fs"; +import * as Path from "path"; export function ensureDirExists(dir, cont) { - if (fs.existsSync(dir)) { - if (typeof cont === "function") { cont(); } - } else { - ensureDirExists(Path.dirname(dir), () => { - if (!fs.existsSync(dir)) { fs.mkdirSync(dir); } - if (typeof cont === "function") { cont(); } - }); - } + if (fs.existsSync(dir)) { + if (typeof cont === "function") { cont(); } + } else { + ensureDirExists(Path.dirname(dir), () => { + if (!fs.existsSync(dir)) { fs.mkdirSync(dir); } + if (typeof cont === "function") { cont(); } + }); + } +} + +export function getDirFiles(dir) { + if (!fs.existsSync(dir)) return []; + const files = fs.readdirSync(dir).map((subdir) => { + const res = Path.resolve(dir, subdir); + return fs.statSync(res).isDirectory() ? getDirFiles(res) : res; + }); + return files.reduce((a, f) => a.concat(f), []); } export function serializeToJson(data) { - return JSON.stringify(data, (key, value) => { - if (value === Infinity) { - return "Infinity"; - } else if (value === -Infinity) { - return "-Infinity"; - } else if (value !== value) { - return "NaN"; - } - return value; - }); + return JSON.stringify(data, (key, value) => { + if (value === Infinity) { + return "Infinity"; + } else if (value === -Infinity) { + return "-Infinity"; + } else if (value !== value) { + return "NaN"; + } + return value; + }); } diff --git a/src/fable-standalone/test/bench/Platform.fs b/src/fable-standalone/test/bench/Platform.fs index f96833c9d8..6ee32668ea 100644 --- a/src/fable-standalone/test/bench/Platform.fs +++ b/src/fable-standalone/test/bench/Platform.fs @@ -1,6 +1,6 @@ module Bench.Platform -#if DOTNET_FILE_SYSTEM +#if DOTNET_FILE_SYSTEM && !FABLE_COMPILER open System.IO @@ -15,7 +15,7 @@ let measureTime (f: 'a -> 'b) x = sw.ElapsedMilliseconds, res // not really serializing, just a stub -let toJson (value: obj) = sprintf "%A" value // Newtonsoft.Json.JsonConvert.SerializeObject(value) +// let toJson (value: obj) = sprintf "%A" value // Newtonsoft.Json.JsonConvert.SerializeObject(value) #else @@ -41,6 +41,6 @@ let measureTime (f: 'a -> 'b) x = let elapsed = Process.hrtime(startTime) int64 (elapsed.[0] * 1e3 + elapsed.[1] / 1e6), res -let toJson (value: obj) = value |> Fable.Core.JsInterop.toJson +// let toJson (value: obj) = value |> Fable.Core.JsInterop.toJson #endif \ No newline at end of file diff --git a/src/fable-standalone/test/bench/app.fs b/src/fable-standalone/test/bench/app.fs index b09e850087..0f7f68c821 100644 --- a/src/fable-standalone/test/bench/app.fs +++ b/src/fable-standalone/test/bench/app.fs @@ -35,13 +35,15 @@ let main argv = let source = readAllText testScriptPath let fable = Fable.Standalone.Main.init () let readAllBytes dllName = readAllBytes (metadataPath + dllName) - let createChecker () = fable.CreateChecker(references, readAllBytes, [||], optimize) + let optimizeFlag = "--optimize" + (if optimize then "+" else "-") + let otherOptions = [| optimizeFlag |] + let createChecker () = fable.CreateChecker(references, readAllBytes, otherOptions) let ms0, checker = measureTime createChecker () printfn "InteractiveChecker created in %d ms" ms0 // let parseFSharpScript () = fable.ParseFSharpScript(checker, fileName, source) let parseFSharpScript () = fable.ParseFSharpFileInProject(checker, fileName, projectFileName, [|fileName|], [|source|]) let fableLibraryDir = "fable-library" - let parseFable (res, fileName) = fable.CompileToBabelAst(fableLibraryDir, res, fileName, optimize) + let parseFable (res, fileName) = fable.CompileToBabelAst(fableLibraryDir, res, fileName) let bench i = let ms1, parseRes = measureTime parseFSharpScript () let errors = fable.GetParseErrors parseRes @@ -49,7 +51,7 @@ let main argv = if errors.Length > 0 then failwith "Too many errors." let ms2, babelAst = measureTime parseFable (parseRes, fileName) // if i = 1 then - // // let fsAstStr = fable.FSharpAstToString(parseRes, fileName, optimize) + // // let fsAstStr = fable.FSharpAstToString(parseRes, fileName) // // printfn "%s Typed AST: %s" fileName fsAstStr // // writeAllText fsAstFile fsAstStr // // printfn "Babel AST: %s" (toJson babelAst) diff --git a/src/fable-standalone/test/bench/bench.fsproj b/src/fable-standalone/test/bench/bench.fsproj index a41817a7ae..d0898408ad 100644 --- a/src/fable-standalone/test/bench/bench.fsproj +++ b/src/fable-standalone/test/bench/bench.fsproj @@ -3,9 +3,15 @@ Exe netcoreapp2.1 + Major $(DefineConstants);DOTNET_FILE_SYSTEM + true + + + + diff --git a/src/fable-standalone/test/bench/package-lock.json b/src/fable-standalone/test/bench/package-lock.json new file mode 100644 index 0000000000..48e341a095 --- /dev/null +++ b/src/fable-standalone/test/bench/package-lock.json @@ -0,0 +1,3 @@ +{ + "lockfileVersion": 1 +} diff --git a/src/fable-standalone/webpack.config.js b/src/fable-standalone/webpack.config.js index 32d08f7f7a..ebab021379 100644 --- a/src/fable-standalone/webpack.config.js +++ b/src/fable-standalone/webpack.config.js @@ -1,4 +1,4 @@ -var path = require("path"); +const resolve = (path) => require("path").join(__dirname, path); module.exports = { entry: resolve('src/Fable.Standalone.fsproj'), @@ -34,9 +34,5 @@ module.exports = { } } ] - } + } }; - -function resolve(x) { - return path.join(__dirname, x); -} \ No newline at end of file diff --git a/src/fable-standalone/worker.config.js b/src/fable-standalone/worker.config.js new file mode 100644 index 0000000000..bfd081e4b5 --- /dev/null +++ b/src/fable-standalone/worker.config.js @@ -0,0 +1,12 @@ +module.exports = { + target: "webworker", + node: { + fs: "empty", + module: "empty", + net: "empty", + }, + mode: "production", + // optimization: { + // minimize: false + // } +}; diff --git a/src/fcs-fable/FSStrings.fs b/src/fcs-fable/FSStrings.fs index e83b30f01b..80f3ba415f 100644 --- a/src/fcs-fable/FSStrings.fs +++ b/src/fcs-fable/FSStrings.fs @@ -44,12 +44,6 @@ let resources = ( "NotUpperCaseConstructor", "Discriminated union cases and exception labels must be uppercase identifiers" ); - ( "PossibleOverload", - "Possible overload: '{0}'. {1}." - ); - ( "PossibleBestOverload", - "\n\nPossible best overload: '{0}'." - ); ( "FunctionExpected", "This function takes too many arguments, or is used in a context where a function is not expected" ); @@ -212,6 +206,9 @@ let resources = ( "Parser.TOKEN.DOT.DOT", "symbol '..'" ); + ( "Parser.TOKEN.DOT.DOT.HAT", + "symbol '..^'" + ); ( "Parser.TOKEN.QUOTE", "quote symbol" ); @@ -449,6 +446,9 @@ let resources = ( "Parser.TOKEN.AND", "keyword 'and'" ); + ( "Parser.TOKEN.AND.BANG", + "keyword 'and!'" + ); ( "Parser.TOKEN.AS", "keyword 'as'" ); diff --git a/src/fcs-fable/README.md b/src/fcs-fable/README.md deleted file mode 100644 index 271c611400..0000000000 --- a/src/fcs-fable/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# FSharp.Compiler.Service for Fable - -These files are generated by the following steps: - -- Clone https://github.com/ncave/FSharp.Compiler.Service/ -- Check out `fable` branch -- Run `fcs/build CodeGen.Fable` -- Copy `fcs-fable` folder, and then `src` folder within it -- Remove `.gitignore` from fcs-fable -- Edit `FSharpSourcesRoot` property in fcs-fable/fcs-fable.fsproj - -Alternatively you can just run `npm run build sync-fcs-fable` :) \ No newline at end of file diff --git a/src/fcs-fable/System.Collections.Generic.fs b/src/fcs-fable/System.Collections.Generic.fs new file mode 100644 index 0000000000..7b7d06cc6c --- /dev/null +++ b/src/fcs-fable/System.Collections.Generic.fs @@ -0,0 +1,18 @@ +//------------------------------------------------------------------------ +// shims for things not yet implemented in Fable +//------------------------------------------------------------------------ + +namespace System.Collections.Generic + +type Queue<'T> = + inherit List<'T> + + new () = Queue() + + member x.Enqueue (item: 'T) = + x.Add(item) + + member x.Dequeue () = + let item = x.Item(0) + x.RemoveAt(0) + item diff --git a/src/fcs-fable/System.IO.fs b/src/fcs-fable/System.IO.fs index 81188d35ac..3e37869f7e 100644 --- a/src/fcs-fable/System.IO.fs +++ b/src/fcs-fable/System.IO.fs @@ -51,3 +51,6 @@ module Path = let IsPathRooted (path: string) = //TODO: proper xplat implementation let normPath = path.Replace("\\", "/").TrimEnd('/') normPath.StartsWith("/") + + let DirectorySeparatorChar = '/' + let AltDirectorySeparatorChar = '/' diff --git a/src/fcs-fable/TcImports_shim.fs b/src/fcs-fable/TcImports_shim.fs index b6302434fd..f71dbb6be0 100644 --- a/src/fcs-fable/TcImports_shim.fs +++ b/src/fcs-fable/TcImports_shim.fs @@ -5,50 +5,28 @@ namespace FSharp.Compiler.SourceCodeServices -open System -open System.Collections.Generic -open System.Collections.Concurrent -open System.Diagnostics -open System.IO -open System.Reflection -open System.Text - -open Microsoft.FSharp.Core.Printf -open FSharp.Compiler +open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.ILBinaryReader -open FSharp.Compiler.AbstractIL.Diagnostics -open FSharp.Compiler.AbstractIL.Internal -open FSharp.Compiler.AbstractIL.Internal.Library - -open FSharp.Compiler.AccessibilityLogic -open FSharp.Compiler.Ast +open FSharp.Compiler.AbstractIL.Internal +open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.AbstractIL.Internal.Utils open FSharp.Compiler.CompileOps open FSharp.Compiler.CompileOptions -#if !FABLE_COMPILER -open FSharp.Compiler.Driver -#endif +open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Lib -open FSharp.Compiler.PrettyNaming -open FSharp.Compiler.Parser open FSharp.Compiler.Range -open FSharp.Compiler.Lexhelp -open FSharp.Compiler.Layout -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Infos -open FSharp.Compiler.InfoReader -open FSharp.Compiler.NameResolution -open FSharp.Compiler.TypeChecker -open FSharp.Compiler.SourceCodeServices.SymbolHelpers +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.Text +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.TypedTreePickle open Internal.Utilities open Internal.Utilities.Collections -open FSharp.Compiler.Layout.TaggedTextOps - //------------------------------------------------------------------------- // TcImports shim @@ -74,13 +52,12 @@ module TcImports = let LoadMod (ccuName: string) = let fileName = - if ccuName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) + if ccuName.EndsWith(".dll", System.StringComparison.OrdinalIgnoreCase) then ccuName else ccuName + ".dll" let bytes = readAllBytes fileName let opts: ILReaderOptions = - { ilGlobals = ilGlobals - metadataOnly = MetadataOnlyFlag.Yes + { metadataOnly = MetadataOnlyFlag.Yes reduceMemoryUsage = ReduceMemoryFlag.Yes pdbDirPath = None tryGetMetadataSnapshot = (fun _ -> None) } @@ -88,11 +65,11 @@ module TcImports = let reader = ILBinaryReader.OpenILModuleReaderFromBytes fileName bytes opts reader.ILModuleDef //reader.ILAssemblyRefs - let GetSignatureData (fileName:string, ilScopeRef, ilModule:ILModuleDef option, bytes:byte[]) = - TastPickle.unpickleObjWithDanglingCcus fileName ilScopeRef ilModule TastPickle.unpickleCcuInfo bytes + let GetSignatureData (fileName:string, ilScopeRef, ilModule:ILModuleDef option, bytes: ReadOnlyByteMemory) = + unpickleObjWithDanglingCcus fileName ilScopeRef ilModule unpickleCcuInfo bytes - let GetOptimizationData (fileName:string, ilScopeRef, ilModule:ILModuleDef option, bytes:byte[]) = - TastPickle.unpickleObjWithDanglingCcus fileName ilScopeRef ilModule Optimizer.u_CcuOptimizationInfo bytes + let GetOptimizationData (fileName:string, ilScopeRef, ilModule:ILModuleDef option, bytes: ReadOnlyByteMemory) = + unpickleObjWithDanglingCcus fileName ilScopeRef ilModule Optimizer.u_CcuOptimizationInfo bytes let memoize_mod = new MemoizationTable<_,_> (LoadMod, keyComparer=HashIdentity.Structural) @@ -146,6 +123,7 @@ module TcImports = | ILScopeRef.Local -> failwith "Unsupported reference" | ILScopeRef.Module x -> memoize_mod.Apply x.Name | ILScopeRef.Assembly x -> memoize_mod.Apply x.Name + | ILScopeRef.PrimaryAssembly -> failwith "Unsupported reference" let ilModule = memoize_mod.Apply ccuName let ilShortAssemName = ilModule.ManifestOfAssembly.Name let ilScopeRef = ILScopeRef.Assembly (mkSimpleAssemblyRef ilShortAssemName) @@ -186,7 +164,7 @@ module TcImports = ImportProvidedType = (fun ty -> Import.ImportProvidedType (tcImports.GetImportMap()) m ty) #endif UsesFSharp20PlusQuotations = minfo.usesQuotations - MemberSignatureEquality = (fun ty1 ty2 -> Tastops.typeEquivAux EraseAll (tcImports.GetTcGlobals()) ty1 ty2) + MemberSignatureEquality = (fun ty1 ty2 -> typeEquivAux EraseAll (tcImports.GetTcGlobals()) ty1 ty2) TryGetILModuleDef = (fun () -> Some ilModule) TypeForwarders = Import.ImportILAssemblyTypeForwarders(tcImports.GetImportMap, m, GetRawTypeForwarders ilModule) } @@ -216,7 +194,7 @@ module TcImports = refCcus |> List.tryFind (fun (x: ImportedAssembly) -> x.FSharpViewOfMetadata.AssemblyName = name) |> Option.map (fun x -> x.FSharpViewOfMetadata) - let fixup (data: TastPickle.PickledDataWithReferences<_>) = + let fixup (data: PickledDataWithReferences<_>) = data.OptionalFixup findCcuInfo |> ignore refCcusUnfixed |> List.choose snd |> List.iter fixup refCcus @@ -258,12 +236,12 @@ module TcImports = let tcGlobals = TcGlobals ( tcConfig.compilingFslib, ilGlobals, fslibCcu.FSharpViewOfMetadata, tcConfig.implicitIncludeDir, tcConfig.mlCompatibility, - tcConfig.isInteractive, tryFindSysTypeCcu, - tcConfig.emitDebugInfoInQuotations, tcConfig.noDebugData) + tcConfig.isInteractive, tryFindSysTypeCcu, tcConfig.emitDebugInfoInQuotations, + tcConfig.noDebugData, tcConfig.pathMap, tcConfig.langVersion) #if DEBUG // the global_g reference cell is used only for debug printing - do global_g := Some tcGlobals + do global_g <- Some tcGlobals #endif // do this prior to parsing, since parsing IL assembly code may refer to mscorlib do tcImports.SetCcuMap(ccuMap) diff --git a/src/fcs-fable/codegen/FSComp.fs b/src/fcs-fable/codegen/FSComp.fs index 3940a78dc5..99297ecffe 100644 --- a/src/fcs-fable/codegen/FSComp.fs +++ b/src/fcs-fable/codegen/FSComp.fs @@ -1,4284 +1,4449 @@ -// This is a generated file; the original input is '/Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt' +// This is a generated file; the original input is 'src/fsharp/FSComp.txt' namespace FSComp type internal SR private() = /// The namespace '%s' is not defined. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:4) + /// (Originally from src/fsharp/FSComp.txt:4) static member undefinedNameNamespace(a0 : System.String) = (sprintf "The namespace '%s' is not defined." a0) /// The namespace or module '%s' is not defined. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:5) + /// (Originally from src/fsharp/FSComp.txt:5) static member undefinedNameNamespaceOrModule(a0 : System.String) = (sprintf "The namespace or module '%s' is not defined." a0) /// The field, constructor or member '%s' is not defined. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:6) + /// (Originally from src/fsharp/FSComp.txt:6) static member undefinedNameFieldConstructorOrMember(a0 : System.String) = (sprintf "The field, constructor or member '%s' is not defined." a0) + /// The type '%s' does not define the field, constructor or member '%s'. + /// (Originally from src/fsharp/FSComp.txt:7) + static member undefinedNameFieldConstructorOrMemberWhenTypeIsKnown(a0 : System.String, a1 : System.String) = (sprintf "The type '%s' does not define the field, constructor or member '%s'." a0 a1) /// The value, constructor, namespace or type '%s' is not defined. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:7) + /// (Originally from src/fsharp/FSComp.txt:8) static member undefinedNameValueConstructorNamespaceOrType(a0 : System.String) = (sprintf "The value, constructor, namespace or type '%s' is not defined." a0) /// The value or constructor '%s' is not defined. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:8) + /// (Originally from src/fsharp/FSComp.txt:9) static member undefinedNameValueOfConstructor(a0 : System.String) = (sprintf "The value or constructor '%s' is not defined." a0) /// The value, namespace, type or module '%s' is not defined. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:9) + /// (Originally from src/fsharp/FSComp.txt:10) static member undefinedNameValueNamespaceTypeOrModule(a0 : System.String) = (sprintf "The value, namespace, type or module '%s' is not defined." a0) /// The constructor, module or namespace '%s' is not defined. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:10) + /// (Originally from src/fsharp/FSComp.txt:11) static member undefinedNameConstructorModuleOrNamespace(a0 : System.String) = (sprintf "The constructor, module or namespace '%s' is not defined." a0) /// The type '%s' is not defined. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:11) + /// (Originally from src/fsharp/FSComp.txt:12) static member undefinedNameType(a0 : System.String) = (sprintf "The type '%s' is not defined." a0) /// The type '%s' is not defined in '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:12) + /// (Originally from src/fsharp/FSComp.txt:13) static member undefinedNameTypeIn(a0 : System.String, a1 : System.String) = (sprintf "The type '%s' is not defined in '%s'." a0 a1) /// The record label or namespace '%s' is not defined. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:13) + /// (Originally from src/fsharp/FSComp.txt:14) static member undefinedNameRecordLabelOrNamespace(a0 : System.String) = (sprintf "The record label or namespace '%s' is not defined." a0) /// The record label '%s' is not defined. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:14) + /// (Originally from src/fsharp/FSComp.txt:15) static member undefinedNameRecordLabel(a0 : System.String) = (sprintf "The record label '%s' is not defined." a0) /// Maybe you want one of the following: - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:15) + /// (Originally from src/fsharp/FSComp.txt:16) static member undefinedNameSuggestionsIntro() = (sprintf "Maybe you want one of the following:" ) /// The type parameter %s is not defined. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:16) + /// (Originally from src/fsharp/FSComp.txt:17) static member undefinedNameTypeParameter(a0 : System.String) = (sprintf "The type parameter %s is not defined." a0) /// The pattern discriminator '%s' is not defined. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:17) + /// (Originally from src/fsharp/FSComp.txt:18) static member undefinedNamePatternDiscriminator(a0 : System.String) = (sprintf "The pattern discriminator '%s' is not defined." a0) /// Replace with '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:18) + /// (Originally from src/fsharp/FSComp.txt:19) static member replaceWithSuggestion(a0 : System.String) = (sprintf "Replace with '%s'" a0) /// Add . for indexer access. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:19) + /// (Originally from src/fsharp/FSComp.txt:20) static member addIndexerDot() = (sprintf "Add . for indexer access." ) /// All elements of a list must be of the same type as the first element, which here is '%s'. This element has type '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:20) + /// (Originally from src/fsharp/FSComp.txt:21) static member listElementHasWrongType(a0 : System.String, a1 : System.String) = (sprintf "All elements of a list must be of the same type as the first element, which here is '%s'. This element has type '%s'." a0 a1) /// All elements of an array must be of the same type as the first element, which here is '%s'. This element has type '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:21) + /// (Originally from src/fsharp/FSComp.txt:22) static member arrayElementHasWrongType(a0 : System.String, a1 : System.String) = (sprintf "All elements of an array must be of the same type as the first element, which here is '%s'. This element has type '%s'." a0 a1) /// This 'if' expression is missing an 'else' branch. Because 'if' is an expression, and not a statement, add an 'else' branch which also returns a value of type '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:22) + /// (Originally from src/fsharp/FSComp.txt:23) static member missingElseBranch(a0 : System.String) = (sprintf "This 'if' expression is missing an 'else' branch. Because 'if' is an expression, and not a statement, add an 'else' branch which also returns a value of type '%s'." a0) /// The 'if' expression needs to have type '%s' to satisfy context type requirements. It currently has type '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:23) + /// (Originally from src/fsharp/FSComp.txt:24) static member ifExpression(a0 : System.String, a1 : System.String) = (sprintf "The 'if' expression needs to have type '%s' to satisfy context type requirements. It currently has type '%s'." a0 a1) /// All branches of an 'if' expression must return values of the same type as the first branch, which here is '%s'. This branch returns a value of type '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:24) + /// (Originally from src/fsharp/FSComp.txt:25) static member elseBranchHasWrongType(a0 : System.String, a1 : System.String) = (sprintf "All branches of an 'if' expression must return values of the same type as the first branch, which here is '%s'. This branch returns a value of type '%s'." a0 a1) /// All branches of a pattern match expression must return values of the same type as the first branch, which here is '%s'. This branch returns a value of type '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:25) + /// (Originally from src/fsharp/FSComp.txt:26) static member followingPatternMatchClauseHasWrongType(a0 : System.String, a1 : System.String) = (sprintf "All branches of a pattern match expression must return values of the same type as the first branch, which here is '%s'. This branch returns a value of type '%s'." a0 a1) /// A pattern match guard must be of type 'bool', but this 'when' expression is of type '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:26) + /// (Originally from src/fsharp/FSComp.txt:27) static member patternMatchGuardIsNotBool(a0 : System.String) = (sprintf "A pattern match guard must be of type 'bool', but this 'when' expression is of type '%s'." a0) /// A ';' is used to separate field values in records. Consider replacing ',' with ';'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:27) + /// (Originally from src/fsharp/FSComp.txt:28) static member commaInsteadOfSemicolonInRecord() = (sprintf "A ';' is used to separate field values in records. Consider replacing ',' with ';'." ) /// The '!' operator is used to dereference a ref cell. Consider using 'not expr' here. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:28) + /// (Originally from src/fsharp/FSComp.txt:29) static member derefInsteadOfNot() = (sprintf "The '!' operator is used to dereference a ref cell. Consider using 'not expr' here." ) /// The non-generic type '%s' does not expect any type arguments, but here is given %d type argument(s) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:29) + /// (Originally from src/fsharp/FSComp.txt:30) static member buildUnexpectedTypeArgs(a0 : System.String, a1 : System.Int32) = (sprintf "The non-generic type '%s' does not expect any type arguments, but here is given %d type argument(s)" a0 a1) /// Consider using 'return!' instead of 'return'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:30) + /// (Originally from src/fsharp/FSComp.txt:31) static member returnUsedInsteadOfReturnBang() = (sprintf "Consider using 'return!' instead of 'return'." ) /// Consider using 'yield!' instead of 'yield'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:31) + /// (Originally from src/fsharp/FSComp.txt:32) static member yieldUsedInsteadOfYieldBang() = (sprintf "Consider using 'yield!' instead of 'yield'." ) /// \nA tuple type is required for one or more arguments. Consider wrapping the given arguments in additional parentheses or review the definition of the interface. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:32) + /// (Originally from src/fsharp/FSComp.txt:33) static member tupleRequiredInAbstractMethod() = (sprintf "\nA tuple type is required for one or more arguments. Consider wrapping the given arguments in additional parentheses or review the definition of the interface." ) /// Invalid warning number '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:33) + /// (Originally from src/fsharp/FSComp.txt:34) static member buildInvalidWarningNumber(a0 : System.String) = (203, sprintf "Invalid warning number '%s'" a0) /// Invalid version string '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:34) + /// (Originally from src/fsharp/FSComp.txt:35) static member buildInvalidVersionString(a0 : System.String) = (204, sprintf "Invalid version string '%s'" a0) /// Invalid version file '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:35) + /// (Originally from src/fsharp/FSComp.txt:36) static member buildInvalidVersionFile(a0 : System.String) = (205, sprintf "Invalid version file '%s'" a0) /// Microsoft (R) F# Compiler version %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:36) + /// (Originally from src/fsharp/FSComp.txt:37) static member buildProductName(a0 : System.String) = (sprintf "Microsoft (R) F# Compiler version %s" a0) /// F# Compiler for F# %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:37) + /// (Originally from src/fsharp/FSComp.txt:38) static member buildProductNameCommunity(a0 : System.String) = (sprintf "F# Compiler for F# %s" a0) /// Problem with filename '%s': %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:38) + /// (Originally from src/fsharp/FSComp.txt:39) static member buildProblemWithFilename(a0 : System.String, a1 : System.String) = (206, sprintf "Problem with filename '%s': %s" a0 a1) /// No inputs specified - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:39) + /// (Originally from src/fsharp/FSComp.txt:40) static member buildNoInputsSpecified() = (207, sprintf "No inputs specified" ) /// The '--pdb' option requires the '--debug' option to be used - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:40) + /// (Originally from src/fsharp/FSComp.txt:41) static member buildPdbRequiresDebug() = (209, sprintf "The '--pdb' option requires the '--debug' option to be used" ) /// The search directory '%s' is invalid - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:41) + /// (Originally from src/fsharp/FSComp.txt:42) static member buildInvalidSearchDirectory(a0 : System.String) = (210, sprintf "The search directory '%s' is invalid" a0) /// The search directory '%s' could not be found - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:42) + /// (Originally from src/fsharp/FSComp.txt:43) static member buildSearchDirectoryNotFound(a0 : System.String) = (211, sprintf "The search directory '%s' could not be found" a0) /// '%s' is not a valid filename - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:43) + /// (Originally from src/fsharp/FSComp.txt:44) static member buildInvalidFilename(a0 : System.String) = (212, sprintf "'%s' is not a valid filename" a0) /// '%s' is not a valid assembly name - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:44) + /// (Originally from src/fsharp/FSComp.txt:45) static member buildInvalidAssemblyName(a0 : System.String) = (213, sprintf "'%s' is not a valid assembly name" a0) /// Unrecognized privacy setting '%s' for managed resource, valid options are 'public' and 'private' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:45) + /// (Originally from src/fsharp/FSComp.txt:46) static member buildInvalidPrivacy(a0 : System.String) = (214, sprintf "Unrecognized privacy setting '%s' for managed resource, valid options are 'public' and 'private'" a0) - /// Multiple references to '%s.dll' are not permitted - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:46) - static member buildMultipleReferencesNotAllowed(a0 : System.String) = (215, sprintf "Multiple references to '%s.dll' are not permitted" a0) /// Unable to read assembly '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:47) + /// (Originally from src/fsharp/FSComp.txt:47) static member buildCannotReadAssembly(a0 : System.String) = (218, sprintf "Unable to read assembly '%s'" a0) /// Assembly resolution failure at or near this location - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:48) + /// (Originally from src/fsharp/FSComp.txt:48) static member buildAssemblyResolutionFailed() = (220, sprintf "Assembly resolution failure at or near this location" ) /// The declarations in this file will be placed in an implicit module '%s' based on the file name '%s'. However this is not a valid F# identifier, so the contents will not be accessible from other files. Consider renaming the file or adding a 'module' or 'namespace' declaration at the top of the file. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:49) + /// (Originally from src/fsharp/FSComp.txt:49) static member buildImplicitModuleIsNotLegalIdentifier(a0 : System.String, a1 : System.String) = (221, sprintf "The declarations in this file will be placed in an implicit module '%s' based on the file name '%s'. However this is not a valid F# identifier, so the contents will not be accessible from other files. Consider renaming the file or adding a 'module' or 'namespace' declaration at the top of the file." a0 a1) /// Files in libraries or multiple-file applications must begin with a namespace or module declaration, e.g. 'namespace SomeNamespace.SubNamespace' or 'module SomeNamespace.SomeModule'. Only the last source file of an application may omit such a declaration. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:50) + /// (Originally from src/fsharp/FSComp.txt:50) static member buildMultiFileRequiresNamespaceOrModule() = (222, sprintf "Files in libraries or multiple-file applications must begin with a namespace or module declaration, e.g. 'namespace SomeNamespace.SubNamespace' or 'module SomeNamespace.SomeModule'. Only the last source file of an application may omit such a declaration." ) /// Files in libraries or multiple-file applications must begin with a namespace or module declaration. When using a module declaration at the start of a file the '=' sign is not allowed. If this is a top-level module, consider removing the = to resolve this error. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:51) + /// (Originally from src/fsharp/FSComp.txt:51) static member noEqualSignAfterModule() = (222, sprintf "Files in libraries or multiple-file applications must begin with a namespace or module declaration. When using a module declaration at the start of a file the '=' sign is not allowed. If this is a top-level module, consider removing the = to resolve this error." ) /// This file contains multiple declarations of the form 'module SomeNamespace.SomeModule'. Only one declaration of this form is permitted in a file. Change your file to use an initial namespace declaration and/or use 'module ModuleName = ...' to define your modules. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:52) + /// (Originally from src/fsharp/FSComp.txt:52) static member buildMultipleToplevelModules() = (223, sprintf "This file contains multiple declarations of the form 'module SomeNamespace.SomeModule'. Only one declaration of this form is permitted in a file. Change your file to use an initial namespace declaration and/or use 'module ModuleName = ...' to define your modules." ) /// Option requires parameter: %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:53) + /// (Originally from src/fsharp/FSComp.txt:53) static member buildOptionRequiresParameter(a0 : System.String) = (224, sprintf "Option requires parameter: %s" a0) /// Source file '%s' could not be found - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:54) + /// (Originally from src/fsharp/FSComp.txt:54) static member buildCouldNotFindSourceFile(a0 : System.String) = (225, sprintf "Source file '%s' could not be found" a0) /// The file extension of '%s' is not recognized. Source files must have extension .fs, .fsi, .fsx, .fsscript, .ml or .mli. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:55) + /// (Originally from src/fsharp/FSComp.txt:55) static member buildInvalidSourceFileExtension(a0 : System.String) = (226, sprintf "The file extension of '%s' is not recognized. Source files must have extension .fs, .fsi, .fsx, .fsscript, .ml or .mli." a0) /// Could not resolve assembly '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:56) + /// (Originally from src/fsharp/FSComp.txt:56) static member buildCouldNotResolveAssembly(a0 : System.String) = (227, sprintf "Could not resolve assembly '%s'" a0) /// Could not resolve assembly '%s' required by '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:57) + /// (Originally from src/fsharp/FSComp.txt:57) static member buildCouldNotResolveAssemblyRequiredByFile(a0 : System.String, a1 : System.String) = (228, sprintf "Could not resolve assembly '%s' required by '%s'" a0 a1) /// Error opening binary file '%s': %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:58) + /// (Originally from src/fsharp/FSComp.txt:58) static member buildErrorOpeningBinaryFile(a0 : System.String, a1 : System.String) = (229, sprintf "Error opening binary file '%s': %s" a0 a1) /// The F#-compiled DLL '%s' needs to be recompiled to be used with this version of F# - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:59) + /// (Originally from src/fsharp/FSComp.txt:59) static member buildDifferentVersionMustRecompile(a0 : System.String) = (231, sprintf "The F#-compiled DLL '%s' needs to be recompiled to be used with this version of F#" a0) /// Invalid directive. Expected '#I \"\"'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:60) + /// (Originally from src/fsharp/FSComp.txt:60) static member buildInvalidHashIDirective() = (232, sprintf "Invalid directive. Expected '#I \"\"'." ) /// Invalid directive. Expected '#r \"\"'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:61) + /// (Originally from src/fsharp/FSComp.txt:61) static member buildInvalidHashrDirective() = (233, sprintf "Invalid directive. Expected '#r \"\"'." ) /// Invalid directive. Expected '#load \"\" ... \"\"'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:62) + /// (Originally from src/fsharp/FSComp.txt:62) static member buildInvalidHashloadDirective() = (234, sprintf "Invalid directive. Expected '#load \"\" ... \"\"'." ) /// Invalid directive. Expected '#time', '#time \"on\"' or '#time \"off\"'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:63) + /// (Originally from src/fsharp/FSComp.txt:63) static member buildInvalidHashtimeDirective() = (235, sprintf "Invalid directive. Expected '#time', '#time \"on\"' or '#time \"off\"'." ) /// Directives inside modules are ignored - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:64) + /// (Originally from src/fsharp/FSComp.txt:64) static member buildDirectivesInModulesAreIgnored() = (236, sprintf "Directives inside modules are ignored" ) /// A signature for the file or module '%s' has already been specified - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:65) + /// (Originally from src/fsharp/FSComp.txt:65) static member buildSignatureAlreadySpecified(a0 : System.String) = (237, sprintf "A signature for the file or module '%s' has already been specified" a0) /// An implementation of file or module '%s' has already been given. Compilation order is significant in F# because of type inference. You may need to adjust the order of your files to place the signature file before the implementation. In Visual Studio files are type-checked in the order they appear in the project file, which can be edited manually or adjusted using the solution explorer. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:66) + /// (Originally from src/fsharp/FSComp.txt:66) static member buildImplementationAlreadyGivenDetail(a0 : System.String) = (238, sprintf "An implementation of file or module '%s' has already been given. Compilation order is significant in F# because of type inference. You may need to adjust the order of your files to place the signature file before the implementation. In Visual Studio files are type-checked in the order they appear in the project file, which can be edited manually or adjusted using the solution explorer." a0) /// An implementation of the file or module '%s' has already been given - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:67) + /// (Originally from src/fsharp/FSComp.txt:67) static member buildImplementationAlreadyGiven(a0 : System.String) = (239, sprintf "An implementation of the file or module '%s' has already been given" a0) /// The signature file '%s' does not have a corresponding implementation file. If an implementation file exists then check the 'module' and 'namespace' declarations in the signature and implementation files match. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:68) + /// (Originally from src/fsharp/FSComp.txt:68) static member buildSignatureWithoutImplementation(a0 : System.String) = (240, sprintf "The signature file '%s' does not have a corresponding implementation file. If an implementation file exists then check the 'module' and 'namespace' declarations in the signature and implementation files match." a0) /// '%s' is not a valid integer argument - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:69) + /// (Originally from src/fsharp/FSComp.txt:69) static member buildArgInvalidInt(a0 : System.String) = (241, sprintf "'%s' is not a valid integer argument" a0) /// '%s' is not a valid floating point argument - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:70) + /// (Originally from src/fsharp/FSComp.txt:70) static member buildArgInvalidFloat(a0 : System.String) = (242, sprintf "'%s' is not a valid floating point argument" a0) /// Unrecognized option: '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:71) + /// (Originally from src/fsharp/FSComp.txt:71) static member buildUnrecognizedOption(a0 : System.String) = (243, sprintf "Unrecognized option: '%s'" a0) /// Invalid module or namespace name - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:72) + /// (Originally from src/fsharp/FSComp.txt:72) static member buildInvalidModuleOrNamespaceName() = (244, sprintf "Invalid module or namespace name" ) /// Error reading/writing metadata for the F# compiled DLL '%s'. Was the DLL compiled with an earlier version of the F# compiler? (error: '%s'). - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:73) + /// (Originally from src/fsharp/FSComp.txt:73) static member pickleErrorReadingWritingMetadata(a0 : System.String, a1 : System.String) = (sprintf "Error reading/writing metadata for the F# compiled DLL '%s'. Was the DLL compiled with an earlier version of the F# compiler? (error: '%s')." a0 a1) /// The type/module '%s' is not a concrete module or type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:74) + /// (Originally from src/fsharp/FSComp.txt:74) static member tastTypeOrModuleNotConcrete(a0 : System.String) = (245, sprintf "The type/module '%s' is not a concrete module or type" a0) /// The type '%s' has an inline assembly code representation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:75) + /// (Originally from src/fsharp/FSComp.txt:75) static member tastTypeHasAssemblyCodeRepresentation(a0 : System.String) = (sprintf "The type '%s' has an inline assembly code representation" a0) + /// Unrecognized value '%s' for --langversion use --langversion:? for complete list + /// (Originally from src/fsharp/FSComp.txt:76) + static member optsUnrecognizedLanguageVersion(a0 : System.String) = (246, sprintf "Unrecognized value '%s' for --langversion use --langversion:? for complete list" a0) /// A namespace and a module named '%s' both occur in two parts of this assembly - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:76) + /// (Originally from src/fsharp/FSComp.txt:77) static member tastNamespaceAndModuleWithSameNameInAssembly(a0 : System.String) = (247, sprintf "A namespace and a module named '%s' both occur in two parts of this assembly" a0) /// Two modules named '%s' occur in two parts of this assembly - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:77) + /// (Originally from src/fsharp/FSComp.txt:78) static member tastTwoModulesWithSameNameInAssembly(a0 : System.String) = (248, sprintf "Two modules named '%s' occur in two parts of this assembly" a0) /// Two type definitions named '%s' occur in namespace '%s' in two parts of this assembly - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:78) + /// (Originally from src/fsharp/FSComp.txt:79) static member tastDuplicateTypeDefinitionInAssembly(a0 : System.String, a1 : System.String) = (249, sprintf "Two type definitions named '%s' occur in namespace '%s' in two parts of this assembly" a0 a1) /// A module and a type definition named '%s' occur in namespace '%s' in two parts of this assembly - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:79) + /// (Originally from src/fsharp/FSComp.txt:80) static member tastConflictingModuleAndTypeDefinitionInAssembly(a0 : System.String, a1 : System.String) = (250, sprintf "A module and a type definition named '%s' occur in namespace '%s' in two parts of this assembly" a0 a1) /// Invalid member signature encountered because of an earlier error - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:80) + /// (Originally from src/fsharp/FSComp.txt:81) static member tastInvalidMemberSignature() = (251, sprintf "Invalid member signature encountered because of an earlier error" ) /// This value does not have a valid property setter type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:81) + /// (Originally from src/fsharp/FSComp.txt:82) static member tastValueDoesNotHaveSetterType() = (252, sprintf "This value does not have a valid property setter type" ) /// Invalid form for a property getter. At least one '()' argument is required when using the explicit syntax. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:82) + /// (Originally from src/fsharp/FSComp.txt:83) static member tastInvalidFormForPropertyGetter() = (253, sprintf "Invalid form for a property getter. At least one '()' argument is required when using the explicit syntax." ) /// Invalid form for a property setter. At least one argument is required. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:83) + /// (Originally from src/fsharp/FSComp.txt:84) static member tastInvalidFormForPropertySetter() = (254, sprintf "Invalid form for a property setter. At least one argument is required." ) /// Unexpected use of a byref-typed variable - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:84) + /// (Originally from src/fsharp/FSComp.txt:85) static member tastUnexpectedByRef() = (255, sprintf "Unexpected use of a byref-typed variable" ) /// A value must be mutable in order to mutate the contents or take the address of a value type, e.g. 'let mutable x = ...' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:85) + /// (Originally from src/fsharp/FSComp.txt:86) static member tastValueMustBeMutable() = (256, sprintf "A value must be mutable in order to mutate the contents or take the address of a value type, e.g. 'let mutable x = ...'" ) /// Invalid mutation of a constant expression. Consider copying the expression to a mutable local, e.g. 'let mutable x = ...'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:86) + /// (Originally from src/fsharp/FSComp.txt:87) static member tastInvalidMutationOfConstant() = (257, sprintf "Invalid mutation of a constant expression. Consider copying the expression to a mutable local, e.g. 'let mutable x = ...'." ) /// The value has been copied to ensure the original is not mutated by this operation or because the copy is implicit when returning a struct from a member and another member is then accessed - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:87) + /// (Originally from src/fsharp/FSComp.txt:88) static member tastValueHasBeenCopied() = (sprintf "The value has been copied to ensure the original is not mutated by this operation or because the copy is implicit when returning a struct from a member and another member is then accessed" ) /// Recursively defined values cannot appear directly as part of the construction of a tuple value within a recursive binding - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:88) + /// (Originally from src/fsharp/FSComp.txt:89) static member tastRecursiveValuesMayNotBeInConstructionOfTuple() = (259, sprintf "Recursively defined values cannot appear directly as part of the construction of a tuple value within a recursive binding" ) /// Recursive values cannot appear directly as a construction of the type '%s' within a recursive binding. This feature has been removed from the F# language. Consider using a record instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:89) + /// (Originally from src/fsharp/FSComp.txt:90) static member tastRecursiveValuesMayNotAppearInConstructionOfType(a0 : System.String) = (260, sprintf "Recursive values cannot appear directly as a construction of the type '%s' within a recursive binding. This feature has been removed from the F# language. Consider using a record instead." a0) /// Recursive values cannot be directly assigned to the non-mutable field '%s' of the type '%s' within a recursive binding. Consider using a mutable field instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:90) + /// (Originally from src/fsharp/FSComp.txt:91) static member tastRecursiveValuesMayNotBeAssignedToNonMutableField(a0 : System.String, a1 : System.String) = (261, sprintf "Recursive values cannot be directly assigned to the non-mutable field '%s' of the type '%s' within a recursive binding. Consider using a mutable field instead." a0 a1) /// Unexpected decode of AutoOpenAttribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:91) + /// (Originally from src/fsharp/FSComp.txt:92) static member tastUnexpectedDecodeOfAutoOpenAttribute() = (sprintf "Unexpected decode of AutoOpenAttribute" ) /// Unexpected decode of InternalsVisibleToAttribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:92) + /// (Originally from src/fsharp/FSComp.txt:93) static member tastUnexpectedDecodeOfInternalsVisibleToAttribute() = (sprintf "Unexpected decode of InternalsVisibleToAttribute" ) /// Unexpected decode of InterfaceDataVersionAttribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:93) + /// (Originally from src/fsharp/FSComp.txt:94) static member tastUnexpectedDecodeOfInterfaceDataVersionAttribute() = (sprintf "Unexpected decode of InterfaceDataVersionAttribute" ) /// Active patterns cannot return more than 7 possibilities - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:94) + /// (Originally from src/fsharp/FSComp.txt:95) static member tastActivePatternsLimitedToSeven() = (265, sprintf "Active patterns cannot return more than 7 possibilities" ) /// This is not a valid constant expression or custom attribute value - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:95) + /// (Originally from src/fsharp/FSComp.txt:96) static member tastNotAConstantExpression() = (267, sprintf "This is not a valid constant expression or custom attribute value" ) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe mutability attributes differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:96) + /// (Originally from src/fsharp/FSComp.txt:97) static member ValueNotContainedMutabilityAttributesDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe mutability attributes differ" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe names differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:97) + /// (Originally from src/fsharp/FSComp.txt:98) static member ValueNotContainedMutabilityNamesDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe names differ" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe compiled names differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:98) + /// (Originally from src/fsharp/FSComp.txt:99) static member ValueNotContainedMutabilityCompiledNamesDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe compiled names differ" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe display names differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:99) + /// (Originally from src/fsharp/FSComp.txt:100) static member ValueNotContainedMutabilityDisplayNamesDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe display names differ" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe accessibility specified in the signature is more than that specified in the implementation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:100) + /// (Originally from src/fsharp/FSComp.txt:101) static member ValueNotContainedMutabilityAccessibilityMore(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe accessibility specified in the signature is more than that specified in the implementation" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe inline flags differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:101) + /// (Originally from src/fsharp/FSComp.txt:102) static member ValueNotContainedMutabilityInlineFlagsDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe inline flags differ" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe literal constant values and/or attributes differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:102) + /// (Originally from src/fsharp/FSComp.txt:103) static member ValueNotContainedMutabilityLiteralConstantValuesDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe literal constant values and/or attributes differ" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is a type function and the other is not. The signature requires explicit type parameters if they are present in the implementation. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:103) + /// (Originally from src/fsharp/FSComp.txt:104) static member ValueNotContainedMutabilityOneIsTypeFunction(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is a type function and the other is not. The signature requires explicit type parameters if they are present in the implementation." a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe respective type parameter counts differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:104) + /// (Originally from src/fsharp/FSComp.txt:105) static member ValueNotContainedMutabilityParameterCountsDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe respective type parameter counts differ" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe types differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:105) + /// (Originally from src/fsharp/FSComp.txt:106) static member ValueNotContainedMutabilityTypesDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe types differ" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is an extension member and the other is not - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:106) + /// (Originally from src/fsharp/FSComp.txt:107) static member ValueNotContainedMutabilityExtensionsDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is an extension member and the other is not" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nAn arity was not inferred for this value - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:107) + /// (Originally from src/fsharp/FSComp.txt:108) static member ValueNotContainedMutabilityArityNotInferred(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nAn arity was not inferred for this value" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe number of generic parameters in the signature and implementation differ (the signature declares %s but the implementation declares %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:108) + /// (Originally from src/fsharp/FSComp.txt:109) static member ValueNotContainedMutabilityGenericParametersDiffer(a0 : System.String, a1 : System.String, a2 : System.String, a3 : System.String, a4 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe number of generic parameters in the signature and implementation differ (the signature declares %s but the implementation declares %s" a0 a1 a2 a3 a4) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe generic parameters in the signature and implementation have different kinds. Perhaps there is a missing [] attribute. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:109) + /// (Originally from src/fsharp/FSComp.txt:110) static member ValueNotContainedMutabilityGenericParametersAreDifferentKinds(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe generic parameters in the signature and implementation have different kinds. Perhaps there is a missing [] attribute." a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe arities in the signature and implementation differ. The signature specifies that '%s' is function definition or lambda expression accepting at least %s argument(s), but the implementation is a computed function value. To declare that a computed function value is a permitted implementation simply parenthesize its type in the signature, e.g.\n\tval %s: int -> (int -> int)\ninstead of\n\tval %s: int -> int -> int. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:110) + /// (Originally from src/fsharp/FSComp.txt:111) static member ValueNotContainedMutabilityAritiesDiffer(a0 : System.String, a1 : System.String, a2 : System.String, a3 : System.String, a4 : System.String, a5 : System.String, a6 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe arities in the signature and implementation differ. The signature specifies that '%s' is function definition or lambda expression accepting at least %s argument(s), but the implementation is a computed function value. To declare that a computed function value is a permitted implementation simply parenthesize its type in the signature, e.g.\n\tval %s: int -> (int -> int)\ninstead of\n\tval %s: int -> int -> int." a0 a1 a2 a3 a4 a5 a6) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe CLI member names differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:111) + /// (Originally from src/fsharp/FSComp.txt:112) static member ValueNotContainedMutabilityDotNetNamesDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe CLI member names differ" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is static and the other isn't - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:112) + /// (Originally from src/fsharp/FSComp.txt:113) static member ValueNotContainedMutabilityStaticsDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is static and the other isn't" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is virtual and the other isn't - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:113) + /// (Originally from src/fsharp/FSComp.txt:114) static member ValueNotContainedMutabilityVirtualsDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is virtual and the other isn't" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is abstract and the other isn't - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:114) + /// (Originally from src/fsharp/FSComp.txt:115) static member ValueNotContainedMutabilityAbstractsDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is abstract and the other isn't" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is final and the other isn't - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:115) + /// (Originally from src/fsharp/FSComp.txt:116) static member ValueNotContainedMutabilityFinalsDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is final and the other isn't" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is marked as an override and the other isn't - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:116) + /// (Originally from src/fsharp/FSComp.txt:117) static member ValueNotContainedMutabilityOverridesDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is marked as an override and the other isn't" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is a constructor/property and the other is not - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:117) + /// (Originally from src/fsharp/FSComp.txt:118) static member ValueNotContainedMutabilityOneIsConstructor(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nOne is a constructor/property and the other is not" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe compiled representation of this method is as a static member but the signature indicates its compiled representation is as an instance member - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:118) + /// (Originally from src/fsharp/FSComp.txt:119) static member ValueNotContainedMutabilityStaticButInstance(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe compiled representation of this method is as a static member but the signature indicates its compiled representation is as an instance member" a0 a1 a2) /// Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe compiled representation of this method is as an instance member, but the signature indicates its compiled representation is as a static member - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:119) + /// (Originally from src/fsharp/FSComp.txt:120) static member ValueNotContainedMutabilityInstanceButStatic(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Module '%s' contains\n %s \nbut its signature specifies\n %s \nThe compiled representation of this method is as an instance member, but the signature indicates its compiled representation is as a static member" a0 a1 a2) /// The %s definitions in the signature and implementation are not compatible because the names differ. The type is called '%s' in the signature file but '%s' in implementation. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:120) + /// (Originally from src/fsharp/FSComp.txt:121) static member DefinitionsInSigAndImplNotCompatibleNamesDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (290, sprintf "The %s definitions in the signature and implementation are not compatible because the names differ. The type is called '%s' in the signature file but '%s' in implementation." a0 a1 a2) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the respective type parameter counts differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:121) + /// (Originally from src/fsharp/FSComp.txt:122) static member DefinitionsInSigAndImplNotCompatibleParameterCountsDiffer(a0 : System.String, a1 : System.String) = (291, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the respective type parameter counts differ" a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the accessibility specified in the signature is more than that specified in the implementation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:122) + /// (Originally from src/fsharp/FSComp.txt:123) static member DefinitionsInSigAndImplNotCompatibleAccessibilityDiffer(a0 : System.String, a1 : System.String) = (292, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the accessibility specified in the signature is more than that specified in the implementation" a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the signature requires that the type supports the interface %s but the interface has not been implemented - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:123) + /// (Originally from src/fsharp/FSComp.txt:124) static member DefinitionsInSigAndImplNotCompatibleMissingInterface(a0 : System.String, a1 : System.String, a2 : System.String) = (293, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the signature requires that the type supports the interface %s but the interface has not been implemented" a0 a1 a2) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation says this type may use nulls as a representation but the signature does not - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:124) + /// (Originally from src/fsharp/FSComp.txt:125) static member DefinitionsInSigAndImplNotCompatibleImplementationSaysNull(a0 : System.String, a1 : System.String) = (294, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation says this type may use nulls as a representation but the signature does not" a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation says this type may use nulls as an extra value but the signature does not - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:125) + /// (Originally from src/fsharp/FSComp.txt:126) static member DefinitionsInSigAndImplNotCompatibleImplementationSaysNull2(a0 : System.String, a1 : System.String) = (294, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation says this type may use nulls as an extra value but the signature does not" a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the signature says this type may use nulls as a representation but the implementation does not - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:126) + /// (Originally from src/fsharp/FSComp.txt:127) static member DefinitionsInSigAndImplNotCompatibleSignatureSaysNull(a0 : System.String, a1 : System.String) = (295, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the signature says this type may use nulls as a representation but the implementation does not" a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the signature says this type may use nulls as an extra value but the implementation does not - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:127) + /// (Originally from src/fsharp/FSComp.txt:128) static member DefinitionsInSigAndImplNotCompatibleSignatureSaysNull2(a0 : System.String, a1 : System.String) = (295, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the signature says this type may use nulls as an extra value but the implementation does not" a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation type is sealed but the signature implies it is not. Consider adding the [] attribute to the signature. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:128) + /// (Originally from src/fsharp/FSComp.txt:129) static member DefinitionsInSigAndImplNotCompatibleImplementationSealed(a0 : System.String, a1 : System.String) = (296, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation type is sealed but the signature implies it is not. Consider adding the [] attribute to the signature." a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation type is not sealed but signature implies it is. Consider adding the [] attribute to the implementation. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:129) + /// (Originally from src/fsharp/FSComp.txt:130) static member DefinitionsInSigAndImplNotCompatibleImplementationIsNotSealed(a0 : System.String, a1 : System.String) = (297, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation type is not sealed but signature implies it is. Consider adding the [] attribute to the implementation." a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation is an abstract class but the signature is not. Consider adding the [] attribute to the signature. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:130) + /// (Originally from src/fsharp/FSComp.txt:131) static member DefinitionsInSigAndImplNotCompatibleImplementationIsAbstract(a0 : System.String, a1 : System.String) = (298, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation is an abstract class but the signature is not. Consider adding the [] attribute to the signature." a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the signature is an abstract class but the implementation is not. Consider adding the [] attribute to the implementation. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:131) + /// (Originally from src/fsharp/FSComp.txt:132) static member DefinitionsInSigAndImplNotCompatibleSignatureIsAbstract(a0 : System.String, a1 : System.String) = (299, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the signature is an abstract class but the implementation is not. Consider adding the [] attribute to the implementation." a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the types have different base types - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:132) + /// (Originally from src/fsharp/FSComp.txt:133) static member DefinitionsInSigAndImplNotCompatibleTypesHaveDifferentBaseTypes(a0 : System.String, a1 : System.String) = (300, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the types have different base types" a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the number of %ss differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:133) + /// (Originally from src/fsharp/FSComp.txt:134) static member DefinitionsInSigAndImplNotCompatibleNumbersDiffer(a0 : System.String, a1 : System.String, a2 : System.String) = (301, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the number of %ss differ" a0 a1 a2) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the signature defines the %s '%s' but the implementation does not (or does, but not in the same order) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:134) + /// (Originally from src/fsharp/FSComp.txt:135) static member DefinitionsInSigAndImplNotCompatibleSignatureDefinesButImplDoesNot(a0 : System.String, a1 : System.String, a2 : System.String, a3 : System.String) = (302, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the signature defines the %s '%s' but the implementation does not (or does, but not in the same order)" a0 a1 a2 a3) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation defines the %s '%s' but the signature does not (or does, but not in the same order) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:135) + /// (Originally from src/fsharp/FSComp.txt:136) static member DefinitionsInSigAndImplNotCompatibleImplDefinesButSignatureDoesNot(a0 : System.String, a1 : System.String, a2 : System.String, a3 : System.String) = (303, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation defines the %s '%s' but the signature does not (or does, but not in the same order)" a0 a1 a2 a3) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation defines a struct but the signature defines a type with a hidden representation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:136) + /// (Originally from src/fsharp/FSComp.txt:137) static member DefinitionsInSigAndImplNotCompatibleImplDefinesStruct(a0 : System.String, a1 : System.String) = (304, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the implementation defines a struct but the signature defines a type with a hidden representation" a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because a CLI type representation is being hidden by a signature - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:137) + /// (Originally from src/fsharp/FSComp.txt:138) static member DefinitionsInSigAndImplNotCompatibleDotNetTypeRepresentationIsHidden(a0 : System.String, a1 : System.String) = (305, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because a CLI type representation is being hidden by a signature" a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because a type representation is being hidden by a signature - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:138) + /// (Originally from src/fsharp/FSComp.txt:139) static member DefinitionsInSigAndImplNotCompatibleTypeIsHidden(a0 : System.String, a1 : System.String) = (306, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because a type representation is being hidden by a signature" a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the types are of different kinds - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:139) + /// (Originally from src/fsharp/FSComp.txt:140) static member DefinitionsInSigAndImplNotCompatibleTypeIsDifferentKind(a0 : System.String, a1 : System.String) = (307, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the types are of different kinds" a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the IL representations differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:140) + /// (Originally from src/fsharp/FSComp.txt:141) static member DefinitionsInSigAndImplNotCompatibleILDiffer(a0 : System.String, a1 : System.String) = (308, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the IL representations differ" a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the representations differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:141) + /// (Originally from src/fsharp/FSComp.txt:142) static member DefinitionsInSigAndImplNotCompatibleRepresentationsDiffer(a0 : System.String, a1 : System.String) = (309, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the representations differ" a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the field %s was present in the implementation but not in the signature - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:142) + /// (Originally from src/fsharp/FSComp.txt:143) static member DefinitionsInSigAndImplNotCompatibleFieldWasPresent(a0 : System.String, a1 : System.String, a2 : System.String) = (311, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the field %s was present in the implementation but not in the signature" a0 a1 a2) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the order of the fields is different in the signature and implementation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:143) + /// (Originally from src/fsharp/FSComp.txt:144) static member DefinitionsInSigAndImplNotCompatibleFieldOrderDiffer(a0 : System.String, a1 : System.String) = (312, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the order of the fields is different in the signature and implementation" a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the field %s was required by the signature but was not specified by the implementation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:144) + /// (Originally from src/fsharp/FSComp.txt:145) static member DefinitionsInSigAndImplNotCompatibleFieldRequiredButNotSpecified(a0 : System.String, a1 : System.String, a2 : System.String) = (313, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the field %s was required by the signature but was not specified by the implementation" a0 a1 a2) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the field '%s' was present in the implementation but not in the signature. Struct types must now reveal their fields in the signature for the type, though the fields may still be labelled 'private' or 'internal'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:145) + /// (Originally from src/fsharp/FSComp.txt:146) static member DefinitionsInSigAndImplNotCompatibleFieldIsInImplButNotSig(a0 : System.String, a1 : System.String, a2 : System.String) = (314, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the field '%s' was present in the implementation but not in the signature. Struct types must now reveal their fields in the signature for the type, though the fields may still be labelled 'private' or 'internal'." a0 a1 a2) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the abstract member '%s' was required by the signature but was not specified by the implementation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:146) + /// (Originally from src/fsharp/FSComp.txt:147) static member DefinitionsInSigAndImplNotCompatibleAbstractMemberMissingInImpl(a0 : System.String, a1 : System.String, a2 : System.String) = (315, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the abstract member '%s' was required by the signature but was not specified by the implementation" a0 a1 a2) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the abstract member '%s' was present in the implementation but not in the signature - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:147) + /// (Originally from src/fsharp/FSComp.txt:148) static member DefinitionsInSigAndImplNotCompatibleAbstractMemberMissingInSig(a0 : System.String, a1 : System.String, a2 : System.String) = (316, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the abstract member '%s' was present in the implementation but not in the signature" a0 a1 a2) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the signature declares a %s while the implementation declares a %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:148) + /// (Originally from src/fsharp/FSComp.txt:149) static member DefinitionsInSigAndImplNotCompatibleSignatureDeclaresDiffer(a0 : System.String, a1 : System.String, a2 : System.String, a3 : System.String) = (317, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the signature declares a %s while the implementation declares a %s" a0 a1 a2 a3) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the abbreviations differ: %s versus %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:149) + /// (Originally from src/fsharp/FSComp.txt:150) static member DefinitionsInSigAndImplNotCompatibleAbbreviationsDiffer(a0 : System.String, a1 : System.String, a2 : System.String, a3 : System.String) = (318, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the abbreviations differ: %s versus %s" a0 a1 a2 a3) /// The %s definitions for type '%s' in the signature and implementation are not compatible because an abbreviation is being hidden by a signature. The abbreviation must be visible to other CLI languages. Consider making the abbreviation visible in the signature. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:150) + /// (Originally from src/fsharp/FSComp.txt:151) static member DefinitionsInSigAndImplNotCompatibleAbbreviationHiddenBySig(a0 : System.String, a1 : System.String) = (319, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because an abbreviation is being hidden by a signature. The abbreviation must be visible to other CLI languages. Consider making the abbreviation visible in the signature." a0 a1) /// The %s definitions for type '%s' in the signature and implementation are not compatible because the signature has an abbreviation while the implementation does not - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:151) + /// (Originally from src/fsharp/FSComp.txt:152) static member DefinitionsInSigAndImplNotCompatibleSigHasAbbreviation(a0 : System.String, a1 : System.String) = (320, sprintf "The %s definitions for type '%s' in the signature and implementation are not compatible because the signature has an abbreviation while the implementation does not" a0 a1) /// The module contains the constructor\n %s \nbut its signature specifies\n %s \nThe names differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:152) + /// (Originally from src/fsharp/FSComp.txt:153) static member ModuleContainsConstructorButNamesDiffer(a0 : System.String, a1 : System.String) = (sprintf "The module contains the constructor\n %s \nbut its signature specifies\n %s \nThe names differ" a0 a1) /// The module contains the constructor\n %s \nbut its signature specifies\n %s \nThe respective number of data fields differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:153) + /// (Originally from src/fsharp/FSComp.txt:154) static member ModuleContainsConstructorButDataFieldsDiffer(a0 : System.String, a1 : System.String) = (sprintf "The module contains the constructor\n %s \nbut its signature specifies\n %s \nThe respective number of data fields differ" a0 a1) /// The module contains the constructor\n %s \nbut its signature specifies\n %s \nThe types of the fields differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:154) + /// (Originally from src/fsharp/FSComp.txt:155) static member ModuleContainsConstructorButTypesOfFieldsDiffer(a0 : System.String, a1 : System.String) = (sprintf "The module contains the constructor\n %s \nbut its signature specifies\n %s \nThe types of the fields differ" a0 a1) /// The module contains the constructor\n %s \nbut its signature specifies\n %s \nthe accessibility specified in the signature is more than that specified in the implementation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:155) + /// (Originally from src/fsharp/FSComp.txt:156) static member ModuleContainsConstructorButAccessibilityDiffers(a0 : System.String, a1 : System.String) = (sprintf "The module contains the constructor\n %s \nbut its signature specifies\n %s \nthe accessibility specified in the signature is more than that specified in the implementation" a0 a1) /// The module contains the field\n %s \nbut its signature specifies\n %s \nThe names differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:156) + /// (Originally from src/fsharp/FSComp.txt:157) static member FieldNotContainedNamesDiffer(a0 : System.String, a1 : System.String) = (sprintf "The module contains the field\n %s \nbut its signature specifies\n %s \nThe names differ" a0 a1) /// The module contains the field\n %s \nbut its signature specifies\n %s \nthe accessibility specified in the signature is more than that specified in the implementation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:157) + /// (Originally from src/fsharp/FSComp.txt:158) static member FieldNotContainedAccessibilitiesDiffer(a0 : System.String, a1 : System.String) = (sprintf "The module contains the field\n %s \nbut its signature specifies\n %s \nthe accessibility specified in the signature is more than that specified in the implementation" a0 a1) /// The module contains the field\n %s \nbut its signature specifies\n %s \nThe 'static' modifiers differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:158) + /// (Originally from src/fsharp/FSComp.txt:159) static member FieldNotContainedStaticsDiffer(a0 : System.String, a1 : System.String) = (sprintf "The module contains the field\n %s \nbut its signature specifies\n %s \nThe 'static' modifiers differ" a0 a1) /// The module contains the field\n %s \nbut its signature specifies\n %s \nThe 'mutable' modifiers differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:159) + /// (Originally from src/fsharp/FSComp.txt:160) static member FieldNotContainedMutablesDiffer(a0 : System.String, a1 : System.String) = (sprintf "The module contains the field\n %s \nbut its signature specifies\n %s \nThe 'mutable' modifiers differ" a0 a1) /// The module contains the field\n %s \nbut its signature specifies\n %s \nThe 'literal' modifiers differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:160) + /// (Originally from src/fsharp/FSComp.txt:161) static member FieldNotContainedLiteralsDiffer(a0 : System.String, a1 : System.String) = (sprintf "The module contains the field\n %s \nbut its signature specifies\n %s \nThe 'literal' modifiers differ" a0 a1) /// The module contains the field\n %s \nbut its signature specifies\n %s \nThe types differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:161) + /// (Originally from src/fsharp/FSComp.txt:162) static member FieldNotContainedTypesDiffer(a0 : System.String, a1 : System.String) = (sprintf "The module contains the field\n %s \nbut its signature specifies\n %s \nThe types differ" a0 a1) /// The implicit instantiation of a generic construct at or near this point could not be resolved because it could resolve to multiple unrelated types, e.g. '%s' and '%s'. Consider using type annotations to resolve the ambiguity - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:162) + /// (Originally from src/fsharp/FSComp.txt:163) static member typrelCannotResolveImplicitGenericInstantiation(a0 : System.String, a1 : System.String) = (331, sprintf "The implicit instantiation of a generic construct at or near this point could not be resolved because it could resolve to multiple unrelated types, e.g. '%s' and '%s'. Consider using type annotations to resolve the ambiguity" a0 a1) /// Could not resolve the ambiguity inherent in the use of a 'printf'-style format string - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:163) + /// (Originally from src/fsharp/FSComp.txt:164) static member typrelCannotResolveAmbiguityInPrintf() = (333, sprintf "Could not resolve the ambiguity inherent in the use of a 'printf'-style format string" ) /// Could not resolve the ambiguity in the use of a generic construct with an 'enum' constraint at or near this position - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:164) + /// (Originally from src/fsharp/FSComp.txt:165) static member typrelCannotResolveAmbiguityInEnum() = (334, sprintf "Could not resolve the ambiguity in the use of a generic construct with an 'enum' constraint at or near this position" ) /// Could not resolve the ambiguity in the use of a generic construct with a 'delegate' constraint at or near this position - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:165) + /// (Originally from src/fsharp/FSComp.txt:166) static member typrelCannotResolveAmbiguityInDelegate() = (335, sprintf "Could not resolve the ambiguity in the use of a generic construct with a 'delegate' constraint at or near this position" ) /// Invalid value - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:166) + /// (Originally from src/fsharp/FSComp.txt:167) static member typrelInvalidValue() = (337, sprintf "Invalid value" ) /// The signature and implementation are not compatible because the respective type parameter counts differ - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:167) + /// (Originally from src/fsharp/FSComp.txt:168) static member typrelSigImplNotCompatibleParamCountsDiffer() = (338, sprintf "The signature and implementation are not compatible because the respective type parameter counts differ" ) /// The signature and implementation are not compatible because the type parameter in the class/signature has a different compile-time requirement to the one in the member/implementation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:168) + /// (Originally from src/fsharp/FSComp.txt:169) static member typrelSigImplNotCompatibleCompileTimeRequirementsDiffer() = (339, sprintf "The signature and implementation are not compatible because the type parameter in the class/signature has a different compile-time requirement to the one in the member/implementation" ) /// The signature and implementation are not compatible because the declaration of the type parameter '%s' requires a constraint of the form %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:169) + /// (Originally from src/fsharp/FSComp.txt:170) static member typrelSigImplNotCompatibleConstraintsDiffer(a0 : System.String, a1 : System.String) = (340, sprintf "The signature and implementation are not compatible because the declaration of the type parameter '%s' requires a constraint of the form %s" a0 a1) /// The signature and implementation are not compatible because the type parameter '%s' has a constraint of the form %s but the implementation does not. Either remove this constraint from the signature or add it to the implementation. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:170) + /// (Originally from src/fsharp/FSComp.txt:171) static member typrelSigImplNotCompatibleConstraintsDifferRemove(a0 : System.String, a1 : System.String) = (341, sprintf "The signature and implementation are not compatible because the type parameter '%s' has a constraint of the form %s but the implementation does not. Either remove this constraint from the signature or add it to the implementation." a0 a1) /// The type '%s' implements 'System.IComparable'. Consider also adding an explicit override for 'Object.Equals' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:171) + /// (Originally from src/fsharp/FSComp.txt:172) static member typrelTypeImplementsIComparableShouldOverrideObjectEquals(a0 : System.String) = (342, sprintf "The type '%s' implements 'System.IComparable'. Consider also adding an explicit override for 'Object.Equals'" a0) /// The type '%s' implements 'System.IComparable' explicitly but provides no corresponding override for 'Object.Equals'. An implementation of 'Object.Equals' has been automatically provided, implemented via 'System.IComparable'. Consider implementing the override 'Object.Equals' explicitly - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:172) + /// (Originally from src/fsharp/FSComp.txt:173) static member typrelTypeImplementsIComparableDefaultObjectEqualsProvided(a0 : System.String) = (343, sprintf "The type '%s' implements 'System.IComparable' explicitly but provides no corresponding override for 'Object.Equals'. An implementation of 'Object.Equals' has been automatically provided, implemented via 'System.IComparable'. Consider implementing the override 'Object.Equals' explicitly" a0) /// The struct, record or union type '%s' has an explicit implementation of 'Object.GetHashCode' or 'Object.Equals'. You must apply the 'CustomEquality' attribute to the type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:173) + /// (Originally from src/fsharp/FSComp.txt:174) static member typrelExplicitImplementationOfGetHashCodeOrEquals(a0 : System.String) = (344, sprintf "The struct, record or union type '%s' has an explicit implementation of 'Object.GetHashCode' or 'Object.Equals'. You must apply the 'CustomEquality' attribute to the type" a0) /// The struct, record or union type '%s' has an explicit implementation of 'Object.GetHashCode'. Consider implementing a matching override for 'Object.Equals(obj)' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:174) + /// (Originally from src/fsharp/FSComp.txt:175) static member typrelExplicitImplementationOfGetHashCode(a0 : System.String) = (345, sprintf "The struct, record or union type '%s' has an explicit implementation of 'Object.GetHashCode'. Consider implementing a matching override for 'Object.Equals(obj)'" a0) /// The struct, record or union type '%s' has an explicit implementation of 'Object.Equals'. Consider implementing a matching override for 'Object.GetHashCode()' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:175) + /// (Originally from src/fsharp/FSComp.txt:176) static member typrelExplicitImplementationOfEquals(a0 : System.String) = (346, sprintf "The struct, record or union type '%s' has an explicit implementation of 'Object.Equals'. Consider implementing a matching override for 'Object.GetHashCode()'" a0) /// The exception definitions are not compatible because a CLI exception mapping is being hidden by a signature. The exception mapping must be visible to other modules. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:176) + /// (Originally from src/fsharp/FSComp.txt:177) static member ExceptionDefsNotCompatibleHiddenBySignature(a0 : System.String, a1 : System.String) = (sprintf "The exception definitions are not compatible because a CLI exception mapping is being hidden by a signature. The exception mapping must be visible to other modules. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s" a0 a1) /// The exception definitions are not compatible because the CLI representations differ. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:177) + /// (Originally from src/fsharp/FSComp.txt:178) static member ExceptionDefsNotCompatibleDotNetRepresentationsDiffer(a0 : System.String, a1 : System.String) = (sprintf "The exception definitions are not compatible because the CLI representations differ. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s" a0 a1) /// The exception definitions are not compatible because the exception abbreviation is being hidden by the signature. The abbreviation must be visible to other CLI languages. Consider making the abbreviation visible in the signature. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:178) + /// (Originally from src/fsharp/FSComp.txt:179) static member ExceptionDefsNotCompatibleAbbreviationHiddenBySignature(a0 : System.String, a1 : System.String) = (sprintf "The exception definitions are not compatible because the exception abbreviation is being hidden by the signature. The abbreviation must be visible to other CLI languages. Consider making the abbreviation visible in the signature. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s." a0 a1) /// The exception definitions are not compatible because the exception abbreviations in the signature and implementation differ. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:179) + /// (Originally from src/fsharp/FSComp.txt:180) static member ExceptionDefsNotCompatibleSignaturesDiffer(a0 : System.String, a1 : System.String) = (sprintf "The exception definitions are not compatible because the exception abbreviations in the signature and implementation differ. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s." a0 a1) /// The exception definitions are not compatible because the exception declarations differ. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:180) + /// (Originally from src/fsharp/FSComp.txt:181) static member ExceptionDefsNotCompatibleExceptionDeclarationsDiffer(a0 : System.String, a1 : System.String) = (sprintf "The exception definitions are not compatible because the exception declarations differ. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s." a0 a1) /// The exception definitions are not compatible because the field '%s' was required by the signature but was not specified by the implementation. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:181) + /// (Originally from src/fsharp/FSComp.txt:182) static member ExceptionDefsNotCompatibleFieldInSigButNotImpl(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "The exception definitions are not compatible because the field '%s' was required by the signature but was not specified by the implementation. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s." a0 a1 a2) /// The exception definitions are not compatible because the field '%s' was present in the implementation but not in the signature. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:182) + /// (Originally from src/fsharp/FSComp.txt:183) static member ExceptionDefsNotCompatibleFieldInImplButNotSig(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "The exception definitions are not compatible because the field '%s' was present in the implementation but not in the signature. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s." a0 a1 a2) /// The exception definitions are not compatible because the order of the fields is different in the signature and implementation. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:183) + /// (Originally from src/fsharp/FSComp.txt:184) static member ExceptionDefsNotCompatibleFieldOrderDiffers(a0 : System.String, a1 : System.String) = (sprintf "The exception definitions are not compatible because the order of the fields is different in the signature and implementation. The module contains the exception definition\n %s \nbut its signature specifies\n\t%s." a0 a1) /// The namespace or module attributes differ between signature and implementation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:184) + /// (Originally from src/fsharp/FSComp.txt:185) static member typrelModuleNamespaceAttributesDifferInSigAndImpl() = (355, sprintf "The namespace or module attributes differ between signature and implementation" ) /// This method is over-constrained in its type parameters - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:185) + /// (Originally from src/fsharp/FSComp.txt:186) static member typrelMethodIsOverconstrained() = (356, sprintf "This method is over-constrained in its type parameters" ) /// No implementations of '%s' had the correct number of arguments and type parameters. The required signature is '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:186) + /// (Originally from src/fsharp/FSComp.txt:187) static member typrelOverloadNotFound(a0 : System.String, a1 : System.String) = (357, sprintf "No implementations of '%s' had the correct number of arguments and type parameters. The required signature is '%s'." a0 a1) /// The override for '%s' was ambiguous - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:187) + /// (Originally from src/fsharp/FSComp.txt:188) static member typrelOverrideWasAmbiguous(a0 : System.String) = (358, sprintf "The override for '%s' was ambiguous" a0) /// More than one override implements '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:188) + /// (Originally from src/fsharp/FSComp.txt:189) static member typrelMoreThenOneOverride(a0 : System.String) = (359, sprintf "More than one override implements '%s'" a0) /// The method '%s' is sealed and cannot be overridden - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:189) + /// (Originally from src/fsharp/FSComp.txt:190) static member typrelMethodIsSealed(a0 : System.String) = (360, sprintf "The method '%s' is sealed and cannot be overridden" a0) /// The override '%s' implements more than one abstract slot, e.g. '%s' and '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:190) + /// (Originally from src/fsharp/FSComp.txt:191) static member typrelOverrideImplementsMoreThenOneSlot(a0 : System.String, a1 : System.String, a2 : System.String) = (361, sprintf "The override '%s' implements more than one abstract slot, e.g. '%s' and '%s'" a0 a1 a2) /// Duplicate or redundant interface - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:191) + /// (Originally from src/fsharp/FSComp.txt:192) static member typrelDuplicateInterface() = (362, sprintf "Duplicate or redundant interface" ) /// The interface '%s' is included in multiple explicitly implemented interface types. Add an explicit implementation of this interface. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:192) + /// (Originally from src/fsharp/FSComp.txt:193) static member typrelNeedExplicitImplementation(a0 : System.String) = (363, sprintf "The interface '%s' is included in multiple explicitly implemented interface types. Add an explicit implementation of this interface." a0) /// A named argument has been assigned more than one value - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:193) + /// (Originally from src/fsharp/FSComp.txt:194) static member typrelNamedArgumentHasBeenAssignedMoreThenOnce() = (364, sprintf "A named argument has been assigned more than one value" ) /// No implementation was given for '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:194) + /// (Originally from src/fsharp/FSComp.txt:195) static member typrelNoImplementationGiven(a0 : System.String) = (365, sprintf "No implementation was given for '%s'" a0) /// No implementation was given for '%s'. Note that all interface members must be implemented and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:195) + /// (Originally from src/fsharp/FSComp.txt:196) static member typrelNoImplementationGivenWithSuggestion(a0 : System.String) = (366, sprintf "No implementation was given for '%s'. Note that all interface members must be implemented and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'." a0) + /// No implementation was given for those members: %s + /// (Originally from src/fsharp/FSComp.txt:197) + static member typrelNoImplementationGivenSeveral(a0 : System.String) = (365, sprintf "No implementation was given for those members: %s" a0) + /// No implementation was given for those members: %sNote that all interface members must be implemented and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'. + /// (Originally from src/fsharp/FSComp.txt:198) + static member typrelNoImplementationGivenSeveralWithSuggestion(a0 : System.String) = (366, sprintf "No implementation was given for those members: %sNote that all interface members must be implemented and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'." a0) + /// No implementation was given for those members (some results omitted): %s + /// (Originally from src/fsharp/FSComp.txt:199) + static member typrelNoImplementationGivenSeveralTruncated(a0 : System.String) = (365, sprintf "No implementation was given for those members (some results omitted): %s" a0) + /// No implementation was given for those members (some results omitted): %sNote that all interface members must be implemented and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'. + /// (Originally from src/fsharp/FSComp.txt:200) + static member typrelNoImplementationGivenSeveralTruncatedWithSuggestion(a0 : System.String) = (366, sprintf "No implementation was given for those members (some results omitted): %sNote that all interface members must be implemented and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'." a0) /// The member '%s' does not have the correct number of arguments. The required signature is '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:196) + /// (Originally from src/fsharp/FSComp.txt:201) static member typrelMemberDoesNotHaveCorrectNumberOfArguments(a0 : System.String, a1 : System.String) = (367, sprintf "The member '%s' does not have the correct number of arguments. The required signature is '%s'." a0 a1) /// The member '%s' does not have the correct number of method type parameters. The required signature is '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:197) + /// (Originally from src/fsharp/FSComp.txt:202) static member typrelMemberDoesNotHaveCorrectNumberOfTypeParameters(a0 : System.String, a1 : System.String) = (368, sprintf "The member '%s' does not have the correct number of method type parameters. The required signature is '%s'." a0 a1) /// The member '%s' does not have the correct kinds of generic parameters. The required signature is '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:198) + /// (Originally from src/fsharp/FSComp.txt:203) static member typrelMemberDoesNotHaveCorrectKindsOfGenericParameters(a0 : System.String, a1 : System.String) = (369, sprintf "The member '%s' does not have the correct kinds of generic parameters. The required signature is '%s'." a0 a1) /// The member '%s' cannot be used to implement '%s'. The required signature is '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:199) + /// (Originally from src/fsharp/FSComp.txt:204) static member typrelMemberCannotImplement(a0 : System.String, a1 : System.String, a2 : System.String) = (370, sprintf "The member '%s' cannot be used to implement '%s'. The required signature is '%s'." a0 a1 a2) /// Error while parsing embedded IL - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:200) + /// (Originally from src/fsharp/FSComp.txt:205) static member astParseEmbeddedILError() = (371, sprintf "Error while parsing embedded IL" ) /// Error while parsing embedded IL type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:201) + /// (Originally from src/fsharp/FSComp.txt:206) static member astParseEmbeddedILTypeError() = (372, sprintf "Error while parsing embedded IL type" ) /// This indexer notation has been removed from the F# language - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:202) + /// (Originally from src/fsharp/FSComp.txt:207) static member astDeprecatedIndexerNotation() = (sprintf "This indexer notation has been removed from the F# language" ) /// Invalid expression on left of assignment - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:203) + /// (Originally from src/fsharp/FSComp.txt:208) static member astInvalidExprLeftHandOfAssignment() = (374, sprintf "Invalid expression on left of assignment" ) /// The 'ReferenceEquality' attribute cannot be used on structs. Consider using the 'StructuralEquality' attribute instead, or implement an override for 'System.Object.Equals(obj)'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:204) + /// (Originally from src/fsharp/FSComp.txt:209) static member augNoRefEqualsOnStruct() = (376, sprintf "The 'ReferenceEquality' attribute cannot be used on structs. Consider using the 'StructuralEquality' attribute instead, or implement an override for 'System.Object.Equals(obj)'." ) /// This type uses an invalid mix of the attributes 'NoEquality', 'ReferenceEquality', 'StructuralEquality', 'NoComparison' and 'StructuralComparison' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:205) + /// (Originally from src/fsharp/FSComp.txt:210) static member augInvalidAttrs() = (377, sprintf "This type uses an invalid mix of the attributes 'NoEquality', 'ReferenceEquality', 'StructuralEquality', 'NoComparison' and 'StructuralComparison'" ) /// The 'NoEquality' attribute must be used in conjunction with the 'NoComparison' attribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:206) + /// (Originally from src/fsharp/FSComp.txt:211) static member augNoEqualityNeedsNoComparison() = (378, sprintf "The 'NoEquality' attribute must be used in conjunction with the 'NoComparison' attribute" ) /// The 'StructuralComparison' attribute must be used in conjunction with the 'StructuralEquality' attribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:207) + /// (Originally from src/fsharp/FSComp.txt:212) static member augStructCompNeedsStructEquality() = (379, sprintf "The 'StructuralComparison' attribute must be used in conjunction with the 'StructuralEquality' attribute" ) /// The 'StructuralEquality' attribute must be used in conjunction with the 'NoComparison' or 'StructuralComparison' attributes - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:208) + /// (Originally from src/fsharp/FSComp.txt:213) static member augStructEqNeedsNoCompOrStructComp() = (380, sprintf "The 'StructuralEquality' attribute must be used in conjunction with the 'NoComparison' or 'StructuralComparison' attributes" ) /// A type cannot have both the 'ReferenceEquality' and 'StructuralEquality' or 'StructuralComparison' attributes - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:209) + /// (Originally from src/fsharp/FSComp.txt:214) static member augTypeCantHaveRefEqAndStructAttrs() = (381, sprintf "A type cannot have both the 'ReferenceEquality' and 'StructuralEquality' or 'StructuralComparison' attributes" ) /// Only record, union, exception and struct types may be augmented with the 'ReferenceEquality', 'StructuralEquality' and 'StructuralComparison' attributes - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:210) + /// (Originally from src/fsharp/FSComp.txt:215) static member augOnlyCertainTypesCanHaveAttrs() = (382, sprintf "Only record, union, exception and struct types may be augmented with the 'ReferenceEquality', 'StructuralEquality' and 'StructuralComparison' attributes" ) /// A type with attribute 'ReferenceEquality' cannot have an explicit implementation of 'Object.Equals(obj)', 'System.IEquatable<_>' or 'System.Collections.IStructuralEquatable' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:211) + /// (Originally from src/fsharp/FSComp.txt:216) static member augRefEqCantHaveObjEquals() = (383, sprintf "A type with attribute 'ReferenceEquality' cannot have an explicit implementation of 'Object.Equals(obj)', 'System.IEquatable<_>' or 'System.Collections.IStructuralEquatable'" ) /// A type with attribute 'CustomEquality' must have an explicit implementation of at least one of 'Object.Equals(obj)', 'System.IEquatable<_>' or 'System.Collections.IStructuralEquatable' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:212) + /// (Originally from src/fsharp/FSComp.txt:217) static member augCustomEqNeedsObjEquals() = (384, sprintf "A type with attribute 'CustomEquality' must have an explicit implementation of at least one of 'Object.Equals(obj)', 'System.IEquatable<_>' or 'System.Collections.IStructuralEquatable'" ) /// A type with attribute 'CustomComparison' must have an explicit implementation of at least one of 'System.IComparable' or 'System.Collections.IStructuralComparable' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:213) + /// (Originally from src/fsharp/FSComp.txt:218) static member augCustomCompareNeedsIComp() = (385, sprintf "A type with attribute 'CustomComparison' must have an explicit implementation of at least one of 'System.IComparable' or 'System.Collections.IStructuralComparable'" ) /// A type with attribute 'NoEquality' should not usually have an explicit implementation of 'Object.Equals(obj)'. Disable this warning if this is intentional for interoperability purposes - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:214) + /// (Originally from src/fsharp/FSComp.txt:219) static member augNoEqNeedsNoObjEquals() = (386, sprintf "A type with attribute 'NoEquality' should not usually have an explicit implementation of 'Object.Equals(obj)'. Disable this warning if this is intentional for interoperability purposes" ) /// A type with attribute 'NoComparison' should not usually have an explicit implementation of 'System.IComparable', 'System.IComparable<_>' or 'System.Collections.IStructuralComparable'. Disable this warning if this is intentional for interoperability purposes - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:215) + /// (Originally from src/fsharp/FSComp.txt:220) static member augNoCompCantImpIComp() = (386, sprintf "A type with attribute 'NoComparison' should not usually have an explicit implementation of 'System.IComparable', 'System.IComparable<_>' or 'System.Collections.IStructuralComparable'. Disable this warning if this is intentional for interoperability purposes" ) /// The 'CustomEquality' attribute must be used in conjunction with the 'NoComparison' or 'CustomComparison' attributes - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:216) + /// (Originally from src/fsharp/FSComp.txt:221) static member augCustomEqNeedsNoCompOrCustomComp() = (387, sprintf "The 'CustomEquality' attribute must be used in conjunction with the 'NoComparison' or 'CustomComparison' attributes" ) /// Positional specifiers are not permitted in format strings - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:217) + /// (Originally from src/fsharp/FSComp.txt:222) static member forPositionalSpecifiersNotPermitted() = (sprintf "Positional specifiers are not permitted in format strings" ) /// Missing format specifier - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:218) + /// (Originally from src/fsharp/FSComp.txt:223) static member forMissingFormatSpecifier() = (sprintf "Missing format specifier" ) /// '%s' flag set twice - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:219) + /// (Originally from src/fsharp/FSComp.txt:224) static member forFlagSetTwice(a0 : System.String) = (sprintf "'%s' flag set twice" a0) /// Prefix flag (' ' or '+') set twice - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:220) + /// (Originally from src/fsharp/FSComp.txt:225) static member forPrefixFlagSpacePlusSetTwice() = (sprintf "Prefix flag (' ' or '+') set twice" ) /// The # formatting modifier is invalid in F# - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:221) + /// (Originally from src/fsharp/FSComp.txt:226) static member forHashSpecifierIsInvalid() = (sprintf "The # formatting modifier is invalid in F#" ) /// Bad precision in format specifier - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:222) + /// (Originally from src/fsharp/FSComp.txt:227) static member forBadPrecision() = (sprintf "Bad precision in format specifier" ) /// Bad width in format specifier - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:223) + /// (Originally from src/fsharp/FSComp.txt:228) static member forBadWidth() = (sprintf "Bad width in format specifier" ) /// '%s' format does not support '0' flag - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:224) + /// (Originally from src/fsharp/FSComp.txt:229) static member forDoesNotSupportZeroFlag(a0 : System.String) = (sprintf "'%s' format does not support '0' flag" a0) /// Precision missing after the '.' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:225) + /// (Originally from src/fsharp/FSComp.txt:230) static member forPrecisionMissingAfterDot() = (sprintf "Precision missing after the '.'" ) /// '%s' format does not support precision - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:226) + /// (Originally from src/fsharp/FSComp.txt:231) static member forFormatDoesntSupportPrecision(a0 : System.String) = (sprintf "'%s' format does not support precision" a0) /// Bad format specifier (after l or L): Expected ld,li,lo,lu,lx or lX. In F# code you can use %%d, %%x, %%o or %%u instead, which are overloaded to work with all basic integer types. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:227) + /// (Originally from src/fsharp/FSComp.txt:232) static member forBadFormatSpecifier() = (sprintf "Bad format specifier (after l or L): Expected ld,li,lo,lu,lx or lX. In F# code you can use %%d, %%x, %%o or %%u instead, which are overloaded to work with all basic integer types." ) /// The 'l' or 'L' in this format specifier is unnecessary. In F# code you can use %%d, %%x, %%o or %%u instead, which are overloaded to work with all basic integer types. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:228) + /// (Originally from src/fsharp/FSComp.txt:233) static member forLIsUnnecessary() = (sprintf "The 'l' or 'L' in this format specifier is unnecessary. In F# code you can use %%d, %%x, %%o or %%u instead, which are overloaded to work with all basic integer types." ) /// The 'h' or 'H' in this format specifier is unnecessary. You can use %%d, %%x, %%o or %%u instead, which are overloaded to work with all basic integer types. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:229) + /// (Originally from src/fsharp/FSComp.txt:234) static member forHIsUnnecessary() = (sprintf "The 'h' or 'H' in this format specifier is unnecessary. You can use %%d, %%x, %%o or %%u instead, which are overloaded to work with all basic integer types." ) /// '%s' does not support prefix '%s' flag - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:230) + /// (Originally from src/fsharp/FSComp.txt:235) static member forDoesNotSupportPrefixFlag(a0 : System.String, a1 : System.String) = (sprintf "'%s' does not support prefix '%s' flag" a0 a1) /// Bad format specifier: '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:231) + /// (Originally from src/fsharp/FSComp.txt:236) static member forBadFormatSpecifierGeneral(a0 : System.String) = (sprintf "Bad format specifier: '%s'" a0) /// System.Environment.Exit did not exit - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:232) + /// (Originally from src/fsharp/FSComp.txt:237) static member elSysEnvExitDidntExit() = (sprintf "System.Environment.Exit did not exit" ) /// The treatment of this operator is now handled directly by the F# compiler and its meaning cannot be redefined - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:233) + /// (Originally from src/fsharp/FSComp.txt:238) static member elDeprecatedOperator() = (sprintf "The treatment of this operator is now handled directly by the F# compiler and its meaning cannot be redefined" ) /// A protected member is called or 'base' is being used. This is only allowed in the direct implementation of members since they could escape their object scope. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:234) + /// (Originally from src/fsharp/FSComp.txt:239) static member chkProtectedOrBaseCalled() = (405, sprintf "A protected member is called or 'base' is being used. This is only allowed in the direct implementation of members since they could escape their object scope." ) /// The byref-typed variable '%s' is used in an invalid way. Byrefs cannot be captured by closures or passed to inner functions. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:235) + /// (Originally from src/fsharp/FSComp.txt:240) static member chkByrefUsedInInvalidWay(a0 : System.String) = (406, sprintf "The byref-typed variable '%s' is used in an invalid way. Byrefs cannot be captured by closures or passed to inner functions." a0) /// The 'base' keyword is used in an invalid way. Base calls cannot be used in closures. Consider using a private member to make base calls. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:236) + /// (Originally from src/fsharp/FSComp.txt:241) static member chkBaseUsedInInvalidWay() = (408, sprintf "The 'base' keyword is used in an invalid way. Base calls cannot be used in closures. Consider using a private member to make base calls." ) /// The variable '%s' is used in an invalid way - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:237) + /// (Originally from src/fsharp/FSComp.txt:242) static member chkVariableUsedInInvalidWay(a0 : System.String) = (sprintf "The variable '%s' is used in an invalid way" a0) /// The type '%s' is less accessible than the value, member or type '%s' it is used in. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:238) + /// (Originally from src/fsharp/FSComp.txt:243) static member chkTypeLessAccessibleThanType(a0 : System.String, a1 : System.String) = (410, sprintf "The type '%s' is less accessible than the value, member or type '%s' it is used in." a0 a1) /// 'System.Void' can only be used as 'typeof' in F# - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:239) + /// (Originally from src/fsharp/FSComp.txt:244) static member chkSystemVoidOnlyInTypeof() = (411, sprintf "'System.Void' can only be used as 'typeof' in F#" ) /// A type instantiation involves a byref type. This is not permitted by the rules of Common IL. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:240) + /// (Originally from src/fsharp/FSComp.txt:245) static member chkErrorUseOfByref() = (412, sprintf "A type instantiation involves a byref type. This is not permitted by the rules of Common IL." ) /// Calls to 'reraise' may only occur directly in a handler of a try-with - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:241) + /// (Originally from src/fsharp/FSComp.txt:246) static member chkErrorContainsCallToRethrow() = (413, sprintf "Calls to 'reraise' may only occur directly in a handler of a try-with" ) /// Expression-splicing operators may only be used within quotations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:242) + /// (Originally from src/fsharp/FSComp.txt:247) static member chkSplicingOnlyInQuotations() = (414, sprintf "Expression-splicing operators may only be used within quotations" ) /// First-class uses of the expression-splicing operator are not permitted - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:243) + /// (Originally from src/fsharp/FSComp.txt:248) static member chkNoFirstClassSplicing() = (415, sprintf "First-class uses of the expression-splicing operator are not permitted" ) /// First-class uses of the address-of operators are not permitted - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:244) + /// (Originally from src/fsharp/FSComp.txt:249) static member chkNoFirstClassAddressOf() = (416, sprintf "First-class uses of the address-of operators are not permitted" ) /// First-class uses of the 'reraise' function is not permitted - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:245) + /// (Originally from src/fsharp/FSComp.txt:250) static member chkNoFirstClassRethrow() = (417, sprintf "First-class uses of the 'reraise' function is not permitted" ) /// The byref typed value '%s' cannot be used at this point - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:246) + /// (Originally from src/fsharp/FSComp.txt:251) static member chkNoByrefAtThisPoint(a0 : System.String) = (418, sprintf "The byref typed value '%s' cannot be used at this point" a0) /// 'base' values may only be used to make direct calls to the base implementations of overridden members - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:247) + /// (Originally from src/fsharp/FSComp.txt:252) static member chkLimitationsOfBaseKeyword() = (419, sprintf "'base' values may only be used to make direct calls to the base implementations of overridden members" ) /// Object constructors cannot directly use try/with and try/finally prior to the initialization of the object. This includes constructs such as 'for x in ...' that may elaborate to uses of these constructs. This is a limitation imposed by Common IL. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:248) + /// (Originally from src/fsharp/FSComp.txt:253) static member chkObjCtorsCantUseExceptionHandling() = (420, sprintf "Object constructors cannot directly use try/with and try/finally prior to the initialization of the object. This includes constructs such as 'for x in ...' that may elaborate to uses of these constructs. This is a limitation imposed by Common IL." ) /// The address of the variable '%s' cannot be used at this point - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:249) + /// (Originally from src/fsharp/FSComp.txt:254) static member chkNoAddressOfAtThisPoint(a0 : System.String) = (421, sprintf "The address of the variable '%s' cannot be used at this point" a0) /// The address of the static field '%s' cannot be used at this point - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:250) + /// (Originally from src/fsharp/FSComp.txt:255) static member chkNoAddressStaticFieldAtThisPoint(a0 : System.String) = (422, sprintf "The address of the static field '%s' cannot be used at this point" a0) /// The address of the field '%s' cannot be used at this point - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:251) + /// (Originally from src/fsharp/FSComp.txt:256) static member chkNoAddressFieldAtThisPoint(a0 : System.String) = (423, sprintf "The address of the field '%s' cannot be used at this point" a0) /// The address of an array element cannot be used at this point - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:252) + /// (Originally from src/fsharp/FSComp.txt:257) static member chkNoAddressOfArrayElementAtThisPoint() = (424, sprintf "The address of an array element cannot be used at this point" ) /// The type of a first-class function cannot contain byrefs - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:253) + /// (Originally from src/fsharp/FSComp.txt:258) static member chkFirstClassFuncNoByref() = (425, sprintf "The type of a first-class function cannot contain byrefs" ) /// A method return type would contain byrefs which is not permitted - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:254) + /// (Originally from src/fsharp/FSComp.txt:259) static member chkReturnTypeNoByref() = (426, sprintf "A method return type would contain byrefs which is not permitted" ) /// Invalid custom attribute value (not a constant or literal) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:255) + /// (Originally from src/fsharp/FSComp.txt:260) static member chkInvalidCustAttrVal() = (428, sprintf "Invalid custom attribute value (not a constant or literal)" ) /// The attribute type '%s' has 'AllowMultiple=false'. Multiple instances of this attribute cannot be attached to a single language element. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:256) + /// (Originally from src/fsharp/FSComp.txt:261) static member chkAttrHasAllowMultiFalse(a0 : System.String) = (429, sprintf "The attribute type '%s' has 'AllowMultiple=false'. Multiple instances of this attribute cannot be attached to a single language element." a0) /// The member '%s' is used in an invalid way. A use of '%s' has been inferred prior to its definition at or near '%s'. This is an invalid forward reference. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:257) + /// (Originally from src/fsharp/FSComp.txt:262) static member chkMemberUsedInInvalidWay(a0 : System.String, a1 : System.String, a2 : System.String) = (430, sprintf "The member '%s' is used in an invalid way. A use of '%s' has been inferred prior to its definition at or near '%s'. This is an invalid forward reference." a0 a1 a2) /// A byref typed value would be stored here. Top-level let-bound byref values are not permitted. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:258) + /// (Originally from src/fsharp/FSComp.txt:263) static member chkNoByrefAsTopValue() = (431, sprintf "A byref typed value would be stored here. Top-level let-bound byref values are not permitted." ) /// [] terms cannot contain uses of the prefix splice operator '%%' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:259) + /// (Originally from src/fsharp/FSComp.txt:264) static member chkReflectedDefCantSplice() = (432, sprintf "[] terms cannot contain uses of the prefix splice operator '%%'" ) /// A function labeled with the 'EntryPointAttribute' attribute must be the last declaration in the last file in the compilation sequence. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:260) + /// (Originally from src/fsharp/FSComp.txt:265) static member chkEntryPointUsage() = (433, sprintf "A function labeled with the 'EntryPointAttribute' attribute must be the last declaration in the last file in the compilation sequence." ) /// compiled form of the union case - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:261) + /// (Originally from src/fsharp/FSComp.txt:266) static member chkUnionCaseCompiledForm() = (sprintf "compiled form of the union case" ) /// default augmentation of the union case - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:262) + /// (Originally from src/fsharp/FSComp.txt:267) static member chkUnionCaseDefaultAugmentation() = (sprintf "default augmentation of the union case" ) /// The property '%s' has the same name as a method in type '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:263) + /// (Originally from src/fsharp/FSComp.txt:268) static member chkPropertySameNameMethod(a0 : System.String, a1 : System.String) = (434, sprintf "The property '%s' has the same name as a method in type '%s'." a0 a1) /// The property '%s' of type '%s' has a getter and a setter that do not match. If one is abstract then the other must be as well. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:264) + /// (Originally from src/fsharp/FSComp.txt:269) static member chkGetterSetterDoNotMatchAbstract(a0 : System.String, a1 : System.String) = (435, sprintf "The property '%s' of type '%s' has a getter and a setter that do not match. If one is abstract then the other must be as well." a0 a1) /// The property '%s' has the same name as another property in type '%s', but one takes indexer arguments and the other does not. You may be missing an indexer argument to one of your properties. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:265) + /// (Originally from src/fsharp/FSComp.txt:270) static member chkPropertySameNameIndexer(a0 : System.String, a1 : System.String) = (436, sprintf "The property '%s' has the same name as another property in type '%s', but one takes indexer arguments and the other does not. You may be missing an indexer argument to one of your properties." a0 a1) /// A type would store a byref typed value. This is not permitted by Common IL. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:266) + /// (Originally from src/fsharp/FSComp.txt:271) static member chkCantStoreByrefValue() = (437, sprintf "A type would store a byref typed value. This is not permitted by Common IL." ) /// Duplicate method. The method '%s' has the same name and signature as another method in type '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:268) + /// (Originally from src/fsharp/FSComp.txt:273) static member chkDuplicateMethod(a0 : System.String, a1 : System.String) = (438, sprintf "Duplicate method. The method '%s' has the same name and signature as another method in type '%s'." a0 a1) /// Duplicate method. The method '%s' has the same name and signature as another method in type '%s' once tuples, functions, units of measure and/or provided types are erased. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:269) + /// (Originally from src/fsharp/FSComp.txt:274) static member chkDuplicateMethodWithSuffix(a0 : System.String, a1 : System.String) = (438, sprintf "Duplicate method. The method '%s' has the same name and signature as another method in type '%s' once tuples, functions, units of measure and/or provided types are erased." a0 a1) /// The method '%s' has curried arguments but has the same name as another method in type '%s'. Methods with curried arguments cannot be overloaded. Consider using a method taking tupled arguments. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:270) + /// (Originally from src/fsharp/FSComp.txt:275) static member chkDuplicateMethodCurried(a0 : System.String, a1 : System.String) = (439, sprintf "The method '%s' has curried arguments but has the same name as another method in type '%s'. Methods with curried arguments cannot be overloaded. Consider using a method taking tupled arguments." a0 a1) /// Methods with curried arguments cannot declare 'out', 'ParamArray', 'optional', 'ReflectedDefinition', 'byref', 'CallerLineNumber', 'CallerMemberName', or 'CallerFilePath' arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:271) + /// (Originally from src/fsharp/FSComp.txt:276) static member chkCurriedMethodsCantHaveOutParams() = (440, sprintf "Methods with curried arguments cannot declare 'out', 'ParamArray', 'optional', 'ReflectedDefinition', 'byref', 'CallerLineNumber', 'CallerMemberName', or 'CallerFilePath' arguments" ) /// Duplicate property. The property '%s' has the same name and signature as another property in type '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:272) + /// (Originally from src/fsharp/FSComp.txt:277) static member chkDuplicateProperty(a0 : System.String, a1 : System.String) = (441, sprintf "Duplicate property. The property '%s' has the same name and signature as another property in type '%s'." a0 a1) /// Duplicate property. The property '%s' has the same name and signature as another property in type '%s' once tuples, functions, units of measure and/or provided types are erased. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:273) + /// (Originally from src/fsharp/FSComp.txt:278) static member chkDuplicatePropertyWithSuffix(a0 : System.String, a1 : System.String) = (441, sprintf "Duplicate property. The property '%s' has the same name and signature as another property in type '%s' once tuples, functions, units of measure and/or provided types are erased." a0 a1) /// Duplicate method. The abstract method '%s' has the same name and signature as an abstract method in an inherited type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:274) + /// (Originally from src/fsharp/FSComp.txt:279) static member chkDuplicateMethodInheritedType(a0 : System.String) = (442, sprintf "Duplicate method. The abstract method '%s' has the same name and signature as an abstract method in an inherited type." a0) /// Duplicate method. The abstract method '%s' has the same name and signature as an abstract method in an inherited type once tuples, functions, units of measure and/or provided types are erased. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:275) + /// (Originally from src/fsharp/FSComp.txt:280) static member chkDuplicateMethodInheritedTypeWithSuffix(a0 : System.String) = (442, sprintf "Duplicate method. The abstract method '%s' has the same name and signature as an abstract method in an inherited type once tuples, functions, units of measure and/or provided types are erased." a0) /// This type implements the same interface at different generic instantiations '%s' and '%s'. This is not permitted in this version of F#. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:276) + /// (Originally from src/fsharp/FSComp.txt:281) static member chkMultipleGenericInterfaceInstantiations(a0 : System.String, a1 : System.String) = (443, sprintf "This type implements the same interface at different generic instantiations '%s' and '%s'. This is not permitted in this version of F#." a0 a1) /// The type of a field using the 'DefaultValue' attribute must admit default initialization, i.e. have 'null' as a proper value or be a struct type whose fields all admit default initialization. You can use 'DefaultValue(false)' to disable this check - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:277) + /// (Originally from src/fsharp/FSComp.txt:282) static member chkValueWithDefaultValueMustHaveDefaultValue() = (444, sprintf "The type of a field using the 'DefaultValue' attribute must admit default initialization, i.e. have 'null' as a proper value or be a struct type whose fields all admit default initialization. You can use 'DefaultValue(false)' to disable this check" ) /// The type abbreviation contains byrefs. This is not permitted by F#. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:278) + /// (Originally from src/fsharp/FSComp.txt:283) static member chkNoByrefInTypeAbbrev() = (445, sprintf "The type abbreviation contains byrefs. This is not permitted by F#." ) /// The variable '%s' is bound in a quotation but is used as part of a spliced expression. This is not permitted since it may escape its scope. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:279) + /// (Originally from src/fsharp/FSComp.txt:284) static member crefBoundVarUsedInSplice(a0 : System.String) = (446, sprintf "The variable '%s' is bound in a quotation but is used as part of a spliced expression. This is not permitted since it may escape its scope." a0) /// Quotations cannot contain uses of generic expressions - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:280) + /// (Originally from src/fsharp/FSComp.txt:285) static member crefQuotationsCantContainGenericExprs() = (447, sprintf "Quotations cannot contain uses of generic expressions" ) /// Quotations cannot contain function definitions that are inferred or declared to be generic. Consider adding some type constraints to make this a valid quoted expression. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:281) + /// (Originally from src/fsharp/FSComp.txt:286) static member crefQuotationsCantContainGenericFunctions() = (448, sprintf "Quotations cannot contain function definitions that are inferred or declared to be generic. Consider adding some type constraints to make this a valid quoted expression." ) /// Quotations cannot contain object expressions - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:282) + /// (Originally from src/fsharp/FSComp.txt:287) static member crefQuotationsCantContainObjExprs() = (449, sprintf "Quotations cannot contain object expressions" ) /// Quotations cannot contain expressions that take the address of a field - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:283) + /// (Originally from src/fsharp/FSComp.txt:288) static member crefQuotationsCantContainAddressOf() = (450, sprintf "Quotations cannot contain expressions that take the address of a field" ) /// Quotations cannot contain expressions that fetch static fields - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:284) + /// (Originally from src/fsharp/FSComp.txt:289) static member crefQuotationsCantContainStaticFieldRef() = (451, sprintf "Quotations cannot contain expressions that fetch static fields" ) /// Quotations cannot contain inline assembly code or pattern matching on arrays - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:285) + /// (Originally from src/fsharp/FSComp.txt:290) static member crefQuotationsCantContainInlineIL() = (452, sprintf "Quotations cannot contain inline assembly code or pattern matching on arrays" ) /// Quotations cannot contain descending for loops - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:286) + /// (Originally from src/fsharp/FSComp.txt:291) static member crefQuotationsCantContainDescendingForLoops() = (453, sprintf "Quotations cannot contain descending for loops" ) /// Quotations cannot contain expressions that fetch union case indexes - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:287) + /// (Originally from src/fsharp/FSComp.txt:292) static member crefQuotationsCantFetchUnionIndexes() = (454, sprintf "Quotations cannot contain expressions that fetch union case indexes" ) /// Quotations cannot contain expressions that set union case fields - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:288) + /// (Originally from src/fsharp/FSComp.txt:293) static member crefQuotationsCantSetUnionFields() = (455, sprintf "Quotations cannot contain expressions that set union case fields" ) /// Quotations cannot contain expressions that set fields in exception values - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:289) + /// (Originally from src/fsharp/FSComp.txt:294) static member crefQuotationsCantSetExceptionFields() = (456, sprintf "Quotations cannot contain expressions that set fields in exception values" ) /// Quotations cannot contain expressions that require byref pointers - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:290) + /// (Originally from src/fsharp/FSComp.txt:295) static member crefQuotationsCantRequireByref() = (457, sprintf "Quotations cannot contain expressions that require byref pointers" ) /// Quotations cannot contain expressions that make member constraint calls, or uses of operators that implicitly resolve to a member constraint call - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:291) + /// (Originally from src/fsharp/FSComp.txt:296) static member crefQuotationsCantCallTraitMembers() = (458, sprintf "Quotations cannot contain expressions that make member constraint calls, or uses of operators that implicitly resolve to a member constraint call" ) /// Quotations cannot contain this kind of constant - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:292) + /// (Originally from src/fsharp/FSComp.txt:297) static member crefQuotationsCantContainThisConstant() = (459, sprintf "Quotations cannot contain this kind of constant" ) /// Quotations cannot contain this kind of pattern match - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:293) + /// (Originally from src/fsharp/FSComp.txt:298) static member crefQuotationsCantContainThisPatternMatch() = (460, sprintf "Quotations cannot contain this kind of pattern match" ) /// Quotations cannot contain array pattern matching - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:294) + /// (Originally from src/fsharp/FSComp.txt:299) static member crefQuotationsCantContainArrayPatternMatching() = (461, sprintf "Quotations cannot contain array pattern matching" ) /// Quotations cannot contain this kind of type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:295) + /// (Originally from src/fsharp/FSComp.txt:300) static member crefQuotationsCantContainThisType() = (462, sprintf "Quotations cannot contain this kind of type" ) /// The declared type parameter '%s' cannot be used here since the type parameter cannot be resolved at compile time - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:296) + /// (Originally from src/fsharp/FSComp.txt:301) static member csTypeCannotBeResolvedAtCompileTime(a0 : System.String) = (sprintf "The declared type parameter '%s' cannot be used here since the type parameter cannot be resolved at compile time" a0) /// This code is less generic than indicated by its annotations. A unit-of-measure specified using '_' has been determined to be '1', i.e. dimensionless. Consider making the code generic, or removing the use of '_'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:297) + /// (Originally from src/fsharp/FSComp.txt:302) static member csCodeLessGeneric() = (464, sprintf "This code is less generic than indicated by its annotations. A unit-of-measure specified using '_' has been determined to be '1', i.e. dimensionless. Consider making the code generic, or removing the use of '_'." ) /// Type inference problem too complicated (maximum iteration depth reached). Consider adding further type annotations. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:298) + /// (Originally from src/fsharp/FSComp.txt:303) static member csTypeInferenceMaxDepth() = (465, sprintf "Type inference problem too complicated (maximum iteration depth reached). Consider adding further type annotations." ) /// Expected arguments to an instance member - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:299) + /// (Originally from src/fsharp/FSComp.txt:304) static member csExpectedArguments() = (sprintf "Expected arguments to an instance member" ) /// This indexer expects %d arguments but is here given %d - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:300) + /// (Originally from src/fsharp/FSComp.txt:305) static member csIndexArgumentMismatch(a0 : System.Int32, a1 : System.Int32) = (sprintf "This indexer expects %d arguments but is here given %d" a0 a1) /// Expecting a type supporting the operator '%s' but given a function type. You may be missing an argument to a function. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:301) + /// (Originally from src/fsharp/FSComp.txt:306) static member csExpectTypeWithOperatorButGivenFunction(a0 : System.String) = (sprintf "Expecting a type supporting the operator '%s' but given a function type. You may be missing an argument to a function." a0) /// Expecting a type supporting the operator '%s' but given a tuple type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:302) + /// (Originally from src/fsharp/FSComp.txt:307) static member csExpectTypeWithOperatorButGivenTuple(a0 : System.String) = (sprintf "Expecting a type supporting the operator '%s' but given a tuple type" a0) /// None of the types '%s' support the operator '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:303) + /// (Originally from src/fsharp/FSComp.txt:308) static member csTypesDoNotSupportOperator(a0 : System.String, a1 : System.String) = (sprintf "None of the types '%s' support the operator '%s'" a0 a1) /// The type '%s' does not support the operator '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:304) + /// (Originally from src/fsharp/FSComp.txt:309) static member csTypeDoesNotSupportOperator(a0 : System.String, a1 : System.String) = (sprintf "The type '%s' does not support the operator '%s'" a0 a1) /// None of the types '%s' support the operator '%s'. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:305) + /// (Originally from src/fsharp/FSComp.txt:310) static member csTypesDoNotSupportOperatorNullable(a0 : System.String, a1 : System.String) = (sprintf "None of the types '%s' support the operator '%s'. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'." a0 a1) /// The type '%s' does not support the operator '%s'. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:306) + /// (Originally from src/fsharp/FSComp.txt:311) static member csTypeDoesNotSupportOperatorNullable(a0 : System.String, a1 : System.String) = (sprintf "The type '%s' does not support the operator '%s'. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'." a0 a1) /// The type '%s' does not support a conversion to the type '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:307) + /// (Originally from src/fsharp/FSComp.txt:312) static member csTypeDoesNotSupportConversion(a0 : System.String, a1 : System.String) = (sprintf "The type '%s' does not support a conversion to the type '%s'" a0 a1) /// The type '%s' has a method '%s' (full name '%s'), but the method is static - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:308) + /// (Originally from src/fsharp/FSComp.txt:313) static member csMethodFoundButIsStatic(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "The type '%s' has a method '%s' (full name '%s'), but the method is static" a0 a1 a2) /// The type '%s' has a method '%s' (full name '%s'), but the method is not static - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:309) + /// (Originally from src/fsharp/FSComp.txt:314) static member csMethodFoundButIsNotStatic(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "The type '%s' has a method '%s' (full name '%s'), but the method is not static" a0 a1 a2) /// The constraints 'struct' and 'not struct' are inconsistent - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:310) + /// (Originally from src/fsharp/FSComp.txt:315) static member csStructConstraintInconsistent() = (472, sprintf "The constraints 'struct' and 'not struct' are inconsistent" ) /// The type '%s' does not have 'null' as a proper value - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:311) + /// (Originally from src/fsharp/FSComp.txt:316) static member csTypeDoesNotHaveNull(a0 : System.String) = (sprintf "The type '%s' does not have 'null' as a proper value" a0) /// The type '%s' does not have 'null' as a proper value. To create a null value for a Nullable type use 'System.Nullable()'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:312) + /// (Originally from src/fsharp/FSComp.txt:317) static member csNullableTypeDoesNotHaveNull(a0 : System.String) = (sprintf "The type '%s' does not have 'null' as a proper value. To create a null value for a Nullable type use 'System.Nullable()'." a0) /// The type '%s' does not support the 'comparison' constraint because it has the 'NoComparison' attribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:313) + /// (Originally from src/fsharp/FSComp.txt:318) static member csTypeDoesNotSupportComparison1(a0 : System.String) = (sprintf "The type '%s' does not support the 'comparison' constraint because it has the 'NoComparison' attribute" a0) /// The type '%s' does not support the 'comparison' constraint. For example, it does not support the 'System.IComparable' interface - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:314) + /// (Originally from src/fsharp/FSComp.txt:319) static member csTypeDoesNotSupportComparison2(a0 : System.String) = (sprintf "The type '%s' does not support the 'comparison' constraint. For example, it does not support the 'System.IComparable' interface" a0) /// The type '%s' does not support the 'comparison' constraint because it is a record, union or struct with one or more structural element types which do not support the 'comparison' constraint. Either avoid the use of comparison with this type, or add the 'StructuralComparison' attribute to the type to determine which field type does not support comparison - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:315) + /// (Originally from src/fsharp/FSComp.txt:320) static member csTypeDoesNotSupportComparison3(a0 : System.String) = (sprintf "The type '%s' does not support the 'comparison' constraint because it is a record, union or struct with one or more structural element types which do not support the 'comparison' constraint. Either avoid the use of comparison with this type, or add the 'StructuralComparison' attribute to the type to determine which field type does not support comparison" a0) /// The type '%s' does not support the 'equality' constraint because it has the 'NoEquality' attribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:316) + /// (Originally from src/fsharp/FSComp.txt:321) static member csTypeDoesNotSupportEquality1(a0 : System.String) = (sprintf "The type '%s' does not support the 'equality' constraint because it has the 'NoEquality' attribute" a0) /// The type '%s' does not support the 'equality' constraint because it is a function type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:317) + /// (Originally from src/fsharp/FSComp.txt:322) static member csTypeDoesNotSupportEquality2(a0 : System.String) = (sprintf "The type '%s' does not support the 'equality' constraint because it is a function type" a0) /// The type '%s' does not support the 'equality' constraint because it is a record, union or struct with one or more structural element types which do not support the 'equality' constraint. Either avoid the use of equality with this type, or add the 'StructuralEquality' attribute to the type to determine which field type does not support equality - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:318) + /// (Originally from src/fsharp/FSComp.txt:323) static member csTypeDoesNotSupportEquality3(a0 : System.String) = (sprintf "The type '%s' does not support the 'equality' constraint because it is a record, union or struct with one or more structural element types which do not support the 'equality' constraint. Either avoid the use of equality with this type, or add the 'StructuralEquality' attribute to the type to determine which field type does not support equality" a0) /// The type '%s' is not a CLI enum type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:319) + /// (Originally from src/fsharp/FSComp.txt:324) static member csTypeIsNotEnumType(a0 : System.String) = (sprintf "The type '%s' is not a CLI enum type" a0) /// The type '%s' has a non-standard delegate type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:320) + /// (Originally from src/fsharp/FSComp.txt:325) static member csTypeHasNonStandardDelegateType(a0 : System.String) = (sprintf "The type '%s' has a non-standard delegate type" a0) /// The type '%s' is not a CLI delegate type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:321) + /// (Originally from src/fsharp/FSComp.txt:326) static member csTypeIsNotDelegateType(a0 : System.String) = (sprintf "The type '%s' is not a CLI delegate type" a0) /// This type parameter cannot be instantiated to 'Nullable'. This is a restriction imposed in order to ensure the meaning of 'null' in some CLI languages is not confusing when used in conjunction with 'Nullable' values. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:322) + /// (Originally from src/fsharp/FSComp.txt:327) static member csTypeParameterCannotBeNullable() = (sprintf "This type parameter cannot be instantiated to 'Nullable'. This is a restriction imposed in order to ensure the meaning of 'null' in some CLI languages is not confusing when used in conjunction with 'Nullable' values." ) /// A generic construct requires that the type '%s' is a CLI or F# struct type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:323) + /// (Originally from src/fsharp/FSComp.txt:328) static member csGenericConstructRequiresStructType(a0 : System.String) = (sprintf "A generic construct requires that the type '%s' is a CLI or F# struct type" a0) /// A generic construct requires that the type '%s' is an unmanaged type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:324) + /// (Originally from src/fsharp/FSComp.txt:329) static member csGenericConstructRequiresUnmanagedType(a0 : System.String) = (sprintf "A generic construct requires that the type '%s' is an unmanaged type" a0) /// The type '%s' is not compatible with any of the types %s, arising from the use of a printf-style format string - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:325) + /// (Originally from src/fsharp/FSComp.txt:330) static member csTypeNotCompatibleBecauseOfPrintf(a0 : System.String, a1 : System.String) = (sprintf "The type '%s' is not compatible with any of the types %s, arising from the use of a printf-style format string" a0 a1) /// A generic construct requires that the type '%s' have reference semantics, but it does not, i.e. it is a struct - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:326) + /// (Originally from src/fsharp/FSComp.txt:331) static member csGenericConstructRequiresReferenceSemantics(a0 : System.String) = (sprintf "A generic construct requires that the type '%s' have reference semantics, but it does not, i.e. it is a struct" a0) /// A generic construct requires that the type '%s' be non-abstract - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:327) + /// (Originally from src/fsharp/FSComp.txt:332) static member csGenericConstructRequiresNonAbstract(a0 : System.String) = (sprintf "A generic construct requires that the type '%s' be non-abstract" a0) /// A generic construct requires that the type '%s' have a public default constructor - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:328) + /// (Originally from src/fsharp/FSComp.txt:333) static member csGenericConstructRequiresPublicDefaultConstructor(a0 : System.String) = (sprintf "A generic construct requires that the type '%s' have a public default constructor" a0) /// Type instantiation length mismatch - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:329) + /// (Originally from src/fsharp/FSComp.txt:334) static member csTypeInstantiationLengthMismatch() = (483, sprintf "Type instantiation length mismatch" ) /// Optional arguments not permitted here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:330) + /// (Originally from src/fsharp/FSComp.txt:335) static member csOptionalArgumentNotPermittedHere() = (484, sprintf "Optional arguments not permitted here" ) /// %s is not a static member - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:331) + /// (Originally from src/fsharp/FSComp.txt:336) static member csMemberIsNotStatic(a0 : System.String) = (485, sprintf "%s is not a static member" a0) /// %s is not an instance member - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:332) + /// (Originally from src/fsharp/FSComp.txt:337) static member csMemberIsNotInstance(a0 : System.String) = (486, sprintf "%s is not an instance member" a0) /// Argument length mismatch - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:333) + /// (Originally from src/fsharp/FSComp.txt:338) static member csArgumentLengthMismatch() = (487, sprintf "Argument length mismatch" ) /// The argument types don't match - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:334) + /// (Originally from src/fsharp/FSComp.txt:339) static member csArgumentTypesDoNotMatch() = (488, sprintf "The argument types don't match" ) /// This method expects a CLI 'params' parameter in this position. 'params' is a way of passing a variable number of arguments to a method in languages such as C#. Consider passing an array for this argument - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:335) + /// (Originally from src/fsharp/FSComp.txt:340) static member csMethodExpectsParams() = (489, sprintf "This method expects a CLI 'params' parameter in this position. 'params' is a way of passing a variable number of arguments to a method in languages such as C#. Consider passing an array for this argument" ) /// The member or object constructor '%s' is not %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:336) + /// (Originally from src/fsharp/FSComp.txt:341) static member csMemberIsNotAccessible(a0 : System.String, a1 : System.String) = (490, sprintf "The member or object constructor '%s' is not %s" a0 a1) /// The member or object constructor '%s' is not %s. Private members may only be accessed from within the declaring type. Protected members may only be accessed from an extending type and cannot be accessed from inner lambda expressions. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:337) + /// (Originally from src/fsharp/FSComp.txt:342) static member csMemberIsNotAccessible2(a0 : System.String, a1 : System.String) = (491, sprintf "The member or object constructor '%s' is not %s. Private members may only be accessed from within the declaring type. Protected members may only be accessed from an extending type and cannot be accessed from inner lambda expressions." a0 a1) /// %s is not a static method - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:338) + /// (Originally from src/fsharp/FSComp.txt:343) static member csMethodIsNotAStaticMethod(a0 : System.String) = (492, sprintf "%s is not a static method" a0) /// %s is not an instance method - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:339) + /// (Originally from src/fsharp/FSComp.txt:344) static member csMethodIsNotAnInstanceMethod(a0 : System.String) = (493, sprintf "%s is not an instance method" a0) /// The member or object constructor '%s' has no argument or settable return property '%s'. %s. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:340) + /// (Originally from src/fsharp/FSComp.txt:345) static member csMemberHasNoArgumentOrReturnProperty(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "The member or object constructor '%s' has no argument or settable return property '%s'. %s." a0 a1 a2) /// The object constructor '%s' has no argument or settable return property '%s'. %s. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:341) + /// (Originally from src/fsharp/FSComp.txt:346) static member csCtorHasNoArgumentOrReturnProperty(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "The object constructor '%s' has no argument or settable return property '%s'. %s." a0 a1 a2) /// The required signature is %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:342) + /// (Originally from src/fsharp/FSComp.txt:347) static member csRequiredSignatureIs(a0 : System.String) = (495, sprintf "The required signature is %s" a0) /// The member or object constructor '%s' requires %d argument(s). The required signature is '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:343) + /// (Originally from src/fsharp/FSComp.txt:348) static member csMemberSignatureMismatch(a0 : System.String, a1 : System.Int32, a2 : System.String) = (496, sprintf "The member or object constructor '%s' requires %d argument(s). The required signature is '%s'." a0 a1 a2) /// The member or object constructor '%s' requires %d additional argument(s). The required signature is '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:344) + /// (Originally from src/fsharp/FSComp.txt:349) static member csMemberSignatureMismatch2(a0 : System.String, a1 : System.Int32, a2 : System.String) = (497, sprintf "The member or object constructor '%s' requires %d additional argument(s). The required signature is '%s'." a0 a1 a2) /// The member or object constructor '%s' requires %d argument(s). The required signature is '%s'. Some names for missing arguments are %s. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:345) + /// (Originally from src/fsharp/FSComp.txt:350) static member csMemberSignatureMismatch3(a0 : System.String, a1 : System.Int32, a2 : System.String, a3 : System.String) = (498, sprintf "The member or object constructor '%s' requires %d argument(s). The required signature is '%s'. Some names for missing arguments are %s." a0 a1 a2 a3) /// The member or object constructor '%s' requires %d additional argument(s). The required signature is '%s'. Some names for missing arguments are %s. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:346) + /// (Originally from src/fsharp/FSComp.txt:351) static member csMemberSignatureMismatch4(a0 : System.String, a1 : System.Int32, a2 : System.String, a3 : System.String) = (499, sprintf "The member or object constructor '%s' requires %d additional argument(s). The required signature is '%s'. Some names for missing arguments are %s." a0 a1 a2 a3) /// The member or object constructor '%s' requires %d argument(s) but is here given %d unnamed and %d named argument(s). The required signature is '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:347) + /// (Originally from src/fsharp/FSComp.txt:352) static member csMemberSignatureMismatchArityNamed(a0 : System.String, a1 : System.Int32, a2 : System.Int32, a3 : System.Int32, a4 : System.String) = (500, sprintf "The member or object constructor '%s' requires %d argument(s) but is here given %d unnamed and %d named argument(s). The required signature is '%s'." a0 a1 a2 a3 a4) /// The member or object constructor '%s' takes %d argument(s) but is here given %d. The required signature is '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:348) + /// (Originally from src/fsharp/FSComp.txt:353) static member csMemberSignatureMismatchArity(a0 : System.String, a1 : System.Int32, a2 : System.Int32, a3 : System.String) = (501, sprintf "The member or object constructor '%s' takes %d argument(s) but is here given %d. The required signature is '%s'." a0 a1 a2 a3) /// The object constructor '%s' takes %d argument(s) but is here given %d. The required signature is '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:349) + /// (Originally from src/fsharp/FSComp.txt:354) static member csCtorSignatureMismatchArity(a0 : System.String, a1 : System.Int32, a2 : System.Int32, a3 : System.String) = (501, sprintf "The object constructor '%s' takes %d argument(s) but is here given %d. The required signature is '%s'." a0 a1 a2 a3) /// The object constructor '%s' takes %d argument(s) but is here given %d. The required signature is '%s'. If some of the arguments are meant to assign values to properties, consider separating those arguments with a comma (','). - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:350) + /// (Originally from src/fsharp/FSComp.txt:355) static member csCtorSignatureMismatchArityProp(a0 : System.String, a1 : System.Int32, a2 : System.Int32, a3 : System.String) = (501, sprintf "The object constructor '%s' takes %d argument(s) but is here given %d. The required signature is '%s'. If some of the arguments are meant to assign values to properties, consider separating those arguments with a comma (',')." a0 a1 a2 a3) /// The member or object constructor '%s' takes %d type argument(s) but is here given %d. The required signature is '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:351) + /// (Originally from src/fsharp/FSComp.txt:356) static member csMemberSignatureMismatchArityType(a0 : System.String, a1 : System.Int32, a2 : System.Int32, a3 : System.String) = (502, sprintf "The member or object constructor '%s' takes %d type argument(s) but is here given %d. The required signature is '%s'." a0 a1 a2 a3) /// A member or object constructor '%s' taking %d arguments is not accessible from this code location. All accessible versions of method '%s' take %d arguments. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:352) + /// (Originally from src/fsharp/FSComp.txt:357) static member csMemberNotAccessible(a0 : System.String, a1 : System.Int32, a2 : System.String, a3 : System.Int32) = (503, sprintf "A member or object constructor '%s' taking %d arguments is not accessible from this code location. All accessible versions of method '%s' take %d arguments." a0 a1 a2 a3) /// Incorrect generic instantiation. No %s member named '%s' takes %d generic arguments. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:353) + /// (Originally from src/fsharp/FSComp.txt:358) static member csIncorrectGenericInstantiation(a0 : System.String, a1 : System.String, a2 : System.Int32) = (504, sprintf "Incorrect generic instantiation. No %s member named '%s' takes %d generic arguments." a0 a1 a2) /// The member or object constructor '%s' does not take %d argument(s). An overload was found taking %d arguments. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:354) + /// (Originally from src/fsharp/FSComp.txt:359) static member csMemberOverloadArityMismatch(a0 : System.String, a1 : System.Int32, a2 : System.Int32) = (505, sprintf "The member or object constructor '%s' does not take %d argument(s). An overload was found taking %d arguments." a0 a1 a2) /// No %s member or object constructor named '%s' takes %d arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:355) + /// (Originally from src/fsharp/FSComp.txt:360) static member csNoMemberTakesTheseArguments(a0 : System.String, a1 : System.String, a2 : System.Int32) = (506, sprintf "No %s member or object constructor named '%s' takes %d arguments" a0 a1 a2) /// No %s member or object constructor named '%s' takes %d arguments. Note the call to this member also provides %d named arguments. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:356) + /// (Originally from src/fsharp/FSComp.txt:361) static member csNoMemberTakesTheseArguments2(a0 : System.String, a1 : System.String, a2 : System.Int32, a3 : System.Int32) = (507, sprintf "No %s member or object constructor named '%s' takes %d arguments. Note the call to this member also provides %d named arguments." a0 a1 a2 a3) /// No %s member or object constructor named '%s' takes %d arguments. The named argument '%s' doesn't correspond to any argument or settable return property for any overload. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:357) + /// (Originally from src/fsharp/FSComp.txt:362) static member csNoMemberTakesTheseArguments3(a0 : System.String, a1 : System.String, a2 : System.Int32, a3 : System.String) = (508, sprintf "No %s member or object constructor named '%s' takes %d arguments. The named argument '%s' doesn't correspond to any argument or settable return property for any overload." a0 a1 a2 a3) /// Method or object constructor '%s' not found - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:358) + /// (Originally from src/fsharp/FSComp.txt:363) static member csMethodNotFound(a0 : System.String) = (509, sprintf "Method or object constructor '%s' not found" a0) /// No overloads match for method '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:359) + /// (Originally from src/fsharp/FSComp.txt:364) static member csNoOverloadsFound(a0 : System.String) = (sprintf "No overloads match for method '%s'." a0) + /// Known type of argument: %s + /// (Originally from src/fsharp/FSComp.txt:365) + static member csNoOverloadsFoundArgumentsPrefixSingular(a0 : System.String) = (sprintf "Known type of argument: %s" a0) + /// Known types of arguments: %s + /// (Originally from src/fsharp/FSComp.txt:366) + static member csNoOverloadsFoundArgumentsPrefixPlural(a0 : System.String) = (sprintf "Known types of arguments: %s" a0) + /// Known type parameter: %s + /// (Originally from src/fsharp/FSComp.txt:367) + static member csNoOverloadsFoundTypeParametersPrefixSingular(a0 : System.String) = (sprintf "Known type parameter: %s" a0) + /// Known type parameters: %s + /// (Originally from src/fsharp/FSComp.txt:368) + static member csNoOverloadsFoundTypeParametersPrefixPlural(a0 : System.String) = (sprintf "Known type parameters: %s" a0) + /// Known return type: %s + /// (Originally from src/fsharp/FSComp.txt:369) + static member csNoOverloadsFoundReturnType(a0 : System.String) = (sprintf "Known return type: %s" a0) /// A unique overload for method '%s' could not be determined based on type information prior to this program point. A type annotation may be needed. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:360) + /// (Originally from src/fsharp/FSComp.txt:370) static member csMethodIsOverloaded(a0 : System.String) = (sprintf "A unique overload for method '%s' could not be determined based on type information prior to this program point. A type annotation may be needed." a0) - /// Candidates: %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:361) - static member csCandidates(a0 : System.String) = (sprintf "Candidates: %s" a0) - /// The available overloads are shown below. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:362) - static member csSeeAvailableOverloads() = (sprintf "The available overloads are shown below." ) + /// Candidates:\n%s + /// (Originally from src/fsharp/FSComp.txt:371) + static member csCandidates(a0 : System.String) = (sprintf "Candidates:\n%s" a0) + /// Available overloads:\n%s + /// (Originally from src/fsharp/FSComp.txt:372) + static member csAvailableOverloads(a0 : System.String) = (sprintf "Available overloads:\n%s" a0) + /// Argument '%s' doesn't match + /// (Originally from src/fsharp/FSComp.txt:373) + static member csOverloadCandidateNamedArgumentTypeMismatch(a0 : System.String) = (sprintf "Argument '%s' doesn't match" a0) + /// Argument at index %d doesn't match + /// (Originally from src/fsharp/FSComp.txt:374) + static member csOverloadCandidateIndexedArgumentTypeMismatch(a0 : System.Int32) = (sprintf "Argument at index %d doesn't match" a0) /// Accessibility modifiers are not permitted on 'do' bindings, but '%s' was given. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:363) + /// (Originally from src/fsharp/FSComp.txt:375) static member parsDoCannotHaveVisibilityDeclarations(a0 : System.String) = (512, sprintf "Accessibility modifiers are not permitted on 'do' bindings, but '%s' was given." a0) /// End of file in #if section begun at or after here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:364) + /// (Originally from src/fsharp/FSComp.txt:376) static member parsEofInHashIf() = (513, sprintf "End of file in #if section begun at or after here" ) /// End of file in string begun at or before here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:365) + /// (Originally from src/fsharp/FSComp.txt:377) static member parsEofInString() = (514, sprintf "End of file in string begun at or before here" ) /// End of file in verbatim string begun at or before here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:366) + /// (Originally from src/fsharp/FSComp.txt:378) static member parsEofInVerbatimString() = (515, sprintf "End of file in verbatim string begun at or before here" ) /// End of file in comment begun at or before here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:367) + /// (Originally from src/fsharp/FSComp.txt:379) static member parsEofInComment() = (516, sprintf "End of file in comment begun at or before here" ) /// End of file in string embedded in comment begun at or before here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:368) + /// (Originally from src/fsharp/FSComp.txt:380) static member parsEofInStringInComment() = (517, sprintf "End of file in string embedded in comment begun at or before here" ) /// End of file in verbatim string embedded in comment begun at or before here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:369) + /// (Originally from src/fsharp/FSComp.txt:381) static member parsEofInVerbatimStringInComment() = (518, sprintf "End of file in verbatim string embedded in comment begun at or before here" ) /// End of file in IF-OCAML section begun at or before here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:370) + /// (Originally from src/fsharp/FSComp.txt:382) static member parsEofInIfOcaml() = (519, sprintf "End of file in IF-OCAML section begun at or before here" ) /// End of file in directive begun at or before here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:371) + /// (Originally from src/fsharp/FSComp.txt:383) static member parsEofInDirective() = (520, sprintf "End of file in directive begun at or before here" ) /// No #endif found for #if or #else - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:372) + /// (Originally from src/fsharp/FSComp.txt:384) static member parsNoHashEndIfFound() = (521, sprintf "No #endif found for #if or #else" ) /// Attributes have been ignored in this construct - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:373) + /// (Originally from src/fsharp/FSComp.txt:385) static member parsAttributesIgnored() = (522, sprintf "Attributes have been ignored in this construct" ) /// 'use' bindings are not permitted in primary constructors - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:374) + /// (Originally from src/fsharp/FSComp.txt:386) static member parsUseBindingsIllegalInImplicitClassConstructors() = (523, sprintf "'use' bindings are not permitted in primary constructors" ) /// 'use' bindings are not permitted in modules and are treated as 'let' bindings - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:375) + /// (Originally from src/fsharp/FSComp.txt:387) static member parsUseBindingsIllegalInModules() = (524, sprintf "'use' bindings are not permitted in modules and are treated as 'let' bindings" ) /// An integer for loop must use a simple identifier - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:376) + /// (Originally from src/fsharp/FSComp.txt:388) static member parsIntegerForLoopRequiresSimpleIdentifier() = (525, sprintf "An integer for loop must use a simple identifier" ) /// At most one 'with' augmentation is permitted - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:377) + /// (Originally from src/fsharp/FSComp.txt:389) static member parsOnlyOneWithAugmentationAllowed() = (526, sprintf "At most one 'with' augmentation is permitted" ) /// A semicolon is not expected at this point - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:378) + /// (Originally from src/fsharp/FSComp.txt:390) static member parsUnexpectedSemicolon() = (527, sprintf "A semicolon is not expected at this point" ) /// Unexpected end of input - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:379) + /// (Originally from src/fsharp/FSComp.txt:391) static member parsUnexpectedEndOfFile() = (528, sprintf "Unexpected end of input" ) /// Accessibility modifiers are not permitted here, but '%s' was given. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:380) + /// (Originally from src/fsharp/FSComp.txt:392) static member parsUnexpectedVisibilityDeclaration(a0 : System.String) = (529, sprintf "Accessibility modifiers are not permitted here, but '%s' was given." a0) /// Only '#' compiler directives may occur prior to the first 'namespace' declaration - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:381) + /// (Originally from src/fsharp/FSComp.txt:393) static member parsOnlyHashDirectivesAllowed() = (530, sprintf "Only '#' compiler directives may occur prior to the first 'namespace' declaration" ) /// Accessibility modifiers should come immediately prior to the identifier naming a construct - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:382) + /// (Originally from src/fsharp/FSComp.txt:394) static member parsVisibilityDeclarationsShouldComePriorToIdentifier() = (531, sprintf "Accessibility modifiers should come immediately prior to the identifier naming a construct" ) /// Files should begin with either a namespace or module declaration, e.g. 'namespace SomeNamespace.SubNamespace' or 'module SomeNamespace.SomeModule', but not both. To define a module within a namespace use 'module SomeModule = ...' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:383) + /// (Originally from src/fsharp/FSComp.txt:395) static member parsNamespaceOrModuleNotBoth() = (532, sprintf "Files should begin with either a namespace or module declaration, e.g. 'namespace SomeNamespace.SubNamespace' or 'module SomeNamespace.SomeModule', but not both. To define a module within a namespace use 'module SomeModule = ...'" ) /// A module abbreviation must be a simple name, not a path - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:384) + /// (Originally from src/fsharp/FSComp.txt:396) static member parsModuleAbbreviationMustBeSimpleName() = (534, sprintf "A module abbreviation must be a simple name, not a path" ) /// Ignoring attributes on module abbreviation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:385) + /// (Originally from src/fsharp/FSComp.txt:397) static member parsIgnoreAttributesOnModuleAbbreviation() = (535, sprintf "Ignoring attributes on module abbreviation" ) /// The '%s' accessibility attribute is not allowed on module abbreviation. Module abbreviations are always private. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:386) + /// (Originally from src/fsharp/FSComp.txt:398) static member parsIgnoreAttributesOnModuleAbbreviationAlwaysPrivate(a0 : System.String) = (536, sprintf "The '%s' accessibility attribute is not allowed on module abbreviation. Module abbreviations are always private." a0) /// The '%s' visibility attribute is not allowed on module abbreviation. Module abbreviations are always private. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:387) + /// (Originally from src/fsharp/FSComp.txt:399) static member parsIgnoreVisibilityOnModuleAbbreviationAlwaysPrivate(a0 : System.String) = (537, sprintf "The '%s' visibility attribute is not allowed on module abbreviation. Module abbreviations are always private." a0) /// Unclosed block - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:388) + /// (Originally from src/fsharp/FSComp.txt:400) static member parsUnClosedBlockInHashLight() = (538, sprintf "Unclosed block" ) /// Unmatched 'begin' or 'struct' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:389) + /// (Originally from src/fsharp/FSComp.txt:401) static member parsUnmatchedBeginOrStruct() = (539, sprintf "Unmatched 'begin' or 'struct'" ) /// A module name must be a simple name, not a path - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:390) + /// (Originally from src/fsharp/FSComp.txt:402) static member parsModuleDefnMustBeSimpleName() = (541, sprintf "A module name must be a simple name, not a path" ) /// Unexpected empty type moduleDefn list - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:391) + /// (Originally from src/fsharp/FSComp.txt:403) static member parsUnexpectedEmptyModuleDefn() = (542, sprintf "Unexpected empty type moduleDefn list" ) /// Attributes should be placed before 'val' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:392) + /// (Originally from src/fsharp/FSComp.txt:404) static member parsAttributesMustComeBeforeVal() = (sprintf "Attributes should be placed before 'val'" ) /// Attributes are not permitted on interface implementations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:393) + /// (Originally from src/fsharp/FSComp.txt:405) static member parsAttributesAreNotPermittedOnInterfaceImplementations() = (543, sprintf "Attributes are not permitted on interface implementations" ) /// Syntax error - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:394) + /// (Originally from src/fsharp/FSComp.txt:406) static member parsSyntaxError() = (544, sprintf "Syntax error" ) /// Augmentations are not permitted on delegate type moduleDefns - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:395) + /// (Originally from src/fsharp/FSComp.txt:407) static member parsAugmentationsIllegalOnDelegateType() = (545, sprintf "Augmentations are not permitted on delegate type moduleDefns" ) /// Unmatched 'class', 'interface' or 'struct' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:396) + /// (Originally from src/fsharp/FSComp.txt:408) static member parsUnmatchedClassInterfaceOrStruct() = (546, sprintf "Unmatched 'class', 'interface' or 'struct'" ) /// A type definition requires one or more members or other declarations. If you intend to define an empty class, struct or interface, then use 'type ... = class end', 'interface end' or 'struct end'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:397) + /// (Originally from src/fsharp/FSComp.txt:409) static member parsEmptyTypeDefinition() = (547, sprintf "A type definition requires one or more members or other declarations. If you intend to define an empty class, struct or interface, then use 'type ... = class end', 'interface end' or 'struct end'." ) /// Unmatched 'with' or badly formatted 'with' block - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:398) + /// (Originally from src/fsharp/FSComp.txt:410) static member parsUnmatchedWith() = (550, sprintf "Unmatched 'with' or badly formatted 'with' block" ) /// 'get', 'set' or 'get,set' required - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:399) + /// (Originally from src/fsharp/FSComp.txt:411) static member parsGetOrSetRequired() = (551, sprintf "'get', 'set' or 'get,set' required" ) /// Only class types may take value arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:400) + /// (Originally from src/fsharp/FSComp.txt:412) static member parsOnlyClassCanTakeValueArguments() = (552, sprintf "Only class types may take value arguments" ) /// Unmatched 'begin' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:401) + /// (Originally from src/fsharp/FSComp.txt:413) static member parsUnmatchedBegin() = (553, sprintf "Unmatched 'begin'" ) /// Invalid declaration syntax - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:402) + /// (Originally from src/fsharp/FSComp.txt:414) static member parsInvalidDeclarationSyntax() = (554, sprintf "Invalid declaration syntax" ) /// 'get' and/or 'set' required - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:403) + /// (Originally from src/fsharp/FSComp.txt:415) static member parsGetAndOrSetRequired() = (555, sprintf "'get' and/or 'set' required" ) /// Type annotations on property getters and setters must be given after the 'get()' or 'set(v)', e.g. 'with get() : string = ...' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:404) + /// (Originally from src/fsharp/FSComp.txt:416) static member parsTypeAnnotationsOnGetSet() = (556, sprintf "Type annotations on property getters and setters must be given after the 'get()' or 'set(v)', e.g. 'with get() : string = ...'" ) /// A getter property is expected to be a function, e.g. 'get() = ...' or 'get(index) = ...' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:405) + /// (Originally from src/fsharp/FSComp.txt:417) static member parsGetterMustHaveAtLeastOneArgument() = (557, sprintf "A getter property is expected to be a function, e.g. 'get() = ...' or 'get(index) = ...'" ) /// Multiple accessibilities given for property getter or setter - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:406) + /// (Originally from src/fsharp/FSComp.txt:418) static member parsMultipleAccessibilitiesForGetSet() = (558, sprintf "Multiple accessibilities given for property getter or setter" ) /// Property setters must be defined using 'set value = ', 'set idx value = ' or 'set (idx1,...,idxN) value = ... ' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:407) + /// (Originally from src/fsharp/FSComp.txt:419) static member parsSetSyntax() = (559, sprintf "Property setters must be defined using 'set value = ', 'set idx value = ' or 'set (idx1,...,idxN) value = ... '" ) /// Interfaces always have the same visibility as the enclosing type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:408) + /// (Originally from src/fsharp/FSComp.txt:420) static member parsInterfacesHaveSameVisibilityAsEnclosingType() = (560, sprintf "Interfaces always have the same visibility as the enclosing type" ) /// Accessibility modifiers are not allowed on this member. Abstract slots always have the same visibility as the enclosing type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:409) + /// (Originally from src/fsharp/FSComp.txt:421) static member parsAccessibilityModsIllegalForAbstract() = (561, sprintf "Accessibility modifiers are not allowed on this member. Abstract slots always have the same visibility as the enclosing type." ) /// Attributes are not permitted on 'inherit' declarations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:410) + /// (Originally from src/fsharp/FSComp.txt:422) static member parsAttributesIllegalOnInherit() = (562, sprintf "Attributes are not permitted on 'inherit' declarations" ) /// Accessibility modifiers are not permitted on an 'inherits' declaration - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:411) + /// (Originally from src/fsharp/FSComp.txt:423) static member parsVisibilityIllegalOnInherit() = (563, sprintf "Accessibility modifiers are not permitted on an 'inherits' declaration" ) /// 'inherit' declarations cannot have 'as' bindings. To access members of the base class when overriding a method, the syntax 'base.SomeMember' may be used; 'base' is a keyword. Remove this 'as' binding. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:412) + /// (Originally from src/fsharp/FSComp.txt:424) static member parsInheritDeclarationsCannotHaveAsBindings() = (564, sprintf "'inherit' declarations cannot have 'as' bindings. To access members of the base class when overriding a method, the syntax 'base.SomeMember' may be used; 'base' is a keyword. Remove this 'as' binding." ) /// Attributes are not allowed here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:413) + /// (Originally from src/fsharp/FSComp.txt:425) static member parsAttributesIllegalHere() = (565, sprintf "Attributes are not allowed here" ) /// Accessibility modifiers are not permitted in this position for type abbreviations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:414) + /// (Originally from src/fsharp/FSComp.txt:426) static member parsTypeAbbreviationsCannotHaveVisibilityDeclarations() = (566, sprintf "Accessibility modifiers are not permitted in this position for type abbreviations" ) /// Accessibility modifiers are not permitted in this position for enum types - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:415) + /// (Originally from src/fsharp/FSComp.txt:427) static member parsEnumTypesCannotHaveVisibilityDeclarations() = (567, sprintf "Accessibility modifiers are not permitted in this position for enum types" ) /// All enum fields must be given values - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:416) + /// (Originally from src/fsharp/FSComp.txt:428) static member parsAllEnumFieldsRequireValues() = (568, sprintf "All enum fields must be given values" ) /// Accessibility modifiers are not permitted on inline assembly code types - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:417) + /// (Originally from src/fsharp/FSComp.txt:429) static member parsInlineAssemblyCannotHaveVisibilityDeclarations() = (569, sprintf "Accessibility modifiers are not permitted on inline assembly code types" ) /// Unexpected identifier: '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:418) + /// (Originally from src/fsharp/FSComp.txt:430) static member parsUnexpectedIdentifier(a0 : System.String) = (571, sprintf "Unexpected identifier: '%s'" a0) + /// Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + /// (Originally from src/fsharp/FSComp.txt:431) + static member parsUnexpectedSymbolDot() = (10, sprintf "Unexpected symbol '.' in member definition. Expected 'with', '=' or other token." ) /// Accessibility modifiers are not permitted on union cases. Use 'type U = internal ...' or 'type U = private ...' to give an accessibility to the whole representation. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:419) + /// (Originally from src/fsharp/FSComp.txt:432) static member parsUnionCasesCannotHaveVisibilityDeclarations() = (572, sprintf "Accessibility modifiers are not permitted on union cases. Use 'type U = internal ...' or 'type U = private ...' to give an accessibility to the whole representation." ) /// Accessibility modifiers are not permitted on enumeration fields - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:420) + /// (Originally from src/fsharp/FSComp.txt:433) static member parsEnumFieldsCannotHaveVisibilityDeclarations() = (573, sprintf "Accessibility modifiers are not permitted on enumeration fields" ) /// Consider using a separate record type instead - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:421) + /// (Originally from src/fsharp/FSComp.txt:434) static member parsConsiderUsingSeparateRecordType() = (sprintf "Consider using a separate record type instead" ) /// Accessibility modifiers are not permitted on record fields. Use 'type R = internal ...' or 'type R = private ...' to give an accessibility to the whole representation. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:422) + /// (Originally from src/fsharp/FSComp.txt:435) static member parsRecordFieldsCannotHaveVisibilityDeclarations() = (575, sprintf "Accessibility modifiers are not permitted on record fields. Use 'type R = internal ...' or 'type R = private ...' to give an accessibility to the whole representation." ) /// The declaration form 'let ... and ...' for non-recursive bindings is not used in F# code. Consider using a sequence of 'let' bindings - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:423) + /// (Originally from src/fsharp/FSComp.txt:436) static member parsLetAndForNonRecBindings() = (576, sprintf "The declaration form 'let ... and ...' for non-recursive bindings is not used in F# code. Consider using a sequence of 'let' bindings" ) /// Unmatched '(' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:424) + /// (Originally from src/fsharp/FSComp.txt:437) static member parsUnmatchedParen() = (583, sprintf "Unmatched '('" ) /// Successive patterns should be separated by spaces or tupled - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:425) + /// (Originally from src/fsharp/FSComp.txt:438) static member parsSuccessivePatternsShouldBeSpacedOrTupled() = (584, sprintf "Successive patterns should be separated by spaces or tupled" ) /// No matching 'in' found for this 'let' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:426) + /// (Originally from src/fsharp/FSComp.txt:439) static member parsNoMatchingInForLet() = (586, sprintf "No matching 'in' found for this 'let'" ) /// Error in the return expression for this 'let'. Possible incorrect indentation. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:427) + /// (Originally from src/fsharp/FSComp.txt:440) static member parsErrorInReturnForLetIncorrectIndentation() = (587, sprintf "Error in the return expression for this 'let'. Possible incorrect indentation." ) /// The block following this '%s' is unfinished. Every code block is an expression and must have a result. '%s' cannot be the final code element in a block. Consider giving this block an explicit result. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:428) + /// (Originally from src/fsharp/FSComp.txt:441) static member parsExpectedExpressionAfterLet(a0 : System.String, a1 : System.String) = (588, sprintf "The block following this '%s' is unfinished. Every code block is an expression and must have a result. '%s' cannot be the final code element in a block. Consider giving this block an explicit result." a0 a1) /// Incomplete conditional. Expected 'if then ' or 'if then else '. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:429) + /// (Originally from src/fsharp/FSComp.txt:442) static member parsIncompleteIf() = (589, sprintf "Incomplete conditional. Expected 'if then ' or 'if then else '." ) /// 'assert' may not be used as a first class value. Use 'assert ' instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:430) + /// (Originally from src/fsharp/FSComp.txt:443) static member parsAssertIsNotFirstClassValue() = (590, sprintf "'assert' may not be used as a first class value. Use 'assert ' instead." ) /// Identifier expected - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:431) + /// (Originally from src/fsharp/FSComp.txt:444) static member parsIdentifierExpected() = (594, sprintf "Identifier expected" ) /// 'in' or '=' expected - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:432) + /// (Originally from src/fsharp/FSComp.txt:445) static member parsInOrEqualExpected() = (595, sprintf "'in' or '=' expected" ) /// The use of '->' in sequence and computation expressions is limited to the form 'for pat in expr -> expr'. Use the syntax 'for ... in ... do ... yield...' to generate elements in more complex sequence expressions. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:433) + /// (Originally from src/fsharp/FSComp.txt:446) static member parsArrowUseIsLimited() = (596, sprintf "The use of '->' in sequence and computation expressions is limited to the form 'for pat in expr -> expr'. Use the syntax 'for ... in ... do ... yield...' to generate elements in more complex sequence expressions." ) /// Successive arguments should be separated by spaces or tupled, and arguments involving function or method applications should be parenthesized - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:434) + /// (Originally from src/fsharp/FSComp.txt:447) static member parsSuccessiveArgsShouldBeSpacedOrTupled() = (597, sprintf "Successive arguments should be separated by spaces or tupled, and arguments involving function or method applications should be parenthesized" ) /// Unmatched '[' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:435) + /// (Originally from src/fsharp/FSComp.txt:448) static member parsUnmatchedBracket() = (598, sprintf "Unmatched '['" ) /// Missing qualification after '.' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:436) + /// (Originally from src/fsharp/FSComp.txt:449) static member parsMissingQualificationAfterDot() = (599, sprintf "Missing qualification after '.'" ) /// In F# code you may use 'expr.[expr]'. A type annotation may be required to indicate the first expression is an array - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:437) + /// (Originally from src/fsharp/FSComp.txt:450) static member parsParenFormIsForML() = (sprintf "In F# code you may use 'expr.[expr]'. A type annotation may be required to indicate the first expression is an array" ) /// Mismatched quotation, beginning with '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:438) + /// (Originally from src/fsharp/FSComp.txt:451) static member parsMismatchedQuote(a0 : System.String) = (601, sprintf "Mismatched quotation, beginning with '%s'" a0) /// Unmatched '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:439) + /// (Originally from src/fsharp/FSComp.txt:452) static member parsUnmatched(a0 : System.String) = (602, sprintf "Unmatched '%s'" a0) /// Unmatched '[|' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:440) + /// (Originally from src/fsharp/FSComp.txt:453) static member parsUnmatchedBracketBar() = (603, sprintf "Unmatched '[|'" ) /// Unmatched '{' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:441) + /// (Originally from src/fsharp/FSComp.txt:454) static member parsUnmatchedBrace() = (604, sprintf "Unmatched '{'" ) /// Unmatched '{|' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:442) + /// (Originally from src/fsharp/FSComp.txt:455) static member parsUnmatchedBraceBar() = (605, sprintf "Unmatched '{|'" ) /// Field bindings must have the form 'id = expr;' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:443) + /// (Originally from src/fsharp/FSComp.txt:456) static member parsFieldBinding() = (609, sprintf "Field bindings must have the form 'id = expr;'" ) /// This member is not permitted in an object implementation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:444) + /// (Originally from src/fsharp/FSComp.txt:457) static member parsMemberIllegalInObjectImplementation() = (610, sprintf "This member is not permitted in an object implementation" ) /// Missing function body - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:445) + /// (Originally from src/fsharp/FSComp.txt:458) static member parsMissingFunctionBody() = (611, sprintf "Missing function body" ) /// Syntax error in labelled type argument - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:446) + /// (Originally from src/fsharp/FSComp.txt:459) static member parsSyntaxErrorInLabeledType() = (613, sprintf "Syntax error in labelled type argument" ) /// Unexpected infix operator in type expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:447) + /// (Originally from src/fsharp/FSComp.txt:460) static member parsUnexpectedInfixOperator() = (615, sprintf "Unexpected infix operator in type expression" ) /// The syntax '(typ,...,typ) ident' is not used in F# code. Consider using 'ident' instead - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:448) + /// (Originally from src/fsharp/FSComp.txt:461) static member parsMultiArgumentGenericTypeFormDeprecated() = (sprintf "The syntax '(typ,...,typ) ident' is not used in F# code. Consider using 'ident' instead" ) /// Invalid literal in type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:449) + /// (Originally from src/fsharp/FSComp.txt:462) static member parsInvalidLiteralInType() = (618, sprintf "Invalid literal in type" ) /// Unexpected infix operator in unit-of-measure expression. Legal operators are '*', '/' and '^'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:450) + /// (Originally from src/fsharp/FSComp.txt:463) static member parsUnexpectedOperatorForUnitOfMeasure() = (619, sprintf "Unexpected infix operator in unit-of-measure expression. Legal operators are '*', '/' and '^'." ) /// Unexpected integer literal in unit-of-measure expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:451) + /// (Originally from src/fsharp/FSComp.txt:464) static member parsUnexpectedIntegerLiteralForUnitOfMeasure() = (620, sprintf "Unexpected integer literal in unit-of-measure expression" ) /// Syntax error: unexpected type parameter specification - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:452) + /// (Originally from src/fsharp/FSComp.txt:465) static member parsUnexpectedTypeParameter() = (621, sprintf "Syntax error: unexpected type parameter specification" ) /// Mismatched quotation operator name, beginning with '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:453) + /// (Originally from src/fsharp/FSComp.txt:466) static member parsMismatchedQuotationName(a0 : System.String) = (622, sprintf "Mismatched quotation operator name, beginning with '%s'" a0) /// Active pattern case identifiers must begin with an uppercase letter - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:454) + /// (Originally from src/fsharp/FSComp.txt:467) static member parsActivePatternCaseMustBeginWithUpperCase() = (623, sprintf "Active pattern case identifiers must begin with an uppercase letter" ) /// The '|' character is not permitted in active pattern case identifiers - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:455) + /// (Originally from src/fsharp/FSComp.txt:468) static member parsActivePatternCaseContainsPipe() = (624, sprintf "The '|' character is not permitted in active pattern case identifiers" ) /// Denominator must not be 0 in unit-of-measure exponent - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:456) + /// (Originally from src/fsharp/FSComp.txt:469) static member parsIllegalDenominatorForMeasureExponent() = (625, sprintf "Denominator must not be 0 in unit-of-measure exponent" ) /// No '=' symbol should follow a 'namespace' declaration - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:457) + /// (Originally from src/fsharp/FSComp.txt:470) static member parsNoEqualShouldFollowNamespace() = (sprintf "No '=' symbol should follow a 'namespace' declaration" ) /// The syntax 'module ... = struct .. end' is not used in F# code. Consider using 'module ... = begin .. end' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:458) + /// (Originally from src/fsharp/FSComp.txt:471) static member parsSyntaxModuleStructEndDeprecated() = (sprintf "The syntax 'module ... = struct .. end' is not used in F# code. Consider using 'module ... = begin .. end'" ) /// The syntax 'module ... : sig .. end' is not used in F# code. Consider using 'module ... = begin .. end' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:459) + /// (Originally from src/fsharp/FSComp.txt:472) static member parsSyntaxModuleSigEndDeprecated() = (sprintf "The syntax 'module ... : sig .. end' is not used in F# code. Consider using 'module ... = begin .. end'" ) /// A static field was used where an instance field is expected - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:460) + /// (Originally from src/fsharp/FSComp.txt:473) static member tcStaticFieldUsedWhenInstanceFieldExpected() = (627, sprintf "A static field was used where an instance field is expected" ) /// Method '%s' is not accessible from this code location - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:461) + /// (Originally from src/fsharp/FSComp.txt:474) static member tcMethodNotAccessible(a0 : System.String) = (629, sprintf "Method '%s' is not accessible from this code location" a0) /// Implicit product of measures following / - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:463) + /// (Originally from src/fsharp/FSComp.txt:476) static member tcImplicitMeasureFollowingSlash() = (632, sprintf "Implicit product of measures following /" ) /// Unexpected SynMeasure.Anon - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:464) + /// (Originally from src/fsharp/FSComp.txt:477) static member tcUnexpectedMeasureAnon() = (633, sprintf "Unexpected SynMeasure.Anon" ) /// Non-zero constants cannot have generic units. For generic zero, write 0.0<_>. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:465) + /// (Originally from src/fsharp/FSComp.txt:478) static member tcNonZeroConstantCannotHaveGenericUnit() = (634, sprintf "Non-zero constants cannot have generic units. For generic zero, write 0.0<_>." ) /// In sequence expressions, results are generated using 'yield' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:466) + /// (Originally from src/fsharp/FSComp.txt:479) static member tcSeqResultsUseYield() = (635, sprintf "In sequence expressions, results are generated using 'yield'" ) /// Unexpected big rational constant - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:467) + /// (Originally from src/fsharp/FSComp.txt:480) static member tcUnexpectedBigRationalConstant() = (sprintf "Unexpected big rational constant" ) /// Units-of-measure supported only on float, float32, decimal and signed integer types - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:468) + /// (Originally from src/fsharp/FSComp.txt:481) static member tcInvalidTypeForUnitsOfMeasure() = (636, sprintf "Units-of-measure supported only on float, float32, decimal and signed integer types" ) /// Unexpected Const_uint16array - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:469) + /// (Originally from src/fsharp/FSComp.txt:482) static member tcUnexpectedConstUint16Array() = (sprintf "Unexpected Const_uint16array" ) /// Unexpected Const_bytearray - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:470) + /// (Originally from src/fsharp/FSComp.txt:483) static member tcUnexpectedConstByteArray() = (sprintf "Unexpected Const_bytearray" ) /// A parameter with attributes must also be given a name, e.g. '[] Name : Type' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:471) + /// (Originally from src/fsharp/FSComp.txt:484) static member tcParameterRequiresName() = (640, sprintf "A parameter with attributes must also be given a name, e.g. '[] Name : Type'" ) /// Return values cannot have names - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:472) + /// (Originally from src/fsharp/FSComp.txt:485) static member tcReturnValuesCannotHaveNames() = (641, sprintf "Return values cannot have names" ) /// MemberKind.PropertyGetSet only expected in parse trees - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:473) + /// (Originally from src/fsharp/FSComp.txt:486) static member tcMemberKindPropertyGetSetNotExpected() = (sprintf "MemberKind.PropertyGetSet only expected in parse trees" ) /// Namespaces cannot contain values. Consider using a module to hold your value declarations. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:474) + /// (Originally from src/fsharp/FSComp.txt:487) static member tcNamespaceCannotContainValues() = (201, sprintf "Namespaces cannot contain values. Consider using a module to hold your value declarations." ) /// Namespaces cannot contain extension members except in the same file and namespace declaration group where the type is defined. Consider using a module to hold declarations of extension members. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:475) + /// (Originally from src/fsharp/FSComp.txt:488) static member tcNamespaceCannotContainExtensionMembers() = (644, sprintf "Namespaces cannot contain extension members except in the same file and namespace declaration group where the type is defined. Consider using a module to hold declarations of extension members." ) /// Multiple visibility attributes have been specified for this identifier - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:476) + /// (Originally from src/fsharp/FSComp.txt:489) static member tcMultipleVisibilityAttributes() = (645, sprintf "Multiple visibility attributes have been specified for this identifier" ) /// Multiple visibility attributes have been specified for this identifier. 'let' bindings in classes are always private, as are any 'let' bindings inside expressions. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:477) + /// (Originally from src/fsharp/FSComp.txt:490) static member tcMultipleVisibilityAttributesWithLet() = (646, sprintf "Multiple visibility attributes have been specified for this identifier. 'let' bindings in classes are always private, as are any 'let' bindings inside expressions." ) /// The name '(%s)' should not be used as a member name. To define comparison semantics for a type, implement the 'System.IComparable' interface. If defining a static member for use from other CLI languages then use the name '%s' instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:478) + /// (Originally from src/fsharp/FSComp.txt:491) static member tcInvalidMethodNameForRelationalOperator(a0 : System.String, a1 : System.String) = (sprintf "The name '(%s)' should not be used as a member name. To define comparison semantics for a type, implement the 'System.IComparable' interface. If defining a static member for use from other CLI languages then use the name '%s' instead." a0 a1) /// The name '(%s)' should not be used as a member name. To define equality semantics for a type, override the 'Object.Equals' member. If defining a static member for use from other CLI languages then use the name '%s' instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:479) + /// (Originally from src/fsharp/FSComp.txt:492) static member tcInvalidMethodNameForEquality(a0 : System.String, a1 : System.String) = (sprintf "The name '(%s)' should not be used as a member name. To define equality semantics for a type, override the 'Object.Equals' member. If defining a static member for use from other CLI languages then use the name '%s' instead." a0 a1) /// The name '(%s)' should not be used as a member name. If defining a static member for use from other CLI languages then use the name '%s' instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:480) + /// (Originally from src/fsharp/FSComp.txt:493) static member tcInvalidMemberName(a0 : System.String, a1 : System.String) = (sprintf "The name '(%s)' should not be used as a member name. If defining a static member for use from other CLI languages then use the name '%s' instead." a0 a1) /// The name '(%s)' should not be used as a member name because it is given a standard definition in the F# library over fixed types - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:481) + /// (Originally from src/fsharp/FSComp.txt:494) static member tcInvalidMemberNameFixedTypes(a0 : System.String) = (sprintf "The name '(%s)' should not be used as a member name because it is given a standard definition in the F# library over fixed types" a0) /// The '%s' operator should not normally be redefined. To define overloaded comparison semantics for a particular type, implement the 'System.IComparable' interface in the definition of that type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:482) + /// (Originally from src/fsharp/FSComp.txt:495) static member tcInvalidOperatorDefinitionRelational(a0 : System.String) = (sprintf "The '%s' operator should not normally be redefined. To define overloaded comparison semantics for a particular type, implement the 'System.IComparable' interface in the definition of that type." a0) /// The '%s' operator should not normally be redefined. To define equality semantics for a type, override the 'Object.Equals' member in the definition of that type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:483) + /// (Originally from src/fsharp/FSComp.txt:496) static member tcInvalidOperatorDefinitionEquality(a0 : System.String) = (sprintf "The '%s' operator should not normally be redefined. To define equality semantics for a type, override the 'Object.Equals' member in the definition of that type." a0) /// The '%s' operator should not normally be redefined. Consider using a different operator name - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:484) + /// (Originally from src/fsharp/FSComp.txt:497) static member tcInvalidOperatorDefinition(a0 : System.String) = (sprintf "The '%s' operator should not normally be redefined. Consider using a different operator name" a0) /// The '%s' operator cannot be redefined. Consider using a different operator name - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:485) + /// (Originally from src/fsharp/FSComp.txt:498) static member tcInvalidIndexOperatorDefinition(a0 : System.String) = (sprintf "The '%s' operator cannot be redefined. Consider using a different operator name" a0) /// Expected module or namespace parent %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:486) + /// (Originally from src/fsharp/FSComp.txt:499) static member tcExpectModuleOrNamespaceParent(a0 : System.String) = (sprintf "Expected module or namespace parent %s" a0) /// The struct, record or union type '%s' implements the interface 'System.IComparable' explicitly. You must apply the 'CustomComparison' attribute to the type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:487) + /// (Originally from src/fsharp/FSComp.txt:500) static member tcImplementsIComparableExplicitly(a0 : System.String) = (647, sprintf "The struct, record or union type '%s' implements the interface 'System.IComparable' explicitly. You must apply the 'CustomComparison' attribute to the type." a0) /// The struct, record or union type '%s' implements the interface 'System.IComparable<_>' explicitly. You must apply the 'CustomComparison' attribute to the type, and should also provide a consistent implementation of the non-generic interface System.IComparable. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:488) + /// (Originally from src/fsharp/FSComp.txt:501) static member tcImplementsGenericIComparableExplicitly(a0 : System.String) = (648, sprintf "The struct, record or union type '%s' implements the interface 'System.IComparable<_>' explicitly. You must apply the 'CustomComparison' attribute to the type, and should also provide a consistent implementation of the non-generic interface System.IComparable." a0) /// The struct, record or union type '%s' implements the interface 'System.IStructuralComparable' explicitly. Apply the 'CustomComparison' attribute to the type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:489) + /// (Originally from src/fsharp/FSComp.txt:502) static member tcImplementsIStructuralComparableExplicitly(a0 : System.String) = (649, sprintf "The struct, record or union type '%s' implements the interface 'System.IStructuralComparable' explicitly. Apply the 'CustomComparison' attribute to the type." a0) /// This record contains fields from inconsistent types - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:490) + /// (Originally from src/fsharp/FSComp.txt:503) static member tcRecordFieldInconsistentTypes() = (656, sprintf "This record contains fields from inconsistent types" ) /// DLLImport stubs cannot be inlined - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:491) + /// (Originally from src/fsharp/FSComp.txt:504) static member tcDllImportStubsCannotBeInlined() = (657, sprintf "DLLImport stubs cannot be inlined" ) /// Structs may only bind a 'this' parameter at member declarations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:492) + /// (Originally from src/fsharp/FSComp.txt:505) static member tcStructsCanOnlyBindThisAtMemberDeclaration() = (658, sprintf "Structs may only bind a 'this' parameter at member declarations" ) /// Unexpected expression at recursive inference point - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:493) + /// (Originally from src/fsharp/FSComp.txt:506) static member tcUnexpectedExprAtRecInfPoint() = (659, sprintf "Unexpected expression at recursive inference point" ) /// This code is less generic than required by its annotations because the explicit type variable '%s' could not be generalized. It was constrained to be '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:494) + /// (Originally from src/fsharp/FSComp.txt:507) static member tcLessGenericBecauseOfAnnotation(a0 : System.String, a1 : System.String) = (660, sprintf "This code is less generic than required by its annotations because the explicit type variable '%s' could not be generalized. It was constrained to be '%s'." a0 a1) /// One or more of the explicit class or function type variables for this binding could not be generalized, because they were constrained to other types - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:495) + /// (Originally from src/fsharp/FSComp.txt:508) static member tcConstrainedTypeVariableCannotBeGeneralized() = (661, sprintf "One or more of the explicit class or function type variables for this binding could not be generalized, because they were constrained to other types" ) /// A generic type parameter has been used in a way that constrains it to always be '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:496) + /// (Originally from src/fsharp/FSComp.txt:509) static member tcGenericParameterHasBeenConstrained(a0 : System.String) = (662, sprintf "A generic type parameter has been used in a way that constrains it to always be '%s'" a0) /// This type parameter has been used in a way that constrains it to always be '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:497) + /// (Originally from src/fsharp/FSComp.txt:510) static member tcTypeParameterHasBeenConstrained(a0 : System.String) = (663, sprintf "This type parameter has been used in a way that constrains it to always be '%s'" a0) /// The type parameters inferred for this value are not stable under the erasure of type abbreviations. This is due to the use of type abbreviations which drop or reorder type parameters, e.g. \n\ttype taggedInt<'a> = int or\n\ttype swap<'a,'b> = 'b * 'a.\nConsider declaring the type parameters for this value explicitly, e.g.\n\tlet f<'a,'b> ((x,y) : swap<'b,'a>) : swap<'a,'b> = (y,x). - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:498) + /// (Originally from src/fsharp/FSComp.txt:511) static member tcTypeParametersInferredAreNotStable() = (664, sprintf "The type parameters inferred for this value are not stable under the erasure of type abbreviations. This is due to the use of type abbreviations which drop or reorder type parameters, e.g. \n\ttype taggedInt<'a> = int or\n\ttype swap<'a,'b> = 'b * 'a.\nConsider declaring the type parameters for this value explicitly, e.g.\n\tlet f<'a,'b> ((x,y) : swap<'b,'a>) : swap<'a,'b> = (y,x)." ) /// Explicit type parameters may only be used on module or member bindings - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:499) + /// (Originally from src/fsharp/FSComp.txt:512) static member tcExplicitTypeParameterInvalid() = (665, sprintf "Explicit type parameters may only be used on module or member bindings" ) /// You must explicitly declare either all or no type parameters when overriding a generic abstract method - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:500) + /// (Originally from src/fsharp/FSComp.txt:513) static member tcOverridingMethodRequiresAllOrNoTypeParameters() = (666, sprintf "You must explicitly declare either all or no type parameters when overriding a generic abstract method" ) /// The field labels and expected type of this record expression or pattern do not uniquely determine a corresponding record type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:501) + /// (Originally from src/fsharp/FSComp.txt:514) static member tcFieldsDoNotDetermineUniqueRecordType() = (667, sprintf "The field labels and expected type of this record expression or pattern do not uniquely determine a corresponding record type" ) /// The field '%s' appears twice in this record expression or pattern - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:502) + /// (Originally from src/fsharp/FSComp.txt:515) static member tcFieldAppearsTwiceInRecord(a0 : System.String) = (668, sprintf "The field '%s' appears twice in this record expression or pattern" a0) /// Unknown union case - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:503) + /// (Originally from src/fsharp/FSComp.txt:516) static member tcUnknownUnion() = (669, sprintf "Unknown union case" ) /// This code is not sufficiently generic. The type variable %s could not be generalized because it would escape its scope. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:504) + /// (Originally from src/fsharp/FSComp.txt:517) static member tcNotSufficientlyGenericBecauseOfScope(a0 : System.String) = (670, sprintf "This code is not sufficiently generic. The type variable %s could not be generalized because it would escape its scope." a0) /// A property cannot have explicit type parameters. Consider using a method instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:505) + /// (Originally from src/fsharp/FSComp.txt:518) static member tcPropertyRequiresExplicitTypeParameters() = (671, sprintf "A property cannot have explicit type parameters. Consider using a method instead." ) /// A constructor cannot have explicit type parameters. Consider using a static construction method instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:506) + /// (Originally from src/fsharp/FSComp.txt:519) static member tcConstructorCannotHaveTypeParameters() = (672, sprintf "A constructor cannot have explicit type parameters. Consider using a static construction method instead." ) /// This instance member needs a parameter to represent the object being invoked. Make the member static or use the notation 'member x.Member(args) = ...'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:507) + /// (Originally from src/fsharp/FSComp.txt:520) static member tcInstanceMemberRequiresTarget() = (673, sprintf "This instance member needs a parameter to represent the object being invoked. Make the member static or use the notation 'member x.Member(args) = ...'." ) /// Unexpected source-level property specification in syntax tree - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:508) + /// (Originally from src/fsharp/FSComp.txt:521) static member tcUnexpectedPropertyInSyntaxTree() = (674, sprintf "Unexpected source-level property specification in syntax tree" ) /// A static initializer requires an argument - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:509) + /// (Originally from src/fsharp/FSComp.txt:522) static member tcStaticInitializerRequiresArgument() = (675, sprintf "A static initializer requires an argument" ) /// An object constructor requires an argument - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:510) + /// (Originally from src/fsharp/FSComp.txt:523) static member tcObjectConstructorRequiresArgument() = (676, sprintf "An object constructor requires an argument" ) /// This static member should not have a 'this' parameter. Consider using the notation 'member Member(args) = ...'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:511) + /// (Originally from src/fsharp/FSComp.txt:524) static member tcStaticMemberShouldNotHaveThis() = (677, sprintf "This static member should not have a 'this' parameter. Consider using the notation 'member Member(args) = ...'." ) /// An explicit static initializer should use the syntax 'static new(args) = expr' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:512) + /// (Originally from src/fsharp/FSComp.txt:525) static member tcExplicitStaticInitializerSyntax() = (678, sprintf "An explicit static initializer should use the syntax 'static new(args) = expr'" ) /// An explicit object constructor should use the syntax 'new(args) = expr' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:513) + /// (Originally from src/fsharp/FSComp.txt:526) static member tcExplicitObjectConstructorSyntax() = (679, sprintf "An explicit object constructor should use the syntax 'new(args) = expr'" ) /// Unexpected source-level property specification - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:514) + /// (Originally from src/fsharp/FSComp.txt:527) static member tcUnexpectedPropertySpec() = (680, sprintf "Unexpected source-level property specification" ) /// This form of object expression is not used in F#. Use 'member this.MemberName ... = ...' to define member implementations in object expressions. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:515) + /// (Originally from src/fsharp/FSComp.txt:528) static member tcObjectExpressionFormDeprecated() = (sprintf "This form of object expression is not used in F#. Use 'member this.MemberName ... = ...' to define member implementations in object expressions." ) /// Invalid declaration - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:516) + /// (Originally from src/fsharp/FSComp.txt:529) static member tcInvalidDeclaration() = (682, sprintf "Invalid declaration" ) /// Attributes are not allowed within patterns - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:517) + /// (Originally from src/fsharp/FSComp.txt:530) static member tcAttributesInvalidInPatterns() = (683, sprintf "Attributes are not allowed within patterns" ) /// The generic function '%s' must be given explicit type argument(s) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:518) + /// (Originally from src/fsharp/FSComp.txt:531) static member tcFunctionRequiresExplicitTypeArguments(a0 : System.String) = (685, sprintf "The generic function '%s' must be given explicit type argument(s)" a0) /// The method or function '%s' should not be given explicit type argument(s) because it does not declare its type parameters explicitly - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:519) + /// (Originally from src/fsharp/FSComp.txt:532) static member tcDoesNotAllowExplicitTypeArguments(a0 : System.String) = (686, sprintf "The method or function '%s' should not be given explicit type argument(s) because it does not declare its type parameters explicitly" a0) /// This value, type or method expects %d type parameter(s) but was given %d - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:520) + /// (Originally from src/fsharp/FSComp.txt:533) static member tcTypeParameterArityMismatch(a0 : System.Int32, a1 : System.Int32) = (687, sprintf "This value, type or method expects %d type parameter(s) but was given %d" a0 a1) /// The default, zero-initializing constructor of a struct type may only be used if all the fields of the struct type admit default initialization - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:521) + /// (Originally from src/fsharp/FSComp.txt:534) static member tcDefaultStructConstructorCall() = (688, sprintf "The default, zero-initializing constructor of a struct type may only be used if all the fields of the struct type admit default initialization" ) /// Couldn't find Dispose on IDisposable, or it was overloaded - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:522) + /// (Originally from src/fsharp/FSComp.txt:535) static member tcCouldNotFindIDisposable() = (sprintf "Couldn't find Dispose on IDisposable, or it was overloaded" ) /// This value is not a literal and cannot be used in a pattern - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:523) + /// (Originally from src/fsharp/FSComp.txt:536) static member tcNonLiteralCannotBeUsedInPattern() = (689, sprintf "This value is not a literal and cannot be used in a pattern" ) /// This field is readonly - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:524) + /// (Originally from src/fsharp/FSComp.txt:537) static member tcFieldIsReadonly() = (690, sprintf "This field is readonly" ) /// Named arguments must appear after all other arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:525) + /// (Originally from src/fsharp/FSComp.txt:538) static member tcNameArgumentsMustAppearLast() = (691, sprintf "Named arguments must appear after all other arguments" ) /// This function value is being used to construct a delegate type whose signature includes a byref argument. You must use an explicit lambda expression taking %d arguments. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:526) + /// (Originally from src/fsharp/FSComp.txt:539) static member tcFunctionRequiresExplicitLambda(a0 : System.Int32) = (692, sprintf "This function value is being used to construct a delegate type whose signature includes a byref argument. You must use an explicit lambda expression taking %d arguments." a0) /// The type '%s' is not a type whose values can be enumerated with this syntax, i.e. is not compatible with either seq<_>, IEnumerable<_> or IEnumerable and does not have a GetEnumerator method - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:527) + /// (Originally from src/fsharp/FSComp.txt:540) static member tcTypeCannotBeEnumerated(a0 : System.String) = (693, sprintf "The type '%s' is not a type whose values can be enumerated with this syntax, i.e. is not compatible with either seq<_>, IEnumerable<_> or IEnumerable and does not have a GetEnumerator method" a0) /// This recursive binding uses an invalid mixture of recursive forms - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:528) + /// (Originally from src/fsharp/FSComp.txt:541) static member tcInvalidMixtureOfRecursiveForms() = (695, sprintf "This recursive binding uses an invalid mixture of recursive forms" ) /// This is not a valid object construction expression. Explicit object constructors must either call an alternate constructor or initialize all fields of the object and specify a call to a super class constructor. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:529) + /// (Originally from src/fsharp/FSComp.txt:542) static member tcInvalidObjectConstructionExpression() = (696, sprintf "This is not a valid object construction expression. Explicit object constructors must either call an alternate constructor or initialize all fields of the object and specify a call to a super class constructor." ) /// Invalid constraint - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:530) + /// (Originally from src/fsharp/FSComp.txt:543) static member tcInvalidConstraint() = (697, sprintf "Invalid constraint" ) /// Invalid constraint: the type used for the constraint is sealed, which means the constraint could only be satisfied by at most one solution - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:531) + /// (Originally from src/fsharp/FSComp.txt:544) static member tcInvalidConstraintTypeSealed() = (698, sprintf "Invalid constraint: the type used for the constraint is sealed, which means the constraint could only be satisfied by at most one solution" ) /// An 'enum' constraint must be of the form 'enum' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:532) + /// (Originally from src/fsharp/FSComp.txt:545) static member tcInvalidEnumConstraint() = (699, sprintf "An 'enum' constraint must be of the form 'enum'" ) /// 'new' constraints must take one argument of type 'unit' and return the constructed type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:533) + /// (Originally from src/fsharp/FSComp.txt:546) static member tcInvalidNewConstraint() = (700, sprintf "'new' constraints must take one argument of type 'unit' and return the constructed type" ) /// This property has an invalid type. Properties taking multiple indexer arguments should have types of the form 'ty1 * ty2 -> ty3'. Properties returning functions should have types of the form '(ty1 -> ty2)'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:534) + /// (Originally from src/fsharp/FSComp.txt:547) static member tcInvalidPropertyType() = (701, sprintf "This property has an invalid type. Properties taking multiple indexer arguments should have types of the form 'ty1 * ty2 -> ty3'. Properties returning functions should have types of the form '(ty1 -> ty2)'." ) /// Expected unit-of-measure parameter, not type parameter. Explicit unit-of-measure parameters must be marked with the [] attribute. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:535) + /// (Originally from src/fsharp/FSComp.txt:548) static member tcExpectedUnitOfMeasureMarkWithAttribute() = (702, sprintf "Expected unit-of-measure parameter, not type parameter. Explicit unit-of-measure parameters must be marked with the [] attribute." ) /// Expected type parameter, not unit-of-measure parameter - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:536) + /// (Originally from src/fsharp/FSComp.txt:549) static member tcExpectedTypeParameter() = (703, sprintf "Expected type parameter, not unit-of-measure parameter" ) /// Expected type, not unit-of-measure - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:537) + /// (Originally from src/fsharp/FSComp.txt:550) static member tcExpectedTypeNotUnitOfMeasure() = (704, sprintf "Expected type, not unit-of-measure" ) /// Expected unit-of-measure, not type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:538) + /// (Originally from src/fsharp/FSComp.txt:551) static member tcExpectedUnitOfMeasureNotType() = (705, sprintf "Expected unit-of-measure, not type" ) /// Units-of-measure cannot be used as prefix arguments to a type. Rewrite as postfix arguments in angle brackets. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:539) + /// (Originally from src/fsharp/FSComp.txt:552) static member tcInvalidUnitsOfMeasurePrefix() = (706, sprintf "Units-of-measure cannot be used as prefix arguments to a type. Rewrite as postfix arguments in angle brackets." ) /// Unit-of-measure cannot be used in type constructor application - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:540) + /// (Originally from src/fsharp/FSComp.txt:553) static member tcUnitsOfMeasureInvalidInTypeConstructor() = (707, sprintf "Unit-of-measure cannot be used in type constructor application" ) /// This control construct may only be used if the computation expression builder defines a '%s' method - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:541) + /// (Originally from src/fsharp/FSComp.txt:554) static member tcRequireBuilderMethod(a0 : System.String) = (708, sprintf "This control construct may only be used if the computation expression builder defines a '%s' method" a0) /// This type has no nested types - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:542) + /// (Originally from src/fsharp/FSComp.txt:555) static member tcTypeHasNoNestedTypes() = (709, sprintf "This type has no nested types" ) /// Unexpected %s in type expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:543) + /// (Originally from src/fsharp/FSComp.txt:556) static member tcUnexpectedSymbolInTypeExpression(a0 : System.String) = (711, sprintf "Unexpected %s in type expression" a0) /// Type parameter cannot be used as type constructor - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:544) + /// (Originally from src/fsharp/FSComp.txt:557) static member tcTypeParameterInvalidAsTypeConstructor() = (712, sprintf "Type parameter cannot be used as type constructor" ) /// Illegal syntax in type expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:545) + /// (Originally from src/fsharp/FSComp.txt:558) static member tcIllegalSyntaxInTypeExpression() = (713, sprintf "Illegal syntax in type expression" ) /// Anonymous unit-of-measure cannot be nested inside another unit-of-measure expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:546) + /// (Originally from src/fsharp/FSComp.txt:559) static member tcAnonymousUnitsOfMeasureCannotBeNested() = (714, sprintf "Anonymous unit-of-measure cannot be nested inside another unit-of-measure expression" ) /// Anonymous type variables are not permitted in this declaration - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:547) + /// (Originally from src/fsharp/FSComp.txt:560) static member tcAnonymousTypeInvalidInDeclaration() = (715, sprintf "Anonymous type variables are not permitted in this declaration" ) /// Unexpected / in type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:548) + /// (Originally from src/fsharp/FSComp.txt:561) static member tcUnexpectedSlashInType() = (716, sprintf "Unexpected / in type" ) /// Unexpected type arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:549) + /// (Originally from src/fsharp/FSComp.txt:562) static member tcUnexpectedTypeArguments() = (717, sprintf "Unexpected type arguments" ) /// Optional arguments are only permitted on type members - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:550) + /// (Originally from src/fsharp/FSComp.txt:563) static member tcOptionalArgsOnlyOnMembers() = (718, sprintf "Optional arguments are only permitted on type members" ) /// Name '%s' not bound in pattern context - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:551) + /// (Originally from src/fsharp/FSComp.txt:564) static member tcNameNotBoundInPattern(a0 : System.String) = (719, sprintf "Name '%s' not bound in pattern context" a0) /// Non-primitive numeric literal constants cannot be used in pattern matches because they can be mapped to multiple different types through the use of a NumericLiteral module. Consider using replacing with a variable, and use 'when = ' at the end of the match clause. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:552) + /// (Originally from src/fsharp/FSComp.txt:565) static member tcInvalidNonPrimitiveLiteralInPatternMatch() = (720, sprintf "Non-primitive numeric literal constants cannot be used in pattern matches because they can be mapped to multiple different types through the use of a NumericLiteral module. Consider using replacing with a variable, and use 'when = ' at the end of the match clause." ) /// Type arguments cannot be specified here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:553) + /// (Originally from src/fsharp/FSComp.txt:566) static member tcInvalidTypeArgumentUsage() = (721, sprintf "Type arguments cannot be specified here" ) /// Only active patterns returning exactly one result may accept arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:554) + /// (Originally from src/fsharp/FSComp.txt:567) static member tcRequireActivePatternWithOneResult() = (722, sprintf "Only active patterns returning exactly one result may accept arguments" ) /// Invalid argument to parameterized pattern label - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:555) + /// (Originally from src/fsharp/FSComp.txt:568) static member tcInvalidArgForParameterizedPattern() = (723, sprintf "Invalid argument to parameterized pattern label" ) /// Internal error. Invalid index into active pattern array - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:556) + /// (Originally from src/fsharp/FSComp.txt:569) static member tcInvalidIndexIntoActivePatternArray() = (724, sprintf "Internal error. Invalid index into active pattern array" ) /// This union case does not take arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:557) + /// (Originally from src/fsharp/FSComp.txt:570) static member tcUnionCaseDoesNotTakeArguments() = (725, sprintf "This union case does not take arguments" ) /// This union case takes one argument - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:558) + /// (Originally from src/fsharp/FSComp.txt:571) static member tcUnionCaseRequiresOneArgument() = (726, sprintf "This union case takes one argument" ) /// This union case expects %d arguments in tupled form - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:559) + /// (Originally from src/fsharp/FSComp.txt:572) static member tcUnionCaseExpectsTupledArguments(a0 : System.Int32) = (727, sprintf "This union case expects %d arguments in tupled form" a0) /// Field '%s' is not static - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:560) + /// (Originally from src/fsharp/FSComp.txt:573) static member tcFieldIsNotStatic(a0 : System.String) = (728, sprintf "Field '%s' is not static" a0) /// This field is not a literal and cannot be used in a pattern - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:561) + /// (Originally from src/fsharp/FSComp.txt:574) static member tcFieldNotLiteralCannotBeUsedInPattern() = (729, sprintf "This field is not a literal and cannot be used in a pattern" ) /// This is not a variable, constant, active recognizer or literal - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:562) + /// (Originally from src/fsharp/FSComp.txt:575) static member tcRequireVarConstRecogOrLiteral() = (730, sprintf "This is not a variable, constant, active recognizer or literal" ) /// This is not a valid pattern - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:563) + /// (Originally from src/fsharp/FSComp.txt:576) static member tcInvalidPattern() = (731, sprintf "This is not a valid pattern" ) /// Character range matches have been removed in F#. Consider using a 'when' pattern guard instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:564) + /// (Originally from src/fsharp/FSComp.txt:577) static member tcUseWhenPatternGuard() = (sprintf "Character range matches have been removed in F#. Consider using a 'when' pattern guard instead." ) /// Illegal pattern - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:565) + /// (Originally from src/fsharp/FSComp.txt:578) static member tcIllegalPattern() = (733, sprintf "Illegal pattern" ) /// Syntax error - unexpected '?' symbol - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:566) + /// (Originally from src/fsharp/FSComp.txt:579) static member tcSyntaxErrorUnexpectedQMark() = (734, sprintf "Syntax error - unexpected '?' symbol" ) /// Expected %d expressions, got %d - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:567) + /// (Originally from src/fsharp/FSComp.txt:580) static member tcExpressionCountMisMatch(a0 : System.Int32, a1 : System.Int32) = (735, sprintf "Expected %d expressions, got %d" a0 a1) /// TcExprUndelayed: delayed - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:568) + /// (Originally from src/fsharp/FSComp.txt:581) static member tcExprUndelayed() = (736, sprintf "TcExprUndelayed: delayed" ) /// This expression form may only be used in sequence and computation expressions - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:569) + /// (Originally from src/fsharp/FSComp.txt:582) static member tcExpressionRequiresSequence() = (737, sprintf "This expression form may only be used in sequence and computation expressions" ) /// Invalid object expression. Objects without overrides or interfaces should use the expression form 'new Type(args)' without braces. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:570) + /// (Originally from src/fsharp/FSComp.txt:583) static member tcInvalidObjectExpressionSyntaxForm() = (738, sprintf "Invalid object expression. Objects without overrides or interfaces should use the expression form 'new Type(args)' without braces." ) /// Invalid object, sequence or record expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:571) + /// (Originally from src/fsharp/FSComp.txt:584) static member tcInvalidObjectSequenceOrRecordExpression() = (739, sprintf "Invalid object, sequence or record expression" ) /// Invalid record, sequence or computation expression. Sequence expressions should be of the form 'seq { ... }' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:572) + /// (Originally from src/fsharp/FSComp.txt:585) static member tcInvalidSequenceExpressionSyntaxForm() = (740, sprintf "Invalid record, sequence or computation expression. Sequence expressions should be of the form 'seq { ... }'" ) /// This list or array expression includes an element of the form 'if ... then ... else'. Parenthesize this expression to indicate it is an individual element of the list or array, to disambiguate this from a list generated using a sequence expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:573) + /// (Originally from src/fsharp/FSComp.txt:586) static member tcExpressionWithIfRequiresParenthesis() = (sprintf "This list or array expression includes an element of the form 'if ... then ... else'. Parenthesize this expression to indicate it is an individual element of the list or array, to disambiguate this from a list generated using a sequence expression" ) /// Unable to parse format string '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:574) + /// (Originally from src/fsharp/FSComp.txt:587) static member tcUnableToParseFormatString(a0 : System.String) = (741, sprintf "Unable to parse format string '%s'" a0) /// This list expression exceeds the maximum size for list literals. Use an array for larger literals and call Array.ToList. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:575) + /// (Originally from src/fsharp/FSComp.txt:588) static member tcListLiteralMaxSize() = (742, sprintf "This list expression exceeds the maximum size for list literals. Use an array for larger literals and call Array.ToList." ) /// The expression form 'expr then expr' may only be used as part of an explicit object constructor - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:576) + /// (Originally from src/fsharp/FSComp.txt:589) static member tcExpressionFormRequiresObjectConstructor() = (743, sprintf "The expression form 'expr then expr' may only be used as part of an explicit object constructor" ) /// Named arguments cannot be given to member trait calls - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:577) + /// (Originally from src/fsharp/FSComp.txt:590) static member tcNamedArgumentsCannotBeUsedInMemberTraits() = (744, sprintf "Named arguments cannot be given to member trait calls" ) /// This is not a valid name for an enumeration case - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:578) + /// (Originally from src/fsharp/FSComp.txt:591) static member tcNotValidEnumCaseName() = (745, sprintf "This is not a valid name for an enumeration case" ) /// This field is not mutable - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:579) + /// (Originally from src/fsharp/FSComp.txt:592) static member tcFieldIsNotMutable() = (746, sprintf "This field is not mutable" ) /// This construct may only be used within list, array and sequence expressions, e.g. expressions of the form 'seq { ... }', '[ ... ]' or '[| ... |]'. These use the syntax 'for ... in ... do ... yield...' to generate elements - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:580) + /// (Originally from src/fsharp/FSComp.txt:593) static member tcConstructRequiresListArrayOrSequence() = (747, sprintf "This construct may only be used within list, array and sequence expressions, e.g. expressions of the form 'seq { ... }', '[ ... ]' or '[| ... |]'. These use the syntax 'for ... in ... do ... yield...' to generate elements" ) /// This construct may only be used within computation expressions. To return a value from an ordinary function simply write the expression without 'return'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:581) + /// (Originally from src/fsharp/FSComp.txt:594) static member tcConstructRequiresComputationExpressions() = (748, sprintf "This construct may only be used within computation expressions. To return a value from an ordinary function simply write the expression without 'return'." ) /// This construct may only be used within sequence or computation expressions - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:582) + /// (Originally from src/fsharp/FSComp.txt:595) static member tcConstructRequiresSequenceOrComputations() = (749, sprintf "This construct may only be used within sequence or computation expressions" ) /// This construct may only be used within computation expressions - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:583) + /// (Originally from src/fsharp/FSComp.txt:596) static member tcConstructRequiresComputationExpression() = (750, sprintf "This construct may only be used within computation expressions" ) /// Invalid indexer expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:584) + /// (Originally from src/fsharp/FSComp.txt:597) static member tcInvalidIndexerExpression() = (751, sprintf "Invalid indexer expression" ) /// The operator 'expr.[idx]' has been used on an object of indeterminate type based on information prior to this program point. Consider adding further type constraints - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:585) + /// (Originally from src/fsharp/FSComp.txt:598) static member tcObjectOfIndeterminateTypeUsedRequireTypeConstraint() = (752, sprintf "The operator 'expr.[idx]' has been used on an object of indeterminate type based on information prior to this program point. Consider adding further type constraints" ) /// Cannot inherit from a variable type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:586) + /// (Originally from src/fsharp/FSComp.txt:599) static member tcCannotInheritFromVariableType() = (753, sprintf "Cannot inherit from a variable type" ) /// Calls to object constructors on type parameters cannot be given arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:587) + /// (Originally from src/fsharp/FSComp.txt:600) static member tcObjectConstructorsOnTypeParametersCannotTakeArguments() = (754, sprintf "Calls to object constructors on type parameters cannot be given arguments" ) /// The 'CompiledName' attribute cannot be used with this language element - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:588) + /// (Originally from src/fsharp/FSComp.txt:601) static member tcCompiledNameAttributeMisused() = (755, sprintf "The 'CompiledName' attribute cannot be used with this language element" ) /// '%s' may only be used with named types - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:589) + /// (Originally from src/fsharp/FSComp.txt:602) static member tcNamedTypeRequired(a0 : System.String) = (756, sprintf "'%s' may only be used with named types" a0) /// 'inherit' cannot be used on interface types. Consider implementing the interface by using 'interface ... with ... end' instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:590) + /// (Originally from src/fsharp/FSComp.txt:603) static member tcInheritCannotBeUsedOnInterfaceType() = (757, sprintf "'inherit' cannot be used on interface types. Consider implementing the interface by using 'interface ... with ... end' instead." ) /// 'new' cannot be used on interface types. Consider using an object expression '{ new ... with ... }' instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:591) + /// (Originally from src/fsharp/FSComp.txt:604) static member tcNewCannotBeUsedOnInterfaceType() = (758, sprintf "'new' cannot be used on interface types. Consider using an object expression '{ new ... with ... }' instead." ) /// 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. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:592) + /// (Originally from src/fsharp/FSComp.txt:605) static member tcAbstractTypeCannotBeInstantiated() = (759, sprintf "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." ) /// It is recommended that objects supporting the IDisposable interface are created using the syntax 'new Type(args)', rather than 'Type(args)' or 'Type' as a function value representing the constructor, to indicate that resources may be owned by the generated value - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:593) + /// (Originally from src/fsharp/FSComp.txt:606) static member tcIDisposableTypeShouldUseNew() = (760, sprintf "It is recommended that objects supporting the IDisposable interface are created using the syntax 'new Type(args)', rather than 'Type(args)' or 'Type' as a function value representing the constructor, to indicate that resources may be owned by the generated value" ) /// '%s' may only be used to construct object types - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:594) + /// (Originally from src/fsharp/FSComp.txt:607) static member tcSyntaxCanOnlyBeUsedToCreateObjectTypes(a0 : System.String) = (761, sprintf "'%s' may only be used to construct object types" a0) /// Constructors for the type '%s' must directly or indirectly call its implicit object constructor. Use a call to the implicit object constructor instead of a record expression. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:595) + /// (Originally from src/fsharp/FSComp.txt:608) static member tcConstructorRequiresCall(a0 : System.String) = (762, sprintf "Constructors for the type '%s' must directly or indirectly call its implicit object constructor. Use a call to the implicit object constructor instead of a record expression." a0) /// The field '%s' has been given a value, but is not present in the type '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:596) + /// (Originally from src/fsharp/FSComp.txt:609) static member tcUndefinedField(a0 : System.String, a1 : System.String) = (763, sprintf "The field '%s' has been given a value, but is not present in the type '%s'" a0 a1) /// No assignment given for field '%s' of type '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:597) + /// (Originally from src/fsharp/FSComp.txt:610) static member tcFieldRequiresAssignment(a0 : System.String, a1 : System.String) = (764, sprintf "No assignment given for field '%s' of type '%s'" a0 a1) /// Extraneous fields have been given values - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:598) + /// (Originally from src/fsharp/FSComp.txt:611) static member tcExtraneousFieldsGivenValues() = (765, sprintf "Extraneous fields have been given values" ) /// Only overrides of abstract and virtual members may be specified in object expressions - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:599) + /// (Originally from src/fsharp/FSComp.txt:612) static member tcObjectExpressionsCanOnlyOverrideAbstractOrVirtual() = (766, sprintf "Only overrides of abstract and virtual members may be specified in object expressions" ) /// The member '%s' does not correspond to any abstract or virtual method available to override or implement. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:600) + /// (Originally from src/fsharp/FSComp.txt:613) static member tcNoAbstractOrVirtualMemberFound(a0 : System.String) = (767, sprintf "The member '%s' does not correspond to any abstract or virtual method available to override or implement." a0) /// The type %s contains the member '%s' but it is not a virtual or abstract method that is available to override or implement. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:601) + /// (Originally from src/fsharp/FSComp.txt:614) static member tcMemberFoundIsNotAbstractOrVirtual(a0 : System.String, a1 : System.String) = (767, sprintf "The type %s contains the member '%s' but it is not a virtual or abstract method that is available to override or implement." a0 a1) /// The member '%s' does not accept the correct number of arguments. %d argument(s) are expected, but %d were given. The required signature is '%s'.%s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:602) + /// (Originally from src/fsharp/FSComp.txt:615) static member tcArgumentArityMismatch(a0 : System.String, a1 : System.Int32, a2 : System.Int32, a3 : System.String, a4 : System.String) = (768, sprintf "The member '%s' does not accept the correct number of arguments. %d argument(s) are expected, but %d were given. The required signature is '%s'.%s" a0 a1 a2 a3 a4) /// The member '%s' does not accept the correct number of arguments. One overload accepts %d arguments, but %d were given. The required signature is '%s'.%s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:603) + /// (Originally from src/fsharp/FSComp.txt:616) static member tcArgumentArityMismatchOneOverload(a0 : System.String, a1 : System.Int32, a2 : System.Int32, a3 : System.String, a4 : System.String) = (769, sprintf "The member '%s' does not accept the correct number of arguments. One overload accepts %d arguments, but %d were given. The required signature is '%s'.%s" a0 a1 a2 a3 a4) /// A simple method name is required here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:604) + /// (Originally from src/fsharp/FSComp.txt:617) static member tcSimpleMethodNameRequired() = (770, sprintf "A simple method name is required here" ) /// The types System.ValueType, System.Enum, System.Delegate, System.MulticastDelegate and System.Array cannot be used as super types in an object expression or class - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:605) + /// (Originally from src/fsharp/FSComp.txt:618) static member tcPredefinedTypeCannotBeUsedAsSuperType() = (771, sprintf "The types System.ValueType, System.Enum, System.Delegate, System.MulticastDelegate and System.Array cannot be used as super types in an object expression or class" ) /// 'new' must be used with a named type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:606) + /// (Originally from src/fsharp/FSComp.txt:619) static member tcNewMustBeUsedWithNamedType() = (772, sprintf "'new' must be used with a named type" ) /// Cannot create an extension of a sealed type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:607) + /// (Originally from src/fsharp/FSComp.txt:620) static member tcCannotCreateExtensionOfSealedType() = (773, sprintf "Cannot create an extension of a sealed type" ) /// No arguments may be given when constructing a record value - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:608) + /// (Originally from src/fsharp/FSComp.txt:621) static member tcNoArgumentsForRecordValue() = (774, sprintf "No arguments may be given when constructing a record value" ) /// Interface implementations cannot be given on construction expressions - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:609) + /// (Originally from src/fsharp/FSComp.txt:622) static member tcNoInterfaceImplementationForConstructionExpression() = (775, sprintf "Interface implementations cannot be given on construction expressions" ) /// Object construction expressions may only be used to implement constructors in class types - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:610) + /// (Originally from src/fsharp/FSComp.txt:623) static member tcObjectConstructionCanOnlyBeUsedInClassTypes() = (776, sprintf "Object construction expressions may only be used to implement constructors in class types" ) /// Only simple bindings of the form 'id = expr' can be used in construction expressions - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:611) + /// (Originally from src/fsharp/FSComp.txt:624) static member tcOnlySimpleBindingsCanBeUsedInConstructionExpressions() = (777, sprintf "Only simple bindings of the form 'id = expr' can be used in construction expressions" ) /// Objects must be initialized by an object construction expression that calls an inherited object constructor and assigns a value to each field - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:612) + /// (Originally from src/fsharp/FSComp.txt:625) static member tcObjectsMustBeInitializedWithObjectExpression() = (778, sprintf "Objects must be initialized by an object construction expression that calls an inherited object constructor and assigns a value to each field" ) /// Expected an interface type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:613) + /// (Originally from src/fsharp/FSComp.txt:626) static member tcExpectedInterfaceType() = (779, sprintf "Expected an interface type" ) /// Constructor expressions for interfaces do not take arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:614) + /// (Originally from src/fsharp/FSComp.txt:627) static member tcConstructorForInterfacesDoNotTakeArguments() = (780, sprintf "Constructor expressions for interfaces do not take arguments" ) /// This object constructor requires arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:615) + /// (Originally from src/fsharp/FSComp.txt:628) static member tcConstructorRequiresArguments() = (781, sprintf "This object constructor requires arguments" ) /// 'new' may only be used with object constructors - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:616) + /// (Originally from src/fsharp/FSComp.txt:629) static member tcNewRequiresObjectConstructor() = (782, sprintf "'new' may only be used with object constructors" ) /// At least one override did not correctly implement its corresponding abstract member - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:617) + /// (Originally from src/fsharp/FSComp.txt:630) static member tcAtLeastOneOverrideIsInvalid() = (783, sprintf "At least one override did not correctly implement its corresponding abstract member" ) /// This numeric literal requires that a module '%s' defining functions FromZero, FromOne, FromInt32, FromInt64 and FromString be in scope - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:618) + /// (Originally from src/fsharp/FSComp.txt:631) static member tcNumericLiteralRequiresModule(a0 : System.String) = (784, sprintf "This numeric literal requires that a module '%s' defining functions FromZero, FromOne, FromInt32, FromInt64 and FromString be in scope" a0) /// Invalid record construction - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:619) + /// (Originally from src/fsharp/FSComp.txt:632) static member tcInvalidRecordConstruction() = (785, sprintf "Invalid record construction" ) /// The expression form { expr with ... } may only be used with record types. To build object types use { new Type(...) with ... } - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:620) + /// (Originally from src/fsharp/FSComp.txt:633) static member tcExpressionFormRequiresRecordTypes() = (786, sprintf "The expression form { expr with ... } may only be used with record types. To build object types use { new Type(...) with ... }" ) /// The inherited type is not an object model type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:621) + /// (Originally from src/fsharp/FSComp.txt:634) static member tcInheritedTypeIsNotObjectModelType() = (787, sprintf "The inherited type is not an object model type" ) /// Object construction expressions (i.e. record expressions with inheritance specifications) may only be used to implement constructors in object model types. Use 'new ObjectType(args)' to construct instances of object model types outside of constructors - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:622) + /// (Originally from src/fsharp/FSComp.txt:635) static member tcObjectConstructionExpressionCanOnlyImplementConstructorsInObjectModelTypes() = (788, sprintf "Object construction expressions (i.e. record expressions with inheritance specifications) may only be used to implement constructors in object model types. Use 'new ObjectType(args)' to construct instances of object model types outside of constructors" ) /// '{ }' is not a valid expression. Records must include at least one field. Empty sequences are specified by using Seq.empty or an empty list '[]'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:623) + /// (Originally from src/fsharp/FSComp.txt:636) static member tcEmptyRecordInvalid() = (789, sprintf "'{ }' is not a valid expression. Records must include at least one field. Empty sequences are specified by using Seq.empty or an empty list '[]'." ) /// This type is not a record type. Values of class and struct types must be created using calls to object constructors. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:624) + /// (Originally from src/fsharp/FSComp.txt:637) static member tcTypeIsNotARecordTypeNeedConstructor() = (790, sprintf "This type is not a record type. Values of class and struct types must be created using calls to object constructors." ) /// This type is not a record type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:625) + /// (Originally from src/fsharp/FSComp.txt:638) static member tcTypeIsNotARecordType() = (791, sprintf "This type is not a record type" ) /// This construct is ambiguous as part of a computation expression. Nested expressions may be written using 'let _ = (...)' and nested computations using 'let! res = builder { ... }'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:626) + /// (Originally from src/fsharp/FSComp.txt:639) static member tcConstructIsAmbiguousInComputationExpression() = (792, sprintf "This construct is ambiguous as part of a computation expression. Nested expressions may be written using 'let _ = (...)' and nested computations using 'let! res = builder { ... }'." ) /// This construct is ambiguous as part of a sequence expression. Nested expressions may be written using 'let _ = (...)' and nested sequences using 'yield! seq {... }'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:627) + /// (Originally from src/fsharp/FSComp.txt:640) static member tcConstructIsAmbiguousInSequenceExpression() = (793, sprintf "This construct is ambiguous as part of a sequence expression. Nested expressions may be written using 'let _ = (...)' and nested sequences using 'yield! seq {... }'." ) /// 'do!' cannot be used within sequence expressions - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:628) + /// (Originally from src/fsharp/FSComp.txt:641) static member tcDoBangIllegalInSequenceExpression() = (794, sprintf "'do!' cannot be used within sequence expressions" ) /// The use of 'let! x = coll' in sequence expressions is not permitted. Use 'for x in coll' instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:629) + /// (Originally from src/fsharp/FSComp.txt:642) static member tcUseForInSequenceExpression() = (795, sprintf "The use of 'let! x = coll' in sequence expressions is not permitted. Use 'for x in coll' instead." ) /// 'try'/'with' cannot be used within sequence expressions - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:630) + /// (Originally from src/fsharp/FSComp.txt:643) static member tcTryIllegalInSequenceExpression() = (796, sprintf "'try'/'with' cannot be used within sequence expressions" ) /// In sequence expressions, multiple results are generated using 'yield!' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:631) + /// (Originally from src/fsharp/FSComp.txt:644) static member tcUseYieldBangForMultipleResults() = (797, sprintf "In sequence expressions, multiple results are generated using 'yield!'" ) /// Invalid assignment - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:632) + /// (Originally from src/fsharp/FSComp.txt:645) static member tcInvalidAssignment() = (799, sprintf "Invalid assignment" ) /// Invalid use of a type name - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:633) + /// (Originally from src/fsharp/FSComp.txt:646) static member tcInvalidUseOfTypeName() = (800, sprintf "Invalid use of a type name" ) /// This type has no accessible object constructors - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:634) + /// (Originally from src/fsharp/FSComp.txt:647) static member tcTypeHasNoAccessibleConstructor() = (801, sprintf "This type has no accessible object constructors" ) /// Invalid use of an interface type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:637) + /// (Originally from src/fsharp/FSComp.txt:650) static member tcInvalidUseOfInterfaceType() = (804, sprintf "Invalid use of an interface type" ) /// Invalid use of a delegate constructor. Use the syntax 'new Type(args)' or just 'Type(args)'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:638) + /// (Originally from src/fsharp/FSComp.txt:651) static member tcInvalidUseOfDelegate() = (805, sprintf "Invalid use of a delegate constructor. Use the syntax 'new Type(args)' or just 'Type(args)'." ) /// Property '%s' is not static - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:639) + /// (Originally from src/fsharp/FSComp.txt:652) static member tcPropertyIsNotStatic(a0 : System.String) = (806, sprintf "Property '%s' is not static" a0) /// Property '%s' is not readable - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:640) + /// (Originally from src/fsharp/FSComp.txt:653) static member tcPropertyIsNotReadable(a0 : System.String) = (807, sprintf "Property '%s' is not readable" a0) /// This lookup cannot be used here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:641) + /// (Originally from src/fsharp/FSComp.txt:654) static member tcLookupMayNotBeUsedHere() = (808, sprintf "This lookup cannot be used here" ) /// Property '%s' is static - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:642) + /// (Originally from src/fsharp/FSComp.txt:655) static member tcPropertyIsStatic(a0 : System.String) = (809, sprintf "Property '%s' is static" a0) /// Property '%s' cannot be set - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:643) + /// (Originally from src/fsharp/FSComp.txt:656) static member tcPropertyCannotBeSet1(a0 : System.String) = (810, sprintf "Property '%s' cannot be set" a0) /// Constructors must be applied to arguments and cannot be used as first-class values. If necessary use an anonymous function '(fun arg1 ... argN -> new Type(arg1,...,argN))'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:644) + /// (Originally from src/fsharp/FSComp.txt:657) static member tcConstructorsCannotBeFirstClassValues() = (811, sprintf "Constructors must be applied to arguments and cannot be used as first-class values. If necessary use an anonymous function '(fun arg1 ... argN -> new Type(arg1,...,argN))'." ) /// The syntax 'expr.id' may only be used with record labels, properties and fields - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:645) + /// (Originally from src/fsharp/FSComp.txt:658) static member tcSyntaxFormUsedOnlyWithRecordLabelsPropertiesAndFields() = (812, sprintf "The syntax 'expr.id' may only be used with record labels, properties and fields" ) /// Event '%s' is static - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:646) + /// (Originally from src/fsharp/FSComp.txt:659) static member tcEventIsStatic(a0 : System.String) = (813, sprintf "Event '%s' is static" a0) /// Event '%s' is not static - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:647) + /// (Originally from src/fsharp/FSComp.txt:660) static member tcEventIsNotStatic(a0 : System.String) = (814, sprintf "Event '%s' is not static" a0) /// The named argument '%s' did not match any argument or mutable property - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:648) + /// (Originally from src/fsharp/FSComp.txt:661) static member tcNamedArgumentDidNotMatch(a0 : System.String) = (815, sprintf "The named argument '%s' did not match any argument or mutable property" a0) /// One or more of the overloads of this method has curried arguments. Consider redesigning these members to take arguments in tupled form. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:649) + /// (Originally from src/fsharp/FSComp.txt:662) static member tcOverloadsCannotHaveCurriedArguments() = (816, sprintf "One or more of the overloads of this method has curried arguments. Consider redesigning these members to take arguments in tupled form." ) /// The unnamed arguments do not form a prefix of the arguments of the method called - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:650) + /// (Originally from src/fsharp/FSComp.txt:663) static member tcUnnamedArgumentsDoNotFormPrefix() = (sprintf "The unnamed arguments do not form a prefix of the arguments of the method called" ) /// Static optimization conditionals are only for use within the F# library - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:651) + /// (Originally from src/fsharp/FSComp.txt:664) static member tcStaticOptimizationConditionalsOnlyForFSharpLibrary() = (817, sprintf "Static optimization conditionals are only for use within the F# library" ) /// The corresponding formal argument is not optional - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:652) + /// (Originally from src/fsharp/FSComp.txt:665) static member tcFormalArgumentIsNotOptional() = (818, sprintf "The corresponding formal argument is not optional" ) /// Invalid optional assignment to a property or field - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:653) + /// (Originally from src/fsharp/FSComp.txt:666) static member tcInvalidOptionalAssignmentToPropertyOrField() = (819, sprintf "Invalid optional assignment to a property or field" ) /// A delegate constructor must be passed a single function value - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:654) + /// (Originally from src/fsharp/FSComp.txt:667) static member tcDelegateConstructorMustBePassed() = (820, sprintf "A delegate constructor must be passed a single function value" ) /// A binding cannot be marked both 'use' and 'rec' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:655) + /// (Originally from src/fsharp/FSComp.txt:668) static member tcBindingCannotBeUseAndRec() = (821, sprintf "A binding cannot be marked both 'use' and 'rec'" ) /// The 'VolatileField' attribute may only be used on 'let' bindings in classes - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:656) + /// (Originally from src/fsharp/FSComp.txt:669) static member tcVolatileOnlyOnClassLetBindings() = (823, sprintf "The 'VolatileField' attribute may only be used on 'let' bindings in classes" ) /// Attributes are not permitted on 'let' bindings in expressions - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:657) + /// (Originally from src/fsharp/FSComp.txt:670) static member tcAttributesAreNotPermittedOnLetBindings() = (824, sprintf "Attributes are not permitted on 'let' bindings in expressions" ) /// The 'DefaultValue' attribute may only be used on 'val' declarations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:658) + /// (Originally from src/fsharp/FSComp.txt:671) static member tcDefaultValueAttributeRequiresVal() = (825, sprintf "The 'DefaultValue' attribute may only be used on 'val' declarations" ) /// The 'ConditionalAttribute' attribute may only be used on members - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:659) + /// (Originally from src/fsharp/FSComp.txt:672) static member tcConditionalAttributeRequiresMembers() = (826, sprintf "The 'ConditionalAttribute' attribute may only be used on members" ) /// This is not a valid name for an active pattern - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:660) + /// (Originally from src/fsharp/FSComp.txt:673) static member tcInvalidActivePatternName() = (827, sprintf "This is not a valid name for an active pattern" ) /// The 'EntryPointAttribute' attribute may only be used on function definitions in modules - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:661) + /// (Originally from src/fsharp/FSComp.txt:674) static member tcEntryPointAttributeRequiresFunctionInModule() = (828, sprintf "The 'EntryPointAttribute' attribute may only be used on function definitions in modules" ) /// Mutable values cannot be marked 'inline' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:662) + /// (Originally from src/fsharp/FSComp.txt:675) static member tcMutableValuesCannotBeInline() = (829, sprintf "Mutable values cannot be marked 'inline'" ) /// Mutable values cannot have generic parameters - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:663) + /// (Originally from src/fsharp/FSComp.txt:676) static member tcMutableValuesMayNotHaveGenericParameters() = (830, sprintf "Mutable values cannot have generic parameters" ) /// Mutable function values should be written 'let mutable f = (fun args -> ...)' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:664) + /// (Originally from src/fsharp/FSComp.txt:677) static member tcMutableValuesSyntax() = (831, sprintf "Mutable function values should be written 'let mutable f = (fun args -> ...)'" ) /// Only functions may be marked 'inline' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:665) + /// (Originally from src/fsharp/FSComp.txt:678) static member tcOnlyFunctionsCanBeInline() = (832, sprintf "Only functions may be marked 'inline'" ) /// A literal value cannot be given the [] or [] attributes - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:666) + /// (Originally from src/fsharp/FSComp.txt:679) static member tcIllegalAttributesForLiteral() = (833, sprintf "A literal value cannot be given the [] or [] attributes" ) /// A literal value cannot be marked 'mutable' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:667) + /// (Originally from src/fsharp/FSComp.txt:680) static member tcLiteralCannotBeMutable() = (834, sprintf "A literal value cannot be marked 'mutable'" ) /// A literal value cannot be marked 'inline' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:668) + /// (Originally from src/fsharp/FSComp.txt:681) static member tcLiteralCannotBeInline() = (835, sprintf "A literal value cannot be marked 'inline'" ) /// Literal values cannot have generic parameters - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:669) + /// (Originally from src/fsharp/FSComp.txt:682) static member tcLiteralCannotHaveGenericParameters() = (836, sprintf "Literal values cannot have generic parameters" ) /// This is not a valid constant expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:670) + /// (Originally from src/fsharp/FSComp.txt:683) static member tcInvalidConstantExpression() = (837, sprintf "This is not a valid constant expression" ) /// This type is not accessible from this code location - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:671) + /// (Originally from src/fsharp/FSComp.txt:684) static member tcTypeIsInaccessible() = (838, sprintf "This type is not accessible from this code location" ) /// Unexpected condition in imported assembly: failed to decode AttributeUsage attribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:672) + /// (Originally from src/fsharp/FSComp.txt:685) static member tcUnexpectedConditionInImportedAssembly() = (839, sprintf "Unexpected condition in imported assembly: failed to decode AttributeUsage attribute" ) /// Unrecognized attribute target. Valid attribute targets are 'assembly', 'module', 'type', 'method', 'property', 'return', 'param', 'field', 'event', 'constructor'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:673) + /// (Originally from src/fsharp/FSComp.txt:686) static member tcUnrecognizedAttributeTarget() = (840, sprintf "Unrecognized attribute target. Valid attribute targets are 'assembly', 'module', 'type', 'method', 'property', 'return', 'param', 'field', 'event', 'constructor'." ) /// This attribute is not valid for use on this language element. Assembly attributes should be attached to a 'do ()' declaration, if necessary within an F# module. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:674) + /// (Originally from src/fsharp/FSComp.txt:687) static member tcAttributeIsNotValidForLanguageElementUseDo() = (841, sprintf "This attribute is not valid for use on this language element. Assembly attributes should be attached to a 'do ()' declaration, if necessary within an F# module." ) /// This attribute is not valid for use on this language element - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:675) + /// (Originally from src/fsharp/FSComp.txt:688) static member tcAttributeIsNotValidForLanguageElement() = (842, sprintf "This attribute is not valid for use on this language element" ) /// Optional arguments cannot be used in custom attributes - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:676) + /// (Originally from src/fsharp/FSComp.txt:689) static member tcOptionalArgumentsCannotBeUsedInCustomAttribute() = (843, sprintf "Optional arguments cannot be used in custom attributes" ) /// This property cannot be set - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:677) + /// (Originally from src/fsharp/FSComp.txt:690) static member tcPropertyCannotBeSet0() = (844, sprintf "This property cannot be set" ) /// This property or field was not found on this custom attribute type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:678) + /// (Originally from src/fsharp/FSComp.txt:691) static member tcPropertyOrFieldNotFoundInAttribute() = (845, sprintf "This property or field was not found on this custom attribute type" ) /// A custom attribute must be a reference type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:679) + /// (Originally from src/fsharp/FSComp.txt:692) static member tcCustomAttributeMustBeReferenceType() = (846, sprintf "A custom attribute must be a reference type" ) /// The number of args for a custom attribute does not match the expected number of args for the attribute constructor - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:680) + /// (Originally from src/fsharp/FSComp.txt:693) static member tcCustomAttributeArgumentMismatch() = (847, sprintf "The number of args for a custom attribute does not match the expected number of args for the attribute constructor" ) /// A custom attribute must invoke an object constructor - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:681) + /// (Originally from src/fsharp/FSComp.txt:694) static member tcCustomAttributeMustInvokeConstructor() = (848, sprintf "A custom attribute must invoke an object constructor" ) /// Attribute expressions must be calls to object constructors - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:682) + /// (Originally from src/fsharp/FSComp.txt:695) static member tcAttributeExpressionsMustBeConstructorCalls() = (849, sprintf "Attribute expressions must be calls to object constructors" ) /// This attribute cannot be used in this version of F# - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:683) + /// (Originally from src/fsharp/FSComp.txt:696) static member tcUnsupportedAttribute() = (850, sprintf "This attribute cannot be used in this version of F#" ) /// Invalid inline specification - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:684) + /// (Originally from src/fsharp/FSComp.txt:697) static member tcInvalidInlineSpecification() = (851, sprintf "Invalid inline specification" ) /// 'use' bindings must be of the form 'use = ' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:685) + /// (Originally from src/fsharp/FSComp.txt:698) static member tcInvalidUseBinding() = (852, sprintf "'use' bindings must be of the form 'use = '" ) /// Abstract members are not permitted in an augmentation - they must be defined as part of the type itself - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:686) + /// (Originally from src/fsharp/FSComp.txt:699) static member tcAbstractMembersIllegalInAugmentation() = (853, sprintf "Abstract members are not permitted in an augmentation - they must be defined as part of the type itself" ) /// Method overrides and interface implementations are not permitted here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:687) + /// (Originally from src/fsharp/FSComp.txt:700) static member tcMethodOverridesIllegalHere() = (854, sprintf "Method overrides and interface implementations are not permitted here" ) /// No abstract or interface member was found that corresponds to this override - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:688) + /// (Originally from src/fsharp/FSComp.txt:701) static member tcNoMemberFoundForOverride() = (855, sprintf "No abstract or interface member was found that corresponds to this override" ) /// This override takes a different number of arguments to the corresponding abstract member. The following abstract members were found:%s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:689) + /// (Originally from src/fsharp/FSComp.txt:702) static member tcOverrideArityMismatch(a0 : System.String) = (856, sprintf "This override takes a different number of arguments to the corresponding abstract member. The following abstract members were found:%s" a0) /// This method already has a default implementation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:690) + /// (Originally from src/fsharp/FSComp.txt:703) static member tcDefaultImplementationAlreadyExists() = (857, sprintf "This method already has a default implementation" ) /// The method implemented by this default is ambiguous - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:691) + /// (Originally from src/fsharp/FSComp.txt:704) static member tcDefaultAmbiguous() = (858, sprintf "The method implemented by this default is ambiguous" ) /// No abstract property was found that corresponds to this override - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:692) + /// (Originally from src/fsharp/FSComp.txt:705) static member tcNoPropertyFoundForOverride() = (859, sprintf "No abstract property was found that corresponds to this override" ) /// This property overrides or implements an abstract property but the abstract property doesn't have a corresponding %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:693) + /// (Originally from src/fsharp/FSComp.txt:706) static member tcAbstractPropertyMissingGetOrSet(a0 : System.String) = (860, sprintf "This property overrides or implements an abstract property but the abstract property doesn't have a corresponding %s" a0) /// Invalid signature for set member - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:694) + /// (Originally from src/fsharp/FSComp.txt:707) static member tcInvalidSignatureForSet() = (861, sprintf "Invalid signature for set member" ) /// This new member hides the abstract member '%s'. Rename the member or use 'override' instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:695) + /// (Originally from src/fsharp/FSComp.txt:708) static member tcNewMemberHidesAbstractMember(a0 : System.String) = (864, sprintf "This new member hides the abstract member '%s'. Rename the member or use 'override' instead." a0) /// This new member hides the abstract member '%s' once tuples, functions, units of measure and/or provided types are erased. Rename the member or use 'override' instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:696) + /// (Originally from src/fsharp/FSComp.txt:709) static member tcNewMemberHidesAbstractMemberWithSuffix(a0 : System.String) = (864, sprintf "This new member hides the abstract member '%s' once tuples, functions, units of measure and/or provided types are erased. Rename the member or use 'override' instead." a0) /// Interfaces cannot contain definitions of static initializers - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:697) + /// (Originally from src/fsharp/FSComp.txt:710) static member tcStaticInitializersIllegalInInterface() = (865, sprintf "Interfaces cannot contain definitions of static initializers" ) /// Interfaces cannot contain definitions of object constructors - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:698) + /// (Originally from src/fsharp/FSComp.txt:711) static member tcObjectConstructorsIllegalInInterface() = (866, sprintf "Interfaces cannot contain definitions of object constructors" ) /// Interfaces cannot contain definitions of member overrides - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:699) + /// (Originally from src/fsharp/FSComp.txt:712) static member tcMemberOverridesIllegalInInterface() = (867, sprintf "Interfaces cannot contain definitions of member overrides" ) /// Interfaces cannot contain definitions of concrete members. You may need to define a constructor on your type to indicate that the type is a class. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:700) + /// (Originally from src/fsharp/FSComp.txt:713) static member tcConcreteMembersIllegalInInterface() = (868, sprintf "Interfaces cannot contain definitions of concrete members. You may need to define a constructor on your type to indicate that the type is a class." ) /// Constructors cannot be specified in exception augmentations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:701) + /// (Originally from src/fsharp/FSComp.txt:714) static member tcConstructorsDisallowedInExceptionAugmentation() = (869, sprintf "Constructors cannot be specified in exception augmentations" ) /// Structs cannot have an object constructor with no arguments. This is a restriction imposed on all CLI languages as structs automatically support a default constructor. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:702) + /// (Originally from src/fsharp/FSComp.txt:715) static member tcStructsCannotHaveConstructorWithNoArguments() = (870, sprintf "Structs cannot have an object constructor with no arguments. This is a restriction imposed on all CLI languages as structs automatically support a default constructor." ) /// Constructors cannot be defined for this type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:703) + /// (Originally from src/fsharp/FSComp.txt:716) static member tcConstructorsIllegalForThisType() = (871, sprintf "Constructors cannot be defined for this type" ) /// Recursive bindings that include member specifications can only occur as a direct augmentation of a type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:704) + /// (Originally from src/fsharp/FSComp.txt:717) static member tcRecursiveBindingsWithMembersMustBeDirectAugmentation() = (872, sprintf "Recursive bindings that include member specifications can only occur as a direct augmentation of a type" ) /// Only simple variable patterns can be bound in 'let rec' constructs - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:705) + /// (Originally from src/fsharp/FSComp.txt:718) static member tcOnlySimplePatternsInLetRec() = (873, sprintf "Only simple variable patterns can be bound in 'let rec' constructs" ) /// Only record fields and simple, non-recursive 'let' bindings may be marked mutable - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:706) + /// (Originally from src/fsharp/FSComp.txt:719) static member tcOnlyRecordFieldsAndSimpleLetCanBeMutable() = (874, sprintf "Only record fields and simple, non-recursive 'let' bindings may be marked mutable" ) /// This member is not sufficiently generic - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:707) + /// (Originally from src/fsharp/FSComp.txt:720) static member tcMemberIsNotSufficientlyGeneric() = (875, sprintf "This member is not sufficiently generic" ) /// A declaration may only be the [] attribute if a constant value is also given, e.g. 'val x : int = 1' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:708) + /// (Originally from src/fsharp/FSComp.txt:721) static member tcLiteralAttributeRequiresConstantValue() = (876, sprintf "A declaration may only be the [] attribute if a constant value is also given, e.g. 'val x : int = 1'" ) /// A declaration may only be given a value in a signature if the declaration has the [] attribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:709) + /// (Originally from src/fsharp/FSComp.txt:722) static member tcValueInSignatureRequiresLiteralAttribute() = (877, sprintf "A declaration may only be given a value in a signature if the declaration has the [] attribute" ) /// Thread-static and context-static variables must be static and given the [] attribute to indicate that the value is initialized to the default value on each new thread - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:710) + /// (Originally from src/fsharp/FSComp.txt:723) static member tcThreadStaticAndContextStaticMustBeStatic() = (878, sprintf "Thread-static and context-static variables must be static and given the [] attribute to indicate that the value is initialized to the default value on each new thread" ) /// Volatile fields must be marked 'mutable' and cannot be thread-static - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:711) + /// (Originally from src/fsharp/FSComp.txt:724) static member tcVolatileFieldsMustBeMutable() = (879, sprintf "Volatile fields must be marked 'mutable' and cannot be thread-static" ) /// Uninitialized 'val' fields must be mutable and marked with the '[]' attribute. Consider using a 'let' binding instead of a 'val' field. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:712) + /// (Originally from src/fsharp/FSComp.txt:725) static member tcUninitializedValFieldsMustBeMutable() = (880, sprintf "Uninitialized 'val' fields must be mutable and marked with the '[]' attribute. Consider using a 'let' binding instead of a 'val' field." ) /// Static 'val' fields in types must be mutable, private and marked with the '[]' attribute. They are initialized to the 'null' or 'zero' value for their type. Consider also using a 'static let mutable' binding in a class type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:713) + /// (Originally from src/fsharp/FSComp.txt:726) static member tcStaticValFieldsMustBeMutableAndPrivate() = (881, sprintf "Static 'val' fields in types must be mutable, private and marked with the '[]' attribute. They are initialized to the 'null' or 'zero' value for their type. Consider also using a 'static let mutable' binding in a class type." ) /// This field requires a name - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:714) + /// (Originally from src/fsharp/FSComp.txt:727) static member tcFieldRequiresName() = (882, sprintf "This field requires a name" ) /// Invalid namespace, module, type or union case name - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:715) + /// (Originally from src/fsharp/FSComp.txt:728) static member tcInvalidNamespaceModuleTypeUnionName() = (883, sprintf "Invalid namespace, module, type or union case name" ) /// Explicit type declarations for constructors must be of the form 'ty1 * ... * tyN -> resTy'. Parentheses may be required around 'resTy' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:716) + /// (Originally from src/fsharp/FSComp.txt:729) static member tcIllegalFormForExplicitTypeDeclaration() = (884, sprintf "Explicit type declarations for constructors must be of the form 'ty1 * ... * tyN -> resTy'. Parentheses may be required around 'resTy'" ) /// Return types of union cases must be identical to the type being defined, up to abbreviations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:717) + /// (Originally from src/fsharp/FSComp.txt:730) static member tcReturnTypesForUnionMustBeSameAsType() = (885, sprintf "Return types of union cases must be identical to the type being defined, up to abbreviations" ) /// This is not a valid value for an enumeration literal - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:718) + /// (Originally from src/fsharp/FSComp.txt:731) static member tcInvalidEnumerationLiteral() = (886, sprintf "This is not a valid value for an enumeration literal" ) /// The type '%s' is not an interface type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:719) + /// (Originally from src/fsharp/FSComp.txt:732) static member tcTypeIsNotInterfaceType1(a0 : System.String) = (887, sprintf "The type '%s' is not an interface type" a0) /// Duplicate specification of an interface - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:720) + /// (Originally from src/fsharp/FSComp.txt:733) static member tcDuplicateSpecOfInterface() = (888, sprintf "Duplicate specification of an interface" ) /// A field/val declaration is not permitted here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:721) + /// (Originally from src/fsharp/FSComp.txt:734) static member tcFieldValIllegalHere() = (889, sprintf "A field/val declaration is not permitted here" ) /// A inheritance declaration is not permitted here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:722) + /// (Originally from src/fsharp/FSComp.txt:735) static member tcInheritIllegalHere() = (890, sprintf "A inheritance declaration is not permitted here" ) /// This declaration opens the module '%s', which is marked as 'RequireQualifiedAccess'. Adjust your code to use qualified references to the elements of the module instead, e.g. 'List.map' instead of 'map'. This change will ensure that your code is robust as new constructs are added to libraries. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:723) + /// (Originally from src/fsharp/FSComp.txt:736) static member tcModuleRequiresQualifiedAccess(a0 : System.String) = (892, sprintf "This declaration opens the module '%s', which is marked as 'RequireQualifiedAccess'. Adjust your code to use qualified references to the elements of the module instead, e.g. 'List.map' instead of 'map'. This change will ensure that your code is robust as new constructs are added to libraries." a0) /// This declaration opens the namespace or module '%s' through a partially qualified path. Adjust this code to use the full path of the namespace. This change will make your code more robust as new constructs are added to the F# and CLI libraries. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:724) + /// (Originally from src/fsharp/FSComp.txt:737) static member tcOpenUsedWithPartiallyQualifiedPath(a0 : System.String) = (893, sprintf "This declaration opens the namespace or module '%s' through a partially qualified path. Adjust this code to use the full path of the namespace. This change will make your code more robust as new constructs are added to the F# and CLI libraries." a0) /// Local class bindings cannot be marked inline. Consider lifting the definition out of the class or else do not mark it as inline. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:725) + /// (Originally from src/fsharp/FSComp.txt:738) static member tcLocalClassBindingsCannotBeInline() = (894, sprintf "Local class bindings cannot be marked inline. Consider lifting the definition out of the class or else do not mark it as inline." ) /// Type abbreviations cannot have members - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:726) + /// (Originally from src/fsharp/FSComp.txt:739) static member tcTypeAbbreviationsMayNotHaveMembers() = (895, sprintf "Type abbreviations cannot have members" ) /// As of F# 4.1, the accessibility of type abbreviations is checked at compile-time. Consider changing the accessibility of the type abbreviation. Ignoring this warning might lead to runtime errors. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:727) + /// (Originally from src/fsharp/FSComp.txt:740) static member tcTypeAbbreviationsCheckedAtCompileTime() = (sprintf "As of F# 4.1, the accessibility of type abbreviations is checked at compile-time. Consider changing the accessibility of the type abbreviation. Ignoring this warning might lead to runtime errors." ) /// Enumerations cannot have members - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:728) + /// (Originally from src/fsharp/FSComp.txt:741) static member tcEnumerationsMayNotHaveMembers() = (896, sprintf "Enumerations cannot have members" ) /// Measure declarations may have only static members - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:729) + /// (Originally from src/fsharp/FSComp.txt:742) static member tcMeasureDeclarationsRequireStaticMembers() = (897, sprintf "Measure declarations may have only static members" ) /// Structs cannot contain 'do' bindings because the default constructor for structs would not execute these bindings - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:730) + /// (Originally from src/fsharp/FSComp.txt:743) static member tcStructsMayNotContainDoBindings() = (sprintf "Structs cannot contain 'do' bindings because the default constructor for structs would not execute these bindings" ) /// Structs cannot contain value definitions because the default constructor for structs will not execute these bindings. Consider adding additional arguments to the primary constructor for the type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:731) + /// (Originally from src/fsharp/FSComp.txt:744) static member tcStructsMayNotContainLetBindings() = (901, sprintf "Structs cannot contain value definitions because the default constructor for structs will not execute these bindings. Consider adding additional arguments to the primary constructor for the type." ) /// Static value definitions may only be used in types with a primary constructor. Consider adding arguments to the type definition, e.g. 'type X(args) = ...'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:732) + /// (Originally from src/fsharp/FSComp.txt:745) static member tcStaticLetBindingsRequireClassesWithImplicitConstructors() = (902, sprintf "Static value definitions may only be used in types with a primary constructor. Consider adding arguments to the type definition, e.g. 'type X(args) = ...'." ) /// Measure declarations may have only static members: constructors are not available - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:733) + /// (Originally from src/fsharp/FSComp.txt:746) static member tcMeasureDeclarationsRequireStaticMembersNotConstructors() = (904, sprintf "Measure declarations may have only static members: constructors are not available" ) /// A member and a local class binding both have the name '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:734) + /// (Originally from src/fsharp/FSComp.txt:747) static member tcMemberAndLocalClassBindingHaveSameName(a0 : System.String) = (905, sprintf "A member and a local class binding both have the name '%s'" a0) /// Type abbreviations cannot have interface declarations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:735) + /// (Originally from src/fsharp/FSComp.txt:748) static member tcTypeAbbreviationsCannotHaveInterfaceDeclaration() = (906, sprintf "Type abbreviations cannot have interface declarations" ) /// Enumerations cannot have interface declarations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:736) + /// (Originally from src/fsharp/FSComp.txt:749) static member tcEnumerationsCannotHaveInterfaceDeclaration() = (907, sprintf "Enumerations cannot have interface declarations" ) /// This type is not an interface type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:737) + /// (Originally from src/fsharp/FSComp.txt:750) static member tcTypeIsNotInterfaceType0() = (908, sprintf "This type is not an interface type" ) /// All implemented interfaces should be declared on the initial declaration of the type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:738) + /// (Originally from src/fsharp/FSComp.txt:751) static member tcAllImplementedInterfacesShouldBeDeclared() = (909, sprintf "All implemented interfaces should be declared on the initial declaration of the type" ) /// A default implementation of this interface has already been added because the explicit implementation of the interface was not specified at the definition of the type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:739) + /// (Originally from src/fsharp/FSComp.txt:752) static member tcDefaultImplementationForInterfaceHasAlreadyBeenAdded() = (910, sprintf "A default implementation of this interface has already been added because the explicit implementation of the interface was not specified at the definition of the type" ) /// This member is not permitted in an interface implementation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:740) + /// (Originally from src/fsharp/FSComp.txt:753) static member tcMemberNotPermittedInInterfaceImplementation() = (911, sprintf "This member is not permitted in an interface implementation" ) /// This declaration element is not permitted in an augmentation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:741) + /// (Originally from src/fsharp/FSComp.txt:754) static member tcDeclarationElementNotPermittedInAugmentation() = (912, sprintf "This declaration element is not permitted in an augmentation" ) /// Types cannot contain nested type definitions - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:742) + /// (Originally from src/fsharp/FSComp.txt:755) static member tcTypesCannotContainNestedTypes() = (913, sprintf "Types cannot contain nested type definitions" ) /// type, exception or module - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:743) + /// (Originally from src/fsharp/FSComp.txt:756) static member tcTypeExceptionOrModule() = (sprintf "type, exception or module" ) /// type or module - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:744) + /// (Originally from src/fsharp/FSComp.txt:757) static member tcTypeOrModule() = (sprintf "type or module" ) /// The struct, record or union type '%s' implements the interface 'System.IStructuralEquatable' explicitly. Apply the 'CustomEquality' attribute to the type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:745) + /// (Originally from src/fsharp/FSComp.txt:758) static member tcImplementsIStructuralEquatableExplicitly(a0 : System.String) = (914, sprintf "The struct, record or union type '%s' implements the interface 'System.IStructuralEquatable' explicitly. Apply the 'CustomEquality' attribute to the type." a0) /// The struct, record or union type '%s' implements the interface 'System.IEquatable<_>' explicitly. Apply the 'CustomEquality' attribute to the type and provide a consistent implementation of the non-generic override 'System.Object.Equals(obj)'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:746) + /// (Originally from src/fsharp/FSComp.txt:759) static member tcImplementsIEquatableExplicitly(a0 : System.String) = (915, sprintf "The struct, record or union type '%s' implements the interface 'System.IEquatable<_>' explicitly. Apply the 'CustomEquality' attribute to the type and provide a consistent implementation of the non-generic override 'System.Object.Equals(obj)'." a0) /// Explicit type specifications cannot be used for exception constructors - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:747) + /// (Originally from src/fsharp/FSComp.txt:760) static member tcExplicitTypeSpecificationCannotBeUsedForExceptionConstructors() = (916, sprintf "Explicit type specifications cannot be used for exception constructors" ) /// Exception abbreviations should not have argument lists - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:748) + /// (Originally from src/fsharp/FSComp.txt:761) static member tcExceptionAbbreviationsShouldNotHaveArgumentList() = (917, sprintf "Exception abbreviations should not have argument lists" ) /// Abbreviations for Common IL exceptions cannot take arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:749) + /// (Originally from src/fsharp/FSComp.txt:762) static member tcAbbreviationsFordotNetExceptionsCannotTakeArguments() = (918, sprintf "Abbreviations for Common IL exceptions cannot take arguments" ) /// Exception abbreviations must refer to existing exceptions or F# types deriving from System.Exception - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:750) + /// (Originally from src/fsharp/FSComp.txt:763) static member tcExceptionAbbreviationsMustReferToValidExceptions() = (919, sprintf "Exception abbreviations must refer to existing exceptions or F# types deriving from System.Exception" ) /// Abbreviations for Common IL exception types must have a matching object constructor - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:751) + /// (Originally from src/fsharp/FSComp.txt:764) static member tcAbbreviationsFordotNetExceptionsMustHaveMatchingObjectConstructor() = (920, sprintf "Abbreviations for Common IL exception types must have a matching object constructor" ) /// Not an exception - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:752) + /// (Originally from src/fsharp/FSComp.txt:765) static member tcNotAnException() = (921, sprintf "Not an exception" ) /// Invalid module name - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:754) + /// (Originally from src/fsharp/FSComp.txt:767) static member tcInvalidModuleName() = (924, sprintf "Invalid module name" ) /// Invalid type extension - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:755) + /// (Originally from src/fsharp/FSComp.txt:768) static member tcInvalidTypeExtension() = (925, sprintf "Invalid type extension" ) /// The attributes of this type specify multiple kinds for the type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:756) + /// (Originally from src/fsharp/FSComp.txt:769) static member tcAttributesOfTypeSpecifyMultipleKindsForType() = (926, sprintf "The attributes of this type specify multiple kinds for the type" ) /// The kind of the type specified by its attributes does not match the kind implied by its definition - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:757) + /// (Originally from src/fsharp/FSComp.txt:770) static member tcKindOfTypeSpecifiedDoesNotMatchDefinition() = (927, sprintf "The kind of the type specified by its attributes does not match the kind implied by its definition" ) /// Measure definitions cannot have type parameters - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:758) + /// (Originally from src/fsharp/FSComp.txt:771) static member tcMeasureDefinitionsCannotHaveTypeParameters() = (928, sprintf "Measure definitions cannot have type parameters" ) /// This type requires a definition - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:759) + /// (Originally from src/fsharp/FSComp.txt:772) static member tcTypeRequiresDefinition() = (929, sprintf "This type requires a definition" ) /// This type abbreviation has one or more declared type parameters that do not appear in the type being abbreviated. Type abbreviations must use all declared type parameters in the type being abbreviated. Consider removing one or more type parameters, or use a concrete type definition that wraps an underlying type, such as 'type C<'a> = C of ...'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:760) + /// (Originally from src/fsharp/FSComp.txt:773) static member tcTypeAbbreviationHasTypeParametersMissingOnType() = (sprintf "This type abbreviation has one or more declared type parameters that do not appear in the type being abbreviated. Type abbreviations must use all declared type parameters in the type being abbreviated. Consider removing one or more type parameters, or use a concrete type definition that wraps an underlying type, such as 'type C<'a> = C of ...'." ) /// Structs, interfaces, enums and delegates cannot inherit from other types - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:761) + /// (Originally from src/fsharp/FSComp.txt:774) static member tcStructsInterfacesEnumsDelegatesMayNotInheritFromOtherTypes() = (931, sprintf "Structs, interfaces, enums and delegates cannot inherit from other types" ) /// Types cannot inherit from multiple concrete types - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:762) + /// (Originally from src/fsharp/FSComp.txt:775) static member tcTypesCannotInheritFromMultipleConcreteTypes() = (932, sprintf "Types cannot inherit from multiple concrete types" ) /// Records, union, abbreviations and struct types cannot have the 'AllowNullLiteral' attribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:763) + /// (Originally from src/fsharp/FSComp.txt:776) static member tcRecordsUnionsAbbreviationsStructsMayNotHaveAllowNullLiteralAttribute() = (934, sprintf "Records, union, abbreviations and struct types cannot have the 'AllowNullLiteral' attribute" ) /// Types with the 'AllowNullLiteral' attribute may only inherit from or implement types which also allow the use of the null literal - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:764) + /// (Originally from src/fsharp/FSComp.txt:777) static member tcAllowNullTypesMayOnlyInheritFromAllowNullTypes() = (935, sprintf "Types with the 'AllowNullLiteral' attribute may only inherit from or implement types which also allow the use of the null literal" ) /// Generic types cannot be given the 'StructLayout' attribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:765) + /// (Originally from src/fsharp/FSComp.txt:778) static member tcGenericTypesCannotHaveStructLayout() = (936, sprintf "Generic types cannot be given the 'StructLayout' attribute" ) /// Only structs and classes without primary constructors may be given the 'StructLayout' attribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:766) + /// (Originally from src/fsharp/FSComp.txt:779) static member tcOnlyStructsCanHaveStructLayout() = (937, sprintf "Only structs and classes without primary constructors may be given the 'StructLayout' attribute" ) /// The representation of this type is hidden by the signature. It must be given an attribute such as [], [] or [] to indicate the characteristics of the type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:767) + /// (Originally from src/fsharp/FSComp.txt:780) static member tcRepresentationOfTypeHiddenBySignature() = (938, sprintf "The representation of this type is hidden by the signature. It must be given an attribute such as [], [] or [] to indicate the characteristics of the type." ) /// Only classes may be given the 'AbstractClass' attribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:768) + /// (Originally from src/fsharp/FSComp.txt:781) static member tcOnlyClassesCanHaveAbstract() = (939, sprintf "Only classes may be given the 'AbstractClass' attribute" ) /// Only types representing units-of-measure may be given the 'Measure' attribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:769) + /// (Originally from src/fsharp/FSComp.txt:782) static member tcOnlyTypesRepresentingUnitsOfMeasureCanHaveMeasure() = (940, sprintf "Only types representing units-of-measure may be given the 'Measure' attribute" ) /// Accessibility modifiers are not permitted on overrides or interface implementations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:770) + /// (Originally from src/fsharp/FSComp.txt:783) static member tcOverridesCannotHaveVisibilityDeclarations() = (941, sprintf "Accessibility modifiers are not permitted on overrides or interface implementations" ) /// Discriminated union types are always sealed - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:771) + /// (Originally from src/fsharp/FSComp.txt:784) static member tcTypesAreAlwaysSealedDU() = (942, sprintf "Discriminated union types are always sealed" ) /// Record types are always sealed - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:772) + /// (Originally from src/fsharp/FSComp.txt:785) static member tcTypesAreAlwaysSealedRecord() = (942, sprintf "Record types are always sealed" ) /// Assembly code types are always sealed - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:773) + /// (Originally from src/fsharp/FSComp.txt:786) static member tcTypesAreAlwaysSealedAssemblyCode() = (942, sprintf "Assembly code types are always sealed" ) /// Struct types are always sealed - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:774) + /// (Originally from src/fsharp/FSComp.txt:787) static member tcTypesAreAlwaysSealedStruct() = (942, sprintf "Struct types are always sealed" ) /// Delegate types are always sealed - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:775) + /// (Originally from src/fsharp/FSComp.txt:788) static member tcTypesAreAlwaysSealedDelegate() = (942, sprintf "Delegate types are always sealed" ) /// Enum types are always sealed - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:776) + /// (Originally from src/fsharp/FSComp.txt:789) static member tcTypesAreAlwaysSealedEnum() = (942, sprintf "Enum types are always sealed" ) /// Interface types and delegate types cannot contain fields - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:777) + /// (Originally from src/fsharp/FSComp.txt:790) static member tcInterfaceTypesAndDelegatesCannotContainFields() = (943, sprintf "Interface types and delegate types cannot contain fields" ) /// Abbreviated types cannot be given the 'Sealed' attribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:778) + /// (Originally from src/fsharp/FSComp.txt:791) static member tcAbbreviatedTypesCannotBeSealed() = (944, sprintf "Abbreviated types cannot be given the 'Sealed' attribute" ) /// Cannot inherit a sealed type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:779) + /// (Originally from src/fsharp/FSComp.txt:792) static member tcCannotInheritFromSealedType() = (945, sprintf "Cannot inherit a sealed type" ) /// Cannot inherit from interface type. Use interface ... with instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:780) + /// (Originally from src/fsharp/FSComp.txt:793) static member tcCannotInheritFromInterfaceType() = (946, sprintf "Cannot inherit from interface type. Use interface ... with instead." ) /// Struct types cannot contain abstract members - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:781) + /// (Originally from src/fsharp/FSComp.txt:794) static member tcStructTypesCannotContainAbstractMembers() = (947, sprintf "Struct types cannot contain abstract members" ) /// Interface types cannot be sealed - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:782) + /// (Originally from src/fsharp/FSComp.txt:795) static member tcInterfaceTypesCannotBeSealed() = (948, sprintf "Interface types cannot be sealed" ) /// Delegate specifications must be of the form 'typ -> typ' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:783) + /// (Originally from src/fsharp/FSComp.txt:796) static member tcInvalidDelegateSpecification() = (949, sprintf "Delegate specifications must be of the form 'typ -> typ'" ) /// Delegate specifications must not be curried types. Use 'typ * ... * typ -> typ' for multi-argument delegates, and 'typ -> (typ -> typ)' for delegates returning function values. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:784) + /// (Originally from src/fsharp/FSComp.txt:797) static member tcDelegatesCannotBeCurried() = (950, sprintf "Delegate specifications must not be curried types. Use 'typ * ... * typ -> typ' for multi-argument delegates, and 'typ -> (typ -> typ)' for delegates returning function values." ) /// Literal enumerations must have type int, uint, int16, uint16, int64, uint64, byte, sbyte or char - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:785) + /// (Originally from src/fsharp/FSComp.txt:798) static member tcInvalidTypeForLiteralEnumeration() = (951, sprintf "Literal enumerations must have type int, uint, int16, uint16, int64, uint64, byte, sbyte or char" ) /// This type definition involves an immediate cyclic reference through an abbreviation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:787) + /// (Originally from src/fsharp/FSComp.txt:800) static member tcTypeDefinitionIsCyclic() = (953, sprintf "This type definition involves an immediate cyclic reference through an abbreviation" ) /// This type definition involves an immediate cyclic reference through a struct field or inheritance relation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:788) + /// (Originally from src/fsharp/FSComp.txt:801) static member tcTypeDefinitionIsCyclicThroughInheritance() = (954, sprintf "This type definition involves an immediate cyclic reference through a struct field or inheritance relation" ) /// The syntax 'type X with ...' is reserved for augmentations. Types whose representations are hidden but which have members are now declared in signatures using 'type X = ...'. You may also need to add the '[] attribute to the type definition in the signature - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:789) + /// (Originally from src/fsharp/FSComp.txt:802) static member tcReservedSyntaxForAugmentation() = (sprintf "The syntax 'type X with ...' is reserved for augmentations. Types whose representations are hidden but which have members are now declared in signatures using 'type X = ...'. You may also need to add the '[] attribute to the type definition in the signature" ) /// Members that extend interface, delegate or enum types must be placed in a module separate to the definition of the type. This module must either have the AutoOpen attribute or be opened explicitly by client code to bring the extension members into scope. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:790) + /// (Originally from src/fsharp/FSComp.txt:803) static member tcMembersThatExtendInterfaceMustBePlacedInSeparateModule() = (956, sprintf "Members that extend interface, delegate or enum types must be placed in a module separate to the definition of the type. This module must either have the AutoOpen attribute or be opened explicitly by client code to bring the extension members into scope." ) /// One or more of the declared type parameters for this type extension have a missing or wrong type constraint not matching the original type constraints on '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:791) + /// (Originally from src/fsharp/FSComp.txt:804) static member tcDeclaredTypeParametersForExtensionDoNotMatchOriginal(a0 : System.String) = (957, sprintf "One or more of the declared type parameters for this type extension have a missing or wrong type constraint not matching the original type constraints on '%s'" a0) /// Type definitions may only have one 'inherit' specification and it must be the first declaration - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:792) + /// (Originally from src/fsharp/FSComp.txt:805) static member tcTypeDefinitionsWithImplicitConstructionMustHaveOneInherit() = (959, sprintf "Type definitions may only have one 'inherit' specification and it must be the first declaration" ) /// 'let' and 'do' bindings must come before member and interface definitions in type definitions - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:793) + /// (Originally from src/fsharp/FSComp.txt:806) static member tcTypeDefinitionsWithImplicitConstructionMustHaveLocalBindingsBeforeMembers() = (960, sprintf "'let' and 'do' bindings must come before member and interface definitions in type definitions" ) /// This 'inherit' declaration specifies the inherited type but no arguments. Consider supplying arguments, e.g. 'inherit BaseType(args)'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:794) + /// (Originally from src/fsharp/FSComp.txt:807) static member tcInheritDeclarationMissingArguments() = (961, sprintf "This 'inherit' declaration specifies the inherited type but no arguments. Consider supplying arguments, e.g. 'inherit BaseType(args)'." ) /// This 'inherit' declaration has arguments, but is not in a type with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:795) + /// (Originally from src/fsharp/FSComp.txt:808) static member tcInheritConstructionCallNotPartOfImplicitSequence() = (962, sprintf "This 'inherit' declaration has arguments, but is not in a type with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'." ) /// This definition may only be used in a type with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:796) + /// (Originally from src/fsharp/FSComp.txt:809) static member tcLetAndDoRequiresImplicitConstructionSequence() = (963, sprintf "This definition may only be used in a type with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'." ) /// Type abbreviations cannot have augmentations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:797) + /// (Originally from src/fsharp/FSComp.txt:810) static member tcTypeAbbreviationsCannotHaveAugmentations() = (964, sprintf "Type abbreviations cannot have augmentations" ) /// The path '%s' is a namespace. A module abbreviation may not abbreviate a namespace. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:798) + /// (Originally from src/fsharp/FSComp.txt:811) static member tcModuleAbbreviationForNamespace(a0 : System.String) = (965, sprintf "The path '%s' is a namespace. A module abbreviation may not abbreviate a namespace." a0) /// The type '%s' is used in an invalid way. A value prior to '%s' has an inferred type involving '%s', which is an invalid forward reference. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:799) + /// (Originally from src/fsharp/FSComp.txt:812) static member tcTypeUsedInInvalidWay(a0 : System.String, a1 : System.String, a2 : System.String) = (966, sprintf "The type '%s' is used in an invalid way. A value prior to '%s' has an inferred type involving '%s', which is an invalid forward reference." a0 a1 a2) /// The member '%s' is used in an invalid way. A use of '%s' has been inferred prior to the definition of '%s', which is an invalid forward reference. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:800) + /// (Originally from src/fsharp/FSComp.txt:813) static member tcMemberUsedInInvalidWay(a0 : System.String, a1 : System.String, a2 : System.String) = (967, sprintf "The member '%s' is used in an invalid way. A use of '%s' has been inferred prior to the definition of '%s', which is an invalid forward reference." a0 a1 a2) /// The attribute 'AutoOpen(\"%s\")' in the assembly '%s' did not refer to a valid module or namespace in that assembly and has been ignored - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:803) + /// (Originally from src/fsharp/FSComp.txt:816) static member tcAttributeAutoOpenWasIgnored(a0 : System.String, a1 : System.String) = (970, sprintf "The attribute 'AutoOpen(\"%s\")' in the assembly '%s' did not refer to a valid module or namespace in that assembly and has been ignored" a0 a1) /// Undefined value '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:804) + /// (Originally from src/fsharp/FSComp.txt:817) static member ilUndefinedValue(a0 : System.String) = (971, sprintf "Undefined value '%s'" a0) /// Label %s not found - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:805) + /// (Originally from src/fsharp/FSComp.txt:818) static member ilLabelNotFound(a0 : System.String) = (972, sprintf "Label %s not found" a0) /// Incorrect number of type arguments to local call - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:806) + /// (Originally from src/fsharp/FSComp.txt:819) static member ilIncorrectNumberOfTypeArguments() = (973, sprintf "Incorrect number of type arguments to local call" ) /// Dynamic invocation of %s is not supported - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:807) + /// (Originally from src/fsharp/FSComp.txt:820) static member ilDynamicInvocationNotSupported(a0 : System.String) = (sprintf "Dynamic invocation of %s is not supported" a0) /// Taking the address of a literal field is invalid - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:808) + /// (Originally from src/fsharp/FSComp.txt:821) static member ilAddressOfLiteralFieldIsInvalid() = (975, sprintf "Taking the address of a literal field is invalid" ) /// This operation involves taking the address of a value '%s' represented using a local variable or other special representation. This is invalid. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:809) + /// (Originally from src/fsharp/FSComp.txt:822) static member ilAddressOfValueHereIsInvalid(a0 : System.String) = (976, sprintf "This operation involves taking the address of a value '%s' represented using a local variable or other special representation. This is invalid." a0) /// Custom marshallers cannot be specified in F# code. Consider using a C# helper function. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:810) + /// (Originally from src/fsharp/FSComp.txt:823) static member ilCustomMarshallersCannotBeUsedInFSharp() = (980, sprintf "Custom marshallers cannot be specified in F# code. Consider using a C# helper function." ) /// The MarshalAs attribute could not be decoded - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:811) + /// (Originally from src/fsharp/FSComp.txt:824) static member ilMarshalAsAttributeCannotBeDecoded() = (981, sprintf "The MarshalAs attribute could not be decoded" ) /// The signature for this external function contains type parameters. Constrain the argument and return types to indicate the types of the corresponding C function. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:812) + /// (Originally from src/fsharp/FSComp.txt:825) static member ilSignatureForExternalFunctionContainsTypeParameters() = (982, sprintf "The signature for this external function contains type parameters. Constrain the argument and return types to indicate the types of the corresponding C function." ) /// The DllImport attribute could not be decoded - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:813) + /// (Originally from src/fsharp/FSComp.txt:826) static member ilDllImportAttributeCouldNotBeDecoded() = (983, sprintf "The DllImport attribute could not be decoded" ) /// Literal fields cannot be set - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:814) + /// (Originally from src/fsharp/FSComp.txt:827) static member ilLiteralFieldsCannotBeSet() = (984, sprintf "Literal fields cannot be set" ) /// GenSetStorage: %s was represented as a static method but was not an appropriate lambda expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:815) + /// (Originally from src/fsharp/FSComp.txt:828) static member ilStaticMethodIsNotLambda(a0 : System.String) = (985, sprintf "GenSetStorage: %s was represented as a static method but was not an appropriate lambda expression" a0) /// Mutable variables cannot escape their method - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:816) + /// (Originally from src/fsharp/FSComp.txt:829) static member ilMutableVariablesCannotEscapeMethod() = (986, sprintf "Mutable variables cannot escape their method" ) /// Compiler error: unexpected unrealized value - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:817) + /// (Originally from src/fsharp/FSComp.txt:830) static member ilUnexpectedUnrealizedValue() = (987, sprintf "Compiler error: unexpected unrealized value" ) /// Main module of program is empty: nothing will happen when it is run - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:818) + /// (Originally from src/fsharp/FSComp.txt:831) static member ilMainModuleEmpty() = (988, sprintf "Main module of program is empty: nothing will happen when it is run" ) /// This type cannot be used for a literal field - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:819) + /// (Originally from src/fsharp/FSComp.txt:832) static member ilTypeCannotBeUsedForLiteralField() = (989, sprintf "This type cannot be used for a literal field" ) /// Unexpected GetSet annotation on a property - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:820) + /// (Originally from src/fsharp/FSComp.txt:833) static member ilUnexpectedGetSetAnnotation() = (990, sprintf "Unexpected GetSet annotation on a property" ) /// The FieldOffset attribute could not be decoded - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:821) + /// (Originally from src/fsharp/FSComp.txt:834) static member ilFieldOffsetAttributeCouldNotBeDecoded() = (991, sprintf "The FieldOffset attribute could not be decoded" ) /// The StructLayout attribute could not be decoded - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:822) + /// (Originally from src/fsharp/FSComp.txt:835) static member ilStructLayoutAttributeCouldNotBeDecoded() = (992, sprintf "The StructLayout attribute could not be decoded" ) /// The DefaultAugmentation attribute could not be decoded - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:823) + /// (Originally from src/fsharp/FSComp.txt:836) static member ilDefaultAugmentationAttributeCouldNotBeDecoded() = (993, sprintf "The DefaultAugmentation attribute could not be decoded" ) /// Reflected definitions cannot contain uses of the prefix splice operator '%%' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:824) + /// (Originally from src/fsharp/FSComp.txt:837) static member ilReflectedDefinitionsCannotUseSliceOperator() = (994, sprintf "Reflected definitions cannot contain uses of the prefix splice operator '%%'" ) /// Problem with codepage '%d': %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:825) + /// (Originally from src/fsharp/FSComp.txt:838) static member optsProblemWithCodepage(a0 : System.Int32, a1 : System.String) = (1000, sprintf "Problem with codepage '%d': %s" a0 a1) /// Copyright (c) Microsoft Corporation. All Rights Reserved. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:826) + /// (Originally from src/fsharp/FSComp.txt:839) static member optsCopyright() = (sprintf "Copyright (c) Microsoft Corporation. All Rights Reserved." ) /// Freely distributed under the MIT Open Source License. https://github.com/Microsoft/visualfsharp/blob/master/License.txt - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:827) + /// (Originally from src/fsharp/FSComp.txt:840) static member optsCopyrightCommunity() = (sprintf "Freely distributed under the MIT Open Source License. https://github.com/Microsoft/visualfsharp/blob/master/License.txt" ) /// Name of the output file (Short form: -o) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:828) + /// (Originally from src/fsharp/FSComp.txt:841) static member optsNameOfOutputFile() = (sprintf "Name of the output file (Short form: -o)" ) /// Build a console executable - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:829) + /// (Originally from src/fsharp/FSComp.txt:842) static member optsBuildConsole() = (sprintf "Build a console executable" ) /// Build a Windows executable - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:830) + /// (Originally from src/fsharp/FSComp.txt:843) static member optsBuildWindows() = (sprintf "Build a Windows executable" ) /// Build a library (Short form: -a) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:831) + /// (Originally from src/fsharp/FSComp.txt:844) static member optsBuildLibrary() = (sprintf "Build a library (Short form: -a)" ) /// Build a module that can be added to another assembly - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:832) + /// (Originally from src/fsharp/FSComp.txt:845) static member optsBuildModule() = (sprintf "Build a module that can be added to another assembly" ) /// Delay-sign the assembly using only the public portion of the strong name key - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:833) + /// (Originally from src/fsharp/FSComp.txt:846) static member optsDelaySign() = (sprintf "Delay-sign the assembly using only the public portion of the strong name key" ) /// Public-sign the assembly using only the public portion of the strong name key, and mark the assembly as signed - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:834) + /// (Originally from src/fsharp/FSComp.txt:847) static member optsPublicSign() = (sprintf "Public-sign the assembly using only the public portion of the strong name key, and mark the assembly as signed" ) /// Write the xmldoc of the assembly to the given file - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:835) + /// (Originally from src/fsharp/FSComp.txt:848) static member optsWriteXml() = (sprintf "Write the xmldoc of the assembly to the given file" ) /// Specify a strong name key file - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:836) + /// (Originally from src/fsharp/FSComp.txt:849) static member optsStrongKeyFile() = (sprintf "Specify a strong name key file" ) /// Specify a strong name key container - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:837) + /// (Originally from src/fsharp/FSComp.txt:850) static member optsStrongKeyContainer() = (sprintf "Specify a strong name key container" ) /// Limit which platforms this code can run on: x86, Itanium, x64, anycpu32bitpreferred, or anycpu. The default is anycpu. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:838) + /// (Originally from src/fsharp/FSComp.txt:851) static member optsPlatform() = (sprintf "Limit which platforms this code can run on: x86, Itanium, x64, anycpu32bitpreferred, or anycpu. The default is anycpu." ) /// Only include optimization information essential for implementing inlined constructs. Inhibits cross-module inlining but improves binary compatibility. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:839) + /// (Originally from src/fsharp/FSComp.txt:852) static member optsNoOpt() = (sprintf "Only include optimization information essential for implementing inlined constructs. Inhibits cross-module inlining but improves binary compatibility." ) /// Don't add a resource to the generated assembly containing F#-specific metadata - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:840) + /// (Originally from src/fsharp/FSComp.txt:853) static member optsNoInterface() = (sprintf "Don't add a resource to the generated assembly containing F#-specific metadata" ) /// Print the inferred interface of the assembly to a file - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:841) + /// (Originally from src/fsharp/FSComp.txt:854) static member optsSig() = (sprintf "Print the inferred interface of the assembly to a file" ) /// Reference an assembly (Short form: -r) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:842) + /// (Originally from src/fsharp/FSComp.txt:855) static member optsReference() = (sprintf "Reference an assembly (Short form: -r)" ) + /// Reference an assembly or directory containing a design time tool (Short form: -t) + /// (Originally from src/fsharp/FSComp.txt:856) + static member optsCompilerTool() = (sprintf "Reference an assembly or directory containing a design time tool (Short form: -t)" ) /// Specify a Win32 resource file (.res) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:843) + /// (Originally from src/fsharp/FSComp.txt:857) static member optsWin32res() = (sprintf "Specify a Win32 resource file (.res)" ) /// Specify a Win32 manifest file - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:844) + /// (Originally from src/fsharp/FSComp.txt:858) static member optsWin32manifest() = (sprintf "Specify a Win32 manifest file" ) /// Do not include the default Win32 manifest - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:845) + /// (Originally from src/fsharp/FSComp.txt:859) static member optsNowin32manifest() = (sprintf "Do not include the default Win32 manifest" ) /// Embed all source files in the portable PDB file - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:846) + /// (Originally from src/fsharp/FSComp.txt:860) static member optsEmbedAllSource() = (sprintf "Embed all source files in the portable PDB file" ) /// Embed specific source files in the portable PDB file - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:847) + /// (Originally from src/fsharp/FSComp.txt:861) static member optsEmbedSource() = (sprintf "Embed specific source files in the portable PDB file" ) /// Source link information file to embed in the portable PDB file - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:848) + /// (Originally from src/fsharp/FSComp.txt:862) static member optsSourceLink() = (sprintf "Source link information file to embed in the portable PDB file" ) /// --embed switch only supported when emitting a Portable PDB (--debug:portable or --debug:embedded) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:849) + /// (Originally from src/fsharp/FSComp.txt:863) static member optsEmbeddedSourceRequirePortablePDBs() = (1501, sprintf "--embed switch only supported when emitting a Portable PDB (--debug:portable or --debug:embedded)" ) /// --sourcelink switch only supported when emitting a Portable PDB (--debug:portable or --debug:embedded) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:850) + /// (Originally from src/fsharp/FSComp.txt:864) static member optsSourceLinkRequirePortablePDBs() = (1502, sprintf "--sourcelink switch only supported when emitting a Portable PDB (--debug:portable or --debug:embedded)" ) /// Source file is too large to embed in a portable PDB - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:851) + /// (Originally from src/fsharp/FSComp.txt:865) static member srcFileTooLarge() = (sprintf "Source file is too large to embed in a portable PDB" ) /// Embed the specified managed resource - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:852) + /// (Originally from src/fsharp/FSComp.txt:866) static member optsResource() = (sprintf "Embed the specified managed resource" ) /// Link the specified resource to this assembly where the resinfo format is [,[,public|private]] - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:853) + /// (Originally from src/fsharp/FSComp.txt:867) static member optsLinkresource() = (sprintf "Link the specified resource to this assembly where the resinfo format is [,[,public|private]]" ) /// Emit debug information (Short form: -g) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:854) + /// (Originally from src/fsharp/FSComp.txt:868) static member optsDebugPM() = (sprintf "Emit debug information (Short form: -g)" ) /// Specify debugging type: full, portable, embedded, pdbonly. ('%s' is the default if no debuggging type specified and enables attaching a debugger to a running program, 'portable' is a cross-platform format, 'embedded' is a cross-platform format embedded into the output file). - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:855) + /// (Originally from src/fsharp/FSComp.txt:869) static member optsDebug(a0 : System.String) = (sprintf "Specify debugging type: full, portable, embedded, pdbonly. ('%s' is the default if no debuggging type specified and enables attaching a debugger to a running program, 'portable' is a cross-platform format, 'embedded' is a cross-platform format embedded into the output file)." a0) /// Enable optimizations (Short form: -O) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:856) + /// (Originally from src/fsharp/FSComp.txt:870) static member optsOptimize() = (sprintf "Enable optimizations (Short form: -O)" ) /// Enable or disable tailcalls - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:857) + /// (Originally from src/fsharp/FSComp.txt:871) static member optsTailcalls() = (sprintf "Enable or disable tailcalls" ) /// Produce a deterministic assembly (including module version GUID and timestamp) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:858) + /// (Originally from src/fsharp/FSComp.txt:872) static member optsDeterministic() = (sprintf "Produce a deterministic assembly (including module version GUID and timestamp)" ) + /// Maps physical paths to source path names output by the compiler + /// (Originally from src/fsharp/FSComp.txt:873) + static member optsPathMap() = (sprintf "Maps physical paths to source path names output by the compiler" ) /// Enable or disable cross-module optimizations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:859) + /// (Originally from src/fsharp/FSComp.txt:874) static member optsCrossoptimize() = (sprintf "Enable or disable cross-module optimizations" ) /// Report all warnings as errors - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:860) + /// (Originally from src/fsharp/FSComp.txt:875) static member optsWarnaserrorPM() = (sprintf "Report all warnings as errors" ) /// Report specific warnings as errors - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:861) + /// (Originally from src/fsharp/FSComp.txt:876) static member optsWarnaserror() = (sprintf "Report specific warnings as errors" ) /// Set a warning level (0-5) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:862) + /// (Originally from src/fsharp/FSComp.txt:877) static member optsWarn() = (sprintf "Set a warning level (0-5)" ) /// Disable specific warning messages - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:863) + /// (Originally from src/fsharp/FSComp.txt:878) static member optsNowarn() = (sprintf "Disable specific warning messages" ) /// Enable specific warnings that may be off by default - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:864) + /// (Originally from src/fsharp/FSComp.txt:879) static member optsWarnOn() = (sprintf "Enable specific warnings that may be off by default" ) /// Generate overflow checks - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:865) + /// (Originally from src/fsharp/FSComp.txt:880) static member optsChecked() = (sprintf "Generate overflow checks" ) /// Define conditional compilation symbols (Short form: -d) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:866) + /// (Originally from src/fsharp/FSComp.txt:881) static member optsDefine() = (sprintf "Define conditional compilation symbols (Short form: -d)" ) /// Ignore ML compatibility warnings - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:867) + /// (Originally from src/fsharp/FSComp.txt:882) static member optsMlcompatibility() = (sprintf "Ignore ML compatibility warnings" ) /// Suppress compiler copyright message - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:868) + /// (Originally from src/fsharp/FSComp.txt:883) static member optsNologo() = (sprintf "Suppress compiler copyright message" ) /// Display this usage message (Short form: -?) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:869) + /// (Originally from src/fsharp/FSComp.txt:884) static member optsHelp() = (sprintf "Display this usage message (Short form: -?)" ) /// Read response file for more options - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:870) + /// (Originally from src/fsharp/FSComp.txt:885) static member optsResponseFile() = (sprintf "Read response file for more options" ) /// Specify the codepage used to read source files - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:871) + /// (Originally from src/fsharp/FSComp.txt:886) static member optsCodepage() = (sprintf "Specify the codepage used to read source files" ) /// Output messages in UTF-8 encoding - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:872) + /// (Originally from src/fsharp/FSComp.txt:887) static member optsUtf8output() = (sprintf "Output messages in UTF-8 encoding" ) /// Output messages with fully qualified paths - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:873) + /// (Originally from src/fsharp/FSComp.txt:888) static member optsFullpaths() = (sprintf "Output messages with fully qualified paths" ) /// Specify a directory for the include path which is used to resolve source files and assemblies (Short form: -I) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:874) + /// (Originally from src/fsharp/FSComp.txt:889) static member optsLib() = (sprintf "Specify a directory for the include path which is used to resolve source files and assemblies (Short form: -I)" ) /// Base address for the library to be built - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:875) + /// (Originally from src/fsharp/FSComp.txt:890) static member optsBaseaddress() = (sprintf "Base address for the library to be built" ) + /// Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) + /// (Originally from src/fsharp/FSComp.txt:891) + static member optsChecksumAlgorithm() = (sprintf "Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default)" ) /// Do not reference the default CLI assemblies by default - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:876) + /// (Originally from src/fsharp/FSComp.txt:892) static member optsNoframework() = (sprintf "Do not reference the default CLI assemblies by default" ) /// Statically link the F# library and all referenced DLLs that depend on it into the assembly being generated - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:877) + /// (Originally from src/fsharp/FSComp.txt:893) static member optsStandalone() = (sprintf "Statically link the F# library and all referenced DLLs that depend on it into the assembly being generated" ) /// Statically link the given assembly and all referenced DLLs that depend on this assembly. Use an assembly name e.g. mylib, not a DLL name. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:878) + /// (Originally from src/fsharp/FSComp.txt:894) static member optsStaticlink() = (sprintf "Statically link the given assembly and all referenced DLLs that depend on this assembly. Use an assembly name e.g. mylib, not a DLL name." ) /// Use a resident background compilation service to improve compiler startup times. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:879) + /// (Originally from src/fsharp/FSComp.txt:895) static member optsResident() = (sprintf "Use a resident background compilation service to improve compiler startup times." ) /// Name the output debug file - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:880) + /// (Originally from src/fsharp/FSComp.txt:896) static member optsPdb() = (sprintf "Name the output debug file" ) /// Resolve assembly references using directory-based rules rather than MSBuild resolution - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:881) + /// (Originally from src/fsharp/FSComp.txt:897) static member optsSimpleresolution() = (sprintf "Resolve assembly references using directory-based rules rather than MSBuild resolution" ) /// Unrecognized target '%s', expected 'exe', 'winexe', 'library' or 'module' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:882) + /// (Originally from src/fsharp/FSComp.txt:898) static member optsUnrecognizedTarget(a0 : System.String) = (1048, sprintf "Unrecognized target '%s', expected 'exe', 'winexe', 'library' or 'module'" a0) /// Unrecognized debug type '%s', expected 'pdbonly' or 'full' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:883) + /// (Originally from src/fsharp/FSComp.txt:899) static member optsUnrecognizedDebugType(a0 : System.String) = (1049, sprintf "Unrecognized debug type '%s', expected 'pdbonly' or 'full'" a0) /// Invalid warning level '%d' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:884) + /// (Originally from src/fsharp/FSComp.txt:900) static member optsInvalidWarningLevel(a0 : System.Int32) = (1050, sprintf "Invalid warning level '%d'" a0) /// Short form of '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:885) + /// (Originally from src/fsharp/FSComp.txt:901) static member optsShortFormOf(a0 : System.String) = (sprintf "Short form of '%s'" a0) /// The command-line option '--cliroot' has been deprecated. Use an explicit reference to a specific copy of mscorlib.dll instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:886) + /// (Originally from src/fsharp/FSComp.txt:902) static member optsClirootDeprecatedMsg() = (sprintf "The command-line option '--cliroot' has been deprecated. Use an explicit reference to a specific copy of mscorlib.dll instead." ) /// Use to override where the compiler looks for mscorlib.dll and framework components - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:887) + /// (Originally from src/fsharp/FSComp.txt:903) static member optsClirootDescription() = (sprintf "Use to override where the compiler looks for mscorlib.dll and framework components" ) /// - OUTPUT FILES - - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:888) + /// (Originally from src/fsharp/FSComp.txt:904) static member optsHelpBannerOutputFiles() = (sprintf "- OUTPUT FILES -" ) /// - INPUT FILES - - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:889) + /// (Originally from src/fsharp/FSComp.txt:905) static member optsHelpBannerInputFiles() = (sprintf "- INPUT FILES -" ) /// - RESOURCES - - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:890) + /// (Originally from src/fsharp/FSComp.txt:906) static member optsHelpBannerResources() = (sprintf "- RESOURCES -" ) /// - CODE GENERATION - - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:891) + /// (Originally from src/fsharp/FSComp.txt:907) static member optsHelpBannerCodeGen() = (sprintf "- CODE GENERATION -" ) /// - ADVANCED - - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:892) + /// (Originally from src/fsharp/FSComp.txt:908) static member optsHelpBannerAdvanced() = (sprintf "- ADVANCED -" ) /// - MISCELLANEOUS - - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:893) + /// (Originally from src/fsharp/FSComp.txt:909) static member optsHelpBannerMisc() = (sprintf "- MISCELLANEOUS -" ) /// - LANGUAGE - - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:894) + /// (Originally from src/fsharp/FSComp.txt:910) static member optsHelpBannerLanguage() = (sprintf "- LANGUAGE -" ) /// - ERRORS AND WARNINGS - - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:895) + /// (Originally from src/fsharp/FSComp.txt:911) static member optsHelpBannerErrsAndWarns() = (sprintf "- ERRORS AND WARNINGS -" ) /// Unknown --test argument: '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:896) + /// (Originally from src/fsharp/FSComp.txt:912) static member optsUnknownArgumentToTheTestSwitch(a0 : System.String) = (1063, sprintf "Unknown --test argument: '%s'" a0) /// Unrecognized platform '%s', valid values are 'x86', 'x64', 'Itanium', 'anycpu32bitpreferred', and 'anycpu' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:897) + /// (Originally from src/fsharp/FSComp.txt:913) static member optsUnknownPlatform(a0 : System.String) = (1064, sprintf "Unrecognized platform '%s', valid values are 'x86', 'x64', 'Itanium', 'anycpu32bitpreferred', and 'anycpu'" a0) + /// Algorithm '%s' is not supported + /// (Originally from src/fsharp/FSComp.txt:914) + static member optsUnknownChecksumAlgorithm(a0 : System.String) = (1065, sprintf "Algorithm '%s' is not supported" a0) /// The command-line option '%s' is for test purposes only - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:898) + /// (Originally from src/fsharp/FSComp.txt:915) static member optsInternalNoDescription(a0 : System.String) = (sprintf "The command-line option '%s' is for test purposes only" a0) /// The command-line option '%s' has been deprecated - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:899) + /// (Originally from src/fsharp/FSComp.txt:916) static member optsDCLONoDescription(a0 : System.String) = (sprintf "The command-line option '%s' has been deprecated" a0) /// The command-line option '%s' has been deprecated. Use '%s' instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:900) + /// (Originally from src/fsharp/FSComp.txt:917) static member optsDCLODeprecatedSuggestAlternative(a0 : System.String, a1 : System.String) = (sprintf "The command-line option '%s' has been deprecated. Use '%s' instead." a0 a1) /// The command-line option '%s' has been deprecated. HTML document generation is now part of the F# Power Pack, via the tool FsHtmlDoc.exe. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:901) + /// (Originally from src/fsharp/FSComp.txt:918) static member optsDCLOHtmlDoc(a0 : System.String) = (sprintf "The command-line option '%s' has been deprecated. HTML document generation is now part of the F# Power Pack, via the tool FsHtmlDoc.exe." a0) /// Output warning and error messages in color - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:902) + /// (Originally from src/fsharp/FSComp.txt:919) static member optsConsoleColors() = (sprintf "Output warning and error messages in color" ) /// Enable high-entropy ASLR - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:903) + /// (Originally from src/fsharp/FSComp.txt:920) static member optsUseHighEntropyVA() = (sprintf "Enable high-entropy ASLR" ) /// Specify subsystem version of this assembly - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:904) + /// (Originally from src/fsharp/FSComp.txt:921) static member optsSubSystemVersion() = (sprintf "Specify subsystem version of this assembly" ) /// Specify target framework profile of this assembly. Valid values are mscorlib, netcore or netstandard. Default - mscorlib - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:905) + /// (Originally from src/fsharp/FSComp.txt:922) static member optsTargetProfile() = (sprintf "Specify target framework profile of this assembly. Valid values are mscorlib, netcore or netstandard. Default - mscorlib" ) /// Emit debug information in quotations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:906) + /// (Originally from src/fsharp/FSComp.txt:923) static member optsEmitDebugInfoInQuotations() = (sprintf "Emit debug information in quotations" ) /// Specify the preferred output language culture name (e.g. es-ES, ja-JP) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:907) + /// (Originally from src/fsharp/FSComp.txt:924) static member optsPreferredUiLang() = (sprintf "Specify the preferred output language culture name (e.g. es-ES, ja-JP)" ) /// Don't copy FSharp.Core.dll along the produced binaries - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:908) + /// (Originally from src/fsharp/FSComp.txt:925) static member optsNoCopyFsharpCore() = (sprintf "Don't copy FSharp.Core.dll along the produced binaries" ) /// Invalid version '%s' for '--subsystemversion'. The version must be 4.00 or greater. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:909) + /// (Originally from src/fsharp/FSComp.txt:926) static member optsInvalidSubSystemVersion(a0 : System.String) = (1051, sprintf "Invalid version '%s' for '--subsystemversion'. The version must be 4.00 or greater." a0) /// Invalid value '%s' for '--targetprofile', valid values are 'mscorlib', 'netcore' or 'netstandard'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:910) + /// (Originally from src/fsharp/FSComp.txt:927) static member optsInvalidTargetProfile(a0 : System.String) = (1052, sprintf "Invalid value '%s' for '--targetprofile', valid values are 'mscorlib', 'netcore' or 'netstandard'." a0) /// Full name - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:911) + /// (Originally from src/fsharp/FSComp.txt:928) static member typeInfoFullName() = (sprintf "Full name" ) /// and %d other overloads - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:915) + /// (Originally from src/fsharp/FSComp.txt:932) static member typeInfoOtherOverloads(a0 : System.Int32) = (sprintf "and %d other overloads" a0) /// union case - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:916) + /// (Originally from src/fsharp/FSComp.txt:933) static member typeInfoUnionCase() = (sprintf "union case" ) /// active pattern result - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:917) + /// (Originally from src/fsharp/FSComp.txt:934) static member typeInfoActivePatternResult() = (sprintf "active pattern result" ) /// active recognizer - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:918) + /// (Originally from src/fsharp/FSComp.txt:935) static member typeInfoActiveRecognizer() = (sprintf "active recognizer" ) /// field - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:919) + /// (Originally from src/fsharp/FSComp.txt:936) static member typeInfoField() = (sprintf "field" ) /// event - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:920) + /// (Originally from src/fsharp/FSComp.txt:937) static member typeInfoEvent() = (sprintf "event" ) /// property - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:921) + /// (Originally from src/fsharp/FSComp.txt:938) static member typeInfoProperty() = (sprintf "property" ) /// extension - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:922) + /// (Originally from src/fsharp/FSComp.txt:939) static member typeInfoExtension() = (sprintf "extension" ) /// custom operation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:923) + /// (Originally from src/fsharp/FSComp.txt:940) static member typeInfoCustomOperation() = (sprintf "custom operation" ) /// argument - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:924) + /// (Originally from src/fsharp/FSComp.txt:941) static member typeInfoArgument() = (sprintf "argument" ) /// anonymous record field - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:925) + /// (Originally from src/fsharp/FSComp.txt:942) static member typeInfoAnonRecdField() = (sprintf "anonymous record field" ) /// patvar - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:926) + /// (Originally from src/fsharp/FSComp.txt:943) static member typeInfoPatternVariable() = (sprintf "patvar" ) /// namespace - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:927) + /// (Originally from src/fsharp/FSComp.txt:944) static member typeInfoNamespace() = (sprintf "namespace" ) /// module - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:928) + /// (Originally from src/fsharp/FSComp.txt:945) static member typeInfoModule() = (sprintf "module" ) /// namespace/module - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:929) + /// (Originally from src/fsharp/FSComp.txt:946) static member typeInfoNamespaceOrModule() = (sprintf "namespace/module" ) /// from %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:930) + /// (Originally from src/fsharp/FSComp.txt:947) static member typeInfoFromFirst(a0 : System.String) = (sprintf "from %s" a0) /// also from %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:931) + /// (Originally from src/fsharp/FSComp.txt:948) static member typeInfoFromNext(a0 : System.String) = (sprintf "also from %s" a0) /// generated property - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:932) + /// (Originally from src/fsharp/FSComp.txt:949) static member typeInfoGeneratedProperty() = (sprintf "generated property" ) /// generated type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:933) + /// (Originally from src/fsharp/FSComp.txt:950) static member typeInfoGeneratedType() = (sprintf "generated type" ) /// Found by AssemblyFolders registry key - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:934) + /// (Originally from src/fsharp/FSComp.txt:951) static member assemblyResolutionFoundByAssemblyFoldersKey() = (sprintf "Found by AssemblyFolders registry key" ) /// Found by AssemblyFoldersEx registry key - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:935) + /// (Originally from src/fsharp/FSComp.txt:952) static member assemblyResolutionFoundByAssemblyFoldersExKey() = (sprintf "Found by AssemblyFoldersEx registry key" ) /// .NET Framework - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:936) + /// (Originally from src/fsharp/FSComp.txt:953) static member assemblyResolutionNetFramework() = (sprintf ".NET Framework" ) /// Global Assembly Cache - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:937) + /// (Originally from src/fsharp/FSComp.txt:954) static member assemblyResolutionGAC() = (sprintf "Global Assembly Cache" ) /// Recursive class hierarchy in type '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:938) + /// (Originally from src/fsharp/FSComp.txt:955) static member recursiveClassHierarchy(a0 : System.String) = (1089, sprintf "Recursive class hierarchy in type '%s'" a0) /// Invalid recursive reference to an abstract slot - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:939) + /// (Originally from src/fsharp/FSComp.txt:956) static member InvalidRecursiveReferenceToAbstractSlot() = (1090, sprintf "Invalid recursive reference to an abstract slot" ) /// The event '%s' has a non-standard type. If this event is declared in another CLI language, you may need to access this event using the explicit %s and %s methods for the event. If this event is declared in F#, make the type of the event an instantiation of either 'IDelegateEvent<_>' or 'IEvent<_,_>'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:940) + /// (Originally from src/fsharp/FSComp.txt:957) static member eventHasNonStandardType(a0 : System.String, a1 : System.String, a2 : System.String) = (1091, sprintf "The event '%s' has a non-standard type. If this event is declared in another CLI language, you may need to access this event using the explicit %s and %s methods for the event. If this event is declared in F#, make the type of the event an instantiation of either 'IDelegateEvent<_>' or 'IEvent<_,_>'." a0 a1 a2) /// The type '%s' is not accessible from this code location - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:941) + /// (Originally from src/fsharp/FSComp.txt:958) static member typeIsNotAccessible(a0 : System.String) = (1092, sprintf "The type '%s' is not accessible from this code location" a0) /// The union cases or fields of the type '%s' are not accessible from this code location - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:942) + /// (Originally from src/fsharp/FSComp.txt:959) static member unionCasesAreNotAccessible(a0 : System.String) = (1093, sprintf "The union cases or fields of the type '%s' are not accessible from this code location" a0) /// The value '%s' is not accessible from this code location - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:943) + /// (Originally from src/fsharp/FSComp.txt:960) static member valueIsNotAccessible(a0 : System.String) = (1094, sprintf "The value '%s' is not accessible from this code location" a0) /// The union case '%s' is not accessible from this code location - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:944) + /// (Originally from src/fsharp/FSComp.txt:961) static member unionCaseIsNotAccessible(a0 : System.String) = (1095, sprintf "The union case '%s' is not accessible from this code location" a0) /// The record, struct or class field '%s' is not accessible from this code location - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:945) + /// (Originally from src/fsharp/FSComp.txt:962) static member fieldIsNotAccessible(a0 : System.String) = (1096, sprintf "The record, struct or class field '%s' is not accessible from this code location" a0) /// The struct or class field '%s' is not accessible from this code location - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:946) + /// (Originally from src/fsharp/FSComp.txt:963) static member structOrClassFieldIsNotAccessible(a0 : System.String) = (1097, sprintf "The struct or class field '%s' is not accessible from this code location" a0) /// This construct is experimental - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:947) + /// (Originally from src/fsharp/FSComp.txt:964) static member experimentalConstruct() = (sprintf "This construct is experimental" ) /// No Invoke methods found for delegate type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:948) + /// (Originally from src/fsharp/FSComp.txt:965) static member noInvokeMethodsFound() = (1099, sprintf "No Invoke methods found for delegate type" ) /// More than one Invoke method found for delegate type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:949) + /// (Originally from src/fsharp/FSComp.txt:966) static member moreThanOneInvokeMethodFound() = (sprintf "More than one Invoke method found for delegate type" ) /// Delegates are not allowed to have curried signatures - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:950) + /// (Originally from src/fsharp/FSComp.txt:967) static member delegatesNotAllowedToHaveCurriedSignatures() = (1101, sprintf "Delegates are not allowed to have curried signatures" ) /// Unexpected Expr.TyChoose - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:951) + /// (Originally from src/fsharp/FSComp.txt:968) static member tlrUnexpectedTExpr() = (1102, sprintf "Unexpected Expr.TyChoose" ) /// Note: Lambda-lifting optimizations have not been applied because of the use of this local constrained generic function as a first class value. Adding type constraints may resolve this condition. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:952) + /// (Originally from src/fsharp/FSComp.txt:969) static member tlrLambdaLiftingOptimizationsNotApplied() = (1103, sprintf "Note: Lambda-lifting optimizations have not been applied because of the use of this local constrained generic function as a first class value. Adding type constraints may resolve this condition." ) /// Identifiers containing '@' are reserved for use in F# code generation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:953) + /// (Originally from src/fsharp/FSComp.txt:970) static member lexhlpIdentifiersContainingAtSymbolReserved() = (1104, sprintf "Identifiers containing '@' are reserved for use in F# code generation" ) /// The identifier '%s' is reserved for future use by F# - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:954) + /// (Originally from src/fsharp/FSComp.txt:971) static member lexhlpIdentifierReserved(a0 : System.String) = (sprintf "The identifier '%s' is reserved for future use by F#" a0) /// Missing variable '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:955) + /// (Originally from src/fsharp/FSComp.txt:972) static member patcMissingVariable(a0 : System.String) = (1106, sprintf "Missing variable '%s'" a0) /// Partial active patterns may only generate one result - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:956) + /// (Originally from src/fsharp/FSComp.txt:973) static member patcPartialActivePatternsGenerateOneResult() = (1107, sprintf "Partial active patterns may only generate one result" ) /// The type '%s' is required here and is unavailable. You must add a reference to assembly '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:957) + /// (Originally from src/fsharp/FSComp.txt:974) static member impTypeRequiredUnavailable(a0 : System.String, a1 : System.String) = (1108, sprintf "The type '%s' is required here and is unavailable. You must add a reference to assembly '%s'." a0 a1) /// A reference to the type '%s' in assembly '%s' was found, but the type could not be found in that assembly - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:958) + /// (Originally from src/fsharp/FSComp.txt:975) static member impReferencedTypeCouldNotBeFoundInAssembly(a0 : System.String, a1 : System.String) = (1109, sprintf "A reference to the type '%s' in assembly '%s' was found, but the type could not be found in that assembly" a0 a1) /// Internal error or badly formed metadata: not enough type parameters were in scope while importing - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:959) + /// (Originally from src/fsharp/FSComp.txt:976) static member impNotEnoughTypeParamsInScopeWhileImporting() = (1110, sprintf "Internal error or badly formed metadata: not enough type parameters were in scope while importing" ) /// A reference to the DLL %s is required by assembly %s. The imported type %s is located in the first assembly and could not be resolved. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:960) + /// (Originally from src/fsharp/FSComp.txt:977) static member impReferenceToDllRequiredByAssembly(a0 : System.String, a1 : System.String, a2 : System.String) = (1111, sprintf "A reference to the DLL %s is required by assembly %s. The imported type %s is located in the first assembly and could not be resolved." a0 a1 a2) /// An imported assembly uses the type '%s' but that type is not public - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:961) + /// (Originally from src/fsharp/FSComp.txt:978) static member impImportedAssemblyUsesNotPublicType(a0 : System.String) = (1112, sprintf "An imported assembly uses the type '%s' but that type is not public" a0) /// The value '%s' was marked inline but its implementation makes use of an internal or private function which is not sufficiently accessible - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:962) + /// (Originally from src/fsharp/FSComp.txt:979) static member optValueMarkedInlineButIncomplete(a0 : System.String) = (1113, sprintf "The value '%s' was marked inline but its implementation makes use of an internal or private function which is not sufficiently accessible" a0) /// The value '%s' was marked inline but was not bound in the optimization environment - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:963) + /// (Originally from src/fsharp/FSComp.txt:980) static member optValueMarkedInlineButWasNotBoundInTheOptEnv(a0 : System.String) = (1114, sprintf "The value '%s' was marked inline but was not bound in the optimization environment" a0) /// Local value %s not found during optimization - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:964) + /// (Originally from src/fsharp/FSComp.txt:981) static member optLocalValueNotFoundDuringOptimization(a0 : System.String) = (1115, sprintf "Local value %s not found during optimization" a0) /// A value marked as 'inline' has an unexpected value - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:965) + /// (Originally from src/fsharp/FSComp.txt:982) static member optValueMarkedInlineHasUnexpectedValue() = (1116, sprintf "A value marked as 'inline' has an unexpected value" ) /// A value marked as 'inline' could not be inlined - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:966) + /// (Originally from src/fsharp/FSComp.txt:983) static member optValueMarkedInlineCouldNotBeInlined() = (1117, sprintf "A value marked as 'inline' could not be inlined" ) /// Failed to inline the value '%s' marked 'inline', perhaps because a recursive value was marked 'inline' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:967) + /// (Originally from src/fsharp/FSComp.txt:984) static member optFailedToInlineValue(a0 : System.String) = (1118, sprintf "Failed to inline the value '%s' marked 'inline', perhaps because a recursive value was marked 'inline'" a0) /// Recursive ValValue %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:968) + /// (Originally from src/fsharp/FSComp.txt:985) static member optRecursiveValValue(a0 : System.String) = (1119, sprintf "Recursive ValValue %s" a0) /// The indentation of this 'in' token is incorrect with respect to the corresponding 'let' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:969) + /// (Originally from src/fsharp/FSComp.txt:986) static member lexfltIncorrentIndentationOfIn() = (sprintf "The indentation of this 'in' token is incorrect with respect to the corresponding 'let'" ) /// Possible incorrect indentation: this token is offside of context started at position %s. Try indenting this token further or using standard formatting conventions. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:970) + /// (Originally from src/fsharp/FSComp.txt:987) static member lexfltTokenIsOffsideOfContextStartedEarlier(a0 : System.String) = (sprintf "Possible incorrect indentation: this token is offside of context started at position %s. Try indenting this token further or using standard formatting conventions." a0) /// The '|' tokens separating rules of this pattern match are misaligned by one column. Consider realigning your code or using further indentation. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:971) + /// (Originally from src/fsharp/FSComp.txt:988) static member lexfltSeparatorTokensOfPatternMatchMisaligned() = (sprintf "The '|' tokens separating rules of this pattern match are misaligned by one column. Consider realigning your code or using further indentation." ) /// Invalid module/expression/type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:972) + /// (Originally from src/fsharp/FSComp.txt:989) static member nrInvalidModuleExprType() = (1123, sprintf "Invalid module/expression/type" ) /// Multiple types exist called '%s', taking different numbers of generic parameters. Provide a type instantiation to disambiguate the type resolution, e.g. '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:973) + /// (Originally from src/fsharp/FSComp.txt:990) static member nrTypeInstantiationNeededToDisambiguateTypesWithSameName(a0 : System.String, a1 : System.String) = (1124, sprintf "Multiple types exist called '%s', taking different numbers of generic parameters. Provide a type instantiation to disambiguate the type resolution, e.g. '%s'." a0 a1) /// The instantiation of the generic type '%s' is missing and can't be inferred from the arguments or return type of this member. Consider providing a type instantiation when accessing this type, e.g. '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:974) + /// (Originally from src/fsharp/FSComp.txt:991) static member nrTypeInstantiationIsMissingAndCouldNotBeInferred(a0 : System.String, a1 : System.String) = (1125, sprintf "The instantiation of the generic type '%s' is missing and can't be inferred from the arguments or return type of this member. Consider providing a type instantiation when accessing this type, e.g. '%s'." a0 a1) /// 'global' may only be used as the first name in a qualified path - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:975) + /// (Originally from src/fsharp/FSComp.txt:992) static member nrGlobalUsedOnlyAsFirstName() = (1126, sprintf "'global' may only be used as the first name in a qualified path" ) /// This is not a constructor or literal, or a constructor is being used incorrectly - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:976) + /// (Originally from src/fsharp/FSComp.txt:993) static member nrIsNotConstructorOrLiteral() = (1127, sprintf "This is not a constructor or literal, or a constructor is being used incorrectly" ) /// Unexpected empty long identifier - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:977) + /// (Originally from src/fsharp/FSComp.txt:994) static member nrUnexpectedEmptyLongId() = (1128, sprintf "Unexpected empty long identifier" ) /// The record type '%s' does not contain a label '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:978) + /// (Originally from src/fsharp/FSComp.txt:995) static member nrRecordDoesNotContainSuchLabel(a0 : System.String, a1 : System.String) = (1129, sprintf "The record type '%s' does not contain a label '%s'." a0 a1) /// Invalid field label - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:979) + /// (Originally from src/fsharp/FSComp.txt:996) static member nrInvalidFieldLabel() = (1130, sprintf "Invalid field label" ) /// Invalid expression '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:980) + /// (Originally from src/fsharp/FSComp.txt:997) static member nrInvalidExpression(a0 : System.String) = (1132, sprintf "Invalid expression '%s'" a0) /// No constructors are available for the type '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:981) + /// (Originally from src/fsharp/FSComp.txt:998) static member nrNoConstructorsAvailableForType(a0 : System.String) = (1133, sprintf "No constructors are available for the type '%s'" a0) /// The union type for union case '%s' was defined with the RequireQualifiedAccessAttribute. Include the name of the union type ('%s') in the name you are using. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:982) + /// (Originally from src/fsharp/FSComp.txt:999) static member nrUnionTypeNeedsQualifiedAccess(a0 : System.String, a1 : System.String) = (1134, sprintf "The union type for union case '%s' was defined with the RequireQualifiedAccessAttribute. Include the name of the union type ('%s') in the name you are using." a0 a1) /// The record type for the record field '%s' was defined with the RequireQualifiedAccessAttribute. Include the name of the record type ('%s') in the name you are using. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:983) + /// (Originally from src/fsharp/FSComp.txt:1000) static member nrRecordTypeNeedsQualifiedAccess(a0 : System.String, a1 : System.String) = (1135, sprintf "The record type for the record field '%s' was defined with the RequireQualifiedAccessAttribute. Include the name of the record type ('%s') in the name you are using." a0 a1) /// Unexpected error creating debug information file '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:984) + /// (Originally from src/fsharp/FSComp.txt:1001) static member ilwriteErrorCreatingPdb(a0 : System.String) = (1136, sprintf "Unexpected error creating debug information file '%s'" a0) /// This number is outside the allowable range for this integer type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:985) + /// (Originally from src/fsharp/FSComp.txt:1002) static member lexOutsideIntegerRange() = (1138, sprintf "This number is outside the allowable range for this integer type" ) /// '%s' is not permitted as a character in operator names and is reserved for future use - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:989) + /// (Originally from src/fsharp/FSComp.txt:1006) static member lexCharNotAllowedInOperatorNames(a0 : System.String) = (sprintf "'%s' is not permitted as a character in operator names and is reserved for future use" a0) /// Unexpected character '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:990) + /// (Originally from src/fsharp/FSComp.txt:1007) static member lexUnexpectedChar(a0 : System.String) = (sprintf "Unexpected character '%s'" a0) /// This byte array literal contains characters that do not encode as a single byte - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:991) + /// (Originally from src/fsharp/FSComp.txt:1008) static member lexByteArrayCannotEncode() = (1140, sprintf "This byte array literal contains characters that do not encode as a single byte" ) /// Identifiers followed by '%s' are reserved for future use - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:992) + /// (Originally from src/fsharp/FSComp.txt:1009) static member lexIdentEndInMarkReserved(a0 : System.String) = (1141, sprintf "Identifiers followed by '%s' are reserved for future use" a0) /// This number is outside the allowable range for 8-bit signed integers - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:993) + /// (Originally from src/fsharp/FSComp.txt:1010) static member lexOutsideEightBitSigned() = (1142, sprintf "This number is outside the allowable range for 8-bit signed integers" ) /// This number is outside the allowable range for hexadecimal 8-bit signed integers - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:994) + /// (Originally from src/fsharp/FSComp.txt:1011) static member lexOutsideEightBitSignedHex() = (1143, sprintf "This number is outside the allowable range for hexadecimal 8-bit signed integers" ) /// This number is outside the allowable range for 8-bit unsigned integers - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:995) + /// (Originally from src/fsharp/FSComp.txt:1012) static member lexOutsideEightBitUnsigned() = (1144, sprintf "This number is outside the allowable range for 8-bit unsigned integers" ) /// This number is outside the allowable range for 16-bit signed integers - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:996) + /// (Originally from src/fsharp/FSComp.txt:1013) static member lexOutsideSixteenBitSigned() = (1145, sprintf "This number is outside the allowable range for 16-bit signed integers" ) /// This number is outside the allowable range for 16-bit unsigned integers - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:997) + /// (Originally from src/fsharp/FSComp.txt:1014) static member lexOutsideSixteenBitUnsigned() = (1146, sprintf "This number is outside the allowable range for 16-bit unsigned integers" ) /// This number is outside the allowable range for 32-bit signed integers - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:998) + /// (Originally from src/fsharp/FSComp.txt:1015) static member lexOutsideThirtyTwoBitSigned() = (1147, sprintf "This number is outside the allowable range for 32-bit signed integers" ) /// This number is outside the allowable range for 32-bit unsigned integers - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:999) + /// (Originally from src/fsharp/FSComp.txt:1016) static member lexOutsideThirtyTwoBitUnsigned() = (1148, sprintf "This number is outside the allowable range for 32-bit unsigned integers" ) /// This number is outside the allowable range for 64-bit signed integers - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1000) + /// (Originally from src/fsharp/FSComp.txt:1017) static member lexOutsideSixtyFourBitSigned() = (1149, sprintf "This number is outside the allowable range for 64-bit signed integers" ) /// This number is outside the allowable range for 64-bit unsigned integers - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1001) + /// (Originally from src/fsharp/FSComp.txt:1018) static member lexOutsideSixtyFourBitUnsigned() = (1150, sprintf "This number is outside the allowable range for 64-bit unsigned integers" ) /// This number is outside the allowable range for signed native integers - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1002) + /// (Originally from src/fsharp/FSComp.txt:1019) static member lexOutsideNativeSigned() = (1151, sprintf "This number is outside the allowable range for signed native integers" ) /// This number is outside the allowable range for unsigned native integers - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1003) + /// (Originally from src/fsharp/FSComp.txt:1020) static member lexOutsideNativeUnsigned() = (1152, sprintf "This number is outside the allowable range for unsigned native integers" ) /// Invalid floating point number - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1004) + /// (Originally from src/fsharp/FSComp.txt:1021) static member lexInvalidFloat() = (1153, sprintf "Invalid floating point number" ) /// This number is outside the allowable range for decimal literals - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1005) + /// (Originally from src/fsharp/FSComp.txt:1022) static member lexOusideDecimal() = (1154, sprintf "This number is outside the allowable range for decimal literals" ) /// This number is outside the allowable range for 32-bit floats - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1006) + /// (Originally from src/fsharp/FSComp.txt:1023) static member lexOusideThirtyTwoBitFloat() = (1155, sprintf "This number is outside the allowable range for 32-bit floats" ) - /// This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0b0001 (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1007) - static member lexInvalidNumericLiteral() = (1156, sprintf "This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0b0001 (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger)." ) + /// This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). + /// (Originally from src/fsharp/FSComp.txt:1024) + static member lexInvalidNumericLiteral() = (1156, sprintf "This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger)." ) /// This is not a valid byte literal - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1008) + /// (Originally from src/fsharp/FSComp.txt:1025) static member lexInvalidByteLiteral() = (1157, sprintf "This is not a valid byte literal" ) /// This is not a valid character literal - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1009) + /// (Originally from src/fsharp/FSComp.txt:1026) static member lexInvalidCharLiteral() = (1158, sprintf "This is not a valid character literal" ) /// This Unicode encoding is only valid in string literals - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1010) + /// (Originally from src/fsharp/FSComp.txt:1027) static member lexThisUnicodeOnlyInStringLiterals() = (1159, sprintf "This Unicode encoding is only valid in string literals" ) /// This token is reserved for future use - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1011) + /// (Originally from src/fsharp/FSComp.txt:1028) static member lexTokenReserved() = (1160, sprintf "This token is reserved for future use" ) /// TABs are not allowed in F# code unless the #indent \"off\" option is used - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1012) + /// (Originally from src/fsharp/FSComp.txt:1029) static member lexTabsNotAllowed() = (1161, sprintf "TABs are not allowed in F# code unless the #indent \"off\" option is used" ) /// Invalid line number: '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1013) + /// (Originally from src/fsharp/FSComp.txt:1030) static member lexInvalidLineNumber(a0 : System.String) = (1162, sprintf "Invalid line number: '%s'" a0) /// #if directive must appear as the first non-whitespace character on a line - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1014) + /// (Originally from src/fsharp/FSComp.txt:1031) static member lexHashIfMustBeFirst() = (1163, sprintf "#if directive must appear as the first non-whitespace character on a line" ) /// #else has no matching #if - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1015) + /// (Originally from src/fsharp/FSComp.txt:1032) static member lexHashElseNoMatchingIf() = (sprintf "#else has no matching #if" ) /// #endif required for #else - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1016) + /// (Originally from src/fsharp/FSComp.txt:1033) static member lexHashEndifRequiredForElse() = (sprintf "#endif required for #else" ) /// #else directive must appear as the first non-whitespace character on a line - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1017) + /// (Originally from src/fsharp/FSComp.txt:1034) static member lexHashElseMustBeFirst() = (1166, sprintf "#else directive must appear as the first non-whitespace character on a line" ) /// #endif has no matching #if - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1018) + /// (Originally from src/fsharp/FSComp.txt:1035) static member lexHashEndingNoMatchingIf() = (sprintf "#endif has no matching #if" ) /// #endif directive must appear as the first non-whitespace character on a line - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1019) + /// (Originally from src/fsharp/FSComp.txt:1036) static member lexHashEndifMustBeFirst() = (1168, sprintf "#endif directive must appear as the first non-whitespace character on a line" ) /// #if directive should be immediately followed by an identifier - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1020) + /// (Originally from src/fsharp/FSComp.txt:1037) static member lexHashIfMustHaveIdent() = (1169, sprintf "#if directive should be immediately followed by an identifier" ) /// Syntax error. Wrong nested #endif, unexpected tokens before it. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1021) + /// (Originally from src/fsharp/FSComp.txt:1038) static member lexWrongNestedHashEndif() = (1170, sprintf "Syntax error. Wrong nested #endif, unexpected tokens before it." ) /// #! may only appear as the first line at the start of a file. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1022) + /// (Originally from src/fsharp/FSComp.txt:1039) static member lexHashBangMustBeFirstInFile() = (sprintf "#! may only appear as the first line at the start of a file." ) /// Expected single line comment or end of line - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1023) + /// (Originally from src/fsharp/FSComp.txt:1040) static member pplexExpectedSingleLineComment() = (1171, sprintf "Expected single line comment or end of line" ) /// Infix operator member '%s' has no arguments. Expected a tuple of 2 arguments, e.g. static member (+) (x,y) = ... - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1024) + /// (Originally from src/fsharp/FSComp.txt:1041) static member memberOperatorDefinitionWithNoArguments(a0 : System.String) = (1172, sprintf "Infix operator member '%s' has no arguments. Expected a tuple of 2 arguments, e.g. static member (+) (x,y) = ..." a0) /// Infix operator member '%s' has %d initial argument(s). Expected a tuple of 2 arguments, e.g. static member (+) (x,y) = ... - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1025) + /// (Originally from src/fsharp/FSComp.txt:1042) static member memberOperatorDefinitionWithNonPairArgument(a0 : System.String, a1 : System.Int32) = (1173, sprintf "Infix operator member '%s' has %d initial argument(s). Expected a tuple of 2 arguments, e.g. static member (+) (x,y) = ..." a0 a1) /// Infix operator member '%s' has extra curried arguments. Expected a tuple of 2 arguments, e.g. static member (+) (x,y) = ... - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1026) + /// (Originally from src/fsharp/FSComp.txt:1043) static member memberOperatorDefinitionWithCurriedArguments(a0 : System.String) = (1174, sprintf "Infix operator member '%s' has extra curried arguments. Expected a tuple of 2 arguments, e.g. static member (+) (x,y) = ..." a0) /// All record, union and struct types in FSharp.Core.dll must be explicitly labelled with 'StructuralComparison' or 'NoComparison' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1027) + /// (Originally from src/fsharp/FSComp.txt:1044) static member tcFSharpCoreRequiresExplicit() = (1175, sprintf "All record, union and struct types in FSharp.Core.dll must be explicitly labelled with 'StructuralComparison' or 'NoComparison'" ) /// The struct, record or union type '%s' has the 'StructuralComparison' attribute but the type parameter '%s' does not satisfy the 'comparison' constraint. Consider adding the 'comparison' constraint to the type parameter - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1028) + /// (Originally from src/fsharp/FSComp.txt:1045) static member tcStructuralComparisonNotSatisfied1(a0 : System.String, a1 : System.String) = (1176, sprintf "The struct, record or union type '%s' has the 'StructuralComparison' attribute but the type parameter '%s' does not satisfy the 'comparison' constraint. Consider adding the 'comparison' constraint to the type parameter" a0 a1) /// The struct, record or union type '%s' has the 'StructuralComparison' attribute but the component type '%s' does not satisfy the 'comparison' constraint - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1029) + /// (Originally from src/fsharp/FSComp.txt:1046) static member tcStructuralComparisonNotSatisfied2(a0 : System.String, a1 : System.String) = (1177, sprintf "The struct, record or union type '%s' has the 'StructuralComparison' attribute but the component type '%s' does not satisfy the 'comparison' constraint" a0 a1) /// The struct, record or union type '%s' is not structurally comparable because the type parameter %s does not satisfy the 'comparison' constraint. Consider adding the 'NoComparison' attribute to the type '%s' to clarify that the type is not comparable - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1030) + /// (Originally from src/fsharp/FSComp.txt:1047) static member tcNoComparisonNeeded1(a0 : System.String, a1 : System.String, a2 : System.String) = (1178, sprintf "The struct, record or union type '%s' is not structurally comparable because the type parameter %s does not satisfy the 'comparison' constraint. Consider adding the 'NoComparison' attribute to the type '%s' to clarify that the type is not comparable" a0 a1 a2) /// The struct, record or union type '%s' is not structurally comparable because the type '%s' does not satisfy the 'comparison' constraint. Consider adding the 'NoComparison' attribute to the type '%s' to clarify that the type is not comparable - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1031) + /// (Originally from src/fsharp/FSComp.txt:1048) static member tcNoComparisonNeeded2(a0 : System.String, a1 : System.String, a2 : System.String) = (1178, sprintf "The struct, record or union type '%s' is not structurally comparable because the type '%s' does not satisfy the 'comparison' constraint. Consider adding the 'NoComparison' attribute to the type '%s' to clarify that the type is not comparable" a0 a1 a2) /// The struct, record or union type '%s' does not support structural equality because the type parameter %s does not satisfy the 'equality' constraint. Consider adding the 'NoEquality' attribute to the type '%s' to clarify that the type does not support structural equality - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1032) + /// (Originally from src/fsharp/FSComp.txt:1049) static member tcNoEqualityNeeded1(a0 : System.String, a1 : System.String, a2 : System.String) = (1178, sprintf "The struct, record or union type '%s' does not support structural equality because the type parameter %s does not satisfy the 'equality' constraint. Consider adding the 'NoEquality' attribute to the type '%s' to clarify that the type does not support structural equality" a0 a1 a2) /// The struct, record or union type '%s' does not support structural equality because the type '%s' does not satisfy the 'equality' constraint. Consider adding the 'NoEquality' attribute to the type '%s' to clarify that the type does not support structural equality - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1033) + /// (Originally from src/fsharp/FSComp.txt:1050) static member tcNoEqualityNeeded2(a0 : System.String, a1 : System.String, a2 : System.String) = (1178, sprintf "The struct, record or union type '%s' does not support structural equality because the type '%s' does not satisfy the 'equality' constraint. Consider adding the 'NoEquality' attribute to the type '%s' to clarify that the type does not support structural equality" a0 a1 a2) /// The struct, record or union type '%s' has the 'StructuralEquality' attribute but the type parameter '%s' does not satisfy the 'equality' constraint. Consider adding the 'equality' constraint to the type parameter - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1034) + /// (Originally from src/fsharp/FSComp.txt:1051) static member tcStructuralEqualityNotSatisfied1(a0 : System.String, a1 : System.String) = (1179, sprintf "The struct, record or union type '%s' has the 'StructuralEquality' attribute but the type parameter '%s' does not satisfy the 'equality' constraint. Consider adding the 'equality' constraint to the type parameter" a0 a1) /// The struct, record or union type '%s' has the 'StructuralEquality' attribute but the component type '%s' does not satisfy the 'equality' constraint - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1035) + /// (Originally from src/fsharp/FSComp.txt:1052) static member tcStructuralEqualityNotSatisfied2(a0 : System.String, a1 : System.String) = (1180, sprintf "The struct, record or union type '%s' has the 'StructuralEquality' attribute but the component type '%s' does not satisfy the 'equality' constraint" a0 a1) /// Each argument of the primary constructor for a struct must be given a type, for example 'type S(x1:int, x2: int) = ...'. These arguments determine the fields of the struct. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1036) + /// (Originally from src/fsharp/FSComp.txt:1053) static member tcStructsMustDeclareTypesOfImplicitCtorArgsExplicitly() = (1181, sprintf "Each argument of the primary constructor for a struct must be given a type, for example 'type S(x1:int, x2: int) = ...'. These arguments determine the fields of the struct." ) /// The value '%s' is unused - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1037) + /// (Originally from src/fsharp/FSComp.txt:1054) static member chkUnusedValue(a0 : System.String) = (1182, sprintf "The value '%s' is unused" a0) /// The recursive object reference '%s' is unused. The presence of a recursive object reference adds runtime initialization checks to members in this and derived types. Consider removing this recursive object reference. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1038) + /// (Originally from src/fsharp/FSComp.txt:1055) static member chkUnusedThisVariable(a0 : System.String) = (1183, sprintf "The recursive object reference '%s' is unused. The presence of a recursive object reference adds runtime initialization checks to members in this and derived types. Consider removing this recursive object reference." a0) /// A getter property may have at most one argument group - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1039) + /// (Originally from src/fsharp/FSComp.txt:1056) static member parsGetterAtMostOneArgument() = (1184, sprintf "A getter property may have at most one argument group" ) /// A setter property may have at most two argument groups - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1040) + /// (Originally from src/fsharp/FSComp.txt:1057) static member parsSetterAtMostTwoArguments() = (1185, sprintf "A setter property may have at most two argument groups" ) /// Invalid property getter or setter - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1041) + /// (Originally from src/fsharp/FSComp.txt:1058) static member parsInvalidProperty() = (1186, sprintf "Invalid property getter or setter" ) /// An indexer property must be given at least one argument - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1042) + /// (Originally from src/fsharp/FSComp.txt:1059) static member parsIndexerPropertyRequiresAtLeastOneArgument() = (1187, sprintf "An indexer property must be given at least one argument" ) /// This operation accesses a mutable top-level value defined in another assembly in an unsupported way. The value cannot be accessed through its address. Consider copying the expression to a mutable local, e.g. 'let mutable x = ...', and if necessary assigning the value back after the completion of the operation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1043) + /// (Originally from src/fsharp/FSComp.txt:1060) static member tastInvalidAddressOfMutableAcrossAssemblyBoundary() = (1188, sprintf "This operation accesses a mutable top-level value defined in another assembly in an unsupported way. The value cannot be accessed through its address. Consider copying the expression to a mutable local, e.g. 'let mutable x = ...', and if necessary assigning the value back after the completion of the operation" ) /// Remove spaces between the type name and type parameter, e.g. \"type C<'T>\", not type \"C <'T>\". Type parameters must be placed directly adjacent to the type name. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1044) + /// (Originally from src/fsharp/FSComp.txt:1061) static member parsNonAdjacentTypars() = (1189, sprintf "Remove spaces between the type name and type parameter, e.g. \"type C<'T>\", not type \"C <'T>\". Type parameters must be placed directly adjacent to the type name." ) /// Remove spaces between the type name and type parameter, e.g. \"C<'T>\", not \"C <'T>\". Type parameters must be placed directly adjacent to the type name. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1045) + /// (Originally from src/fsharp/FSComp.txt:1062) static member parsNonAdjacentTyargs() = (1190, sprintf "Remove spaces between the type name and type parameter, e.g. \"C<'T>\", not \"C <'T>\". Type parameters must be placed directly adjacent to the type name." ) /// The use of the type syntax 'int C' and 'C ' is not permitted here. Consider adjusting this type to be written in the form 'C' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1046) + /// (Originally from src/fsharp/FSComp.txt:1063) static member parsNonAtomicType() = (sprintf "The use of the type syntax 'int C' and 'C ' is not permitted here. Consider adjusting this type to be written in the form 'C'" ) /// The module/namespace '%s' from compilation unit '%s' did not contain the module/namespace '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1049) + /// (Originally from src/fsharp/FSComp.txt:1066) static member tastUndefinedItemRefModuleNamespace(a0 : System.String, a1 : System.String, a2 : System.String) = (1193, sprintf "The module/namespace '%s' from compilation unit '%s' did not contain the module/namespace '%s'" a0 a1 a2) /// The module/namespace '%s' from compilation unit '%s' did not contain the val '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1050) + /// (Originally from src/fsharp/FSComp.txt:1067) static member tastUndefinedItemRefVal(a0 : System.String, a1 : System.String, a2 : System.String) = (1194, sprintf "The module/namespace '%s' from compilation unit '%s' did not contain the val '%s'" a0 a1 a2) /// The module/namespace '%s' from compilation unit '%s' did not contain the namespace, module or type '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1051) + /// (Originally from src/fsharp/FSComp.txt:1068) static member tastUndefinedItemRefModuleNamespaceType(a0 : System.String, a1 : System.String, a2 : System.String) = (1195, sprintf "The module/namespace '%s' from compilation unit '%s' did not contain the namespace, module or type '%s'" a0 a1 a2) /// The 'UseNullAsTrueValue' attribute flag may only be used with union types that have one nullary case and at least one non-nullary case - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1052) + /// (Originally from src/fsharp/FSComp.txt:1069) static member tcInvalidUseNullAsTrueValue() = (1196, sprintf "The 'UseNullAsTrueValue' attribute flag may only be used with union types that have one nullary case and at least one non-nullary case" ) /// The parameter '%s' 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. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1053) + /// (Originally from src/fsharp/FSComp.txt:1070) static member tcParameterInferredByref(a0 : System.String) = (1197, sprintf "The parameter '%s' 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." a0) /// The generic member '%s' has been used at a non-uniform instantiation prior to this program point. Consider reordering the members so this member occurs first. Alternatively, specify the full type of the member explicitly, including argument types, return type and any additional generic parameters and constraints. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1054) + /// (Originally from src/fsharp/FSComp.txt:1071) static member tcNonUniformMemberUse(a0 : System.String) = (1198, sprintf "The generic member '%s' has been used at a non-uniform instantiation prior to this program point. Consider reordering the members so this member occurs first. Alternatively, specify the full type of the member explicitly, including argument types, return type and any additional generic parameters and constraints." a0) /// The attribute '%s' appears in both the implementation and the signature, but the attribute arguments differ. Only the attribute from the signature will be included in the compiled code. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1055) + /// (Originally from src/fsharp/FSComp.txt:1072) static member tcAttribArgsDiffer(a0 : System.String) = (1200, sprintf "The attribute '%s' appears in both the implementation and the signature, but the attribute arguments differ. Only the attribute from the signature will be included in the compiled code." a0) /// Cannot call an abstract base member: '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1056) + /// (Originally from src/fsharp/FSComp.txt:1073) static member tcCannotCallAbstractBaseMember(a0 : System.String) = (1201, sprintf "Cannot call an abstract base member: '%s'" a0) /// Could not resolve the ambiguity in the use of a generic construct with an 'unmanaged' constraint at or near this position - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1057) + /// (Originally from src/fsharp/FSComp.txt:1074) static member typrelCannotResolveAmbiguityInUnmanaged() = (1202, sprintf "Could not resolve the ambiguity in the use of a generic construct with an 'unmanaged' constraint at or near this position" ) /// This construct is for ML compatibility. %s. You can disable this warning by using '--mlcompatibility' or '--nowarn:62'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1060) + /// (Originally from src/fsharp/FSComp.txt:1077) static member mlCompatMessage(a0 : System.String) = (sprintf "This construct is for ML compatibility. %s. You can disable this warning by using '--mlcompatibility' or '--nowarn:62'." a0) /// The type '%s' has been marked as having an Explicit layout, but the field '%s' has not been marked with the 'FieldOffset' attribute - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1062) + /// (Originally from src/fsharp/FSComp.txt:1079) static member ilFieldDoesNotHaveValidOffsetForStructureLayout(a0 : System.String, a1 : System.String) = (1206, sprintf "The type '%s' has been marked as having an Explicit layout, but the field '%s' has not been marked with the 'FieldOffset' attribute" a0 a1) /// Interfaces inherited by other interfaces should be declared using 'inherit ...' instead of 'interface ...' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1063) + /// (Originally from src/fsharp/FSComp.txt:1080) static member tcInterfacesShouldUseInheritNotInterface() = (1207, sprintf "Interfaces inherited by other interfaces should be declared using 'inherit ...' instead of 'interface ...'" ) /// Invalid prefix operator - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1064) + /// (Originally from src/fsharp/FSComp.txt:1081) static member parsInvalidPrefixOperator() = (1208, sprintf "Invalid prefix operator" ) /// Invalid operator definition. Prefix operator definitions must use a valid prefix operator name. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1065) + /// (Originally from src/fsharp/FSComp.txt:1082) static member parsInvalidPrefixOperatorDefinition() = (1208, sprintf "Invalid operator definition. Prefix operator definitions must use a valid prefix operator name." ) /// The file extensions '.ml' and '.mli' are for ML compatibility - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1066) + /// (Originally from src/fsharp/FSComp.txt:1083) static member buildCompilingExtensionIsForML() = (sprintf "The file extensions '.ml' and '.mli' are for ML compatibility" ) /// Consider using a file with extension '.ml' or '.mli' instead - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1067) + /// (Originally from src/fsharp/FSComp.txt:1084) static member lexIndentOffForML() = (sprintf "Consider using a file with extension '.ml' or '.mli' instead" ) /// Active pattern '%s' is not a function - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1068) + /// (Originally from src/fsharp/FSComp.txt:1085) static member activePatternIdentIsNotFunctionTyped(a0 : System.String) = (1209, sprintf "Active pattern '%s' is not a function" a0) /// Active pattern '%s' has a result type containing type variables that are not determined by the input. The common cause is a when a result case is not mentioned, e.g. 'let (|A|B|) (x:int) = A x'. This can be fixed with a type constraint, e.g. 'let (|A|B|) (x:int) : Choice = A x' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1069) + /// (Originally from src/fsharp/FSComp.txt:1086) static member activePatternChoiceHasFreeTypars(a0 : System.String) = (1210, sprintf "Active pattern '%s' has a result type containing type variables that are not determined by the input. The common cause is a when a result case is not mentioned, e.g. 'let (|A|B|) (x:int) = A x'. This can be fixed with a type constraint, e.g. 'let (|A|B|) (x:int) : Choice = A x'" a0) /// The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1070) + /// (Originally from src/fsharp/FSComp.txt:1087) static member ilFieldHasOffsetForSequentialLayout() = (1211, sprintf "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)" ) /// Optional arguments must come at the end of the argument list, after any non-optional arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1071) + /// (Originally from src/fsharp/FSComp.txt:1088) static member tcOptionalArgsMustComeAfterNonOptionalArgs() = (1212, sprintf "Optional arguments must come at the end of the argument list, after any non-optional arguments" ) /// Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1072) + /// (Originally from src/fsharp/FSComp.txt:1089) static member tcConditionalAttributeUsage() = (1213, sprintf "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes" ) /// Extension members cannot provide operator overloads. Consider defining the operator as part of the type definition instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1074) + /// (Originally from src/fsharp/FSComp.txt:1091) static member tcMemberOperatorDefinitionInExtrinsic() = (1215, sprintf "Extension members cannot provide operator overloads. Consider defining the operator as part of the type definition instead." ) /// The name of the MDB file must be .mdb. The --pdb option will be ignored. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1075) + /// (Originally from src/fsharp/FSComp.txt:1092) static member ilwriteMDBFileNameCannotBeChangedWarning() = (1216, sprintf "The name of the MDB file must be .mdb. The --pdb option will be ignored." ) /// MDB generation failed. Could not find compatible member %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1076) + /// (Originally from src/fsharp/FSComp.txt:1093) static member ilwriteMDBMemberMissing(a0 : System.String) = (1217, sprintf "MDB generation failed. Could not find compatible member %s" a0) /// Cannot generate MDB debug information. Failed to load the 'MonoSymbolWriter' type from the 'Mono.CompilerServices.SymbolWriter.dll' assembly. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1077) + /// (Originally from src/fsharp/FSComp.txt:1094) static member ilwriteErrorCreatingMdb() = (1218, sprintf "Cannot generate MDB debug information. Failed to load the 'MonoSymbolWriter' type from the 'Mono.CompilerServices.SymbolWriter.dll' assembly." ) /// The union case named '%s' conflicts with the generated type '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1078) + /// (Originally from src/fsharp/FSComp.txt:1095) static member tcUnionCaseNameConflictsWithGeneratedType(a0 : System.String, a1 : System.String) = (1219, sprintf "The union case named '%s' conflicts with the generated type '%s'" a0 a1) /// ReflectedDefinitionAttribute may not be applied to an instance member on a struct type, because the instance member takes an implicit 'this' byref parameter - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1079) + /// (Originally from src/fsharp/FSComp.txt:1096) static member chkNoReflectedDefinitionOnStructMember() = (1220, sprintf "ReflectedDefinitionAttribute may not be applied to an instance member on a struct type, because the instance member takes an implicit 'this' byref parameter" ) /// DLLImport bindings must be static members in a class or function definitions in a module - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1080) + /// (Originally from src/fsharp/FSComp.txt:1097) static member tcDllImportNotAllowed() = (1221, sprintf "DLLImport bindings must be static members in a class or function definitions in a module" ) - /// When mscorlib.dll or FSharp.Core.dll is explicitly referenced the %s option must also be passed - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1081) - static member buildExplicitCoreLibRequiresNoFramework(a0 : System.String) = (1222, sprintf "When mscorlib.dll or FSharp.Core.dll is explicitly referenced the %s option must also be passed" a0) /// FSharp.Core.sigdata not found alongside FSharp.Core. File expected in %s. Consider upgrading to a more recent version of FSharp.Core, where this file is no longer be required. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1082) + /// (Originally from src/fsharp/FSComp.txt:1098) static member buildExpectedSigdataFile(a0 : System.String) = (1223, sprintf "FSharp.Core.sigdata not found alongside FSharp.Core. File expected in %s. Consider upgrading to a more recent version of FSharp.Core, where this file is no longer be required." a0) /// File '%s' not found alongside FSharp.Core. File expected in %s. Consider upgrading to a more recent version of FSharp.Core, where this file is no longer be required. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1083) + /// (Originally from src/fsharp/FSComp.txt:1099) static member buildExpectedFileAlongSideFSharpCore(a0 : System.String, a1 : System.String) = (1225, sprintf "File '%s' not found alongside FSharp.Core. File expected in %s. Consider upgrading to a more recent version of FSharp.Core, where this file is no longer be required." a0 a1) /// Filename '%s' contains invalid character '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1084) + /// (Originally from src/fsharp/FSComp.txt:1100) static member buildUnexpectedFileNameCharacter(a0 : System.String, a1 : System.String) = (1227, sprintf "Filename '%s' contains invalid character '%s'" a0 a1) /// 'use!' bindings must be of the form 'use! = ' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1085) + /// (Originally from src/fsharp/FSComp.txt:1101) static member tcInvalidUseBangBinding() = (1228, sprintf "'use!' bindings must be of the form 'use! = '" ) /// Inner generic functions are not permitted in quoted expressions. Consider adding some type constraints until this function is no longer generic. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1086) + /// (Originally from src/fsharp/FSComp.txt:1102) static member crefNoInnerGenericsInQuotations() = (1230, sprintf "Inner generic functions are not permitted in quoted expressions. Consider adding some type constraints until this function is no longer generic." ) /// The type '%s' is not a valid enumerator type , i.e. does not have a 'MoveNext()' method returning a bool, and a 'Current' property - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1087) + /// (Originally from src/fsharp/FSComp.txt:1103) static member tcEnumTypeCannotBeEnumerated(a0 : System.String) = (1231, sprintf "The type '%s' is not a valid enumerator type , i.e. does not have a 'MoveNext()' method returning a bool, and a 'Current' property" a0) /// End of file in triple-quote string begun at or before here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1088) + /// (Originally from src/fsharp/FSComp.txt:1104) static member parsEofInTripleQuoteString() = (1232, sprintf "End of file in triple-quote string begun at or before here" ) /// End of file in triple-quote string embedded in comment begun at or before here - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1089) + /// (Originally from src/fsharp/FSComp.txt:1105) static member parsEofInTripleQuoteStringInComment() = (1233, sprintf "End of file in triple-quote string embedded in comment begun at or before here" ) /// This type test or downcast will ignore the unit-of-measure '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1090) + /// (Originally from src/fsharp/FSComp.txt:1106) static member tcTypeTestLosesMeasures(a0 : System.String) = (1240, sprintf "This type test or downcast will ignore the unit-of-measure '%s'" a0) /// Expected type argument or static argument - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1091) + /// (Originally from src/fsharp/FSComp.txt:1107) static member parsMissingTypeArgs() = (1241, sprintf "Expected type argument or static argument" ) /// Unmatched '<'. Expected closing '>' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1092) + /// (Originally from src/fsharp/FSComp.txt:1108) static member parsMissingGreaterThan() = (1242, sprintf "Unmatched '<'. Expected closing '>'" ) /// Unexpected quotation operator '<@' in type definition. If you intend to pass a verbatim string as a static argument to a type provider, put a space between the '<' and '@' characters. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1093) + /// (Originally from src/fsharp/FSComp.txt:1109) static member parsUnexpectedQuotationOperatorInTypeAliasDidYouMeanVerbatimString() = (1243, sprintf "Unexpected quotation operator '<@' in type definition. If you intend to pass a verbatim string as a static argument to a type provider, put a space between the '<' and '@' characters." ) /// Attempted to parse this as an operator name, but failed - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1094) + /// (Originally from src/fsharp/FSComp.txt:1110) static member parsErrorParsingAsOperatorName() = (1244, sprintf "Attempted to parse this as an operator name, but failed" ) /// \U%s is not a valid Unicode character escape sequence - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1095) + /// (Originally from src/fsharp/FSComp.txt:1111) static member lexInvalidUnicodeLiteral(a0 : System.String) = (1245, sprintf "\U%s is not a valid Unicode character escape sequence" a0) /// '%s' must be applied to an argument of type '%s', but has been applied to an argument of type '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1096) + /// (Originally from src/fsharp/FSComp.txt:1112) static member tcCallerInfoWrongType(a0 : System.String, a1 : System.String, a2 : System.String) = (1246, sprintf "'%s' must be applied to an argument of type '%s', but has been applied to an argument of type '%s'" a0 a1 a2) /// '%s' can only be applied to optional arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1097) + /// (Originally from src/fsharp/FSComp.txt:1113) static member tcCallerInfoNotOptional(a0 : System.String) = (1247, sprintf "'%s' can only be applied to optional arguments" a0) /// The specified .NET Framework version '%s' is not supported. Please specify a value from the enumeration Microsoft.Build.Utilities.TargetDotNetFrameworkVersion. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1099) + /// (Originally from src/fsharp/FSComp.txt:1115) static member toolLocationHelperUnsupportedFrameworkVersion(a0 : System.String) = (1300, sprintf "The specified .NET Framework version '%s' is not supported. Please specify a value from the enumeration Microsoft.Build.Utilities.TargetDotNetFrameworkVersion." a0) /// Invalid Magic value in CLR Header - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1103) + /// (Originally from src/fsharp/FSComp.txt:1119) static member ilSignInvalidMagicValue() = (1301, sprintf "Invalid Magic value in CLR Header" ) /// Bad image format - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1104) + /// (Originally from src/fsharp/FSComp.txt:1120) static member ilSignBadImageFormat() = (1302, sprintf "Bad image format" ) /// Private key expected - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1105) + /// (Originally from src/fsharp/FSComp.txt:1121) static member ilSignPrivateKeyExpected() = (1303, sprintf "Private key expected" ) /// RSA key expected - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1106) + /// (Originally from src/fsharp/FSComp.txt:1122) static member ilSignRsaKeyExpected() = (1304, sprintf "RSA key expected" ) /// Invalid bit Length - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1107) + /// (Originally from src/fsharp/FSComp.txt:1123) static member ilSignInvalidBitLen() = (1305, sprintf "Invalid bit Length" ) /// Invalid RSAParameters structure - '{0}' expected - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1108) + /// (Originally from src/fsharp/FSComp.txt:1124) static member ilSignInvalidRSAParams() = (1306, sprintf "Invalid RSAParameters structure - '{0}' expected" ) /// Invalid algId - 'Exponent' expected - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1109) + /// (Originally from src/fsharp/FSComp.txt:1125) static member ilSignInvalidAlgId() = (1307, sprintf "Invalid algId - 'Exponent' expected" ) /// Invalid signature size - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1110) + /// (Originally from src/fsharp/FSComp.txt:1126) static member ilSignInvalidSignatureSize() = (1308, sprintf "Invalid signature size" ) /// No signature directory - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1111) + /// (Originally from src/fsharp/FSComp.txt:1127) static member ilSignNoSignatureDirectory() = (1309, sprintf "No signature directory" ) /// Invalid Public Key blob - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1112) + /// (Originally from src/fsharp/FSComp.txt:1128) static member ilSignInvalidPKBlob() = (1310, sprintf "Invalid Public Key blob" ) /// Exiting - too many errors - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1114) + /// (Originally from src/fsharp/FSComp.txt:1130) static member fscTooManyErrors() = (sprintf "Exiting - too many errors" ) /// The documentation file has no .xml suffix - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1115) + /// (Originally from src/fsharp/FSComp.txt:1131) static member docfileNoXmlSuffix() = (2001, sprintf "The documentation file has no .xml suffix" ) /// No implementation files specified - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1116) + /// (Originally from src/fsharp/FSComp.txt:1132) static member fscNoImplementationFiles() = (2002, sprintf "No implementation files specified" ) /// The attribute %s specified version '%s', but this value is invalid and has been ignored - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1117) + /// (Originally from src/fsharp/FSComp.txt:1133) static member fscBadAssemblyVersion(a0 : System.String, a1 : System.String) = (2003, sprintf "The attribute %s specified version '%s', but this value is invalid and has been ignored" a0 a1) /// Conflicting options specified: 'win32manifest' and 'win32res'. Only one of these can be used. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1118) + /// (Originally from src/fsharp/FSComp.txt:1134) static member fscTwoResourceManifests() = (2004, sprintf "Conflicting options specified: 'win32manifest' and 'win32res'. Only one of these can be used." ) /// The code in assembly '%s' makes uses of quotation literals. Static linking may not include components that make use of quotation literals unless all assemblies are compiled with at least F# 4.0. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1119) + /// (Originally from src/fsharp/FSComp.txt:1135) static member fscQuotationLiteralsStaticLinking(a0 : System.String) = (2005, sprintf "The code in assembly '%s' makes uses of quotation literals. Static linking may not include components that make use of quotation literals unless all assemblies are compiled with at least F# 4.0." a0) /// Code in this assembly makes uses of quotation literals. Static linking may not include components that make use of quotation literals unless all assemblies are compiled with at least F# 4.0. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1120) + /// (Originally from src/fsharp/FSComp.txt:1136) static member fscQuotationLiteralsStaticLinking0() = (2006, sprintf "Code in this assembly makes uses of quotation literals. Static linking may not include components that make use of quotation literals unless all assemblies are compiled with at least F# 4.0." ) /// Static linking may not include a .EXE - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1121) + /// (Originally from src/fsharp/FSComp.txt:1137) static member fscStaticLinkingNoEXE() = (2007, sprintf "Static linking may not include a .EXE" ) /// Static linking may not include a mixed managed/unmanaged DLL - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1122) + /// (Originally from src/fsharp/FSComp.txt:1138) static member fscStaticLinkingNoMixedDLL() = (2008, sprintf "Static linking may not include a mixed managed/unmanaged DLL" ) /// Ignoring mixed managed/unmanaged assembly '%s' during static linking - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1123) + /// (Originally from src/fsharp/FSComp.txt:1139) static member fscIgnoringMixedWhenLinking(a0 : System.String) = (2009, sprintf "Ignoring mixed managed/unmanaged assembly '%s' during static linking" a0) /// Assembly '%s' was referenced transitively and the assembly could not be resolved automatically. Static linking will assume this DLL has no dependencies on the F# library or other statically linked DLLs. Consider adding an explicit reference to this DLL. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1124) + /// (Originally from src/fsharp/FSComp.txt:1140) static member fscAssumeStaticLinkContainsNoDependencies(a0 : System.String) = (2011, sprintf "Assembly '%s' was referenced transitively and the assembly could not be resolved automatically. Static linking will assume this DLL has no dependencies on the F# library or other statically linked DLLs. Consider adding an explicit reference to this DLL." a0) /// Assembly '%s' not found in dependency set of target binary. Statically linked roots should be specified using an assembly name, without a DLL or EXE extension. If this assembly was referenced explicitly then it is possible the assembly was not actually required by the generated binary, in which case it should not be statically linked. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1125) + /// (Originally from src/fsharp/FSComp.txt:1141) static member fscAssemblyNotFoundInDependencySet(a0 : System.String) = (2012, sprintf "Assembly '%s' not found in dependency set of target binary. Statically linked roots should be specified using an assembly name, without a DLL or EXE extension. If this assembly was referenced explicitly then it is possible the assembly was not actually required by the generated binary, in which case it should not be statically linked." a0) /// The key file '%s' could not be opened - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1126) + /// (Originally from src/fsharp/FSComp.txt:1142) static member fscKeyFileCouldNotBeOpened(a0 : System.String) = (2013, sprintf "The key file '%s' could not be opened" a0) /// A problem occurred writing the binary '%s': %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1127) + /// (Originally from src/fsharp/FSComp.txt:1143) static member fscProblemWritingBinary(a0 : System.String, a1 : System.String) = (2014, sprintf "A problem occurred writing the binary '%s': %s" a0 a1) /// The 'AssemblyVersionAttribute' has been ignored because a version was given using a command line option - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1128) + /// (Originally from src/fsharp/FSComp.txt:1144) static member fscAssemblyVersionAttributeIgnored() = (2015, sprintf "The 'AssemblyVersionAttribute' has been ignored because a version was given using a command line option" ) /// Error emitting 'System.Reflection.AssemblyCultureAttribute' attribute -- 'Executables cannot be satellite assemblies, Culture should always be empty' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1129) + /// (Originally from src/fsharp/FSComp.txt:1145) static member fscAssemblyCultureAttributeError() = (2016, sprintf "Error emitting 'System.Reflection.AssemblyCultureAttribute' attribute -- 'Executables cannot be satellite assemblies, Culture should always be empty'" ) /// Option '--delaysign' overrides attribute 'System.Reflection.AssemblyDelaySignAttribute' given in a source file or added module - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1130) + /// (Originally from src/fsharp/FSComp.txt:1146) static member fscDelaySignWarning() = (2017, sprintf "Option '--delaysign' overrides attribute 'System.Reflection.AssemblyDelaySignAttribute' given in a source file or added module" ) /// Option '--keyfile' overrides attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file or added module - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1131) + /// (Originally from src/fsharp/FSComp.txt:1147) static member fscKeyFileWarning() = (2018, sprintf "Option '--keyfile' overrides attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file or added module" ) /// Option '--keycontainer' overrides attribute 'System.Reflection.AssemblyNameAttribute' given in a source file or added module - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1132) + /// (Originally from src/fsharp/FSComp.txt:1148) static member fscKeyNameWarning() = (2019, sprintf "Option '--keycontainer' overrides attribute 'System.Reflection.AssemblyNameAttribute' given in a source file or added module" ) /// The assembly '%s' is listed on the command line. Assemblies should be referenced using a command line flag such as '-r'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1133) + /// (Originally from src/fsharp/FSComp.txt:1149) static member fscReferenceOnCommandLine(a0 : System.String) = (2020, sprintf "The assembly '%s' is listed on the command line. Assemblies should be referenced using a command line flag such as '-r'." a0) /// The resident compilation service was not used because a problem occured in communicating with the server. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1134) + /// (Originally from src/fsharp/FSComp.txt:1150) static member fscRemotingError() = (2021, sprintf "The resident compilation service was not used because a problem occured in communicating with the server." ) /// Problem with filename '%s': Illegal characters in path. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1135) + /// (Originally from src/fsharp/FSComp.txt:1151) static member pathIsInvalid(a0 : System.String) = (2022, sprintf "Problem with filename '%s': Illegal characters in path." a0) /// Passing a .resx file (%s) as a source file to the compiler is deprecated. Use resgen.exe to transform the .resx file into a .resources file to pass as a --resource option. If you are using MSBuild, this can be done via an item in the .fsproj project file. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1136) + /// (Originally from src/fsharp/FSComp.txt:1152) static member fscResxSourceFileDeprecated(a0 : System.String) = (2023, sprintf "Passing a .resx file (%s) as a source file to the compiler is deprecated. Use resgen.exe to transform the .resx file into a .resources file to pass as a --resource option. If you are using MSBuild, this can be done via an item in the .fsproj project file." a0) /// Static linking may not be used on an assembly referencing mscorlib (e.g. a .NET Framework assembly) when generating an assembly that references System.Runtime (e.g. a .NET Core or Portable assembly). - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1137) + /// (Originally from src/fsharp/FSComp.txt:1153) static member fscStaticLinkingNoProfileMismatches() = (2024, sprintf "Static linking may not be used on an assembly referencing mscorlib (e.g. a .NET Framework assembly) when generating an assembly that references System.Runtime (e.g. a .NET Core or Portable assembly)." ) /// An %s specified version '%s', but this value is a wildcard, and you have requested a deterministic build, these are in conflict. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1138) + /// (Originally from src/fsharp/FSComp.txt:1154) static member fscAssemblyWildcardAndDeterminism(a0 : System.String, a1 : System.String) = (2025, sprintf "An %s specified version '%s', but this value is a wildcard, and you have requested a deterministic build, these are in conflict." a0 a1) - /// Determinstic builds only support portable PDBs (--debug:portable or --debug:embedded) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1139) - static member fscDeterministicDebugRequiresPortablePdb() = (2026, sprintf "Determinstic builds only support portable PDBs (--debug:portable or --debug:embedded)" ) + /// Deterministic builds only support portable PDBs (--debug:portable or --debug:embedded) + /// (Originally from src/fsharp/FSComp.txt:1155) + static member fscDeterministicDebugRequiresPortablePdb() = (2026, sprintf "Deterministic builds only support portable PDBs (--debug:portable or --debug:embedded)" ) + /// --pathmap can only be used with portable PDBs (--debug:portable or --debug:embedded) + /// (Originally from src/fsharp/FSComp.txt:1156) + static member fscPathMapDebugRequiresPortablePdb() = (2027, sprintf "--pathmap can only be used with portable PDBs (--debug:portable or --debug:embedded)" ) + /// Invalid path map. Mappings must be comma separated and of the format 'path=sourcePath' + /// (Originally from src/fsharp/FSComp.txt:1157) + static member optsInvalidPathMapFormat() = (2028, sprintf "Invalid path map. Mappings must be comma separated and of the format 'path=sourcePath'" ) /// Character '%s' is not allowed in provided namespace name '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1140) + /// (Originally from src/fsharp/FSComp.txt:1158) static member etIllegalCharactersInNamespaceName(a0 : System.String, a1 : System.String) = (3000, sprintf "Character '%s' is not allowed in provided namespace name '%s'" a0 a1) /// The provided type '%s' returned a member with a null or empty member name - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1141) + /// (Originally from src/fsharp/FSComp.txt:1159) static member etNullOrEmptyMemberName(a0 : System.String) = (3001, sprintf "The provided type '%s' returned a member with a null or empty member name" a0) /// The provided type '%s' returned a null member - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1142) + /// (Originally from src/fsharp/FSComp.txt:1160) static member etNullMember(a0 : System.String) = (3002, sprintf "The provided type '%s' returned a null member" a0) /// The provided type '%s' member info '%s' has null declaring type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1143) + /// (Originally from src/fsharp/FSComp.txt:1161) static member etNullMemberDeclaringType(a0 : System.String, a1 : System.String) = (3003, sprintf "The provided type '%s' member info '%s' has null declaring type" a0 a1) /// The provided type '%s' has member '%s' which has declaring type '%s'. Expected declaring type to be the same as provided type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1144) + /// (Originally from src/fsharp/FSComp.txt:1162) static member etNullMemberDeclaringTypeDifferentFromProvidedType(a0 : System.String, a1 : System.String, a2 : System.String) = (3004, sprintf "The provided type '%s' has member '%s' which has declaring type '%s'. Expected declaring type to be the same as provided type." a0 a1 a2) /// Referenced assembly '%s' has assembly level attribute '%s' but no public type provider classes were found - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1145) + /// (Originally from src/fsharp/FSComp.txt:1163) static member etHostingAssemblyFoundWithoutHosts(a0 : System.String, a1 : System.String) = (3005, sprintf "Referenced assembly '%s' has assembly level attribute '%s' but no public type provider classes were found" a0 a1) /// Type '%s' from type provider '%s' has an empty namespace. Use 'null' for the global namespace. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1146) + /// (Originally from src/fsharp/FSComp.txt:1164) static member etEmptyNamespaceOfTypeNotAllowed(a0 : System.String, a1 : System.String) = (3006, sprintf "Type '%s' from type provider '%s' has an empty namespace. Use 'null' for the global namespace." a0 a1) /// Empty namespace found from the type provider '%s'. Use 'null' for the global namespace. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1147) + /// (Originally from src/fsharp/FSComp.txt:1165) static member etEmptyNamespaceNotAllowed(a0 : System.String) = (3007, sprintf "Empty namespace found from the type provider '%s'. Use 'null' for the global namespace." a0) /// Provided type '%s' has 'IsGenericType' as true, but generic types are not supported. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1148) + /// (Originally from src/fsharp/FSComp.txt:1166) static member etMustNotBeGeneric(a0 : System.String) = (3011, sprintf "Provided type '%s' has 'IsGenericType' as true, but generic types are not supported." a0) /// Provided type '%s' has 'IsArray' as true, but array types are not supported. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1149) + /// (Originally from src/fsharp/FSComp.txt:1167) static member etMustNotBeAnArray(a0 : System.String) = (3013, sprintf "Provided type '%s' has 'IsArray' as true, but array types are not supported." a0) /// Invalid member '%s' on provided type '%s'. Provided type members must be public, and not be generic, virtual, or abstract. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1150) + /// (Originally from src/fsharp/FSComp.txt:1168) static member etMethodHasRequirements(a0 : System.String, a1 : System.String) = (3014, sprintf "Invalid member '%s' on provided type '%s'. Provided type members must be public, and not be generic, virtual, or abstract." a0 a1) /// Invalid member '%s' on provided type '%s'. Only properties, methods and constructors are allowed - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1151) + /// (Originally from src/fsharp/FSComp.txt:1169) static member etUnsupportedMemberKind(a0 : System.String, a1 : System.String) = (3015, sprintf "Invalid member '%s' on provided type '%s'. Only properties, methods and constructors are allowed" a0 a1) /// Property '%s' on provided type '%s' has CanRead=true but there was no value from GetGetMethod() - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1152) + /// (Originally from src/fsharp/FSComp.txt:1170) static member etPropertyCanReadButHasNoGetter(a0 : System.String, a1 : System.String) = (3016, sprintf "Property '%s' on provided type '%s' has CanRead=true but there was no value from GetGetMethod()" a0 a1) /// Property '%s' on provided type '%s' has CanRead=false but GetGetMethod() returned a method - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1153) + /// (Originally from src/fsharp/FSComp.txt:1171) static member etPropertyHasGetterButNoCanRead(a0 : System.String, a1 : System.String) = (3017, sprintf "Property '%s' on provided type '%s' has CanRead=false but GetGetMethod() returned a method" a0 a1) /// Property '%s' on provided type '%s' has CanWrite=true but there was no value from GetSetMethod() - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1154) + /// (Originally from src/fsharp/FSComp.txt:1172) static member etPropertyCanWriteButHasNoSetter(a0 : System.String, a1 : System.String) = (3018, sprintf "Property '%s' on provided type '%s' has CanWrite=true but there was no value from GetSetMethod()" a0 a1) /// Property '%s' on provided type '%s' has CanWrite=false but GetSetMethod() returned a method - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1155) + /// (Originally from src/fsharp/FSComp.txt:1173) static member etPropertyHasSetterButNoCanWrite(a0 : System.String, a1 : System.String) = (3019, sprintf "Property '%s' on provided type '%s' has CanWrite=false but GetSetMethod() returned a method" a0 a1) /// One or more errors seen during provided type setup - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1156) + /// (Originally from src/fsharp/FSComp.txt:1174) static member etOneOrMoreErrorsSeenDuringExtensionTypeSetting() = (3020, sprintf "One or more errors seen during provided type setup" ) /// Unexpected exception from provided type '%s' member '%s': %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1157) + /// (Originally from src/fsharp/FSComp.txt:1175) static member etUnexpectedExceptionFromProvidedTypeMember(a0 : System.String, a1 : System.String, a2 : System.String) = (3021, sprintf "Unexpected exception from provided type '%s' member '%s': %s" a0 a1 a2) /// Unsupported constant type '%s'. Quotations provided by type providers can only contain simple constants. The implementation of the type provider may need to be adjusted by moving a value declared outside a provided quotation literal to be a 'let' binding inside the quotation literal. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1158) + /// (Originally from src/fsharp/FSComp.txt:1176) static member etUnsupportedConstantType(a0 : System.String) = (3022, sprintf "Unsupported constant type '%s'. Quotations provided by type providers can only contain simple constants. The implementation of the type provider may need to be adjusted by moving a value declared outside a provided quotation literal to be a 'let' binding inside the quotation literal." a0) /// Unsupported expression '%s' from type provider. If you are the author of this type provider, consider adjusting it to provide a different provided expression. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1159) + /// (Originally from src/fsharp/FSComp.txt:1177) static member etUnsupportedProvidedExpression(a0 : System.String) = (3025, sprintf "Unsupported expression '%s' from type provider. If you are the author of this type provider, consider adjusting it to provide a different provided expression." a0) /// Expected provided type named '%s' but provided type has 'Name' with value '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1160) + /// (Originally from src/fsharp/FSComp.txt:1178) static member etProvidedTypeHasUnexpectedName(a0 : System.String, a1 : System.String) = (3028, sprintf "Expected provided type named '%s' but provided type has 'Name' with value '%s'" a0 a1) /// Event '%s' on provided type '%s' has no value from GetAddMethod() - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1161) + /// (Originally from src/fsharp/FSComp.txt:1179) static member etEventNoAdd(a0 : System.String, a1 : System.String) = (3029, sprintf "Event '%s' on provided type '%s' has no value from GetAddMethod()" a0 a1) /// Event '%s' on provided type '%s' has no value from GetRemoveMethod() - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1162) + /// (Originally from src/fsharp/FSComp.txt:1180) static member etEventNoRemove(a0 : System.String, a1 : System.String) = (3030, sprintf "Event '%s' on provided type '%s' has no value from GetRemoveMethod()" a0 a1) /// Assembly attribute '%s' refers to a designer assembly '%s' which cannot be loaded or doesn't exist. %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1163) + /// (Originally from src/fsharp/FSComp.txt:1181) static member etProviderHasWrongDesignerAssembly(a0 : System.String, a1 : System.String, a2 : System.String) = (3031, sprintf "Assembly attribute '%s' refers to a designer assembly '%s' which cannot be loaded or doesn't exist. %s" a0 a1 a2) /// The type provider does not have a valid constructor. A constructor taking either no arguments or one argument of type 'TypeProviderConfig' was expected. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1164) + /// (Originally from src/fsharp/FSComp.txt:1182) static member etProviderDoesNotHaveValidConstructor() = (3032, sprintf "The type provider does not have a valid constructor. A constructor taking either no arguments or one argument of type 'TypeProviderConfig' was expected." ) /// The type provider '%s' reported an error: %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1165) + /// (Originally from src/fsharp/FSComp.txt:1183) static member etProviderError(a0 : System.String, a1 : System.String) = (3033, sprintf "The type provider '%s' reported an error: %s" a0 a1) /// The type provider '%s' used an invalid parameter in the ParameterExpression: %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1166) + /// (Originally from src/fsharp/FSComp.txt:1184) static member etIncorrectParameterExpression(a0 : System.String, a1 : System.String) = (3034, sprintf "The type provider '%s' used an invalid parameter in the ParameterExpression: %s" a0 a1) /// The type provider '%s' provided a method with a name '%s' and metadata token '%d', which is not reported among its methods of its declaring type '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1167) + /// (Originally from src/fsharp/FSComp.txt:1185) static member etIncorrectProvidedMethod(a0 : System.String, a1 : System.String, a2 : System.Int32, a3 : System.String) = (3035, sprintf "The type provider '%s' provided a method with a name '%s' and metadata token '%d', which is not reported among its methods of its declaring type '%s'" a0 a1 a2 a3) /// The type provider '%s' provided a constructor which is not reported among the constructors of its declaring type '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1168) + /// (Originally from src/fsharp/FSComp.txt:1186) static member etIncorrectProvidedConstructor(a0 : System.String, a1 : System.String) = (3036, sprintf "The type provider '%s' provided a constructor which is not reported among the constructors of its declaring type '%s'" a0 a1) /// A direct reference to the generated type '%s' is not permitted. Instead, use a type definition, e.g. 'type TypeAlias = '. This indicates that a type provider adds generated types to your assembly. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1169) + /// (Originally from src/fsharp/FSComp.txt:1187) static member etDirectReferenceToGeneratedTypeNotAllowed(a0 : System.String) = (3039, sprintf "A direct reference to the generated type '%s' is not permitted. Instead, use a type definition, e.g. 'type TypeAlias = '. This indicates that a type provider adds generated types to your assembly." a0) /// Expected provided type with path '%s' but provided type has path '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1170) + /// (Originally from src/fsharp/FSComp.txt:1188) static member etProvidedTypeHasUnexpectedPath(a0 : System.String, a1 : System.String) = (3041, sprintf "Expected provided type with path '%s' but provided type has path '%s'" a0 a1) /// Unexpected 'null' return value from provided type '%s' member '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1171) + /// (Originally from src/fsharp/FSComp.txt:1189) static member etUnexpectedNullFromProvidedTypeMember(a0 : System.String, a1 : System.String) = (3042, sprintf "Unexpected 'null' return value from provided type '%s' member '%s'" a0 a1) /// Unexpected exception from member '%s' of provided type '%s' member '%s': %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1172) + /// (Originally from src/fsharp/FSComp.txt:1190) static member etUnexpectedExceptionFromProvidedMemberMember(a0 : System.String, a1 : System.String, a2 : System.String, a3 : System.String) = (3043, sprintf "Unexpected exception from member '%s' of provided type '%s' member '%s': %s" a0 a1 a2 a3) /// Nested provided types do not take static arguments or generic parameters - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1173) + /// (Originally from src/fsharp/FSComp.txt:1191) static member etNestedProvidedTypesDoNotTakeStaticArgumentsOrGenericParameters() = (3044, sprintf "Nested provided types do not take static arguments or generic parameters" ) /// Invalid static argument to provided type. Expected an argument of kind '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1174) + /// (Originally from src/fsharp/FSComp.txt:1192) static member etInvalidStaticArgument(a0 : System.String) = (3045, sprintf "Invalid static argument to provided type. Expected an argument of kind '%s'." a0) /// An error occured applying the static arguments to a provided type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1175) + /// (Originally from src/fsharp/FSComp.txt:1193) static member etErrorApplyingStaticArgumentsToType() = (3046, sprintf "An error occured applying the static arguments to a provided type" ) /// Unknown static argument kind '%s' when resolving a reference to a provided type or method '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1176) + /// (Originally from src/fsharp/FSComp.txt:1194) static member etUnknownStaticArgumentKind(a0 : System.String, a1 : System.String) = (3047, sprintf "Unknown static argument kind '%s' when resolving a reference to a provided type or method '%s'" a0 a1) /// invalid namespace for provided type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1177) + /// (Originally from src/fsharp/FSComp.txt:1195) static member invalidNamespaceForProvidedType() = (sprintf "invalid namespace for provided type" ) /// invalid full name for provided type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1178) + /// (Originally from src/fsharp/FSComp.txt:1196) static member invalidFullNameForProvidedType() = (sprintf "invalid full name for provided type" ) /// The type provider returned 'null', which is not a valid return value from '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1180) + /// (Originally from src/fsharp/FSComp.txt:1198) static member etProviderReturnedNull(a0 : System.String) = (3051, sprintf "The type provider returned 'null', which is not a valid return value from '%s'" a0) /// The type provider constructor has thrown an exception: %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1181) + /// (Originally from src/fsharp/FSComp.txt:1199) static member etTypeProviderConstructorException(a0 : System.String) = (3053, sprintf "The type provider constructor has thrown an exception: %s" a0) /// Type provider '%s' returned null from GetInvokerExpression. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1182) + /// (Originally from src/fsharp/FSComp.txt:1200) static member etNullProvidedExpression(a0 : System.String) = (3056, sprintf "Type provider '%s' returned null from GetInvokerExpression." a0) /// The type provider '%s' returned an invalid type from 'ApplyStaticArguments'. A type with name '%s' was expected, but a type with name '%s' was returned. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1183) + /// (Originally from src/fsharp/FSComp.txt:1201) static member etProvidedAppliedTypeHadWrongName(a0 : System.String, a1 : System.String, a2 : System.String) = (3057, sprintf "The type provider '%s' returned an invalid type from 'ApplyStaticArguments'. A type with name '%s' was expected, but a type with name '%s' was returned." a0 a1 a2) /// The type provider '%s' returned an invalid method from 'ApplyStaticArgumentsForMethod'. A method with name '%s' was expected, but a method with name '%s' was returned. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1184) + /// (Originally from src/fsharp/FSComp.txt:1202) static member etProvidedAppliedMethodHadWrongName(a0 : System.String, a1 : System.String, a2 : System.String) = (3058, sprintf "The type provider '%s' returned an invalid method from 'ApplyStaticArgumentsForMethod'. A method with name '%s' was expected, but a method with name '%s' was returned." a0 a1 a2) /// This type test or downcast will erase the provided type '%s' to the type '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1185) + /// (Originally from src/fsharp/FSComp.txt:1203) static member tcTypeTestLossy(a0 : System.String, a1 : System.String) = (3060, sprintf "This type test or downcast will erase the provided type '%s' to the type '%s'" a0 a1) /// This downcast will erase the provided type '%s' to the type '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1186) + /// (Originally from src/fsharp/FSComp.txt:1204) static member tcTypeCastErased(a0 : System.String, a1 : System.String) = (3061, sprintf "This downcast will erase the provided type '%s' to the type '%s'." a0 a1) /// This type test with a provided type '%s' is not allowed because this provided type will be erased to '%s' at runtime. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1187) + /// (Originally from src/fsharp/FSComp.txt:1205) static member tcTypeTestErased(a0 : System.String, a1 : System.String) = (3062, sprintf "This type test with a provided type '%s' is not allowed because this provided type will be erased to '%s' at runtime." a0 a1) /// Cannot inherit from erased provided type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1188) + /// (Originally from src/fsharp/FSComp.txt:1206) static member tcCannotInheritFromErasedType() = (3063, sprintf "Cannot inherit from erased provided type" ) /// Assembly '%s' hase TypeProviderAssembly attribute with invalid value '%s'. The value should be a valid assembly name - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1189) + /// (Originally from src/fsharp/FSComp.txt:1207) static member etInvalidTypeProviderAssemblyName(a0 : System.String, a1 : System.String) = (3065, sprintf "Assembly '%s' hase TypeProviderAssembly attribute with invalid value '%s'. The value should be a valid assembly name" a0 a1) /// Invalid member name. Members may not have name '.ctor' or '.cctor' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1190) + /// (Originally from src/fsharp/FSComp.txt:1208) static member tcInvalidMemberNameCtor() = (3066, sprintf "Invalid member name. Members may not have name '.ctor' or '.cctor'" ) /// The function or member '%s' is used in a way that requires further type annotations at its definition to ensure consistency of inferred types. The inferred signature is '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1191) + /// (Originally from src/fsharp/FSComp.txt:1209) static member tcInferredGenericTypeGivesRiseToInconsistency(a0 : System.String, a1 : System.String) = (3068, sprintf "The function or member '%s' is used in a way that requires further type annotations at its definition to ensure consistency of inferred types. The inferred signature is '%s'." a0 a1) /// The number of type arguments did not match: '%d' given, '%d' expected. This may be related to a previously reported error. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1192) + /// (Originally from src/fsharp/FSComp.txt:1210) static member tcInvalidTypeArgumentCount(a0 : System.Int32, a1 : System.Int32) = (3069, sprintf "The number of type arguments did not match: '%d' given, '%d' expected. This may be related to a previously reported error." a0 a1) /// Cannot override inherited member '%s' because it is sealed - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1193) + /// (Originally from src/fsharp/FSComp.txt:1211) static member tcCannotOverrideSealedMethod(a0 : System.String) = (3070, sprintf "Cannot override inherited member '%s' because it is sealed" a0) /// The type provider '%s' reported an error in the context of provided type '%s', member '%s'. The error: %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1194) + /// (Originally from src/fsharp/FSComp.txt:1212) static member etProviderErrorWithContext(a0 : System.String, a1 : System.String, a2 : System.String, a3 : System.String) = (3071, sprintf "The type provider '%s' reported an error in the context of provided type '%s', member '%s'. The error: %s" a0 a1 a2 a3) /// An exception occurred when accessing the '%s' of a provided type: %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1195) + /// (Originally from src/fsharp/FSComp.txt:1213) static member etProvidedTypeWithNameException(a0 : System.String, a1 : System.String) = (3072, sprintf "An exception occurred when accessing the '%s' of a provided type: %s" a0 a1) /// The '%s' of a provided type was null or empty. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1196) + /// (Originally from src/fsharp/FSComp.txt:1214) static member etProvidedTypeWithNullOrEmptyName(a0 : System.String) = (3073, sprintf "The '%s' of a provided type was null or empty." a0) /// Character '%s' is not allowed in provided type name '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1197) + /// (Originally from src/fsharp/FSComp.txt:1215) static member etIllegalCharactersInTypeName(a0 : System.String, a1 : System.String) = (3075, sprintf "Character '%s' is not allowed in provided type name '%s'" a0 a1) /// In queries, '%s' must use a simple pattern - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1198) + /// (Originally from src/fsharp/FSComp.txt:1216) static member tcJoinMustUseSimplePattern(a0 : System.String) = (3077, sprintf "In queries, '%s' must use a simple pattern" a0) /// A custom query operation for '%s' is required but not specified - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1199) + /// (Originally from src/fsharp/FSComp.txt:1217) static member tcMissingCustomOperation(a0 : System.String) = (3078, sprintf "A custom query operation for '%s' is required but not specified" a0) /// Named static arguments must come after all unnamed static arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1200) + /// (Originally from src/fsharp/FSComp.txt:1218) static member etBadUnnamedStaticArgs() = (3080, sprintf "Named static arguments must come after all unnamed static arguments" ) /// The static parameter '%s' of the provided type or method '%s' requires a value. Static parameters to type providers may be optionally specified using named arguments, e.g. '%s<%s=...>'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1201) + /// (Originally from src/fsharp/FSComp.txt:1219) static member etStaticParameterRequiresAValue(a0 : System.String, a1 : System.String, a2 : System.String, a3 : System.String) = (3081, sprintf "The static parameter '%s' of the provided type or method '%s' requires a value. Static parameters to type providers may be optionally specified using named arguments, e.g. '%s<%s=...>'." a0 a1 a2 a3) /// No static parameter exists with name '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1202) + /// (Originally from src/fsharp/FSComp.txt:1220) static member etNoStaticParameterWithName(a0 : System.String) = (3082, sprintf "No static parameter exists with name '%s'" a0) /// The static parameter '%s' has already been given a value - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1203) + /// (Originally from src/fsharp/FSComp.txt:1221) static member etStaticParameterAlreadyHasValue(a0 : System.String) = (3083, sprintf "The static parameter '%s' has already been given a value" a0) /// Multiple static parameters exist with name '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1204) + /// (Originally from src/fsharp/FSComp.txt:1222) static member etMultipleStaticParameterWithName(a0 : System.String) = (3084, sprintf "Multiple static parameters exist with name '%s'" a0) /// A custom operation may not be used in conjunction with a non-value or recursive 'let' binding in another part of this computation expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1205) + /// (Originally from src/fsharp/FSComp.txt:1223) static member tcCustomOperationMayNotBeUsedInConjunctionWithNonSimpleLetBindings() = (3085, sprintf "A custom operation may not be used in conjunction with a non-value or recursive 'let' binding in another part of this computation expression" ) /// A custom operation may not be used in conjunction with 'use', 'try/with', 'try/finally', 'if/then/else' or 'match' operators within this computation expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1206) + /// (Originally from src/fsharp/FSComp.txt:1224) static member tcCustomOperationMayNotBeUsedHere() = (3086, sprintf "A custom operation may not be used in conjunction with 'use', 'try/with', 'try/finally', 'if/then/else' or 'match' operators within this computation expression" ) /// The custom operation '%s' refers to a method which is overloaded. The implementations of custom operations may not be overloaded. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1207) + /// (Originally from src/fsharp/FSComp.txt:1225) static member tcCustomOperationMayNotBeOverloaded(a0 : System.String) = (3087, sprintf "The custom operation '%s' refers to a method which is overloaded. The implementations of custom operations may not be overloaded." a0) /// An if/then/else expression may not be used within queries. Consider using either an if/then expression, or use a sequence expression instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1208) + /// (Originally from src/fsharp/FSComp.txt:1226) static member tcIfThenElseMayNotBeUsedWithinQueries() = (3090, sprintf "An if/then/else expression may not be used within queries. Consider using either an if/then expression, or use a sequence expression instead." ) /// Invalid argument to 'methodhandleof' during codegen - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1209) + /// (Originally from src/fsharp/FSComp.txt:1227) static member ilxgenUnexpectedArgumentToMethodHandleOfDuringCodegen() = (3091, sprintf "Invalid argument to 'methodhandleof' during codegen" ) /// A reference to a provided type was missing a value for the static parameter '%s'. You may need to recompile one or more referenced assemblies. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1210) + /// (Originally from src/fsharp/FSComp.txt:1228) static member etProvidedTypeReferenceMissingArgument(a0 : System.String) = (3092, sprintf "A reference to a provided type was missing a value for the static parameter '%s'. You may need to recompile one or more referenced assemblies." a0) /// A reference to a provided type had an invalid value '%s' for a static parameter. You may need to recompile one or more referenced assemblies. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1211) + /// (Originally from src/fsharp/FSComp.txt:1229) static member etProvidedTypeReferenceInvalidText(a0 : System.String) = (3093, sprintf "A reference to a provided type had an invalid value '%s' for a static parameter. You may need to recompile one or more referenced assemblies." a0) /// '%s' is not used correctly. This is a custom operation in this query or computation expression. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1212) + /// (Originally from src/fsharp/FSComp.txt:1230) static member tcCustomOperationNotUsedCorrectly(a0 : System.String) = (3095, sprintf "'%s' is not used correctly. This is a custom operation in this query or computation expression." a0) /// '%s' is not used correctly. Usage: %s. This is a custom operation in this query or computation expression. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1213) + /// (Originally from src/fsharp/FSComp.txt:1231) static member tcCustomOperationNotUsedCorrectly2(a0 : System.String, a1 : System.String) = (3095, sprintf "'%s' is not used correctly. Usage: %s. This is a custom operation in this query or computation expression." a0 a1) /// %s var in collection %s (outerKey = innerKey). Note that parentheses are required after '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1214) + /// (Originally from src/fsharp/FSComp.txt:1232) static member customOperationTextLikeJoin(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "%s var in collection %s (outerKey = innerKey). Note that parentheses are required after '%s'" a0 a1 a2) /// %s var in collection %s (outerKey = innerKey) into group. Note that parentheses are required after '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1215) + /// (Originally from src/fsharp/FSComp.txt:1233) static member customOperationTextLikeGroupJoin(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "%s var in collection %s (outerKey = innerKey) into group. Note that parentheses are required after '%s'" a0 a1 a2) /// %s var in collection - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1216) + /// (Originally from src/fsharp/FSComp.txt:1234) static member customOperationTextLikeZip(a0 : System.String) = (sprintf "%s var in collection" a0) /// '%s' must be followed by a variable name. Usage: %s. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1217) + /// (Originally from src/fsharp/FSComp.txt:1235) static member tcBinaryOperatorRequiresVariable(a0 : System.String, a1 : System.String) = (3096, sprintf "'%s' must be followed by a variable name. Usage: %s." a0 a1) /// Incorrect syntax for '%s'. Usage: %s. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1218) + /// (Originally from src/fsharp/FSComp.txt:1236) static member tcOperatorIncorrectSyntax(a0 : System.String, a1 : System.String) = (3097, sprintf "Incorrect syntax for '%s'. Usage: %s." a0 a1) /// '%s' must come after a 'for' selection clause and be followed by the rest of the query. Syntax: ... %s ... - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1219) + /// (Originally from src/fsharp/FSComp.txt:1237) static member tcBinaryOperatorRequiresBody(a0 : System.String, a1 : System.String) = (3098, sprintf "'%s' must come after a 'for' selection clause and be followed by the rest of the query. Syntax: ... %s ..." a0 a1) /// '%s' is used with an incorrect number of arguments. This is a custom operation in this query or computation expression. Expected %d argument(s), but given %d. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1220) + /// (Originally from src/fsharp/FSComp.txt:1238) static member tcCustomOperationHasIncorrectArgCount(a0 : System.String, a1 : System.Int32, a2 : System.Int32) = (3099, sprintf "'%s' is used with an incorrect number of arguments. This is a custom operation in this query or computation expression. Expected %d argument(s), but given %d." a0 a1 a2) /// Expected an expression after this point - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1221) + /// (Originally from src/fsharp/FSComp.txt:1239) static member parsExpectedExpressionAfterToken() = (3100, sprintf "Expected an expression after this point" ) /// Expected a type after this point - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1222) + /// (Originally from src/fsharp/FSComp.txt:1240) static member parsExpectedTypeAfterToken() = (3101, sprintf "Expected a type after this point" ) /// Unmatched '[<'. Expected closing '>]' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1223) + /// (Originally from src/fsharp/FSComp.txt:1241) static member parsUnmatchedLBrackLess() = (3102, sprintf "Unmatched '[<'. Expected closing '>]'" ) /// Unexpected end of input in 'match' expression. Expected 'match with | -> | -> ...'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1224) + /// (Originally from src/fsharp/FSComp.txt:1242) static member parsUnexpectedEndOfFileMatch() = (3103, sprintf "Unexpected end of input in 'match' expression. Expected 'match with | -> | -> ...'." ) /// Unexpected end of input in 'try' expression. Expected 'try with ' or 'try finally '. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1225) + /// (Originally from src/fsharp/FSComp.txt:1243) static member parsUnexpectedEndOfFileTry() = (3104, sprintf "Unexpected end of input in 'try' expression. Expected 'try with ' or 'try finally '." ) /// Unexpected end of input in 'while' expression. Expected 'while do '. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1226) + /// (Originally from src/fsharp/FSComp.txt:1244) static member parsUnexpectedEndOfFileWhile() = (3105, sprintf "Unexpected end of input in 'while' expression. Expected 'while do '." ) /// Unexpected end of input in 'for' expression. Expected 'for in do '. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1227) + /// (Originally from src/fsharp/FSComp.txt:1245) static member parsUnexpectedEndOfFileFor() = (3106, sprintf "Unexpected end of input in 'for' expression. Expected 'for in do '." ) /// Unexpected end of input in 'match' or 'try' expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1228) + /// (Originally from src/fsharp/FSComp.txt:1246) static member parsUnexpectedEndOfFileWith() = (3107, sprintf "Unexpected end of input in 'match' or 'try' expression" ) /// Unexpected end of input in 'then' branch of conditional expression. Expected 'if then ' or 'if then else '. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1229) + /// (Originally from src/fsharp/FSComp.txt:1247) static member parsUnexpectedEndOfFileThen() = (3108, sprintf "Unexpected end of input in 'then' branch of conditional expression. Expected 'if then ' or 'if then else '." ) /// Unexpected end of input in 'else' branch of conditional expression. Expected 'if then ' or 'if then else '. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1230) + /// (Originally from src/fsharp/FSComp.txt:1248) static member parsUnexpectedEndOfFileElse() = (3109, sprintf "Unexpected end of input in 'else' branch of conditional expression. Expected 'if then ' or 'if then else '." ) /// Unexpected end of input in body of lambda expression. Expected 'fun ... -> '. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1231) + /// (Originally from src/fsharp/FSComp.txt:1249) static member parsUnexpectedEndOfFileFunBody() = (3110, sprintf "Unexpected end of input in body of lambda expression. Expected 'fun ... -> '." ) /// Unexpected end of input in type arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1232) + /// (Originally from src/fsharp/FSComp.txt:1250) static member parsUnexpectedEndOfFileTypeArgs() = (3111, sprintf "Unexpected end of input in type arguments" ) /// Unexpected end of input in type signature - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1233) + /// (Originally from src/fsharp/FSComp.txt:1251) static member parsUnexpectedEndOfFileTypeSignature() = (3112, sprintf "Unexpected end of input in type signature" ) /// Unexpected end of input in type definition - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1234) + /// (Originally from src/fsharp/FSComp.txt:1252) static member parsUnexpectedEndOfFileTypeDefinition() = (3113, sprintf "Unexpected end of input in type definition" ) /// Unexpected end of input in object members - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1235) + /// (Originally from src/fsharp/FSComp.txt:1253) static member parsUnexpectedEndOfFileObjectMembers() = (3114, sprintf "Unexpected end of input in object members" ) /// Unexpected end of input in value, function or member definition - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1236) + /// (Originally from src/fsharp/FSComp.txt:1254) static member parsUnexpectedEndOfFileDefinition() = (3115, sprintf "Unexpected end of input in value, function or member definition" ) /// Unexpected end of input in expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1237) + /// (Originally from src/fsharp/FSComp.txt:1255) static member parsUnexpectedEndOfFileExpression() = (3116, sprintf "Unexpected end of input in expression" ) /// Unexpected end of type. Expected a name after this point. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1238) + /// (Originally from src/fsharp/FSComp.txt:1256) static member parsExpectedNameAfterToken() = (3117, sprintf "Unexpected end of type. Expected a name after this point." ) /// Incomplete value or function definition. If this is in an expression, the body of the expression must be indented to the same column as the 'let' keyword. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1239) + /// (Originally from src/fsharp/FSComp.txt:1257) static member parsUnmatchedLet() = (3118, sprintf "Incomplete value or function definition. If this is in an expression, the body of the expression must be indented to the same column as the 'let' keyword." ) /// Incomplete value definition. If this is in an expression, the body of the expression must be indented to the same column as the 'let!' keyword. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1240) + /// (Originally from src/fsharp/FSComp.txt:1258) static member parsUnmatchedLetBang() = (3119, sprintf "Incomplete value definition. If this is in an expression, the body of the expression must be indented to the same column as the 'let!' keyword." ) /// Incomplete value definition. If this is in an expression, the body of the expression must be indented to the same column as the 'use!' keyword. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1241) + /// (Originally from src/fsharp/FSComp.txt:1259) static member parsUnmatchedUseBang() = (3120, sprintf "Incomplete value definition. If this is in an expression, the body of the expression must be indented to the same column as the 'use!' keyword." ) /// Incomplete value definition. If this is in an expression, the body of the expression must be indented to the same column as the 'use' keyword. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1242) + /// (Originally from src/fsharp/FSComp.txt:1260) static member parsUnmatchedUse() = (3121, sprintf "Incomplete value definition. If this is in an expression, the body of the expression must be indented to the same column as the 'use' keyword." ) /// Missing 'do' in 'while' expression. Expected 'while do '. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1243) + /// (Originally from src/fsharp/FSComp.txt:1261) static member parsWhileDoExpected() = (3122, sprintf "Missing 'do' in 'while' expression. Expected 'while do '." ) /// Missing 'do' in 'for' expression. Expected 'for in do '. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1244) + /// (Originally from src/fsharp/FSComp.txt:1262) static member parsForDoExpected() = (3123, sprintf "Missing 'do' in 'for' expression. Expected 'for in do '." ) /// Invalid join relation in '%s'. Expected 'expr expr', where is =, =?, ?= or ?=?. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1245) + /// (Originally from src/fsharp/FSComp.txt:1263) static member tcInvalidRelationInJoin(a0 : System.String) = (3125, sprintf "Invalid join relation in '%s'. Expected 'expr expr', where is =, =?, ?= or ?=?." a0) /// Calls - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1246) + /// (Originally from src/fsharp/FSComp.txt:1264) static member typeInfoCallsWord() = (sprintf "Calls" ) /// Invalid number of generic arguments to type '%s' in provided type. Expected '%d' arguments, given '%d'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1247) + /// (Originally from src/fsharp/FSComp.txt:1265) static member impInvalidNumberOfGenericArguments(a0 : System.String, a1 : System.Int32, a2 : System.Int32) = (3126, sprintf "Invalid number of generic arguments to type '%s' in provided type. Expected '%d' arguments, given '%d'." a0 a1 a2) /// Invalid value '%s' for unit-of-measure parameter '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1248) + /// (Originally from src/fsharp/FSComp.txt:1266) static member impInvalidMeasureArgument1(a0 : System.String, a1 : System.String) = (3127, sprintf "Invalid value '%s' for unit-of-measure parameter '%s'" a0 a1) /// Invalid value unit-of-measure parameter '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1249) + /// (Originally from src/fsharp/FSComp.txt:1267) static member impInvalidMeasureArgument2(a0 : System.String) = (3127, sprintf "Invalid value unit-of-measure parameter '%s'" a0) /// Property '%s' on provided type '%s' is neither readable nor writable as it has CanRead=false and CanWrite=false - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1250) + /// (Originally from src/fsharp/FSComp.txt:1268) static member etPropertyNeedsCanWriteOrCanRead(a0 : System.String, a1 : System.String) = (3128, sprintf "Property '%s' on provided type '%s' is neither readable nor writable as it has CanRead=false and CanWrite=false" a0 a1) /// A use of 'into' must be followed by the remainder of the computation - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1251) + /// (Originally from src/fsharp/FSComp.txt:1269) static member tcIntoNeedsRestOfQuery() = (3129, sprintf "A use of 'into' must be followed by the remainder of the computation" ) /// The operator '%s' does not accept the use of 'into' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1252) + /// (Originally from src/fsharp/FSComp.txt:1270) static member tcOperatorDoesntAcceptInto(a0 : System.String) = (3130, sprintf "The operator '%s' does not accept the use of 'into'" a0) /// The definition of the custom operator '%s' does not use a valid combination of attribute flags - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1253) + /// (Originally from src/fsharp/FSComp.txt:1271) static member tcCustomOperationInvalid(a0 : System.String) = (3131, sprintf "The definition of the custom operator '%s' does not use a valid combination of attribute flags" a0) /// This type definition may not have the 'CLIMutable' attribute. Only record types may have this attribute. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1254) + /// (Originally from src/fsharp/FSComp.txt:1272) static member tcThisTypeMayNotHaveACLIMutableAttribute() = (3132, sprintf "This type definition may not have the 'CLIMutable' attribute. Only record types may have this attribute." ) /// 'member val' definitions are only permitted in types with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1255) + /// (Originally from src/fsharp/FSComp.txt:1273) static member tcAutoPropertyRequiresImplicitConstructionSequence() = (3133, sprintf "'member val' definitions are only permitted in types with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'." ) /// Property definitions may not be declared mutable. To indicate that this property can be set, use 'member val PropertyName = expr with get,set'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1256) + /// (Originally from src/fsharp/FSComp.txt:1274) static member parsMutableOnAutoPropertyShouldBeGetSet() = (3134, sprintf "Property definitions may not be declared mutable. To indicate that this property can be set, use 'member val PropertyName = expr with get,set'." ) /// To indicate that this property can be set, use 'member val PropertyName = expr with get,set'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1257) + /// (Originally from src/fsharp/FSComp.txt:1275) static member parsMutableOnAutoPropertyShouldBeGetSetNotJustSet() = (3135, sprintf "To indicate that this property can be set, use 'member val PropertyName = expr with get,set'." ) /// Type '%s' is illegal because in byref, T cannot contain byref types. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1258) + /// (Originally from src/fsharp/FSComp.txt:1276) static member chkNoByrefsOfByrefs(a0 : System.String) = (3136, sprintf "Type '%s' is illegal because in byref, T cannot contain byref types." a0) /// F# supports array ranks between 1 and 32. The value %d is not allowed. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1259) + /// (Originally from src/fsharp/FSComp.txt:1277) static member tastopsMaxArrayThirtyTwo(a0 : System.Int32) = (3138, sprintf "F# supports array ranks between 1 and 32. The value %d is not allowed." a0) /// In queries, use the form 'for x in n .. m do ...' for ranging over integers - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1260) + /// (Originally from src/fsharp/FSComp.txt:1278) static member tcNoIntegerForLoopInQuery() = (3139, sprintf "In queries, use the form 'for x in n .. m do ...' for ranging over integers" ) /// 'while' expressions may not be used in queries - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1261) + /// (Originally from src/fsharp/FSComp.txt:1279) static member tcNoWhileInQuery() = (3140, sprintf "'while' expressions may not be used in queries" ) /// 'try/finally' expressions may not be used in queries - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1262) + /// (Originally from src/fsharp/FSComp.txt:1280) static member tcNoTryFinallyInQuery() = (3141, sprintf "'try/finally' expressions may not be used in queries" ) /// 'use' expressions may not be used in queries - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1263) + /// (Originally from src/fsharp/FSComp.txt:1281) static member tcUseMayNotBeUsedInQueries() = (3142, sprintf "'use' expressions may not be used in queries" ) /// 'let!', 'use!' and 'do!' expressions may not be used in queries - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1264) + /// (Originally from src/fsharp/FSComp.txt:1282) static member tcBindMayNotBeUsedInQueries() = (3143, sprintf "'let!', 'use!' and 'do!' expressions may not be used in queries" ) /// 'return' and 'return!' may not be used in queries - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1265) + /// (Originally from src/fsharp/FSComp.txt:1283) static member tcReturnMayNotBeUsedInQueries() = (3144, sprintf "'return' and 'return!' may not be used in queries" ) /// 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. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1266) + /// (Originally from src/fsharp/FSComp.txt:1284) static member tcUnrecognizedQueryOperator() = (3145, sprintf "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." ) /// 'try/with' expressions may not be used in queries - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1267) + /// (Originally from src/fsharp/FSComp.txt:1285) static member tcTryWithMayNotBeUsedInQueries() = (3146, sprintf "'try/with' expressions may not be used in queries" ) /// This 'let' definition may not be used in a query. Only simple value definitions may be used in queries. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1268) + /// (Originally from src/fsharp/FSComp.txt:1286) static member tcNonSimpleLetBindingInQuery() = (3147, sprintf "This 'let' definition may not be used in a query. Only simple value definitions may be used in queries." ) /// Too many static parameters. Expected at most %d parameters, but got %d unnamed and %d named parameters. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1269) + /// (Originally from src/fsharp/FSComp.txt:1287) static member etTooManyStaticParameters(a0 : System.Int32, a1 : System.Int32, a2 : System.Int32) = (3148, sprintf "Too many static parameters. Expected at most %d parameters, but got %d unnamed and %d named parameters." a0 a1 a2) /// Invalid provided literal value '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1270) + /// (Originally from src/fsharp/FSComp.txt:1288) static member infosInvalidProvidedLiteralValue(a0 : System.String) = (3149, sprintf "Invalid provided literal value '%s'" a0) /// The 'anycpu32bitpreferred' platform can only be used with EXE targets. You must use 'anycpu' instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1271) + /// (Originally from src/fsharp/FSComp.txt:1289) static member invalidPlatformTarget() = (3150, sprintf "The 'anycpu32bitpreferred' platform can only be used with EXE targets. You must use 'anycpu' instead." ) /// This member, function or value declaration may not be declared 'inline' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1272) + /// (Originally from src/fsharp/FSComp.txt:1290) static member tcThisValueMayNotBeInlined() = (3151, sprintf "This member, function or value declaration may not be declared 'inline'" ) /// The provider '%s' returned a non-generated type '%s' in the context of a set of generated types. Consider adjusting the type provider to only return generated types. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1273) + /// (Originally from src/fsharp/FSComp.txt:1291) static member etErasedTypeUsedInGeneration(a0 : System.String, a1 : System.String) = (3152, sprintf "The provider '%s' returned a non-generated type '%s' in the context of a set of generated types. Consider adjusting the type provider to only return generated types." a0 a1) /// Arguments to query operators may require parentheses, e.g. 'where (x > y)' or 'groupBy (x.Length / 10)' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1274) + /// (Originally from src/fsharp/FSComp.txt:1292) static member tcUnrecognizedQueryBinaryOperator() = (3153, sprintf "Arguments to query operators may require parentheses, e.g. 'where (x > y)' or 'groupBy (x.Length / 10)'" ) /// A quotation may not involve an assignment to or taking the address of a captured local variable - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1275) + /// (Originally from src/fsharp/FSComp.txt:1293) static member crefNoSetOfHole() = (3155, sprintf "A quotation may not involve an assignment to or taking the address of a captured local variable" ) /// + 1 overload - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1276) + /// (Originally from src/fsharp/FSComp.txt:1294) static member nicePrintOtherOverloads1() = (sprintf "+ 1 overload" ) /// + %d overloads - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1277) + /// (Originally from src/fsharp/FSComp.txt:1295) static member nicePrintOtherOverloadsN(a0 : System.Int32) = (sprintf "+ %d overloads" a0) /// Erased to - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1278) + /// (Originally from src/fsharp/FSComp.txt:1296) static member erasedTo() = (sprintf "Erased to" ) /// Unexpected token '%s' or incomplete expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1279) + /// (Originally from src/fsharp/FSComp.txt:1297) static member parsUnfinishedExpression(a0 : System.String) = (3156, sprintf "Unexpected token '%s' or incomplete expression" a0) /// Cannot find code target for this attribute, possibly because the code after the attribute is incomplete. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1280) + /// (Originally from src/fsharp/FSComp.txt:1298) static member parsAttributeOnIncompleteCode() = (3158, sprintf "Cannot find code target for this attribute, possibly because the code after the attribute is incomplete." ) /// Type name cannot be empty. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1281) + /// (Originally from src/fsharp/FSComp.txt:1299) static member parsTypeNameCannotBeEmpty() = (3159, sprintf "Type name cannot be empty." ) /// Problem reading assembly '%s': %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1282) + /// (Originally from src/fsharp/FSComp.txt:1300) static member buildProblemReadingAssembly(a0 : System.String, a1 : System.String) = (3160, sprintf "Problem reading assembly '%s': %s" a0 a1) /// Invalid provided field. Provided fields of erased provided types must be literals. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1283) + /// (Originally from src/fsharp/FSComp.txt:1301) static member tcTPFieldMustBeLiteral() = (3161, sprintf "Invalid provided field. Provided fields of erased provided types must be literals." ) /// (loading description...) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1284) + /// (Originally from src/fsharp/FSComp.txt:1302) static member loadingDescription() = (sprintf "(loading description...)" ) /// (description unavailable...) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1285) + /// (Originally from src/fsharp/FSComp.txt:1303) static member descriptionUnavailable() = (sprintf "(description unavailable...)" ) /// A type variable has been constrained by multiple different class types. A type variable may only have one class constraint. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1286) + /// (Originally from src/fsharp/FSComp.txt:1304) static member chkTyparMultipleClassConstraints() = (3162, sprintf "A type variable has been constrained by multiple different class types. A type variable may only have one class constraint." ) /// 'match' expressions may not be used in queries - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1287) + /// (Originally from src/fsharp/FSComp.txt:1305) static member tcMatchMayNotBeUsedWithQuery() = (3163, sprintf "'match' expressions may not be used in queries" ) /// Infix operator member '%s' has %d initial argument(s). Expected a tuple of 3 arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1288) + /// (Originally from src/fsharp/FSComp.txt:1306) static member memberOperatorDefinitionWithNonTripleArgument(a0 : System.String, a1 : System.Int32) = (3164, sprintf "Infix operator member '%s' has %d initial argument(s). Expected a tuple of 3 arguments" a0 a1) /// The operator '%s' cannot be resolved. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1289) + /// (Originally from src/fsharp/FSComp.txt:1307) static member cannotResolveNullableOperators(a0 : System.String) = (3165, sprintf "The operator '%s' cannot be resolved. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'." a0) /// '%s' must be followed by 'in'. Usage: %s. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1290) + /// (Originally from src/fsharp/FSComp.txt:1308) static member tcOperatorRequiresIn(a0 : System.String, a1 : System.String) = (3167, sprintf "'%s' must be followed by 'in'. Usage: %s." a0 a1) /// Neither 'member val' nor 'override val' definitions are permitted in object expressions. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1291) + /// (Originally from src/fsharp/FSComp.txt:1309) static member parsIllegalMemberVarInObjectImplementation() = (3168, sprintf "Neither 'member val' nor 'override val' definitions are permitted in object expressions." ) /// Copy-and-update record expressions must include at least one field. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1292) + /// (Originally from src/fsharp/FSComp.txt:1310) static member tcEmptyCopyAndUpdateRecordInvalid() = (3169, sprintf "Copy-and-update record expressions must include at least one field." ) /// '_' cannot be used as field name - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1293) + /// (Originally from src/fsharp/FSComp.txt:1311) static member parsUnderscoreInvalidFieldName() = (3170, sprintf "'_' cannot be used as field name" ) /// The provided types generated by this use of a type provider may not be used from other F# assemblies and should be marked internal or private. Consider using 'type internal TypeName = ...' or 'type private TypeName = ...'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1294) + /// (Originally from src/fsharp/FSComp.txt:1312) static member tcGeneratedTypesShouldBeInternalOrPrivate() = (3171, sprintf "The provided types generated by this use of a type provider may not be used from other F# assemblies and should be marked internal or private. Consider using 'type internal TypeName = ...' or 'type private TypeName = ...'." ) /// A property's getter and setter must have the same type. Property '%s' has getter of type '%s' but setter of type '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1295) + /// (Originally from src/fsharp/FSComp.txt:1313) static member chkGetterAndSetterHaveSamePropertyType(a0 : System.String, a1 : System.String, a2 : System.String) = (3172, sprintf "A property's getter and setter must have the same type. Property '%s' has getter of type '%s' but setter of type '%s'." a0 a1 a2) /// Array method '%s' is supplied by the runtime and cannot be directly used in code. For operations with array elements consider using family of GetArray/SetArray functions from LanguagePrimitives.IntrinsicFunctions module. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1296) + /// (Originally from src/fsharp/FSComp.txt:1314) static member tcRuntimeSuppliedMethodCannotBeUsedInUserCode(a0 : System.String) = (3173, sprintf "Array method '%s' is supplied by the runtime and cannot be directly used in code. For operations with array elements consider using family of GetArray/SetArray functions from LanguagePrimitives.IntrinsicFunctions module." a0) /// The union case '%s' does not have a field named '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1297) + /// (Originally from src/fsharp/FSComp.txt:1315) static member tcUnionCaseConstructorDoesNotHaveFieldWithGivenName(a0 : System.String, a1 : System.String) = (3174, sprintf "The union case '%s' does not have a field named '%s'." a0 a1) /// The exception '%s' does not have a field named '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1298) + /// (Originally from src/fsharp/FSComp.txt:1316) static member tcExceptionConstructorDoesNotHaveFieldWithGivenName(a0 : System.String, a1 : System.String) = (3174, sprintf "The exception '%s' does not have a field named '%s'." a0 a1) /// Active patterns do not have fields. This syntax is invalid. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1299) + /// (Originally from src/fsharp/FSComp.txt:1317) static member tcActivePatternsDoNotHaveFields() = (3174, sprintf "Active patterns do not have fields. This syntax is invalid." ) /// The constructor does not have a field named '%s'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1300) + /// (Originally from src/fsharp/FSComp.txt:1318) static member tcConstructorDoesNotHaveFieldWithGivenName(a0 : System.String) = (3174, sprintf "The constructor does not have a field named '%s'." a0) /// Union case/exception field '%s' cannot be used more than once. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1301) + /// (Originally from src/fsharp/FSComp.txt:1319) static member tcUnionCaseFieldCannotBeUsedMoreThanOnce(a0 : System.String) = (3175, sprintf "Union case/exception field '%s' cannot be used more than once." a0) /// Named field '%s' is used more than once. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1302) + /// (Originally from src/fsharp/FSComp.txt:1320) static member tcFieldNameIsUsedModeThanOnce(a0 : System.String) = (3176, sprintf "Named field '%s' is used more than once." a0) /// Named field '%s' conflicts with autogenerated name for anonymous field. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1303) + /// (Originally from src/fsharp/FSComp.txt:1321) static member tcFieldNameConflictsWithGeneratedNameForAnonymousField(a0 : System.String) = (3176, sprintf "Named field '%s' conflicts with autogenerated name for anonymous field." a0) /// This literal expression or attribute argument results in an arithmetic overflow. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1304) + /// (Originally from src/fsharp/FSComp.txt:1322) static member tastConstantExpressionOverflow() = (3177, sprintf "This literal expression or attribute argument results in an arithmetic overflow." ) /// This is not valid literal expression. The [] attribute will be ignored. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1305) + /// (Originally from src/fsharp/FSComp.txt:1323) static member tcIllegalStructTypeForConstantExpression() = (3178, sprintf "This is not valid literal expression. The [] attribute will be ignored." ) /// System.Runtime.InteropServices assembly is required to use UnknownWrapper\DispatchWrapper classes. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1306) + /// (Originally from src/fsharp/FSComp.txt:1324) static member fscSystemRuntimeInteropServicesIsRequired() = (3179, sprintf "System.Runtime.InteropServices assembly is required to use UnknownWrapper\DispatchWrapper classes." ) /// The mutable local '%s' is implicitly allocated as a reference cell because it has been captured by a closure. This warning is for informational purposes only to indicate where implicit allocations are performed. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1307) + /// (Originally from src/fsharp/FSComp.txt:1325) static member abImplicitHeapAllocation(a0 : System.String) = (3180, sprintf "The mutable local '%s' is implicitly allocated as a reference cell because it has been captured by a closure. This warning is for informational purposes only to indicate where implicit allocations are performed." a0) /// A type provider implemented GetStaticParametersForMethod, but ApplyStaticArgumentsForMethod was not implemented or invalid - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1308) + /// (Originally from src/fsharp/FSComp.txt:1326) static member estApplyStaticArgumentsForMethodNotImplemented() = (sprintf "A type provider implemented GetStaticParametersForMethod, but ApplyStaticArgumentsForMethod was not implemented or invalid" ) /// An error occured applying the static arguments to a provided method - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1309) + /// (Originally from src/fsharp/FSComp.txt:1327) static member etErrorApplyingStaticArgumentsToMethod() = (3181, sprintf "An error occured applying the static arguments to a provided method" ) /// Unexpected character '%s' in preprocessor expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1310) + /// (Originally from src/fsharp/FSComp.txt:1328) static member pplexUnexpectedChar(a0 : System.String) = (3182, sprintf "Unexpected character '%s' in preprocessor expression" a0) /// Unexpected token '%s' in preprocessor expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1311) + /// (Originally from src/fsharp/FSComp.txt:1329) static member ppparsUnexpectedToken(a0 : System.String) = (3183, sprintf "Unexpected token '%s' in preprocessor expression" a0) /// Incomplete preprocessor expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1312) + /// (Originally from src/fsharp/FSComp.txt:1330) static member ppparsIncompleteExpression() = (3184, sprintf "Incomplete preprocessor expression" ) /// Missing token '%s' in preprocessor expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1313) + /// (Originally from src/fsharp/FSComp.txt:1331) static member ppparsMissingToken(a0 : System.String) = (3185, sprintf "Missing token '%s' in preprocessor expression" a0) /// An error occurred while reading the F# metadata node at position %d in table '%s' of assembly '%s'. The node had no matching declaration. Please report this warning. You may need to recompile the F# assembly you are using. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1314) + /// (Originally from src/fsharp/FSComp.txt:1332) static member pickleMissingDefinition(a0 : System.Int32, a1 : System.String, a2 : System.String) = (3186, sprintf "An error occurred while reading the F# metadata node at position %d in table '%s' of assembly '%s'. The node had no matching declaration. Please report this warning. You may need to recompile the F# assembly you are using." a0 a1 a2) /// Type inference caused the type variable %s to escape its scope. Consider adding an explicit type parameter declaration or adjusting your code to be less generic. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1315) + /// (Originally from src/fsharp/FSComp.txt:1333) static member checkNotSufficientlyGenericBecauseOfScope(a0 : System.String) = (3187, sprintf "Type inference caused the type variable %s to escape its scope. Consider adding an explicit type parameter declaration or adjusting your code to be less generic." a0) /// Type inference caused an inference type variable to escape its scope. Consider adding type annotations to make your code less generic. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1316) + /// (Originally from src/fsharp/FSComp.txt:1334) static member checkNotSufficientlyGenericBecauseOfScopeAnon() = (3188, sprintf "Type inference caused an inference type variable to escape its scope. Consider adding type annotations to make your code less generic." ) /// Redundant arguments are being ignored in function '%s'. Expected %d but got %d arguments. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1317) + /// (Originally from src/fsharp/FSComp.txt:1335) static member checkRaiseFamilyFunctionArgumentCount(a0 : System.String, a1 : System.Int32, a2 : System.Int32) = (3189, sprintf "Redundant arguments are being ignored in function '%s'. Expected %d but got %d arguments." a0 a1 a2) /// Lowercase literal '%s' is being shadowed by a new pattern with the same name. Only uppercase and module-prefixed literals can be used as named patterns. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1318) + /// (Originally from src/fsharp/FSComp.txt:1336) static member checkLowercaseLiteralBindingInPattern(a0 : System.String) = (3190, sprintf "Lowercase literal '%s' is being shadowed by a new pattern with the same name. Only uppercase and module-prefixed literals can be used as named patterns." a0) /// This literal pattern does not take arguments - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1319) + /// (Originally from src/fsharp/FSComp.txt:1337) static member tcLiteralDoesNotTakeArguments() = (3191, sprintf "This literal pattern does not take arguments" ) /// Constructors are not permitted as extension members - they must be defined as part of the original definition of the type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1320) + /// (Originally from src/fsharp/FSComp.txt:1338) static member tcConstructorsIllegalInAugmentation() = (3192, sprintf "Constructors are not permitted as extension members - they must be defined as part of the original definition of the type" ) /// Invalid response file '%s' ( '%s' ) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1321) + /// (Originally from src/fsharp/FSComp.txt:1339) static member optsInvalidResponseFile(a0 : System.String, a1 : System.String) = (3193, sprintf "Invalid response file '%s' ( '%s' )" a0 a1) /// Response file '%s' not found in '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1322) + /// (Originally from src/fsharp/FSComp.txt:1340) static member optsResponseFileNotFound(a0 : System.String, a1 : System.String) = (3194, sprintf "Response file '%s' not found in '%s'" a0 a1) /// Response file name '%s' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1323) + /// (Originally from src/fsharp/FSComp.txt:1341) static member optsResponseFileNameInvalid(a0 : System.String) = (3195, sprintf "Response file name '%s' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long" a0) /// Cannot find FSharp.Core.dll in compiler's directory - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1324) + /// (Originally from src/fsharp/FSComp.txt:1342) static member fsharpCoreNotFoundToBeCopied() = (3196, sprintf "Cannot find FSharp.Core.dll in compiler's directory" ) /// One tuple type is a struct tuple, the other is a reference tuple - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1325) + /// (Originally from src/fsharp/FSComp.txt:1343) static member tcTupleStructMismatch() = (sprintf "One tuple type is a struct tuple, the other is a reference tuple" ) /// This provided method requires static parameters - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1326) + /// (Originally from src/fsharp/FSComp.txt:1344) static member etMissingStaticArgumentsToMethod() = (3197, sprintf "This provided method requires static parameters" ) /// The conversion from %s to %s is a compile-time safe upcast, not a downcast. Consider using 'upcast' instead of 'downcast'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1327) + /// (Originally from src/fsharp/FSComp.txt:1345) static member considerUpcast(a0 : System.String, a1 : System.String) = (3198, sprintf "The conversion from %s to %s is a compile-time safe upcast, not a downcast. Consider using 'upcast' instead of 'downcast'." a0 a1) /// The conversion from %s to %s is a compile-time safe upcast, not a downcast. Consider using the :> (upcast) operator instead of the :?> (downcast) operator. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1328) + /// (Originally from src/fsharp/FSComp.txt:1346) static member considerUpcastOperator(a0 : System.String, a1 : System.String) = (3198, sprintf "The conversion from %s to %s is a compile-time safe upcast, not a downcast. Consider using the :> (upcast) operator instead of the :?> (downcast) operator." a0 a1) /// The 'rec' on this module is implied by an outer 'rec' declaration and is being ignored - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1329) + /// (Originally from src/fsharp/FSComp.txt:1347) static member tcRecImplied() = (3199, sprintf "The 'rec' on this module is implied by an outer 'rec' declaration and is being ignored" ) /// In a recursive declaration group, 'open' declarations must come first in each module - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1330) + /// (Originally from src/fsharp/FSComp.txt:1348) static member tcOpenFirstInMutRec() = (3200, sprintf "In a recursive declaration group, 'open' declarations must come first in each module" ) /// In a recursive declaration group, module abbreviations must come after all 'open' declarations and before other declarations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1331) + /// (Originally from src/fsharp/FSComp.txt:1349) static member tcModuleAbbrevFirstInMutRec() = (3201, sprintf "In a recursive declaration group, module abbreviations must come after all 'open' declarations and before other declarations" ) /// This declaration is not supported in recursive declaration groups - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1332) + /// (Originally from src/fsharp/FSComp.txt:1350) static member tcUnsupportedMutRecDecl() = (3202, sprintf "This declaration is not supported in recursive declaration groups" ) /// Invalid use of 'rec' keyword - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1333) + /// (Originally from src/fsharp/FSComp.txt:1351) static member parsInvalidUseOfRec() = (3203, sprintf "Invalid use of 'rec' keyword" ) /// If a union type has more than one case and is a struct, then all fields within the union type must be given unique names. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1334) + /// (Originally from src/fsharp/FSComp.txt:1352) static member tcStructUnionMultiCaseDistinctFields() = (3204, sprintf "If a union type has more than one case and is a struct, then all fields within the union type must be given unique names." ) /// The CallerMemberNameAttribute applied to parameter '%s' will have no effect. It is overridden by the CallerFilePathAttribute. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1335) + /// (Originally from src/fsharp/FSComp.txt:1353) static member CallerMemberNameIsOverriden(a0 : System.String) = (3206, sprintf "The CallerMemberNameAttribute applied to parameter '%s' will have no effect. It is overridden by the CallerFilePathAttribute." a0) /// Invalid use of 'fixed'. 'fixed' may only be used in a declaration of the form 'use x = fixed expr' where the expression is an array, the address of a field, the address of an array element or a string' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1336) + /// (Originally from src/fsharp/FSComp.txt:1354) static member tcFixedNotAllowed() = (3207, sprintf "Invalid use of 'fixed'. 'fixed' may only be used in a declaration of the form 'use x = fixed expr' where the expression is an array, the address of a field, the address of an array element or a string'" ) /// Could not find method System.Runtime.CompilerServices.OffsetToStringData in references when building 'fixed' expression. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1337) + /// (Originally from src/fsharp/FSComp.txt:1355) static member tcCouldNotFindOffsetToStringData() = (3208, sprintf "Could not find method System.Runtime.CompilerServices.OffsetToStringData in references when building 'fixed' expression." ) /// The address of the variable '%s' or a related expression cannot be used at this point. This is to ensure the address of the local value does not escape its scope. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1338) + /// (Originally from src/fsharp/FSComp.txt:1356) static member chkNoByrefAddressOfLocal(a0 : System.String) = (3209, sprintf "The address of the variable '%s' or a related expression cannot be used at this point. This is to ensure the address of the local value does not escape its scope." a0) /// %s is an active pattern and cannot be treated as a discriminated union case with named fields. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1339) + /// (Originally from src/fsharp/FSComp.txt:1357) static member tcNamedActivePattern(a0 : System.String) = (3210, sprintf "%s is an active pattern and cannot be treated as a discriminated union case with named fields." a0) /// The default value does not have the same type as the argument. The DefaultParameterValue attribute and any Optional attribute will be ignored. Note: 'null' needs to be annotated with the correct type, e.g. 'DefaultParameterValue(null:obj)'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1340) + /// (Originally from src/fsharp/FSComp.txt:1358) static member DefaultParameterValueNotAppropriateForArgument() = (3211, sprintf "The default value does not have the same type as the argument. The DefaultParameterValue attribute and any Optional attribute will be ignored. Note: 'null' needs to be annotated with the correct type, e.g. 'DefaultParameterValue(null:obj)'." ) /// The system type '%s' was required but no referenced system DLL contained this type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1341) + /// (Originally from src/fsharp/FSComp.txt:1359) static member tcGlobalsSystemTypeNotFound(a0 : System.String) = (sprintf "The system type '%s' was required but no referenced system DLL contained this type" a0) /// The member '%s' matches multiple overloads of the same method.\nPlease restrict it to one of the following:%s. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1342) + /// (Originally from src/fsharp/FSComp.txt:1360) static member typrelMemberHasMultiplePossibleDispatchSlots(a0 : System.String, a1 : System.String) = (3213, sprintf "The member '%s' matches multiple overloads of the same method.\nPlease restrict it to one of the following:%s." a0 a1) /// Method or object constructor '%s' is not static - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1343) + /// (Originally from src/fsharp/FSComp.txt:1361) static member methodIsNotStatic(a0 : System.String) = (3214, sprintf "Method or object constructor '%s' is not static" a0) /// Unexpected symbol '=' in expression. Did you intend to use 'for x in y .. z do' instead? - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1344) + /// (Originally from src/fsharp/FSComp.txt:1362) static member parsUnexpectedSymbolEqualsInsteadOfIn() = (3215, sprintf "Unexpected symbol '=' in expression. Did you intend to use 'for x in y .. z do' instead?" ) + /// Package manager key '%s' was not registered in %s. Currently registered: %s + /// (Originally from src/fsharp/FSComp.txt:1363) + static member packageManagerUnknown(a0 : System.String, a1 : System.String, a2 : System.String) = (3216, sprintf "Package manager key '%s' was not registered in %s. Currently registered: %s" a0 a1 a2) + /// %s + /// (Originally from src/fsharp/FSComp.txt:1364) + static member packageManagerError(a0 : System.String) = (3217, sprintf "%s" a0) /// Two anonymous record types are from different assemblies '%s' and '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1345) + /// (Originally from src/fsharp/FSComp.txt:1365) static member tcAnonRecdCcuMismatch(a0 : System.String, a1 : System.String) = (sprintf "Two anonymous record types are from different assemblies '%s' and '%s'" a0 a1) - /// Two anonymous record types have mismatched sets of field names '%s' and '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1346) - static member tcAnonRecdFieldNameMismatch(a0 : System.String, a1 : System.String) = (sprintf "Two anonymous record types have mismatched sets of field names '%s' and '%s'" a0 a1) + /// This anonymous record does not exactly match the expected shape. Add the missing fields %s and remove the extra fields %s. + /// (Originally from src/fsharp/FSComp.txt:1366) + static member tcAnonRecdFieldNameMismatch(a0 : System.String, a1 : System.String) = (sprintf "This anonymous record does not exactly match the expected shape. Add the missing fields %s and remove the extra fields %s." a0 a1) + /// This anonymous record does not have enough fields. Add the missing fields %s. + /// (Originally from src/fsharp/FSComp.txt:1367) + static member tcAnonRecdFieldNameSubset(a0 : System.String) = (sprintf "This anonymous record does not have enough fields. Add the missing fields %s." a0) + /// This anonymous record has too many fields. Remove the extra fields %s. + /// (Originally from src/fsharp/FSComp.txt:1368) + static member tcAnonRecdFieldNameSuperset(a0 : System.String) = (sprintf "This anonymous record has too many fields. Remove the extra fields %s." a0) + /// This is the wrong anonymous record. It should have the fields %s. + /// (Originally from src/fsharp/FSComp.txt:1369) + static member tcAnonRecdFieldNameDifferent(a0 : System.String) = (sprintf "This is the wrong anonymous record. It should have the fields %s." a0) /// Indicates a method that either has no implementation in the type in which it is declared or that is virtual and has a default implementation. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1347) + /// (Originally from src/fsharp/FSComp.txt:1370) static member keywordDescriptionAbstract() = (sprintf "Indicates a method that either has no implementation in the type in which it is declared or that is virtual and has a default implementation." ) /// Used in mutually recursive bindings, in property declarations, and with multiple constraints on generic parameters. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1348) + /// (Originally from src/fsharp/FSComp.txt:1371) static member keyworkDescriptionAnd() = (sprintf "Used in mutually recursive bindings, in property declarations, and with multiple constraints on generic parameters." ) /// Used to give the current class object an object name. Also used to give a name to a whole pattern within a pattern match. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1349) + /// (Originally from src/fsharp/FSComp.txt:1372) static member keywordDescriptionAs() = (sprintf "Used to give the current class object an object name. Also used to give a name to a whole pattern within a pattern match." ) /// Used to verify code during debugging. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1350) + /// (Originally from src/fsharp/FSComp.txt:1373) static member keywordDescriptionAssert() = (sprintf "Used to verify code during debugging." ) /// Used as the name of the base class object. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1351) + /// (Originally from src/fsharp/FSComp.txt:1374) static member keywordDescriptionBase() = (sprintf "Used as the name of the base class object." ) /// In verbose syntax, indicates the start of a code block. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1352) + /// (Originally from src/fsharp/FSComp.txt:1375) static member keywordDescriptionBegin() = (sprintf "In verbose syntax, indicates the start of a code block." ) /// In verbose syntax, indicates the start of a class definition. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1353) + /// (Originally from src/fsharp/FSComp.txt:1376) static member keywordDescriptionClass() = (sprintf "In verbose syntax, indicates the start of a class definition." ) /// Indicates an implementation of an abstract method; used together with an abstract method declaration to create a virtual method. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1354) + /// (Originally from src/fsharp/FSComp.txt:1377) static member keywordDescriptionDefault() = (sprintf "Indicates an implementation of an abstract method; used together with an abstract method declaration to create a virtual method." ) /// Used to declare a delegate. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1355) + /// (Originally from src/fsharp/FSComp.txt:1378) static member keywordDescriptionDelegate() = (sprintf "Used to declare a delegate." ) /// Used in looping constructs or to execute imperative code. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1356) + /// (Originally from src/fsharp/FSComp.txt:1379) static member keywordDescriptionDo() = (sprintf "Used in looping constructs or to execute imperative code." ) /// In verbose syntax, indicates the end of a block of code in a looping expression. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1357) + /// (Originally from src/fsharp/FSComp.txt:1380) static member keywordDescriptionDone() = (sprintf "In verbose syntax, indicates the end of a block of code in a looping expression." ) /// Used to convert to a type that is lower in the inheritance chain. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1358) + /// (Originally from src/fsharp/FSComp.txt:1381) static member keywordDescriptionDowncast() = (sprintf "Used to convert to a type that is lower in the inheritance chain." ) /// In a for expression, used when counting in reverse. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1359) + /// (Originally from src/fsharp/FSComp.txt:1382) static member keywordDescriptionDownto() = (sprintf "In a for expression, used when counting in reverse." ) /// Used in conditional branching. A short form of else if. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1360) + /// (Originally from src/fsharp/FSComp.txt:1383) static member keywordDescriptionElif() = (sprintf "Used in conditional branching. A short form of else if." ) /// Used in conditional branching. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1361) + /// (Originally from src/fsharp/FSComp.txt:1384) static member keywordDescriptionElse() = (sprintf "Used in conditional branching." ) /// In type definitions and type extensions, indicates the end of a section of member definitions. In verbose syntax, used to specify the end of a code block that starts with the begin keyword. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1362) + /// (Originally from src/fsharp/FSComp.txt:1385) static member keywordDescriptionEnd() = (sprintf "In type definitions and type extensions, indicates the end of a section of member definitions. In verbose syntax, used to specify the end of a code block that starts with the begin keyword." ) /// Used to declare an exception type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1363) + /// (Originally from src/fsharp/FSComp.txt:1386) static member keywordDescriptionException() = (sprintf "Used to declare an exception type." ) /// Indicates that a declared program element is defined in another binary or assembly. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1364) + /// (Originally from src/fsharp/FSComp.txt:1387) static member keywordDescriptionExtern() = (sprintf "Indicates that a declared program element is defined in another binary or assembly." ) /// Used as a Boolean literal. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1365) + /// (Originally from src/fsharp/FSComp.txt:1388) static member keywordDescriptionTrueFalse() = (sprintf "Used as a Boolean literal." ) /// Used together with try to introduce a block of code that executes regardless of whether an exception occurs. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1366) + /// (Originally from src/fsharp/FSComp.txt:1389) static member keywordDescriptionFinally() = (sprintf "Used together with try to introduce a block of code that executes regardless of whether an exception occurs." ) /// Used in looping constructs. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1367) + /// (Originally from src/fsharp/FSComp.txt:1390) static member keywordDescriptionFor() = (sprintf "Used in looping constructs." ) /// Used in lambda expressions, also known as anonymous functions. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1368) + /// (Originally from src/fsharp/FSComp.txt:1391) static member keywordDescriptionFun() = (sprintf "Used in lambda expressions, also known as anonymous functions." ) /// Used as a shorter alternative to the fun keyword and a match expression in a lambda expression that has pattern matching on a single argument. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1369) + /// (Originally from src/fsharp/FSComp.txt:1392) static member keywordDescriptionFunction() = (sprintf "Used as a shorter alternative to the fun keyword and a match expression in a lambda expression that has pattern matching on a single argument." ) /// Used to reference the top-level .NET namespace. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1370) + /// (Originally from src/fsharp/FSComp.txt:1393) static member keywordDescriptionGlobal() = (sprintf "Used to reference the top-level .NET namespace." ) /// Used in conditional branching constructs. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1371) + /// (Originally from src/fsharp/FSComp.txt:1394) static member keywordDescriptionIf() = (sprintf "Used in conditional branching constructs." ) /// Used for sequence expressions and, in verbose syntax, to separate expressions from bindings. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1372) + /// (Originally from src/fsharp/FSComp.txt:1395) static member keywordDescriptionIn() = (sprintf "Used for sequence expressions and, in verbose syntax, to separate expressions from bindings." ) /// Used to specify a base class or base interface. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1373) + /// (Originally from src/fsharp/FSComp.txt:1396) static member keywordDescriptionInherit() = (sprintf "Used to specify a base class or base interface." ) /// Used to indicate a function that should be integrated directly into the caller's code. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1374) + /// (Originally from src/fsharp/FSComp.txt:1397) static member keywordDescriptionInline() = (sprintf "Used to indicate a function that should be integrated directly into the caller's code." ) /// Used to declare and implement interfaces. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1375) + /// (Originally from src/fsharp/FSComp.txt:1398) static member keywordDescriptionInterface() = (sprintf "Used to declare and implement interfaces." ) /// Used to specify that a member is visible inside an assembly but not outside it. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1376) + /// (Originally from src/fsharp/FSComp.txt:1399) static member keywordDescriptionInternal() = (sprintf "Used to specify that a member is visible inside an assembly but not outside it." ) /// Used to specify a computation that is to be performed only when a result is needed. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1377) + /// (Originally from src/fsharp/FSComp.txt:1400) static member keywordDescriptionLazy() = (sprintf "Used to specify a computation that is to be performed only when a result is needed." ) /// Used to associate, or bind, a name to a value or function. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1378) + /// (Originally from src/fsharp/FSComp.txt:1401) static member keywordDescriptionLet() = (sprintf "Used to associate, or bind, a name to a value or function." ) /// Used in computation expressions to bind a name to the result of another computation expression. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1379) + /// (Originally from src/fsharp/FSComp.txt:1402) static member keywordDescriptionLetBang() = (sprintf "Used in computation expressions to bind a name to the result of another computation expression." ) /// Used to branch by comparing a value to a pattern. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1380) + /// (Originally from src/fsharp/FSComp.txt:1403) static member keywordDescriptionMatch() = (sprintf "Used to branch by comparing a value to a pattern." ) /// Used in computation expressions to pattern match directly over the result of another computation expression. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1381) + /// (Originally from src/fsharp/FSComp.txt:1404) static member keywordDescriptionMatchBang() = (sprintf "Used in computation expressions to pattern match directly over the result of another computation expression." ) /// Used to declare a property or method in an object type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1382) + /// (Originally from src/fsharp/FSComp.txt:1405) static member keywordDescriptionMember() = (sprintf "Used to declare a property or method in an object type." ) /// Used to associate a name with a group of related types, values, and functions, to logically separate it from other code. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1383) + /// (Originally from src/fsharp/FSComp.txt:1406) static member keywordDescriptionModule() = (sprintf "Used to associate a name with a group of related types, values, and functions, to logically separate it from other code." ) /// Used to declare a variable, that is, a value that can be changed. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1384) + /// (Originally from src/fsharp/FSComp.txt:1407) static member keywordDescriptionMutable() = (sprintf "Used to declare a variable, that is, a value that can be changed." ) /// Used to associate a name with a group of related types and modules, to logically separate it from other code. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1385) + /// (Originally from src/fsharp/FSComp.txt:1408) static member keywordDescriptionNamespace() = (sprintf "Used to associate a name with a group of related types and modules, to logically separate it from other code." ) /// Used to declare, define, or invoke a constructor that creates or that can create an object. Also used in generic parameter constraints to indicate that a type must have a certain constructor. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1386) + /// (Originally from src/fsharp/FSComp.txt:1409) static member keywordDescriptionNew() = (sprintf "Used to declare, define, or invoke a constructor that creates or that can create an object. Also used in generic parameter constraints to indicate that a type must have a certain constructor." ) /// Not actually a keyword. However, not struct in combination is used as a generic parameter constraint. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1387) + /// (Originally from src/fsharp/FSComp.txt:1410) static member keywordDescriptionNot() = (sprintf "Not actually a keyword. However, not struct in combination is used as a generic parameter constraint." ) /// Indicates the absence of an object. Also used in generic parameter constraints. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1388) + /// (Originally from src/fsharp/FSComp.txt:1411) static member keywordDescriptionNull() = (sprintf "Indicates the absence of an object. Also used in generic parameter constraints." ) /// Used in discriminated unions to indicate the type of categories of values, and in delegate and exception declarations. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1389) + /// (Originally from src/fsharp/FSComp.txt:1412) static member keywordDescriptionOf() = (sprintf "Used in discriminated unions to indicate the type of categories of values, and in delegate and exception declarations." ) /// Used to make the contents of a namespace or module available without qualification. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1390) + /// (Originally from src/fsharp/FSComp.txt:1413) static member keywordDescriptionOpen() = (sprintf "Used to make the contents of a namespace or module available without qualification." ) /// Used with Boolean conditions as a Boolean or operator. Equivalent to ||. Also used in member constraints. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1391) + /// (Originally from src/fsharp/FSComp.txt:1414) static member keywordDescriptionOr() = (sprintf "Used with Boolean conditions as a Boolean or operator. Equivalent to ||. Also used in member constraints." ) /// Used to implement a version of an abstract or virtual method that differs from the base version. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1392) + /// (Originally from src/fsharp/FSComp.txt:1415) static member keywordDescriptionOverride() = (sprintf "Used to implement a version of an abstract or virtual method that differs from the base version." ) /// Restricts access to a member to code in the same type or module. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1393) + /// (Originally from src/fsharp/FSComp.txt:1416) static member keywordDescriptionPrivate() = (sprintf "Restricts access to a member to code in the same type or module." ) /// Allows access to a member from outside the type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1394) + /// (Originally from src/fsharp/FSComp.txt:1417) static member keywordDescriptionPublic() = (sprintf "Allows access to a member from outside the type." ) /// Used to indicate that a function is recursive. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1395) + /// (Originally from src/fsharp/FSComp.txt:1418) static member keywordDescriptionRec() = (sprintf "Used to indicate that a function is recursive." ) /// Used to provide a value for the result of the containing computation expression. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1396) + /// (Originally from src/fsharp/FSComp.txt:1419) static member keywordDescriptionReturn() = (sprintf "Used to provide a value for the result of the containing computation expression." ) /// Used to provide a value for the result of the containing computation expression, where that value itself comes from the result another computation expression. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1397) + /// (Originally from src/fsharp/FSComp.txt:1420) static member keywordDescriptionReturnBang() = (sprintf "Used to provide a value for the result of the containing computation expression, where that value itself comes from the result another computation expression." ) /// Used in query expressions to specify what fields or columns to extract. Note that this is a contextual keyword, which means that it is not actually a reserved word and it only acts like a keyword in appropriate context. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1398) + /// (Originally from src/fsharp/FSComp.txt:1421) static member keywordDescriptionSelect() = (sprintf "Used in query expressions to specify what fields or columns to extract. Note that this is a contextual keyword, which means that it is not actually a reserved word and it only acts like a keyword in appropriate context." ) /// Used to indicate a method or property that can be called without an instance of a type, or a value member that is shared among all instances of a type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1399) + /// (Originally from src/fsharp/FSComp.txt:1422) static member keywordDescriptionStatic() = (sprintf "Used to indicate a method or property that can be called without an instance of a type, or a value member that is shared among all instances of a type." ) /// Used to declare a structure type. Also used in generic parameter constraints. Used for OCaml compatibility in module definitions. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1400) + /// (Originally from src/fsharp/FSComp.txt:1423) static member keywordDescriptionStruct() = (sprintf "Used to declare a structure type. Also used in generic parameter constraints. Used for OCaml compatibility in module definitions." ) /// Used in conditional expressions. Also used to perform side effects after object construction. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1401) + /// (Originally from src/fsharp/FSComp.txt:1424) static member keywordDescriptionThen() = (sprintf "Used in conditional expressions. Also used to perform side effects after object construction." ) /// Used in for loops to indicate a range. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1402) + /// (Originally from src/fsharp/FSComp.txt:1425) static member keywordDescriptionTo() = (sprintf "Used in for loops to indicate a range." ) /// Used to introduce a block of code that might generate an exception. Used together with with or finally. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1403) + /// (Originally from src/fsharp/FSComp.txt:1426) static member keywordDescriptionTry() = (sprintf "Used to introduce a block of code that might generate an exception. Used together with with or finally." ) /// Used to declare a class, record, structure, discriminated union, enumeration type, unit of measure, or type abbreviation. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1404) + /// (Originally from src/fsharp/FSComp.txt:1427) static member keywordDescriptionType() = (sprintf "Used to declare a class, record, structure, discriminated union, enumeration type, unit of measure, or type abbreviation." ) /// Used to convert to a type that is higher in the inheritance chain. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1405) + /// (Originally from src/fsharp/FSComp.txt:1428) static member keywordDescriptionUpcast() = (sprintf "Used to convert to a type that is higher in the inheritance chain." ) /// Used instead of let for values that implement IDisposable - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1406) + /// (Originally from src/fsharp/FSComp.txt:1429) static member keywordDescriptionUse() = (sprintf "Used instead of let for values that implement IDisposable" ) /// Used instead of let! in computation expressions for computation expression results that implement IDisposable. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1407) + /// (Originally from src/fsharp/FSComp.txt:1430) static member keywordDescriptionUseBang() = (sprintf "Used instead of let! in computation expressions for computation expression results that implement IDisposable." ) /// Used in a signature to indicate a value, or in a type to declare a member, in limited situations. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1408) + /// (Originally from src/fsharp/FSComp.txt:1431) static member keywordDescriptionVal() = (sprintf "Used in a signature to indicate a value, or in a type to declare a member, in limited situations." ) /// Indicates the .NET void type. Used when interoperating with other .NET languages. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1409) + /// (Originally from src/fsharp/FSComp.txt:1432) static member keywordDescriptionVoid() = (sprintf "Indicates the .NET void type. Used when interoperating with other .NET languages." ) /// Used for Boolean conditions (when guards) on pattern matches and to introduce a constraint clause for a generic type parameter. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1410) + /// (Originally from src/fsharp/FSComp.txt:1433) static member keywordDescriptionWhen() = (sprintf "Used for Boolean conditions (when guards) on pattern matches and to introduce a constraint clause for a generic type parameter." ) /// Introduces a looping construct. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1411) + /// (Originally from src/fsharp/FSComp.txt:1434) static member keywordDescriptionWhile() = (sprintf "Introduces a looping construct." ) /// Used together with the match keyword in pattern matching expressions. Also used in object expressions, record copying expressions, and type extensions to introduce member definitions, and to introduce exception handlers. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1412) + /// (Originally from src/fsharp/FSComp.txt:1435) static member keywordDescriptionWith() = (sprintf "Used together with the match keyword in pattern matching expressions. Also used in object expressions, record copying expressions, and type extensions to introduce member definitions, and to introduce exception handlers." ) /// Used in a sequence expression to produce a value for a sequence. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1413) + /// (Originally from src/fsharp/FSComp.txt:1436) static member keywordDescriptionYield() = (sprintf "Used in a sequence expression to produce a value for a sequence." ) /// Used in a computation expression to append the result of a given computation expression to a collection of results for the containing computation expression. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1414) + /// (Originally from src/fsharp/FSComp.txt:1437) static member keywordDescriptionYieldBang() = (sprintf "Used in a computation expression to append the result of a given computation expression to a collection of results for the containing computation expression." ) /// In function types, delimits arguments and return values. Yields an expression (in sequence expressions); equivalent to the yield keyword. Used in match expressions - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1415) + /// (Originally from src/fsharp/FSComp.txt:1438) static member keywordDescriptionRightArrow() = (sprintf "In function types, delimits arguments and return values. Yields an expression (in sequence expressions); equivalent to the yield keyword. Used in match expressions" ) /// Assigns a value to a variable. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1416) + /// (Originally from src/fsharp/FSComp.txt:1439) static member keywordDescriptionLeftArrow() = (sprintf "Assigns a value to a variable." ) /// Converts a type to type that is higher in the hierarchy. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1417) + /// (Originally from src/fsharp/FSComp.txt:1440) static member keywordDescriptionCast() = (sprintf "Converts a type to type that is higher in the hierarchy." ) /// Converts a type to a type that is lower in the hierarchy. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1418) + /// (Originally from src/fsharp/FSComp.txt:1441) static member keywordDescriptionDynamicCast() = (sprintf "Converts a type to a type that is lower in the hierarchy." ) /// Delimits a typed code quotation. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1419) + /// (Originally from src/fsharp/FSComp.txt:1442) static member keywordDescriptionTypedQuotation() = (sprintf "Delimits a typed code quotation." ) /// Delimits a untyped code quotation. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1420) + /// (Originally from src/fsharp/FSComp.txt:1443) static member keywordDescriptionUntypedQuotation() = (sprintf "Delimits a untyped code quotation." ) /// %s '%s' not found in assembly '%s'. A possible cause may be a version incompatibility. You may need to explicitly reference the correct version of this assembly to allow all referenced components to use the correct version. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1421) + /// (Originally from src/fsharp/FSComp.txt:1444) static member itemNotFoundDuringDynamicCodeGen(a0 : System.String, a1 : System.String, a2 : System.String) = (3216, sprintf "%s '%s' not found in assembly '%s'. A possible cause may be a version incompatibility. You may need to explicitly reference the correct version of this assembly to allow all referenced components to use the correct version." a0 a1 a2) /// %s '%s' not found in type '%s' from assembly '%s'. A possible cause may be a version incompatibility. You may need to explicitly reference the correct version of this assembly to allow all referenced components to use the correct version. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1422) + /// (Originally from src/fsharp/FSComp.txt:1445) static member itemNotFoundInTypeDuringDynamicCodeGen(a0 : System.String, a1 : System.String, a2 : System.String, a3 : System.String) = (3216, sprintf "%s '%s' not found in type '%s' from assembly '%s'. A possible cause may be a version incompatibility. You may need to explicitly reference the correct version of this assembly to allow all referenced components to use the correct version." a0 a1 a2 a3) /// is - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1423) + /// (Originally from src/fsharp/FSComp.txt:1446) static member descriptionWordIs() = (sprintf "is" ) /// This value is not a function and cannot be applied. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1424) + /// (Originally from src/fsharp/FSComp.txt:1447) static member notAFunction() = (sprintf "This value is not a function and cannot be applied." ) /// This value is not a function and cannot be applied. Did you intend to access the indexer via %s.[index] instead? - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1425) + /// (Originally from src/fsharp/FSComp.txt:1448) static member notAFunctionButMaybeIndexerWithName(a0 : System.String) = (sprintf "This value is not a function and cannot be applied. Did you intend to access the indexer via %s.[index] instead?" a0) /// This expression is not a function and cannot be applied. Did you intend to access the indexer via expr.[index] instead? - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1426) + /// (Originally from src/fsharp/FSComp.txt:1449) static member notAFunctionButMaybeIndexer() = (sprintf "This expression is not a function and cannot be applied. Did you intend to access the indexer via expr.[index] instead?" ) - /// - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1427) + /// + /// (Originally from src/fsharp/FSComp.txt:1450) static member notAFunctionButMaybeIndexerErrorCode() = (3217, sprintf "" ) /// This value is not a function and cannot be applied. Did you forget to terminate a declaration? - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1428) + /// (Originally from src/fsharp/FSComp.txt:1451) static member notAFunctionButMaybeDeclaration() = (sprintf "This value is not a function and cannot be applied. Did you forget to terminate a declaration?" ) /// The argument names in the signature '%s' and implementation '%s' do not match. The argument name from the signature file will be used. This may cause problems when debugging or profiling. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1429) + /// (Originally from src/fsharp/FSComp.txt:1452) static member ArgumentsInSigAndImplMismatch(a0 : System.String, a1 : System.String) = (3218, sprintf "The argument names in the signature '%s' and implementation '%s' do not match. The argument name from the signature file will be used. This may cause problems when debugging or profiling." a0 a1) /// An error occurred while reading the F# metadata of assembly '%s'. A reserved construct was utilized. You may need to upgrade your F# compiler or use an earlier version of the assembly that doesn't make use of a specific construct. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1430) + /// (Originally from src/fsharp/FSComp.txt:1453) static member pickleUnexpectedNonZero(a0 : System.String) = (3219, sprintf "An error occurred while reading the F# metadata of assembly '%s'. A reserved construct was utilized. You may need to upgrade your F# compiler or use an earlier version of the assembly that doesn't make use of a specific construct." a0) /// This method or property is not normally used from F# code, use an explicit tuple pattern for deconstruction instead. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1431) + /// (Originally from src/fsharp/FSComp.txt:1454) static member tcTupleMemberNotNormallyUsed() = (3220, sprintf "This method or property is not normally used from F# code, use an explicit tuple pattern for deconstruction instead." ) /// This expression returns a value of type '%s' but is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to use the expression as a value in the sequence then use an explicit 'yield'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1432) + /// (Originally from src/fsharp/FSComp.txt:1455) static member implicitlyDiscardedInSequenceExpression(a0 : System.String) = (3221, sprintf "This expression returns a value of type '%s' but is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to use the expression as a value in the sequence then use an explicit 'yield'." a0) /// This expression returns a value of type '%s' but is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to use the expression as a value in the sequence then use an explicit 'yield!'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1433) + /// (Originally from src/fsharp/FSComp.txt:1456) static member implicitlyDiscardedSequenceInSequenceExpression(a0 : System.String) = (3222, sprintf "This expression returns a value of type '%s' but is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to use the expression as a value in the sequence then use an explicit 'yield!'." a0) /// The file '%s' changed on disk unexpectedly, please reload. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1434) + /// (Originally from src/fsharp/FSComp.txt:1457) static member ilreadFileChanged(a0 : System.String) = (3223, sprintf "The file '%s' changed on disk unexpectedly, please reload." a0) /// The byref pointer is readonly, so this write is not permitted. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1435) + /// (Originally from src/fsharp/FSComp.txt:1458) static member writeToReadOnlyByref() = (3224, sprintf "The byref pointer is readonly, so this write is not permitted." ) /// A ReadOnly attribute has been applied to a struct type with a mutable field. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1436) + /// (Originally from src/fsharp/FSComp.txt:1459) static member readOnlyAttributeOnStructWithMutableField() = (3225, sprintf "A ReadOnly attribute has been applied to a struct type with a mutable field." ) /// A byref pointer returned by a function or method is implicitly dereferenced as of F# 4.5. To acquire the return value as a pointer, use the address-of operator, e.g. '&f(x)' or '&obj.Method(arg1, arg2)'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1437) + /// (Originally from src/fsharp/FSComp.txt:1460) static member tcByrefReturnImplicitlyDereferenced() = (3226, sprintf "A byref pointer returned by a function or method is implicitly dereferenced as of F# 4.5. To acquire the return value as a pointer, use the address-of operator, e.g. '&f(x)' or '&obj.Method(arg1, arg2)'." ) /// A type annotated with IsByRefLike must also be a struct. Consider adding the [] attribute to the type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1438) + /// (Originally from src/fsharp/FSComp.txt:1461) static member tcByRefLikeNotStruct() = (3227, sprintf "A type annotated with IsByRefLike must also be a struct. Consider adding the [] attribute to the type." ) /// The address of a value returned from the expression cannot be used at this point. This is to ensure the address of the local value does not escape its scope. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1439) + /// (Originally from src/fsharp/FSComp.txt:1462) static member chkNoByrefAddressOfValueFromExpression() = (3228, sprintf "The address of a value returned from the expression cannot be used at this point. This is to ensure the address of the local value does not escape its scope." ) /// This value can't be assigned because the target '%s' may refer to non-stack-local memory, while the expression being assigned is assessed to potentially refer to stack-local memory. This is to help prevent pointers to stack-bound memory escaping their scope. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1440) + /// (Originally from src/fsharp/FSComp.txt:1463) static member chkNoWriteToLimitedSpan(a0 : System.String) = (3229, sprintf "This value can't be assigned because the target '%s' may refer to non-stack-local memory, while the expression being assigned is assessed to potentially refer to stack-local memory. This is to help prevent pointers to stack-bound memory escaping their scope." a0) /// A value defined in a module must be mutable in order to take its address, e.g. 'let mutable x = ...' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1441) + /// (Originally from src/fsharp/FSComp.txt:1464) static member tastValueMustBeLocal() = (3230, sprintf "A value defined in a module must be mutable in order to take its address, e.g. 'let mutable x = ...'" ) /// A type annotated with IsReadOnly must also be a struct. Consider adding the [] attribute to the type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1442) + /// (Originally from src/fsharp/FSComp.txt:1465) static member tcIsReadOnlyNotStruct() = (3231, sprintf "A type annotated with IsReadOnly must also be a struct. Consider adding the [] attribute to the type." ) /// Struct members cannot return the address of fields of the struct by reference - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1443) + /// (Originally from src/fsharp/FSComp.txt:1466) static member chkStructsMayNotReturnAddressesOfContents() = (3232, sprintf "Struct members cannot return the address of fields of the struct by reference" ) /// The function or method call cannot be used at this point, because one argument that is a byref of a non-stack-local Span or IsByRefLike type is used with another argument that is a stack-local Span or IsByRefLike type. This is to ensure the address of the local value does not escape its scope. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1444) + /// (Originally from src/fsharp/FSComp.txt:1467) static member chkNoByrefLikeFunctionCall() = (3233, sprintf "The function or method call cannot be used at this point, because one argument that is a byref of a non-stack-local Span or IsByRefLike type is used with another argument that is a stack-local Span or IsByRefLike type. This is to ensure the address of the local value does not escape its scope." ) /// The Span or IsByRefLike variable '%s' cannot be used at this point. This is to ensure the address of the local value does not escape its scope. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1445) + /// (Originally from src/fsharp/FSComp.txt:1468) static member chkNoSpanLikeVariable(a0 : System.String) = (3234, sprintf "The Span or IsByRefLike variable '%s' cannot be used at this point. This is to ensure the address of the local value does not escape its scope." a0) /// A Span or IsByRefLike value returned from the expression cannot be used at ths point. This is to ensure the address of the local value does not escape its scope. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1446) + /// (Originally from src/fsharp/FSComp.txt:1469) static member chkNoSpanLikeValueFromExpression() = (3235, sprintf "A Span or IsByRefLike value returned from the expression cannot be used at ths point. This is to ensure the address of the local value does not escape its scope." ) /// Cannot take the address of the value returned from the expression. Assign the returned value to a let-bound value before taking the address. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1447) + /// (Originally from src/fsharp/FSComp.txt:1470) static member tastCantTakeAddressOfExpression() = (3236, sprintf "Cannot take the address of the value returned from the expression. Assign the returned value to a let-bound value before taking the address." ) /// Cannot call the byref extension method '%s. The first parameter requires the value to be mutable or a non-readonly byref type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1448) + /// (Originally from src/fsharp/FSComp.txt:1471) static member tcCannotCallExtensionMethodInrefToByref(a0 : System.String) = (3237, sprintf "Cannot call the byref extension method '%s. The first parameter requires the value to be mutable or a non-readonly byref type." a0) /// Byref types are not allowed to have optional type extensions. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1449) + /// (Originally from src/fsharp/FSComp.txt:1472) static member tcByrefsMayNotHaveTypeExtensions() = (3238, sprintf "Byref types are not allowed to have optional type extensions." ) /// Cannot partially apply the extension method '%s' because the first parameter is a byref type. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1450) + /// (Originally from src/fsharp/FSComp.txt:1473) static member tcCannotPartiallyApplyExtensionMethodForByref(a0 : System.String) = (3239, sprintf "Cannot partially apply the extension method '%s' because the first parameter is a byref type." a0) /// This type does not inherit Attribute, it will not work correctly with other .NET languages. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1451) + /// (Originally from src/fsharp/FSComp.txt:1474) static member tcTypeDoesNotInheritAttribute() = (3242, sprintf "This type does not inherit Attribute, it will not work correctly with other .NET languages." ) /// Invalid anonymous record expression - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1452) + /// (Originally from src/fsharp/FSComp.txt:1475) static member parsInvalidAnonRecdExpr() = (3243, sprintf "Invalid anonymous record expression" ) /// Invalid anonymous record type - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1453) + /// (Originally from src/fsharp/FSComp.txt:1476) static member parsInvalidAnonRecdType() = (3244, sprintf "Invalid anonymous record type" ) /// The input to a copy-and-update expression that creates an anonymous record must be either an anonymous record or a record - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1454) + /// (Originally from src/fsharp/FSComp.txt:1477) static member tcCopyAndUpdateNeedsRecordType() = (3245, sprintf "The input to a copy-and-update expression that creates an anonymous record must be either an anonymous record or a record" ) + /// Attributes cannot be applied to type extensions. + /// (Originally from src/fsharp/FSComp.txt:1478) + static member tcAugmentationsCannotHaveAttributes() = (3246, sprintf "Attributes cannot be applied to type extensions." ) + /// The dependency manager extension %s could not be loaded. Message: %s + /// (Originally from src/fsharp/FSComp.txt:1479) + static member couldNotLoadDependencyManagerExtension(a0 : System.String, a1 : System.String) = (3247, sprintf "The dependency manager extension %s could not be loaded. Message: %s" a0 a1) + /// Expression does not have a name. + /// (Originally from src/fsharp/FSComp.txt:1480) + static member expressionHasNoName() = (3250, sprintf "Expression does not have a name." ) + /// Using the 'nameof' operator as a first-class function value is not permitted. + /// (Originally from src/fsharp/FSComp.txt:1481) + static member chkNoFirstClassNameOf() = (3251, sprintf "Using the 'nameof' operator as a first-class function value is not permitted." ) /// The parameter '%s' has an invalid type '%s'. This is not permitted by the rules of Common IL. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1455) + /// (Originally from src/fsharp/FSComp.txt:1482) static member chkInvalidFunctionParameterType(a0 : System.String, a1 : System.String) = (3300, sprintf "The parameter '%s' has an invalid type '%s'. This is not permitted by the rules of Common IL." a0 a1) /// The function or method has an invalid return type '%s'. This is not permitted by the rules of Common IL. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/FSComp.txt:1456) + /// (Originally from src/fsharp/FSComp.txt:1483) static member chkInvalidFunctionReturnType(a0 : System.String) = (3301, sprintf "The function or method has an invalid return type '%s'. This is not permitted by the rules of Common IL." a0) + /// The package management feature requires language version 5.0 use /langversion:preview + /// (Originally from src/fsharp/FSComp.txt:1484) + static member packageManagementRequiresVFive() = (3302, sprintf "The package management feature requires language version 5.0 use /langversion:preview" ) + /// From the end slicing with requires language version 5.0, use /langversion:preview. + /// (Originally from src/fsharp/FSComp.txt:1485) + static member fromEndSlicingRequiresVFive() = (3303, sprintf "From the end slicing with requires language version 5.0, use /langversion:preview." ) + /// The 'let! ... and! ...' construct may only be used if the computation expression builder defines either a '%s' method or appropriate 'MergeSource' and 'Bind' methods + /// (Originally from src/fsharp/FSComp.txt:1486) + static member tcRequireMergeSourcesOrBindN(a0 : System.String) = (3343, sprintf "The 'let! ... and! ...' construct may only be used if the computation expression builder defines either a '%s' method or appropriate 'MergeSource' and 'Bind' methods" a0) + /// This feature is not supported in this version of F#. You may need to add /langversion:preview to use this feature. + /// (Originally from src/fsharp/FSComp.txt:1487) + static member tcAndBangNotSupported() = (3344, sprintf "This feature is not supported in this version of F#. You may need to add /langversion:preview to use this feature." ) + /// use! may not be combined with and! + /// (Originally from src/fsharp/FSComp.txt:1488) + static member tcInvalidUseBangBindingNoAndBangs() = (3345, sprintf "use! may not be combined with and!" ) + /// Feature '%s' is not available in F# %s. Please use language version %s or greater. + /// (Originally from src/fsharp/FSComp.txt:1489) + static member chkFeatureNotLanguageSupported(a0 : System.String, a1 : System.String, a2 : System.String) = (3350, sprintf "Feature '%s' is not available in F# %s. Please use language version %s or greater." a0 a1 a2) + /// Feature '%s' is not supported by target runtime. + /// (Originally from src/fsharp/FSComp.txt:1490) + static member chkFeatureNotRuntimeSupported(a0 : System.String) = (3351, sprintf "Feature '%s' is not supported by target runtime." a0) + /// Interface member '%s' does not have a most specific implementation. + /// (Originally from src/fsharp/FSComp.txt:1491) + static member typrelInterfaceMemberNoMostSpecificImplementation(a0 : System.String) = (3352, sprintf "Interface member '%s' does not have a most specific implementation." a0) + /// Use reference assemblies for .NET framework references when available (Enabled by default). + /// (Originally from src/fsharp/FSComp.txt:1492) + static member useSdkRefs() = (sprintf "Use reference assemblies for .NET framework references when available (Enabled by default)." ) + /// %s for F# %s + /// (Originally from src/fsharp/FSComp.txt:1493) + static member fSharpBannerVersion(a0 : System.String, a1 : System.String) = (sprintf "%s for F# %s" a0 a1) + /// Display the allowed values for language version, specify language version such as 'latest' or 'preview' + /// (Originally from src/fsharp/FSComp.txt:1494) + static member optsLangVersion() = (sprintf "Display the allowed values for language version, specify language version such as 'latest' or 'preview'" ) + /// Supported language versions: + /// (Originally from src/fsharp/FSComp.txt:1495) + static member optsSupportedLangVersions() = (sprintf "Supported language versions:" ) + /// Stream does not begin with a null resource and is not in '.RES' format. + /// (Originally from src/fsharp/FSComp.txt:1496) + static member nativeResourceFormatError() = (sprintf "Stream does not begin with a null resource and is not in '.RES' format." ) + /// Resource header beginning at offset %s is malformed. + /// (Originally from src/fsharp/FSComp.txt:1497) + static member nativeResourceHeaderMalformed(a0 : System.String) = (sprintf "Resource header beginning at offset %s is malformed." a0) + /// - %s + /// (Originally from src/fsharp/FSComp.txt:1498) + static member formatDashItem(a0 : System.String) = (sprintf " - %s" a0) + /// single underscore pattern + /// (Originally from src/fsharp/FSComp.txt:1499) + static member featureSingleUnderscorePattern() = (sprintf "single underscore pattern" ) + /// wild card in for loop + /// (Originally from src/fsharp/FSComp.txt:1500) + static member featureWildCardInForLoop() = (sprintf "wild card in for loop" ) + /// whitespace relexation + /// (Originally from src/fsharp/FSComp.txt:1501) + static member featureRelaxWhitespace() = (sprintf "whitespace relexation" ) + /// nameof + /// (Originally from src/fsharp/FSComp.txt:1502) + static member featureNameOf() = (sprintf "nameof" ) + /// implicit yield + /// (Originally from src/fsharp/FSComp.txt:1503) + static member featureImplicitYield() = (sprintf "implicit yield" ) + /// open static classes + /// (Originally from src/fsharp/FSComp.txt:1504) + static member featureOpenStaticClasses() = (sprintf "open static classes" ) + /// dotless float32 literal + /// (Originally from src/fsharp/FSComp.txt:1505) + static member featureDotlessFloat32Literal() = (sprintf "dotless float32 literal" ) + /// package management + /// (Originally from src/fsharp/FSComp.txt:1506) + static member featurePackageManagement() = (sprintf "package management" ) + /// from-end slicing + /// (Originally from src/fsharp/FSComp.txt:1507) + static member featureFromEndSlicing() = (sprintf "from-end slicing" ) + /// fixed-index slice 3d/4d + /// (Originally from src/fsharp/FSComp.txt:1508) + static member featureFixedIndexSlice3d4d() = (sprintf "fixed-index slice 3d/4d" ) + /// applicative computation expressions + /// (Originally from src/fsharp/FSComp.txt:1509) + static member featureAndBang() = (sprintf "applicative computation expressions" ) + /// nullable optional interop + /// (Originally from src/fsharp/FSComp.txt:1510) + static member featureNullableOptionalInterop() = (sprintf "nullable optional interop" ) + /// default interface member consumption + /// (Originally from src/fsharp/FSComp.txt:1511) + static member featureDefaultInterfaceMemberConsumption() = (sprintf "default interface member consumption" ) diff --git a/src/fcs-fable/codegen/FSIstrings.fs b/src/fcs-fable/codegen/FSIstrings.fs index ca5480cc8d..37b04c3044 100644 --- a/src/fcs-fable/codegen/FSIstrings.fs +++ b/src/fcs-fable/codegen/FSIstrings.fs @@ -1,162 +1,168 @@ -// This is a generated file; the original input is '/Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt' +// This is a generated file; the original input is 'src/fsharp/fsi/FSIstrings.txt' namespace FSIstrings type internal SR private() = /// Stopped due to error\n - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:2) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:2) static member stoppedDueToError() = (sprintf "Stopped due to error\n" ) /// Usage: %s [script.fsx []] - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:3) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:3) static member fsiUsage(a0 : System.String) = (sprintf "Usage: %s [script.fsx []]" a0) /// - INPUT FILES - - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:4) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:4) static member fsiInputFiles() = (sprintf "- INPUT FILES -" ) /// - CODE GENERATION - - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:5) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:5) static member fsiCodeGeneration() = (sprintf "- CODE GENERATION -" ) /// - ERRORS AND WARNINGS - - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:6) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:6) static member fsiErrorsAndWarnings() = (sprintf "- ERRORS AND WARNINGS -" ) /// - LANGUAGE - - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:7) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:7) static member fsiLanguage() = (sprintf "- LANGUAGE -" ) /// - MISCELLANEOUS - - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:8) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:8) static member fsiMiscellaneous() = (sprintf "- MISCELLANEOUS -" ) /// - ADVANCED - - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:9) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:9) static member fsiAdvanced() = (sprintf "- ADVANCED -" ) /// Exception raised when starting remoting server.\n%s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:10) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:10) static member fsiExceptionRaisedStartingServer(a0 : System.String) = (sprintf "Exception raised when starting remoting server.\n%s" a0) /// Use the given file on startup as initial input - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:11) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:11) static member fsiUse() = (sprintf "Use the given file on startup as initial input" ) /// #load the given file on startup - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:12) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:12) static member fsiLoad() = (sprintf "#load the given file on startup" ) /// Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:13) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:13) static member fsiRemaining() = (sprintf "Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs" ) /// Display this usage message (Short form: -?) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:14) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:14) static member fsiHelp() = (sprintf "Display this usage message (Short form: -?)" ) /// Exit fsi after loading the files or running the .fsx script given on the command line - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:15) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:15) static member fsiExec() = (sprintf "Exit fsi after loading the files or running the .fsx script given on the command line" ) /// Execute interactions on a Windows Forms event loop (on by default) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:16) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:16) static member fsiGui() = (sprintf "Execute interactions on a Windows Forms event loop (on by default)" ) /// Suppress fsi writing to stdout - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:17) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:17) static member fsiQuiet() = (sprintf "Suppress fsi writing to stdout" ) /// Support TAB completion in console (on by default) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:18) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:18) static member fsiReadline() = (sprintf "Support TAB completion in console (on by default)" ) /// Emit debug information in quotations - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:19) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:19) static member fsiEmitDebugInfoInQuotations() = (sprintf "Emit debug information in quotations" ) /// For help type #help;; - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:20) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:20) static member fsiBanner3() = (sprintf "For help type #help;;" ) /// A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:21) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:21) static member fsiConsoleProblem() = (sprintf "A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'." ) /// '%s' is not a valid assembly name - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:22) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:22) static member fsiInvalidAssembly(a0 : System.String) = (2301, sprintf "'%s' is not a valid assembly name" a0) /// Directory '%s' doesn't exist - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:23) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:23) static member fsiDirectoryDoesNotExist(a0 : System.String) = (2302, sprintf "Directory '%s' doesn't exist" a0) /// Invalid directive '#%s %s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:24) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:24) static member fsiInvalidDirective(a0 : System.String, a1 : System.String) = (sprintf "Invalid directive '#%s %s'" a0 a1) /// Warning: line too long, ignoring some characters\n - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:25) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:25) static member fsiLineTooLong() = (sprintf "Warning: line too long, ignoring some characters\n" ) /// Real: %s, CPU: %s, GC %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:26) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:26) static member fsiTimeInfoMainString(a0 : System.String, a1 : System.String, a2 : System.String) = (sprintf "Real: %s, CPU: %s, GC %s" a0 a1 a2) /// gen - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:27) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:27) static member fsiTimeInfoGCGenerationLabelSomeShorthandForTheWordGeneration() = (sprintf "gen" ) /// \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: %s\n - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:28) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:28) static member fsiExceptionDuringPrettyPrinting(a0 : System.String) = (sprintf "\n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: %s\n" a0) /// F# Interactive directives: - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:29) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:29) static member fsiIntroTextHeader1directives() = (sprintf " F# Interactive directives:" ) /// Reference (dynamically load) the given DLL - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:30) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:30) static member fsiIntroTextHashrInfo() = (sprintf "Reference (dynamically load) the given DLL" ) /// Add the given search path for referenced DLLs - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:31) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:31) static member fsiIntroTextHashIInfo() = (sprintf "Add the given search path for referenced DLLs" ) /// Load the given file(s) as if compiled and referenced - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:32) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:32) static member fsiIntroTextHashloadInfo() = (sprintf "Load the given file(s) as if compiled and referenced" ) /// Toggle timing on/off - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:33) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:33) static member fsiIntroTextHashtimeInfo() = (sprintf "Toggle timing on/off" ) /// Display help - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:34) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:34) static member fsiIntroTextHashhelpInfo() = (sprintf "Display help" ) /// Exit - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:35) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:35) static member fsiIntroTextHashquitInfo() = (sprintf "Exit" ) /// F# Interactive command line options: - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:36) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:36) static member fsiIntroTextHeader2commandLine() = (sprintf " F# Interactive command line options:" ) /// See '%s' for options - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:37) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:37) static member fsiIntroTextHeader3(a0 : System.String) = (sprintf " See '%s' for options" a0) /// Loading - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:38) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:38) static member fsiLoadingFilesPrefixText() = (sprintf "Loading" ) /// \n- Interrupt\n - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:39) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:39) static member fsiInterrupt() = (sprintf "\n- Interrupt\n" ) /// \n- Exit...\n - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:40) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:40) static member fsiExit() = (sprintf "\n- Exit...\n" ) /// - Aborting main thread... - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:41) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:41) static member fsiAbortingMainThread() = (sprintf "- Aborting main thread..." ) /// Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t%s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:42) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:42) static member fsiCouldNotInstallCtrlCHandler(a0 : System.String) = (sprintf "Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t%s" a0) /// --> Referenced '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:43) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:43) static member fsiDidAHashr(a0 : System.String) = (sprintf "--> Referenced '%s'" a0) /// --> Referenced '%s' (file may be locked by F# Interactive process) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:44) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:44) static member fsiDidAHashrWithLockWarning(a0 : System.String) = (sprintf "--> Referenced '%s' (file may be locked by F# Interactive process)" a0) /// --> Referenced '%s' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:45) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:45) static member fsiDidAHashrWithStaleWarning(a0 : System.String) = (sprintf "--> Referenced '%s' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly)" a0) /// --> Added '%s' to library include path - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:46) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:46) static member fsiDidAHashI(a0 : System.String) = (sprintf "--> Added '%s' to library include path" a0) /// --> Timing now on - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:47) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:47) static member fsiTurnedTimingOn() = (sprintf "--> Timing now on" ) /// --> Timing now off - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:48) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:48) static member fsiTurnedTimingOff() = (sprintf "--> Timing now off" ) /// - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:49) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:49) static member fsiUnexpectedThreadAbortException() = (sprintf "- Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart..." ) /// Failed to resolve assembly '%s' - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:50) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:50) static member fsiFailedToResolveAssembly(a0 : System.String) = (sprintf "Failed to resolve assembly '%s'" a0) /// Binding session to '%s'... - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:51) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:51) static member fsiBindingSessionTo(a0 : System.String) = (sprintf "Binding session to '%s'..." a0) /// Microsoft (R) F# Interactive version %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:52) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:52) static member fsiProductName(a0 : System.String) = (sprintf "Microsoft (R) F# Interactive version %s" a0) /// F# Interactive for F# %s - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:53) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:53) static member fsiProductNameCommunity(a0 : System.String) = (sprintf "F# Interactive for F# %s" a0) /// Prevents references from being locked by the F# Interactive process - /// (Originally from /Users/alfonsogarciacaronunez/dev/FSharp.Compiler.Service_fable/src/fsharp/fsi/FSIstrings.txt:54) + /// (Originally from src/fsharp/fsi/FSIstrings.txt:54) static member shadowCopyReferences() = (sprintf "Prevents references from being locked by the F# Interactive process" ) + /// Operation could not be completed due to earlier error + /// (Originally from src/fsharp/fsi/FSIstrings.txt:55) + static member fsiOperationCouldNotBeCompleted() = (sprintf "Operation could not be completed due to earlier error" ) + /// Operation failed. The error text has been printed in the error stream. To return the corresponding FSharpErrorInfo use the EvalInteractionNonThrowing, EvalScriptNonThrowing or EvalExpressionNonThrowing + /// (Originally from src/fsharp/fsi/FSIstrings.txt:56) + static member fsiOperationFailed() = (sprintf "Operation failed. The error text has been printed in the error stream. To return the corresponding FSharpErrorInfo use the EvalInteractionNonThrowing, EvalScriptNonThrowing or EvalExpressionNonThrowing" ) diff --git a/src/fcs-fable/codegen/codegen.fsproj b/src/fcs-fable/codegen/codegen.fsproj index 6ead1f0c8a..7906cb37d4 100644 --- a/src/fcs-fable/codegen/codegen.fsproj +++ b/src/fcs-fable/codegen/codegen.fsproj @@ -3,11 +3,12 @@ $(MSBuildProjectDirectory)\..\..\..\src - + Exe - netcoreapp2.1 + netcoreapp3.1 + Major - - - + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + diff --git a/src/fcs-fable/service_slim.fs b/src/fcs-fable/service_slim.fs index 08d6f029c3..c5ba46c73b 100644 --- a/src/fcs-fable/service_slim.fs +++ b/src/fcs-fable/service_slim.fs @@ -5,49 +5,26 @@ namespace FSharp.Compiler.SourceCodeServices -open System open System.Collections.Generic open System.Collections.Concurrent -open System.Diagnostics -open System.IO -open System.Reflection -open System.Text - -open Microsoft.FSharp.Core.Printf -open FSharp.Compiler -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.IL -open FSharp.Compiler.AbstractIL.ILBinaryReader -open FSharp.Compiler.AbstractIL.Diagnostics -open FSharp.Compiler.AbstractIL.Internal -open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.AccessibilityLogic -open FSharp.Compiler.Ast +open FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.CompileOps open FSharp.Compiler.CompileOptions -#if !FABLE_COMPILER -open FSharp.Compiler.Driver -#endif +open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Lib -open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.NameResolution open FSharp.Compiler.Parser open FSharp.Compiler.Range -open FSharp.Compiler.Lexhelp -open FSharp.Compiler.Layout -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Infos -open FSharp.Compiler.InfoReader -open FSharp.Compiler.NameResolution +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.Text open FSharp.Compiler.TypeChecker -open FSharp.Compiler.SourceCodeServices.SymbolHelpers +open FSharp.Compiler.TypedTree open Internal.Utilities open Internal.Utilities.Collections -open FSharp.Compiler.Layout.TaggedTextOps //------------------------------------------------------------------------- @@ -59,6 +36,7 @@ type internal TcErrors = FSharpErrorInfo[] type InteractiveChecker internal (tcConfig, tcGlobals, tcImports, tcInitialState, ctok, reactorOps, parseCache, checkCache) = let userOpName = "Unknown" + let suggestNamesForErrors = true static member Create(references: string[], readAllBytes: string -> byte[], defines: string[], optimize: bool) = let otherOptions = [| @@ -70,7 +48,7 @@ type InteractiveChecker internal (tcConfig, tcGlobals, tcImports, tcInitialState static member Create(references: string[], readAllBytes: string -> byte[], otherOptions: string[]) = let projectFileName = "Project" let toRefOption (fileName: string) = - if fileName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) + if fileName.EndsWith(".dll", System.StringComparison.OrdinalIgnoreCase) then "-r:" + fileName else "-r:" + fileName + ".dll" let otherOptions = references |> Array.map toRefOption |> Array.append otherOptions @@ -98,6 +76,7 @@ type InteractiveChecker internal (tcConfig, tcGlobals, tcImports, tcInitialState let tcConfig = let tcConfigB = TcConfigBuilder.Initial + tcConfigB.implicitIncludeDir <- System.IO.Path.GetDirectoryName (projectOptions.ProjectFileName) let sourceFiles = projectOptions.SourceFiles |> Array.toList let argv = projectOptions.OtherOptions |> Array.toList let _sourceFiles = ApplyCommandLineArgs(tcConfigB, sourceFiles, argv) @@ -154,7 +133,8 @@ type InteractiveChecker internal (tcConfig, tcGlobals, tcImports, tcInitialState let parseCacheKey = fileName, hash source parseCache.GetOrAdd(parseCacheKey, fun _ -> x.ClearStaleCache(fileName, parsingOptions) - let parseErrors, parseTreeOpt, anyErrors = Parser.parseFile (source, fileName, parsingOptions, userOpName) + let sourceText = SourceText.ofString source + let parseErrors, parseTreeOpt, anyErrors = ParseAndCheckFile.parseFile (sourceText, fileName, parsingOptions, userOpName, suggestNamesForErrors) let dependencyFiles = [||] // interactions have no dependencies FSharpParseFileResults (parseErrors, parseTreeOpt, anyErrors, dependencyFiles) ) @@ -173,7 +153,7 @@ type InteractiveChecker internal (tcConfig, tcGlobals, tcImports, tcInitialState |> Eventually.force ctok let fileName = parseResults.FileName - let tcErrors = ErrorHelpers.CreateErrorInfos (tcConfig.errorSeverityOptions, false, fileName, (capturingErrorLogger.GetErrors())) + let tcErrors = ErrorHelpers.CreateErrorInfos (tcConfig.errorSeverityOptions, false, fileName, (capturingErrorLogger.GetErrors()), suggestNamesForErrors) (tcResult, tcErrors), (tcState, moduleNamesDict) member private x.CheckFile (projectFileName: string, parseResults: FSharpParseFileResults, tcState: TcState, moduleNamesDict: ModuleNamesDict) = @@ -187,7 +167,6 @@ type InteractiveChecker internal (tcConfig, tcGlobals, tcImports, tcInitialState checkCache.[fileName] <- ((tcResult, tcErrors), (tcState, moduleNamesDict)) let loadClosure = None - let checkAlive () = true let textSnapshotInfo = None let keepAssemblyContents = true @@ -196,7 +175,7 @@ type InteractiveChecker internal (tcConfig, tcGlobals, tcImports, tcInitialState let scope = TypeCheckInfo (tcConfig, tcGlobals, ccuSigForFile, tcState.Ccu, tcImports, tcEnvAtEnd.AccessRights, projectFileName, fileName, sink.GetResolutions(), sink.GetSymbolUses(), tcEnvAtEnd.NameEnv, - loadClosure, reactorOps, checkAlive, textSnapshotInfo, implFile, sink.GetOpenDeclarations()) + loadClosure, reactorOps, textSnapshotInfo, implFile, sink.GetOpenDeclarations()) FSharpCheckFileResults (fileName, errors, Some scope, parseResults.DependencyFiles, None, reactorOps, keepAssemblyContents) |> Some | None -> @@ -231,24 +210,24 @@ type InteractiveChecker internal (tcConfig, tcGlobals, tcImports, tcInitialState /// Parses and checks single file only, left as is for backwards compatibility. /// Despite the name, there is no support for #load etc. member x.ParseAndCheckScript (projectFileName: string, fileName: string, source: string) = + let sourceText = SourceText.ofString source let fileNames = [| fileName |] let parsingOptions = FSharpParsingOptions.FromTcConfig(tcConfig, fileNames, false) let parseResults = x.ParseFile (fileName, source, parsingOptions) let moduleNamesDict = Map.empty let loadClosure = None let backgroundErrors = [||] - let checkAlive () = true let textSnapshotInfo = None let tcState = tcInitialState - let tcResults = Parser.CheckOneFile( - parseResults, source, fileName, projectFileName, tcConfig, tcGlobals, tcImports, tcState, - moduleNamesDict, loadClosure, backgroundErrors, reactorOps, checkAlive, textSnapshotInfo, userOpName) + let tcResults = ParseAndCheckFile.CheckOneFile( + parseResults, sourceText, fileName, projectFileName, tcConfig, tcGlobals, tcImports, tcState, + moduleNamesDict, loadClosure, backgroundErrors, reactorOps, textSnapshotInfo, userOpName, suggestNamesForErrors) match tcResults with - | tcErrors, Parser.TypeCheckAborted.No scope -> + | tcErrors, Result.Ok tcFileInfo -> let errors = Array.append parseResults.Errors tcErrors - let tcImplFilesOpt = match scope.ImplementationFile with Some x -> Some [x] | None -> None - let typeCheckResults = FSharpCheckFileResults (fileName, errors, Some scope, parseResults.DependencyFiles, None, reactorOps, true) - let symbolUses = [scope.ScopeSymbolUses] + let tcImplFilesOpt = match tcFileInfo.ImplementationFile with Some x -> Some [x] | None -> None + let typeCheckResults = FSharpCheckFileResults (fileName, errors, Some tcFileInfo, parseResults.DependencyFiles, None, reactorOps, true) + let symbolUses = [tcFileInfo.ScopeSymbolUses] let projectResults = x.MakeProjectResults (projectFileName, [|parseResults|], tcState, errors, symbolUses, None, tcImplFilesOpt) parseResults, typeCheckResults, projectResults | _ -> diff --git a/src/fcs-fable/src/Directory.Build.props b/src/fcs-fable/src/Directory.Build.props deleted file mode 100644 index bb8eac309b..0000000000 --- a/src/fcs-fable/src/Directory.Build.props +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/fcs-fable/src/Directory.Build.targets b/src/fcs-fable/src/Directory.Build.targets deleted file mode 100644 index ccd47cc0a9..0000000000 --- a/src/fcs-fable/src/Directory.Build.targets +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/fcs-fable/src/absil/bytes.fs b/src/fcs-fable/src/absil/bytes.fs old mode 100755 new mode 100644 index a272b99a45..bbf5ed49e0 --- a/src/fcs-fable/src/absil/bytes.fs +++ b/src/fcs-fable/src/absil/bytes.fs @@ -3,11 +3,35 @@ /// Byte arrays namespace FSharp.Compiler.AbstractIL.Internal +open System open System.IO -open Internal.Utilities +#if !FABLE_COMPILER +open System.IO.MemoryMappedFiles +open System.Runtime.InteropServices +open System.Runtime.CompilerServices +open FSharp.NativeInterop +#endif + +#nowarn "9" -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.Internal +module Utils = + let runningOnMono = + #if ENABLE_MONO_SUPPORT + // Officially supported way to detect if we are running on Mono. + // See http://www.mono-project.com/FAQ:_Technical + // "How can I detect if am running in Mono?" section + try + System.Type.GetType ("Mono.Runtime") <> null + with _ -> + // Must be robust in the case that someone else has installed a handler into System.AppDomain.OnTypeResolveEvent + // that is not reliable. + // This is related to bug 5506--the issue is actually a bug in VSTypeResolutionService.EnsurePopulated which is + // called by OnTypeResolveEvent. The function throws a NullReferenceException. I'm working with that team to get + // their issue fixed but we need to be robust here anyway. + false + #else + false + #endif module internal Bytes = let b0 n = (n &&& 0xFF) @@ -30,10 +54,371 @@ module internal Bytes = Array.append (System.Text.Encoding.UTF8.GetBytes s) (ofInt32Array [| 0x0 |]) let stringAsUnicodeNullTerminated (s:string) = - Array.append (System.Text.Encoding.Unicode.GetBytes s) (ofInt32Array [| 0x0;0x0 |]) + Array.append (System.Text.Encoding.Unicode.GetBytes s) (ofInt32Array [| 0x0;0x0 |]) + +[] +type ByteMemory () = + +#if FABLE_COMPILER + abstract Item: int -> byte with get +#else + abstract Item: int -> byte with get, set +#endif + + abstract Length: int + + abstract ReadBytes: pos: int * count: int -> byte[] + + abstract ReadInt32: pos: int -> int + + abstract ReadUInt16: pos: int -> uint16 + + abstract ReadUtf8String: pos: int * count: int -> string + + abstract Slice: pos: int * count: int -> ByteMemory + +#if !FABLE_COMPILER + abstract CopyTo: Stream -> unit +#endif + + abstract Copy: srcOffset: int * dest: byte[] * destOffset: int * count: int -> unit + + abstract ToArray: unit -> byte[] + +#if !FABLE_COMPILER + abstract AsStream: unit -> Stream + + abstract AsReadOnlyStream: unit -> Stream +#endif + +[] +type ByteArrayMemory(bytes: byte[], offset, length) = + inherit ByteMemory() + + let checkCount count = + if count < 0 then + raise (ArgumentOutOfRangeException("count", "Count is less than zero.")) + + do + if length < 0 || length > bytes.Length then + raise (ArgumentOutOfRangeException("length")) + + if offset < 0 || (offset + length) > bytes.Length then + raise (ArgumentOutOfRangeException("offset")) + + override _.Item + with get i = bytes.[offset + i] +#if !FABLE_COMPILER + and set i v = bytes.[offset + i] <- v +#endif + + override _.Length = length + + override _.ReadBytes(pos, count) = + checkCount count + if count > 0 then + Array.sub bytes (offset + pos) count + else + Array.empty + + override _.ReadInt32 pos = + let finalOffset = offset + pos + (uint32 bytes.[finalOffset]) ||| + ((uint32 bytes.[finalOffset + 1]) <<< 8) ||| + ((uint32 bytes.[finalOffset + 2]) <<< 16) ||| + ((uint32 bytes.[finalOffset + 3]) <<< 24) + |> int + + override _.ReadUInt16 pos = + let finalOffset = offset + pos + (uint16 bytes.[finalOffset]) ||| + ((uint16 bytes.[finalOffset + 1]) <<< 8) + + override _.ReadUtf8String(pos, count) = + checkCount count + if count > 0 then + System.Text.Encoding.UTF8.GetString(bytes, offset + pos, count) + else + String.Empty + + override _.Slice(pos, count) = + checkCount count + if count > 0 then + ByteArrayMemory(bytes, offset + pos, count) :> ByteMemory + else + ByteArrayMemory(Array.empty, 0, 0) :> ByteMemory + +#if !FABLE_COMPILER + override _.CopyTo stream = + if length > 0 then + stream.Write(bytes, offset, length) +#endif + + override _.Copy(srcOffset, dest, destOffset, count) = + checkCount count + if count > 0 then + Array.blit bytes (offset + srcOffset) dest destOffset count + + override _.ToArray() = + if length > 0 then + Array.sub bytes offset length + else + Array.empty + +#if !FABLE_COMPILER + override _.AsStream() = + if length > 0 then + new MemoryStream(bytes, offset, length) :> Stream + else + new MemoryStream([||], 0, 0, false) :> Stream + + override _.AsReadOnlyStream() = + if length > 0 then + new MemoryStream(bytes, offset, length, false) :> Stream + else + new MemoryStream([||], 0, 0, false) :> Stream +#endif + +#if !FABLE_COMPILER + +[] +type SafeUnmanagedMemoryStream = + inherit UnmanagedMemoryStream + + val mutable private holder: obj + val mutable private isDisposed: bool + + new (addr, length, holder) = + { + inherit UnmanagedMemoryStream(addr, length) + holder = holder + isDisposed = false + } + + new (addr: nativeptr, length: int64, capacity: int64, access: FileAccess, holder) = + { + inherit UnmanagedMemoryStream(addr, length, capacity, access) + holder = holder + isDisposed = false + } + + override x.Dispose disposing = + base.Dispose disposing + x.holder <- null // Null out so it can be collected. + +[] +type RawByteMemory(addr: nativeptr, length: int, holder: obj) = + inherit ByteMemory () + + let check i = + if i < 0 || i >= length then + raise (ArgumentOutOfRangeException("i")) + + let checkCount count = + if count < 0 then + raise (ArgumentOutOfRangeException("count", "Count is less than zero.")) + + do + if length < 0 then + raise (ArgumentOutOfRangeException("length")) + + override _.Item + with get i = + check i + NativePtr.add addr i + |> NativePtr.read + and set i v = + check i + NativePtr.set addr i v + + override _.Length = length + + override _.ReadUtf8String(pos, count) = + checkCount count + if count > 0 then + check pos + check (pos + count - 1) + System.Text.Encoding.UTF8.GetString(NativePtr.add addr pos, count) + else + String.Empty + + override _.ReadBytes(pos, count) = + checkCount count + if count > 0 then + check pos + check (pos + count - 1) + let res = Bytes.zeroCreate count + Marshal.Copy(NativePtr.toNativeInt addr + nativeint pos, res, 0, count) + res + else + Array.empty + + override _.ReadInt32 pos = + check pos + check (pos + 3) + Marshal.ReadInt32(NativePtr.toNativeInt addr + nativeint pos) + + override _.ReadUInt16 pos = + check pos + check (pos + 1) + uint16(Marshal.ReadInt16(NativePtr.toNativeInt addr + nativeint pos)) + + override _.Slice(pos, count) = + checkCount count + if count > 0 then + check pos + check (pos + count - 1) + RawByteMemory(NativePtr.add addr pos, count, holder) :> ByteMemory + else + ByteArrayMemory(Array.empty, 0, 0) :> ByteMemory + + override x.CopyTo stream = + if length > 0 then + use stream2 = x.AsStream() + stream2.CopyTo stream + + override _.Copy(srcOffset, dest, destOffset, count) = + checkCount count + if count > 0 then + check srcOffset + Marshal.Copy(NativePtr.toNativeInt addr + nativeint srcOffset, dest, destOffset, count) + + override _.ToArray() = + if length > 0 then + let res = Array.zeroCreate length + Marshal.Copy(NativePtr.toNativeInt addr, res, 0, res.Length) + res + else + Array.empty + + override _.AsStream() = + if length > 0 then + new SafeUnmanagedMemoryStream(addr, int64 length, holder) :> Stream + else + new MemoryStream([||], 0, 0, false) :> Stream + + override _.AsReadOnlyStream() = + if length > 0 then + new SafeUnmanagedMemoryStream(addr, int64 length, int64 length, FileAccess.Read, holder) :> Stream + else + new MemoryStream([||], 0, 0, false) :> Stream + +#endif //!FABLE_COMPILER + +[] +type ReadOnlyByteMemory(bytes: ByteMemory) = + + member _.Item with get i = bytes.[i] + + member _.Length with get () = bytes.Length + + member _.ReadBytes(pos, count) = bytes.ReadBytes(pos, count) + + member _.ReadInt32 pos = bytes.ReadInt32 pos + + member _.ReadUInt16 pos = bytes.ReadUInt16 pos + + member _.ReadUtf8String(pos, count) = bytes.ReadUtf8String(pos, count) + + member _.Slice(pos, count) = bytes.Slice(pos, count) |> ReadOnlyByteMemory + +#if !FABLE_COMPILER + member _.CopyTo stream = bytes.CopyTo stream +#endif + + member _.Copy(srcOffset, dest, destOffset, count) = bytes.Copy(srcOffset, dest, destOffset, count) + + member _.ToArray() = bytes.ToArray() + +#if !FABLE_COMPILER + member _.AsStream() = bytes.AsReadOnlyStream() +#endif + +type ByteMemory with + + member x.AsReadOnly() = ReadOnlyByteMemory x + +#if !FABLE_COMPILER + static member CreateMemoryMappedFile(bytes: ReadOnlyByteMemory) = + if Utils.runningOnMono + then + // mono's MemoryMappedFile implementation throws with null `mapName`, so we use byte arrays instead: https://github.com/mono/mono/issues/10245 + ByteArrayMemory.FromArray (bytes.ToArray()) :> ByteMemory + else + let length = int64 bytes.Length + let mmf = + let mmf = MemoryMappedFile.CreateNew(null, length, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None) + use stream = mmf.CreateViewStream(0L, length, MemoryMappedFileAccess.ReadWrite) + bytes.CopyTo stream + mmf + + let accessor = mmf.CreateViewAccessor(0L, length, MemoryMappedFileAccess.ReadWrite) + RawByteMemory.FromUnsafePointer(accessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), int length, (mmf, accessor)) + + static member FromFile(path, access, ?canShadowCopy: bool) = + let canShadowCopy = defaultArg canShadowCopy false + + if Utils.runningOnMono + then + // mono's MemoryMappedFile implementation throws with null `mapName`, so we use byte arrays instead: https://github.com/mono/mono/issues/10245 + let bytes = File.ReadAllBytes path + ByteArrayMemory.FromArray bytes + else + let memoryMappedFileAccess = + match access with + | FileAccess.Read -> MemoryMappedFileAccess.Read + | FileAccess.Write -> MemoryMappedFileAccess.Write + | _ -> MemoryMappedFileAccess.ReadWrite + + let fileStream = File.Open(path, FileMode.Open, access, FileShare.Read) + + let length = fileStream.Length + + let mmf, accessor, length = + let mmf = + if canShadowCopy then + let mmf = + MemoryMappedFile.CreateNew( + null, + length, + MemoryMappedFileAccess.ReadWrite, + MemoryMappedFileOptions.None, + HandleInheritability.None) + use stream = mmf.CreateViewStream(0L, length, MemoryMappedFileAccess.ReadWrite) + fileStream.CopyTo(stream) + fileStream.Dispose() + mmf + else + MemoryMappedFile.CreateFromFile( + fileStream, + null, + length, + memoryMappedFileAccess, + HandleInheritability.None, + leaveOpen=false) + mmf, mmf.CreateViewAccessor(0L, length, memoryMappedFileAccess), length + + // Validate MMF with the access that was intended. + match access with + | FileAccess.Read when not accessor.CanRead -> invalidOp "Cannot read file" + | FileAccess.Write when not accessor.CanWrite -> invalidOp "Cannot write file" + | FileAccess.ReadWrite when not accessor.CanRead || not accessor.CanWrite -> invalidOp "Cannot read or write file" + | _ -> () + + RawByteMemory.FromUnsafePointer(accessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), int length, (mmf, accessor)) + + static member FromUnsafePointer(addr, length, holder: obj) = + RawByteMemory(NativePtr.ofNativeInt addr, length, holder) :> ByteMemory +#endif //!FABLE_COMPILER + + static member FromArray(bytes, offset, length) = + ByteArrayMemory(bytes, offset, length) :> ByteMemory + + static member FromArray bytes = + ByteArrayMemory.FromArray(bytes, 0, bytes.Length) type internal ByteStream = - { bytes: byte[] + { bytes: ReadOnlyByteMemory mutable pos: int max: int } member b.ReadByte() = @@ -42,18 +427,18 @@ type internal ByteStream = b.pos <- b.pos + 1 res member b.ReadUtf8String n = - let res = System.Text.Encoding.UTF8.GetString(b.bytes,b.pos,n) + let res = b.bytes.ReadUtf8String(b.pos,n) b.pos <- b.pos + n; res - static member FromBytes (b:byte[],n,len) = + static member FromBytes (b: ReadOnlyByteMemory,n,len) = if n < 0 || (n+len) > b.Length then failwith "FromBytes" { bytes = b; pos = n; max = n+len } member b.ReadBytes n = if b.pos + n > b.max then failwith "ReadBytes: end of stream" - let res = Bytes.sub b.bytes b.pos n + let res = b.bytes.Slice(b.pos, n) b.pos <- b.pos + n - res + res member b.Position = b.pos #if LAZY_UNPICKLE @@ -87,10 +472,10 @@ type internal ByteBuffer = let n = arr.Length let newSize = buf.bbCurrent + n buf.Ensure newSize - let bbarr = buf.bbArray - let bbbase = buf.bbCurrent + let bbArr = buf.bbArray + let bbBase = buf.bbCurrent for i = 0 to n - 1 do - bbarr.[bbbase + i] <- byte arr.[i] + bbArr.[bbBase + i] <- byte arr.[i] buf.bbCurrent <- newSize member bb.FixupInt32 pos n = @@ -112,6 +497,13 @@ type internal ByteBuffer = Bytes.blit i 0 buf.bbArray buf.bbCurrent n buf.bbCurrent <- newSize + member buf.EmitByteMemory (i:ReadOnlyByteMemory) = + let n = i.Length + let newSize = buf.bbCurrent + n + buf.Ensure newSize + i.Copy(0, buf.bbArray, buf.bbCurrent, n) + buf.bbCurrent <- newSize + member buf.EmitInt32AsUInt16 n = let newSize = buf.bbCurrent + 2 buf.Ensure newSize diff --git a/src/fcs-fable/src/absil/bytes.fsi b/src/fcs-fable/src/absil/bytes.fsi old mode 100755 new mode 100644 index c611e80c77..07a12805a4 --- a/src/fcs-fable/src/absil/bytes.fsi +++ b/src/fcs-fable/src/absil/bytes.fsi @@ -3,11 +3,15 @@ /// Blobs of bytes, cross-compiling namespace FSharp.Compiler.AbstractIL.Internal +#if !FABLE_COMPILER +open System.IO +#endif open Internal.Utilities - open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.Internal +module Utils = + val runningOnMono: bool module internal Bytes = /// returned int will be 0 <= x <= 255 @@ -22,6 +26,95 @@ module internal Bytes = val stringAsUnicodeNullTerminated: string -> byte[] val stringAsUtf8NullTerminated: string -> byte[] +/// May be backed by managed or unmanaged memory, or memory mapped file. +[] +type internal ByteMemory = + + abstract Item: int -> byte with get + + abstract Length: int + + abstract ReadBytes: pos: int * count: int -> byte[] + + abstract ReadInt32: pos: int -> int + + abstract ReadUInt16: pos: int -> uint16 + + abstract ReadUtf8String: pos: int * count: int -> string + + abstract Slice: pos: int * count: int -> ByteMemory + +#if !FABLE_COMPILER + abstract CopyTo: Stream -> unit +#endif + + abstract Copy: srcOffset: int * dest: byte[] * destOffset: int * count: int -> unit + + abstract ToArray: unit -> byte[] + +#if !FABLE_COMPILER + /// Get a stream representation of the backing memory. + /// Disposing this will not free up any of the backing memory. + abstract AsStream: unit -> Stream + + /// Get a stream representation of the backing memory. + /// Disposing this will not free up any of the backing memory. + /// Stream cannot be written to. + abstract AsReadOnlyStream: unit -> Stream +#endif + +[] +type internal ReadOnlyByteMemory = + + new: ByteMemory -> ReadOnlyByteMemory + + member Item: int -> byte with get + + member Length: int + + member ReadBytes: pos: int * count: int -> byte[] + + member ReadInt32: pos: int -> int + + member ReadUInt16: pos: int -> uint16 + + member ReadUtf8String: pos: int * count: int -> string + + member Slice: pos: int * count: int -> ReadOnlyByteMemory + +#if !FABLE_COMPILER + member CopyTo: Stream -> unit +#endif + + member Copy: srcOffset: int * dest: byte[] * destOffset: int * count: int -> unit + + member ToArray: unit -> byte[] + +#if !FABLE_COMPILER + member AsStream: unit -> Stream +#endif + +type ByteMemory with + + member AsReadOnly: unit -> ReadOnlyByteMemory + +#if !FABLE_COMPILER + /// Create another ByteMemory object that has a backing memory mapped file based on another ByteMemory's contents. + static member CreateMemoryMappedFile: ReadOnlyByteMemory -> ByteMemory + + /// Creates a ByteMemory object that has a backing memory mapped file from a file on-disk. + static member FromFile: path: string * FileAccess * ?canShadowCopy: bool -> ByteMemory + + /// Creates a ByteMemory object that is backed by a raw pointer. + /// Use with care. + static member FromUnsafePointer: addr: nativeint * length: int * holder: obj -> ByteMemory +#endif //!FABLE_COMPILER + + /// Creates a ByteMemory object that is backed by a byte array with the specified offset and length. + static member FromArray: bytes: byte[] * offset: int * length: int -> ByteMemory + + /// Creates a ByteMemory object that is backed by a byte array. + static member FromArray: bytes: byte[] -> ByteMemory /// Imperative buffers and streams of byte[] [] @@ -31,6 +124,7 @@ type internal ByteBuffer = member EmitIntsAsBytes : int[] -> unit member EmitByte : byte -> unit member EmitBytes : byte[] -> unit + member EmitByteMemory : ReadOnlyByteMemory -> unit member EmitInt32 : int32 -> unit member EmitInt64 : int64 -> unit member FixupInt32 : pos: int -> value: int32 -> unit @@ -44,10 +138,10 @@ type internal ByteBuffer = [] type internal ByteStream = member ReadByte : unit -> byte - member ReadBytes : int -> byte[] + member ReadBytes : int -> ReadOnlyByteMemory member ReadUtf8String : int -> string member Position : int - static member FromBytes : byte[] * start:int * length:int -> ByteStream + static member FromBytes : ReadOnlyByteMemory * start:int * length:int -> ByteStream #if LAZY_UNPICKLE member CloneAndSeek : int -> ByteStream diff --git a/src/fcs-fable/src/absil/il.fs b/src/fcs-fable/src/absil/il.fs index 2507e882f1..368dcddd59 100644 --- a/src/fcs-fable/src/absil/il.fs +++ b/src/fcs-fable/src/absil/il.fs @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -module FSharp.Compiler.AbstractIL.IL +module FSharp.Compiler.AbstractIL.IL #nowarn "49" #nowarn "343" // The type 'ILAssemblyRef' implements 'System.IComparable' explicitly but provides no corresponding override for 'Object.Equals'. @@ -12,8 +12,9 @@ open System.IO open System.Collections open System.Collections.Generic open System.Collections.Concurrent -open System.Runtime.CompilerServices open System.Reflection +open System.Text +open System.Threading open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.Diagnostics @@ -21,26 +22,8 @@ open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library open Internal.Utilities - -let logging = false - -let runningOnMono = -#if ENABLE_MONO_SUPPORT -// Officially supported way to detect if we are running on Mono. -// See http://www.mono-project.com/FAQ:_Technical -// "How can I detect if am running in Mono?" section - try - System.Type.GetType("Mono.Runtime") <> null - with e-> - // Must be robust in the case that someone else has installed a handler into System.AppDomain.OnTypeResolveEvent - // that is not reliable. - // This is related to bug 5506--the issue is actually a bug in VSTypeResolutionService.EnsurePopulated which is - // called by OnTypeResolveEvent. The function throws a NullReferenceException. I'm working with that team to get - // their issue fixed but we need to be robust here anyway. - false -#else - false -#endif + +let logging = false let _ = if logging then dprintn "* warning: Il.logging is on" @@ -48,45 +31,41 @@ let int_order = LanguagePrimitives.FastGenericComparer let notlazy v = Lazy<_>.CreateFromValue v -/// A little ugly, but the idea is that if a data structure does not -/// contain lazy values then we don't add laziness. So if the thing to map -/// is already evaluated then immediately apply the function. -let lazyMap f (x: Lazy<_>) = +/// A little ugly, but the idea is that if a data structure does not +/// contain lazy values then we don't add laziness. So if the thing to map +/// is already evaluated then immediately apply the function. +let lazyMap f (x: Lazy<_>) = if x.IsValueCreated then notlazy (f (x.Force())) else lazy (f (x.Force())) [] -type PrimaryAssembly = +type PrimaryAssembly = | Mscorlib - | System_Runtime - | NetStandard + | System_Runtime + | NetStandard - member this.Name = + member this.Name = match this with | Mscorlib -> "mscorlib" | System_Runtime -> "System.Runtime" | NetStandard -> "netstandard" - static member IsSomePrimaryAssembly n = - n = PrimaryAssembly.Mscorlib.Name - || n = PrimaryAssembly.System_Runtime.Name - || n = PrimaryAssembly.NetStandard.Name -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Utilities: type names -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -let splitNameAt (nm: string) idx = +let splitNameAt (nm: string) idx = if idx < 0 then failwith "splitNameAt: idx < 0" - let last = nm.Length - 1 + let last = nm.Length - 1 if idx > last then failwith "splitNameAt: idx > last" - (nm.Substring(0, idx)), + (nm.Substring (0, idx)), (if idx < last then nm.Substring (idx+1, last - idx) else "") -let rec splitNamespaceAux (nm: string) = - match nm.IndexOf '.' with +let rec splitNamespaceAux (nm: string) = + match nm.IndexOf '.' with | -1 -> [nm] - | idx -> - let s1, s2 = splitNameAt nm idx - s1::splitNamespaceAux s2 + | idx -> + let s1, s2 = splitNameAt nm idx + s1 :: splitNamespaceAux s2 /// Global State. All namespace splits ever seen // ++GLOBAL MUTABLE STATE (concurrency-safe) @@ -97,23 +76,23 @@ let memoizeNamespaceRightTable = new ConcurrentDictionary() let splitNamespaceToArray nm = - memoizeNamespaceArrayTable.GetOrAdd(nm, fun nm -> + memoizeNamespaceArrayTable.GetOrAdd (nm, fun nm -> let x = Array.ofList (splitNamespace nm) x) -let splitILTypeName (nm: string) = +let splitILTypeName (nm: string) = match nm.LastIndexOf '.' with | -1 -> [], nm - | idx -> + | idx -> let s1, s2 = splitNameAt nm idx splitNamespace s1, s2 @@ -123,18 +102,18 @@ let emptyStringArray = ([| |] : string[]) // The type names that flow to the point include the "mangled" type names used for static parameters for provided types. // For example, // Foo.Bar,"1.0" -// This is because the ImportSystemType code goes via Abstract IL type references. Ultimately this probably isn't +// This is because the ImportSystemType code goes via Abstract IL type references. Ultimately this probably isn't // the best way to do things. -let splitILTypeNameWithPossibleStaticArguments (nm: string) = - let nm, suffix = +let splitILTypeNameWithPossibleStaticArguments (nm: string) = + let nm, suffix = match nm.IndexOf ',' with | -1 -> nm, None | idx -> let s1, s2 = splitNameAt nm idx in s1, Some s2 - let nsp, nm = + let nsp, nm = match nm.LastIndexOf '.' with | -1 -> emptyStringArray, nm - | idx -> + | idx -> let s1, s2 = splitNameAt nm idx splitNamespaceToArray s1, s2 nsp, (match suffix with None -> nm | Some s -> nm + "," + s) @@ -148,48 +127,48 @@ splitILTypeNameWithPossibleStaticArguments "Foo.Bar,\"1.0\"" = ([| "Foo" |], "Ba splitILTypeNameWithPossibleStaticArguments "Foo.Bar.Bar,\"1.0\"" = ([| "Foo"; "Bar" |], "Bar,\"1.0\"") *) -let unsplitTypeName (ns, n) = - match ns with - | [] -> String.concat "." ns + "." + n - | _ -> n +let unsplitTypeName (ns, n) = + match ns with + | [] -> String.concat "." ns + "." + n + | _ -> n -let splitTypeNameRightAux (nm: string) = +let splitTypeNameRightAux (nm: string) = let idx = nm.LastIndexOf '.' if idx = -1 then None, nm else let s1, s2 = splitNameAt nm idx Some s1, s2 let splitTypeNameRight nm = - memoizeNamespaceRightTable.GetOrAdd(nm, splitTypeNameRightAux) + memoizeNamespaceRightTable.GetOrAdd (nm, splitTypeNameRightAux) -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Ordered lists with a lookup table // -------------------------------------------------------------------- /// This is used to store event, property and field maps. -type LazyOrderedMultiMap<'Key, 'Data when 'Key : equality>(keyf : 'Data -> 'Key, lazyItems : Lazy<'Data list>) = +type LazyOrderedMultiMap<'Key, 'Data when 'Key : equality>(keyf : 'Data -> 'Key, lazyItems : Lazy<'Data list>) = - let quickMap = - lazyItems |> lazyMap (fun entries -> + let quickMap = + lazyItems |> lazyMap (fun entries -> let t = new Dictionary<_, _>(entries.Length, HashIdentity.Structural) do entries |> List.iter (fun y -> let key = keyf y let v = - match t.TryGetValue(key) with + match t.TryGetValue key with | true, v -> v | _ -> [] - t.[key] <- y :: v) + t.[key] <- y :: v) t) member self.Entries() = lazyItems.Force() - member self.Add(y) = new LazyOrderedMultiMap<'Key, 'Data>(keyf, lazyItems |> lazyMap (fun x -> y :: x)) - - member self.Filter(f) = new LazyOrderedMultiMap<'Key, 'Data>(keyf, lazyItems |> lazyMap (List.filter f)) + member self.Add y = new LazyOrderedMultiMap<'Key, 'Data>(keyf, lazyItems |> lazyMap (fun x -> y :: x)) + + member self.Filter f = new LazyOrderedMultiMap<'Key, 'Data>(keyf, lazyItems |> lazyMap (List.filter f)) member self.Item - with get(x) = - match quickMap.Force().TryGetValue(x) with + with get x = + match quickMap.Force().TryGetValue x with | true, v -> v | _ -> [] @@ -206,11 +185,11 @@ let b2 n = ((n >>> 16) &&& 0xFF) let b3 n = ((n >>> 24) &&& 0xFF) -module SHA1 = +module SHA1 = let inline (>>>&) (x: int) (y: int) = int32 (uint32 x >>> y) - let f(t, b, c, d) = + let f(t, b, c, d) = if t < 20 then (b &&& c) ||| ((~~~b) &&& d) elif t < 40 then b ^^^ c ^^^ d elif t < 60 then (b &&& c) ||| (b &&& d) ||| (c &&& d) @@ -221,29 +200,29 @@ module SHA1 = let [] k40to59 = 0x8F1BBCDC let [] k60to79 = 0xCA62C1D6 - let k t = - if t < 20 then k0to19 - elif t < 40 then k20to39 - elif t < 60 then k40to59 - else k60to79 + let k t = + if t < 20 then k0to19 + elif t < 40 then k20to39 + elif t < 60 then k40to59 + else k60to79 - type SHAStream = + type SHAStream = { stream: byte[] mutable pos: int mutable eof: bool } let rotLeft32 x n = (x <<< n) ||| (x >>>& (32-n)) - - // padding and length (in bits!) recorded at end - let shaAfterEof sha = + + // padding and length (in bits!) recorded at end + let shaAfterEof sha = let n = sha.pos let len = sha.stream.Length if n = len then 0x80 - else + else let padded_len = (((len + 9 + 63) / 64) * 64) - 8 - if n < padded_len - 8 then 0x0 + if n < padded_len - 8 then 0x0 elif (n &&& 63) = 56 then int32 ((int64 len * int64 8) >>> 56) &&& 0xff elif (n &&& 63) = 57 then int32 ((int64 len * int64 8) >>> 48) &&& 0xff elif (n &&& 63) = 58 then int32 ((int64 len * int64 8) >>> 40) &&& 0xff @@ -254,13 +233,13 @@ module SHA1 = elif (n &&& 63) = 63 then (sha.eof <- true; int32 (int64 len * int64 8) &&& 0xff) else 0x0 - let shaRead8 sha = - let s = sha.stream + let shaRead8 sha = + let s = sha.stream let b = if sha.pos >= s.Length then shaAfterEof sha else int32 s.[sha.pos] sha.pos <- sha.pos + 1 b - - let shaRead32 sha = + + let shaRead32 sha = let b0 = shaRead8 sha let b1 = shaRead8 sha let b2 = shaRead8 sha @@ -268,7 +247,7 @@ module SHA1 = let res = (b0 <<< 24) ||| (b1 <<< 16) ||| (b2 <<< 8) ||| b3 res - let sha1Hash sha = + let sha1Hash sha = let mutable h0 = 0x67452301 let mutable h1 = 0xEFCDAB89 let mutable h2 = 0x98BADCFE @@ -285,13 +264,13 @@ module SHA1 = w.[i] <- shaRead32 sha for t = 16 to 79 do w.[t] <- rotLeft32 (w.[t-3] ^^^ w.[t-8] ^^^ w.[t-14] ^^^ w.[t-16]) 1 - a <- h0 + a <- h0 b <- h1 c <- h2 d <- h3 e <- h4 for t = 0 to 79 do - let temp = (rotLeft32 a 5) + f(t, b, c, d) + e + w.[t] + k(t) + let temp = (rotLeft32 a 5) + f (t, b, c, d) + e + w.[t] + k t e <- d d <- c c <- rotLeft32 b 30 @@ -304,11 +283,11 @@ module SHA1 = h4 <- h4 + e h0, h1, h2, h3, h4 - let sha1HashBytes s = + let sha1HashBytes s = let (_h0, _h1, _h2, h3, h4) = sha1Hash { stream = s; pos = 0; eof = false } // the result of the SHA algorithm is stored in registers 3 and 4 Array.map byte [| b0 h4; b1 h4; b2 h4; b3 h4; b0 h3; b1 h3; b2 h3; b3 h3; |] - let sha1HashInt64 s = + let sha1HashInt64 s = let (_h0,_h1,_h2,h3,h4) = sha1Hash { stream = s; pos = 0; eof = false } // the result of the SHA algorithm is stored in registers 3 and 4 (int64 h3 <<< 32) ||| int64 h4 @@ -316,10 +295,23 @@ let sha1HashBytes s = SHA1.sha1HashBytes s let sha1HashInt64 s = SHA1.sha1HashInt64 s // -------------------------------------------------------------------- -// -// -------------------------------------------------------------------- +// +// -------------------------------------------------------------------- + +[] +type ILVersionInfo = + + val Major: uint16 + val Minor: uint16 + val Build: uint16 + val Revision: uint16 + + new (major, minor, build, revision) = + { Major = major; Minor = minor; Build = build; Revision = revision } + + /// For debugging + override x.ToString() = sprintf "ILVersionInfo: %u %u %u %u" (x.Major) (x.Minor) (x.Build) (x.Revision) -type ILVersionInfo = uint16 * uint16 * uint16 * uint16 type Locale = string @@ -338,12 +330,12 @@ type PublicKey = member x.KeyToken=match x with PublicKeyToken b -> b | _ -> invalidOp"not a key token" - member x.ToToken() = - match x with + member x.ToToken() = + match x with | PublicKey bytes -> SHA1.sha1HashBytes bytes | PublicKeyToken token -> token - static member KeyAsToken(k) = PublicKeyToken(PublicKey(k).ToToken()) + static member KeyAsToken key = PublicKeyToken (PublicKey(key).ToToken()) [] type AssemblyRefData = @@ -362,7 +354,8 @@ let isMscorlib data = [] type ILAssemblyRef(data) = - let uniqueStamp = AssemblyRefUniqueStampGenerator.Encode(data) + let uniqueStamp = AssemblyRefUniqueStampGenerator.Encode data + let uniqueIgnoringVersionStamp = AssemblyRefUniqueStampGenerator.Encode { data with assemRefVersion = None } member x.Name=data.assemRefName @@ -370,7 +363,7 @@ type ILAssemblyRef(data) = member x.PublicKey=data.assemRefPublicKeyInfo - member x.Retargetable=data.assemRefRetargetable + member x.Retargetable=data.assemRefRetargetable member x.Version=data.assemRefVersion @@ -378,14 +371,19 @@ type ILAssemblyRef(data) = member x.UniqueStamp=uniqueStamp + member x.UniqueIgnoringVersionStamp=uniqueIgnoringVersionStamp + + member x.EqualsIgnoringVersion (aref: ILAssemblyRef) = + aref.UniqueIgnoringVersionStamp = uniqueIgnoringVersionStamp + override x.GetHashCode() = uniqueStamp - override x.Equals(yobj) = ((yobj :?> ILAssemblyRef).UniqueStamp = uniqueStamp) + override x.Equals yobj = ((yobj :?> ILAssemblyRef).UniqueStamp = uniqueStamp) - interface System.IComparable with - override x.CompareTo(yobj) = compare (yobj :?> ILAssemblyRef).UniqueStamp uniqueStamp + interface IComparable with + override x.CompareTo yobj = compare (yobj :?> ILAssemblyRef).UniqueStamp uniqueStamp - static member Create(name, hash, publicKey, retargetable, version, locale) = + static member Create (name, hash, publicKey, retargetable, version, locale) = ILAssemblyRef { assemRefName=name assemRefHash=hash @@ -395,120 +393,110 @@ type ILAssemblyRef(data) = assemRefLocale=locale } #if !FABLE_COMPILER - static member FromAssemblyName (aname: System.Reflection.AssemblyName) = + static member FromAssemblyName (aname: AssemblyName) = let locale = None - let publicKey = - match aname.GetPublicKey() with - | null | [| |] -> - match aname.GetPublicKeyToken() with + let publicKey = + match aname.GetPublicKey() with + | null | [| |] -> + match aname.GetPublicKeyToken() with | null | [| |] -> None | bytes -> Some (PublicKeyToken bytes) - | bytes -> + | bytes -> Some (PublicKey bytes) - - let version = - match aname.Version with + + let version = + match aname.Version with | null -> None - | v -> Some (uint16 v.Major, uint16 v.Minor, uint16 v.Build, uint16 v.Revision) - - let retargetable = aname.Flags = System.Reflection.AssemblyNameFlags.Retargetable + | v -> Some (ILVersionInfo (uint16 v.Major, uint16 v.Minor, uint16 v.Build, uint16 v.Revision)) - ILAssemblyRef.Create(aname.Name, None, publicKey, retargetable, version, locale) -#endif + let retargetable = aname.Flags = AssemblyNameFlags.Retargetable - member aref.QualifiedName = - let b = new System.Text.StringBuilder(100) - let add (s: string) = b.Append(s) |> ignore -#if FABLE_COMPILER - let addC (s: char) = b.Append(string s) |> ignore -#else - let addC (s: char) = b.Append(s) |> ignore + ILAssemblyRef.Create (aname.Name, None, publicKey, retargetable, version, locale) #endif - add(aref.Name) - match aref.Version with + + member aref.QualifiedName = + let b = StringBuilder(100) + let add (s: string) = b.Append s |> ignore + let addC (s: char) = b.Append s |> ignore + add aref.Name + match aref.Version with | None -> () - | Some (a, b, c, d) -> + | Some (version) -> add ", Version=" - add (string (int a)) + add (string (int version.Major)) add "." - add (string (int b)) + add (string (int version.Minor)) add "." - add (string (int c)) + add (string (int version.Build)) add "." - add (string (int d)) + add (string (int version.Revision)) add ", Culture=" - match aref.Locale with + match aref.Locale with | None -> add "neutral" | Some b -> add b add ", PublicKeyToken=" - match aref.PublicKey with + match aref.PublicKey with | None -> add "null" - | Some pki -> + | Some pki -> let pkt = pki.ToToken() - let convDigit(digit) = - let digitc = - if digit < 10 - then System.Convert.ToInt32 '0' + digit - else System.Convert.ToInt32 'a' + (digit - 10) - System.Convert.ToChar(digitc) + let convDigit digit = + let digitc = + if digit < 10 + then Convert.ToInt32 '0' + digit + else Convert.ToInt32 'a' + (digit - 10) + Convert.ToChar digitc for i = 0 to pkt.Length-1 do let v = pkt.[i] - addC (convDigit(System.Convert.ToInt32(v)/16)) - addC (convDigit(System.Convert.ToInt32(v)%16)) + addC (convDigit (int32 v / 16)) + addC (convDigit (int32 v % 16)) // retargetable can be true only for system assemblies that definitely have Version if aref.Retargetable then - add ", Retargetable=Yes" + add ", Retargetable=Yes" b.ToString() [] -type ILModuleRef = +type ILModuleRef = { name: string - hasMetadata: bool + hasMetadata: bool hash: byte[] option } - static member Create(name, hasMetadata, hash) = + static member Create (name, hasMetadata, hash) = { name=name hasMetadata= hasMetadata hash=hash } - + member x.Name=x.name member x.HasMetadata=x.hasMetadata - member x.Hash=x.hash + member x.Hash=x.hash [] [] -type ILScopeRef = +type ILScopeRef = | Local - | Module of ILModuleRef + | Module of ILModuleRef | Assembly of ILAssemblyRef + | PrimaryAssembly member x.IsLocalRef = match x with ILScopeRef.Local -> true | _ -> false - member x.IsModuleRef = match x with ILScopeRef.Module _ -> true | _ -> false - - member x.IsAssemblyRef= match x with ILScopeRef.Assembly _ -> true | _ -> false - - member x.ModuleRef = match x with ILScopeRef.Module x -> x | _ -> failwith "not a module reference" - - member x.AssemblyRef = match x with ILScopeRef.Assembly x -> x | _ -> failwith "not an assembly reference" - - member x.QualifiedName = - match x with + member x.QualifiedName = + match x with | ILScopeRef.Local -> "" | ILScopeRef.Module mref -> "module "+mref.Name | ILScopeRef.Assembly aref -> aref.QualifiedName + | ILScopeRef.PrimaryAssembly -> "" -type ILArrayBound = int32 option +type ILArrayBound = int32 option type ILArrayBounds = ILArrayBound * ILArrayBound [] -type ILArrayShape = +type ILArrayShape = | ILArrayShape of ILArrayBounds list (* lobound/size pairs *) @@ -516,25 +504,25 @@ type ILArrayShape = static member SingleDimensional = ILArrayShapeStatics.SingleDimensional - static member FromRank n = if n = 1 then ILArrayShape.SingleDimensional else ILArrayShape(List.replicate n (Some 0, None)) + static member FromRank n = if n = 1 then ILArrayShape.SingleDimensional else ILArrayShape (List.replicate n (Some 0, None)) -and ILArrayShapeStatics() = +and ILArrayShapeStatics() = - static let singleDimensional = ILArrayShape [(Some 0, None)] + static let singleDimensional = ILArrayShape [(Some 0, None)] static member SingleDimensional = singleDimensional /// Calling conventions. These are used in method pointer types. [] -type ILArgConvention = +type ILArgConvention = | Default - | CDecl - | StdCall - | ThisCall - | FastCall + | CDecl + | StdCall + | ThisCall + | FastCall | VarArg - + [] type ILThisConvention = | Instance @@ -546,9 +534,9 @@ type ILCallingConv = | Callconv of ILThisConvention * ILArgConvention - member x.ThisConv = let (Callconv(a, _b)) = x in a + member x.ThisConv = let (Callconv (a, _b)) = x in a - member x.BasicConv = let (Callconv(_a, b)) = x in b + member x.BasicConv = let (Callconv (_a, b)) = x in b member x.IsInstance = match x.ThisConv with ILThisConvention.Instance -> true | _ -> false @@ -561,37 +549,37 @@ type ILCallingConv = static member Static = ILCallingConvStatics.Static /// Static storage to amortize the allocation of ILCallingConv.Instance and ILCallingConv.Static. -and ILCallingConvStatics() = +and ILCallingConvStatics() = - static let instanceCallConv = Callconv(ILThisConvention.Instance, ILArgConvention.Default) + static let instanceCallConv = Callconv (ILThisConvention.Instance, ILArgConvention.Default) - static let staticCallConv = Callconv(ILThisConvention.Static, ILArgConvention.Default) + static let staticCallConv = Callconv (ILThisConvention.Static, ILArgConvention.Default) static member Instance = instanceCallConv static member Static = staticCallConv -type ILBoxity = - | AsObject +type ILBoxity = + | AsObject | AsValue // IL type references have a pre-computed hash code to enable quick lookup tables during binary generation. [] -type ILTypeRef = +type ILTypeRef = { trefScope: ILScopeRef trefEnclosing: string list trefName: string - hashCode : int + hashCode : int mutable asBoxedType: ILType } - - static member Create(scope, enclosing, name) = + + static member Create (scope, enclosing, name) = let hashCode = hash scope * 17 ^^^ (hash enclosing * 101 <<< 1) ^^^ (hash name * 47 <<< 2) { trefScope=scope trefEnclosing=enclosing trefName=name hashCode=hashCode asBoxedType = Unchecked.defaultof<_> } - + member x.Scope = x.trefScope member x.Enclosing = x.trefEnclosing @@ -600,50 +588,50 @@ type ILTypeRef = member x.ApproxId = x.hashCode - member x.AsBoxedType (tspec: ILTypeSpec) = + member x.AsBoxedType (tspec: ILTypeSpec) = if isNil tspec.tspecInst then let v = x.asBoxedType - match box v with - | null -> + match box v with + | null -> let r = ILType.Boxed tspec x.asBoxedType <- r r | _ -> v - else + else ILType.Boxed tspec override x.GetHashCode() = x.hashCode - override x.Equals(yobj) = - let y = (yobj :?> ILTypeRef) - (x.ApproxId = y.ApproxId) && - (x.Scope = y.Scope) && - (x.Name = y.Name) && + override x.Equals yobj = + let y = (yobj :?> ILTypeRef) + (x.ApproxId = y.ApproxId) && + (x.Scope = y.Scope) && + (x.Name = y.Name) && (x.Enclosing = y.Enclosing) - interface System.IComparable with + interface IComparable with - override x.CompareTo(yobj) = - let y = (yobj :?> ILTypeRef) + override x.CompareTo yobj = + let y = (yobj :?> ILTypeRef) let c = compare x.ApproxId y.ApproxId if c <> 0 then c else let c = compare x.Scope y.Scope if c <> 0 then c else - let c = compare x.Name y.Name + let c = compare x.Name y.Name if c <> 0 then c else compare x.Enclosing y.Enclosing - + member tref.FullName = String.concat "." (tref.Enclosing @ [tref.Name]) - + member tref.BasicQualifiedName = (String.concat "+" (tref.Enclosing @ [ tref.Name ] )).Replace(",", @"\,") - member tref.AddQualifiedNameExtension(basic) = + member tref.AddQualifiedNameExtension basic = let sco = tref.Scope.QualifiedName if sco = "" then basic else String.concat ", " [basic;sco] - member tref.QualifiedName = - tref.AddQualifiedNameExtension(tref.BasicQualifiedName) + member tref.QualifiedName = + tref.AddQualifiedNameExtension tref.BasicQualifiedName /// For debugging [] @@ -652,12 +640,12 @@ type ILTypeRef = /// For debugging override x.ToString() = x.FullName - + and [] - ILTypeSpec = + ILTypeSpec = { tspecTypeRef: ILTypeRef /// The type instantiation if the type is generic. - tspecInst: ILGenericArgs } + tspecInst: ILGenericArgs } member x.TypeRef=x.tspecTypeRef @@ -669,17 +657,17 @@ and [ List.map (fun arg -> "[" + arg.QualifiedName + "]")) + "]" - member x.AddQualifiedNameExtension(basic) = - x.TypeRef.AddQualifiedNameExtension(basic) + member x.AddQualifiedNameExtension basic = + x.TypeRef.AddQualifiedNameExtension basic member x.FullName=x.TypeRef.FullName @@ -691,69 +679,69 @@ and [] ILType = - | Void - | Array of ILArrayShape * ILType - | Value of ILTypeSpec - | Boxed of ILTypeSpec - | Ptr of ILType - | Byref of ILType - | FunctionPointer of ILCallingSignature - | TypeVar of uint16 + | Void + | Array of ILArrayShape * ILType + | Value of ILTypeSpec + | Boxed of ILTypeSpec + | Ptr of ILType + | Byref of ILType + | FunctionPointer of ILCallingSignature + | TypeVar of uint16 | Modified of bool * ILTypeRef * ILType - member x.BasicQualifiedName = - match x with + member x.BasicQualifiedName = + match x with | ILType.TypeVar n -> "!" + string n - | ILType.Modified(_, _ty1, ty2) -> ty2.BasicQualifiedName - | ILType.Array (ILArrayShape(s), ty) -> ty.BasicQualifiedName + "[" + System.String(',', s.Length-1) + "]" + | ILType.Modified (_, _ty1, ty2) -> ty2.BasicQualifiedName + | ILType.Array (ILArrayShape s, ty) -> ty.BasicQualifiedName + "[" + String(',', s.Length-1) + "]" | ILType.Value tr | ILType.Boxed tr -> tr.BasicQualifiedName | ILType.Void -> "void" | ILType.Ptr _ty -> failwith "unexpected pointer type" | ILType.Byref _ty -> failwith "unexpected byref type" | ILType.FunctionPointer _mref -> failwith "unexpected function pointer type" - member x.AddQualifiedNameExtension(basic) = - match x with + member x.AddQualifiedNameExtension basic = + match x with | ILType.TypeVar _n -> basic - | ILType.Modified(_, _ty1, ty2) -> ty2.AddQualifiedNameExtension(basic) - | ILType.Array (ILArrayShape(_s), ty) -> ty.AddQualifiedNameExtension(basic) - | ILType.Value tr | ILType.Boxed tr -> tr.AddQualifiedNameExtension(basic) + | ILType.Modified (_, _ty1, ty2) -> ty2.AddQualifiedNameExtension basic + | ILType.Array (ILArrayShape(_s), ty) -> ty.AddQualifiedNameExtension basic + | ILType.Value tr | ILType.Boxed tr -> tr.AddQualifiedNameExtension basic | ILType.Void -> failwith "void" | ILType.Ptr _ty -> failwith "unexpected pointer type" | ILType.Byref _ty -> failwith "unexpected byref type" | ILType.FunctionPointer _mref -> failwith "unexpected function pointer type" - - member x.QualifiedName = + + member x.QualifiedName = x.AddQualifiedNameExtension(x.BasicQualifiedName) member x.TypeSpec = - match x with + match x with | ILType.Boxed tr | ILType.Value tr -> tr | _ -> invalidOp "not a nominal type" member x.Boxity = - match x with + match x with | ILType.Boxed _ -> AsObject | ILType.Value _ -> AsValue | _ -> invalidOp "not a nominal type" - member x.TypeRef = - match x with + member x.TypeRef = + match x with | ILType.Boxed tspec | ILType.Value tspec -> tspec.TypeRef | _ -> invalidOp "not a nominal type" - member x.IsNominal = - match x with + member x.IsNominal = + match x with | ILType.Boxed _ | ILType.Value _ -> true | _ -> false member x.GenericArgs = - match x with + match x with | ILType.Boxed tspec | ILType.Value tspec -> tspec.GenericArgs | _ -> [] member x.IsTyvar = - match x with + match x with | ILType.TypeVar _ -> true | _ -> false /// For debugging @@ -763,7 +751,7 @@ and [] - ILCallingSignature = + ILCallingSignature = { CallingConv: ILCallingConv ArgTypes: ILTypes ReturnType: ILType } @@ -801,8 +789,8 @@ type ILMethodRef = member x.CallingSignature = mkILCallSig (x.CallingConv, x.ArgTypes, x.ReturnType) - static member Create(a, b, c, d, e, f) = - { mrefParent= a;mrefCallconv=b;mrefName=c;mrefGenericArity=d; mrefArgs=e;mrefReturn=f } + static member Create (a, b, c, d, e, f) = + { mrefParent=a; mrefCallconv=b; mrefName=c; mrefGenericArity=d; mrefArgs=e; mrefReturn=f } /// For debugging [] @@ -810,9 +798,8 @@ type ILMethodRef = override x.ToString() = x.DeclaringTypeRef.ToString() + "::" + x.Name + "(...)" - [] -type ILFieldRef = +type ILFieldRef = { DeclaringTypeRef: ILTypeRef Name: string Type: ILType } @@ -824,14 +811,14 @@ type ILFieldRef = override x.ToString() = x.DeclaringTypeRef.ToString() + "::" + x.Name [] -type ILMethodSpec = +type ILMethodSpec = { mspecMethodRef: ILMethodRef - mspecDeclaringType: ILType + mspecDeclaringType: ILType - mspecMethodInst: ILGenericArgs } + mspecMethodInst: ILGenericArgs } - static member Create(a, b, c) = { mspecDeclaringType=a; mspecMethodRef=b; mspecMethodInst=c } + static member Create (a, b, c) = { mspecDeclaringType=a; mspecMethodRef=b; mspecMethodInst=c } member x.MethodRef = x.mspecMethodRef @@ -858,7 +845,7 @@ type ILMethodSpec = [] type ILFieldSpec = { FieldRef: ILFieldRef - DeclaringType: ILType } + DeclaringType: ILType } member x.FormalType = x.FieldRef.Type @@ -873,23 +860,23 @@ type ILFieldSpec = override x.ToString() = x.FieldRef.ToString() // -------------------------------------------------------------------- -// Debug info. -// -------------------------------------------------------------------- +// Debug info. +// -------------------------------------------------------------------- type ILGuid = byte[] -type ILPlatform = +type ILPlatform = | X86 | AMD64 | IA64 -type ILSourceDocument = +type ILSourceDocument = { sourceLanguage: ILGuid option sourceVendor: ILGuid option sourceDocType: ILGuid option sourceFile: string } - static member Create(language, vendor, docType, file) = + static member Create (language, vendor, docType, file) = { sourceLanguage=language sourceVendor=vendor sourceDocType=docType @@ -911,7 +898,7 @@ type ILSourceMarker = sourceEndLine: int sourceEndColumn: int } - static member Create(document, line, column, endLine, endColumn) = + static member Create (document, line, column, endLine, endColumn) = { sourceDocument=document sourceLine=line sourceColumn=column @@ -934,7 +921,7 @@ type ILSourceMarker = override x.ToString() = sprintf "(%d, %d)-(%d, %d)" x.Line x.Column x.EndLine x.EndColumn -type ILAttribElem = +type ILAttribElem = | String of string option | Bool of bool | Char of char @@ -948,7 +935,7 @@ type ILAttribElem = | UInt64 of uint64 | Single of single | Double of double - | Null + | Null | Type of ILType option | TypeRef of ILTypeRef option | Array of ILType * ILAttribElem list @@ -970,7 +957,7 @@ type ILAttribute = | Encoded (_, _, elements) -> elements | Decoded (_, fixedArgs, namedArgs) -> fixedArgs @ (namedArgs |> List.map (fun (_, _, _, e) -> e)) - member x.WithMethod(method: ILMethodSpec) = + member x.WithMethod (method: ILMethodSpec) = match x with | Encoded (_, data, elements) -> Encoded (method, data, elements) | Decoded (_, fixedArgs, namedArgs) -> Decoded (method, fixedArgs, namedArgs) @@ -997,9 +984,9 @@ type ILAttributesStored = /// Already computed | Given of ILAttributes - member x.GetCustomAttrs metadataIndex = + member x.GetCustomAttrs metadataIndex = match x with - | Reader f -> ILAttributes(f metadataIndex) + | Reader f -> ILAttributes (f metadataIndex) | Given attrs -> attrs let emptyILCustomAttrs = ILAttributes [| |] @@ -1017,8 +1004,8 @@ let mkILCustomAttrsReader f = ILAttributesStored.Reader f type ILCodeLabel = int // -------------------------------------------------------------------- -// Instruction set. -// -------------------------------------------------------------------- +// Instruction set. +// -------------------------------------------------------------------- type ILBasicType = | DT_R @@ -1037,91 +1024,91 @@ type ILBasicType = | DT_REF [] -type ILToken = - | ILType of ILType - | ILMethod of ILMethodSpec +type ILToken = + | ILType of ILType + | ILMethod of ILMethodSpec | ILField of ILFieldSpec [] -type ILConst = +type ILConst = | I4 of int32 | I8 of int64 | R4 of single | R8 of double -type ILTailcall = +type ILTailcall = | Tailcall | Normalcall -type ILAlignment = +type ILAlignment = | Aligned | Unaligned1 | Unaligned2 | Unaligned4 -type ILVolatility = +type ILVolatility = | Volatile | Nonvolatile -type ILReadonly = +type ILReadonly = | ReadonlyAddress | NormalAddress type ILVarArgs = ILTypes option [] -type ILComparisonInstr = - | BI_beq - | BI_bge - | BI_bge_un - | BI_bgt - | BI_bgt_un - | BI_ble - | BI_ble_un - | BI_blt - | BI_blt_un - | BI_bne_un - | BI_brfalse - | BI_brtrue +type ILComparisonInstr = + | BI_beq + | BI_bge + | BI_bge_un + | BI_bgt + | BI_bgt_un + | BI_ble + | BI_ble_un + | BI_blt + | BI_blt_un + | BI_bne_un + | BI_brfalse + | BI_brtrue [] -type ILInstr = - | AI_add +type ILInstr = + | AI_add | AI_add_ovf | AI_add_ovf_un - | AI_and - | AI_div + | AI_and + | AI_div | AI_div_un - | AI_ceq - | AI_cgt - | AI_cgt_un - | AI_clt - | AI_clt_un + | AI_ceq + | AI_cgt + | AI_cgt_un + | AI_clt + | AI_clt_un | AI_conv of ILBasicType | AI_conv_ovf of ILBasicType | AI_conv_ovf_un of ILBasicType - | AI_mul - | AI_mul_ovf + | AI_mul + | AI_mul_ovf | AI_mul_ovf_un - | AI_rem - | AI_rem_un - | AI_shl - | AI_shr + | AI_rem + | AI_rem_un + | AI_shl + | AI_shr | AI_shr_un - | AI_sub - | AI_sub_ovf - | AI_sub_ovf_un - | AI_xor - | AI_or - | AI_neg - | AI_not - | AI_ldnull - | AI_dup + | AI_sub + | AI_sub_ovf + | AI_sub_ovf_un + | AI_xor + | AI_or + | AI_neg + | AI_not + | AI_ldnull + | AI_dup | AI_pop - | AI_ckfinite + | AI_ckfinite | AI_nop - | AI_ldc of ILBasicType * ILConst + | AI_ldc of ILBasicType * ILConst | I_ldarg of uint16 | I_ldarga of uint16 | I_ldind of ILAlignment * ILVolatility * ILBasicType @@ -1133,9 +1120,9 @@ type ILInstr = | I_br of ILCodeLabel | I_jmp of ILMethodSpec - | I_brcmp of ILComparisonInstr * ILCodeLabel - | I_switch of ILCodeLabel list - | I_ret + | I_brcmp of ILComparisonInstr * ILCodeLabel + | I_switch of ILCodeLabel list + | I_ret | I_call of ILTailcall * ILMethodSpec * ILVarArgs | I_callvirt of ILTailcall * ILMethodSpec * ILVarArgs @@ -1143,7 +1130,7 @@ type ILInstr = | I_calli of ILTailcall * ILCallingSignature * ILVarArgs | I_ldftn of ILMethodSpec | I_newobj of ILMethodSpec * ILVarArgs - + | I_throw | I_endfinally | I_endfilter @@ -1153,7 +1140,7 @@ type ILInstr = | I_ldsfld of ILVolatility * ILFieldSpec | I_ldfld of ILAlignment * ILVolatility * ILFieldSpec | I_ldsflda of ILFieldSpec - | I_ldflda of ILFieldSpec + | I_ldflda of ILFieldSpec | I_stsfld of ILVolatility * ILFieldSpec | I_stfld of ILAlignment * ILVolatility * ILFieldSpec | I_ldstr of string @@ -1176,69 +1163,69 @@ type ILInstr = | I_ldelema of ILReadonly * bool * ILArrayShape * ILType | I_ldelem_any of ILArrayShape * ILType | I_stelem_any of ILArrayShape * ILType - | I_newarr of ILArrayShape * ILType + | I_newarr of ILArrayShape * ILType | I_ldlen | I_mkrefany of ILType - | I_refanytype + | I_refanytype | I_refanyval of ILType - | I_break + | I_break | I_seqpoint of ILSourceMarker - | I_arglist + | I_arglist | I_localloc | I_cpblk of ILAlignment * ILVolatility | I_initblk of ILAlignment * ILVolatility - (* FOR EXTENSIONS, e.g. MS-ILX *) + (* FOR EXTENSIONS, e.g. MS-ILX *) | EI_ilzero of ILType | EI_ldlen_multi of int32 * int32 [] -type ILExceptionClause = +type ILExceptionClause = | Finally of (ILCodeLabel * ILCodeLabel) | Fault of (ILCodeLabel * ILCodeLabel) | FilterCatch of (ILCodeLabel * ILCodeLabel) * (ILCodeLabel * ILCodeLabel) | TypeCatch of ILType * (ILCodeLabel * ILCodeLabel) [] -type ILExceptionSpec = +type ILExceptionSpec = { Range: (ILCodeLabel * ILCodeLabel) Clause: ILExceptionClause } -/// Indicates that a particular local variable has a particular source -/// language name within a given set of ranges. This does not effect local -/// variable numbering, which is global over the whole method. +/// Indicates that a particular local variable has a particular source +/// language name within a given set of ranges. This does not effect local +/// variable numbering, which is global over the whole method. [] type ILLocalDebugMapping = { LocalIndex: int LocalName: string } [] -type ILLocalDebugInfo = +type ILLocalDebugInfo = { Range: (ILCodeLabel * ILCodeLabel) DebugMappings: ILLocalDebugMapping list } [] -type ILCode = - { Labels: Dictionary - Instrs: ILInstr[] - Exceptions: ILExceptionSpec list +type ILCode = + { Labels: Dictionary + Instrs: ILInstr[] + Exceptions: ILExceptionSpec list Locals: ILLocalDebugInfo list } [] -type ILLocal = +type ILLocal = { Type: ILType IsPinned: bool DebugInfo: (string * int * int) option } - + type ILLocals = list [] -type ILMethodBody = +type ILMethodBody = { IsZeroInit: bool MaxStack: int32 NoInlining: bool @@ -1248,17 +1235,17 @@ type ILMethodBody = SourceMarker: ILSourceMarker option } [] -type ILMemberAccess = +type ILMemberAccess = | Assembly | CompilerControlled | FamilyAndAssembly | FamilyOrAssembly | Family - | Private - | Public + | Private + | Public [] -type ILFieldInit = +type ILFieldInit = | String of string | Bool of bool | Char of uint16 @@ -1273,15 +1260,15 @@ type ILFieldInit = | Single of single | Double of double | Null - -// -------------------------------------------------------------------- + +// -------------------------------------------------------------------- // Native Types, for marshalling to the native C interface. // These are taken directly from the ILASM syntax, and don't really -// correspond yet to the ECMA Spec (Partition II, 7.4). -// -------------------------------------------------------------------- +// correspond yet to the ECMA Spec (Partition II, 7.4). +// -------------------------------------------------------------------- [] -type ILNativeType = +type ILNativeType = | Empty | Custom of ILGuid * string * string * byte[] (* guid, nativeTypeName, custMarshallerName, cookieString *) | FixedSysString of int32 @@ -1316,67 +1303,67 @@ type ILNativeType = | IUnknown | IDispatch | Interface - | Error - | SafeArray of ILNativeVariant * string option + | Error + | SafeArray of ILNativeVariant * string option | ANSIBSTR | VariantBool -and +and [] - ILNativeVariant = + ILNativeVariant = | Empty | Null | Variant | Currency - | Decimal - | Date - | BSTR - | LPSTR - | LPWSTR - | IUnknown - | IDispatch - | SafeArray - | Error - | HRESULT - | CArray - | UserDefined - | Record + | Decimal + | Date + | BSTR + | LPSTR + | LPWSTR + | IUnknown + | IDispatch + | SafeArray + | Error + | HRESULT + | CArray + | UserDefined + | Record | FileTime - | Blob - | Stream - | Storage - | StreamedObject - | StoredObject - | BlobObject - | CF + | Blob + | Stream + | Storage + | StreamedObject + | StoredObject + | BlobObject + | CF | CLSID - | Void + | Void | Bool | Int8 - | Int16 - | Int32 - | Int64 - | Single - | Double - | UInt8 - | UInt16 - | UInt32 - | UInt64 - | PTR - | Array of ILNativeVariant - | Vector of ILNativeVariant - | Byref of ILNativeVariant - | Int - | UInt + | Int16 + | Int32 + | Int64 + | Single + | Double + | UInt8 + | UInt16 + | UInt32 + | UInt64 + | PTR + | Array of ILNativeVariant + | Vector of ILNativeVariant + | Byref of ILNativeVariant + | Int + | UInt [] -type ILSecurityAction = - | Request +type ILSecurityAction = + | Request | Demand | Assert | Deny | PermitOnly - | LinkCheck + | LinkCheck | InheritCheck | ReqMin | ReqOpt @@ -1391,11 +1378,11 @@ type ILSecurityAction = | DemandChoice [] -type ILSecurityDecl = +type ILSecurityDecl = | ILSecurityDecl of ILSecurityAction * byte[] [] -type ILSecurityDecls(array : ILSecurityDecl[]) = +type ILSecurityDecls (array : ILSecurityDecl[]) = member x.AsArray = array member x.AsList = x.AsArray |> Array.toList @@ -1408,7 +1395,7 @@ type ILSecurityDeclsStored = /// Already computed | Given of ILSecurityDecls - member x.GetSecurityDecls metadataIndex = + member x.GetSecurityDecls metadataIndex = match x with | Reader f -> ILSecurityDecls(f metadataIndex) | Given attrs -> attrs @@ -1424,7 +1411,7 @@ let storeILSecurityDecls (x: ILSecurityDecls) = if x.AsArray.Length = 0 then emp let mkILSecurityDeclsReader f = ILSecurityDeclsStored.Reader f [] -type PInvokeCharBestFit = +type PInvokeCharBestFit = | UseAssembly | Enabled | Disabled @@ -1479,7 +1466,7 @@ type ILParameter = type ILParameters = list [] -type ILReturn = +type ILReturn = { Marshal: ILNativeType option Type: ILType CustomAttrsStored: ILAttributesStored @@ -1489,24 +1476,24 @@ type ILReturn = member x.WithCustomAttrs(customAttrs) = { x with CustomAttrsStored = storeILCustomAttrs customAttrs } -type ILOverridesSpec = +type ILOverridesSpec = | OverridesSpec of ILMethodRef * ILType - member x.MethodRef = let (OverridesSpec(mr, _ty)) = x in mr + member x.MethodRef = let (OverridesSpec (mr, _ty)) = x in mr - member x.DeclaringType = let (OverridesSpec(_mr, ty)) = x in ty + member x.DeclaringType = let (OverridesSpec (_mr, ty)) = x in ty -type ILMethodVirtualInfo = +type ILMethodVirtualInfo = { IsFinal: bool - IsNewSlot: bool + IsNewSlot: bool IsCheckAccessOnOverride: bool IsAbstract: bool } type MethodKind = - | Static - | Cctor - | Ctor - | NonVirtual + | Static + | Cctor + | Ctor + | NonVirtual | Virtual of ILMethodVirtualInfo [] @@ -1517,7 +1504,7 @@ type MethodBody = | Native | NotAvailable -type ILLazyMethodBody = +type ILLazyMethodBody = | ILLazyMethodBody of Lazy member x.Contents = let (ILLazyMethodBody mb) = x in mb.Force() @@ -1544,10 +1531,10 @@ type ILGenericVariance = type ILGenericParameterDef = { Name: string Constraints: ILTypes - Variance: ILGenericVariance + Variance: ILGenericVariance HasReferenceTypeConstraint: bool HasNotNullableValueTypeConstraint: bool - HasDefaultConstructorConstraint: bool + HasDefaultConstructorConstraint: bool CustomAttrsStored : ILAttributesStored MetadataIndex: int32 } @@ -1557,18 +1544,18 @@ type ILGenericParameterDef = [] member x.DebugText = x.ToString() - override x.ToString() = x.Name + override x.ToString() = x.Name type ILGenericParameterDefs = ILGenericParameterDef list let memberAccessOfFlags flags = let f = (flags &&& 0x00000007) - if f = 0x00000001 then ILMemberAccess.Private - elif f = 0x00000006 then ILMemberAccess.Public - elif f = 0x00000004 then ILMemberAccess.Family - elif f = 0x00000002 then ILMemberAccess.FamilyAndAssembly - elif f = 0x00000005 then ILMemberAccess.FamilyOrAssembly - elif f = 0x00000003 then ILMemberAccess.Assembly + if f = 0x00000001 then ILMemberAccess.Private + elif f = 0x00000006 then ILMemberAccess.Public + elif f = 0x00000004 then ILMemberAccess.Family + elif f = 0x00000002 then ILMemberAccess.FamilyAndAssembly + elif f = 0x00000005 then ILMemberAccess.FamilyOrAssembly + elif f = 0x00000003 then ILMemberAccess.Assembly else ILMemberAccess.CompilerControlled let convertMemberAccess (ilMemberAccess: ILMemberAccess) = @@ -1590,14 +1577,14 @@ type ILMethodDef (name: string, attributes: MethodAttributes, implAttributes: Me parameters: ILParameters, ret: ILReturn, body: ILLazyMethodBody, isEntryPoint: bool, genericParams: ILGenericParameterDefs, securityDeclsStored: ILSecurityDeclsStored, customAttrsStored: ILAttributesStored, metadataIndex: int32) = - static member CreateStored (name, attributes, implAttributes, callingConv, parameters, ret, body, isEntryPoint, genericParams, securityDeclsStored, customAttrsStored, metadataIndex) = + static member CreateStored (name, attributes, implAttributes, callingConv, parameters, ret, body, isEntryPoint, genericParams, securityDeclsStored, customAttrsStored, metadataIndex) = ILMethodDef(name, attributes, implAttributes, callingConv, parameters, ret, body, isEntryPoint, genericParams, securityDeclsStored, customAttrsStored, metadataIndex) - static member Create (name, attributes, implAttributes, callingConv, parameters, ret, body, isEntryPoint, genericParams, securityDecls, customAttrs) = - ILMethodDef(name, attributes, implAttributes, callingConv, parameters, ret, body, isEntryPoint, genericParams, + static member Create (name, attributes, implAttributes, callingConv, parameters, ret, body, isEntryPoint, genericParams, securityDecls, customAttrs) = + ILMethodDef (name, attributes, implAttributes, callingConv, parameters, ret, body, isEntryPoint, genericParams, storeILSecurityDecls securityDecls, storeILCustomAttrs customAttrs, NoMetadataIdx) - + // The captured data - remember the object will be as large as the data captured by these members member __.Name = name @@ -1623,9 +1610,9 @@ type ILMethodDef (name: string, attributes: MethodAttributes, implAttributes: Me member __.MetadataIndex = metadataIndex - member x.With (?name: string, ?attributes: MethodAttributes, ?implAttributes: MethodImplAttributes, - ?callingConv: ILCallingConv, ?parameters: ILParameters, ?ret: ILReturn, - ?body: ILLazyMethodBody, ?securityDecls: ILSecurityDecls, ?isEntryPoint: bool, + member x.With (?name: string, ?attributes: MethodAttributes, ?implAttributes: MethodImplAttributes, + ?callingConv: ILCallingConv, ?parameters: ILParameters, ?ret: ILReturn, + ?body: ILLazyMethodBody, ?securityDecls: ILSecurityDecls, ?isEntryPoint: bool, ?genericParams: ILGenericParameterDefs, ?customAttrs: ILAttributes) = ILMethodDef.Create (name = defaultArg name x.Name, @@ -1646,8 +1633,8 @@ type ILMethodDef (name: string, attributes: MethodAttributes, implAttributes: Me member x.ParameterTypes = typesOfILParams x.Parameters - member md.Code = - match md.Body.Contents with + member md.Code = + match md.Body.Contents with | MethodBody.IL il-> Some il.Code | _ -> None @@ -1659,7 +1646,7 @@ type ILMethodDef (name: string, attributes: MethodAttributes, implAttributes: Me member x.SourceMarker = x.MethodBody.SourceMarker - member x.MaxStack = x.MethodBody.MaxStack + member x.MaxStack = x.MethodBody.MaxStack member x.IsZeroInit = x.MethodBody.IsZeroInit @@ -1692,7 +1679,7 @@ type ILMethodDef (name: string, attributes: MethodAttributes, implAttributes: Me member x.IsMustRun = x.ImplAttributes &&& MethodImplAttributes.NoOptimization <> enum 0 member x.WithSpecialName = x.With(attributes = (x.Attributes ||| MethodAttributes.SpecialName)) - member x.WithHideBySig() = + member x.WithHideBySig() = x.With(attributes = ( if x.IsVirtual then x.Attributes &&& ~~~MethodAttributes.CheckAccessOnOverride ||| MethodAttributes.HideBySig else failwith "WithHideBySig")) @@ -1709,44 +1696,48 @@ type ILMethodDef (name: string, attributes: MethodAttributes, implAttributes: Me member x.WithAggressiveInlining(condition) = x.With(implAttributes = (x.ImplAttributes |> conditionalAdd condition MethodImplAttributes.AggressiveInlining)) member x.WithRuntime(condition) = x.With(implAttributes = (x.ImplAttributes |> conditionalAdd condition MethodImplAttributes.Runtime)) -/// Index table by name and arity. +/// Index table by name and arity. type MethodDefMap = Map [] -type ILMethodDefs(f : (unit -> ILMethodDef[])) = +type ILMethodDefs(f : (unit -> ILMethodDef[])) = let mutable array = InlineDelayInit<_>(f) - let mutable dict = InlineDelayInit<_>(fun () -> + let mutable dict = InlineDelayInit<_>(fun () -> let arr = array.Value let t = Dictionary<_, _>() - for i = arr.Length - 1 downto 0 do + for i = arr.Length - 1 downto 0 do let y = arr.[i] let key = y.Name - match t.TryGetValue(key) with + match t.TryGetValue key with | true, m -> t.[key] <- y :: m | _ -> t.[key] <- [y] t) - interface IEnumerable with + interface IEnumerable with member x.GetEnumerator() = ((x :> IEnumerable).GetEnumerator() :> IEnumerator) - interface IEnumerable with + interface IEnumerable with member x.GetEnumerator() = (array.Value :> IEnumerable).GetEnumerator() member x.AsArray = array.Value member x.AsList = array.Value|> Array.toList - member x.FindByName(nm) = - match dict.Value.TryGetValue(nm) with + member x.FindByName nm = + match dict.Value.TryGetValue nm with | true, m -> m | _ -> [] member x.FindByNameAndArity (nm, arity) = x.FindByName nm |> List.filter (fun x -> List.length x.Parameters = arity) + member x.TryFindInstanceByNameAndCallingSignature (nm, callingSig) = + x.FindByName nm + |> List.tryFind (fun x -> not x.IsStatic && x.CallingSignature = callingSig) + [] -type ILEventDef(eventType: ILType option, name: string, attributes: EventAttributes, - addMethod: ILMethodRef, removeMethod: ILMethodRef, fireMethod: ILMethodRef option, +type ILEventDef(eventType: ILType option, name: string, attributes: EventAttributes, + addMethod: ILMethodRef, removeMethod: ILMethodRef, fireMethod: ILMethodRef option, otherMethods: ILMethodRef list, customAttrsStored: ILAttributesStored, metadataIndex: int32) = static member CreateStored (eventType, name, attributes, addMethod, removeMethod, fireMethod, otherMethods, customAttrsStored, metadataIndex) = @@ -1766,7 +1757,7 @@ type ILEventDef(eventType: ILType option, name: string, attributes: EventAttribu member __.MetadataIndex = metadataIndex member x.CustomAttrs = customAttrsStored.GetCustomAttrs x.MetadataIndex - member x.With(?eventType, ?name, ?attributes, ?addMethod, ?removeMethod, ?fireMethod, ?otherMethods, ?customAttrs) = + member x.With(?eventType, ?name, ?attributes, ?addMethod, ?removeMethod, ?fireMethod, ?otherMethods, ?customAttrs) = ILEventDef.Create(eventType= defaultArg eventType x.EventType, name= defaultArg name x.Name, attributes= defaultArg attributes x.Attributes, @@ -1786,7 +1777,7 @@ type ILEventDef(eventType: ILType option, name: string, attributes: EventAttribu override x.ToString() = "event " + x.Name [] -type ILEventDefs = +type ILEventDefs = | ILEvents of LazyOrderedMultiMap member x.AsList = let (ILEvents t) = x in t.Entries() @@ -1794,8 +1785,8 @@ type ILEventDefs = member x.LookupByName s = let (ILEvents t) = x in t.[s] [] -type ILPropertyDef(name: string, attributes: PropertyAttributes, setMethod: ILMethodRef option, - getMethod: ILMethodRef option, callingConv: ILThisConvention, propertyType: ILType, +type ILPropertyDef(name: string, attributes: PropertyAttributes, setMethod: ILMethodRef option, + getMethod: ILMethodRef option, callingConv: ILThisConvention, propertyType: ILType, init: ILFieldInit option, args: ILTypes, customAttrsStored: ILAttributesStored, metadataIndex: int32) = static member CreateStored (name, attributes, setMethod, getMethod, callingConv, propertyType, init, args, customAttrsStored, metadataIndex) = @@ -1816,7 +1807,7 @@ type ILPropertyDef(name: string, attributes: PropertyAttributes, setMethod: ILMe member x.CustomAttrs = customAttrsStored.GetCustomAttrs x.MetadataIndex member x.MetadataIndex = metadataIndex - member x.With(?name, ?attributes, ?setMethod, ?getMethod, ?callingConv, ?propertyType, ?init, ?args, ?customAttrs) = + member x.With(?name, ?attributes, ?setMethod, ?getMethod, ?callingConv, ?propertyType, ?init, ?args, ?customAttrs) = ILPropertyDef.Create(name=defaultArg name x.Name, attributes=defaultArg attributes x.Attributes, setMethod=defaultArg setMethod x.SetMethod, @@ -1836,10 +1827,10 @@ type ILPropertyDef(name: string, attributes: PropertyAttributes, setMethod: ILMe member x.DebugText = x.ToString() override x.ToString() = "property " + x.Name - + // Index table by name. [] -type ILPropertyDefs = +type ILPropertyDefs = | ILProperties of LazyOrderedMultiMap member x.AsList = let (ILProperties t) = x in t.Entries() member x.LookupByName s = let (ILProperties t) = x in t.[s] @@ -1855,14 +1846,14 @@ let convertFieldAccess (ilMemberAccess: ILMemberAccess) = | ILMemberAccess.Public -> FieldAttributes.Public [] -type ILFieldDef(name: string, fieldType: ILType, attributes: FieldAttributes, data: byte[] option, - literalValue: ILFieldInit option, offset: int32 option, marshal: ILNativeType option, - customAttrsStored: ILAttributesStored, metadataIndex: int32) = +type ILFieldDef(name: string, fieldType: ILType, attributes: FieldAttributes, data: byte[] option, + literalValue: ILFieldInit option, offset: int32 option, marshal: ILNativeType option, + customAttrsStored: ILAttributesStored, metadataIndex: int32) = static member CreateStored (name, fieldType, attributes, data, literalValue, offset, marshal, customAttrsStored, metadataIndex) = ILFieldDef(name, fieldType, attributes, data, literalValue, offset, marshal, customAttrsStored, metadataIndex) - static member Create (name, fieldType, attributes, data, literalValue, offset, marshal, customAttrs) = + static member Create (name, fieldType, attributes, data, literalValue, offset, marshal, customAttrs) = ILFieldDef(name, fieldType, attributes, data, literalValue, offset, marshal, storeILCustomAttrs customAttrs, NoMetadataIdx) member __.Name=name @@ -1876,7 +1867,7 @@ type ILFieldDef(name: string, fieldType: ILType, attributes: FieldAttributes, da member x.CustomAttrs = customAttrsStored.GetCustomAttrs x.MetadataIndex member x.MetadataIndex = metadataIndex - member x.With(?name: string, ?fieldType: ILType, ?attributes: FieldAttributes, ?data: byte[] option, ?literalValue: ILFieldInit option, ?offset: int32 option, ?marshal: ILNativeType option, ?customAttrs: ILAttributes) = + member x.With(?name: string, ?fieldType: ILType, ?attributes: FieldAttributes, ?data: byte[] option, ?literalValue: ILFieldInit option, ?offset: int32 option, ?marshal: ILNativeType option, ?customAttrs: ILAttributes) = ILFieldDef.Create(name=defaultArg name x.Name, fieldType=defaultArg fieldType x.FieldType, attributes=defaultArg attributes x.Attributes, @@ -1899,9 +1890,8 @@ type ILFieldDef(name: string, fieldType: ILType, attributes: FieldAttributes, da member x.WithLiteralDefaultValue(literal) = x.With(literalValue = literal, attributes = (x.Attributes |> conditionalAdd literal.IsSome (FieldAttributes.Literal ||| FieldAttributes.HasDefault))) member x.WithFieldMarshal(marshal) = x.With(marshal = marshal, attributes = (x.Attributes |> conditionalAdd marshal.IsSome FieldAttributes.HasFieldMarshal)) - // Index table by name. Keep a canonical list to make sure field order is not disturbed for binary manipulation. -type ILFieldDefs = +type ILFieldDefs = | ILFields of LazyOrderedMultiMap member x.AsList = let (ILFields t) = x in t.Entries() @@ -1912,8 +1902,8 @@ type ILMethodImplDef = { Overrides: ILOverridesSpec OverrideBy: ILMethodSpec } -// Index table by name and arity. -type ILMethodImplDefs = +// Index table by name and arity. +type ILMethodImplDefs = | ILMethodImpls of Lazy member x.AsList = let (ILMethodImpls ltab) = x in Map.foldBack (fun _x y r -> y@r) (ltab.Force()) [] @@ -1928,7 +1918,7 @@ type ILTypeDefLayout = and ILTypeDefLayoutInfo = { Size: int32 option - Pack: uint16 option } + Pack: uint16 option } [] type ILTypeInit = @@ -1942,25 +1932,25 @@ type ILDefaultPInvokeEncoding = | Unicode type ILTypeDefAccess = - | Public + | Public | Private - | Nested of ILMemberAccess + | Nested of ILMemberAccess let typeAccessOfFlags flags = let f = (flags &&& 0x00000007) - if f = 0x00000001 then ILTypeDefAccess.Public - elif f = 0x00000002 then ILTypeDefAccess.Nested ILMemberAccess.Public - elif f = 0x00000003 then ILTypeDefAccess.Nested ILMemberAccess.Private - elif f = 0x00000004 then ILTypeDefAccess.Nested ILMemberAccess.Family - elif f = 0x00000006 then ILTypeDefAccess.Nested ILMemberAccess.FamilyAndAssembly - elif f = 0x00000007 then ILTypeDefAccess.Nested ILMemberAccess.FamilyOrAssembly - elif f = 0x00000005 then ILTypeDefAccess.Nested ILMemberAccess.Assembly + if f = 0x00000001 then ILTypeDefAccess.Public + elif f = 0x00000002 then ILTypeDefAccess.Nested ILMemberAccess.Public + elif f = 0x00000003 then ILTypeDefAccess.Nested ILMemberAccess.Private + elif f = 0x00000004 then ILTypeDefAccess.Nested ILMemberAccess.Family + elif f = 0x00000006 then ILTypeDefAccess.Nested ILMemberAccess.FamilyAndAssembly + elif f = 0x00000007 then ILTypeDefAccess.Nested ILMemberAccess.FamilyOrAssembly + elif f = 0x00000005 then ILTypeDefAccess.Nested ILMemberAccess.Assembly else ILTypeDefAccess.Private -let typeEncodingOfFlags flags = +let typeEncodingOfFlags flags = let f = (flags &&& 0x00030000) - if f = 0x00020000 then ILDefaultPInvokeEncoding.Auto - elif f = 0x00010000 then ILDefaultPInvokeEncoding.Unicode + if f = 0x00020000 then ILDefaultPInvokeEncoding.Auto + elif f = 0x00010000 then ILDefaultPInvokeEncoding.Unicode else ILDefaultPInvokeEncoding.Ansi [] @@ -1968,28 +1958,28 @@ type ILTypeDefKind = | Class | ValueType | Interface - | Enum + | Enum | Delegate let typeKindOfFlags nm _mdefs _fdefs (super: ILType option) flags = - if (flags &&& 0x00000020) <> 0x0 then ILTypeDefKind.Interface - else - let isEnum, isDelegate, isMulticastDelegate, isValueType = - match super with + if (flags &&& 0x00000020) <> 0x0 then ILTypeDefKind.Interface + else + let isEnum, isDelegate, isMulticastDelegate, isValueType = + match super with | None -> false, false, false, false - | Some ty -> + | Some ty -> ty.TypeSpec.Name = "System.Enum", ty.TypeSpec.Name = "System.Delegate", ty.TypeSpec.Name = "System.MulticastDelegate", ty.TypeSpec.Name = "System.ValueType" && nm <> "System.Enum" let selfIsMulticastDelegate = nm = "System.MulticastDelegate" - if isEnum then ILTypeDefKind.Enum + if isEnum then ILTypeDefKind.Enum elif (isDelegate && not selfIsMulticastDelegate) || isMulticastDelegate then ILTypeDefKind.Delegate - elif isValueType then ILTypeDefKind.ValueType - else ILTypeDefKind.Class + elif isValueType then ILTypeDefKind.ValueType + else ILTypeDefKind.Class -let convertTypeAccessFlags access = - match access with +let convertTypeAccessFlags access = + match access with | ILTypeDefAccess.Public -> TypeAttributes.Public | ILTypeDefAccess.Private -> TypeAttributes.NotPublic | ILTypeDefAccess.Nested ILMemberAccess.Public -> TypeAttributes.NestedPublic @@ -2029,24 +2019,24 @@ let convertToNestedTypeAccess (ilMemberAccess: ILMemberAccess) = | ILMemberAccess.Family -> TypeAttributes.NestedFamily | ILMemberAccess.Private -> TypeAttributes.NestedPrivate | ILMemberAccess.Public -> TypeAttributes.NestedPublic - + let convertInitSemantics (init: ILTypeInit) = - match init with + match init with | ILTypeInit.BeforeField -> TypeAttributes.BeforeFieldInit | ILTypeInit.OnAny -> enum 0 [] type ILTypeDef(name: string, attributes: TypeAttributes, layout: ILTypeDefLayout, implements: ILTypes, genericParams: ILGenericParameterDefs, extends: ILType option, methods: ILMethodDefs, nestedTypes: ILTypeDefs, fields: ILFieldDefs, methodImpls: ILMethodImplDefs, - events: ILEventDefs, properties: ILPropertyDefs, securityDeclsStored: ILSecurityDeclsStored, customAttrsStored: ILAttributesStored, metadataIndex: int32) = + events: ILEventDefs, properties: ILPropertyDefs, securityDeclsStored: ILSecurityDeclsStored, customAttrsStored: ILAttributesStored, metadataIndex: int32) = let mutable customAttrsStored = customAttrsStored static member CreateStored (name, attributes, layout, implements, genericParams, extends, methods, nestedTypes, fields, methodImpls, events, properties, securityDeclsStored, customAttrsStored, metadataIndex) = ILTypeDef (name, attributes, layout, implements, genericParams, extends, methods, nestedTypes, fields, methodImpls, events, properties, securityDeclsStored, customAttrsStored, metadataIndex) - static member Create (name, attributes, layout, implements, genericParams, extends, methods, nestedTypes, fields, methodImpls, events, properties, securityDecls, customAttrs) = - ILTypeDef (name, attributes, layout, implements, genericParams, extends, methods, nestedTypes, fields, methodImpls, events, properties, storeILSecurityDecls securityDecls, storeILCustomAttrs customAttrs, NoMetadataIdx) + static member Create (name, attributes, layout, implements, genericParams, extends, methods, nestedTypes, fields, methodImpls, events, properties, securityDecls, customAttrs) = + ILTypeDef (name, attributes, layout, implements, genericParams, extends, methods, nestedTypes, fields, methodImpls, events, properties, storeILSecurityDecls securityDecls, storeILCustomAttrs customAttrs, NoMetadataIdx) member __.Name = name member __.Attributes = attributes @@ -2064,7 +2054,7 @@ type ILTypeDef(name: string, attributes: TypeAttributes, layout: ILTypeDefLayout member __.CustomAttrsStored = customAttrsStored member __.MetadataIndex = metadataIndex - member x.With(?name, ?attributes, ?layout, ?implements, ?genericParams, ?extends, ?methods, ?nestedTypes, ?fields, ?methodImpls, ?events, ?properties, ?customAttrs, ?securityDecls) = + member x.With(?name, ?attributes, ?layout, ?implements, ?genericParams, ?extends, ?methods, ?nestedTypes, ?fields, ?methodImpls, ?events, ?properties, ?customAttrs, ?securityDecls) = ILTypeDef.Create(name=defaultArg name x.Name, attributes=defaultArg attributes x.Attributes, layout=defaultArg layout x.Layout, @@ -2080,13 +2070,13 @@ type ILTypeDef(name: string, attributes: TypeAttributes, layout: ILTypeDefLayout properties = defaultArg properties x.Properties, customAttrs = defaultArg customAttrs x.CustomAttrs) - member x.CustomAttrs = - match customAttrsStored with + member x.CustomAttrs = + match customAttrsStored with | ILAttributesStored.Reader f -> let res = ILAttributes(f x.MetadataIndex) customAttrsStored <- ILAttributesStored.Given res - res - | ILAttributesStored.Given res -> + res + | ILAttributesStored.Given res -> res member x.SecurityDecls = x.SecurityDeclsStored.GetSecurityDecls x.MetadataIndex @@ -2096,11 +2086,11 @@ type ILTypeDef(name: string, attributes: TypeAttributes, layout: ILTypeDefLayout member x.IsInterface = (typeKindOfFlags x.Name x.Methods x.Fields x.Extends (int x.Attributes)) = ILTypeDefKind.Interface member x.IsEnum = (typeKindOfFlags x.Name x.Methods x.Fields x.Extends (int x.Attributes)) = ILTypeDefKind.Enum member x.IsDelegate = (typeKindOfFlags x.Name x.Methods x.Fields x.Extends (int x.Attributes)) = ILTypeDefKind.Delegate - member x.Access = typeAccessOfFlags (int x.Attributes) + member x.Access = typeAccessOfFlags (int x.Attributes) member x.IsAbstract = x.Attributes &&& TypeAttributes.Abstract <> enum 0 member x.IsSealed = x.Attributes &&& TypeAttributes.Sealed <> enum 0 member x.IsSerializable = x.Attributes &&& TypeAttributes.Serializable <> enum 0 - member x.IsComInterop = x.Attributes &&& TypeAttributes.Import <> enum 0 (* Class or interface generated for COM interop *) + member x.IsComInterop = x.Attributes &&& TypeAttributes.Import <> enum 0 (* Class or interface generated for COM interop *) member x.IsSpecialName = x.Attributes &&& TypeAttributes.SpecialName <> enum 0 member x.HasSecurity = x.Attributes &&& TypeAttributes.HasSecurity <> enum 0 member x.Encoding = typeEncodingOfFlags (int x.Attributes) @@ -2122,10 +2112,10 @@ and [] ILTypeDefs(f : unit -> ILPreTypeDef[]) = let mutable array = InlineDelayInit<_>(f) - let mutable dict = InlineDelayInit<_>(fun () -> + let mutable dict = InlineDelayInit<_>(fun () -> let arr = array.Value let t = Dictionary<_, _>(HashIdentity.Structural) - for pre in arr do + for pre in arr do let key = pre.Namespace, pre.Name t.[key] <- pre t) @@ -2134,46 +2124,53 @@ and [] ILTypeDefs(f : unit -> ILPreTypeDef[]) = member x.AsList = [ for pre in array.Value -> pre.GetTypeDef() ] - interface IEnumerable with + interface IEnumerable with member x.GetEnumerator() = ((x :> IEnumerable).GetEnumerator() :> IEnumerator) - interface IEnumerable with - member x.GetEnumerator() = + interface IEnumerable with + member x.GetEnumerator() = (seq { for pre in array.Value -> pre.GetTypeDef() }).GetEnumerator() - + member x.AsArrayOfPreTypeDefs = array.Value - member x.FindByName nm = + member x.FindByName nm = let ns, n = splitILTypeName nm dict.Value.[(ns, n)].GetTypeDef() + +and [] ILPreTypeDef = + abstract Namespace: string list + abstract Name: string + abstract GetTypeDef: unit -> ILTypeDef + + /// This is a memory-critical class. Very many of these objects get allocated and held to represent the contents of .NET assemblies. -and [] ILPreTypeDef(nameSpace: string list, name: string, metadataIndex: int32, storage: ILTypeDefStored) = +and [] ILPreTypeDefImpl(nameSpace: string list, name: string, metadataIndex: int32, storage: ILTypeDefStored) = let mutable store : ILTypeDef = Unchecked.defaultof<_> - member __.Namespace = nameSpace - member __.Name = name - member __.MetadataIndex = metadataIndex - - member x.GetTypeDef() = - match box store with - | null -> - match storage with - | ILTypeDefStored.Given td -> - store <- td - td + interface ILPreTypeDef with + member __.Namespace = nameSpace + member __.Name = name + + member x.GetTypeDef() = + match box store with + | null -> + match storage with + | ILTypeDefStored.Given td -> + store <- td + td #if FABLE_COMPILER - | ILTypeDefStored.Computed f -> store <- f(); store - | ILTypeDefStored.Reader f -> store <- f x.MetadataIndex; store + | ILTypeDefStored.Computed f -> store <- f(); store + | ILTypeDefStored.Reader f -> store <- f metadataIndex; store #else - | ILTypeDefStored.Computed f -> - System.Threading.LazyInitializer.EnsureInitialized(&store, System.Func<_>(fun () -> f())) - | ILTypeDefStored.Reader f -> - System.Threading.LazyInitializer.EnsureInitialized(&store, System.Func<_>(fun () -> f x.MetadataIndex)) + | ILTypeDefStored.Computed f -> + LazyInitializer.EnsureInitialized(&store, Func<_>(fun () -> f())) + | ILTypeDefStored.Reader f -> + LazyInitializer.EnsureInitialized(&store, Func<_>(fun () -> f metadataIndex)) #endif - | _ -> store - -and ILTypeDefStored = + | _ -> store + +and ILTypeDefStored = | Given of ILTypeDef | Reader of (int32 -> ILTypeDef) | Computed of (unit -> ILTypeDef) @@ -2184,15 +2181,15 @@ type ILNestedExportedType = { Name: string Access: ILMemberAccess Nested: ILNestedExportedTypes - CustomAttrsStored: ILAttributesStored - MetadataIndex: int32 } + CustomAttrsStored: ILAttributesStored + MetadataIndex: int32 } member x.CustomAttrs = x.CustomAttrsStored.GetCustomAttrs x.MetadataIndex -and ILNestedExportedTypes = +and ILNestedExportedTypes = | ILNestedExportedTypes of Lazy> - member x.AsList = let (ILNestedExportedTypes ltab) = x in Map.foldBack (fun _x y r -> y::r) (ltab.Force()) [] + member x.AsList = let (ILNestedExportedTypes ltab) = x in Map.foldBack (fun _x y r -> y :: r) (ltab.Force()) [] and [] ILExportedTypeOrForwarder = @@ -2200,29 +2197,33 @@ and [] Name: string Attributes: TypeAttributes Nested: ILNestedExportedTypes - CustomAttrsStored: ILAttributesStored - MetadataIndex: int32 } + CustomAttrsStored: ILAttributesStored + MetadataIndex: int32 } - member x.Access = typeAccessOfFlags (int x.Attributes) + member x.Access = typeAccessOfFlags (int x.Attributes) member x.IsForwarder = x.Attributes &&& enum(0x00200000) <> enum 0 member x.CustomAttrs = x.CustomAttrsStored.GetCustomAttrs x.MetadataIndex -and ILExportedTypesAndForwarders = +and ILExportedTypesAndForwarders = | ILExportedTypesAndForwarders of Lazy> - member x.AsList = let (ILExportedTypesAndForwarders ltab) = x in Map.foldBack (fun _x y r -> y::r) (ltab.Force()) [] + member x.AsList = let (ILExportedTypesAndForwarders ltab) = x in Map.foldBack (fun _x y r -> y :: r) (ltab.Force()) [] + + member x.TryFindByName nm = + match x with + | ILExportedTypesAndForwarders ltab -> + ltab.Value.TryFind nm [] -type ILResourceAccess = - | Public - | Private +type ILResourceAccess = + | Public + | Private [] type ILResourceLocation = - | LocalIn of string * int * int - | LocalOut of byte[] + | Local of ReadOnlyByteMemory | File of ILModuleRef * int32 | Assembly of ILAssemblyRef @@ -2230,29 +2231,25 @@ type ILResource = { Name: string Location: ILResourceLocation Access: ILResourceAccess - CustomAttrsStored: ILAttributesStored + CustomAttrsStored: ILAttributesStored MetadataIndex: int32 } /// Read the bytes from a resource local to an assembly - member r.GetBytes() = + member r.GetBytes() = match r.Location with -#if !FABLE_COMPILER - | ILResourceLocation.LocalIn (file, start, len) -> - File.ReadBinaryChunk(file, start, len) -#endif - | ILResourceLocation.LocalOut bytes -> bytes + | ILResourceLocation.Local bytes -> bytes | _ -> failwith "GetBytes" member x.CustomAttrs = x.CustomAttrsStored.GetCustomAttrs x.MetadataIndex -type ILResources = +type ILResources = | ILResources of ILResource list member x.AsList = let (ILResources ltab) = x in ltab -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // One module in the "current" assembly -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- [] type ILAssemblyLongevity = @@ -2263,7 +2260,7 @@ type ILAssemblyLongevity = | PlatformSystem -type ILAssemblyManifest = +type ILAssemblyManifest = { Name: string AuxModuleHashAlgorithm: int32 SecurityDeclsStored: ILSecurityDeclsStored @@ -2272,30 +2269,30 @@ type ILAssemblyManifest = Locale: Locale option CustomAttrsStored: ILAttributesStored - AssemblyLongevity: ILAssemblyLongevity + AssemblyLongevity: ILAssemblyLongevity DisableJitOptimizations: bool JitTracking: bool IgnoreSymbolStoreSequencePoints: bool Retargetable: bool - /// Records the types implemented by other modules. + /// Records the types implemented by other modules. ExportedTypes: ILExportedTypesAndForwarders - /// Records whether the entrypoint resides in another module. - EntrypointElsewhere: ILModuleRef option + /// Records whether the entrypoint resides in another module. + EntrypointElsewhere: ILModuleRef option MetadataIndex: int32 - } + } member x.CustomAttrs = x.CustomAttrsStored.GetCustomAttrs x.MetadataIndex member x.SecurityDecls = x.SecurityDeclsStored.GetSecurityDecls x.MetadataIndex [] -type ILNativeResource = +type ILNativeResource = | In of fileName: string * linkedResourceBase: int * linkedResourceStart: int * linkedResourceLength: int | Out of unlinkedResource: byte[] -type ILModuleDef = +type ILModuleDef = { Manifest: ILAssemblyManifest option Name: string TypeDefs: ILTypeDefs @@ -2315,24 +2312,24 @@ type ILModuleDef = MetadataVersion: string Resources: ILResources /// e.g. win32 resources - NativeResources: ILNativeResource list + NativeResources: ILNativeResource list CustomAttrsStored: ILAttributesStored MetadataIndex: int32 } - member x.ManifestOfAssembly = - match x.Manifest with + member x.ManifestOfAssembly = + match x.Manifest with | Some m -> m | None -> failwith "no manifest" - member m.HasManifest = + member m.HasManifest = match m.Manifest with None -> false | _ -> true member x.CustomAttrs = x.CustomAttrsStored.GetCustomAttrs x.MetadataIndex -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Add fields and types to tables, with decent error messages // when clashes occur... -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- let mkILEmptyGenericParams = ([]: ILGenericParameterDefs) @@ -2340,26 +2337,26 @@ let emptyILGenericArgsList = ([]: ILType list) // -------------------------------------------------------------------- // Make ILTypeRefs etc. -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -let mkILNestedTyRef (scope, l, nm) = ILTypeRef.Create(scope, l, nm) +let mkILNestedTyRef (scope, l, nm) = ILTypeRef.Create (scope, l, nm) let mkILTyRef (scope, nm) = mkILNestedTyRef (scope, [], nm) type ILGenericArgsList = ILType list -let mkILTySpec (tref, inst) = ILTypeSpec.Create(tref, inst) +let mkILTySpec (tref, inst) = ILTypeSpec.Create (tref, inst) let mkILNonGenericTySpec tref = mkILTySpec (tref, []) -let mkILTyRefInTyRef (tref: ILTypeRef, nm) = +let mkILTyRefInTyRef (tref: ILTypeRef, nm) = mkILNestedTyRef (tref.Scope, tref.Enclosing@[tref.Name], nm) -let mkILTy boxed tspec = +let mkILTy boxed tspec = match boxed with AsObject -> mkILBoxedType tspec | _ -> ILType.Value tspec -let mkILNamedTy vc tref tinst = mkILTy vc (ILTypeSpec.Create(tref, tinst)) +let mkILNamedTy vc tref tinst = mkILTy vc (ILTypeSpec.Create (tref, tinst)) let mkILValueTy tref tinst = mkILNamedTy AsValue tref tinst @@ -2369,31 +2366,31 @@ let mkILNonGenericValueTy tref = mkILNamedTy AsValue tref [] let mkILNonGenericBoxedTy tref = mkILNamedTy AsObject tref [] -let mkSimpleAssemblyRef n = - ILAssemblyRef.Create(n, None, None, false, None, None) +let mkSimpleAssemblyRef n = + ILAssemblyRef.Create (n, None, None, false, None, None) -let mkSimpleModRef n = - ILModuleRef.Create(n, true, None) +let mkSimpleModRef n = + ILModuleRef.Create (n, true, None) // -------------------------------------------------------------------- // The toplevel class of a module is called "" -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- let typeNameForGlobalFunctions = "" -let mkILTypeForGlobalFunctions scoref = mkILBoxedType (mkILNonGenericTySpec (ILTypeRef.Create(scoref, [], typeNameForGlobalFunctions))) +let mkILTypeForGlobalFunctions scoref = mkILBoxedType (mkILNonGenericTySpec (ILTypeRef.Create (scoref, [], typeNameForGlobalFunctions))) let isTypeNameForGlobalFunctions d = (d = typeNameForGlobalFunctions) let mkILMethRef (tref, callconv, nm, gparams, args, rty) = - { mrefParent=tref + { mrefParent=tref mrefCallconv=callconv mrefGenericArity=gparams mrefName=nm mrefArgs=args mrefReturn=rty} -let mkILMethSpecForMethRefInTy (mref, ty, minst) = +let mkILMethSpecForMethRefInTy (mref, ty, minst) = { mspecMethodRef=mref mspecDeclaringType=ty mspecMethodInst=minst } @@ -2406,7 +2403,7 @@ let mkILMethSpecInTypeRef (tref, vc, cc, nm, args, rty, tinst, minst) = let mkILMethSpecInTy (ty: ILType, cc, nm, args, rty, minst: ILGenericArgs) = mkILMethSpecForMethRefInTy (mkILMethRef (ty.TypeRef, cc, nm, minst.Length, args, rty), ty, minst) -let mkILNonGenericMethSpecInTy (ty, cc, nm, args, rty) = +let mkILNonGenericMethSpecInTy (ty, cc, nm, args, rty) = mkILMethSpecInTy (ty, cc, nm, args, rty, []) let mkILInstanceMethSpecInTy (ty: ILType, nm, args, rty, minst) = @@ -2421,33 +2418,33 @@ let mkILStaticMethSpecInTy (ty, nm, args, rty, minst) = let mkILNonGenericStaticMethSpecInTy (ty, nm, args, rty) = mkILStaticMethSpecInTy (ty, nm, args, rty, []) -let mkILCtorMethSpec (tref, args, cinst) = - mkILMethSpecInTypeRef(tref, AsObject, ILCallingConv.Instance, ".ctor", args, ILType.Void, cinst, []) +let mkILCtorMethSpec (tref, args, cinst) = + mkILMethSpecInTypeRef (tref, AsObject, ILCallingConv.Instance, ".ctor", args, ILType.Void, cinst, []) -let mkILCtorMethSpecForTy (ty, args) = - mkILMethSpecInTy(ty, ILCallingConv.Instance, ".ctor", args, ILType.Void, []) +let mkILCtorMethSpecForTy (ty, args) = + mkILMethSpecInTy (ty, ILCallingConv.Instance, ".ctor", args, ILType.Void, []) -let mkILNonGenericCtorMethSpec (tref, args) = +let mkILNonGenericCtorMethSpec (tref, args) = mkILCtorMethSpec (tref, args, []) // -------------------------------------------------------------------- // Make references to fields -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -let mkILFieldRef(tref, nm, ty) = { DeclaringTypeRef=tref; Name=nm; Type=ty} +let mkILFieldRef (tref, nm, ty) = { DeclaringTypeRef=tref; Name=nm; Type=ty} let mkILFieldSpec (tref, ty) = { FieldRef= tref; DeclaringType=ty } -let mkILFieldSpecInTy (ty: ILType, nm, fty) = +let mkILFieldSpecInTy (ty: ILType, nm, fty) = mkILFieldSpec (mkILFieldRef (ty.TypeRef, nm, fty), ty) - -let andTailness x y = + +let andTailness x y = match x with Tailcall when y -> Tailcall | _ -> Normalcall -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Basic operations on code. -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- let formatCodeLabel (x: int) = "L"+string x @@ -2456,17 +2453,17 @@ let codeLabelCount = ref 0 #if FABLE_COMPILER let generateCodeLabel() = codeLabelCount := !codeLabelCount + 1; !codeLabelCount #else -let generateCodeLabel() = System.Threading.Interlocked.Increment(codeLabelCount) +let generateCodeLabel() = Interlocked.Increment codeLabelCount #endif -let instrIsRet i = - match i with +let instrIsRet i = + match i with | I_ret -> true | _ -> false -let nonBranchingInstrsToCode instrs : ILCode = +let nonBranchingInstrsToCode instrs : ILCode = let instrs = Array.ofList instrs - let instrs = + let instrs = if instrs.Length <> 0 && instrIsRet (Array.last instrs) then instrs else Array.append instrs [| I_ret |] @@ -2476,9 +2473,9 @@ let nonBranchingInstrsToCode instrs : ILCode = Locals = [] } -// -------------------------------------------------------------------- -// -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- +// +// -------------------------------------------------------------------- let mkILTyvarTy tv = ILType.TypeVar tv @@ -2498,29 +2495,29 @@ let mkILFormalTypars (x: ILGenericArgsList) = List.map gparam_of_gactual x let mkILFormalGenericArgs numtypars (gparams: ILGenericParameterDefs) = List.mapi (fun n _gf -> mkILTyvarTy (uint16 (numtypars + n))) gparams - + let mkILFormalBoxedTy tref gparams = mkILBoxedTy tref (mkILFormalGenericArgs 0 gparams) let mkILFormalNamedTy bx tref gparams = mkILNamedTy bx tref (mkILFormalGenericArgs 0 gparams) -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Operations on class etc. defs. -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -let mkRefForNestedILTypeDef scope (enc: ILTypeDef list, td: ILTypeDef) = - mkILNestedTyRef(scope, (enc |> List.map (fun etd -> etd.Name)), td.Name) +let mkRefForNestedILTypeDef scope (enc: ILTypeDef list, td: ILTypeDef) = + mkILNestedTyRef (scope, (enc |> List.map (fun etd -> etd.Name)), td.Name) -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Operations on type tables. -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -let mkILPreTypeDef (td: ILTypeDef) = +let mkILPreTypeDef (td: ILTypeDef) = let ns, n = splitILTypeName td.Name - ILPreTypeDef(ns, n, NoMetadataIdx, ILTypeDefStored.Given td) + ILPreTypeDefImpl (ns, n, NoMetadataIdx, ILTypeDefStored.Given td) :> ILPreTypeDef let mkILPreTypeDefComputed (ns, n, f) = - ILPreTypeDef(ns, n, NoMetadataIdx, ILTypeDefStored.Computed f) + ILPreTypeDefImpl (ns, n, NoMetadataIdx, ILTypeDefStored.Computed f) :> ILPreTypeDef let mkILPreTypeDefRead (ns, n, idx, f) = - ILPreTypeDef(ns, n, idx, f) + ILPreTypeDefImpl (ns, n, idx, f) :> ILPreTypeDef let addILTypeDef td (tdefs: ILTypeDefs) = ILTypeDefs (fun () -> [| yield mkILPreTypeDef td; yield! tdefs.AsArrayOfPreTypeDefs |]) @@ -2529,42 +2526,45 @@ let mkILTypeDefs l = mkILTypeDefsFromArray (Array.ofList l) let mkILTypeDefsComputed f = ILTypeDefs f let emptyILTypeDefs = mkILTypeDefsFromArray [| |] -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Operations on method tables. -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- let mkILMethodsFromArray xs = ILMethodDefs (fun () -> xs) let mkILMethods xs = xs |> Array.ofList |> mkILMethodsFromArray let mkILMethodsComputed f = ILMethodDefs f let emptyILMethods = mkILMethodsFromArray [| |] -let filterILMethodDefs f (mdefs: ILMethodDefs) = +let filterILMethodDefs f (mdefs: ILMethodDefs) = ILMethodDefs (fun () -> mdefs.AsArray |> Array.filter f) -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Operations and defaults for modules, assemblies etc. -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- let defaultSubSystem = 3 (* this is what comes out of ILDASM on 30/04/2001 *) let defaultPhysAlignment = 512 (* this is what comes out of ILDASM on 30/04/2001 *) let defaultVirtAlignment = 0x2000 (* this is what comes out of ILDASM on 30/04/2001 *) let defaultImageBase = 0x034f0000 (* this is what comes out of ILDASM on 30/04/2001 *) -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Array types -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -let mkILArrTy (ty, shape) = ILType.Array(shape, ty) +let mkILArrTy (ty, shape) = ILType.Array (shape, ty) let mkILArr1DTy ty = mkILArrTy (ty, ILArrayShape.SingleDimensional) let isILArrTy ty = match ty with ILType.Array _ -> true| _ -> false -let destILArrTy ty = match ty with ILType.Array(shape, ty) -> (shape, ty) | _ -> failwith "destILArrTy" +let destILArrTy ty = + match ty with + | ILType.Array (shape, ty) -> (shape, ty) + | _ -> failwith "destILArrTy" -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Sigs of special types built-in -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- [] let tname_Object = "System.Object" @@ -2620,51 +2620,47 @@ let tname_IntPtr = "System.IntPtr" [] let tname_UIntPtr = "System.UIntPtr" +[] +let tname_TypedReference = "System.TypedReference" + [] -// This data structure needs an entirely delayed implementation -type ILGlobals(primaryScopeRef) = - - let m_mkSysILTypeRef nm = mkILTyRef(primaryScopeRef, nm) - - let m_typ_Object = mkILBoxedType (mkILNonGenericTySpec (m_mkSysILTypeRef tname_Object)) - let m_typ_String = mkILBoxedType (mkILNonGenericTySpec (m_mkSysILTypeRef tname_String)) - let m_typ_Array = mkILBoxedType (mkILNonGenericTySpec (m_mkSysILTypeRef tname_Array)) - let m_typ_Type = mkILBoxedType (mkILNonGenericTySpec (m_mkSysILTypeRef tname_Type)) - let m_typ_SByte = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_SByte)) - let m_typ_Int16 = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_Int16)) - let m_typ_Int32 = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_Int32)) - let m_typ_Int64 = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_Int64)) - let m_typ_Byte = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_Byte)) - let m_typ_UInt16 = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_UInt16)) - let m_typ_UInt32 = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_UInt32)) - let m_typ_UInt64 = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_UInt64)) - let m_typ_Single = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_Single)) - let m_typ_Double = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_Double)) - let m_typ_Bool = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_Bool)) - let m_typ_Char = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_Char)) - let m_typ_IntPtr = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_IntPtr)) - let m_typ_UIntPtr = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_UIntPtr)) - - member x.primaryAssemblyScopeRef = m_typ_Object.TypeRef.Scope - member x.primaryAssemblyName = m_typ_Object.TypeRef.Scope.AssemblyRef.Name - member x.typ_Object = m_typ_Object - member x.typ_String = m_typ_String - member x.typ_Array = m_typ_Array - member x.typ_Type = m_typ_Type - member x.typ_IntPtr = m_typ_IntPtr - member x.typ_UIntPtr = m_typ_UIntPtr - member x.typ_Byte = m_typ_Byte - member x.typ_Int16 = m_typ_Int16 - member x.typ_Int32 = m_typ_Int32 - member x.typ_Int64 = m_typ_Int64 - member x.typ_SByte = m_typ_SByte - member x.typ_UInt16 = m_typ_UInt16 - member x.typ_UInt32 = m_typ_UInt32 - member x.typ_UInt64 = m_typ_UInt64 - member x.typ_Single = m_typ_Single - member x.typ_Double = m_typ_Double - member x.typ_Bool = m_typ_Bool - member x.typ_Char = m_typ_Char +type ILGlobals(primaryScopeRef: ILScopeRef, assembliesThatForwardToPrimaryAssembly: ILAssemblyRef list) = + + let assembliesThatForwardToPrimaryAssembly = Array.ofList assembliesThatForwardToPrimaryAssembly + + let mkSysILTypeRef nm = mkILTyRef (primaryScopeRef, nm) + + member _.primaryAssemblyScopeRef = primaryScopeRef + member x.primaryAssemblyRef = + match primaryScopeRef with + | ILScopeRef.Assembly aref -> aref + | _ -> failwith "Invalid primary assembly" + member x.primaryAssemblyName = x.primaryAssemblyRef.Name + + member val typ_Object = mkILBoxedType (mkILNonGenericTySpec (mkSysILTypeRef tname_Object)) + member val typ_String = mkILBoxedType (mkILNonGenericTySpec (mkSysILTypeRef tname_String)) + member val typ_Array = mkILBoxedType (mkILNonGenericTySpec (mkSysILTypeRef tname_Array)) + member val typ_Type = mkILBoxedType (mkILNonGenericTySpec (mkSysILTypeRef tname_Type)) + member val typ_SByte = ILType.Value (mkILNonGenericTySpec (mkSysILTypeRef tname_SByte)) + member val typ_Int16 = ILType.Value (mkILNonGenericTySpec (mkSysILTypeRef tname_Int16)) + member val typ_Int32 = ILType.Value (mkILNonGenericTySpec (mkSysILTypeRef tname_Int32)) + member val typ_Int64 = ILType.Value (mkILNonGenericTySpec (mkSysILTypeRef tname_Int64)) + member val typ_Byte = ILType.Value (mkILNonGenericTySpec (mkSysILTypeRef tname_Byte)) + member val typ_UInt16 = ILType.Value (mkILNonGenericTySpec (mkSysILTypeRef tname_UInt16)) + member val typ_UInt32 = ILType.Value (mkILNonGenericTySpec (mkSysILTypeRef tname_UInt32)) + member val typ_UInt64 = ILType.Value (mkILNonGenericTySpec (mkSysILTypeRef tname_UInt64)) + member val typ_Single = ILType.Value (mkILNonGenericTySpec (mkSysILTypeRef tname_Single)) + member val typ_Double = ILType.Value (mkILNonGenericTySpec (mkSysILTypeRef tname_Double)) + member val typ_Bool = ILType.Value (mkILNonGenericTySpec (mkSysILTypeRef tname_Bool)) + member val typ_Char = ILType.Value (mkILNonGenericTySpec (mkSysILTypeRef tname_Char)) + member val typ_IntPtr = ILType.Value (mkILNonGenericTySpec (mkSysILTypeRef tname_IntPtr)) + member val typ_UIntPtr = ILType.Value (mkILNonGenericTySpec (mkSysILTypeRef tname_UIntPtr)) + member val typ_TypedReference = ILType.Value (mkILNonGenericTySpec (mkSysILTypeRef tname_TypedReference)) + + member x.IsPossiblePrimaryAssemblyRef(aref: ILAssemblyRef) = + aref.EqualsIgnoringVersion x.primaryAssemblyRef || + assembliesThatForwardToPrimaryAssembly + |> Array.exists aref.EqualsIgnoringVersion /// For debugging [] @@ -2672,7 +2668,7 @@ type ILGlobals(primaryScopeRef) = override x.ToString() = "" -let mkILGlobals primaryScopeRef = ILGlobals primaryScopeRef +let mkILGlobals (primaryScopeRef, assembliesThatForwardToPrimaryAssembly) = ILGlobals (primaryScopeRef, assembliesThatForwardToPrimaryAssembly) let mkNormalCall mspec = I_call (Normalcall, mspec, None) @@ -2711,122 +2707,123 @@ let tname_CompilerGeneratedAttribute = "System.Runtime.CompilerServices.Compiler let tname_DebuggableAttribute = "System.Diagnostics.DebuggableAttribute" (* NOTE: ecma_ prefix refers to the standard "mscorlib" *) -let ecmaPublicKey = PublicKeyToken (Bytes.ofInt32Array [|0xde; 0xad; 0xbe; 0xef; 0xca; 0xfe; 0xfa; 0xce |]) - +let ecmaPublicKey = PublicKeyToken (Bytes.ofInt32Array [|0xde; 0xad; 0xbe; 0xef; 0xca; 0xfe; 0xfa; 0xce |]) + let isILBoxedTy = function ILType.Boxed _ -> true | _ -> false let isILValueTy = function ILType.Value _ -> true | _ -> false -let isPrimaryAssemblyTySpec (tspec: ILTypeSpec) n = +let isBuiltInTySpec (ilg: ILGlobals) (tspec: ILTypeSpec) n = let tref = tspec.TypeRef let scoref = tref.Scope - (tref.Name = n) && - match scoref with - | ILScopeRef.Assembly n -> PrimaryAssembly.IsSomePrimaryAssembly n.Name - | ILScopeRef.Module _ -> false - | ILScopeRef.Local -> true + tref.Name = n && + (match scoref with + | ILScopeRef.Local + | ILScopeRef.Module _ -> false + | ILScopeRef.Assembly aref -> ilg.IsPossiblePrimaryAssemblyRef aref + | ILScopeRef.PrimaryAssembly -> true) + +let isILBoxedBuiltInTy ilg (ty: ILType) n = + isILBoxedTy ty && isBuiltInTySpec ilg ty.TypeSpec n -let isILBoxedPrimaryAssemblyTy (ty: ILType) n = - isILBoxedTy ty && isPrimaryAssemblyTySpec ty.TypeSpec n +let isILValueBuiltInTy ilg (ty: ILType) n = + isILValueTy ty && isBuiltInTySpec ilg ty.TypeSpec n -let isILValuePrimaryAssemblyTy (ty: ILType) n = - isILValueTy ty && isPrimaryAssemblyTySpec ty.TypeSpec n - -let isILObjectTy ty = isILBoxedPrimaryAssemblyTy ty tname_Object +let isILObjectTy ilg ty = isILBoxedBuiltInTy ilg ty tname_Object -let isILStringTy ty = isILBoxedPrimaryAssemblyTy ty tname_String +let isILStringTy ilg ty = isILBoxedBuiltInTy ilg ty tname_String -let isILTypedReferenceTy ty = isILValuePrimaryAssemblyTy ty "System.TypedReference" +let isILTypedReferenceTy ilg ty = isILValueBuiltInTy ilg ty tname_TypedReference -let isILSByteTy ty = isILValuePrimaryAssemblyTy ty tname_SByte +let isILSByteTy ilg ty = isILValueBuiltInTy ilg ty tname_SByte -let isILByteTy ty = isILValuePrimaryAssemblyTy ty tname_Byte +let isILByteTy ilg ty = isILValueBuiltInTy ilg ty tname_Byte -let isILInt16Ty ty = isILValuePrimaryAssemblyTy ty tname_Int16 +let isILInt16Ty ilg ty = isILValueBuiltInTy ilg ty tname_Int16 -let isILUInt16Ty ty = isILValuePrimaryAssemblyTy ty tname_UInt16 +let isILUInt16Ty ilg ty = isILValueBuiltInTy ilg ty tname_UInt16 -let isILInt32Ty ty = isILValuePrimaryAssemblyTy ty tname_Int32 +let isILInt32Ty ilg ty = isILValueBuiltInTy ilg ty tname_Int32 -let isILUInt32Ty ty = isILValuePrimaryAssemblyTy ty tname_UInt32 +let isILUInt32Ty ilg ty = isILValueBuiltInTy ilg ty tname_UInt32 -let isILInt64Ty ty = isILValuePrimaryAssemblyTy ty tname_Int64 +let isILInt64Ty ilg ty = isILValueBuiltInTy ilg ty tname_Int64 -let isILUInt64Ty ty = isILValuePrimaryAssemblyTy ty tname_UInt64 +let isILUInt64Ty ilg ty = isILValueBuiltInTy ilg ty tname_UInt64 -let isILIntPtrTy ty = isILValuePrimaryAssemblyTy ty tname_IntPtr +let isILIntPtrTy ilg ty = isILValueBuiltInTy ilg ty tname_IntPtr -let isILUIntPtrTy ty = isILValuePrimaryAssemblyTy ty tname_UIntPtr +let isILUIntPtrTy ilg ty = isILValueBuiltInTy ilg ty tname_UIntPtr -let isILBoolTy ty = isILValuePrimaryAssemblyTy ty tname_Bool +let isILBoolTy ilg ty = isILValueBuiltInTy ilg ty tname_Bool -let isILCharTy ty = isILValuePrimaryAssemblyTy ty tname_Char +let isILCharTy ilg ty = isILValueBuiltInTy ilg ty tname_Char -let isILSingleTy ty = isILValuePrimaryAssemblyTy ty tname_Single +let isILSingleTy ilg ty = isILValueBuiltInTy ilg ty tname_Single -let isILDoubleTy ty = isILValuePrimaryAssemblyTy ty tname_Double +let isILDoubleTy ilg ty = isILValueBuiltInTy ilg ty tname_Double -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Rescoping -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -let rescopeILScopeRef scoref scoref1 = - match scoref, scoref1 with - | _, ILScopeRef.Local -> scoref +let rescopeILScopeRef scoref scoref1 = + match scoref, scoref1 with + | _, ILScopeRef.Local -> scoref | ILScopeRef.Local, _ -> scoref1 | _, ILScopeRef.Module _ -> scoref | ILScopeRef.Module _, _ -> scoref1 | _ -> scoref1 -let rescopeILTypeRef scoref (tref1: ILTypeRef) = - let scoref1 = tref1.Scope +let rescopeILTypeRef scoref (tref1: ILTypeRef) = + let scoref1 = tref1.Scope let scoref2 = rescopeILScopeRef scoref scoref1 if scoref1 === scoref2 then tref1 - else ILTypeRef.Create(scoref2, tref1.Enclosing, tref1.Name) + else ILTypeRef.Create (scoref2, tref1.Enclosing, tref1.Name) // ORIGINAL IMPLEMENTATION (too many allocations // { tspecTypeRef=rescopeILTypeRef scoref tref -// tspecInst=rescopeILTypes scoref tinst } -let rec rescopeILTypeSpec scoref (tspec1: ILTypeSpec) = +// tspecInst=rescopeILTypes scoref tinst } +let rec rescopeILTypeSpec scoref (tspec1: ILTypeSpec) = let tref1 = tspec1.TypeRef let tinst1 = tspec1.GenericArgs let tref2 = rescopeILTypeRef scoref tref1 - // avoid reallocation in the common case - if tref1 === tref2 then + // avoid reallocation in the common case + if tref1 === tref2 then if isNil tinst1 then tspec1 else let tinst2 = rescopeILTypes scoref tinst1 - if tinst1 === tinst2 then tspec1 else + if tinst1 === tinst2 then tspec1 else ILTypeSpec.Create (tref2, tinst2) else let tinst2 = rescopeILTypes scoref tinst1 ILTypeSpec.Create (tref2, tinst2) -and rescopeILType scoref ty = - match ty with +and rescopeILType scoref ty = + match ty with | ILType.Ptr t -> ILType.Ptr (rescopeILType scoref t) | ILType.FunctionPointer t -> ILType.FunctionPointer (rescopeILCallSig scoref t) | ILType.Byref t -> ILType.Byref (rescopeILType scoref t) - | ILType.Boxed cr1 -> + | ILType.Boxed cr1 -> let cr2 = rescopeILTypeSpec scoref cr1 - if cr1 === cr2 then ty else + if cr1 === cr2 then ty else mkILBoxedType cr2 - | ILType.Array (s, ety1) -> + | ILType.Array (s, ety1) -> let ety2 = rescopeILType scoref ety1 - if ety1 === ety2 then ty else + if ety1 === ety2 then ty else ILType.Array (s, ety2) - | ILType.Value cr1 -> - let cr2 = rescopeILTypeSpec scoref cr1 - if cr1 === cr2 then ty else + | ILType.Value cr1 -> + let cr2 = rescopeILTypeSpec scoref cr1 + if cr1 === cr2 then ty else ILType.Value cr2 - | ILType.Modified(b, tref, ty) -> ILType.Modified(b, rescopeILTypeRef scoref tref, rescopeILType scoref ty) + | ILType.Modified (b, tref, ty) -> ILType.Modified (b, rescopeILTypeRef scoref tref, rescopeILType scoref ty) | x -> x -and rescopeILTypes scoref i = +and rescopeILTypes scoref i = if isNil i then i else List.mapq (rescopeILType scoref) i -and rescopeILCallSig scoref csig = +and rescopeILCallSig scoref csig = mkILCallSig (csig.CallingConv, rescopeILTypes scoref csig.ArgTypes, rescopeILType scoref csig.ReturnType) let rescopeILMethodRef scoref (x: ILMethodRef) = @@ -2837,46 +2834,46 @@ let rescopeILMethodRef scoref (x: ILMethodRef) = mrefArgs = rescopeILTypes scoref x.mrefArgs mrefReturn= rescopeILType scoref x.mrefReturn } -let rescopeILFieldRef scoref x = +let rescopeILFieldRef scoref x = { DeclaringTypeRef = rescopeILTypeRef scoref x.DeclaringTypeRef Name= x.Name Type= rescopeILType scoref x.Type } -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Instantiate polymorphism in types -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -let rec instILTypeSpecAux numFree inst (tspec: ILTypeSpec) = - ILTypeSpec.Create(tspec.TypeRef, instILGenericArgsAux numFree inst tspec.GenericArgs) - -and instILTypeAux numFree (inst: ILGenericArgs) ty = - match ty with +let rec instILTypeSpecAux numFree inst (tspec: ILTypeSpec) = + ILTypeSpec.Create (tspec.TypeRef, instILGenericArgsAux numFree inst tspec.GenericArgs) + +and instILTypeAux numFree (inst: ILGenericArgs) ty = + match ty with | ILType.Ptr t -> ILType.Ptr (instILTypeAux numFree inst t) | ILType.FunctionPointer t -> ILType.FunctionPointer (instILCallSigAux numFree inst t) | ILType.Array (a, t) -> ILType.Array (a, instILTypeAux numFree inst t) | ILType.Byref t -> ILType.Byref (instILTypeAux numFree inst t) | ILType.Boxed cr -> mkILBoxedType (instILTypeSpecAux numFree inst cr) | ILType.Value cr -> ILType.Value (instILTypeSpecAux numFree inst cr) - | ILType.TypeVar v -> + | ILType.TypeVar v -> let v = int v let top = inst.Length if v < numFree then ty else - if v - numFree >= top then - ILType.TypeVar (uint16 (v - top)) - else + if v - numFree >= top then + ILType.TypeVar (uint16 (v - top)) + else List.item (v - numFree) inst | x -> x - + and instILGenericArgsAux numFree inst i = List.map (instILTypeAux numFree inst) i -and instILCallSigAux numFree inst csig = +and instILCallSigAux numFree inst csig = mkILCallSig (csig.CallingConv, List.map (instILTypeAux numFree inst) csig.ArgTypes, instILTypeAux numFree inst csig.ReturnType) let instILType i t = instILTypeAux 0 i t // -------------------------------------------------------------------- // MS-IL: Parameters, Return types and Locals -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- let mkILParam (name, ty) : ILParameter = { Name=name @@ -2893,40 +2890,40 @@ let mkILParamNamed (s, ty) = mkILParam (Some s, ty) let mkILParamAnon ty = mkILParam (None, ty) -let mkILReturn ty : ILReturn = +let mkILReturn ty : ILReturn = { Marshal=None Type=ty CustomAttrsStored=storeILCustomAttrs emptyILCustomAttrs MetadataIndex = NoMetadataIdx } -let mkILLocal ty dbgInfo : ILLocal = +let mkILLocal ty dbgInfo : ILLocal = { IsPinned=false Type=ty DebugInfo=dbgInfo } type ILFieldSpec with - member fr.ActualType = + member fr.ActualType = let env = fr.DeclaringType.GenericArgs instILType env fr.FormalType -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Make a method mbody -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -let mkILMethodBody (zeroinit, locals, maxstack, code, tag) : ILMethodBody = +let mkILMethodBody (zeroinit, locals, maxstack, code, tag) : ILMethodBody = { IsZeroInit=zeroinit MaxStack=maxstack NoInlining=false AggressiveInlining=false - Locals= locals + Locals= locals Code= code SourceMarker=tag } let mkMethodBody (zeroinit, locals, maxstack, code, tag) = MethodBody.IL (mkILMethodBody (zeroinit, locals, maxstack, code, tag)) -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Make a constructor -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- let mkILVoidReturn = mkILReturn ILType.Void @@ -2936,7 +2933,7 @@ let methBodyAbstract = mkMethBodyAux MethodBody.Abstract let methBodyNative = mkMethBodyAux MethodBody.Native -let mkILCtor (access, args, impl) = +let mkILCtor (access, args, impl) = ILMethodDef.Create(name=".ctor", attributes=(convertMemberAccess access ||| MethodAttributes.SpecialName ||| MethodAttributes.RTSpecialName), implAttributes=MethodImplAttributes.Managed, @@ -2949,9 +2946,9 @@ let mkILCtor (access, args, impl) = genericParams=mkILEmptyGenericParams, customAttrs = emptyILCustomAttrs) -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Do-nothing ctor, just pass on to monomorphic superclass -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- let mkCallBaseConstructor (ty, args: ILType list) = [ mkLdarg0 ] @ @@ -2968,20 +2965,20 @@ let mkNormalLdfld fspec = I_ldfld (Aligned, Nonvolatile, fspec) let mkNormalLdflda fspec = I_ldflda fspec -let mkNormalLdobj dt = I_ldobj(Aligned, Nonvolatile, dt) +let mkNormalLdobj dt = I_ldobj (Aligned, Nonvolatile, dt) -let mkNormalStobj dt = I_stobj(Aligned, Nonvolatile, dt) +let mkNormalStobj dt = I_stobj (Aligned, Nonvolatile, dt) -let mkILNonGenericEmptyCtor tag superTy = +let mkILNonGenericEmptyCtor tag superTy = let ctor = mkCallBaseConstructor (superTy, []) - mkILCtor(ILMemberAccess.Public, [], mkMethodBody(false, [], 8, nonBranchingInstrsToCode ctor, tag)) + mkILCtor (ILMemberAccess.Public, [], mkMethodBody (false, [], 8, nonBranchingInstrsToCode ctor, tag)) -// -------------------------------------------------------------------- -// Make a static, top level monomophic method - very useful for +// -------------------------------------------------------------------- +// Make a static, top level monomorphic method - very useful for // creating helper ILMethodDefs for internal use. -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -let mkILStaticMethod (genparams, nm, access, args, ret, impl) = +let mkILStaticMethod (genparams, nm, access, args, ret, impl) = ILMethodDef.Create(genericParams=genparams, name=nm, attributes=(convertMemberAccess access ||| MethodAttributes.Static), @@ -2994,10 +2991,10 @@ let mkILStaticMethod (genparams, nm, access, args, ret, impl) = customAttrs = emptyILCustomAttrs, body= mkMethBodyAux impl) -let mkILNonGenericStaticMethod (nm, access, args, ret, impl) = +let mkILNonGenericStaticMethod (nm, access, args, ret, impl) = mkILStaticMethod (mkILEmptyGenericParams, nm, access, args, ret, impl) -let mkILClassCtor impl = +let mkILClassCtor impl = ILMethodDef.Create(name=".cctor", attributes=(MethodAttributes.Private ||| MethodAttributes.Static ||| MethodAttributes.SpecialName ||| MethodAttributes.RTSpecialName), implAttributes=MethodImplAttributes.Managed, @@ -3010,19 +3007,19 @@ let mkILClassCtor impl = customAttrs=emptyILCustomAttrs, body= mkMethBodyAux impl) -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Make a virtual method, where the overriding is simply the default // (i.e. overrides by name/signature) -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- let mk_ospec (ty: ILType, callconv, nm, genparams, formal_args, formal_ret) = OverridesSpec (mkILMethRef (ty.TypeRef, callconv, nm, genparams, formal_args, formal_ret), ty) -let mkILGenericVirtualMethod (nm, access, genparams, actual_args, actual_ret, impl) = +let mkILGenericVirtualMethod (nm, access, genparams, actual_args, actual_ret, impl) = ILMethodDef.Create(name=nm, - attributes= + attributes= (convertMemberAccess access ||| - MethodAttributes.CheckAccessOnOverride ||| + MethodAttributes.CheckAccessOnOverride ||| (match impl with MethodBody.Abstract -> MethodAttributes.Abstract ||| MethodAttributes.Virtual | _ -> MethodAttributes.Virtual)), implAttributes=MethodImplAttributes.Managed, genericParams=genparams, @@ -3033,11 +3030,11 @@ let mkILGenericVirtualMethod (nm, access, genparams, actual_args, actual_ret, im securityDecls=emptyILSecurityDecls, customAttrs = emptyILCustomAttrs, body= mkMethBodyAux impl) - -let mkILNonGenericVirtualMethod (nm, access, args, ret, impl) = + +let mkILNonGenericVirtualMethod (nm, access, args, ret, impl) = mkILGenericVirtualMethod (nm, access, mkILEmptyGenericParams, args, ret, impl) -let mkILGenericNonVirtualMethod (nm, access, genparams, actual_args, actual_ret, impl) = +let mkILGenericNonVirtualMethod (nm, access, genparams, actual_args, actual_ret, impl) = ILMethodDef.Create(name=nm, attributes=(convertMemberAccess access ||| MethodAttributes.HideBySig), implAttributes=MethodImplAttributes.Managed, @@ -3049,67 +3046,67 @@ let mkILGenericNonVirtualMethod (nm, access, genparams, actual_args, actual_ret, securityDecls=emptyILSecurityDecls, customAttrs = emptyILCustomAttrs, body= mkMethBodyAux impl) - -let mkILNonGenericInstanceMethod (nm, access, args, ret, impl) = + +let mkILNonGenericInstanceMethod (nm, access, args, ret, impl) = mkILGenericNonVirtualMethod (nm, access, mkILEmptyGenericParams, args, ret, impl) -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Add some code to the end of the .cctor for a type. Create a .cctor // if one doesn't exist already. -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- let ilmbody_code2code f (il: ILMethodBody) = {il with Code = f il.Code} let mdef_code2code f (md: ILMethodDef) = - let il = - match md.Body.Contents with - | MethodBody.IL il-> il + let il = + match md.Body.Contents with + | MethodBody.IL il-> il | _ -> failwith "mdef_code2code - method not IL" let b = MethodBody.IL (ilmbody_code2code f il) - md.With(body= mkMethBodyAux b) + md.With(body = mkMethBodyAux b) -let prependInstrsToCode (instrs: ILInstr list) (c2: ILCode) = +let prependInstrsToCode (instrs: ILInstr list) (c2: ILCode) = let instrs = Array.ofList instrs let n = instrs.Length - match c2.Instrs.[0] with + match c2.Instrs.[0] with // If there is a sequence point as the first instruction then keep it at the front | I_seqpoint _ as i0 -> - let labels = + let labels = let dict = Dictionary.newWithSize c2.Labels.Count - for kvp in c2.Labels do dict.Add(kvp.Key, if kvp.Value = 0 then 0 else kvp.Value + n) + for kvp in c2.Labels do dict.Add (kvp.Key, if kvp.Value = 0 then 0 else kvp.Value + n) dict { c2 with Labels = labels Instrs = Array.concat [| [|i0|] ; instrs ; c2.Instrs.[1..] |] } | _ -> let labels = let dict = Dictionary.newWithSize c2.Labels.Count - for kvp in c2.Labels do dict.Add(kvp.Key, kvp.Value + n) + for kvp in c2.Labels do dict.Add (kvp.Key, kvp.Value + n) dict { c2 with Labels = labels Instrs = Array.append instrs c2.Instrs } -let prependInstrsToMethod new_code md = +let prependInstrsToMethod new_code md = mdef_code2code (prependInstrsToCode new_code) md -// Creates cctor if needed -let cdef_cctorCode2CodeOrCreate tag f (cd: ILTypeDef) = +// Creates cctor if needed +let cdef_cctorCode2CodeOrCreate tag f (cd: ILTypeDef) = let mdefs = cd.Methods - let cctor = - match mdefs.FindByName ".cctor" with + let cctor = + match mdefs.FindByName ".cctor" with | [mdef] -> mdef | [] -> mkILClassCtor (mkMethodBody (false, [], 1, nonBranchingInstrsToCode [ ], tag)) | _ -> failwith "bad method table: more than one .cctor found" - + let methods = ILMethodDefs (fun () -> [| yield f cctor; for md in mdefs do if md.Name <> ".cctor" then yield md |]) cd.With(methods = methods) -let code_of_mdef (md: ILMethodDef) = - match md.Code with +let code_of_mdef (md: ILMethodDef) = + match md.Code with | Some x -> x - | None -> failwith "code_of_mdef: not IL" + | None -> failwith "code_of_mdef: not IL" let mkRefToILMethod (tref, md: ILMethodDef) = mkILMethRef (tref, md.CallingConv, md.Name, md.GenericParams.Length, md.ParameterTypes, md.Return.Type) @@ -3120,16 +3117,16 @@ let mkRefForILMethod scope (tdefs, tdef) mdef = mkRefToILMethod (mkRefForNestedI let mkRefForILField scope (tdefs, tdef) (fdef: ILFieldDef) = mkILFieldRef (mkRefForNestedILTypeDef scope (tdefs, tdef), fdef.Name, fdef.FieldType) -// Creates cctor if needed -let prependInstrsToClassCtor instrs tag cd = - cdef_cctorCode2CodeOrCreate tag (prependInstrsToMethod instrs) cd +// Creates cctor if needed +let prependInstrsToClassCtor instrs tag cd = + cdef_cctorCode2CodeOrCreate tag (prependInstrsToMethod instrs) cd let mkILField (isStatic, nm, ty, (init: ILFieldInit option), (at: byte [] option), access, isLiteral) = ILFieldDef.Create(name=nm, fieldType=ty, attributes= (convertFieldAccess access ||| - (if isStatic then FieldAttributes.Static else enum 0) ||| + (if isStatic then FieldAttributes.Static else enum 0) ||| (if isLiteral then FieldAttributes.Literal else enum 0) ||| (if init.IsSome then FieldAttributes.HasDefault else enum 0) ||| (if at.IsSome then FieldAttributes.HasFieldRVA else enum 0)), @@ -3145,33 +3142,32 @@ let mkILStaticField (nm, ty, init, at, access) = mkILField (true, nm, ty, init, let mkILLiteralField (nm, ty, init, at, access) = mkILField (true, nm, ty, Some init, at, access, true) -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Scopes for allocating new temporary variables. -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -type ILLocalsAllocator(numPrealloc: int) = +type ILLocalsAllocator (numPrealloc: int) = let newLocals = ResizeArray() - member tmps.AllocLocal loc = - let locn = uint16(numPrealloc + newLocals.Count) + member tmps.AllocLocal loc = + let locn = uint16 (numPrealloc + newLocals.Count) newLocals.Add loc locn member tmps.Close() = ResizeArray.toList newLocals - -let mkILFieldsLazy l = ILFields (LazyOrderedMultiMap((fun (f: ILFieldDef) -> f.Name), l)) +let mkILFieldsLazy l = ILFields (LazyOrderedMultiMap ((fun (f: ILFieldDef) -> f.Name), l)) let mkILFields l = mkILFieldsLazy (notlazy l) let emptyILFields = mkILFields [] -let mkILEventsLazy l = ILEvents (LazyOrderedMultiMap((fun (e: ILEventDef) -> e.Name), l)) +let mkILEventsLazy l = ILEvents (LazyOrderedMultiMap ((fun (e: ILEventDef) -> e.Name), l)) let mkILEvents l = mkILEventsLazy (notlazy l) let emptyILEvents = mkILEvents [] -let mkILPropertiesLazy l = ILProperties (LazyOrderedMultiMap((fun (p: ILPropertyDef) -> p.Name), l) ) +let mkILPropertiesLazy l = ILProperties (LazyOrderedMultiMap ((fun (p: ILPropertyDef) -> p.Name), l) ) let mkILProperties l = mkILPropertiesLazy (notlazy l) @@ -3194,10 +3190,10 @@ let mkTypeForwarder scopeRef name nested customAttrs access = CustomAttrsStored=storeILCustomAttrs customAttrs MetadataIndex = NoMetadataIdx } -let mkILNestedExportedTypes l = +let mkILNestedExportedTypes l = ILNestedExportedTypes (notlazy (List.foldBack addNestedExportedTypeToTable l Map.empty)) -let mkILNestedExportedTypesLazy (l: Lazy<_>) = +let mkILNestedExportedTypesLazy (l: Lazy<_>) = ILNestedExportedTypes (lazy (List.foldBack addNestedExportedTypeToTable (l.Force()) Map.empty)) let mkILResources l = ILResources l @@ -3205,7 +3201,7 @@ let mkILResources l = ILResources l let addMethodImplToTable y tab = let key = (y.Overrides.MethodRef.Name, y.Overrides.MethodRef.ArgTypes.Length) let prev = Map.tryFindMulti key tab - Map.add key (y::prev) tab + Map.add key (y :: prev) tab let mkILMethodImpls l = ILMethodImpls (notlazy (List.foldBack addMethodImplToTable l Map.empty)) @@ -3215,42 +3211,42 @@ let emptyILMethodImpls = mkILMethodImpls [] /// Make a constructor that simply takes its arguments and stuffs /// them in fields. preblock is how to call the superclass constructor.... -let mkILStorageCtorWithParamNames(tag, preblock, ty, extraParams, flds, access) = +let mkILStorageCtorWithParamNames (tag, preblock, ty, extraParams, flds, access) = mkILCtor(access, (flds |> List.map (fun (pnm, _, ty) -> mkILParamNamed (pnm, ty))) @ extraParams, mkMethodBody (false, [], 2, nonBranchingInstrsToCode - begin - (match tag with Some x -> [I_seqpoint x] | None -> []) @ + begin + (match tag with Some x -> [I_seqpoint x] | None -> []) @ preblock @ - List.concat (List.mapi (fun n (_pnm, nm, fieldTy) -> + List.concat (List.mapi (fun n (_pnm, nm, fieldTy) -> [ mkLdarg0 mkLdarg (uint16 (n+1)) mkNormalStfld (mkILFieldSpecInTy (ty, nm, fieldTy)) ]) flds) end, tag)) - -let mkILSimpleStorageCtorWithParamNames(tag, baseTySpec, ty, extraParams, flds, access) = - let preblock = - match baseTySpec with + +let mkILSimpleStorageCtorWithParamNames (tag, baseTySpec, ty, extraParams, flds, access) = + let preblock = + match baseTySpec with None -> [] - | Some tspec -> - ([ mkLdarg0 + | Some tspec -> + ([ mkLdarg0 mkNormalCall (mkILCtorMethSpecForTy (mkILBoxedType tspec, [])) ]) - mkILStorageCtorWithParamNames(tag, preblock, ty, extraParams, flds, access) + mkILStorageCtorWithParamNames (tag, preblock, ty, extraParams, flds, access) -let addParamNames flds = +let addParamNames flds = flds |> List.map (fun (nm, ty) -> (nm, nm, ty)) -let mkILSimpleStorageCtor(tag, baseTySpec, ty, extraParams, flds, access) = - mkILSimpleStorageCtorWithParamNames(tag, baseTySpec, ty, extraParams, addParamNames flds, access) +let mkILSimpleStorageCtor (tag, baseTySpec, ty, extraParams, flds, access) = + mkILSimpleStorageCtorWithParamNames (tag, baseTySpec, ty, extraParams, addParamNames flds, access) -let mkILStorageCtor(tag, preblock, ty, flds, access) = mkILStorageCtorWithParamNames(tag, preblock, ty, [], addParamNames flds, access) +let mkILStorageCtor (tag, preblock, ty, flds, access) = mkILStorageCtorWithParamNames (tag, preblock, ty, [], addParamNames flds, access) let mkILGenericClass (nm, access, genparams, extends, impl, methods, fields, nestedTypes, props, events, attrs, init) = ILTypeDef.Create(name=nm, - attributes=(convertTypeAccessFlags access ||| TypeAttributes.AutoLayout ||| TypeAttributes.Class ||| + attributes=(convertTypeAccessFlags access ||| TypeAttributes.AutoLayout ||| TypeAttributes.Class ||| (match init with | ILTypeInit.BeforeField -> TypeAttributes.BeforeFieldInit | _ -> enum 0) ||| TypeAttributes.AnsiClass), genericParams= genparams, implements = impl, @@ -3264,11 +3260,11 @@ let mkILGenericClass (nm, access, genparams, extends, impl, methods, fields, nes properties=props, events=events, securityDecls=emptyILSecurityDecls) - + let mkRawDataValueTypeDef (iltyp_ValueType: ILType) (nm, size, pack) = ILTypeDef.Create(name = nm, genericParams= [], - attributes = (TypeAttributes.NotPublic ||| TypeAttributes.Sealed ||| TypeAttributes.ExplicitLayout ||| + attributes = (TypeAttributes.NotPublic ||| TypeAttributes.Sealed ||| TypeAttributes.ExplicitLayout ||| TypeAttributes.BeforeFieldInit ||| TypeAttributes.AnsiClass), implements = [], extends = Some iltyp_ValueType, @@ -3286,19 +3282,19 @@ let mkRawDataValueTypeDef (iltyp_ValueType: ILType) (nm, size, pack) = let mkILSimpleClass (ilg: ILGlobals) (nm, access, methods, fields, nestedTypes, props, events, attrs, init) = mkILGenericClass (nm, access, mkILEmptyGenericParams, ilg.typ_Object, [], methods, fields, nestedTypes, props, events, attrs, init) -let mkILTypeDefForGlobalFunctions ilg (methods, fields) = +let mkILTypeDefForGlobalFunctions ilg (methods, fields) = mkILSimpleClass ilg (typeNameForGlobalFunctions, ILTypeDefAccess.Public, methods, fields, emptyILTypeDefs, emptyILProperties, emptyILEvents, emptyILCustomAttrs, ILTypeInit.BeforeField) -let destTypeDefsWithGlobalFunctionsFirst ilg (tdefs: ILTypeDefs) = +let destTypeDefsWithGlobalFunctionsFirst ilg (tdefs: ILTypeDefs) = let l = tdefs.AsList let top, nontop = l |> List.partition (fun td -> td.Name = typeNameForGlobalFunctions) let top2 = if isNil top then [ mkILTypeDefForGlobalFunctions ilg (emptyILMethods, emptyILFields) ] else top top2@nontop -let mkILSimpleModule assemblyName modname dll subsystemVersion useHighEntropyVA tdefs hashalg locale flags exportedTypes metadataVersion = - let manifest = +let mkILSimpleModule assemblyName modname dll subsystemVersion useHighEntropyVA tdefs hashalg locale flags exportedTypes metadataVersion = + let manifest = { Name=assemblyName - AuxModuleHashAlgorithm= match hashalg with | Some(alg) -> alg | _ -> 0x8004 // SHA1 + AuxModuleHashAlgorithm= match hashalg with | Some alg -> alg | _ -> 0x8004 // SHA1 SecurityDeclsStored=emptyILSecurityDeclsStored PublicKey= None Version= None @@ -3310,7 +3306,7 @@ let mkILSimpleModule assemblyName modname dll subsystemVersion useHighEntropyVA IgnoreSymbolStoreSequencePoints = (0 <> (flags &&& 0x2000)) Retargetable = (0 <> (flags &&& 0x100)) ExportedTypes=exportedTypes - EntrypointElsewhere=None + EntrypointElsewhere=None MetadataIndex = NoMetadataIdx } { Manifest= Some manifest CustomAttrsStored=storeILCustomAttrs emptyILCustomAttrs @@ -3332,21 +3328,21 @@ let mkILSimpleModule assemblyName modname dll subsystemVersion useHighEntropyVA ImageBase=defaultImageBase MetadataVersion=metadataVersion Resources=mkILResources [] - MetadataIndex = NoMetadataIdx + MetadataIndex = NoMetadataIdx } //----------------------------------------------------------------------- // [instructions_to_code] makes the basic block structure of code from // a primitive array of instructions. We -// do this be iterating over the instructions, pushing new basic blocks -// everytime we encounter an address that has been recorded +// do this be iterating over the instructions, pushing new basic blocks +// every time we encounter an address that has been recorded // [bbstartToCodeLabelMap]. //----------------------------------------------------------------------- - + // REVIEW: this function shows up on performance traces. If we eliminated the last ILX->IL rewrites from the -// F# compiler we could get rid of this structured code representation from Abstract IL altogether and +// F# compiler we could get rid of this structured code representation from Abstract IL altogether and // never convert F# code into this form. let buildILCode (_methName: string) lab2pc instrs tryspecs localspecs : ILCode = { Labels = lab2pc @@ -3355,39 +3351,39 @@ let buildILCode (_methName: string) lab2pc instrs tryspecs localspecs : ILCode = Locals = localspecs } -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Detecting Delegates -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -let mkILDelegateMethods (access) (ilg: ILGlobals) (iltyp_AsyncCallback, iltyp_IAsyncResult) (parms, rtv: ILReturn) = +let mkILDelegateMethods (access) (ilg: ILGlobals) (iltyp_AsyncCallback, iltyp_IAsyncResult) (parms, rtv: ILReturn) = let rty = rtv.Type let one nm args ret = let mdef = mkILNonGenericVirtualMethod (nm, access, args, mkILReturn ret, MethodBody.Abstract) mdef.WithAbstract(false).WithHideBySig(true).WithRuntime(true) - let ctor = mkILCtor(access, [ mkILParamNamed("object", ilg.typ_Object); mkILParamNamed("method", ilg.typ_IntPtr) ], MethodBody.Abstract) + let ctor = mkILCtor (access, [ mkILParamNamed("object", ilg.typ_Object); mkILParamNamed("method", ilg.typ_IntPtr) ], MethodBody.Abstract) let ctor = ctor.WithRuntime(true).WithHideBySig(true) [ ctor one "Invoke" parms rty - one "BeginInvoke" (parms @ [mkILParamNamed("callback", iltyp_AsyncCallback); mkILParamNamed("objects", ilg.typ_Object) ] ) iltyp_IAsyncResult - one "EndInvoke" [mkILParamNamed("result", iltyp_IAsyncResult)] rty ] - + one "BeginInvoke" (parms @ [mkILParamNamed ("callback", iltyp_AsyncCallback); mkILParamNamed ("objects", ilg.typ_Object) ] ) iltyp_IAsyncResult + one "EndInvoke" [mkILParamNamed ("result", iltyp_IAsyncResult)] rty ] + let mkCtorMethSpecForDelegate (ilg: ILGlobals) (ty: ILType, useUIntPtr) = - let scoref = ty.TypeRef.Scope + let scoref = ty.TypeRef.Scope mkILInstanceMethSpecInTy (ty, ".ctor", [rescopeILType scoref ilg.typ_Object - rescopeILType scoref (if useUIntPtr then ilg.typ_UIntPtr else ilg.typ_IntPtr)], + rescopeILType scoref (if useUIntPtr then ilg.typ_UIntPtr else ilg.typ_IntPtr)], ILType.Void, emptyILGenericArgsList) type ILEnumInfo = - { enumValues: (string * ILFieldInit) list + { enumValues: (string * ILFieldInit) list enumType: ILType } let getTyOfILEnumInfo info = info.enumType -let computeILEnumInfo (mdName, mdFields: ILFieldDefs) = - match (List.partition (fun (fd: ILFieldDef) -> fd.IsStatic) mdFields.AsList) with - | staticFields, [vfd] -> - { enumType = vfd.FieldType +let computeILEnumInfo (mdName, mdFields: ILFieldDefs) = + match (List.partition (fun (fd: ILFieldDef) -> fd.IsStatic) mdFields.AsList) with + | staticFields, [vfd] -> + { enumType = vfd.FieldType enumValues = staticFields |> List.map (fun fd -> (fd.Name, match fd.LiteralValue with Some i -> i | None -> failwith ("info_of_enum_tdef: badly formed enum "+mdName+": static field does not have an default value"))) } | _, [] -> failwith ("info_of_enum_tdef: badly formed enum "+mdName+": no non-static field found") | _, _ -> failwith ("info_of_enum_tdef: badly formed enum "+mdName+": more than one non-static field found") @@ -3397,42 +3393,42 @@ let computeILEnumInfo (mdName, mdFields: ILFieldDefs) = // pass around an int index //--------------------------------------------------------------------- -let sigptr_get_byte bytes sigptr = +let sigptr_get_byte bytes sigptr = Bytes.get bytes sigptr, sigptr + 1 -let sigptr_get_bool bytes sigptr = +let sigptr_get_bool bytes sigptr = let b0, sigptr = sigptr_get_byte bytes sigptr (b0 = 0x01), sigptr -let sigptr_get_u8 bytes sigptr = +let sigptr_get_u8 bytes sigptr = let b0, sigptr = sigptr_get_byte bytes sigptr byte b0, sigptr -let sigptr_get_i8 bytes sigptr = +let sigptr_get_i8 bytes sigptr = let i, sigptr = sigptr_get_u8 bytes sigptr sbyte i, sigptr -let sigptr_get_u16 bytes sigptr = +let sigptr_get_u16 bytes sigptr = let b0, sigptr = sigptr_get_byte bytes sigptr let b1, sigptr = sigptr_get_byte bytes sigptr uint16 (b0 ||| (b1 <<< 8)), sigptr -let sigptr_get_i16 bytes sigptr = +let sigptr_get_i16 bytes sigptr = let u, sigptr = sigptr_get_u16 bytes sigptr int16 u, sigptr -let sigptr_get_i32 bytes sigptr = +let sigptr_get_i32 bytes sigptr = let b0, sigptr = sigptr_get_byte bytes sigptr let b1, sigptr = sigptr_get_byte bytes sigptr let b2, sigptr = sigptr_get_byte bytes sigptr let b3, sigptr = sigptr_get_byte bytes sigptr b0 ||| (b1 <<< 8) ||| (b2 <<< 16) ||| (b3 <<< 24), sigptr -let sigptr_get_u32 bytes sigptr = +let sigptr_get_u32 bytes sigptr = let u, sigptr = sigptr_get_i32 bytes sigptr uint32 u, sigptr -let sigptr_get_i64 bytes sigptr = +let sigptr_get_i64 bytes sigptr = let b0, sigptr = sigptr_get_byte bytes sigptr let b1, sigptr = sigptr_get_byte bytes sigptr let b2, sigptr = sigptr_get_byte bytes sigptr @@ -3445,80 +3441,80 @@ let sigptr_get_i64 bytes sigptr = (int64 b4 <<< 32) ||| (int64 b5 <<< 40) ||| (int64 b6 <<< 48) ||| (int64 b7 <<< 56), sigptr -let sigptr_get_u64 bytes sigptr = +let sigptr_get_u64 bytes sigptr = let u, sigptr = sigptr_get_i64 bytes sigptr uint64 u, sigptr -let float32_of_bits (x: int32) = System.BitConverter.ToSingle(System.BitConverter.GetBytes(x), 0) +let float32_of_bits (x: int32) = BitConverter.ToSingle (BitConverter.GetBytes x, 0) -let float_of_bits (x: int64) = System.BitConverter.Int64BitsToDouble(x) +let float_of_bits (x: int64) = BitConverter.Int64BitsToDouble x -let sigptr_get_ieee32 bytes sigptr = +let sigptr_get_ieee32 bytes sigptr = let u, sigptr = sigptr_get_i32 bytes sigptr float32_of_bits u, sigptr -let sigptr_get_ieee64 bytes sigptr = +let sigptr_get_ieee64 bytes sigptr = let u, sigptr = sigptr_get_i64 bytes sigptr float_of_bits u, sigptr -let sigptr_get_intarray n (bytes: byte[]) sigptr = +let sigptr_get_intarray n (bytes: byte[]) sigptr = let res = Bytes.zeroCreate n - for i = 0 to n - 1 do + for i = 0 to n - 1 do res.[i] <- bytes.[sigptr + i] res, sigptr + n -let sigptr_get_string n bytes sigptr = +let sigptr_get_string n bytes sigptr = let intarray, sigptr = sigptr_get_intarray n bytes sigptr - System.Text.Encoding.UTF8.GetString(intarray, 0, intarray.Length), sigptr - -let sigptr_get_z_i32 bytes sigptr = + Encoding.UTF8.GetString (intarray, 0, intarray.Length), sigptr + +let sigptr_get_z_i32 bytes sigptr = let b0, sigptr = sigptr_get_byte bytes sigptr if b0 <= 0x7F then b0, sigptr - elif b0 <= 0xbf then + elif b0 <= 0xbf then let b0 = b0 &&& 0x7f let b1, sigptr = sigptr_get_byte bytes sigptr (b0 <<< 8) ||| b1, sigptr - else + else let b0 = b0 &&& 0x3f let b1, sigptr = sigptr_get_byte bytes sigptr let b2, sigptr = sigptr_get_byte bytes sigptr let b3, sigptr = sigptr_get_byte bytes sigptr (b0 <<< 24) ||| (b1 <<< 16) ||| (b2 <<< 8) ||| b3, sigptr -let sigptr_get_serstring bytes sigptr = - let len, sigptr = sigptr_get_z_i32 bytes sigptr - sigptr_get_string ( len) bytes sigptr - -let sigptr_get_serstring_possibly_null bytes sigptr = - let b0, new_sigptr = sigptr_get_byte bytes sigptr +let sigptr_get_serstring bytes sigptr = + let len, sigptr = sigptr_get_z_i32 bytes sigptr + sigptr_get_string ( len) bytes sigptr + +let sigptr_get_serstring_possibly_null bytes sigptr = + let b0, new_sigptr = sigptr_get_byte bytes sigptr if b0 = 0xFF then // null case None, new_sigptr else // throw away new_sigptr, getting length & text advance - let len, sigptr = sigptr_get_z_i32 bytes sigptr + let len, sigptr = sigptr_get_z_i32 bytes sigptr let s, sigptr = sigptr_get_string len bytes sigptr - Some(s), sigptr - + Some s, sigptr + //--------------------------------------------------------------------- // Get the public key token from the public key. //--------------------------------------------------------------------- -let mkRefToILAssembly (m: ILAssemblyManifest) = - ILAssemblyRef.Create(m.Name, None, (match m.PublicKey with Some k -> Some (PublicKey.KeyAsToken(k)) | None -> None), m.Retargetable, m.Version, m.Locale) +let mkRefToILAssembly (m: ILAssemblyManifest) = + ILAssemblyRef.Create (m.Name, None, (match m.PublicKey with Some k -> Some (PublicKey.KeyAsToken k) | None -> None), m.Retargetable, m.Version, m.Locale) -let z_unsigned_int_size n = +let z_unsigned_int_size n = if n <= 0x7F then 1 elif n <= 0x3FFF then 2 else 3 -let z_unsigned_int n = - if n >= 0 && n <= 0x7F then [| byte n |] - elif n >= 0x80 && n <= 0x3FFF then [| byte (0x80 ||| (n >>>& 8)); byte (n &&& 0xFF) |] +let z_unsigned_int n = + if n >= 0 && n <= 0x7F then [| byte n |] + elif n >= 0x80 && n <= 0x3FFF then [| byte (0x80 ||| (n >>>& 8)); byte (n &&& 0xFF) |] else [| byte (0xc0 ||| (n >>>& 24)) - byte ((n >>>& 16) &&& 0xFF) - byte ((n >>>& 8) &&& 0xFF) + byte ((n >>>& 16) &&& 0xFF) + byte ((n >>>& 8) &&& 0xFF) byte (n &&& 0xFF) |] -let string_as_utf8_bytes (s: string) = System.Text.Encoding.UTF8.GetBytes s +let string_as_utf8_bytes (s: string) = Encoding.UTF8.GetBytes s (* Little-endian encoding of int64 *) let dw7 n = byte ((n >>> 56) &&& 0xFFL) @@ -3553,9 +3549,9 @@ let u32AsBytes (i: uint32) = i32AsBytes (int32 i) let u64AsBytes (i: uint64) = i64AsBytes (int64 i) -let bits_of_float32 (x: float32) = System.BitConverter.ToInt32(System.BitConverter.GetBytes(x), 0) +let bits_of_float32 (x: float32) = BitConverter.ToInt32 (BitConverter.GetBytes x, 0) -let bits_of_float (x: float) = System.BitConverter.DoubleToInt64Bits(x) +let bits_of_float (x: float) = BitConverter.DoubleToInt64Bits x let ieee32AsBytes i = i32AsBytes (bits_of_float32 i) @@ -3593,13 +3589,13 @@ let et_MVAR = 0x1Euy let et_CMOD_REQD = 0x1Fuy let et_CMOD_OPT = 0x20uy -let formatILVersion ((a, b, c, d):ILVersionInfo) = sprintf "%d.%d.%d.%d" (int a) (int b) (int c) (int d) +let formatILVersion (version: ILVersionInfo) = sprintf "%d.%d.%d.%d" (int version.Major) (int version.Minor) (int version.Build) (int version.Revision) -let encodeCustomAttrString s = +let encodeCustomAttrString s = let arr = string_as_utf8_bytes s - Array.concat [ z_unsigned_int arr.Length; arr ] + Array.concat [ z_unsigned_int arr.Length; arr ] -let rec encodeCustomAttrElemType x = +let rec encodeCustomAttrElemType x = match x with | ILType.Value tspec when tspec.Name = tname_SByte -> [| et_I1 |] | ILType.Value tspec when tspec.Name = tname_Byte -> [| et_U1 |] @@ -3614,15 +3610,15 @@ let rec encodeCustomAttrElemType x = | ILType.Value tspec when tspec.Name = tname_Char -> [| et_CHAR |] | ILType.Value tspec when tspec.Name = tname_Bool -> [| et_BOOLEAN |] | ILType.Boxed tspec when tspec.Name = tname_String -> [| et_STRING |] - | ILType.Boxed tspec when tspec.Name = tname_Object -> [| 0x51uy |] + | ILType.Boxed tspec when tspec.Name = tname_Object -> [| 0x51uy |] | ILType.Boxed tspec when tspec.Name = tname_Type -> [| 0x50uy |] | ILType.Value tspec -> Array.append [| 0x55uy |] (encodeCustomAttrString tspec.TypeRef.QualifiedName) - | ILType.Array (shape, elemType) when shape = ILArrayShape.SingleDimensional -> + | ILType.Array (shape, elemType) when shape = ILArrayShape.SingleDimensional -> Array.append [| et_SZARRAY |] (encodeCustomAttrElemType elemType) | _ -> failwith "encodeCustomAttrElemType: unrecognized custom element type" /// Given a custom attribute element, work out the type of the .NET argument for that element. -let rec encodeCustomAttrElemTypeForObject x = +let rec encodeCustomAttrElemTypeForObject x = match x with | ILAttribElem.String _ -> [| et_STRING |] | ILAttribElem.Bool _ -> [| et_BOOLEAN |] @@ -3642,7 +3638,7 @@ let rec encodeCustomAttrElemTypeForObject x = | ILAttribElem.Double _ -> [| et_R8 |] | ILAttribElem.Array (elemTy, _) -> [| yield et_SZARRAY; yield! encodeCustomAttrElemType elemTy |] -let rec decodeCustomAttrElemType (ilg: ILGlobals) bytes sigptr x = +let rec decodeCustomAttrElemType (ilg: ILGlobals) bytes sigptr x = match x with | x when x = et_I1 -> ilg.typ_SByte, sigptr | x when x = et_U1 -> ilg.typ_Byte, sigptr @@ -3658,8 +3654,8 @@ let rec decodeCustomAttrElemType (ilg: ILGlobals) bytes sigptr x = | x when x = et_BOOLEAN -> ilg.typ_Bool, sigptr | x when x = et_STRING -> ilg.typ_String, sigptr | x when x = et_OBJECT -> ilg.typ_Object, sigptr - | x when x = et_SZARRAY -> - let et, sigptr = sigptr_get_u8 bytes sigptr + | x when x = et_SZARRAY -> + let et, sigptr = sigptr_get_u8 bytes sigptr let elemTy, sigptr = decodeCustomAttrElemType ilg bytes sigptr et mkILArr1DTy elemTy, sigptr | x when x = 0x50uy -> ilg.typ_Type, sigptr @@ -3667,8 +3663,8 @@ let rec decodeCustomAttrElemType (ilg: ILGlobals) bytes sigptr x = /// Given a custom attribute element, encode it to a binary representation according to the rules in Ecma 335 Partition II. -let rec encodeCustomAttrPrimValue ilg c = - match c with +let rec encodeCustomAttrPrimValue ilg c = + match c with | ILAttribElem.Bool b -> [| (if b then 0x01uy else 0x00uy) |] | ILAttribElem.String None | ILAttribElem.Type None @@ -3688,22 +3684,22 @@ let rec encodeCustomAttrPrimValue ilg c = | ILAttribElem.Double x -> ieee64AsBytes x | ILAttribElem.Type (Some ty) -> encodeCustomAttrString ty.QualifiedName | ILAttribElem.TypeRef (Some tref) -> encodeCustomAttrString tref.QualifiedName - | ILAttribElem.Array (_, elems) -> + | ILAttribElem.Array (_, elems) -> [| yield! i32AsBytes elems.Length; for elem in elems do yield! encodeCustomAttrPrimValue ilg elem |] -and encodeCustomAttrValue ilg ty c = - match ty, c with - | ILType.Boxed tspec, _ when tspec.Name = tname_Object -> +and encodeCustomAttrValue ilg ty c = + match ty, c with + | ILType.Boxed tspec, _ when tspec.Name = tname_Object -> [| yield! encodeCustomAttrElemTypeForObject c; yield! encodeCustomAttrPrimValue ilg c |] - | ILType.Array (shape, _), ILAttribElem.Null when shape = ILArrayShape.SingleDimensional -> + | ILType.Array (shape, _), ILAttribElem.Null when shape = ILArrayShape.SingleDimensional -> [| yield! i32AsBytes 0xFFFFFFFF |] - | ILType.Array (shape, elemType), ILAttribElem.Array (_, elems) when shape = ILArrayShape.SingleDimensional -> + | ILType.Array (shape, elemType), ILAttribElem.Array (_, elems) when shape = ILArrayShape.SingleDimensional -> [| yield! i32AsBytes elems.Length; for elem in elems do yield! encodeCustomAttrValue ilg elemType elem |] - | _ -> + | _ -> encodeCustomAttrPrimValue ilg c -let encodeCustomAttrNamedArg ilg (nm, ty, prop, elem) = - [| yield (if prop then 0x54uy else 0x53uy) +let encodeCustomAttrNamedArg ilg (nm, ty, prop, elem) = + [| yield (if prop then 0x54uy else 0x53uy) yield! encodeCustomAttrElemType ty yield! encodeCustomAttrString nm yield! encodeCustomAttrValue ilg ty elem |] @@ -3733,9 +3729,9 @@ let getCustomAttrData (ilg: ILGlobals) cattr = | ILAttribute.Decoded (mspec, fixedArgs, namedArgs) -> encodeCustomAttrArgs ilg mspec fixedArgs namedArgs -let MscorlibScopeRef = ILScopeRef.Assembly (ILAssemblyRef.Create("mscorlib", None, Some ecmaPublicKey, true, None, None)) +let MscorlibScopeRef = ILScopeRef.Assembly (ILAssemblyRef.Create ("mscorlib", None, Some ecmaPublicKey, true, None, None)) -let EcmaMscorlibILGlobals = mkILGlobals MscorlibScopeRef +let EcmaMscorlibILGlobals = mkILGlobals (MscorlibScopeRef, []) // ILSecurityDecl is a 'blob' having the following format: // - A byte containing a period (.). @@ -3745,23 +3741,23 @@ let EcmaMscorlibILGlobals = mkILGlobals MscorlibScopeRef // as a compressed int to indicate the size followed by an array of UTF8 characters.) // - A set of properties, encoded as the named arguments to a custom attribute would be (as // in §23.3, beginning with NumNamed). -let mkPermissionSet (ilg: ILGlobals) (action, attributes: list<(ILTypeRef * (string * ILType * ILAttribElem) list)>) = - let bytes = +let mkPermissionSet (ilg: ILGlobals) (action, attributes: list<(ILTypeRef * (string * ILType * ILAttribElem) list)>) = + let bytes = [| yield (byte '.') yield! z_unsigned_int attributes.Length - for (tref: ILTypeRef, props) in attributes do + for (tref: ILTypeRef, props) in attributes do yield! encodeCustomAttrString tref.QualifiedName - let bytes = + let bytes = [| yield! z_unsigned_int props.Length - for (nm, ty, value) in props do + for (nm, ty, value) in props do yield! encodeCustomAttrNamedArg ilg (nm, ty, true, value)|] yield! z_unsigned_int bytes.Length yield! bytes |] - - ILSecurityDecl.ILSecurityDecl(action, bytes) + + ILSecurityDecl.ILSecurityDecl (action, bytes) // Parse an IL type signature argument within a custom attribute blob -type ILTypeSigParser(tstring : string) = +type ILTypeSigParser (tstring : string) = let mutable startPos = 0 let mutable currentPos = 0 @@ -3771,7 +3767,7 @@ type ILTypeSigParser(tstring : string) = // take a look at the next value, but don't advance let peek() = if currentPos < (tstring.Length-1) then tstring.[currentPos+1] else nil - let peekN(skip) = if currentPos < (tstring.Length - skip) then tstring.[currentPos+skip] else nil + let peekN skip = if currentPos < (tstring.Length - skip) then tstring.[currentPos+skip] else nil // take a look at the current value, but don't advance let here() = if currentPos < tstring.Length then tstring.[currentPos] else nil // move on to the next character @@ -3781,7 +3777,7 @@ type ILTypeSigParser(tstring : string) = // ignore the current lexeme, advance let drop() = skip() ; step() ; skip() // return the current lexeme, advance - let take() = + let take() = let s = if currentPos < tstring.Length then tstring.[startPos..currentPos] else "" drop() s @@ -3795,7 +3791,7 @@ type ILTypeSigParser(tstring : string) = // dev.virtualearth.net.webservices.v1.search.CategorySpecificPropertySet], // mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" // - // Note that + // Note that // Since we're only reading valid IL, we assume that the signature is properly formed // For type parameters, if the type is non-local, it will be wrapped in brackets ([]) // Still needs testing with jagged arrays and byref parameters @@ -3804,22 +3800,22 @@ type ILTypeSigParser(tstring : string) = // Does the type name start with a leading '['? If so, ignore it // (if the specialization type is in another module, it will be wrapped in bracket) if here() = '[' then drop() - + // 1. Iterate over beginning of type, grabbing the type name and determining if it's generic or an array - let typeName = + let typeName = while (peek() <> '`') && (peek() <> '[') && (peek() <> ']') && (peek() <> ',') && (peek() <> nil) do step() take() - + // 2. Classify the type // Is the type generic? - let typeName, specializations = + let typeName, specializations = if here() = '`' then drop() // step to the number // fetch the arity - let arity = + let arity = while (int(here()) >= (int('0'))) && (int(here()) <= ((int('9')))) && (int(peek()) >= (int('0'))) && (int(peek()) <= ((int('9')))) do step() - System.Int32.Parse(take()) + Int32.Parse(take()) // skip the '[' drop() // get the specializations @@ -3828,7 +3824,7 @@ type ILTypeSigParser(tstring : string) = typeName, None // Is the type an array? - let rank = + let rank = if here() = '[' then let mutable rank = 0 @@ -3842,8 +3838,8 @@ type ILTypeSigParser(tstring : string) = None // Is there a scope? - let scope = - if (here() = ',' || here() = ' ') && (peek() <> '[' && peekN(2) <> '[') then + let scope = + if (here() = ',' || here() = ' ') && (peek() <> '[' && peekN 2 <> '[') then let grabScopeComponent() = if here() = ',' then drop() // ditch the ',' if here() = ' ' then drop() // ditch the ' ' @@ -3860,7 +3856,7 @@ type ILTypeSigParser(tstring : string) = #if FABLE_COMPILER ILScopeRef.Assembly(mkSimpleAssemblyRef scope) #else - ILScopeRef.Assembly(ILAssemblyRef.FromAssemblyName(System.Reflection.AssemblyName(scope))) + ILScopeRef.Assembly(ILAssemblyRef.FromAssemblyName(AssemblyName scope)) #endif else ILScopeRef.Local @@ -3870,13 +3866,13 @@ type ILTypeSigParser(tstring : string) = if (here() = ',') then drop() // build the IL type - let tref = mkILTyRef(scope, typeName) - let genericArgs = + let tref = mkILTyRef (scope, typeName) + let genericArgs = match specializations with | None -> [] - | Some(genericArgs) -> genericArgs - let tspec = ILTypeSpec.Create(tref, genericArgs) - let ilty = + | Some genericArgs -> genericArgs + let tspec = ILTypeSpec.Create (tref, genericArgs) + let ilty = match tspec.Name with | "System.SByte" | "System.Byte" @@ -3889,20 +3885,20 @@ type ILTypeSigParser(tstring : string) = | "System.Char" | "System.Double" | "System.Single" - | "System.Boolean" -> ILType.Value(tspec) - | _ -> ILType.Boxed(tspec) + | "System.Boolean" -> ILType.Value tspec + | _ -> ILType.Boxed tspec // if it's an array, wrap it - otherwise, just return the IL type match rank with - | Some(r) -> ILType.Array(r, ilty) + | Some r -> ILType.Array (r, ilty) | _ -> ilty - + member x.ParseTypeSpec() = reset() let ilty = x.ParseType() - ILAttribElem.Type(Some(ilty)) + ILAttribElem.Type (Some ilty) -let decodeILAttribData (ilg: ILGlobals) (ca: ILAttribute) = +let decodeILAttribData (ilg: ILGlobals) (ca: ILAttribute) = match ca with | ILAttribute.Decoded (_, fixedArgs, namedArgs) -> fixedArgs, namedArgs | ILAttribute.Encoded (_, bytes, _) -> @@ -3912,137 +3908,138 @@ let decodeILAttribData (ilg: ILGlobals) (ca: ILAttribute) = let bb1, sigptr = sigptr_get_byte bytes sigptr if not (bb0 = 0x01 && bb1 = 0x00) then failwith "decodeILAttribData: invalid data" - let rec parseVal argty sigptr = - match argty with - | ILType.Value tspec when tspec.Name = "System.SByte" -> + let rec parseVal argty sigptr = + match argty with + | ILType.Value tspec when tspec.Name = "System.SByte" -> let n, sigptr = sigptr_get_i8 bytes sigptr ILAttribElem.SByte n, sigptr - | ILType.Value tspec when tspec.Name = "System.Byte" -> + | ILType.Value tspec when tspec.Name = "System.Byte" -> let n, sigptr = sigptr_get_u8 bytes sigptr ILAttribElem.Byte n, sigptr - | ILType.Value tspec when tspec.Name = "System.Int16" -> + | ILType.Value tspec when tspec.Name = "System.Int16" -> let n, sigptr = sigptr_get_i16 bytes sigptr ILAttribElem.Int16 n, sigptr - | ILType.Value tspec when tspec.Name = "System.UInt16" -> + | ILType.Value tspec when tspec.Name = "System.UInt16" -> let n, sigptr = sigptr_get_u16 bytes sigptr ILAttribElem.UInt16 n, sigptr - | ILType.Value tspec when tspec.Name = "System.Int32" -> + | ILType.Value tspec when tspec.Name = "System.Int32" -> let n, sigptr = sigptr_get_i32 bytes sigptr ILAttribElem.Int32 n, sigptr - | ILType.Value tspec when tspec.Name = "System.UInt32" -> + | ILType.Value tspec when tspec.Name = "System.UInt32" -> let n, sigptr = sigptr_get_u32 bytes sigptr ILAttribElem.UInt32 n, sigptr - | ILType.Value tspec when tspec.Name = "System.Int64" -> + | ILType.Value tspec when tspec.Name = "System.Int64" -> let n, sigptr = sigptr_get_i64 bytes sigptr ILAttribElem.Int64 n, sigptr - | ILType.Value tspec when tspec.Name = "System.UInt64" -> + | ILType.Value tspec when tspec.Name = "System.UInt64" -> let n, sigptr = sigptr_get_u64 bytes sigptr ILAttribElem.UInt64 n, sigptr - | ILType.Value tspec when tspec.Name = "System.Double" -> + | ILType.Value tspec when tspec.Name = "System.Double" -> let n, sigptr = sigptr_get_ieee64 bytes sigptr ILAttribElem.Double n, sigptr - | ILType.Value tspec when tspec.Name = "System.Single" -> + | ILType.Value tspec when tspec.Name = "System.Single" -> let n, sigptr = sigptr_get_ieee32 bytes sigptr ILAttribElem.Single n, sigptr - | ILType.Value tspec when tspec.Name = "System.Char" -> + | ILType.Value tspec when tspec.Name = "System.Char" -> let n, sigptr = sigptr_get_u16 bytes sigptr ILAttribElem.Char (char (int32 n)), sigptr - | ILType.Value tspec when tspec.Name = "System.Boolean" -> + | ILType.Value tspec when tspec.Name = "System.Boolean" -> let n, sigptr = sigptr_get_byte bytes sigptr ILAttribElem.Bool (not (n = 0)), sigptr - | ILType.Boxed tspec when tspec.Name = "System.String" -> + | ILType.Boxed tspec when tspec.Name = "System.String" -> let n, sigptr = sigptr_get_serstring_possibly_null bytes sigptr ILAttribElem.String n, sigptr - | ILType.Boxed tspec when tspec.Name = "System.Type" -> + | ILType.Boxed tspec when tspec.Name = "System.Type" -> let nOpt, sigptr = sigptr_get_serstring_possibly_null bytes sigptr match nOpt with - | None -> ILAttribElem.TypeRef(None), sigptr - | Some n -> + | None -> ILAttribElem.TypeRef None, sigptr + | Some n -> try - let parser = ILTypeSigParser(n) + let parser = ILTypeSigParser n parser.ParseTypeSpec(), sigptr with e -> failwith (sprintf "decodeILAttribData: error parsing type in custom attribute blob: %s" e.Message) - | ILType.Boxed tspec when tspec.Name = "System.Object" -> + | ILType.Boxed tspec when tspec.Name = "System.Object" -> let et, sigptr = sigptr_get_u8 bytes sigptr - if et = 0xFFuy then + if et = 0xFFuy then ILAttribElem.Null, sigptr else - let ty, sigptr = decodeCustomAttrElemType ilg bytes sigptr et - parseVal ty sigptr - | ILType.Array(shape, elemTy) when shape = ILArrayShape.SingleDimensional -> + let ty, sigptr = decodeCustomAttrElemType ilg bytes sigptr et + parseVal ty sigptr + | ILType.Array (shape, elemTy) when shape = ILArrayShape.SingleDimensional -> let n, sigptr = sigptr_get_i32 bytes sigptr if n = 0xFFFFFFFF then ILAttribElem.Null, sigptr else - let rec parseElems acc n sigptr = + let rec parseElems acc n sigptr = if n = 0 then List.rev acc, sigptr else let v, sigptr = parseVal elemTy sigptr - parseElems (v ::acc) (n-1) sigptr - let elems, sigptr = parseElems [] n sigptr - ILAttribElem.Array(elemTy, elems), sigptr + parseElems (v :: acc) (n-1) sigptr + let elems, sigptr = parseElems [] n sigptr + ILAttribElem.Array (elemTy, elems), sigptr | ILType.Value _ -> (* assume it is an enumeration *) let n, sigptr = sigptr_get_i32 bytes sigptr ILAttribElem.Int32 n, sigptr | _ -> failwith "decodeILAttribData: attribute data involves an enum or System.Type value" - let rec parseFixed argtys sigptr = - match argtys with + let rec parseFixed argtys sigptr = + match argtys with [] -> [], sigptr - | h::t -> + | h :: t -> let nh, sigptr = parseVal h sigptr let nt, sigptr = parseFixed t sigptr - nh ::nt, sigptr + nh :: nt, sigptr let fixedArgs, sigptr = parseFixed ca.Method.FormalArgTypes sigptr let nnamed, sigptr = sigptr_get_u16 bytes sigptr - let rec parseNamed acc n sigptr = + let rec parseNamed acc n sigptr = if n = 0 then List.rev acc else let isPropByte, sigptr = sigptr_get_u8 bytes sigptr let isProp = (int isPropByte = 0x54) let et, sigptr = sigptr_get_u8 bytes sigptr - // We have a named value - let ty, sigptr = + // We have a named value + let ty, sigptr = if ( (* 0x50 = (int et) || *) 0x55 = (int et)) then let qualified_tname, sigptr = sigptr_get_serstring bytes sigptr - let unqualified_tname, rest = - let pieces = qualified_tname.Split(',') - if pieces.Length > 1 then + let unqualified_tname, rest = + let pieces = qualified_tname.Split (',') + if pieces.Length > 1 then pieces.[0], Some (String.concat "," pieces.[1..]) - else + else pieces.[0], None - let scoref = - match rest with + let scoref = + match rest with #if FABLE_COMPILER | Some aname -> ILScopeRef.Assembly(mkSimpleAssemblyRef aname) #else - | Some aname -> ILScopeRef.Assembly(ILAssemblyRef.FromAssemblyName(System.Reflection.AssemblyName(aname))) + | Some aname -> ILScopeRef.Assembly (ILAssemblyRef.FromAssemblyName (AssemblyName aname)) #endif | None -> ilg.primaryAssemblyScopeRef let tref = mkILTyRef (scoref, unqualified_tname) let tspec = mkILNonGenericTySpec tref - ILType.Value(tspec), sigptr + ILType.Value tspec, sigptr else decodeCustomAttrElemType ilg bytes sigptr et let nm, sigptr = sigptr_get_serstring bytes sigptr let v, sigptr = parseVal ty sigptr parseNamed ((nm, ty, isProp, v) :: acc) (n-1) sigptr let named = parseNamed [] (int nnamed) sigptr - fixedArgs, named + fixedArgs, named -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Functions to collect up all the references in a full module or // assembly manifest. The process also allocates // a unique name to each unique internal assembly reference. -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -type ILReferences = - { AssemblyReferences: ILAssemblyRef list +type ILReferences = + { AssemblyReferences: ILAssemblyRef list ModuleReferences: ILModuleRef list } -type ILReferencesAccumulator = - { refsA: HashSet +type ILReferencesAccumulator = + { ilg: ILGlobals + refsA: HashSet refsM: HashSet } -let emptyILRefs = +let emptyILRefs = { AssemblyReferences=[] ModuleReferences = [] } @@ -4050,23 +4047,24 @@ let emptyILRefs = let refs_of_assemblyRef (s: ILReferencesAccumulator) x = s.refsA.Add x |> ignore let refs_of_modref (s: ILReferencesAccumulator) x = s.refsM.Add x |> ignore - -let refs_of_scoref s x = - match x with - | ILScopeRef.Local -> () + +let refs_of_scoref s x = + match x with + | ILScopeRef.Local -> () | ILScopeRef.Assembly assemblyRef -> refs_of_assemblyRef s assemblyRef - | ILScopeRef.Module modref -> refs_of_modref s modref + | ILScopeRef.Module modref -> refs_of_modref s modref + | ILScopeRef.PrimaryAssembly -> refs_of_assemblyRef s s.ilg.primaryAssemblyRef let refs_of_tref s (x: ILTypeRef) = refs_of_scoref s x.Scope - -let rec refs_of_typ s x = + +let rec refs_of_typ s x = match x with | ILType.Void | ILType.TypeVar _ -> () - | ILType.Modified(_, ty1, ty2) -> refs_of_tref s ty1; refs_of_typ s ty2 + | ILType.Modified (_, ty1, ty2) -> refs_of_tref s ty1; refs_of_typ s ty2 | ILType.Array (_, ty) - | ILType.Ptr ty | ILType.Byref ty -> refs_of_typ s ty + | ILType.Ptr ty | ILType.Byref ty -> refs_of_typ s ty | ILType.Value tr | ILType.Boxed tr -> refs_of_tspec s tr - | ILType.FunctionPointer mref -> refs_of_callsig s mref + | ILType.FunctionPointer mref -> refs_of_callsig s mref and refs_of_inst s i = refs_of_tys s i @@ -4077,19 +4075,19 @@ and refs_of_callsig s csig = refs_of_tys s csig.ArgTypes; refs_of_typ s csig.Ret and refs_of_genparam s x = refs_of_tys s x.Constraints and refs_of_genparams s b = List.iter (refs_of_genparam s) b - + and refs_of_dloc s ts = refs_of_tref s ts - -and refs_of_mref s (x: ILMethodRef) = + +and refs_of_mref s (x: ILMethodRef) = refs_of_dloc s x.DeclaringTypeRef refs_of_tys s x.mrefArgs refs_of_typ s x.mrefReturn - + and refs_of_fref s x = refs_of_tref s x.DeclaringTypeRef; refs_of_typ s x.Type -and refs_of_ospec s (OverridesSpec(mref, ty)) = refs_of_mref s mref; refs_of_typ s ty +and refs_of_ospec s (OverridesSpec (mref, ty)) = refs_of_mref s mref; refs_of_typ s ty -and refs_of_mspec s (x: ILMethodSpec) = +and refs_of_mspec s (x: ILMethodSpec) = refs_of_mref s x.MethodRef refs_of_typ s x.DeclaringType refs_of_inst s x.GenericArgs @@ -4099,117 +4097,117 @@ and refs_of_fspec s x = refs_of_typ s x.DeclaringType and refs_of_tys s l = List.iter (refs_of_typ s) l - -and refs_of_token s x = + +and refs_of_token s x = match x with | ILToken.ILType ty -> refs_of_typ s ty | ILToken.ILMethod mr -> refs_of_mspec s mr | ILToken.ILField fr -> refs_of_fspec s fr and refs_of_custom_attr s (cattr: ILAttribute) = refs_of_mspec s cattr.Method - + and refs_of_custom_attrs s (cas : ILAttributes) = Array.iter (refs_of_custom_attr s) cas.AsArray -and refs_of_varargs s tyso = Option.iter (refs_of_tys s) tyso +and refs_of_varargs s tyso = Option.iter (refs_of_tys s) tyso -and refs_of_instr s x = +and refs_of_instr s x = match x with | I_call (_, mr, varargs) | I_newobj (mr, varargs) | I_callvirt (_, mr, varargs) -> refs_of_mspec s mr refs_of_varargs s varargs - | I_callconstraint (_, tr, mr, varargs) -> + | I_callconstraint (_, tr, mr, varargs) -> refs_of_typ s tr refs_of_mspec s mr refs_of_varargs s varargs - | I_calli (_, callsig, varargs) -> - refs_of_callsig s callsig; refs_of_varargs s varargs - | I_jmp mr | I_ldftn mr | I_ldvirtftn mr -> + | I_calli (_, callsig, varargs) -> + refs_of_callsig s callsig; refs_of_varargs s varargs + | I_jmp mr | I_ldftn mr | I_ldvirtftn mr -> refs_of_mspec s mr - | I_ldsfld (_, fr) | I_ldfld (_, _, fr) | I_ldsflda fr | I_ldflda fr | I_stsfld (_, fr) | I_stfld (_, _, fr) -> + | I_ldsfld (_, fr) | I_ldfld (_, _, fr) | I_ldsflda fr | I_ldflda fr | I_stsfld (_, fr) | I_stfld (_, _, fr) -> refs_of_fspec s fr - | I_isinst ty | I_castclass ty | I_cpobj ty | I_initobj ty | I_ldobj (_, _, ty) + | I_isinst ty | I_castclass ty | I_cpobj ty | I_initobj ty | I_ldobj (_, _, ty) | I_stobj (_, _, ty) | I_box ty |I_unbox ty | I_unbox_any ty | I_sizeof ty | I_ldelem_any (_, ty) | I_ldelema (_, _, _, ty) |I_stelem_any (_, ty) | I_newarr (_, ty) - | I_mkrefany ty | I_refanyval ty - | EI_ilzero ty -> refs_of_typ s ty - | I_ldtoken token -> refs_of_token s token + | I_mkrefany ty | I_refanyval ty + | EI_ilzero ty -> refs_of_typ s ty + | I_ldtoken token -> refs_of_token s token | I_stelem _|I_ldelem _|I_ldstr _|I_switch _|I_stloc _|I_stind _ | I_starg _|I_ldloca _|I_ldloc _|I_ldind _ | I_ldarga _|I_ldarg _|I_leave _|I_br _ - | I_brcmp _|I_rethrow|I_refanytype|I_ldlen|I_throw|I_initblk _ |I_cpblk _ + | I_brcmp _|I_rethrow|I_refanytype|I_ldlen|I_throw|I_initblk _ |I_cpblk _ | I_localloc|I_ret |I_endfilter|I_endfinally|I_arglist | I_break - | AI_add | AI_add_ovf | AI_add_ovf_un | AI_and | AI_div | AI_div_un | AI_ceq | AI_cgt | AI_cgt_un | AI_clt - | AI_clt_un | AI_conv _ | AI_conv_ovf _ | AI_conv_ovf_un _ | AI_mul | AI_mul_ovf | AI_mul_ovf_un | AI_rem | AI_rem_un - | AI_shl | AI_shr | AI_shr_un | AI_sub | AI_sub_ovf | AI_sub_ovf_un | AI_xor | AI_or | AI_neg | AI_not + | AI_add | AI_add_ovf | AI_add_ovf_un | AI_and | AI_div | AI_div_un | AI_ceq | AI_cgt | AI_cgt_un | AI_clt + | AI_clt_un | AI_conv _ | AI_conv_ovf _ | AI_conv_ovf_un _ | AI_mul | AI_mul_ovf | AI_mul_ovf_un | AI_rem | AI_rem_un + | AI_shl | AI_shr | AI_shr_un | AI_sub | AI_sub_ovf | AI_sub_ovf_un | AI_xor | AI_or | AI_neg | AI_not | AI_ldnull | AI_dup | AI_pop | AI_ckfinite | AI_nop | AI_ldc _ | I_seqpoint _ | EI_ldlen_multi _ -> () - -and refs_of_il_code s (c: ILCode) = - c.Instrs |> Array.iter (refs_of_instr s) - c.Exceptions |> List.iter (fun e -> e.Clause |> (function + +and refs_of_il_code s (c: ILCode) = + c.Instrs |> Array.iter (refs_of_instr s) + c.Exceptions |> List.iter (fun e -> e.Clause |> (function | ILExceptionClause.TypeCatch (ilty, _) -> refs_of_typ s ilty | _ -> ())) -and refs_of_ilmbody s (il: ILMethodBody) = +and refs_of_ilmbody s (il: ILMethodBody) = List.iter (refs_of_local s) il.Locals - refs_of_il_code s il.Code - + refs_of_il_code s il.Code + and refs_of_local s loc = refs_of_typ s loc.Type - -and refs_of_mbody s x = - match x with + +and refs_of_mbody s x = + match x with | MethodBody.IL il -> refs_of_ilmbody s il | MethodBody.PInvoke (attr) -> refs_of_modref s attr.Where | _ -> () -and refs_of_mdef s (md: ILMethodDef) = +and refs_of_mdef s (md: ILMethodDef) = List.iter (refs_of_param s) md.Parameters refs_of_return s md.Return refs_of_mbody s md.Body.Contents refs_of_custom_attrs s md.CustomAttrs refs_of_genparams s md.GenericParams - -and refs_of_param s p = refs_of_typ s p.Type + +and refs_of_param s p = refs_of_typ s p.Type and refs_of_return s (rt: ILReturn) = refs_of_typ s rt.Type and refs_of_mdefs s x = Seq.iter (refs_of_mdef s) x - -and refs_of_event_def s (ed: ILEventDef) = + +and refs_of_event_def s (ed: ILEventDef) = Option.iter (refs_of_typ s) ed.EventType refs_of_mref s ed.AddMethod refs_of_mref s ed.RemoveMethod Option.iter (refs_of_mref s) ed.FireMethod List.iter (refs_of_mref s) ed.OtherMethods refs_of_custom_attrs s ed.CustomAttrs - + and refs_of_events s (x: ILEventDefs) = List.iter (refs_of_event_def s) x.AsList - -and refs_of_property_def s (pd: ILPropertyDef) = + +and refs_of_property_def s (pd: ILPropertyDef) = Option.iter (refs_of_mref s) pd.SetMethod Option.iter (refs_of_mref s) pd.GetMethod refs_of_typ s pd.PropertyType refs_of_tys s pd.Args refs_of_custom_attrs s pd.CustomAttrs - + and refs_of_properties s (x: ILPropertyDefs) = List.iter (refs_of_property_def s) x.AsList - -and refs_of_fdef s (fd: ILFieldDef) = + +and refs_of_fdef s (fd: ILFieldDef) = refs_of_typ s fd.FieldType refs_of_custom_attrs s fd.CustomAttrs and refs_of_fields s fields = List.iter (refs_of_fdef s) fields - + and refs_of_method_impls s mimpls = List.iter (refs_of_method_impl s) mimpls - -and refs_of_method_impl s m = + +and refs_of_method_impl s m = refs_of_ospec s m.Overrides refs_of_mspec s m.OverrideBy and refs_of_tdef_kind _s _k = () - -and refs_of_tdef s (td : ILTypeDef) = + +and refs_of_tdef s (td : ILTypeDef) = refs_of_types s td.NestedTypes refs_of_genparams s td.GenericParams refs_of_tys s td.Implements @@ -4225,119 +4223,118 @@ and refs_of_tdef s (td : ILTypeDef) = and refs_of_string _s _ = () and refs_of_types s (types: ILTypeDefs) = Seq.iter (refs_of_tdef s) types - -and refs_of_exported_type s (c: ILExportedTypeOrForwarder) = + +and refs_of_exported_type s (c: ILExportedTypeOrForwarder) = refs_of_custom_attrs s c.CustomAttrs - + and refs_of_exported_types s (tab: ILExportedTypesAndForwarders) = List.iter (refs_of_exported_type s) tab.AsList - -and refs_of_resource_where s x = - match x with - | ILResourceLocation.LocalIn _ -> () - | ILResourceLocation.LocalOut _ -> () + +and refs_of_resource_where s x = + match x with + | ILResourceLocation.Local _ -> () | ILResourceLocation.File (mref, _) -> refs_of_modref s mref | ILResourceLocation.Assembly aref -> refs_of_assemblyRef s aref -and refs_of_resource s x = +and refs_of_resource s x = refs_of_resource_where s x.Location refs_of_custom_attrs s x.CustomAttrs - + and refs_of_resources s (tab: ILResources) = List.iter (refs_of_resource s) tab.AsList - -and refs_of_modul s m = + +and refs_of_modul s m = refs_of_types s m.TypeDefs refs_of_resources s m.Resources Option.iter (refs_of_manifest s) m.Manifest - -and refs_of_manifest s (m: ILAssemblyManifest) = + +and refs_of_manifest s (m: ILAssemblyManifest) = refs_of_custom_attrs s m.CustomAttrs refs_of_exported_types s m.ExportedTypes -let computeILRefs modul = - let s = - { refsA = HashSet<_>(HashIdentity.Structural) +let computeILRefs ilg modul = + let s = + { ilg = ilg + refsA = HashSet<_>(HashIdentity.Structural) refsM = HashSet<_>(HashIdentity.Structural) } refs_of_modul s modul - { AssemblyReferences = Seq.fold (fun acc x -> x::acc) [] s.refsA - ModuleReferences = Seq.fold (fun acc x -> x::acc) [] s.refsM } + { AssemblyReferences = Seq.fold (fun acc x -> x :: acc) [] s.refsA + ModuleReferences = Seq.fold (fun acc x -> x :: acc) [] s.refsM } -let tspan = System.TimeSpan(System.DateTime.UtcNow.Ticks - System.DateTime(2000, 1, 1).Ticks) +let tspan = TimeSpan (DateTime.UtcNow.Ticks - DateTime(2000, 1, 1).Ticks) -let parseILVersion (vstr : string) = +let parseILVersion (vstr : string) = // matches "v1.2.3.4" or "1.2.3.4". Note, if numbers are missing, returns -1 (not 0). - let mutable vstr = vstr.TrimStart [|'v'|] + let mutable vstr = vstr.TrimStart [|'v'|] // if the version string contains wildcards, replace them - let versionComponents = vstr.Split([|'.'|]) - + let versionComponents = vstr.Split ([|'.'|]) + // account for wildcards if versionComponents.Length > 2 then - let defaultBuild = (uint16)tspan.Days % System.UInt16.MaxValue - 1us - let defaultRevision = (uint16)(System.DateTime.UtcNow.TimeOfDay.TotalSeconds / 2.0) % System.UInt16.MaxValue - 1us + let defaultBuild = uint16 tspan.Days % UInt16.MaxValue - 1us + let defaultRevision = uint16 (DateTime.UtcNow.TimeOfDay.TotalSeconds / 2.0) % UInt16.MaxValue - 1us if versionComponents.[2] = "*" then if versionComponents.Length > 3 then failwith "Invalid version format" else // set the build number to the number of days since Jan 1, 2000 - versionComponents.[2] <- defaultBuild.ToString() + versionComponents.[2] <- defaultBuild.ToString() // Set the revision number to number of seconds today / 2 - vstr <- System.String.Join(".", versionComponents) + "." + defaultRevision.ToString() + vstr <- String.Join (".", versionComponents) + "." + defaultRevision.ToString() elif versionComponents.Length > 3 && versionComponents.[3] = "*" then // Set the revision number to number of seconds today / 2 - versionComponents.[3] <- defaultRevision.ToString() - vstr <- System.String.Join(".", versionComponents) - + versionComponents.[3] <- defaultRevision.ToString() + vstr <- String.Join (".", versionComponents) + #if FABLE_COMPILER let parts = vstr.Split([|'.'|]) let versions = Array.append (Array.map uint16 parts) [|0us;0us;0us;0us|] - (versions.[0], versions.[1], versions.[2], versions.[3]) + ILVersionInfo (versions.[0], versions.[1], versions.[2], versions.[3]) #else - let version = System.Version(vstr) - let zero32 n = if n < 0 then 0us else uint16(n) + let version = System.Version vstr + let zero32 n = if n < 0 then 0us else uint16 n // since the minor revision will be -1 if none is specified, we need to truncate to 0 to not break existing code - let minorRevision = if version.Revision = -1 then 0us else uint16(version.MinorRevision) - (zero32 version.Major, zero32 version.Minor, zero32 version.Build, minorRevision) + let minorRevision = if version.Revision = -1 then 0us else uint16 version.MinorRevision + ILVersionInfo (zero32 version.Major, zero32 version.Minor, zero32 version.Build, minorRevision) #endif - -let compareILVersions (a1, a2, a3, a4) ((b1, b2, b3, b4) : ILVersionInfo) = - let c = compare a1 b1 +let compareILVersions (version1 : ILVersionInfo) (version2 : ILVersionInfo) = + let c = compare version1.Major version2.Major if c <> 0 then c else - let c = compare a2 b2 + let c = compare version1.Minor version2.Minor if c <> 0 then c else - let c = compare a3 b3 + let c = compare version1.Build version2.Build if c <> 0 then c else - let c = compare a4 b4 + let c = compare version1.Revision version2.Revision if c <> 0 then c else 0 -let unscopeILTypeRef (x: ILTypeRef) = ILTypeRef.Create(ILScopeRef.Local, x.Enclosing, x.Name) +let unscopeILTypeRef (x: ILTypeRef) = ILTypeRef.Create (ILScopeRef.Local, x.Enclosing, x.Name) -let rec unscopeILTypeSpec (tspec: ILTypeSpec) = +let rec unscopeILTypeSpec (tspec: ILTypeSpec) = let tref = tspec.TypeRef let tinst = tspec.GenericArgs let tref = unscopeILTypeRef tref ILTypeSpec.Create (tref, unscopeILTypes tinst) -and unscopeILType ty = - match ty with +and unscopeILType ty = + match ty with | ILType.Ptr t -> ILType.Ptr (unscopeILType t) | ILType.FunctionPointer t -> ILType.FunctionPointer (unscopeILCallSig t) | ILType.Byref t -> ILType.Byref (unscopeILType t) | ILType.Boxed cr -> mkILBoxedType (unscopeILTypeSpec cr) | ILType.Array (s, ty) -> ILType.Array (s, unscopeILType ty) | ILType.Value cr -> ILType.Value (unscopeILTypeSpec cr) - | ILType.Modified(b, tref, ty) -> ILType.Modified(b, unscopeILTypeRef tref, unscopeILType ty) + | ILType.Modified (b, tref, ty) -> ILType.Modified (b, unscopeILTypeRef tref, unscopeILType ty) | x -> x -and unscopeILTypes i = +and unscopeILTypes i = if List.isEmpty i then i else List.map unscopeILType i -and unscopeILCallSig csig = +and unscopeILCallSig csig = mkILCallSig (csig.CallingConv, unscopeILTypes csig.ArgTypes, unscopeILType csig.ReturnType) -let resolveILMethodRefWithRescope r (td: ILTypeDef) (mref: ILMethodRef) = +let resolveILMethodRefWithRescope r (td: ILTypeDef) (mref: ILMethodRef) = let args = mref.ArgTypes let nargs = args.Length let nm = mref.Name @@ -4345,27 +4342,27 @@ let resolveILMethodRefWithRescope r (td: ILTypeDef) (mref: ILMethodRef) = if isNil possibles then failwith ("no method named " + nm + " found in type " + td.Name) let argTypes = mref.ArgTypes |> List.map r let retType : ILType = r mref.ReturnType - match - possibles |> List.filter (fun md -> + match + possibles |> List.filter (fun md -> mref.CallingConv = md.CallingConv && // REVIEW: this uses equality on ILType. For CMOD_OPTIONAL this is not going to be correct (md.Parameters, argTypes) ||> List.lengthsEqAndForall2 (fun p1 p2 -> r p1.Type = p2) && - // REVIEW: this uses equality on ILType. For CMOD_OPTIONAL this is not going to be correct - r md.Return.Type = retType) with + // REVIEW: this uses equality on ILType. For CMOD_OPTIONAL this is not going to be correct + r md.Return.Type = retType) with | [] -> failwith ("no method named "+nm+" with appropriate argument types found in type "+td.Name) | [mdef] -> mdef | _ -> failwith ("multiple methods named "+nm+" appear with identical argument types in type "+td.Name) - + let resolveILMethodRef td mref = resolveILMethodRefWithRescope id td mref let mkRefToILModule m = - ILModuleRef.Create(m.Name, true, None) + ILModuleRef.Create (m.Name, true, None) type ILEventRef = { erA: ILTypeRef erB: string } - static member Create(a, b) = {erA=a;erB=b} + static member Create (a, b) = {erA=a;erB=b} member x.DeclaringTypeRef = x.erA diff --git a/src/fcs-fable/src/absil/il.fsi b/src/fcs-fable/src/absil/il.fsi old mode 100755 new mode 100644 index 8f1e561256..c701e67175 --- a/src/fcs-fable/src/absil/il.fsi +++ b/src/fcs-fable/src/absil/il.fsi @@ -3,6 +3,7 @@ /// The "unlinked" view of .NET metadata and code. Central to the Abstract IL library module public FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler.AbstractIL.Internal open System.Collections.Generic open System.Reflection @@ -53,7 +54,15 @@ type PublicKey = member KeyToken: byte[] static member KeyAsToken: byte[] -> PublicKey -type ILVersionInfo = uint16 * uint16 * uint16 * uint16 +[] +type ILVersionInfo = + + val Major: uint16 + val Minor: uint16 + val Build: uint16 + val Revision: uint16 + + new : major: uint16 * minor: uint16 * build: uint16 * revision: uint16 -> ILVersionInfo [] type ILAssemblyRef = @@ -72,6 +81,9 @@ type ILAssemblyRef = member Retargetable: bool member Version: ILVersionInfo option member Locale: string option + + member EqualsIgnoringVersion: ILAssemblyRef -> bool + interface System.IComparable [] @@ -90,12 +102,10 @@ type ILScopeRef = /// A reference to a type in a module in the same assembly | Module of ILModuleRef /// A reference to a type in another assembly - | Assembly of ILAssemblyRef + | Assembly of ILAssemblyRef + /// A reference to a type in the primary assembly + | PrimaryAssembly member IsLocalRef: bool - member IsModuleRef: bool - member IsAssemblyRef: bool - member ModuleRef: ILModuleRef - member AssemblyRef: ILAssemblyRef member QualifiedName: string // Calling conventions. @@ -1055,6 +1065,7 @@ type ILMethodDefs = member AsArray: ILMethodDef[] member AsList: ILMethodDef list member FindByName: string -> ILMethodDef list + member TryFindInstanceByNameAndCallingSignature: string * ILCallingSignature -> ILMethodDef option /// Field definitions. [] @@ -1316,12 +1327,16 @@ and [] /// The information is enough to perform name resolution for the F# compiler, probe attributes /// for ExtensionAttribute etc. This is key to the on-demand exploration of .NET metadata. /// This information has to be "Goldilocks" - not too much, not too little, just right. -and [] ILPreTypeDef = - member Namespace: string list - member Name: string - member MetadataIndex: int32 +and [] ILPreTypeDef = + abstract Namespace: string list + abstract Name: string /// Realise the actual full typedef - member GetTypeDef : unit -> ILTypeDef + abstract GetTypeDef : unit -> ILTypeDef + + +and [] ILPreTypeDefImpl = + interface ILPreTypeDef + and [] ILTypeDefStored @@ -1386,7 +1401,8 @@ type ILExportedTypeOrForwarder = [] [] type ILExportedTypesAndForwarders = - member AsList: ILExportedTypeOrForwarder list + member AsList: ILExportedTypeOrForwarder list + member TryFindByName: string -> ILExportedTypeOrForwarder option [] type ILResourceAccess = @@ -1395,11 +1411,9 @@ type ILResourceAccess = [] type ILResourceLocation = - /// Represents a manifest resource that can be read from within the PE file - | LocalIn of string * int * int - - /// Represents a manifest resource that is due to be written to the output PE file - | LocalOut of byte[] + internal + /// Represents a manifest resource that can be read or written to a PE file + | Local of ReadOnlyByteMemory /// Represents a manifest resource in an associated file | File of ILModuleRef * int32 @@ -1419,7 +1433,7 @@ type ILResource = MetadataIndex: int32 } /// Read the bytes from a resource local to an assembly. Will fail for non-local resources. - member GetBytes : unit -> byte[] + member internal GetBytes : unit -> ReadOnlyByteMemory member CustomAttrs: ILAttributes @@ -1566,6 +1580,7 @@ val isTypeNameForGlobalFunctions: string -> bool [] type ILGlobals = member primaryAssemblyScopeRef: ILScopeRef + member primaryAssemblyRef: ILAssemblyRef member primaryAssemblyName: string member typ_Object: ILType member typ_String: ILType @@ -1585,10 +1600,20 @@ type ILGlobals = member typ_Double: ILType member typ_Bool: ILType member typ_Char: ILType - + member typ_TypedReference: ILType + + /// Is the given assembly possibly a primary assembly? + /// In practice, a primary assembly is an assembly that contains the System.Object type definition + /// and has no referenced assemblies. + /// However, we must consider assemblies that forward the System.Object type definition + /// to be possible primary assemblies. + /// Therefore, this will return true if the given assembly is the real primary assembly or an assembly that forwards + /// the System.Object type definition. + /// Assembly equivalency ignores the version here. + member IsPossiblePrimaryAssemblyRef: ILAssemblyRef -> bool /// Build the table of commonly used references given functions to find types in system assemblies -val mkILGlobals: ILScopeRef -> ILGlobals +val mkILGlobals: primaryScopeRef: ILScopeRef * assembliesThatForwardToPrimaryAssembly: ILAssemblyRef list -> ILGlobals val EcmaMscorlibILGlobals: ILGlobals @@ -1939,23 +1964,23 @@ val instILType: ILGenericArgs -> ILType -> ILType val ecmaPublicKey: PublicKey /// Discriminating different important built-in types. -val isILObjectTy: ILType -> bool -val isILStringTy: ILType -> bool -val isILSByteTy: ILType -> bool -val isILByteTy: ILType -> bool -val isILInt16Ty: ILType -> bool -val isILUInt16Ty: ILType -> bool -val isILInt32Ty: ILType -> bool -val isILUInt32Ty: ILType -> bool -val isILInt64Ty: ILType -> bool -val isILUInt64Ty: ILType -> bool -val isILIntPtrTy: ILType -> bool -val isILUIntPtrTy: ILType -> bool -val isILBoolTy: ILType -> bool -val isILCharTy: ILType -> bool -val isILTypedReferenceTy: ILType -> bool -val isILDoubleTy: ILType -> bool -val isILSingleTy: ILType -> bool +val isILObjectTy: ILGlobals -> ILType -> bool +val isILStringTy: ILGlobals -> ILType -> bool +val isILSByteTy: ILGlobals -> ILType -> bool +val isILByteTy: ILGlobals -> ILType -> bool +val isILInt16Ty: ILGlobals -> ILType -> bool +val isILUInt16Ty: ILGlobals -> ILType -> bool +val isILInt32Ty: ILGlobals -> ILType -> bool +val isILUInt32Ty: ILGlobals -> ILType -> bool +val isILInt64Ty: ILGlobals -> ILType -> bool +val isILUInt64Ty: ILGlobals -> ILType -> bool +val isILIntPtrTy: ILGlobals -> ILType -> bool +val isILUIntPtrTy: ILGlobals -> ILType -> bool +val isILBoolTy: ILGlobals -> ILType -> bool +val isILCharTy: ILGlobals -> ILType -> bool +val isILTypedReferenceTy: ILGlobals -> ILType -> bool +val isILDoubleTy: ILGlobals -> ILType -> bool +val isILSingleTy: ILGlobals -> ILType -> bool val sha1HashInt64 : byte[] -> int64 /// Get a public key token from a public key. @@ -1990,13 +2015,11 @@ type ILPropertyRef = member Name: string interface System.IComparable -val runningOnMono: bool - type ILReferences = { AssemblyReferences: ILAssemblyRef list ModuleReferences: ILModuleRef list } /// Find the full set of assemblies referenced by a module. -val computeILRefs: ILModuleDef -> ILReferences +val computeILRefs: ILGlobals -> ILModuleDef -> ILReferences val emptyILRefs: ILReferences diff --git a/src/fcs-fable/src/absil/ilascii.fs b/src/fcs-fable/src/absil/ilascii.fs old mode 100755 new mode 100644 index cf8cef0a63..e5b7782ba7 --- a/src/fcs-fable/src/absil/ilascii.fs +++ b/src/fcs-fable/src/absil/ilascii.fs @@ -8,8 +8,8 @@ open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.IL // set to the proper value at CompileOps.fs (BuildFrameworkTcImports) -// Only reelvant when compiling FSharp.Core.dll -let parseILGlobals = ref EcmaMscorlibILGlobals +// Only relevant when compiling FSharp.Core.dll +let mutable parseILGlobals = EcmaMscorlibILGlobals /// Table of parsing and pretty printing data for instructions. let noArgInstrs = @@ -226,12 +226,6 @@ let DoubleInstrs : Lazy> = ["ldc";"r8"], (fun x -> (AI_ldc (DT_R8, x))) ] -/// Table of parsing and pretty printing data for instructions. -let MethodSpecInstrs : Lazy> = - lazy [ - ["call"], (fun (mspec, y) -> I_call (Normalcall, mspec, y)) - ] - /// Table of parsing and pretty printing data for instructions. let StringInstrs : Lazy> = lazy [ diff --git a/src/fcs-fable/src/absil/ilascii.fsi b/src/fcs-fable/src/absil/ilascii.fsi old mode 100755 new mode 100644 index 1b94bbed22..67a5c9eb4b --- a/src/fcs-fable/src/absil/ilascii.fsi +++ b/src/fcs-fable/src/absil/ilascii.fsi @@ -14,7 +14,7 @@ open FSharp.Compiler.AbstractIL.IL // IL Parser state - must be initialized before parsing a module // -------------------------------------------------------------------- -val parseILGlobals: ILGlobals ref +val mutable parseILGlobals: ILGlobals // -------------------------------------------------------------------- // IL Lexer and pretty-printer tables @@ -41,7 +41,6 @@ val Int64Instrs: LazyInstrTable val Int32Instrs: LazyInstrTable val Int32Int32Instrs: LazyInstrTable val DoubleInstrs: LazyInstrTable -val MethodSpecInstrs: LazyInstrTable val StringInstrs: LazyInstrTable val TokenInstrs: LazyInstrTable val TypeInstrs: LazyInstrTable diff --git a/src/fcs-fable/src/absil/ilbinary.fs b/src/fcs-fable/src/absil/ilbinary.fs old mode 100755 new mode 100644 index 2b22b4cbab..eea2f06bfd --- a/src/fcs-fable/src/absil/ilbinary.fs +++ b/src/fcs-fable/src/absil/ilbinary.fs @@ -2,10 +2,7 @@ module internal FSharp.Compiler.AbstractIL.Internal.BinaryConstants -open Internal.Utilities -open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL -open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library [] diff --git a/src/fcs-fable/src/absil/ilbinary.fsi b/src/fcs-fable/src/absil/ilbinary.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/absil/ildiag.fs b/src/fcs-fable/src/absil/ildiag.fs old mode 100755 new mode 100644 index 7cca91ba7f..6aec197182 --- a/src/fcs-fable/src/absil/ildiag.fs +++ b/src/fcs-fable/src/absil/ildiag.fs @@ -4,27 +4,28 @@ module internal FSharp.Compiler.AbstractIL.Diagnostics -open Internal.Utilities #if FABLE_COMPILER + let dprintf fmt = printf fmt let dprintfn fmt = printfn fmt let dprintn s = printfn "%s" s + #else -let diagnosticsLog = ref (Some stdout) +let mutable diagnosticsLog = Some stdout -let setDiagnosticsChannel s = diagnosticsLog := s +let setDiagnosticsChannel s = diagnosticsLog <- s -let dflushn () = match !diagnosticsLog with None -> () | Some d -> d.WriteLine(); d.Flush() -let dflush () = match !diagnosticsLog with None -> () | Some d -> d.Flush() +let dflushn () = match diagnosticsLog with None -> () | Some d -> d.WriteLine(); d.Flush() +let dflush () = match diagnosticsLog with None -> () | Some d -> d.Flush() let dprintn (s:string) = - match !diagnosticsLog with None -> () | Some d -> d.Write s; d.Write "\n"; dflush() + match diagnosticsLog with None -> () | Some d -> d.Write s; d.Write "\n"; dflush() let dprintf (fmt: Format<_,_,_,_>) = - Printf.kfprintf dflush (match !diagnosticsLog with None -> System.IO.TextWriter.Null | Some d -> d) fmt + Printf.kfprintf dflush (match diagnosticsLog with None -> System.IO.TextWriter.Null | Some d -> d) fmt let dprintfn (fmt: Format<_,_,_,_>) = - Printf.kfprintf dflushn (match !diagnosticsLog with None -> System.IO.TextWriter.Null | Some d -> d) fmt + Printf.kfprintf dflushn (match diagnosticsLog with None -> System.IO.TextWriter.Null | Some d -> d) fmt #endif \ No newline at end of file diff --git a/src/fcs-fable/src/absil/ildiag.fsi b/src/fcs-fable/src/absil/ildiag.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/absil/illex.fsl b/src/fcs-fable/src/absil/illex.fsl old mode 100755 new mode 100644 index e1f923c358..fb600548e8 --- a/src/fcs-fable/src/absil/illex.fsl +++ b/src/fcs-fable/src/absil/illex.fsl @@ -70,7 +70,6 @@ let kwdInstrTable = addTable (fun i -> INSTR_I32_I32 i) Int32Int32Instrs; addTable (fun i -> INSTR_I8 i) Int64Instrs; addTable (fun i -> INSTR_R i) DoubleInstrs; - addTable (fun i -> INSTR_METHOD i) MethodSpecInstrs; addTable (fun i -> INSTR_TYPE i) TypeInstrs; addTable (fun i -> INSTR_INT_TYPE i) IntTypeInstrs; addTable (fun i -> INSTR_VALUETYPE i) ValueTypeInstrs; diff --git a/src/fcs-fable/src/absil/illib.fs b/src/fcs-fable/src/absil/illib.fs old mode 100755 new mode 100644 index 854ebf1c1c..01ca9918f6 --- a/src/fcs-fable/src/absil/illib.fs +++ b/src/fcs-fable/src/absil/illib.fs @@ -12,10 +12,6 @@ open System.Reflection open System.Threading open System.Runtime.CompilerServices -#if FX_RESHAPED_REFLECTION -open Microsoft.FSharp.Core.ReflectionAdapters -#endif - // Logical shift right treating int32 as unsigned integer. // Code that uses this should probably be adjusted to use unsigned integer types. let (>>>&) (x: int32) (n: int32) = int32 (uint32 x >>> n) @@ -44,23 +40,23 @@ let inline nonNull msg x = if isNull x then failwith ("null: " + msg) else x let inline (===) x y = LanguagePrimitives.PhysicalEquality x y /// Per the docs the threshold for the Large Object Heap is 85000 bytes: https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/large-object-heap#how-an-object-ends-up-on-the-large-object-heap-and-how-gc-handles-them -/// We set the limit to slightly under that to allow for some 'slop' -let LOH_SIZE_THRESHOLD_BYTES = 84_900 +/// We set the limit to be 80k to account for larger pointer sizes for when F# is running 64-bit. +let LOH_SIZE_THRESHOLD_BYTES = 80_000 #if !FABLE_COMPILER // no Process support //--------------------------------------------------------------------- // Library: ReportTime //--------------------------------------------------------------------- let reportTime = - let tFirst = ref None - let tPrev = ref None + let mutable tFirst =None + let mutable tPrev = None fun showTimes descr -> if showTimes then let t = Process.GetCurrentProcess().UserProcessorTime.TotalSeconds - let prev = match !tPrev with None -> 0.0 | Some t -> t - let first = match !tFirst with None -> (tFirst := Some t; t) | Some t -> t + let prev = match tPrev with None -> 0.0 | Some t -> t + let first = match tFirst with None -> (tFirst <- Some t; t) | Some t -> t printf "ilwrite: TIME %10.3f (total) %10.3f (delta) - %s\n" (t - first) (t - prev) descr - tPrev := Some t + tPrev <- Some t #endif //------------------------------------------------------------------------- @@ -176,12 +172,12 @@ module Array = /// pass an array byref to reverse it in place let revInPlace (array: 'T []) = if Array.isEmpty array then () else - let arrlen, revlen = array.Length-1, array.Length/2 - 1 - for idx in 0 .. revlen do + let arrLen, revLen = array.Length-1, array.Length/2 - 1 + for idx in 0 .. revLen do let t1 = array.[idx] - let t2 = array.[arrlen-idx] + let t2 = array.[arrLen-idx] array.[idx] <- t2 - array.[arrlen-idx] <- t1 + array.[arrLen-idx] <- t1 /// Async implementation of Array.map. let mapAsync (mapping : 'T -> Async<'U>) (array : 'T[]) : Async<'U[]> = @@ -266,24 +262,18 @@ module Option = module List = - //let item n xs = List.nth xs n -#if FX_RESHAPED_REFLECTION - open PrimReflectionAdapters - open Microsoft.FSharp.Core.ReflectionAdapters -#endif - let sortWithOrder (c: IComparer<'T>) elements = List.sortWith (Order.toFunction c) elements let splitAfter n l = - let rec split_after_acc n l1 l2 = if n <= 0 then List.rev l1, l2 else split_after_acc (n-1) ((List.head l2):: l1) (List.tail l2) + let rec split_after_acc n l1 l2 = if n <= 0 then List.rev l1, l2 else split_after_acc (n-1) ((List.head l2) :: l1) (List.tail l2) split_after_acc n [] l let existsi f xs = - let rec loop i xs = match xs with [] -> false | h::t -> f i h || loop (i+1) t + let rec loop i xs = match xs with [] -> false | h :: t -> f i h || loop (i+1) t loop 0 xs let existsTrue (xs: bool list) = - let rec loop i xs = match xs with [] -> false | h::t -> h || loop (i+1) t + let rec loop i xs = match xs with [] -> false | h :: t -> h || loop (i+1) t loop 0 xs let lengthsEqAndForall2 p l1 l2 = @@ -293,27 +283,27 @@ module List = let rec findi n f l = match l with | [] -> None - | h::t -> if f h then Some (h, n) else findi (n+1) f t + | h :: t -> if f h then Some (h, n) else findi (n+1) f t let rec drop n l = match l with | [] -> [] - | _::xs -> if n=0 then l else drop (n-1) xs + | _ :: xs -> if n=0 then l else drop (n-1) xs let splitChoose select l = let rec ch acc1 acc2 l = match l with | [] -> List.rev acc1, List.rev acc2 - | x::xs -> + | x :: xs -> match select x with - | Choice1Of2 sx -> ch (sx::acc1) acc2 xs - | Choice2Of2 sx -> ch acc1 (sx::acc2) xs + | Choice1Of2 sx -> ch (sx :: acc1) acc2 xs + | Choice2Of2 sx -> ch acc1 (sx :: acc2) xs ch [] [] l let rec checkq l1 l2 = match l1, l2 with - | h1::t1, h2::t2 -> h1 === h2 && checkq t1 t2 + | h1 :: t1, h2 :: t2 -> h1 === h2 && checkq t1 t2 | _ -> true let mapq (f: 'T -> 'T) inp = @@ -345,14 +335,14 @@ module List = Debug.Assert(false, "empty list") invalidArg "l" "empty list" | [h] -> List.rev acc, h - | h::t -> loop (h::acc) t + | h :: t -> loop (h :: acc) t loop [] l let tryRemove f inp = let rec loop acc l = match l with | [] -> None - | h :: t -> if f h then Some (h, List.rev acc @ t) else loop (h::acc) t + | h :: t -> if f h then Some (h, List.rev acc @ t) else loop (h :: acc) t loop [] inp let headAndTail l = @@ -360,7 +350,7 @@ module List = | [] -> Debug.Assert(false, "empty list") failwith "List.headAndTail" - | h::t -> h, t + | h :: t -> h, t let zip4 l1 l2 l3 l4 = List.zip l1 (List.zip3 l2 l3 l4) |> List.map (fun (x1, (x2, x3, x4)) -> (x1, x2, x3, x4)) @@ -372,7 +362,7 @@ module List = let rec iter3 f l1 l2 l3 = match l1, l2, l3 with - | h1::t1, h2::t2, h3::t3 -> f h1 h2 h3; iter3 f t1 t2 t3 + | h1 :: t1, h2 :: t2, h3 :: t3 -> f h1 h2 h3; iter3 f t1 t2 t3 | [], [], [] -> () | _ -> failwith "iter3" @@ -380,7 +370,7 @@ module List = let rec loop acc l = match l with | [] -> List.rev acc, [] - | x::xs -> if p x then List.rev acc, l else loop (x::acc) xs + | x :: xs -> if p x then List.rev acc, l else loop (x :: acc) xs loop [] l let order (eltOrder: IComparer<'T>) = @@ -391,7 +381,7 @@ module List = | [], [] -> 0 | [], _ -> -1 | _, [] -> 1 - | x::xs, y::ys -> + | x :: xs, y :: ys -> let cxy = eltOrder.Compare(x, y) if cxy=0 then loop xs ys else cxy loop xs ys } @@ -406,22 +396,22 @@ module List = let rec assoc x l = match l with | [] -> indexNotFound() - | ((h, r)::t) -> if x = h then r else assoc x t + | ((h, r) :: t) -> if x = h then r else assoc x t let rec memAssoc x l = match l with | [] -> false - | ((h, _)::t) -> x = h || memAssoc x t + | ((h, _) :: t) -> x = h || memAssoc x t let rec memq x l = match l with | [] -> false - | h::t -> LanguagePrimitives.PhysicalEquality x h || memq x t + | h :: t -> LanguagePrimitives.PhysicalEquality x h || memq x t let mapNth n f xs = let rec mn i = function | [] -> [] - | x::xs -> if i=n then f x::xs else x::mn (i+1) xs + | x :: xs -> if i=n then f x :: xs else x :: mn (i+1) xs mn 0 xs let count pred xs = List.fold (fun n x -> if pred x then n+1 else n) 0 xs @@ -430,7 +420,7 @@ module List = let mapHeadTail fhead ftail = function | [] -> [] | [x] -> [fhead x] - | x::xs -> fhead x :: List.map ftail xs + | x :: xs -> fhead x :: List.map ftail xs let collectFold f s l = let l, s = List.mapFold f s l @@ -509,10 +499,10 @@ module ValueOptionInternal = let inline bind f x = match x with ValueSome x -> f x | ValueNone -> ValueNone type String with - member inline x.StartsWithOrdinal(value) = + member inline x.StartsWithOrdinal value = x.StartsWith(value, StringComparison.Ordinal) - member inline x.EndsWithOrdinal(value) = + member inline x.EndsWithOrdinal value = x.EndsWith(value, StringComparison.Ordinal) module String = @@ -522,7 +512,7 @@ module String = let sub (s: string) (start: int) (len: int) = s.Substring(start, len) - let contains (s: string) (c: char) = s.IndexOf(c) <> -1 + let contains (s: string) (c: char) = s.IndexOf c <> -1 let order = LanguagePrimitives.FastGenericComparer @@ -557,7 +547,7 @@ module String = | None -> str | Some c -> strArr.[0] <- Char.ToLower c - String (strArr) + String strArr let extractTrailingIndex (str: string) = match str with @@ -583,7 +573,7 @@ module String = let (|StartsWith|_|) (pattern: string) value = if String.IsNullOrWhiteSpace value then None - elif value.StartsWithOrdinal(pattern) then + elif value.StartsWithOrdinal pattern then Some() else None @@ -594,18 +584,20 @@ module String = Some() else None -#if !FABLE_COMPILER let getLines (str: string) = +#if FABLE_COMPILER + System.Text.RegularExpressions.Regex.Split(str, "\r\n|\r|\n"); +#else use reader = new StringReader(str) [| - let line = ref (reader.ReadLine()) - while not (isNull !line) do - yield !line - line := reader.ReadLine() - if str.EndsWithOrdinal("\n") then - // last trailing space not returned - // http://stackoverflow.com/questions/19365404/stringreader-omits-trailing-linebreak - yield String.Empty + let mutable line = reader.ReadLine() + while not (isNull line) do + yield line + line <- reader.ReadLine() + if str.EndsWithOrdinal("\n") then + // last trailing space not returned + // http://stackoverflow.com/questions/19365404/stringreader-omits-trailing-linebreak + yield String.Empty |] #endif @@ -650,7 +642,7 @@ type CompilationThreadToken() = interface ExecutionToken let RequireCompilationThread (_ctok: CompilationThreadToken) = () /// Represents a place in the compiler codebase where we are passed a CompilationThreadToken unnecessarily. -/// This reprents code that may potentially not need to be executed on the compilation thread. +/// This represents code that may potentially not need to be executed on the compilation thread. let DoesNotRequireCompilerThreadTokenAndCouldPossiblyBeMadeConcurrent (_ctok: CompilationThreadToken) = () /// Represents a place in the compiler codebase where we assume we are executing on a compilation thread @@ -777,7 +769,7 @@ module Cancellable = /// ValueOrCancelled.Cancelled. let runWithoutCancellation comp = #if FABLE_COMPILER - let res = run (System.Threading.CancellationToken()) comp + let res = run (CancellationToken()) comp #else let res = run CancellationToken.None comp #endif @@ -832,9 +824,9 @@ type CancellableBuilder() = member x.Bind(e, k) = Cancellable.bind k e - member x.Return(v) = Cancellable.ret v + member x.Return v = Cancellable.ret v - member x.ReturnFrom(v) = v + member x.ReturnFrom v = v member x.Combine(e1, e2) = e1 |> Cancellable.bind (fun () -> e2) @@ -844,7 +836,7 @@ type CancellableBuilder() = member x.TryFinally(e, compensation) = Cancellable.tryFinally e compensation - member x.Delay(f) = Cancellable.delay f + member x.Delay f = Cancellable.delay f member x.Zero() = Cancellable.ret () @@ -872,12 +864,12 @@ module Eventually = let rec box e = match e with | Done x -> Done (Operators.box x) - | NotYetDone (work) -> NotYetDone (fun ctok -> box (work ctok)) + | NotYetDone work -> NotYetDone (fun ctok -> box (work ctok)) let rec forceWhile ctok check e = match e with - | Done x -> Some(x) - | NotYetDone (work) -> + | Done x -> Some x + | NotYetDone work -> if not(check()) then None else forceWhile ctok check (work ctok) @@ -942,7 +934,7 @@ module Eventually = let delay (f: unit -> Eventually<'T>) = NotYetDone (fun _ctok -> f()) let tryFinally e compensation = - catch (e) + catch e |> bind (fun res -> compensation() match res with @@ -961,9 +953,9 @@ type EventuallyBuilder() = member x.Bind(e, k) = Eventually.bind k e - member x.Return(v) = Eventually.Done v + member x.Return v = Eventually.Done v - member x.ReturnFrom(v) = v + member x.ReturnFrom v = v member x.Combine(e1, e2) = e1 |> Eventually.bind (fun () -> e2) @@ -971,7 +963,7 @@ type EventuallyBuilder() = member x.TryFinally(e, compensation) = Eventually.tryFinally e compensation - member x.Delay(f) = Eventually.delay f + member x.Delay f = Eventually.delay f member x.Zero() = Eventually.Done () @@ -990,7 +982,7 @@ type UniqueStampGenerator<'T when 'T : equality>() = let encodeTab = new Dictionary<'T, int>(HashIdentity.Structural) let mutable nItems = 0 let encode str = - match encodeTab.TryGetValue(str) with + match encodeTab.TryGetValue str with | true, idx -> idx | _ -> let idx = nItems @@ -998,7 +990,7 @@ type UniqueStampGenerator<'T when 'T : equality>() = nItems <- nItems + 1 idx - member this.Encode(str) = encode str + member this.Encode str = encode str member this.Table = encodeTab.Keys @@ -1007,22 +999,15 @@ type MemoizationTable<'T, 'U>(compute: 'T -> 'U, keyComparer: IEqualityComparer< let table = new Dictionary<'T, 'U>(keyComparer) - member t.Apply(x) = + member t.Apply x = if (match canMemoize with None -> true | Some f -> f x) then -#if FABLE_COMPILER // no byref - ( - let ok, res = table.TryGetValue(x) -#else - let mutable res = Unchecked.defaultof<'U> - let ok = table.TryGetValue(x, &res) - if ok then res - else + match table.TryGetValue x with + | true, res -> res + | _ -> lock table (fun () -> - let mutable res = Unchecked.defaultof<'U> - let ok = table.TryGetValue(x, &res) -#endif - if ok then res - else + match table.TryGetValue x with + | true, res -> res + | _ -> let res = compute x table.[x] <- res res) @@ -1076,14 +1061,14 @@ type LazyWithContext<'T, 'ctxt> = x.UnsynchronizedForce(ctxt) #else // Enter the lock in case another thread is in the process of evaluating the result - Monitor.Enter(x); + Monitor.Enter x; try - x.UnsynchronizedForce(ctxt) + x.UnsynchronizedForce ctxt finally - Monitor.Exit(x) + Monitor.Exit x #endif - member x.UnsynchronizedForce(ctxt) = + member x.UnsynchronizedForce ctxt = match x.funcOrException with | null -> x.value | :? LazyWithContextFailure as res -> @@ -1107,22 +1092,12 @@ module Tables = let memoize f = let t = new Dictionary<_, _>(1000, HashIdentity.Structural) fun x -> -#if FABLE_COMPILER - match t.TryGetValue(x) with + match t.TryGetValue x with | true, res -> res | _ -> let res = f x t.[x] <- res res -#else - let mutable res = Unchecked.defaultof<_> - if t.TryGetValue(x, &res) then - res - else - res <- f x - t.[x] <- res - res -#endif /// Interface that defines methods for comparing objects using partial equality relation type IPartialEqualityComparer<'T> = @@ -1146,15 +1121,15 @@ module IPartialEqualityComparer = let partialDistinctBy (per: IPartialEqualityComparer<'T>) seq = let wper = { new IPartialEqualityComparer> with - member __.InEqualityRelation (Wrap x) = per.InEqualityRelation (x) + member __.InEqualityRelation (Wrap x) = per.InEqualityRelation x member __.Equals(Wrap x, Wrap y) = per.Equals(x, y) - member __.GetHashCode (Wrap x) = per.GetHashCode(x) } + member __.GetHashCode (Wrap x) = per.GetHashCode x } // Wrap a Wrap _ around all keys in case the key type is itself a type using null as a representation let dict = Dictionary, obj>(wper) seq |> List.filter (fun v -> - let key = Wrap(v) - if (per.InEqualityRelation(v)) then - if dict.ContainsKey(key) then false else (dict.[key] <- null; true) + let key = Wrap v + if (per.InEqualityRelation v) then + if dict.ContainsKey key then false else (dict.[key] <- null; true) else true) //------------------------------------------------------------------------- @@ -1317,11 +1292,6 @@ type LayeredMultiMap<'Key, 'Value when 'Key : equality and 'Key : comparison>(co [] module Shim = -#if FX_RESHAPED_REFLECTION - open PrimReflectionAdapters - open Microsoft.FSharp.Core.ReflectionAdapters -#endif - type IFileSystem = #if !FABLE_COMPILER @@ -1400,18 +1370,18 @@ module Shim = member __.IsInvalidPathShim(path: string) = let isInvalidPath(p: string) = - String.IsNullOrEmpty(p) || p.IndexOfAny(Path.GetInvalidPathChars()) <> -1 + String.IsNullOrEmpty p || p.IndexOfAny(Path.GetInvalidPathChars()) <> -1 let isInvalidFilename(p: string) = - String.IsNullOrEmpty(p) || p.IndexOfAny(Path.GetInvalidFileNameChars()) <> -1 + String.IsNullOrEmpty p || p.IndexOfAny(Path.GetInvalidFileNameChars()) <> -1 let isInvalidDirectory(d: string) = d=null || d.IndexOfAny(Path.GetInvalidPathChars()) <> -1 - isInvalidPath (path) || - let directory = Path.GetDirectoryName(path) - let filename = Path.GetFileName(path) - isInvalidDirectory(directory) || isInvalidFilename(filename) + isInvalidPath path || + let directory = Path.GetDirectoryName path + let filename = Path.GetFileName path + isInvalidDirectory directory || isInvalidFilename filename #if !FABLE_COMPILER member __.GetTempPathShim() = Path.GetTempPath() @@ -1423,7 +1393,7 @@ module Shim = member __.FileDelete (fileName: string) = File.Delete fileName member __.IsStableFileHeuristic (fileName: string) = - let directory = Path.GetDirectoryName(fileName) + let directory = Path.GetDirectoryName fileName directory.Contains("Reference Assemblies/") || directory.Contains("Reference Assemblies\\") || directory.Contains("packages/") || @@ -1431,10 +1401,48 @@ module Shim = directory.Contains("lib/mono/") #endif - let mutable FileSystem = DefaultFileSystem() :> IFileSystem + let mutable FileSystem = DefaultFileSystem() :> IFileSystem #if !FABLE_COMPILER + // The choice of 60 retries times 50 ms is not arbitrary. The NTFS FILETIME structure + // uses 2 second resolution for LastWriteTime. We retry long enough to surpass this threshold + // plus 1 second. Once past the threshold the incremental builder will be able to retry asynchronously based + // on plain old timestamp checking. + // + // The sleep time of 50ms is chosen so that we can respond to the user more quickly for Intellisense operations. + // + // This is not run on the UI thread for VS but it is on a thread that must be stopped before Intellisense + // can return any result except for pending. + let private retryDelayMilliseconds = 50 + let private numRetries = 60 + + let private getReader (filename, codePage: int option, retryLocked: bool) = + // Retry multiple times since other processes may be writing to this file. + let rec getSource retryNumber = + try + // Use the .NET functionality to auto-detect the unicode encoding + let stream = FileSystem.FileStreamReadShim(filename) + match codePage with + | None -> new StreamReader(stream,true) + | Some n -> new StreamReader(stream,System.Text.Encoding.GetEncoding(n)) + with + // We can get here if the file is locked--like when VS is saving a file--we don't have direct + // access to the HRESULT to see that this is EONOACCESS. + | :? System.IO.IOException as err when retryLocked && err.GetType() = typeof -> + // This second check is to make sure the exception is exactly IOException and none of these for example: + // DirectoryNotFoundException + // EndOfStreamException + // FileNotFoundException + // FileLoadException + // PathTooLongException + if retryNumber < numRetries then + System.Threading.Thread.Sleep (retryDelayMilliseconds) + getSource (retryNumber + 1) + else + reraise() + getSource 0 + type File with static member ReadBinaryChunk (fileName, start, len) = @@ -1446,4 +1454,7 @@ module Shim = n <- n + stream.Read(buffer, n, len-n) buffer + static member OpenReaderAndRetry (filename, codepage, retryLocked) = + getReader (filename, codepage, retryLocked) + #endif diff --git a/src/fcs-fable/src/absil/ilmorph.fs b/src/fcs-fable/src/absil/ilmorph.fs old mode 100755 new mode 100644 index ffd86aa504..b6fb7ce69b --- a/src/fcs-fable/src/absil/ilmorph.fs +++ b/src/fcs-fable/src/absil/ilmorph.fs @@ -3,11 +3,8 @@ module internal FSharp.Compiler.AbstractIL.Morphs open System.Collections.Generic -open Internal.Utilities open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.AbstractIL.Diagnostics open FSharp.Compiler.AbstractIL.IL let mutable morphCustomAttributeData = false @@ -50,7 +47,7 @@ let code_instr2instr_ty2ty (finstr,fty) (c:ILCode) = Exceptions = c.Exceptions |> List.map (fun e -> { e with Clause = e.Clause |> (function ILExceptionClause.TypeCatch (ilty, b) -> ILExceptionClause.TypeCatch (fty ilty, b) | cl -> cl) }) } // -------------------------------------------------------------------- -// Standard morphisms - mapping tyes etc. +// Standard morphisms - mapping types etc. // -------------------------------------------------------------------- let rec ty_tref2tref f x = diff --git a/src/fcs-fable/src/absil/ilmorph.fsi b/src/fcs-fable/src/absil/ilmorph.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/absil/ilnativeres.fs b/src/fcs-fable/src/absil/ilnativeres.fs new file mode 100644 index 0000000000..53321b9eef --- /dev/null +++ b/src/fcs-fable/src/absil/ilnativeres.fs @@ -0,0 +1,955 @@ +// Quite literal port of : +// https://github.com/dotnet/roslyn/blob/fab7134296816fc80019c60b0f5bef7400cf23ea/src/Compilers/Core/Portable/PEWriter/NativeResourceWriter.cs +// And https://github.com/dotnet/roslyn/blob/d36121da4b527ee0617e4b0940b9d0b17b584470/src/Compilers/Core/Portable/CvtRes.cs +// And their dependencies (some classes) + +module internal FSharp.Compiler.AbstractIL.Internal.NativeRes + +open System +open System.Collections.Generic +open System.Diagnostics +open System.IO +open System.Globalization +open System.Runtime.InteropServices +open System.Linq +open System.Reflection.Metadata +open System.Reflection.PortableExecutable +open System.Runtime.CompilerServices +open System.Text + +open Checked + +type BYTE = byte +type DWORD = uint32 +type WCHAR = System.Char +type WORD = uint16 + +let inline WORD s = uint16 s +let inline DWORD s = uint32 s +let inline WCHAR s = char s +let inline BYTE s = byte s + +type ResourceException(name: string, ?inner: Exception) = + inherit Exception (name, Option.toObj inner) + +type RESOURCE_STRING () = + member val Ordinal = Unchecked.defaultof with get, set + member val theString = Unchecked.defaultof with get, set + +type RESOURCE () = + member val pstringType = Unchecked.defaultof with get, set + member val pstringName = Unchecked.defaultof with get, set + member val DataSize = Unchecked.defaultof with get, set + member val HeaderSize = Unchecked.defaultof with get, set + member val DataVersion = Unchecked.defaultof with get, set + member val MemoryFlags = Unchecked.defaultof with get, set + member val LanguageId = Unchecked.defaultof with get, set + member val Version = Unchecked.defaultof with get, set + member val Characteristics = Unchecked.defaultof with get, set + member val data = Unchecked.defaultof with get, set + +type CvtResFile () = + static member val private RT_DLGINCLUDE = 17 with get, set + + static member ReadResFile (stream: Stream) = + let mutable reader = new BinaryReader (stream, Encoding.Unicode) + let mutable resourceNames = new List() + + // The stream might be empty, so let's check + if not (reader.PeekChar () = -1) then + let mutable startPos = stream.Position + let mutable initial32Bits = reader.ReadUInt32 () + if initial32Bits <> uint32 0 then + raise <| ResourceException(FSComp.SR.nativeResourceFormatError()) + stream.Position <- startPos + while (stream.Position < stream.Length) do + let mutable cbData = reader.ReadUInt32 () + let mutable cbHdr = reader.ReadUInt32 () + if cbHdr < 2u * uint32 sizeof then + // TODO: + // Current FSComp.txt converter doesn't yet support %x and %lx so format it as a string + // Because the lkg build is out of our control, will need to do it this way until + // The conversion fix flows through to the lkg + let msg = String.Format("0x{0:x}", stream.Position - 8L) + raise <| ResourceException(FSComp.SR.nativeResourceHeaderMalformed msg) + if cbData = 0u then + stream.Position <- stream.Position + int64 cbHdr - 2L * int64 sizeof + else + let mutable pAdditional = RESOURCE() + pAdditional.HeaderSize <- cbHdr + pAdditional.DataSize <- cbData + pAdditional.pstringType <- CvtResFile.ReadStringOrID (reader) + pAdditional.pstringName <- CvtResFile.ReadStringOrID (reader) + stream.Position <- stream.Position + 3L &&& ~~~3L + pAdditional.DataVersion <- reader.ReadUInt32 () + pAdditional.MemoryFlags <- reader.ReadUInt16 () + pAdditional.LanguageId <- reader.ReadUInt16 () + pAdditional.Version <- reader.ReadUInt32 () + pAdditional.Characteristics <- reader.ReadUInt32 () + pAdditional.data <- Array.zeroCreate (int pAdditional.DataSize) + reader.Read (pAdditional.data, 0, pAdditional.data.Length) |> ignore + stream.Position <- stream.Position + 3L &&& ~~~3L + if pAdditional.pstringType.theString = Unchecked.defaultof<_> && (pAdditional.pstringType.Ordinal = uint16 CvtResFile.RT_DLGINCLUDE) then + () (* ERROR ContinueNotSupported *) + else + resourceNames.Add (pAdditional) + resourceNames + + static member private ReadStringOrID (fhIn: BinaryReader) = + let mutable (pstring: RESOURCE_STRING) = RESOURCE_STRING () + let mutable (firstWord: WCHAR) = (fhIn.ReadChar ()) + if int firstWord = 0xFFFF then + pstring.Ordinal <- fhIn.ReadUInt16 () + else + pstring.Ordinal <- uint16 0xFFFF + let mutable (sb: StringBuilder) = StringBuilder () + let mutable (curChar: WCHAR) = firstWord + while (curChar <> char 0) do + sb.Append(curChar) |> ignore + curChar <- fhIn.ReadChar () + pstring.theString <- sb.ToString () + pstring + + +[] +type SectionCharacteristics = + | TypeReg = 0u + | TypeDSect = 1u + | TypeNoLoad = 2u + | TypeGroup = 4u + | TypeNoPad = 8u + | TypeCopy = 16u + | ContainsCode = 32u + | ContainsInitializedData = 64u + | ContainsUninitializedData = 128u + | LinkerOther = 256u + | LinkerInfo = 512u + | TypeOver = 1024u + | LinkerRemove = 2048u + | LinkerComdat = 4096u + | MemProtected = 16384u + | NoDeferSpecExc = 16384u + | GPRel = 32768u + | MemFardata = 32768u + | MemSysheap = 65536u + | MemPurgeable = 131072u + | Mem16Bit = 131072u + | MemLocked = 262144u + | MemPreload = 524288u + | Align1Bytes = 1048576u + | Align2Bytes = 2097152u + | Align4Bytes = 3145728u + | Align8Bytes = 4194304u + | Align16Bytes = 5242880u + | Align32Bytes = 6291456u + | Align64Bytes = 7340032u + | Align128Bytes = 8388608u + | Align256Bytes = 9437184u + | Align512Bytes = 10485760u + | Align1024Bytes = 11534336u + | Align2048Bytes = 12582912u + | Align4096Bytes = 13631488u + | Align8192Bytes = 14680064u + | AlignMask = 15728640u + | LinkerNRelocOvfl = 16777216u + | MemDiscardable = 33554432u + | MemNotCached = 67108864u + | MemNotPaged = 134217728u + | MemShared = 268435456u + | MemExecute = 536870912u + | MemRead = 1073741824u + | MemWrite = 2147483648u + +type ResourceSection() = + new(sectionBytes: byte[], relocations: uint32[]) as this = + (ResourceSection ()) + then + Debug.Assert (sectionBytes :> obj <> Unchecked.defaultof<_>) + Debug.Assert (relocations :> obj <> Unchecked.defaultof<_>) + this.SectionBytes <- sectionBytes + this.Relocations <- relocations + + member val SectionBytes = Unchecked.defaultof with get,set + member val Relocations = Unchecked.defaultof with get,set + +[] +type StreamExtensions () = + [] + static member TryReadAll (stream: Stream, buffer: byte[], offset: int, count: int) = + Debug.Assert (count > 0) + let mutable (totalBytesRead: int) = Unchecked.defaultof + let mutable (isFinished: bool) = false + let mutable (bytesRead: int) = 0 + do + totalBytesRead <- 0 + while totalBytesRead < count && not isFinished do + bytesRead <- stream.Read (buffer, (offset + totalBytesRead), (count - totalBytesRead)) + if bytesRead = 0 then + isFinished <- true // break; + else totalBytesRead <- totalBytesRead + bytesRead + totalBytesRead + +type COFFResourceReader() = + static member private ConfirmSectionValues (hdr: SectionHeader, fileSize: int64) = + if int64 hdr.PointerToRawData + int64 hdr.SizeOfRawData > fileSize then + raise <| ResourceException ("CoffResourceInvalidSectionSize") + + static member ReadWin32ResourcesFromCOFF (stream: Stream) = + let mutable peHeaders = new PEHeaders (stream) + let mutable rsrc1 = SectionHeader () + let mutable rsrc2 = SectionHeader () + let mutable (foundCount: int) = 0 + for sectionHeader in peHeaders.SectionHeaders do + if sectionHeader.Name = ".rsrc$01" then + rsrc1 <- sectionHeader + foundCount <- foundCount + 1 + else + if sectionHeader.Name = ".rsrc$02" then + rsrc2 <- sectionHeader + foundCount <- foundCount + 1 + if foundCount <> 2 then + raise <| ResourceException ("CoffResourceMissingSection") + COFFResourceReader.ConfirmSectionValues (rsrc1, stream.Length) + COFFResourceReader.ConfirmSectionValues (rsrc2, stream.Length) + let mutable imageResourceSectionBytes = Array.zeroCreate (rsrc1.SizeOfRawData + rsrc2.SizeOfRawData) + stream.Seek (int64 rsrc1.PointerToRawData, SeekOrigin.Begin) |> ignore + stream.TryReadAll (imageResourceSectionBytes, 0, rsrc1.SizeOfRawData) |> ignore + stream.Seek (int64 rsrc2.PointerToRawData, SeekOrigin.Begin) |> ignore + stream.TryReadAll (imageResourceSectionBytes, rsrc1.SizeOfRawData, rsrc2.SizeOfRawData) |> ignore + let mutable (SizeOfRelocationEntry: int) = 10 + try + let mutable relocLastAddress = rsrc1.PointerToRelocations + (int rsrc1.NumberOfRelocations * SizeOfRelocationEntry) + if int64 relocLastAddress > stream.Length then + raise <| ResourceException ("CoffResourceInvalidRelocation") + with + :? OverflowException -> (raise <| ResourceException("CoffResourceInvalidRelocation")) + let mutable relocationOffsets = Array.zeroCreate (int rsrc1.NumberOfRelocations) + let mutable relocationSymbolIndices = Array.zeroCreate (int rsrc1.NumberOfRelocations) + let mutable reader = new BinaryReader (stream, Encoding.Unicode) + stream.Position <- int64 rsrc1.PointerToRelocations + do + let mutable (i: int) = 0 + while (i < int rsrc1.NumberOfRelocations) do + relocationOffsets.[i] <- reader.ReadUInt32 () + relocationSymbolIndices.[i] <- reader.ReadUInt32 () + reader.ReadUInt16 () |> ignore //we do nothing with the "Type" + i <- i + 1 + stream.Position <- int64 peHeaders.CoffHeader.PointerToSymbolTable + let mutable (ImageSizeOfSymbol: uint32) = 18u + try + let mutable lastSymAddress = int64 peHeaders.CoffHeader.PointerToSymbolTable + int64 peHeaders.CoffHeader.NumberOfSymbols * int64 ImageSizeOfSymbol (* ERROR UnknownNode *) + if lastSymAddress > stream.Length then + raise <| ResourceException ("CoffResourceInvalidSymbol") + with + :? OverflowException -> (raise <| ResourceException("CoffResourceInvalidSymbol")) + let mutable outputStream = new MemoryStream (imageResourceSectionBytes) + let mutable writer = new BinaryWriter (outputStream) + do + let mutable (i: int) = 0 + while (i < relocationSymbolIndices.Length) do + if int relocationSymbolIndices.[i] > peHeaders.CoffHeader.NumberOfSymbols then + raise <| ResourceException ("CoffResourceInvalidRelocation") + let mutable offsetOfSymbol = int64 peHeaders.CoffHeader.PointerToSymbolTable + int64 relocationSymbolIndices.[i] * int64 ImageSizeOfSymbol + stream.Position <- offsetOfSymbol + stream.Position <- stream.Position + 8L + let mutable symValue = reader.ReadUInt32 () + let mutable symSection = reader.ReadInt16 () + let mutable symType = reader.ReadUInt16 () + let mutable (IMAGE_SYM_TYPE_NULL: uint16) = uint16 0x0000 + if symType <> IMAGE_SYM_TYPE_NULL || symSection <> 3s then + raise <| ResourceException("CoffResourceInvalidSymbol") + outputStream.Position <- int64 relocationOffsets.[i] + writer.Write (uint32 (int64 symValue + int64 rsrc1.SizeOfRawData)) + i <- i + 1 + + ResourceSection(imageResourceSectionBytes, relocationOffsets) + +[] +type ICONDIRENTRY = + val mutable bWidth: BYTE + val mutable bHeight: BYTE + val mutable bColorCount: BYTE + val mutable bReserved: BYTE + val mutable wPlanes: WORD + val mutable wBitCount: WORD + val mutable dwBytesInRes: DWORD + val mutable dwImageOffset: DWORD + +type VersionHelper() = + /// + /// Parses a version string of the form "major [ '.' minor [ '.' build [ '.' revision ] ] ]". + /// + /// The version string to parse. + /// If parsing succeeds, the parsed version. Otherwise a version that represents as much of the input as could be parsed successfully. + /// True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise. + static member TryParse(s: string, [] version: byref) = + VersionHelper.TryParse (s, false, UInt16.MaxValue, true, ref version) + + /// + /// Parses a version string of the form "major [ '.' minor [ '.' ( '*' | ( build [ '.' ( '*' | revision ) ] ) ) ] ]" + /// as accepted by System.Reflection.AssemblyVersionAttribute. + /// + /// The version string to parse. + /// Indicates whether or not a wildcard is accepted as the terminal component. + /// + /// If parsing succeeded, the parsed version. Otherwise a version instance with all parts set to zero. + /// If contains * the version build and/or revision numbers are set to . + /// + /// True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise. + + static member TryParseAssemblyVersion (s: string, allowWildcard: bool, [] version: byref) = + VersionHelper.TryParse (s, allowWildcard, (UInt16.MaxValue - 1us), false, ref version) + + static member private NullVersion = new Version (0, 0, 0, 0) + + /// + /// Parses a version string of the form "major [ '.' minor [ '.' ( '*' | ( build [ '.' ( '*' | revision ) ] ) ) ] ]" + /// as accepted by System.Reflection.AssemblyVersionAttribute. + /// + /// The version string to parse. + /// Indicates whether or not we're parsing an assembly version string. If so, wildcards are accepted and each component must be less than 65535. + /// The maximum value that a version component may have. + /// Allow the parsing of version elements where invalid characters exist. e.g. 1.2.2a.1 + /// + /// If parsing succeeded, the parsed version. When is true a version with values up to the first invalid character set. Otherwise a version with all parts set to zero. + /// If contains * and wildcard is allowed the version build and/or revision numbers are set to . + /// + /// True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise. + static member private TryParse(s: string, allowWildcard: bool, maxValue: uint16, allowPartialParse: bool, [] version: byref) = + Debug.Assert (not allowWildcard || maxValue < UInt16.MaxValue) + if String.IsNullOrWhiteSpace (s) then + version <- VersionHelper.NullVersion + false + else + let mutable (elements: string[]) = s.Split ('.') + let mutable (hasWildcard: bool) = allowWildcard && elements.[(int (elements.Length - 1))] = "*" + if hasWildcard && elements.Length < 3 || elements.Length > 4 then + version <- VersionHelper.NullVersion + false + else + let mutable (values: uint16[]) = Array.zeroCreate 4 + let mutable (lastExplicitValue: int) = + if hasWildcard then + elements.Length - 1 + else elements.Length + let mutable (parseError: bool) = false + let mutable earlyReturn = None + do + let mutable (i: int) = 0 + let mutable breakLoop = false + while (i < lastExplicitValue) && not breakLoop do + if not (UInt16.TryParse (elements.[i], NumberStyles.None, CultureInfo.InvariantCulture, ref values.[i])) || values.[i] > maxValue then + if not allowPartialParse then + earlyReturn <- Some false + breakLoop <- true + version <- VersionHelper.NullVersion + else + parseError <- true + if String.IsNullOrWhiteSpace (elements.[i]) then + values.[i] <- 0us + breakLoop <- true + else + if values.[i] > maxValue then + values.[i] <- 0us + breakLoop <- true + else + let mutable (invalidFormat: bool) = false + //let mutable (number: bigint) = 0I + do + let mutable idx = 0 + let mutable breakLoop = false + while (idx < elements.[i].Length) && not breakLoop do + if not (Char.IsDigit (elements.[i].[idx])) then + invalidFormat <- true + VersionHelper.TryGetValue ((elements.[i].Substring (0, idx)), ref values.[i]) |> ignore + breakLoop <- true + else + idx <- idx + 1 + let mutable doBreak = true + if not invalidFormat then + if VersionHelper.TryGetValue (elements.[i], ref values.[i]) then + //For this scenario the old compiler would continue processing the remaining version elements + //so continue processing + doBreak <- false + () (* ERROR ContinueNotSupported *) + (* ERROR BreakNotSupported *) + if not breakLoop then + i <- i + 1 + if hasWildcard then + let mutable (i: int) = lastExplicitValue + while (i < values.Length) do + values.[i] <- UInt16.MaxValue + i <- i + 1 + version <- new Version(int values.[0], int values.[1], int values.[2], int values.[3]) + not parseError + + static member private TryGetValue(s: string, [] value: byref): bool = + let mutable (number: bigint) = Unchecked.defaultof + if bigint.TryParse (s, NumberStyles.None, CultureInfo.InvariantCulture, ref number) then + value <- uint16 (number % bigint 65536) + true + else + value <- 0us + false + + static member GenerateVersionFromPatternAndCurrentTime(time: DateTime, pattern: Version) = + if pattern = Unchecked.defaultof<_> || pattern.Revision <> int UInt16.MaxValue then + pattern + else + let mutable time = time + // MSDN doc on the attribute: + // "The default build number increments daily. The default revision number is the number of seconds since midnight local time + // (without taking into account time zone adjustments for daylight saving time), divided by 2." + if time = Unchecked.defaultof then + time <- DateTime.Now + let mutable (revision: int) = int time.TimeOfDay.TotalSeconds / 2 + Debug.Assert (revision < int UInt16.MaxValue) + if pattern.Build = int UInt16.MaxValue then + let mutable (days: TimeSpan) = time.Date - new DateTime(2000, 1, 1) + let mutable (build: int) = Math.Min (int UInt16.MaxValue, (int days.TotalDays)) + new Version(pattern.Major, pattern.Minor, int (uint16 build), int (uint16 revision)) + else + new Version(pattern.Major, pattern.Minor, pattern.Build, int (uint16 revision)) + +type VersionResourceSerializer () = + member val private _commentsContents = Unchecked.defaultof with get, set + member val private _companyNameContents = Unchecked.defaultof with get, set + member val private _fileDescriptionContents = Unchecked.defaultof with get, set + member val private _fileVersionContents = Unchecked.defaultof with get, set + member val private _internalNameContents = Unchecked.defaultof with get, set + member val private _legalCopyrightContents = Unchecked.defaultof with get, set + member val private _legalTrademarksContents = Unchecked.defaultof with get, set + member val private _originalFileNameContents = Unchecked.defaultof with get, set + member val private _productNameContents = Unchecked.defaultof with get, set + member val private _productVersionContents = Unchecked.defaultof with get, set + member val private _assemblyVersionContents = Unchecked.defaultof with get, set + static member val private vsVersionInfoKey = "VS_VERSION_INFO" with get, set + static member val private varFileInfoKey = "VarFileInfo" with get, set + static member val private translationKey = "Translation" with get, set + static member val private stringFileInfoKey = "StringFileInfo" with get, set + member val private _langIdAndCodePageKey = Unchecked.defaultof with get, set + + static member val private CP_WINUNICODE = 1200u + static member val private sizeVS_FIXEDFILEINFO = uint16 (sizeof * 13) + + member val private _isDll = Unchecked.defaultof with get, set + + new(isDll: bool, + comments: string, + companyName: string, + fileDescription: string, + fileVersion: string, + internalName: string, + legalCopyright: string, + legalTrademark: string, + originalFileName: string, + productName: string, + productVersion: string, + assemblyVersion: Version) as this = + + VersionResourceSerializer () + then + this._isDll <- isDll + this._commentsContents <- comments + this._companyNameContents <- companyName + this._fileDescriptionContents <- fileDescription + this._fileVersionContents <- fileVersion + this._internalNameContents <- internalName + this._legalCopyrightContents <- legalCopyright + this._legalTrademarksContents <- legalTrademark + this._originalFileNameContents <- originalFileName + this._productNameContents <- productName + this._productVersionContents <- productVersion + this._assemblyVersionContents <- assemblyVersion + this._langIdAndCodePageKey <- System.String.Format ("{0:x4}{1:x4}", 0, VersionResourceSerializer.CP_WINUNICODE) + + static member val private VFT_APP = 0x00000001u + static member val private VFT_DLL = 0x00000002u + + member private this.GetVerStrings() = seq { + if this._commentsContents <> Unchecked.defaultof<_> then + yield KeyValuePair<_,_>("Comments", this._commentsContents) + if this._companyNameContents <> Unchecked.defaultof<_> then + yield KeyValuePair<_,_>("CompanyName", this._companyNameContents) + if this._fileDescriptionContents <> Unchecked.defaultof<_> then + yield KeyValuePair<_,_>("FileDescription", this._fileDescriptionContents) + yield KeyValuePair<_,_>("FileVersion", this._fileVersionContents) + if this._internalNameContents <> Unchecked.defaultof<_> then + yield KeyValuePair<_,_>("InternalName", this._internalNameContents) + if this._legalCopyrightContents <> Unchecked.defaultof<_> then + yield KeyValuePair<_,_>("LegalCopyright", this._legalCopyrightContents) + if this._legalTrademarksContents <> Unchecked.defaultof<_> then + yield KeyValuePair<_,_>("LegalTrademarks", this._legalTrademarksContents) + if this._originalFileNameContents <> Unchecked.defaultof<_> then + yield KeyValuePair<_,_>("OriginalFilename", this._originalFileNameContents) + if this._productNameContents <> Unchecked.defaultof<_> then + yield KeyValuePair<_,_>("ProductName", this._productNameContents) + yield KeyValuePair<_,_>("ProductVersion", this._fileVersionContents) + if this._assemblyVersionContents <> Unchecked.defaultof<_> then + yield KeyValuePair<_,_>("Assembly Version", this._assemblyVersionContents.ToString()) + } + + member private this.FileType : uint32 = + if this._isDll then + VersionResourceSerializer.VFT_DLL + else + VersionResourceSerializer.VFT_APP + + member private this.WriteVSFixedFileInfo(writer: BinaryWriter) = + let mutable (fileVersion: Version) = Unchecked.defaultof + VersionHelper.TryParse (this._fileVersionContents, ref fileVersion) |> ignore + let mutable (productVersion: Version) = Unchecked.defaultof + VersionHelper.TryParse (this._productVersionContents, ref productVersion) |> ignore + writer.Write (0xFEEF04BDu) + writer.Write (0x00010000u) + writer.Write ((uint32 fileVersion.Major <<< 16) ||| uint32 fileVersion.Minor) + writer.Write ((uint32 fileVersion.Build <<< 16) ||| uint32 fileVersion.Revision) + writer.Write ((uint32 productVersion.Major <<< 16) ||| uint32 productVersion.Minor) + writer.Write ((uint32 productVersion.Build <<< 16) ||| uint32 productVersion.Revision) + writer.Write (0x0000003Fu) + writer.Write 0u + writer.Write (0x00000004u) + writer.Write (this.FileType) + writer.Write 0u + writer.Write 0u + writer.Write 0u + + static member private PadKeyLen(cb: int) = + VersionResourceSerializer.PadToDword (cb + 3 * sizeof) - 3 * sizeof + + static member private PadToDword(cb: int) = + cb + 3 &&& ~~~3 + + static member val private HDRSIZE = (int (3 * sizeof)) with get, set + + static member private SizeofVerString(lpszKey: string, lpszValue: string) = + let mutable (cbKey: int) = Unchecked.defaultof + let mutable (cbValue: int) = Unchecked.defaultof + cbKey <- lpszKey.Length + 1 * 2 + cbValue <- lpszValue.Length + 1 * 2 + VersionResourceSerializer.PadKeyLen(cbKey) + cbValue + VersionResourceSerializer.HDRSIZE + + static member private WriteVersionString(keyValuePair: KeyValuePair, writer: BinaryWriter) = + Debug.Assert (keyValuePair.Value <> Unchecked.defaultof<_>) + let mutable (cbBlock: uint16) = uint16 <| VersionResourceSerializer.SizeofVerString (keyValuePair.Key, keyValuePair.Value) + let mutable (cbKey: int) = keyValuePair.Key.Length + 1 * 2 + //let mutable (cbVal: int) = keyValuePair.Value.Length + 1 * 2 + let mutable startPos = writer.BaseStream.Position + Debug.Assert (startPos &&& 3L = 0L) + writer.Write (cbBlock) + writer.Write (uint16 (keyValuePair.Value.Length + 1)) + writer.Write (1us) + writer.Write (keyValuePair.Key.ToCharArray ()) + writer.Write (uint16 0) //(WORD)'\0' + writer.Write (Array.zeroCreate (VersionResourceSerializer.PadKeyLen (cbKey) - cbKey): byte[]) + Debug.Assert (writer.BaseStream.Position &&& 3L = 0L) + writer.Write (keyValuePair.Value.ToCharArray ()) + writer.Write (uint16 0) // (WORD)'\0' + Debug.Assert (int64 cbBlock = writer.BaseStream.Position - startPos) + + static member private KEYSIZE(sz: string) = + VersionResourceSerializer.PadKeyLen (sz.Length + 1 * sizeof) / sizeof + + static member private KEYBYTES(sz: string) = + VersionResourceSerializer.KEYSIZE (sz) * sizeof + + member private this.GetStringsSize() = + let mutable (sum: int) = 0 + for verString in this.GetVerStrings () do + sum <- sum + 3 &&& ~~~3 + sum <- sum + VersionResourceSerializer.SizeofVerString (verString.Key, verString.Value) + sum + + member this.GetDataSize () = + let mutable (sizeEXEVERRESOURCE: int) = + sizeof * 3 * 5 + 2 * sizeof + + VersionResourceSerializer.KEYBYTES (VersionResourceSerializer.vsVersionInfoKey) + + VersionResourceSerializer.KEYBYTES (VersionResourceSerializer.varFileInfoKey) + + VersionResourceSerializer.KEYBYTES (VersionResourceSerializer.translationKey) + + VersionResourceSerializer.KEYBYTES (VersionResourceSerializer.stringFileInfoKey) + + VersionResourceSerializer.KEYBYTES (this._langIdAndCodePageKey) + + int VersionResourceSerializer.sizeVS_FIXEDFILEINFO + this.GetStringsSize () + sizeEXEVERRESOURCE + + member this.WriteVerResource (writer: BinaryWriter) = + let mutable debugPos = writer.BaseStream.Position + let mutable dataSize = this.GetDataSize () + writer.Write (WORD dataSize) + writer.Write (WORD VersionResourceSerializer.sizeVS_FIXEDFILEINFO) + writer.Write (WORD 0us) + writer.Write (VersionResourceSerializer.vsVersionInfoKey.ToCharArray ()) + writer.Write (Array.zeroCreate (VersionResourceSerializer.KEYBYTES (VersionResourceSerializer.vsVersionInfoKey) - VersionResourceSerializer.vsVersionInfoKey.Length * 2): byte[]) + Debug.Assert (writer.BaseStream.Position &&& 3L = 0L) + this.WriteVSFixedFileInfo (writer) + writer.Write (WORD (sizeof * 2 + + 2 * VersionResourceSerializer.HDRSIZE + + VersionResourceSerializer.KEYBYTES (VersionResourceSerializer.varFileInfoKey) + + VersionResourceSerializer.KEYBYTES (VersionResourceSerializer.translationKey))) + writer.Write (WORD 0us) + writer.Write (WORD 1us) + writer.Write (VersionResourceSerializer.varFileInfoKey.ToCharArray ()) + writer.Write (Array.zeroCreate (VersionResourceSerializer.KEYBYTES (VersionResourceSerializer.varFileInfoKey) - VersionResourceSerializer.varFileInfoKey.Length * 2): byte[]) + Debug.Assert (writer.BaseStream.Position &&& 3L = 0L) + writer.Write (WORD (sizeof * 2 + VersionResourceSerializer.HDRSIZE + VersionResourceSerializer.KEYBYTES (VersionResourceSerializer.translationKey))) + writer.Write (WORD (sizeof * 2)) + writer.Write (WORD 0us) + writer.Write (VersionResourceSerializer.translationKey.ToCharArray ()) + writer.Write (Array.zeroCreate (VersionResourceSerializer.KEYBYTES (VersionResourceSerializer.translationKey) - VersionResourceSerializer.translationKey.Length * 2): byte[]) + Debug.Assert (writer.BaseStream.Position &&& 3L = 0L) + writer.Write (0us) + writer.Write (WORD VersionResourceSerializer.CP_WINUNICODE) + Debug.Assert (writer.BaseStream.Position &&& 3L = 0L) + writer.Write (WORD (2 * VersionResourceSerializer.HDRSIZE + + VersionResourceSerializer.KEYBYTES (VersionResourceSerializer.stringFileInfoKey) + + VersionResourceSerializer.KEYBYTES (this._langIdAndCodePageKey) + this.GetStringsSize ())) + writer.Write (0us) + writer.Write (1us) + writer.Write (VersionResourceSerializer.stringFileInfoKey.ToCharArray ()) + writer.Write (Array.zeroCreate (VersionResourceSerializer.KEYBYTES (VersionResourceSerializer.stringFileInfoKey) - VersionResourceSerializer.stringFileInfoKey.Length * 2): byte[]) + Debug.Assert (writer.BaseStream.Position &&& 3L = 0L) + writer.Write (WORD (VersionResourceSerializer.HDRSIZE + VersionResourceSerializer.KEYBYTES (this._langIdAndCodePageKey) + this.GetStringsSize ())) + writer.Write (0us) + writer.Write (1us) + writer.Write (this._langIdAndCodePageKey.ToCharArray ()) + writer.Write (Array.zeroCreate (VersionResourceSerializer.KEYBYTES (this._langIdAndCodePageKey) - this._langIdAndCodePageKey.Length * 2): byte[]) + Debug.Assert (writer.BaseStream.Position &&& 3L = 0L) + Debug.Assert (writer.BaseStream.Position - debugPos = int64 dataSize - int64 (this.GetStringsSize ())) + debugPos <- writer.BaseStream.Position + for entry in this.GetVerStrings () do + let mutable writerPos = writer.BaseStream.Position + writer.Write (Array.zeroCreate (int ((writerPos + 3L) &&& ~~~3L - writerPos)): byte[]) + Debug.Assert (entry.Value <> Unchecked.defaultof<_>) + VersionResourceSerializer.WriteVersionString (entry, writer) + Debug.Assert (writer.BaseStream.Position - debugPos = int64 (this.GetStringsSize ())) + +type Win32ResourceConversions () = + static member AppendIconToResourceStream(resStream: Stream, iconStream: Stream) = + let mutable iconReader = new BinaryReader(iconStream) + let mutable reserved = iconReader.ReadUInt16 () + if reserved <> 0us then + raise <| ResourceException("IconStreamUnexpectedFormat") + let mutable ``type`` = iconReader.ReadUInt16 () + if ``type`` <> 1us then + raise <| ResourceException("IconStreamUnexpectedFormat") + let mutable count = iconReader.ReadUInt16 () + if count = 0us then + raise <| ResourceException("IconStreamUnexpectedFormat") + let mutable iconDirEntries: ICONDIRENTRY [] = Array.zeroCreate (int count) + do + let mutable (i: uint16) = 0us + while (i < count) do + iconDirEntries.[(int i)].bWidth <- iconReader.ReadByte () + iconDirEntries.[(int i)].bHeight <- iconReader.ReadByte () + iconDirEntries.[(int i)].bColorCount <- iconReader.ReadByte () + iconDirEntries.[(int i)].bReserved <- iconReader.ReadByte () + iconDirEntries.[(int i)].wPlanes <- iconReader.ReadUInt16 () + iconDirEntries.[(int i)].wBitCount <- iconReader.ReadUInt16 () + iconDirEntries.[(int i)].dwBytesInRes <- iconReader.ReadUInt32 () + iconDirEntries.[(int i)].dwImageOffset <- iconReader.ReadUInt32 () + i <- i + 1us + do + let mutable (i: uint16) = 0us + while (i < count) do + iconStream.Position <- int64 iconDirEntries.[(int i)].dwImageOffset + if iconReader.ReadUInt32 () = 40u then + iconStream.Position <- iconStream.Position + 8L + iconDirEntries.[(int i)].wPlanes <- iconReader.ReadUInt16 () + iconDirEntries.[(int i)].wBitCount <- iconReader.ReadUInt16 () + i <- i + 1us + + let mutable resWriter = new BinaryWriter(resStream) + let mutable (RT_ICON: WORD) = 3us + do + let mutable (i: uint16) = 0us + while (i < count) do + resStream.Position <- resStream.Position + 3L &&& ~~~3L + resWriter.Write (iconDirEntries.[(int i)].dwBytesInRes) + resWriter.Write (0x00000020u) + resWriter.Write (0xFFFFus) + resWriter.Write (RT_ICON) + resWriter.Write (0xFFFFus) + resWriter.Write ((i + 1us)) + resWriter.Write (0x00000000u) + resWriter.Write (0x1010us) + resWriter.Write (0x0000us) + resWriter.Write (0x00000000u) + resWriter.Write (0x00000000u) + iconStream.Position <- int64 iconDirEntries.[(int i)].dwImageOffset + resWriter.Write (iconReader.ReadBytes (int (iconDirEntries.[int i].dwBytesInRes))) + i <- i + 1us + + let mutable (RT_GROUP_ICON: WORD) = (RT_ICON + 11us) + resStream.Position <- resStream.Position + 3L &&& ~~~3L + resWriter.Write (uint32 (3 * sizeof + int count * 14)) + resWriter.Write (0x00000020u) + resWriter.Write (0xFFFFus) + resWriter.Write (RT_GROUP_ICON) + resWriter.Write (0xFFFFus) + resWriter.Write (0x7F00us) + resWriter.Write (0x00000000u) + resWriter.Write (0x1030us) + resWriter.Write (0x0000us) + resWriter.Write (0x00000000u) + resWriter.Write (0x00000000u) + resWriter.Write (0x0000us) + resWriter.Write (0x0001us) + resWriter.Write (count) + do + let mutable (i: uint16) = 0us + while (i < count) do + resWriter.Write (iconDirEntries.[(int i)].bWidth) + resWriter.Write (iconDirEntries.[(int i)].bHeight) + resWriter.Write (iconDirEntries.[(int i)].bColorCount) + resWriter.Write (iconDirEntries.[(int i)].bReserved) + resWriter.Write (iconDirEntries.[(int i)].wPlanes) + resWriter.Write (iconDirEntries.[(int i)].wBitCount) + resWriter.Write (iconDirEntries.[(int i)].dwBytesInRes) + resWriter.Write ((i + 1us)) + i <- i + 1us + () + + static member AppendVersionToResourceStream (resStream: Stream, + isDll: bool, + fileVersion: string, + originalFileName: string, + internalName: string, + productVersion: string, + assemblyVersion: Version, + ?fileDescription: string, + ?legalCopyright: string, + ?legalTrademarks: string, + ?productName: string, + ?comments: string, + ?companyName: string) = + let fileDescription = (defaultArg fileDescription) " " + let legalCopyright = (defaultArg legalCopyright) " " + let legalTrademarks = (defaultArg legalTrademarks) Unchecked.defaultof<_> + let productName = (defaultArg productName) Unchecked.defaultof<_> + let comments = (defaultArg comments) Unchecked.defaultof<_> + let companyName = (defaultArg companyName) Unchecked.defaultof<_> + let mutable resWriter = new BinaryWriter(resStream, Encoding.Unicode) + resStream.Position <- resStream.Position + 3L &&& ~~~3L + let mutable (RT_VERSION: DWORD) = 16u + let mutable ver = + new VersionResourceSerializer(isDll, comments, companyName, + fileDescription, fileVersion, internalName, legalCopyright, + legalTrademarks, originalFileName, productName, productVersion, + assemblyVersion) + let mutable startPos = resStream.Position + let mutable dataSize = ver.GetDataSize () + let mutable (headerSize: int) = 0x20 + resWriter.Write (uint32 dataSize) + resWriter.Write (uint32 headerSize) + resWriter.Write (0xFFFFus) + resWriter.Write (uint16 RT_VERSION) + resWriter.Write (0xFFFFus) + resWriter.Write (0x0001us) + resWriter.Write (0x00000000u) + resWriter.Write (0x0030us) + resWriter.Write (0x0000us) + resWriter.Write (0x00000000u) + resWriter.Write (0x00000000u) + ver.WriteVerResource (resWriter) + Debug.Assert (resStream.Position - startPos = int64 dataSize + int64 headerSize) + + static member AppendManifestToResourceStream(resStream: Stream, manifestStream: Stream, isDll: bool) = + resStream.Position <- resStream.Position + 3L &&& ~~~3L (* ERROR UnknownPrefixOperator "~" *) + let mutable (RT_MANIFEST: WORD) = 24us + let mutable resWriter = new BinaryWriter(resStream) + resWriter.Write (uint32 manifestStream.Length) + resWriter.Write (0x00000020u) + resWriter.Write (0xFFFFus) + resWriter.Write (RT_MANIFEST) + resWriter.Write (0xFFFFus) + resWriter.Write (if isDll then 0x0002us else 0x0001us) + resWriter.Write (0x00000000u) + resWriter.Write (0x1030us) + resWriter.Write (0x0000us) + resWriter.Write (0x00000000u) + resWriter.Write (0x00000000u) + manifestStream.CopyTo (resStream) + + +type Win32Resource (data: byte[], codePage: DWORD, languageId: DWORD, id: int, name: string, typeId: int, typeName: string) = + member val Data = data + member val CodePage = codePage + member val LanguageId = languageId + member val Id = id + member val Name = name + member val TypeId = typeId + member val TypeName = typeName + +type Directory (name, id) = + member val Name = name + member val ID = id + member val NumberOfNamedEntries = Unchecked.defaultof with get, set + member val NumberOfIdEntries = Unchecked.defaultof with get, set + member val Entries = new List() + +type NativeResourceWriter () = + static member private CompareResources (left: Win32Resource) (right: Win32Resource) = + let mutable (result: int) = NativeResourceWriter.CompareResourceIdentifiers (left.TypeId, left.TypeName, right.TypeId, right.TypeName) + if result = 0 then + NativeResourceWriter.CompareResourceIdentifiers (left.Id, left.Name, right.Id, right.Name) + else result + + static member private CompareResourceIdentifiers (xOrdinal: int, xString: string, yOrdinal: int, yString: string) = + if xString = Unchecked.defaultof<_> then + if yString = Unchecked.defaultof<_> then + xOrdinal - yOrdinal + else + 1 + else + if yString = Unchecked.defaultof<_> then + -1 + else + String.Compare (xString, yString, StringComparison.OrdinalIgnoreCase) + + static member SortResources (resources: IEnumerable) = + resources.OrderBy ((fun d -> d), Comparer<_>.Create(Comparison<_> NativeResourceWriter.CompareResources)) :> IEnumerable + + static member SerializeWin32Resources (builder: BlobBuilder, theResources: IEnumerable, resourcesRva: int) = + let theResources = NativeResourceWriter.SortResources (theResources) + let mutable (typeDirectory: Directory) = new Directory(String.Empty, 0) + let mutable (nameDirectory: Directory) = Unchecked.defaultof<_> + let mutable (languageDirectory: Directory) = Unchecked.defaultof<_> + let mutable (lastTypeID: int) = Int32.MinValue + let mutable (lastTypeName: string) = Unchecked.defaultof<_> + let mutable (lastID: int) = Int32.MinValue + let mutable (lastName: string) = Unchecked.defaultof<_> + let mutable (sizeOfDirectoryTree: uint32) = 16u + for (r: Win32Resource) in theResources do + let mutable (typeDifferent: bool) = r.TypeId < 0 && r.TypeName <> lastTypeName || r.TypeId > lastTypeID + if typeDifferent then + lastTypeID <- r.TypeId + lastTypeName <- r.TypeName + if lastTypeID < 0 then + Debug.Assert ((typeDirectory.NumberOfIdEntries = 0us), "Not all Win32 resources with types encoded as strings precede those encoded as ints") + typeDirectory.NumberOfNamedEntries <- typeDirectory.NumberOfNamedEntries + 1us + else + typeDirectory.NumberOfIdEntries <- typeDirectory.NumberOfIdEntries + 1us + sizeOfDirectoryTree <- sizeOfDirectoryTree + 24u + nameDirectory <- new Directory(lastTypeName, lastTypeID) + typeDirectory.Entries.Add (nameDirectory) + if typeDifferent || r.Id < 0 && r.Name <> lastName || r.Id > lastID then + lastID <- r.Id + lastName <- r.Name + if lastID < 0 then + Debug.Assert ((nameDirectory.NumberOfIdEntries = 0us), "Not all Win32 resources with names encoded as strings precede those encoded as ints") + nameDirectory.NumberOfNamedEntries <- nameDirectory.NumberOfNamedEntries + 1us + else + nameDirectory.NumberOfIdEntries <- nameDirectory.NumberOfIdEntries + 1us + sizeOfDirectoryTree <- sizeOfDirectoryTree + 24u + languageDirectory <- new Directory (lastName, lastID) + nameDirectory.Entries.Add (languageDirectory) + languageDirectory.NumberOfIdEntries <- languageDirectory.NumberOfIdEntries + 1us + sizeOfDirectoryTree <- sizeOfDirectoryTree + 8u + languageDirectory.Entries.Add (r) + let mutable dataWriter = new BlobBuilder() + NativeResourceWriter.WriteDirectory (typeDirectory, builder, 0u, 0u, sizeOfDirectoryTree, resourcesRva, dataWriter) + builder.LinkSuffix dataWriter + builder.WriteByte 0uy + builder.Align 4 + + static member private WriteDirectory (directory: Directory, writer: BlobBuilder, offset: uint32, + level: uint32, sizeOfDirectoryTree: uint32, + virtualAddressBase: int, dataWriter: BlobBuilder) = + writer.WriteUInt32 0u + writer.WriteUInt32 0u + writer.WriteUInt32 0u + writer.WriteUInt16 directory.NumberOfNamedEntries + writer.WriteUInt16 directory.NumberOfIdEntries + let mutable (n: uint32) = uint32 directory.Entries.Count + let mutable (k: uint32) = offset + 16u + n * 8u + do + let mutable (i: uint32) = 0u + while (i < n) do + let mutable (id: int) = Unchecked.defaultof + let mutable (name: string) = Unchecked.defaultof + let mutable (nameOffset: uint32) = uint32 dataWriter.Count + sizeOfDirectoryTree + let mutable (directoryOffset: uint32) = k + let isDir = + match directory.Entries.[int i] with + | :? Directory as subDir -> + id <- subDir.ID + name <- subDir.Name + if level = 0u then k <- k + NativeResourceWriter.SizeOfDirectory (subDir) + else k <- k + 16u + 8u * uint32 subDir.Entries.Count + true + | :? Win32Resource as r -> + id <- + if level = 0u then + r.TypeId + else + if level = 1u then + r.Id + else + int r.LanguageId + name <- + if level = 0u then + r.TypeName + else + if level = 1u then + r.Name + else + Unchecked.defaultof<_> + dataWriter.WriteUInt32 ((uint32 virtualAddressBase + sizeOfDirectoryTree + 16u + uint32 dataWriter.Count)) + let mutable (data: byte[]) = (new List (r.Data)).ToArray () + dataWriter.WriteUInt32 (uint32 data.Length) + dataWriter.WriteUInt32 (r.CodePage) + dataWriter.WriteUInt32 0u + dataWriter.WriteBytes (data) + while (dataWriter.Count % 4 <> 0) do + dataWriter.WriteByte (0uy) + false + | e -> failwithf "Unknown entry %s" (if isNull e then "" else e.GetType().FullName) + if id >= 0 then writer.WriteInt32 (id) + else + if name = Unchecked.defaultof<_> then + name <- String.Empty + writer.WriteUInt32 (nameOffset ||| 0x80000000u) + dataWriter.WriteUInt16 (uint16 name.Length) + dataWriter.WriteUTF16 (name) + if isDir then writer.WriteUInt32 (directoryOffset ||| 0x80000000u) + else writer.WriteUInt32 (nameOffset) + i <- i + 1u + + k <- offset + 16u + n * 8u + do + let mutable (i: int) = 0 + while (uint32 i < n) do + match directory.Entries.[i] with + | :? Directory as subDir -> + NativeResourceWriter.WriteDirectory (subDir, writer, k, (level + 1u), sizeOfDirectoryTree, virtualAddressBase, dataWriter) + if level = 0u then + k <- k + NativeResourceWriter.SizeOfDirectory (subDir) + else + k <- k + 16u + 8u * uint32 subDir.Entries.Count + | _ -> () + i <- i + 1 + () + + static member private SizeOfDirectory (directory: Directory) = + let mutable (n: uint32) = uint32 directory.Entries.Count + let mutable (size: uint32) = 16u + 8u * n + do + let mutable (i: int) = 0 + while (uint32 i < n) do + match directory.Entries.[i] with + | :? Directory as subDir -> + size <- size + 16u + 8u * uint32 subDir.Entries.Count + | _ -> () + i <- i + 1 + size + + (* + static member SerializeWin32Resources (builder: BlobBuilder, resourceSections: ResourceSection, resourcesRva: int) = + let mutable sectionWriter = new BlobWriter (builder.ReserveBytes (resourceSections.SectionBytes.Length)) + sectionWriter.WriteBytes (resourceSections.SectionBytes) + let mutable readStream = new MemoryStream (resourceSections.SectionBytes) + let mutable reader = new BinaryReader (readStream) + for (addressToFixup: int) in resourceSections.Relocations do + sectionWriter.Offset <- addressToFixup + reader.BaseStream.Position <- addressToFixup + sectionWriter.WriteUInt32 (reader.ReadUInt32 () + resourcesRva :> uint32) + ()*) \ No newline at end of file diff --git a/src/fcs-fable/src/absil/ilnativeres.fsi b/src/fcs-fable/src/absil/ilnativeres.fsi new file mode 100644 index 0000000000..c958240085 --- /dev/null +++ b/src/fcs-fable/src/absil/ilnativeres.fsi @@ -0,0 +1,62 @@ + +module internal FSharp.Compiler.AbstractIL.Internal.NativeRes + +open System +open System.Collections.Generic +open System.Linq +open System.Diagnostics +open System.IO +open System.Reflection.Metadata + +type BYTE = System.Byte +type DWORD = System.UInt32 +type WCHAR = System.Char +type WORD = System.UInt16 + +[] +type RESOURCE_STRING = + member Ordinal: WORD with get, set + member theString : string with get, set + +[] +type RESOURCE = + member pstringType : RESOURCE_STRING with get, set + member pstringName : RESOURCE_STRING with get, set + member DataSize : DWORD with get, set + member HeaderSize : DWORD with get, set + member DataVersion : DWORD with get, set + member MemoryFlags : WORD with get, set + member LanguageId : WORD with get, set + member Version : DWORD with get, set + member Characteristics : DWORD with get, set + member data : byte[] with get, set + +type Win32Resource = + new : data:byte [] * codePage: DWORD * languageId: DWORD * id: int * + name: string * typeId:int * typeName : string -> Win32Resource + member CodePage: DWORD + member Data: byte [] + member Id: int + member LanguageId : DWORD + member Name: string + member TypeId: int + member TypeName: string + +[] +type CvtResFile = + static member ReadResFile : stream:Stream -> System.Collections.Generic.List + +[] +type Win32ResourceConversions = + static member AppendIconToResourceStream : resStream:Stream * iconStream:Stream -> unit + static member AppendVersionToResourceStream : resStream:Stream * isDll:System.Boolean * fileVersion:string * originalFileName:string * internalName:string * productVersion:string * assemblyVersion:Version * ?fileDescription:string * ?legalCopyright:string * ?legalTrademarks:string * ?productName:string * ?comments:string * ?companyName:string -> unit + static member AppendManifestToResourceStream : resStream:Stream * manifestStream:Stream * isDll:System.Boolean -> unit + +// Write native resources +[] +type NativeResourceWriter = + static member SortResources: resources: IEnumerable -> IEnumerable + static member SerializeWin32Resources: builder:BlobBuilder * theResources: IEnumerable * resourcesRva: int -> unit + (* + static member SerializeWin32Resources (builder : BlobBuilder, resourceSections : ResourceSection, resourcesRva : int) -> unit + ()*) \ No newline at end of file diff --git a/src/fcs-fable/src/absil/ilpars.fsy b/src/fcs-fable/src/absil/ilpars.fsy old mode 100755 new mode 100644 index b685201546..e831677e50 --- a/src/fcs-fable/src/absil/ilpars.fsy +++ b/src/fcs-fable/src/absil/ilpars.fsy @@ -20,21 +20,6 @@ let pfailwith s = stderr.WriteLine ("*** error: "+s); raise Parsing.RecoverableParseError -/// vararg sentinels -type SigArg = SigArg of (string option * ILType) | Sentinel - -let decodeVarargs args = - let rec normals = function - | [] -> ([],None) - | Sentinel :: t -> ([],Some (varargs t)) - | SigArg (_,p)::t -> let (n,r) = normals t in (p::n, r) - and varargs = function - | [] -> [] - | SigArg (_,ty):: t -> let l = varargs t in ty::l - | Sentinel :: t -> pfailwith "two sentinels in vararg call" - normals args - - type ResolvedAtMethodSpecScope<'T> = ResolvedAtMethodSpecScope of (ILGenericParameterDefs -> 'T) @@ -43,17 +28,12 @@ let resolveMethodSpecScope (ResolvedAtMethodSpecScope f) x = f x let resolveMethodSpecScopeThen (ResolvedAtMethodSpecScope f) g = ResolvedAtMethodSpecScope (fun x -> resolveMethodSpecScope (g(f x)) x) -let resolveFormalMethodSpecScope tspeco obj = - match tspeco with - None -> resolveMethodSpecScope obj mkILEmptyGenericParams - | Some (tspec:ILTypeSpec) -> resolveMethodSpecScope obj (mkILFormalTypars tspec.GenericArgs) - let resolveCurrentMethodSpecScope obj = resolveMethodSpecScope obj mkILEmptyGenericParams let findSystemRuntimeAssemblyRef() = - match (!parseILGlobals).primaryAssemblyScopeRef with + match parseILGlobals.primaryAssemblyScopeRef with | ILScopeRef.Assembly aref -> aref | _ -> pfailwith "systemRuntimeScopeRef not set to valid assembly reference in parseILGlobals" @@ -75,7 +55,6 @@ let findAssemblyRef nm = %token INSTR_I32_I32 %token INSTR_I8 %token INSTR_R -%token INSTR_METHOD %token INSTR_NONE %token INSTR_STRING %token INSTR_TOK @@ -163,18 +142,6 @@ instrs2: { $1 :: $2 } | { [] } - - -methodSpecMaybeArrayMethod: - callConv typ typSpec DCOLON methodName opt_actual_tyargs LPAREN sigArgs0 RPAREN - { let callee_class_typ : ILType = resolveCurrentMethodSpecScope $3 - let gscope = (if isILArrTy callee_class_typ then None else Some callee_class_typ.TypeSpec) - let argtys_n_varargs = resolveFormalMethodSpecScope gscope $8 - let (argtys,varargs) = decodeVarargs argtys_n_varargs - let minst = resolveCurrentMethodSpecScope $6 - let callee_retty = resolveFormalMethodSpecScope gscope $2 - (callee_class_typ, $1, $5, argtys, callee_retty, minst), varargs } - instr: INSTR_NONE { ($1 ()) } @@ -188,19 +155,6 @@ instr: { ($1 (ILConst.R8 $2)) } | INSTR_R int64 { ($1 (ILConst.R8 (float $2))) } - | INSTR_METHOD methodSpecMaybeArrayMethod - { - let ((encl_typ, _cc, nm, _argtys, _retty, _minst) as data),varargs = $2 - if isILArrTy encl_typ then - let (shape,ty) = destILArrTy encl_typ - match nm with - | "Get" -> I_ldelem_any(shape,ty) - | "Set" -> I_stelem_any(shape,ty) - | "Address" -> I_ldelema(NormalAddress,false,shape,ty) - | ".ctor" -> I_newarr(shape,ty) - | _ -> failwith "bad method on array type" - else - $1 (mkILMethSpecInTy data, varargs) } | INSTR_TYPE typSpec { $1 (resolveCurrentMethodSpecScope $2) } | INSTR_INT_TYPE int32 typSpec @@ -209,34 +163,6 @@ instr: { $1 (resolveCurrentMethodSpecScope $2) } | INSTR_TOK typSpec { ($1 (ILToken.ILType (resolveCurrentMethodSpecScope $2))) } - -/*----------------------------------------------- - * Formal signatures of methods etc. - *---------------------------------------------*/ - -sigArgs0: - { noMethodSpecScope [] } - | sigArgs1 { $1 } - -sigArgs1: - sigArgs1a - { ResolvedAtMethodSpecScope (fun c -> List.map (fun obj -> resolveMethodSpecScope obj c) (List.rev $1)) } - -sigArgs1a: - sigArg - { [$1] } - | sigArgs1a COMMA sigArg - { $3:: $1 } - -sigArg: - | typ opt_id - { resolveMethodSpecScopeThen $1 (fun ty -> - noMethodSpecScope (SigArg($2, ty))) } - - - -opt_id: { None } | id { Some $1 } - /*----------------------------------------------- * Type names @@ -261,7 +187,7 @@ slashedName: name1 { ([],$1) } | name1 SLASH slashedName - { let (enc,nm) = $3 in ($1::enc, nm) } + { let (enc,nm) = $3 in ($1 :: enc, nm) } typeNameInst: className opt_actual_tyargs @@ -309,9 +235,9 @@ callKind: *---------------------------------------------*/ typ: STRING - { noMethodSpecScope (!parseILGlobals).typ_String } + { noMethodSpecScope parseILGlobals.typ_String } | OBJECT - { noMethodSpecScope (!parseILGlobals).typ_Object } + { noMethodSpecScope parseILGlobals.typ_Object } | CLASS typeNameInst { resolveMethodSpecScopeThen $2 (fun tspec -> noMethodSpecScope (mkILBoxedType tspec)) } @@ -330,45 +256,45 @@ typ: STRING | typ STAR { resolveMethodSpecScopeThen $1 (fun ty -> noMethodSpecScope (ILType.Ptr ty)) } | CHAR - { noMethodSpecScope (!parseILGlobals).typ_Char } + { noMethodSpecScope parseILGlobals.typ_Char } | VOID { noMethodSpecScope ILType.Void } | BOOL - { noMethodSpecScope (!parseILGlobals).typ_Bool } + { noMethodSpecScope parseILGlobals.typ_Bool } | INT8 - { noMethodSpecScope (!parseILGlobals).typ_SByte } + { noMethodSpecScope parseILGlobals.typ_SByte } | INT16 - { noMethodSpecScope (!parseILGlobals).typ_Int16 } + { noMethodSpecScope parseILGlobals.typ_Int16 } | INT32 - { noMethodSpecScope (!parseILGlobals).typ_Int32 } + { noMethodSpecScope parseILGlobals.typ_Int32 } | INT64 - { noMethodSpecScope (!parseILGlobals).typ_Int64 } + { noMethodSpecScope parseILGlobals.typ_Int64 } | FLOAT32 - { noMethodSpecScope (!parseILGlobals).typ_Single } + { noMethodSpecScope parseILGlobals.typ_Single } | FLOAT64 - { noMethodSpecScope (!parseILGlobals).typ_Double } + { noMethodSpecScope parseILGlobals.typ_Double } | UNSIGNED INT8 - { noMethodSpecScope (!parseILGlobals).typ_Byte } + { noMethodSpecScope parseILGlobals.typ_Byte } | UNSIGNED INT16 - { noMethodSpecScope (!parseILGlobals).typ_UInt16 } + { noMethodSpecScope parseILGlobals.typ_UInt16 } | UNSIGNED INT32 - { noMethodSpecScope (!parseILGlobals).typ_UInt32 } + { noMethodSpecScope parseILGlobals.typ_UInt32 } | UNSIGNED INT64 - { noMethodSpecScope (!parseILGlobals).typ_UInt64 } + { noMethodSpecScope parseILGlobals.typ_UInt64 } | UINT8 - { noMethodSpecScope (!parseILGlobals).typ_Byte } + { noMethodSpecScope parseILGlobals.typ_Byte } | UINT16 - { noMethodSpecScope (!parseILGlobals).typ_UInt16 } + { noMethodSpecScope parseILGlobals.typ_UInt16 } | UINT32 - { noMethodSpecScope (!parseILGlobals).typ_UInt32 } + { noMethodSpecScope parseILGlobals.typ_UInt32 } | UINT64 - { noMethodSpecScope (!parseILGlobals).typ_UInt64 } + { noMethodSpecScope parseILGlobals.typ_UInt64 } | NATIVE INT - { noMethodSpecScope (!parseILGlobals).typ_IntPtr } + { noMethodSpecScope parseILGlobals.typ_IntPtr } | NATIVE UNSIGNED INT - { noMethodSpecScope (!parseILGlobals).typ_UIntPtr } + { noMethodSpecScope parseILGlobals.typ_UIntPtr } | NATIVE UINT - { noMethodSpecScope (!parseILGlobals).typ_UIntPtr } + { noMethodSpecScope parseILGlobals.typ_UIntPtr } | BANG int32 { noMethodSpecScope (ILType.TypeVar (uint16 ( $2))) } diff --git a/src/fcs-fable/src/absil/ilprint.fs b/src/fcs-fable/src/absil/ilprint.fs old mode 100755 new mode 100644 index 5614522f02..42c0dcddd6 --- a/src/fcs-fable/src/absil/ilprint.fs +++ b/src/fcs-fable/src/absil/ilprint.fs @@ -1,40 +1,36 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -module internal FSharp.Compiler.AbstractIL.ILAsciiWriter +module internal FSharp.Compiler.AbstractIL.ILAsciiWriter -open Internal.Utilities -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.Internal +open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.AbstractIL.Diagnostics -open FSharp.Compiler.AbstractIL.Extensions.ILX.Types -open FSharp.Compiler.AbstractIL.Internal.AsciiConstants -open FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler.AbstractIL.Extensions.ILX.Types +open FSharp.Compiler.AbstractIL.Internal.AsciiConstants +open FSharp.Compiler.AbstractIL.IL -open System.Text open System.IO open System.Reflection #if DEBUG let pretty () = true -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Pretty printing // -------------------------------------------------------------------- -let tyvar_generator = - let i = ref 0 - fun n -> +let tyvar_generator = + let i = ref 0 + fun n -> incr i; n + string !i -// Carry an environment because the way we print method variables -// depends on the gparams of the current scope. -type ppenv = +// Carry an environment because the way we print method variables +// depends on the gparams of the current scope. +type ppenv = { ilGlobals: ILGlobals ppenvClassFormals: int ppenvMethodFormals: int } -let ppenv_enter_method mgparams env = +let ppenv_enter_method mgparams env = {env with ppenvMethodFormals=mgparams} let ppenv_enter_tdef gparams env = @@ -42,40 +38,40 @@ let ppenv_enter_tdef gparams env = let mk_ppenv ilg = { ilGlobals = ilg; ppenvClassFormals = 0; ppenvMethodFormals = 0 } -let debug_ppenv = mk_ppenv +let debug_ppenv = mk_ppenv let ppenv_enter_modul env = { env with ppenvClassFormals=0; ppenvMethodFormals=0 } -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Pretty printing - output streams -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -let output_string (os: TextWriter) (s:string) = os.Write s +let output_string (os: TextWriter) (s:string) = os.Write s let output_char (os: TextWriter) (c:char) = os.Write c let output_int os (i:int) = output_string os (string i) -let output_hex_digit os i = +let output_hex_digit os i = assert (i >= 0 && i < 16) - if i > 9 then output_char os (char (int32 'A' + (i-10))) + if i > 9 then output_char os (char (int32 'A' + (i-10))) else output_char os (char (int32 '0' + i)) let output_qstring os s = output_char os '"' for i = 0 to String.length s - 1 do let c = String.get s i - if (c >= '\000' && c <= '\031') || (c >= '\127' && c <= '\255') then + if (c >= '\000' && c <= '\031') || (c >= '\127' && c <= '\255') then let c' = int32 c output_char os '\\' output_int os (c'/64) output_int os ((c' % 64) / 8) - output_int os (c' % 8) - else if (c = '"') then + output_int os (c' % 8) + else if (c = '"') then output_char os '\\'; output_char os '"' - else if (c = '\\') then + else if (c = '\\') then output_char os '\\'; output_char os '\\' - else + else output_char os c done output_char os '"' @@ -83,24 +79,24 @@ let output_sqstring os s = output_char os '\'' for i = 0 to String.length s - 1 do let c = s.[i] - if (c >= '\000' && c <= '\031') || (c >= '\127' && c <= '\255') then + if (c >= '\000' && c <= '\031') || (c >= '\127' && c <= '\255') then let c' = int32 c output_char os '\\' output_int os (c'/64) output_int os ((c' % 64) / 8) - output_int os (c' % 8) - else if (c = '\\') then + output_int os (c' % 8) + else if (c = '\\') then output_char os '\\'; output_char os '\\' - else if (c = '\'') then + else if (c = '\'') then output_char os '\\'; output_char os '\'' - else + else output_char os c done output_char os '\'' let output_seq sep f os (a:seq<_>) = use e = a.GetEnumerator() - if e.MoveNext() then + if e.MoveNext() then f os e.Current while e.MoveNext() do output_string os sep @@ -125,19 +121,19 @@ let output_label os n = output_string os n let output_lid os lid = output_seq "." output_string os lid -let string_of_type_name (_,n) = n +let string_of_type_name (_, n) = n -let output_byte os i = +let output_byte os i = output_hex_digit os (i / 16) output_hex_digit os (i % 16) -let output_bytes os (bytes:byte[]) = +let output_bytes os (bytes:byte[]) = for i = 0 to bytes.Length - 1 do output_byte os (Bytes.get bytes i) output_string os " " -let bits_of_float32 (x:float32) = System.BitConverter.ToInt32(System.BitConverter.GetBytes(x),0) +let bits_of_float32 (x:float32) = System.BitConverter.ToInt32(System.BitConverter.GetBytes(x), 0) let bits_of_float (x:float) = System.BitConverter.DoubleToInt64Bits(x) @@ -151,56 +147,58 @@ let output_i16 os (x:int16) = output_string os (string (int x)) let output_u32 os (x:uint32) = output_string os (string (int64 x)) -let output_i32 os (x:int32) = output_string os (string x) +let output_i32 os (x:int32) = output_string os (string x) let output_u64 os (x:uint64) = output_string os (string (int64 x)) -let output_i64 os (x:int64) = output_string os (string x) +let output_i64 os (x:int64) = output_string os (string x) let output_ieee32 os (x:float32) = output_string os "float32 ("; output_string os (string (bits_of_float32 x)); output_string os ")" let output_ieee64 os (x:float) = output_string os "float64 ("; output_string os (string (bits_of_float x)); output_string os ")" -let rec goutput_scoref _env os = function +let rec goutput_scoref env os = function | ILScopeRef.Local -> () | ILScopeRef.Assembly aref -> output_string os "["; output_sqstring os aref.Name; output_string os "]" | ILScopeRef.Module mref -> - output_string os "[.module "; output_sqstring os mref.Name; output_string os "]" + output_string os "[.module "; output_sqstring os mref.Name; output_string os "]" + | ILScopeRef.PrimaryAssembly -> + output_string os "["; output_sqstring os env.ilGlobals.primaryAssemblyName; output_string os "]" -and goutput_type_name_ref env os (scoref,enc,n) = +and goutput_type_name_ref env os (scoref, enc, n) = goutput_scoref env os scoref output_seq "/" output_sqstring os (enc@[n]) -and goutput_tref env os (x:ILTypeRef) = - goutput_type_name_ref env os (x.Scope,x.Enclosing,x.Name) +and goutput_tref env os (x:ILTypeRef) = + goutput_type_name_ref env os (x.Scope, x.Enclosing, x.Name) and goutput_typ env os ty = - match ty with + match ty with | ILType.Boxed tr -> goutput_tspec env os tr - | ILType.TypeVar tv -> - // Special rule to print method type variables in Generic EE preferred form - // when an environment is available to help us do this. - let cgparams = env.ppenvClassFormals - let mgparams = env.ppenvMethodFormals - if int tv < cgparams then + | ILType.TypeVar tv -> + // Special rule to print method type variables in Generic EE preferred form + // when an environment is available to help us do this. + let cgparams = env.ppenvClassFormals + let mgparams = env.ppenvMethodFormals + if int tv < cgparams then output_string os "!" output_tyvar os tv - elif int tv - cgparams < mgparams then + elif int tv - cgparams < mgparams then output_string os "!!" output_int os (int tv - cgparams) - else + else output_string os "!" output_tyvar os tv output_int os (int tv) - + | ILType.Byref typ -> goutput_typ env os typ; output_string os "&" | ILType.Ptr typ -> goutput_typ env os typ; output_string os "*" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_SByte.TypeSpec.Name -> output_string os "int8" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_SByte.TypeSpec.Name -> output_string os "int8" | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Int16.TypeSpec.Name -> output_string os "int16" | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Int32.TypeSpec.Name -> output_string os "int32" | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Int64.TypeSpec.Name -> output_string os "int64" | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_IntPtr.TypeSpec.Name -> output_string os "native int" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Byte.TypeSpec.Name -> output_string os "unsigned int8" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Byte.TypeSpec.Name -> output_string os "unsigned int8" | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_UInt16.TypeSpec.Name -> output_string os "unsigned int16" | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_UInt32.TypeSpec.Name -> output_string os "unsigned int32" | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_UInt64.TypeSpec.Name -> output_string os "unsigned int64" @@ -215,7 +213,7 @@ and goutput_typ env os ty = output_string os " " goutput_gactuals env os tspec.GenericArgs | ILType.Void -> output_string os "void" - | ILType.Array (bounds,ty) -> + | ILType.Array (bounds, ty) -> goutput_typ env os ty output_string os "[" output_arr_bounds os bounds @@ -224,11 +222,11 @@ and goutput_typ env os ty = output_string os "method " goutput_typ env os csig.ReturnType output_string os " *(" - output_seq "," (goutput_typ env) os csig.ArgTypes + output_seq ", " (goutput_typ env) os csig.ArgTypes output_string os ")" | _ -> output_string os "NaT" - -and output_tyvar os d = + +and output_tyvar os d = output_u16 os d; () and goutput_ldtoken_info env os = function @@ -237,11 +235,11 @@ and goutput_ldtoken_info env os = function | ILToken.ILField x -> output_string os "field "; goutput_fspec env os x and goutput_typ_with_shortened_class_syntax env os = function - ILType.Boxed tspec when tspec.GenericArgs = [] -> + ILType.Boxed tspec when tspec.GenericArgs = [] -> goutput_tref env os tspec.TypeRef | typ2 -> goutput_typ env os typ2 -and goutput_gactuals env os inst = +and goutput_gactuals env os inst = if not (List.isEmpty inst) then output_string os "<" output_seq ", " (goutput_gactual env) os inst @@ -249,34 +247,34 @@ and goutput_gactuals env os inst = and goutput_gactual env os ty = goutput_typ env os ty -and goutput_tspec env os tspec = +and goutput_tspec env os tspec = output_string os "class " goutput_tref env os tspec.TypeRef output_string os " " goutput_gactuals env os tspec.GenericArgs -and output_arr_bounds os = function +and output_arr_bounds os = function | bounds when bounds = ILArrayShape.SingleDimensional -> () | ILArrayShape l -> - output_seq "," + output_seq ", " (fun os -> function - | (None,None) -> output_string os "" - | (None,Some sz) -> + | (None, None) -> output_string os "" + | (None, Some sz) -> output_int os sz - | (Some lower,None) -> + | (Some lower, None) -> output_int os lower output_string os " ... " - | (Some lower,Some d) -> + | (Some lower, Some d) -> output_int os lower output_string os " ... " output_int os d) - os + os l - -and goutput_permission _env os p = - let output_security_action os x = - output_string os - (match x with + +and goutput_permission _env os p = + let output_security_action os x = + output_string os + (match x with | ILSecurityAction.Request -> "request" | ILSecurityAction.Demand -> "demand" | ILSecurityAction.Assert-> "assert" @@ -291,32 +289,32 @@ and goutput_permission _env os p = | ILSecurityAction.PreJitDeny-> "prejitdeny" | ILSecurityAction.NonCasDemand-> "noncasdemand" | ILSecurityAction.NonCasLinkDemand-> "noncaslinkdemand" - | ILSecurityAction.NonCasInheritance-> "noncasinheritance" + | ILSecurityAction.NonCasInheritance-> "noncasinheritance" | ILSecurityAction.LinkDemandChoice -> "linkdemandchoice" | ILSecurityAction.InheritanceDemandChoice -> "inheritancedemandchoice" - | ILSecurityAction.DemandChoice -> "demandchoice") + | ILSecurityAction.DemandChoice -> "demandchoice") - match p with - | ILSecurityDecl (sa,b) -> + match p with + | ILSecurityDecl (sa, b) -> output_string os " .permissionset " - output_security_action os sa - output_string os " = (" - output_bytes os b - output_string os ")" - + output_security_action os sa + output_string os " = (" + output_bytes os b + output_string os ")" + and goutput_security_decls env os (ps: ILSecurityDecls) = output_seq " " (goutput_permission env) os ps.AsList -and goutput_gparam env os (gf: ILGenericParameterDef) = +and goutput_gparam env os (gf: ILGenericParameterDef) = output_string os (tyvar_generator gf.Name) - output_parens (output_seq "," (goutput_typ env)) os gf.Constraints + output_parens (output_seq ", " (goutput_typ env)) os gf.Constraints -and goutput_gparams env os b = - if not (isNil b) then - output_string os "<"; output_seq "," (goutput_gparam env) os b; output_string os ">"; () +and goutput_gparams env os b = + if not (isNil b) then + output_string os "<"; output_seq ", " (goutput_gparam env) os b; output_string os ">"; () and output_bcc os bcc = - output_string os - (match bcc with + output_string os + (match bcc with | ILArgConvention.FastCall -> "fastcall " | ILArgConvention.StdCall -> "stdcall " | ILArgConvention.ThisCall -> "thiscall " @@ -324,103 +322,103 @@ and output_bcc os bcc = | ILArgConvention.Default -> " " | ILArgConvention.VarArg -> "vararg ") -and output_callconv os (Callconv (hasthis,cc)) = - output_string os - (match hasthis with - ILThisConvention.Instance -> "instance " +and output_callconv os (Callconv (hasthis, cc)) = + output_string os + (match hasthis with + ILThisConvention.Instance -> "instance " | ILThisConvention.InstanceExplicit -> "explicit " - | ILThisConvention.Static -> "") + | ILThisConvention.Static -> "") output_bcc os cc -and goutput_dlocref env os (dref:ILType) = - match dref with - | dref when - dref.IsNominal && +and goutput_dlocref env os (dref:ILType) = + match dref with + | dref when + dref.IsNominal && isTypeNameForGlobalFunctions dref.TypeRef.Name && - dref.TypeRef.Scope = ILScopeRef.Local -> + dref.TypeRef.Scope = ILScopeRef.Local -> () - | dref when - dref.IsNominal && + | dref when + dref.IsNominal && isTypeNameForGlobalFunctions dref.TypeRef.Name -> goutput_scoref env os dref.TypeRef.Scope output_string os "::" - | ty ->goutput_typ_with_shortened_class_syntax env os ty; output_string os "::" + | ty ->goutput_typ_with_shortened_class_syntax env os ty; output_string os "::" and goutput_callsig env os (csig:ILCallingSignature) = output_callconv os csig.CallingConv output_string os " " goutput_typ env os csig.ReturnType - output_parens (output_seq "," (goutput_typ env)) os csig.ArgTypes + output_parens (output_seq ", " (goutput_typ env)) os csig.ArgTypes and goutput_mref env os (mref:ILMethodRef) = output_callconv os mref.CallingConv output_string os " " goutput_typ_with_shortened_class_syntax env os mref.ReturnType output_string os " " - // no quotes for ".ctor" - let name = mref.Name + // no quotes for ".ctor" + let name = mref.Name if name = ".ctor" || name = ".cctor" then output_string os name else output_id os name - output_parens (output_seq "," (goutput_typ env)) os mref.ArgTypes + output_parens (output_seq ", " (goutput_typ env)) os mref.ArgTypes -and goutput_mspec env os (mspec:ILMethodSpec) = - let fenv = +and goutput_mspec env os (mspec:ILMethodSpec) = + let fenv = ppenv_enter_method mspec.GenericArity - (ppenv_enter_tdef (mkILFormalTypars mspec.DeclaringType.GenericArgs) env) + (ppenv_enter_tdef (mkILFormalTypars mspec.DeclaringType.GenericArgs) env) output_callconv os mspec.CallingConv output_string os " " goutput_typ fenv os mspec.FormalReturnType output_string os " " goutput_dlocref env os mspec.DeclaringType output_string os " " - let name = mspec.Name + let name = mspec.Name if name = ".ctor" || name = ".cctor" then output_string os name else output_id os name goutput_gactuals env os mspec.GenericArgs - output_parens (output_seq "," (goutput_typ fenv)) os mspec.FormalArgTypes + output_parens (output_seq ", " (goutput_typ fenv)) os mspec.FormalArgTypes and goutput_vararg_mspec env os (mspec, varargs) = - match varargs with + match varargs with | None -> goutput_mspec env os mspec - | Some varargs' -> - let fenv = + | Some varargs' -> + let fenv = ppenv_enter_method mspec.GenericArity - (ppenv_enter_tdef (mkILFormalTypars mspec.DeclaringType.GenericArgs) env) + (ppenv_enter_tdef (mkILFormalTypars mspec.DeclaringType.GenericArgs) env) output_callconv os mspec.CallingConv output_string os " " goutput_typ fenv os mspec.FormalReturnType output_string os " " goutput_dlocref env os mspec.DeclaringType - let name = mspec.Name + let name = mspec.Name if name = ".ctor" || name = ".cctor" then output_string os name else output_id os name goutput_gactuals env os mspec.GenericArgs output_string os "(" - output_seq "," (goutput_typ fenv) os mspec.FormalArgTypes - output_string os ",...," - output_seq "," (goutput_typ fenv) os varargs' + output_seq ", " (goutput_typ fenv) os mspec.FormalArgTypes + output_string os ", ..., " + output_seq ", " (goutput_typ fenv) os varargs' output_string os ")" -and goutput_vararg_sig env os (csig:ILCallingSignature,varargs:ILVarArgs) = - match varargs with +and goutput_vararg_sig env os (csig:ILCallingSignature, varargs:ILVarArgs) = + match varargs with | None -> goutput_callsig env os csig; () - | Some varargs' -> + | Some varargs' -> goutput_typ env os csig.ReturnType output_string os " (" - let argtys = csig.ArgTypes + let argtys = csig.ArgTypes if argtys.Length <> 0 then output_seq ", " (goutput_typ env) os argtys - output_string os ",...," - output_seq "," (goutput_typ env) os varargs' + output_string os ", ..., " + output_seq ", " (goutput_typ env) os varargs' output_string os ")" and goutput_fspec env os (x:ILFieldSpec) = - let fenv = ppenv_enter_tdef (mkILFormalTypars x.DeclaringType.GenericArgs) env + let fenv = ppenv_enter_tdef (mkILFormalTypars x.DeclaringType.GenericArgs) env goutput_typ fenv os x.FormalType output_string os " " goutput_dlocref env os x.DeclaringType output_id os x.Name - -let output_member_access os access = - output_string os - (match access with + +let output_member_access os access = + output_string os + (match access with | ILMemberAccess.Public -> "public" | ILMemberAccess.Private -> "private" | ILMemberAccess.Family -> "family" @@ -429,14 +427,14 @@ let output_member_access os access = | ILMemberAccess.FamilyOrAssembly -> "famorassem" | ILMemberAccess.Assembly -> "assembly") -let output_type_access os access = - match access with +let output_type_access os access = + match access with | ILTypeDefAccess.Public -> output_string os "public" | ILTypeDefAccess.Private -> output_string os "private" | ILTypeDefAccess.Nested ilMemberAccess -> output_string os "nested "; output_member_access os ilMemberAccess -let output_encoding os e = - match e with +let output_encoding os e = + match e with | ILDefaultPInvokeEncoding.Ansi -> output_string os " ansi " | ILDefaultPInvokeEncoding.Auto -> output_string os " autochar " | ILDefaultPInvokeEncoding.Unicode -> output_string os " unicode " @@ -454,29 +452,29 @@ let output_field_init os = function | ILFieldInit.UInt64 x-> output_string os "= uint64"; output_parens output_u64 os x | ILFieldInit.Single x-> output_string os "= float32"; output_parens output_ieee32 os x | ILFieldInit.Double x-> output_string os "= float64"; output_parens output_ieee64 os x - | ILFieldInit.Null-> output_string os "= nullref" + | ILFieldInit.Null-> output_string os "= nullref" let output_at os b = Printf.fprintf os " at (* no labels for data available, data = %a *)" (output_parens output_bytes) b let output_option f os = function None -> () | Some x -> f os x - -let goutput_alternative_ref env os (alt: IlxUnionAlternative) = + +let goutput_alternative_ref env os (alt: IlxUnionAlternative) = output_id os alt.Name - alt.FieldDefs |> output_parens (output_array "," (fun os fdef -> goutput_typ env os fdef.Type)) os + alt.FieldDefs |> output_parens (output_array ", " (fun os fdef -> goutput_typ env os fdef.Type)) os -let goutput_curef env os (IlxUnionRef(_,tref,alts,_,_)) = +let goutput_curef env os (IlxUnionRef(_, tref, alts, _, _)) = output_string os " .classunion import " goutput_tref env os tref - output_parens (output_array "," (goutput_alternative_ref env)) os alts - -let goutput_cuspec env os (IlxUnionSpec(IlxUnionRef(_,tref,_,_,_),i)) = + output_parens (output_array ", " (goutput_alternative_ref env)) os alts + +let goutput_cuspec env os (IlxUnionSpec(IlxUnionRef(_, tref, _, _, _), i)) = output_string os "class /* classunion */ " goutput_tref env os tref goutput_gactuals env os i -let output_basic_type os x = - output_string os +let output_basic_type os x = + output_string os (match x with | DT_I1 -> "i1" | DT_U1 -> "u1" @@ -493,9 +491,9 @@ let output_basic_type os x = | DT_U -> "u" | DT_REF -> "ref") -let output_custom_attr_data os data = +let output_custom_attr_data os data = output_string os " = "; output_parens output_bytes os data - + let goutput_custom_attr env os (attr: ILAttribute) = output_string os " .custom " goutput_mspec env os attr.Method @@ -507,8 +505,8 @@ let goutput_custom_attrs env os (attrs : ILAttributes) = let goutput_fdef _tref env os (fd: ILFieldDef) = output_string os " .field " - match fd.Offset with Some i -> output_string os "["; output_i32 os i; output_string os "] " | None -> () - match fd.Marshal with Some _i -> output_string os "// marshal attribute not printed\n"; | None -> () + match fd.Offset with Some i -> output_string os "["; output_i32 os i; output_string os "] " | None -> () + match fd.Marshal with Some _i -> output_string os "// marshal attribute not printed\n"; | None -> () output_member_access os fd.Access output_string os " " if fd.IsStatic then output_string os " static " @@ -540,17 +538,17 @@ let output_after_tailcall os = function | Tailcall -> output_string os " ret " | _ -> () let rec goutput_apps env os = function - | Apps_tyapp (actual,cs) -> + | Apps_tyapp (actual, cs) -> output_angled (goutput_gactual env) os actual output_string os " " - output_angled (goutput_gparam env) os (mkILSimpleTypar "T") + output_angled (goutput_gparam env) os (mkILSimpleTypar "T") output_string os " " goutput_apps env os cs - | Apps_app(ty,cs) -> + | Apps_app(ty, cs) -> output_parens (goutput_typ env) os ty output_string os " " goutput_apps env os cs - | Apps_done ty -> + | Apps_done ty -> output_string os "--> " goutput_typ env os ty @@ -563,37 +561,37 @@ let output_short_i32 os i32 = if i32 < 256 && 0 >= i32 then (output_string os ".s "; output_i32 os i32) else output_string os " "; output_i32 os i32 -let output_code_label os lab = +let output_code_label os lab = output_string os (formatCodeLabel lab) -let goutput_local env os (l: ILLocal) = +let goutput_local env os (l: ILLocal) = goutput_typ env os l.Type if l.IsPinned then output_string os " pinned" -let goutput_param env os (l: ILParameter) = - match l.Name with +let goutput_param env os (l: ILParameter) = + match l.Name with None -> goutput_typ env os l.Type | Some n -> goutput_typ env os l.Type; output_string os " "; output_sqstring os n -let goutput_params env os ps = - output_parens (output_seq "," (goutput_param env)) os ps +let goutput_params env os ps = + output_parens (output_seq ", " (goutput_param env)) os ps -let goutput_freevar env os l = - goutput_typ env os l.fvType; output_string os " "; output_sqstring os l.fvName +let goutput_freevar env os l = + goutput_typ env os l.fvType; output_string os " "; output_sqstring os l.fvName -let goutput_freevars env os ps = - output_parens (output_seq "," (goutput_freevar env)) os ps +let goutput_freevars env os ps = + output_parens (output_seq ", " (goutput_freevar env)) os ps -let output_source os (s:ILSourceMarker) = - if s.Document.File <> "" then +let output_source os (s:ILSourceMarker) = + if s.Document.File <> "" then output_string os " .line " output_int os s.Line - if s.Column <> -1 then + if s.Column <> -1 then output_string os " : " output_int os s.Column output_string os " /* - " output_int os s.EndLine - if s.Column <> -1 then + if s.Column <> -1 then output_string os " : " output_int os s.EndColumn output_string os "*/ " @@ -604,9 +602,9 @@ let rec goutput_instr env os inst = match inst with | si when isNoArgInstr si -> output_lid os (wordsOfNoArgInstr si) - | I_brcmp (cmp,tg1) -> - output_string os - (match cmp with + | I_brcmp (cmp, tg1) -> + output_string os + (match cmp with | BI_beq -> "beq" | BI_bgt -> "bgt" | BI_bgt_un -> "bgt.un" @@ -623,159 +621,159 @@ let rec goutput_instr env os inst = output_code_label os tg1 | I_br tg -> output_string os "/* br "; output_code_label os tg; output_string os "*/" | I_leave tg -> output_string os "leave "; output_code_label os tg - | I_call (tl,mspec,varargs) -> + | I_call (tl, mspec, varargs) -> output_tailness os tl output_string os "call " - goutput_vararg_mspec env os (mspec,varargs) + goutput_vararg_mspec env os (mspec, varargs) output_after_tailcall os tl - | I_calli (tl,mref,varargs) -> + | I_calli (tl, mref, varargs) -> output_tailness os tl output_string os "calli " - goutput_vararg_sig env os (mref,varargs) + goutput_vararg_sig env os (mref, varargs) output_after_tailcall os tl | I_ldarg u16 -> output_string os "ldarg"; output_short_u16 os u16 | I_ldarga u16 -> output_string os "ldarga "; output_u16 os u16 - | (AI_ldc (dt, ILConst.I4 x)) -> + | (AI_ldc (dt, ILConst.I4 x)) -> output_string os "ldc."; output_basic_type os dt; output_short_i32 os x - | (AI_ldc (dt, ILConst.I8 x)) -> + | (AI_ldc (dt, ILConst.I8 x)) -> output_string os "ldc."; output_basic_type os dt; output_string os " "; output_i64 os x - | (AI_ldc (dt, ILConst.R4 x)) -> + | (AI_ldc (dt, ILConst.R4 x)) -> output_string os "ldc."; output_basic_type os dt; output_string os " "; output_ieee32 os x - | (AI_ldc (dt, ILConst.R8 x)) -> + | (AI_ldc (dt, ILConst.R8 x)) -> output_string os "ldc."; output_basic_type os dt; output_string os " "; output_ieee64 os x | I_ldftn mspec -> output_string os "ldftn "; goutput_mspec env os mspec | I_ldvirtftn mspec -> output_string os "ldvirtftn "; goutput_mspec env os mspec - | I_ldind (al,vol,dt) -> + | I_ldind (al, vol, dt) -> output_alignment os al output_volatility os vol output_string os "ldind." - output_basic_type os dt - | I_cpblk (al,vol) -> + output_basic_type os dt + | I_cpblk (al, vol) -> output_alignment os al output_volatility os vol output_string os "cpblk" - | I_initblk (al,vol) -> + | I_initblk (al, vol) -> output_alignment os al output_volatility os vol output_string os "initblk" | I_ldloc u16 -> output_string os "ldloc"; output_short_u16 os u16 | I_ldloca u16 -> output_string os "ldloca "; output_u16 os u16 | I_starg u16 -> output_string os "starg "; output_u16 os u16 - | I_stind (al,vol,dt) -> + | I_stind (al, vol, dt) -> output_alignment os al output_volatility os vol output_string os "stind." - output_basic_type os dt + output_basic_type os dt | I_stloc u16 -> output_string os "stloc"; output_short_u16 os u16 - | I_switch l -> output_string os "switch "; output_parens (output_seq "," output_code_label) os l - | I_callvirt (tl,mspec,varargs) -> + | I_switch l -> output_string os "switch "; output_parens (output_seq ", " output_code_label) os l + | I_callvirt (tl, mspec, varargs) -> output_tailness os tl output_string os "callvirt " - goutput_vararg_mspec env os (mspec,varargs) + goutput_vararg_mspec env os (mspec, varargs) output_after_tailcall os tl - | I_callconstraint (tl,ty,mspec,varargs) -> + | I_callconstraint (tl, ty, mspec, varargs) -> output_tailness os tl output_string os "constraint. " goutput_typ env os ty output_string os " callvirt " - goutput_vararg_mspec env os (mspec,varargs) + goutput_vararg_mspec env os (mspec, varargs) output_after_tailcall os tl | I_castclass ty -> output_string os "castclass "; goutput_typ env os ty | I_isinst ty -> output_string os "isinst "; goutput_typ env os ty - | I_ldfld (al,vol,fspec) -> + | I_ldfld (al, vol, fspec) -> output_alignment os al output_volatility os vol output_string os "ldfld " goutput_fspec env os fspec - | I_ldflda fspec -> - output_string os "ldflda " + | I_ldflda fspec -> + output_string os "ldflda " goutput_fspec env os fspec - | I_ldsfld (vol,fspec) -> + | I_ldsfld (vol, fspec) -> output_volatility os vol output_string os "ldsfld " goutput_fspec env os fspec - | I_ldsflda fspec -> + | I_ldsflda fspec -> output_string os "ldsflda " goutput_fspec env os fspec - | I_stfld (al,vol,fspec) -> + | I_stfld (al, vol, fspec) -> output_alignment os al output_volatility os vol output_string os "stfld " goutput_fspec env os fspec - | I_stsfld (vol,fspec) -> + | I_stsfld (vol, fspec) -> output_volatility os vol output_string os "stsfld " goutput_fspec env os fspec - | I_ldtoken tok -> output_string os "ldtoken "; goutput_ldtoken_info env os tok + | I_ldtoken tok -> output_string os "ldtoken "; goutput_ldtoken_info env os tok | I_refanyval ty -> output_string os "refanyval "; goutput_typ env os ty | I_refanytype -> output_string os "refanytype" | I_mkrefany typ -> output_string os "mkrefany "; goutput_typ env os typ - | I_ldstr s -> + | I_ldstr s -> output_string os "ldstr " output_string os s - | I_newobj (mspec,varargs) -> - // newobj: IL has a special rule that the CC is always implicitly "instance" and need - // not be mentioned explicitly + | I_newobj (mspec, varargs) -> + // newobj: IL has a special rule that the CC is always implicitly "instance" and need + // not be mentioned explicitly output_string os "newobj " - goutput_vararg_mspec env os (mspec,varargs) - | I_stelem dt -> output_string os "stelem."; output_basic_type os dt - | I_ldelem dt -> output_string os "ldelem."; output_basic_type os dt + goutput_vararg_mspec env os (mspec, varargs) + | I_stelem dt -> output_string os "stelem."; output_basic_type os dt + | I_ldelem dt -> output_string os "ldelem."; output_basic_type os dt - | I_newarr (shape,typ) -> - if shape = ILArrayShape.SingleDimensional then + | I_newarr (shape, typ) -> + if shape = ILArrayShape.SingleDimensional then output_string os "newarr " goutput_typ_with_shortened_class_syntax env os typ - else + else output_string os "newobj void " - goutput_dlocref env os (mkILArrTy(typ,shape)) + goutput_dlocref env os (mkILArrTy(typ, shape)) output_string os ".ctor" - let rank = shape.Rank - output_parens (output_array "," (goutput_typ env)) os (Array.create ( rank) EcmaMscorlibILGlobals.typ_Int32) - | I_stelem_any (shape,dt) -> - if shape = ILArrayShape.SingleDimensional then - output_string os "stelem.any "; goutput_typ env os dt - else + let rank = shape.Rank + output_parens (output_array ", " (goutput_typ env)) os (Array.create ( rank) EcmaMscorlibILGlobals.typ_Int32) + | I_stelem_any (shape, dt) -> + if shape = ILArrayShape.SingleDimensional then + output_string os "stelem.any "; goutput_typ env os dt + else output_string os "call instance void " - goutput_dlocref env os (mkILArrTy(dt,shape)) + goutput_dlocref env os (mkILArrTy(dt, shape)) output_string os "Set" - let rank = shape.Rank + let rank = shape.Rank let arr = Array.create (rank + 1) EcmaMscorlibILGlobals.typ_Int32 arr.[rank] <- dt - output_parens (output_array "," (goutput_typ env)) os arr - | I_ldelem_any (shape,tok) -> - if shape = ILArrayShape.SingleDimensional then - output_string os "ldelem.any "; goutput_typ env os tok - else + output_parens (output_array ", " (goutput_typ env)) os arr + | I_ldelem_any (shape, tok) -> + if shape = ILArrayShape.SingleDimensional then + output_string os "ldelem.any "; goutput_typ env os tok + else output_string os "call instance " goutput_typ env os tok output_string os " " - goutput_dlocref env os (mkILArrTy(tok,shape)) + goutput_dlocref env os (mkILArrTy(tok, shape)) output_string os "Get" - let rank = shape.Rank - output_parens (output_array "," (goutput_typ env)) os (Array.create ( rank) EcmaMscorlibILGlobals.typ_Int32) - | I_ldelema (ro,_,shape,tok) -> + let rank = shape.Rank + output_parens (output_array ", " (goutput_typ env)) os (Array.create ( rank) EcmaMscorlibILGlobals.typ_Int32) + | I_ldelema (ro, _, shape, tok) -> if ro = ReadonlyAddress then output_string os "readonly. " - if shape = ILArrayShape.SingleDimensional then - output_string os "ldelema "; goutput_typ env os tok - else + if shape = ILArrayShape.SingleDimensional then + output_string os "ldelema "; goutput_typ env os tok + else output_string os "call instance " goutput_typ env os (ILType.Byref tok) output_string os " " - goutput_dlocref env os (mkILArrTy(tok,shape)) + goutput_dlocref env os (mkILArrTy(tok, shape)) output_string os "Address" - let rank = shape.Rank - output_parens (output_array "," (goutput_typ env)) os (Array.create ( rank) EcmaMscorlibILGlobals.typ_Int32) - + let rank = shape.Rank + output_parens (output_array ", " (goutput_typ env)) os (Array.create ( rank) EcmaMscorlibILGlobals.typ_Int32) + | I_box tok -> output_string os "box "; goutput_typ env os tok | I_unbox tok -> output_string os "unbox "; goutput_typ env os tok | I_unbox_any tok -> output_string os "unbox.any "; goutput_typ env os tok | I_initobj tok -> output_string os "initobj "; goutput_typ env os tok - | I_ldobj (al,vol,tok) -> + | I_ldobj (al, vol, tok) -> output_alignment os al output_volatility os vol output_string os "ldobj " goutput_typ env os tok - | I_stobj (al,vol,tok) -> + | I_stobj (al, vol, tok) -> output_alignment os al output_volatility os vol output_string os "stobj " @@ -784,7 +782,7 @@ let rec goutput_instr env os inst = | I_sizeof tok -> output_string os "sizeof "; goutput_typ env os tok | I_seqpoint s -> output_source os s | EI_ilzero ty -> output_string os "ilzero "; goutput_typ env os ty - | _ -> + | _ -> output_string os "" @@ -793,31 +791,31 @@ let goutput_ilmbody env os (il: ILMethodBody) = output_string os " .maxstack " output_i32 os il.MaxStack output_string os "\n" - if il.Locals.Length <> 0 then + if il.Locals.Length <> 0 then output_string os " .locals(" - output_seq ",\n " (goutput_local env) os il.Locals + output_seq ", \n " (goutput_local env) os il.Locals output_string os ")\n" - + let goutput_mbody is_entrypoint env os (md: ILMethodDef) = if md.ImplAttributes &&& MethodImplAttributes.Native <> enum 0 then output_string os "native " elif md.ImplAttributes &&& MethodImplAttributes.IL <> enum 0 then output_string os "cil " else output_string os "runtime " - + output_string os (if md.IsInternalCall then "internalcall " else " ") output_string os (if md.IsManaged then "managed " else " ") output_string os (if md.IsForwardRef then "forwardref " else " ") - output_string os " \n{ \n" + output_string os " \n{ \n" goutput_security_decls env os md.SecurityDecls goutput_custom_attrs env os md.CustomAttrs - match md.Body.Contents with + match md.Body.Contents with | MethodBody.IL il -> goutput_ilmbody env os il | _ -> () if is_entrypoint then output_string os " .entrypoint" output_string os "\n" output_string os "}\n" - + let goutput_mdef env os (md:ILMethodDef) = - let attrs = + let attrs = if md.IsVirtual then "virtual " + (if md.IsFinal then "final " else "") + @@ -829,18 +827,18 @@ let goutput_mdef env os (md:ILMethodDef) = elif md.IsConstructor then "rtspecialname" elif md.IsStatic then "static " + - (match md.Body.Contents with - MethodBody.PInvoke (attr) -> + (match md.Body.Contents with + MethodBody.PInvoke (attr) -> "pinvokeimpl(\"" + attr.Where.Name + "\" as \"" + attr.Name + "\"" + - (match attr.CallingConv with + (match attr.CallingConv with | PInvokeCallingConvention.None -> "" | PInvokeCallingConvention.Cdecl -> " cdecl" | PInvokeCallingConvention.Stdcall -> " stdcall" - | PInvokeCallingConvention.Thiscall -> " thiscall" + | PInvokeCallingConvention.Thiscall -> " thiscall" | PInvokeCallingConvention.Fastcall -> " fastcall" | PInvokeCallingConvention.WinApi -> " winapi" ) + - (match attr.CharEncoding with + (match attr.CharEncoding with | PInvokeCharEncoding.None -> "" | PInvokeCharEncoding.Ansi -> " ansi" | PInvokeCharEncoding.Unicode -> " unicode" @@ -849,12 +847,12 @@ let goutput_mdef env os (md:ILMethodDef) = (if attr.NoMangle then " nomangle" else "") + (if attr.LastError then " lasterr" else "") + ")" - | _ -> + | _ -> "") - elif md.IsClassInitializer then "specialname rtspecialname static" + elif md.IsClassInitializer then "specialname rtspecialname static" else "" - let is_entrypoint = md.IsEntryPoint - let menv = ppenv_enter_method (List.length md.GenericParams) env + let is_entrypoint = md.IsEntryPoint + let menv = ppenv_enter_method (List.length md.GenericParams) env output_string os " .method " if md.IsHideBySig then output_string os "hidebysig " if md.IsReqSecObj then output_string os "reqsecobj " @@ -868,7 +866,7 @@ let goutput_mdef env os (md:ILMethodDef) = output_string os " " (goutput_typ menv) os md.Return.Type output_string os " " - output_id os md.Name + output_id os md.Name output_string os " " (goutput_gparams env) os md.GenericParams output_string os " " @@ -888,19 +886,19 @@ let goutput_pdef env os (pd: ILPropertyDef) = output_string os "\n\tsetter: " (match pd.SetMethod with None -> () | Some mref -> goutput_mref env os mref) -let goutput_superclass env os = function +let goutput_superclass env os = function None -> () | Some typ -> output_string os "extends "; (goutput_typ_with_shortened_class_syntax env) os typ let goutput_superinterfaces env os imp = if not (List.isEmpty imp) then output_string os "implements " - output_seq "," (goutput_typ_with_shortened_class_syntax env) os imp + output_seq ", " (goutput_typ_with_shortened_class_syntax env) os imp let goutput_implements env os (imp:ILTypes) = if not (List.isEmpty imp) then output_string os "implements " - output_seq "," (goutput_typ_with_shortened_class_syntax env) os imp + output_seq ", " (goutput_typ_with_shortened_class_syntax env) os imp let the = function Some x -> x | None -> failwith "the" @@ -909,29 +907,29 @@ let output_type_layout_info os info = if info.Pack <> None then (output_string os " .pack "; output_u16 os (the info.Pack)) let splitTypeLayout = function - | ILTypeDefLayout.Auto -> "auto",(fun _os () -> ()) + | ILTypeDefLayout.Auto -> "auto", (fun _os () -> ()) | ILTypeDefLayout.Sequential info -> "sequential", (fun os () -> output_type_layout_info os info) | ILTypeDefLayout.Explicit info -> "explicit", (fun os () -> output_type_layout_info os info) - -let goutput_fdefs tref env os (fdefs: ILFieldDefs) = + +let goutput_fdefs tref env os (fdefs: ILFieldDefs) = List.iter (fun f -> (goutput_fdef tref env) os f; output_string os "\n" ) fdefs.AsList -let goutput_mdefs env os (mdefs: ILMethodDefs) = +let goutput_mdefs env os (mdefs: ILMethodDefs) = Array.iter (fun f -> (goutput_mdef env) os f; output_string os "\n" ) mdefs.AsArray -let goutput_pdefs env os (pdefs: ILPropertyDefs) = +let goutput_pdefs env os (pdefs: ILPropertyDefs) = List.iter (fun f -> (goutput_pdef env) os f; output_string os "\n" ) pdefs.AsList let rec goutput_tdef enc env contents os (cd: ILTypeDef) = - let env = ppenv_enter_tdef cd.GenericParams env - let layout_attr,pp_layout_decls = splitTypeLayout cd.Layout - if isTypeNameForGlobalFunctions cd.Name then - if contents then - let tref = (mkILNestedTyRef (ILScopeRef.Local,enc,cd.Name)) + let env = ppenv_enter_tdef cd.GenericParams env + let layout_attr, pp_layout_decls = splitTypeLayout cd.Layout + if isTypeNameForGlobalFunctions cd.Name then + if contents then + let tref = (mkILNestedTyRef (ILScopeRef.Local, enc, cd.Name)) goutput_mdefs env os cd.Methods goutput_fdefs tref env os cd.Fields goutput_pdefs env os cd.Properties - else + else output_string os "\n" if cd.IsInterface then output_string os ".class interface " else output_string os ".class " @@ -947,15 +945,15 @@ let rec goutput_tdef enc env contents os (cd: ILTypeDef) = if cd.IsAbstract then output_string os "abstract " if cd.IsSerializable then output_string os "serializable " if cd.IsComInterop then output_string os "import " - output_sqstring os cd.Name + output_sqstring os cd.Name goutput_gparams env os cd.GenericParams output_string os "\n\t" goutput_superclass env os cd.Extends output_string os "\n\t" goutput_implements env os cd.Implements output_string os "\n{\n " - if contents then - let tref = (mkILNestedTyRef (ILScopeRef.Local,enc,cd.Name)) + if contents then + let tref = (mkILNestedTyRef (ILScopeRef.Local, enc, cd.Name)) goutput_custom_attrs env os cd.CustomAttrs goutput_security_decls env os cd.SecurityDecls pp_layout_decls os () @@ -967,39 +965,39 @@ let rec goutput_tdef enc env contents os (cd: ILTypeDef) = and output_init_semantics os f = if f &&& TypeAttributes.BeforeFieldInit <> enum 0 then output_string os "beforefieldinit" -and goutput_lambdas env os lambdas = +and goutput_lambdas env os lambdas = match lambdas with - | Lambdas_forall (gf,l) -> + | Lambdas_forall (gf, l) -> output_angled (goutput_gparam env) os gf output_string os " " (goutput_lambdas env) os l - | Lambdas_lambda (ps,l) -> + | Lambdas_lambda (ps, l) -> output_parens (goutput_param env) os ps output_string os " " (goutput_lambdas env) os l | Lambdas_return typ -> output_string os "--> "; (goutput_typ env) os typ - + and goutput_tdefs contents enc env os (td: ILTypeDefs) = List.iter (goutput_tdef enc env contents os) td.AsList -let output_ver os (a,b,c,d) = +let output_ver os (version: ILVersionInfo) = output_string os " .ver " - output_u16 os a + output_u16 os version.Major output_string os " : " - output_u16 os b + output_u16 os version.Minor output_string os " : " - output_u16 os c + output_u16 os version.Build output_string os " : " - output_u16 os d + output_u16 os version.Revision let output_locale os s = output_string os " .Locale "; output_qstring os s -let output_hash os x = - output_string os " .hash = "; output_parens output_bytes os x -let output_publickeytoken os x = - output_string os " .publickeytoken = "; output_parens output_bytes os x -let output_publickey os x = - output_string os " .publickey = "; output_parens output_bytes os x +let output_hash os x = + output_string os " .hash = "; output_parens output_bytes os x +let output_publickeytoken os x = + output_string os " .publickeytoken = "; output_parens output_bytes os x +let output_publickey os x = + output_string os " .publickey = "; output_parens output_bytes os x let output_publickeyinfo os = function | PublicKey k -> output_publickey os k @@ -1021,29 +1019,28 @@ let output_modref os (modref:ILModuleRef) = output_sqstring os modref.Name output_option output_hash os modref.Hash -let goutput_resource env os r = +let goutput_resource env os r = output_string os " .mresource " output_string os (match r.Access with ILResourceAccess.Public -> " public " | ILResourceAccess.Private -> " private ") output_sqstring os r.Name output_string os " { " goutput_custom_attrs env os r.CustomAttrs - match r.Location with - | ILResourceLocation.LocalIn _ - | ILResourceLocation.LocalOut _ -> + match r.Location with + | ILResourceLocation.Local _ -> output_string os " /* loc nyi */ " - | ILResourceLocation.File (mref,off) -> + | ILResourceLocation.File (mref, off) -> output_string os " .file " output_sqstring os mref.Name output_string os " at " - output_i32 os off - | ILResourceLocation.Assembly aref -> + output_i32 os off + | ILResourceLocation.Assembly aref -> output_string os " .assembly extern " output_sqstring os aref.Name output_string os " }\n " -let goutput_manifest env os m = +let goutput_manifest env os m = output_string os " .assembly " - match m.AssemblyLongevity with + match m.AssemblyLongevity with | ILAssemblyLongevity.Unspecified -> () | ILAssemblyLongevity.Library -> output_string os "library " | ILAssemblyLongevity.PlatformAppDomain -> output_string os "platformappdomain " @@ -1060,25 +1057,25 @@ let goutput_manifest env os m = let output_module_fragment_aux _refs os (ilg: ILGlobals) modul = - try + try let env = mk_ppenv ilg - let env = ppenv_enter_modul env + let env = ppenv_enter_modul env goutput_tdefs false ([]) env os modul.TypeDefs goutput_tdefs true ([]) env os modul.TypeDefs - with e -> + with e -> output_string os "*** Error during printing : "; output_string os (e.ToString()); os.Flush() reraise() let output_module_fragment os (ilg: ILGlobals) modul = - let refs = computeILRefs modul + let refs = computeILRefs ilg modul output_module_fragment_aux refs os ilg modul refs -let output_module_refs os refs = +let output_module_refs os refs = List.iter (fun x -> output_assemblyRef os x; output_string os "\n") refs.AssemblyReferences List.iter (fun x -> output_modref os x; output_string os "\n") refs.ModuleReferences - -let goutput_module_manifest env os modul = + +let goutput_module_manifest env os modul = output_string os " .module "; output_sqstring os modul.Name goutput_custom_attrs env os modul.CustomAttrs output_string os " .imagebase "; output_i32 os modul.ImageBase @@ -1090,20 +1087,20 @@ let goutput_module_manifest env os modul = output_option (goutput_manifest env) os modul.Manifest let output_module os (ilg: ILGlobals) modul = - try - let refs = computeILRefs modul + try + let refs = computeILRefs ilg modul let env = mk_ppenv ilg - let env = ppenv_enter_modul env + let env = ppenv_enter_modul env output_module_refs os refs goutput_module_manifest env os modul output_module_fragment_aux refs os ilg modul - with e -> + with e -> output_string os "*** Error during printing : "; output_string os (e.ToString()); os.Flush() raise e #endif - - - + + + diff --git a/src/fcs-fable/src/absil/ilprint.fsi b/src/fcs-fable/src/absil/ilprint.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/absil/ilread.fs b/src/fcs-fable/src/absil/ilread.fs old mode 100755 new mode 100644 index f712747a53..5ac2d660c6 --- a/src/fcs-fable/src/absil/ilread.fs +++ b/src/fcs-fable/src/absil/ilread.fs @@ -10,27 +10,35 @@ module FSharp.Compiler.AbstractIL.ILBinaryReader #nowarn "42" // This construct is deprecated: it is only for use in the F# library open System +open System.Collections.Concurrent open System.Collections.Generic open System.Diagnostics open System.IO +#if !FABLE_COMPILER +open System.IO.MemoryMappedFiles open System.Runtime.InteropServices +#endif open System.Text open Internal.Utilities open Internal.Utilities.Collections -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.Internal -#if !FX_NO_PDB_READER -open FSharp.Compiler.AbstractIL.Internal.Support -#endif +open FSharp.NativeInterop open FSharp.Compiler.AbstractIL.Diagnostics +open FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.BinaryConstants -open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Library +#if !FABLE_COMPILER +open FSharp.Compiler.AbstractIL.Internal.Support +#endif +open FSharp.Compiler.AbstractIL.Internal.Utils open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Range -open Microsoft.FSharp.NativeInterop open System.Reflection +#nowarn "9" + +let primaryAssemblyILGlobals = mkILGlobals (ILScopeRef.PrimaryAssembly, []) + let checking = false let logging = false let _ = if checking then dprintn "warning: ILBinaryReader.checking is on" @@ -46,8 +54,8 @@ let stronglyHeldReaderCacheSizeDefault = 30 let stronglyHeldReaderCacheSize = try (match System.Environment.GetEnvironmentVariable("FSharp_StronglyHeldBinaryReaderCacheSize") with null -> stronglyHeldReaderCacheSizeDefault | s -> int32 s) with _ -> stronglyHeldReaderCacheSizeDefault #endif -let singleOfBits (x: int32) = System.BitConverter.ToSingle(System.BitConverter.GetBytes(x), 0) -let doubleOfBits (x: int64) = System.BitConverter.Int64BitsToDouble(x) +let singleOfBits (x: int32) = System.BitConverter.ToSingle(System.BitConverter.GetBytes x, 0) +let doubleOfBits (x: int64) = System.BitConverter.Int64BitsToDouble x //--------------------------------------------------------------------- // Utilities. @@ -113,250 +121,35 @@ let stats = let GetStatistics() = stats -[] -/// An abstraction over how we access the contents of .NET binaries. May be backed by managed or unmanaged memory, -/// memory mapped file or by on-disk resources. These objects should never need explicit disposal - they must either -/// not hold resources of clean up after themselves when collected. -type BinaryView() = - - /// Read a byte from the file - abstract ReadByte: addr: int -> byte - - /// Read a chunk of bytes from the file - abstract ReadBytes: addr: int -> int -> byte[] - - /// Read an Int32 from the file - abstract ReadInt32: addr: int -> int - - /// Read a UInt16 from the file - abstract ReadUInt16: addr: int -> uint16 +type private BinaryView = ReadOnlyByteMemory - /// Read a length of a UTF8 string from the file - abstract CountUtf8String: addr: int -> int - - /// Read a UTF8 string from the file - abstract ReadUTF8String: addr: int -> string - -/// An abstraction over how we access the contents of .NET binaries. May be backed by managed or unmanaged memory, -/// memory mapped file or by on-disk resources. +/// An abstraction over how we access the contents of .NET binaries. type BinaryFile = - /// Return a BinaryView for temporary use which eagerly holds any necessary memory resources for the duration of its lifetime, - /// and is faster to access byte-by-byte. The returned BinaryView should _not_ be captured in a closure that outlives the - /// desired lifetime. abstract GetView: unit -> BinaryView #if !FABLE_COMPILER - -/// A view over a raw pointer to memory -type RawMemoryView(obj: obj, start: nativeint, len: int) = - inherit BinaryView() - - override m.ReadByte i = - if nativeint i + 1n > nativeint len then failwithf "RawMemoryView overrun, i = %d, obj = %A" i obj - Marshal.ReadByte(start + nativeint i) - - override m.ReadBytes i n = - if nativeint i + nativeint n > nativeint len then failwithf "RawMemoryView overrun, i = %d, n = %d, obj = %A" i n obj - let res = Bytes.zeroCreate n - Marshal.Copy(start + nativeint i, res, 0, n) - res - - override m.ReadInt32 i = - if nativeint i + 4n > nativeint len then failwithf "RawMemoryView overrun, i = %d, obj = %A" i obj - Marshal.ReadInt32(start + nativeint i) - - override m.ReadUInt16 i = - if nativeint i + 2n > nativeint len then failwithf "RawMemoryView overrun, i = %d, obj = %A" i obj - uint16(Marshal.ReadInt16(start + nativeint i)) - - override m.CountUtf8String i = - if nativeint i > nativeint len then failwithf "RawMemoryView overrun, i = %d, obj = %A" i obj - let pStart = start + nativeint i - let mutable p = start - while Marshal.ReadByte(p) <> 0uy do - p <- p + 1n - int (p - pStart) - - override m.ReadUTF8String i = - let n = m.CountUtf8String i - if nativeint i + nativeint n > nativeint len then failwithf "RawMemoryView overrun, i = %d, n = %d, obj = %A" i n obj - System.Runtime.InteropServices.Marshal.PtrToStringAnsi(start + nativeint i, n) - - member __.HoldObj() = obj - - /// Gives views over a raw chunk of memory, for example those returned to us by the memory manager in Roslyn's /// Visual Studio integration. 'obj' must keep the memory alive. The object will capture it and thus also keep the memory alive for /// the lifetime of this object. type RawMemoryFile(fileName: string, obj: obj, addr: nativeint, length: int) = do stats.rawMemoryFileCount <- stats.rawMemoryFileCount + 1 - let view = RawMemoryView(obj, addr, length) + let view = ByteMemory.FromUnsafePointer(addr, length, obj).AsReadOnly() member __.HoldObj() = obj // make sure we capture 'obj' member __.FileName = fileName interface BinaryFile with - override __.GetView() = view :>_ - -/// Read from memory mapped files. -module MemoryMapping = - - type HANDLE = nativeint - type ADDR = nativeint - type SIZE_T = nativeint - - [] - extern bool CloseHandle (HANDLE _handler) - - [] - extern HANDLE CreateFile (string _lpFileName, - int _dwDesiredAccess, - int _dwShareMode, - HANDLE _lpSecurityAttributes, - int _dwCreationDisposition, - int _dwFlagsAndAttributes, - HANDLE _hTemplateFile) - - [] - extern HANDLE CreateFileMapping (HANDLE _hFile, - HANDLE _lpAttributes, - int _flProtect, - int _dwMaximumSizeLow, - int _dwMaximumSizeHigh, - string _lpName) - - [] - extern ADDR MapViewOfFile (HANDLE _hFileMappingObject, - int _dwDesiredAccess, - int _dwFileOffsetHigh, - int _dwFileOffsetLow, - SIZE_T _dwNumBytesToMap) - - [] - extern bool UnmapViewOfFile (ADDR _lpBaseAddress) - - let INVALID_HANDLE = new IntPtr(-1) - let MAP_READ = 0x0004 - let GENERIC_READ = 0x80000000 - let NULL_HANDLE = IntPtr.Zero - let FILE_SHARE_NONE = 0x0000 - let FILE_SHARE_READ = 0x0001 - let FILE_SHARE_WRITE = 0x0002 - let FILE_SHARE_READ_WRITE = 0x0003 - let CREATE_ALWAYS = 0x0002 - let OPEN_EXISTING = 0x0003 - let OPEN_ALWAYS = 0x0004 - -/// A view over a raw pointer to memory given by a memory mapped file. -/// NOTE: we should do more checking of validity here. -type MemoryMapView(start: nativeint) = - inherit BinaryView() - - override m.ReadByte i = - Marshal.ReadByte(start + nativeint i) - - override m.ReadBytes i n = - let res = Bytes.zeroCreate n - Marshal.Copy(start + nativeint i, res, 0, n) - res - - override m.ReadInt32 i = - Marshal.ReadInt32(start + nativeint i) - - override m.ReadUInt16 i = - uint16(Marshal.ReadInt16(start + nativeint i)) - - override m.CountUtf8String i = - let pStart = start + nativeint i - let mutable p = start - while Marshal.ReadByte(p) <> 0uy do - p <- p + 1n - int (p - pStart) - - override m.ReadUTF8String i = - let n = m.CountUtf8String i - System.Runtime.InteropServices.Marshal.PtrToStringAnsi(start + nativeint i, n) - -/// Memory maps a file and creates a single view over the entirety of its contents. The -/// lock on the file is only released when the object is disposed. -/// For memory mapping we currently take one view and never release it. -[] -type MemoryMapFile(fileName: string, view: MemoryMapView, hMap: MemoryMapping.HANDLE, hView: nativeint) = - - do stats.memoryMapFileOpenedCount <- stats.memoryMapFileOpenedCount + 1 - let mutable closed = false - static member Create fileName = - let hFile = MemoryMapping.CreateFile (fileName, MemoryMapping.GENERIC_READ, MemoryMapping.FILE_SHARE_READ_WRITE, IntPtr.Zero, MemoryMapping.OPEN_EXISTING, 0, IntPtr.Zero ) - if hFile.Equals(MemoryMapping.INVALID_HANDLE) then - failwithf "CreateFile(0x%08x)" (Marshal.GetHRForLastWin32Error()) - let protection = 0x00000002 - let hMap = MemoryMapping.CreateFileMapping (hFile, IntPtr.Zero, protection, 0, 0, null ) - ignore(MemoryMapping.CloseHandle(hFile)) - if hMap.Equals(MemoryMapping.NULL_HANDLE) then - failwithf "CreateFileMapping(0x%08x)" (Marshal.GetHRForLastWin32Error()) - - let hView = MemoryMapping.MapViewOfFile (hMap, MemoryMapping.MAP_READ, 0, 0, 0n) - - if hView.Equals(IntPtr.Zero) then - failwithf "MapViewOfFile(0x%08x)" (Marshal.GetHRForLastWin32Error()) - - let view = MemoryMapView(hView) - - MemoryMapFile(fileName, view, hMap, hView) - - member __.FileName = fileName - - member __.Close() = - stats.memoryMapFileClosedCount <- stats.memoryMapFileClosedCount + 1 - if not closed then - closed <- true - MemoryMapping.UnmapViewOfFile hView |> ignore - MemoryMapping.CloseHandle hMap |> ignore - - interface BinaryFile with - override __.GetView() = (view :> BinaryView) - + override __.GetView() = view #endif //!FABLE_COMPILER -/// Read file from memory blocks -type ByteView(bytes: byte[]) = - inherit BinaryView() - - override __.ReadByte addr = bytes.[addr] - - override __.ReadBytes addr len = Array.sub bytes addr len - - override __.CountUtf8String addr = - let mutable p = addr - while bytes.[p] <> 0uy do - p <- p + 1 - p - addr - - override bfv.ReadUTF8String addr = - let n = bfv.CountUtf8String addr - System.Text.Encoding.UTF8.GetString (bytes, addr, n) - - override bfv.ReadInt32 addr = - let b0 = bfv.ReadByte addr - let b1 = bfv.ReadByte (addr+1) - let b2 = bfv.ReadByte (addr+2) - let b3 = bfv.ReadByte (addr+3) - int b0 ||| (int b1 <<< 8) ||| (int b2 <<< 16) ||| (int b3 <<< 24) - - override bfv.ReadUInt16 addr = - let b0 = bfv.ReadByte addr - let b1 = bfv.ReadByte (addr+1) - uint16 b0 ||| (uint16 b1 <<< 8) - /// A BinaryFile backed by an array of bytes held strongly as managed memory [] type ByteFile(fileName: string, bytes: byte[]) = - let view = ByteView(bytes) + let view = ByteMemory.FromArray(bytes).AsReadOnly() do stats.byteFileCount <- stats.byteFileCount + 1 member __.FileName = fileName interface BinaryFile with - override bf.GetView() = view :> BinaryView + override bf.GetView() = view #if !FABLE_COMPILER - /// Same as ByteFile but holds the bytes weakly. The bytes will be re-read from the backing file when a view is requested. /// This is the default implementation used by F# Compiler Services when accessing "stable" binaries. It is not used /// by Visual Studio, where tryGetMetadataSnapshot provides a RawMemoryFile backed by Roslyn data. @@ -366,7 +159,7 @@ type WeakByteFile(fileName: string, chunk: (int * int) option) = do stats.weakByteFileCount <- stats.weakByteFileCount + 1 /// Used to check that the file hasn't changed - let fileStamp = FileSystem.GetLastWriteTimeShim(fileName) + let fileStamp = FileSystem.GetLastWriteTimeShim fileName /// The weak handle to the bytes for the file let weakBytes = new WeakReference (null) @@ -380,7 +173,7 @@ type WeakByteFile(fileName: string, chunk: (int * int) option) = let strongBytes = let mutable tg = null if not (weakBytes.TryGetTarget(&tg)) then - if FileSystem.GetLastWriteTimeShim(fileName) <> fileStamp then + if FileSystem.GetLastWriteTimeShim fileName <> fileStamp then error (Error (FSComp.SR.ilreadFileChanged fileName, range0)) let bytes = @@ -394,12 +187,11 @@ type WeakByteFile(fileName: string, chunk: (int * int) option) = tg - (ByteView(strongBytes) :> BinaryView) - + ByteMemory.FromArray(strongBytes).AsReadOnly() #endif //!FABLE_COMPILER -let seekReadByte (mdv: BinaryView) addr = mdv.ReadByte addr -let seekReadBytes (mdv: BinaryView) addr len = mdv.ReadBytes addr len +let seekReadByte (mdv: BinaryView) addr = mdv.[addr] +let seekReadBytes (mdv: BinaryView) addr len = mdv.ReadBytes(addr, len) let seekReadInt32 (mdv: BinaryView) addr = mdv.ReadInt32 addr let seekReadUInt16 (mdv: BinaryView) addr = mdv.ReadUInt16 addr @@ -543,7 +335,7 @@ let sigptrGetZInt32 bytes sigptr = let rec sigptrFoldAcc f n (bytes: byte[]) (sigptr: int) i acc = if i < n then let x, sp = f bytes sigptr - sigptrFoldAcc f n bytes sp (i+1) (x::acc) + sigptrFoldAcc f n bytes sp (i+1) (x :: acc) else List.rev acc, sigptr @@ -685,8 +477,8 @@ let instrs () = i_ldc_i4_s, I_i32_i8_instr (noPrefixes mkLdcInt32) i_ldc_r4, I_r4_instr (noPrefixes (fun x -> (AI_ldc (DT_R4, ILConst.R4 x)))) i_ldc_r8, I_r8_instr (noPrefixes (fun x -> (AI_ldc (DT_R8, ILConst.R8 x)))) - i_ldfld, I_field_instr (volatileOrUnalignedPrefix(fun (x, y) fspec -> I_ldfld(x, y, fspec))) - i_stfld, I_field_instr (volatileOrUnalignedPrefix(fun (x, y) fspec -> I_stfld(x, y, fspec))) + i_ldfld, I_field_instr (volatileOrUnalignedPrefix(fun (x, y) fspec -> I_ldfld (x, y, fspec))) + i_stfld, I_field_instr (volatileOrUnalignedPrefix(fun (x, y) fspec -> I_stfld (x, y, fspec))) i_ldsfld, I_field_instr (volatilePrefix (fun x fspec -> I_ldsfld (x, fspec))) i_stsfld, I_field_instr (volatilePrefix (fun x fspec -> I_stsfld (x, fspec))) i_ldflda, I_field_instr (noPrefixes I_ldflda) @@ -916,16 +708,11 @@ let mkCacheInt32 lowMem _inbase _nm _sz = | null -> cache := new Dictionary(11) | _ -> () !cache -#if FABLE_COMPILER - let ok, res = cache.TryGetValue(idx) -#else - let mutable res = Unchecked.defaultof<_> - let ok = cache.TryGetValue(idx, &res) -#endif - if ok then + match cache.TryGetValue idx with + | true, res -> incr count res - else + | _ -> let res = f idx cache.[idx] <- res res @@ -943,7 +730,7 @@ let mkCacheGeneric lowMem _inbase _nm _sz = | null -> cache := new Dictionary<_, _>(11 (* sz: int *) ) | _ -> () !cache - match cache.TryGetValue(idx) with + match cache.TryGetValue idx with | true, v -> incr count v @@ -989,37 +776,33 @@ let seekReadIndexedRows (numRows, rowReader, keyFunc, keyComparer, binaryChop, r // now read off rows, forward and backwards let mid = (low + high) / 2 // read forward - begin - let mutable fin = false - let mutable curr = mid - while not fin do - if curr > numRows then - fin <- true - else - let currrow = rowReader curr - if keyComparer (keyFunc currrow) = 0 then - res <- rowConverter currrow :: res - else - fin <- true - curr <- curr + 1 - done - end + let mutable fin = false + let mutable curr = mid + while not fin do + if curr > numRows then + fin <- true + else + let currrow = rowReader curr + if keyComparer (keyFunc currrow) = 0 then + res <- rowConverter currrow :: res + else + fin <- true + curr <- curr + 1 + res <- List.rev res // read backwards - begin - let mutable fin = false - let mutable curr = mid - 1 - while not fin do - if curr = 0 then + let mutable fin = false + let mutable curr = mid - 1 + while not fin do + if curr = 0 then fin <- true - else + else let currrow = rowReader curr if keyComparer (keyFunc currrow) = 0 then res <- rowConverter currrow :: res else fin <- true curr <- curr - 1 - end // sanity check #if CHECKING if checking then @@ -1046,7 +829,7 @@ let seekReadOptionalIndexedRow info = match seekReadIndexedRows info with | [k] -> Some k | [] -> None - | h::_ -> + | h :: _ -> dprintn ("multiple rows found when indexing table") Some h @@ -1089,8 +872,7 @@ type PEReader = [] type ILMetadataReader = - { ilg: ILGlobals - sorted: int64 + { sorted: int64 mdfile: BinaryFile pectxtCaptured: PEReader option // only set when reading full PE including code etc. for static linking entryPointToken: TableName * int @@ -1595,17 +1377,15 @@ let readBlobHeapAsDouble ctxt vidx = fst (sigptrGetDouble (readBlobHeap ctxt vid let readNativeResources (pectxt: PEReader) = [ if pectxt.nativeResourcesSize <> 0x0 && pectxt.nativeResourcesAddr <> 0x0 then let start = pectxt.anyV2P (pectxt.fileName + ": native resources", pectxt.nativeResourcesAddr) +#if !FABLE_COMPILER if pectxt.noFileOnDisk then -#if !FX_NO_LINKEDRESOURCES let unlinkedResource = let linkedResource = seekReadBytes (pectxt.pefile.GetView()) start pectxt.nativeResourcesSize unlinkResource pectxt.nativeResourcesAddr linkedResource yield ILNativeResource.Out unlinkedResource -#else - () -#endif else - yield ILNativeResource.In (pectxt.fileName, pectxt.nativeResourcesAddr, start, pectxt.nativeResourcesSize ) ] +#endif + yield ILNativeResource.In (pectxt.fileName, pectxt.nativeResourcesAddr, start, pectxt.nativeResourcesSize ) ] let getDataEndPointsDelayed (pectxt: PEReader) ctxtH = @@ -1614,7 +1394,7 @@ let getDataEndPointsDelayed (pectxt: PEReader) ctxtH = let mdv = ctxt.mdfile.GetView() let dataStartPoints = let res = ref [] - for i = 1 to ctxt.getNumRows (TableNames.FieldRVA) do + for i = 1 to ctxt.getNumRows TableNames.FieldRVA do let rva, _fidx = seekReadFieldRVARow ctxt mdv i res := ("field", rva) :: !res for i = 1 to ctxt.getNumRows TableNames.ManifestResource do @@ -1657,7 +1437,7 @@ let rvaToData (ctxt: ILMetadataReader) (pectxt: PEReader) nm rva = match l with | [] -> failwithf "find_text_data_extent: none found for fileName=%s, name=%s, rva=0x%08x, start=0x%08x" ctxt.fileName nm rva start - | e::t -> + | e :: t -> if start < e then let pev = pectxt.pefile.GetView() seekReadBytes pev start (e - start) @@ -1672,7 +1452,7 @@ let rvaToData (ctxt: ILMetadataReader) (pectxt: PEReader) nm rva = let isSorted (ctxt: ILMetadataReader) (tab: TableName) = ((ctxt.sorted &&& (int64 1 <<< tab.Index)) <> int64 0x0) // Note, pectxtEager and pevEager must not be captured by the results of this function -let rec seekReadModule (ctxt: ILMetadataReader) (pectxtEager: PEReader) pevEager peinfo ilMetadataVersion idx = +let rec seekReadModule (ctxt: ILMetadataReader) canReduceMemory (pectxtEager: PEReader) pevEager peinfo ilMetadataVersion idx = let (subsys, subsysversion, useHighEntropyVA, ilOnly, only32, is32bitpreferred, only64, platform, isDll, alignVirt, alignPhys, imageBaseReal) = peinfo let mdv = ctxt.mdfile.GetView() let (_generation, nameIdx, _mvidIdx, _encidIdx, _encbaseidIdx) = seekReadModuleRow ctxt mdv idx @@ -1680,7 +1460,7 @@ let rec seekReadModule (ctxt: ILMetadataReader) (pectxtEager: PEReader) pevEager let nativeResources = readNativeResources pectxtEager { Manifest = - if ctxt.getNumRows (TableNames.Assembly) > 0 then Some (seekReadAssemblyManifest ctxt pectxtEager 1) + if ctxt.getNumRows TableNames.Assembly > 0 then Some (seekReadAssemblyManifest ctxt pectxtEager 1) else None CustomAttrsStored = ctxt.customAttrsReader_Module MetadataIndex = idx @@ -1701,7 +1481,7 @@ let rec seekReadModule (ctxt: ILMetadataReader) (pectxtEager: PEReader) pevEager PhysicalAlignment = alignPhys ImageBase = imageBaseReal MetadataVersion = ilMetadataVersion - Resources = seekReadManifestResources ctxt mdv pectxtEager pevEager } + Resources = seekReadManifestResources ctxt canReduceMemory mdv pectxtEager pevEager } and seekReadAssemblyManifest (ctxt: ILMetadataReader) pectxt idx = let mdview = ctxt.mdfile.GetView() @@ -1712,7 +1492,7 @@ and seekReadAssemblyManifest (ctxt: ILMetadataReader) pectxt idx = AuxModuleHashAlgorithm=hash SecurityDeclsStored= ctxt.securityDeclsReader_Assembly PublicKey= pubkey - Version= Some (v1, v2, v3, v4) + Version= Some (ILVersionInfo (v1, v2, v3, v4)) Locale= readStringHeapOption ctxt localeIdx CustomAttrsStored = ctxt.customAttrsReader_Assembly MetadataIndex = idx @@ -1745,15 +1525,15 @@ and seekReadAssemblyRefUncached ctxtH idx = | Some blob -> Some (if (flags &&& 0x0001) <> 0x0 then PublicKey blob else PublicKeyToken blob) ILAssemblyRef.Create - (name=nm, - hash=readBlobHeapOption ctxt hashValueIdx, - publicKey=publicKey, - retargetable=((flags &&& 0x0100) <> 0x0), - version=Some(v1, v2, v3, v4), - locale=readStringHeapOption ctxt localeIdx) + (name = nm, + hash = readBlobHeapOption ctxt hashValueIdx, + publicKey = publicKey, + retargetable = ((flags &&& 0x0100) <> 0x0), + version = Some (ILVersionInfo (v1, v2, v3, v4)), + locale = readStringHeapOption ctxt localeIdx) and seekReadModuleRef (ctxt: ILMetadataReader) mdv idx = - let (nameIdx) = seekReadModuleRefRow ctxt mdv idx + let nameIdx = seekReadModuleRefRow ctxt mdv idx ILModuleRef.Create(name = readStringHeap ctxt nameIdx, hasMetadata=true, hash=None) and seekReadFile (ctxt: ILMetadataReader) mdv idx = @@ -1761,7 +1541,14 @@ and seekReadFile (ctxt: ILMetadataReader) mdv idx = ILModuleRef.Create(name = readStringHeap ctxt nameIdx, hasMetadata= ((flags &&& 0x0001) = 0x0), hash= readBlobHeapOption ctxt hashValueIdx) and seekReadClassLayout (ctxt: ILMetadataReader) mdv idx = - match seekReadOptionalIndexedRow (ctxt.getNumRows TableNames.ClassLayout, seekReadClassLayoutRow ctxt mdv, (fun (_, _, tidx) -> tidx), simpleIndexCompare idx, isSorted ctxt TableNames.ClassLayout, (fun (pack, size, _) -> pack, size)) with + let res = + seekReadOptionalIndexedRow (ctxt.getNumRows TableNames.ClassLayout, + seekReadClassLayoutRow ctxt mdv, + (fun (_, _, tidx) -> tidx), + simpleIndexCompare idx, + isSorted ctxt TableNames.ClassLayout, + (fun (pack, size, _) -> pack, size)) + match res with | None -> { Size = None; Pack = None } | Some (pack, size) -> { Size = Some size; Pack = Some pack } @@ -1974,7 +1761,7 @@ and seekReadTypeDefOrRefAsTypeRef (ctxt: ILMetadataReader) (TaggedIndex(tag, idx | tag when tag = tdor_TypeRef -> seekReadTypeRef ctxt idx | tag when tag = tdor_TypeSpec -> dprintn ("type spec used where a type ref or def is required") - ctxt.ilg.typ_Object.TypeRef + primaryAssemblyILGlobals.typ_Object.TypeRef | _ -> failwith "seekReadTypeDefOrRefAsTypeRef_readTypeDefOrRefOrSpec" and seekReadMethodRefParent (ctxt: ILMetadataReader) mdv numtypars (TaggedIndex(tag, idx)) = @@ -2072,14 +1859,16 @@ and seekReadFields (ctxt: ILMetadataReader) (numtypars, hasLayout) fidx1 fidx2 = mkILFieldsLazy (lazy let mdv = ctxt.mdfile.GetView() - [ for i = fidx1 to fidx2 - 1 do - yield seekReadField ctxt mdv (numtypars, hasLayout) i ]) + [ if fidx1 > 0 then + for i = fidx1 to fidx2 - 1 do + yield seekReadField ctxt mdv (numtypars, hasLayout) i ]) and seekReadMethods (ctxt: ILMetadataReader) numtypars midx1 midx2 = mkILMethodsComputed (fun () -> let mdv = ctxt.mdfile.GetView() - [| for i = midx1 to midx2 - 1 do - yield seekReadMethod ctxt mdv numtypars i |]) + [| if midx1 > 0 then + for i = midx1 to midx2 - 1 do + yield seekReadMethod ctxt mdv numtypars i |]) and sigptrGetTypeDefOrRefOrSpecIdx bytes sigptr = let n, sigptr = sigptrGetZInt32 bytes sigptr @@ -2090,22 +1879,22 @@ and sigptrGetTypeDefOrRefOrSpecIdx bytes sigptr = and sigptrGetTy (ctxt: ILMetadataReader) numtypars bytes sigptr = let b0, sigptr = sigptrGetByte bytes sigptr - if b0 = et_OBJECT then ctxt.ilg.typ_Object, sigptr - elif b0 = et_STRING then ctxt.ilg.typ_String, sigptr - elif b0 = et_I1 then ctxt.ilg.typ_SByte, sigptr - elif b0 = et_I2 then ctxt.ilg.typ_Int16, sigptr - elif b0 = et_I4 then ctxt.ilg.typ_Int32, sigptr - elif b0 = et_I8 then ctxt.ilg.typ_Int64, sigptr - elif b0 = et_I then ctxt.ilg.typ_IntPtr, sigptr - elif b0 = et_U1 then ctxt.ilg.typ_Byte, sigptr - elif b0 = et_U2 then ctxt.ilg.typ_UInt16, sigptr - elif b0 = et_U4 then ctxt.ilg.typ_UInt32, sigptr - elif b0 = et_U8 then ctxt.ilg.typ_UInt64, sigptr - elif b0 = et_U then ctxt.ilg.typ_UIntPtr, sigptr - elif b0 = et_R4 then ctxt.ilg.typ_Single, sigptr - elif b0 = et_R8 then ctxt.ilg.typ_Double, sigptr - elif b0 = et_CHAR then ctxt.ilg.typ_Char, sigptr - elif b0 = et_BOOLEAN then ctxt.ilg.typ_Bool, sigptr + if b0 = et_OBJECT then primaryAssemblyILGlobals.typ_Object, sigptr + elif b0 = et_STRING then primaryAssemblyILGlobals.typ_String, sigptr + elif b0 = et_I1 then primaryAssemblyILGlobals.typ_SByte, sigptr + elif b0 = et_I2 then primaryAssemblyILGlobals.typ_Int16, sigptr + elif b0 = et_I4 then primaryAssemblyILGlobals.typ_Int32, sigptr + elif b0 = et_I8 then primaryAssemblyILGlobals.typ_Int64, sigptr + elif b0 = et_I then primaryAssemblyILGlobals.typ_IntPtr, sigptr + elif b0 = et_U1 then primaryAssemblyILGlobals.typ_Byte, sigptr + elif b0 = et_U2 then primaryAssemblyILGlobals.typ_UInt16, sigptr + elif b0 = et_U4 then primaryAssemblyILGlobals.typ_UInt32, sigptr + elif b0 = et_U8 then primaryAssemblyILGlobals.typ_UInt64, sigptr + elif b0 = et_U then primaryAssemblyILGlobals.typ_UIntPtr, sigptr + elif b0 = et_R4 then primaryAssemblyILGlobals.typ_Single, sigptr + elif b0 = et_R8 then primaryAssemblyILGlobals.typ_Double, sigptr + elif b0 = et_CHAR then primaryAssemblyILGlobals.typ_Char, sigptr + elif b0 = et_BOOLEAN then primaryAssemblyILGlobals.typ_Bool, sigptr elif b0 = et_WITH then let b0, sigptr = sigptrGetByte bytes sigptr let tdorIdx, sigptr = sigptrGetTypeDefOrRefOrSpecIdx bytes sigptr @@ -2151,8 +1940,7 @@ and sigptrGetTy (ctxt: ILMetadataReader) numtypars bytes sigptr = elif b0 = et_VOID then ILType.Void, sigptr elif b0 = et_TYPEDBYREF then - let t = mkILNonGenericValueTy(mkILTyRef(ctxt.ilg.primaryAssemblyScopeRef, "System.TypedReference")) - t, sigptr + primaryAssemblyILGlobals.typ_TypedReference, sigptr elif b0 = et_CMOD_REQD || b0 = et_CMOD_OPT then let tdorIdx, sigptr = sigptrGetTypeDefOrRefOrSpecIdx bytes sigptr let ty, sigptr = sigptrGetTy ctxt numtypars bytes sigptr @@ -2182,10 +1970,10 @@ and sigptrGetArgTys (ctxt: ILMetadataReader) n numtypars bytes sigptr acc = let b0, sigptr2 = sigptrGetByte bytes sigptr if b0 = et_SENTINEL then let varargs, sigptr = sigptrGetVarArgTys ctxt n numtypars bytes sigptr2 - (List.rev acc, Some(varargs)), sigptr + (List.rev acc, Some varargs), sigptr else let x, sigptr = sigptrGetTy ctxt numtypars bytes sigptr - sigptrGetArgTys ctxt (n-1) numtypars bytes sigptr (x::acc) + sigptrGetArgTys ctxt (n-1) numtypars bytes sigptr (x :: acc) and sigptrGetLocal (ctxt: ILMetadataReader) numtypars bytes sigptr = let pinned, sigptr = @@ -2517,7 +2305,7 @@ and seekReadoptional_MethodSemantics ctxt id = match seekReadMultipleMethodSemantics ctxt id with | [] -> None | [h] -> Some h - | h::_ -> dprintn "multiple method semantics found"; Some h + | h :: _ -> dprintn "multiple method semantics found"; Some h and seekReadMethodSemantics ctxt id = match seekReadoptional_MethodSemantics ctxt id with @@ -2551,8 +2339,9 @@ and seekReadEvents (ctxt: ILMetadataReader) numtypars tidx = let (_, endEventIdx) = seekReadEventMapRow ctxt mdv (rowNum + 1) endEventIdx - [ for i in beginEventIdx .. endEventIdx - 1 do - yield seekReadEvent ctxt mdv numtypars i ]) + [ if beginEventIdx > 0 then + for i in beginEventIdx .. endEventIdx - 1 do + yield seekReadEvent ctxt mdv numtypars i ]) and seekReadProperty ctxt mdv numtypars idx = let (flags, nameIdx, typIdx) = seekReadPropertyRow ctxt mdv idx @@ -2593,8 +2382,9 @@ and seekReadProperties (ctxt: ILMetadataReader) numtypars tidx = else let (_, endPropIdx) = seekReadPropertyMapRow ctxt mdv (rowNum + 1) endPropIdx - [ for i in beginPropIdx .. endPropIdx - 1 do - yield seekReadProperty ctxt mdv numtypars i ]) + [ if beginPropIdx > 0 then + for i in beginPropIdx .. endPropIdx - 1 do + yield seekReadProperty ctxt mdv numtypars i ]) and customAttrsReader ctxtH tag: ILAttributesStored = @@ -2647,7 +2437,7 @@ and seekReadConstant (ctxt: ILMetadataReader) idx = | x when x = uint16 et_STRING -> let blobHeap = readBlobHeap ctxt vidx let s = System.Text.Encoding.Unicode.GetString(blobHeap, 0, blobHeap.Length) - ILFieldInit.String (s) + ILFieldInit.String s | x when x = uint16 et_BOOLEAN -> ILFieldInit.Bool (readBlobHeapAsBool ctxt vidx) | x when x = uint16 et_CHAR -> ILFieldInit.Char (readBlobHeapAsUInt16 ctxt vidx) | x when x = uint16 et_I1 -> ILFieldInit.Int8 (readBlobHeapAsSByte ctxt vidx) @@ -2720,15 +2510,11 @@ and seekReadImplMap (ctxt: ILMetadataReader) nm midx = and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz: int) start seqpoints = let labelsOfRawOffsets = new Dictionary<_, _>(sz/2) let ilOffsetsOfLabels = new Dictionary<_, _>(sz/2) - let tryRawToLabel rawOffset = - match labelsOfRawOffsets.TryGetValue(rawOffset) with - | true, v -> Some v - | _ -> None - + let rawToLabel rawOffset = - match tryRawToLabel rawOffset with - | Some l -> l - | None -> + match labelsOfRawOffsets.TryGetValue rawOffset with + | true, l -> l + | _ -> let lab = generateCodeLabel() labelsOfRawOffsets.[rawOffset] <- lab lab @@ -2888,7 +2674,7 @@ and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz: int) start s let (tab, idx) = seekReadUncodedToken pev (start + (!curr)) curr := !curr + 4 if tab <> TableNames.UserStrings then dprintn "warning: bad table in user string for ldstr" - f prefixes (readUserStringHeap ctxt (idx)) + f prefixes (readUserStringHeap ctxt idx) | I_conditional_i32_instr f -> let offsDest = (seekReadInt32 pev (start + (!curr))) @@ -2957,9 +2743,9 @@ and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz: int) start s // the start of the next instruction referred to by the raw offset. let raw2nextLab rawOffset = let isInstrStart x = - match tryRawToLabel x with - | None -> false - | Some lab -> ilOffsetsOfLabels.ContainsKey lab + match labelsOfRawOffsets.TryGetValue x with + | true, lab -> ilOffsetsOfLabels.ContainsKey lab + | _ -> false if isInstrStart rawOffset then rawToLabel rawOffset elif isInstrStart (rawOffset+1) then rawToLabel (rawOffset+1) else failwith ("the bytecode raw offset "+string rawOffset+" did not refer either to the start or end of an instruction") @@ -2992,12 +2778,13 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int let pdbm = pdbReaderGetMethod pdbr (uncodedToken TableNames.Method idx) let sps = pdbMethodGetSequencePoints pdbm - (*dprintf "#sps for 0x%x = %d\n" (uncodedToken TableNames.Method idx) (Array.length sps) *) (* let roota, rootb = pdbScopeGetOffsets rootScope in *) let seqpoints = let arr = sps |> Array.map (fun sp -> - (* It is VERY annoying to have to call GetURL for the document for each sequence point. This appears to be a short coming of the PDB reader API. They should return an index into the array of documents for the reader *) + // It is VERY annoying to have to call GetURL for the document for + // each sequence point. This appears to be a short coming of the PDB + // reader API. They should return an index into the array of documents for the reader let sourcedoc = get_doc (pdbDocumentGetURL sp.pdbSeqPointDocument) let source = ILSourceMarker.Create(document = sourcedoc, @@ -3159,7 +2946,7 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int end let key = (tryStart, tryFinish) - match sehMap.TryGetValue(key) with + match sehMap.TryGetValue key with | true, prev -> sehMap.[key] <- prev @ [clause] | _ -> sehMap.[key] <- [clause]) clauses @@ -3208,24 +2995,24 @@ and sigptrGetILNativeType ctxt bytes sigptr = List.assoc ntbyte (Lazy.force ILNativeTypeMap), sigptr elif ntbyte = 0x0uy then ILNativeType.Empty, sigptr elif ntbyte = nt_CUSTOMMARSHALER then - // reading native type blob (CM1), sigptr= "+string sigptr+ ", bytes.Length = "+string bytes.Length) + // reading native type blob CM1, sigptr= "+string sigptr+ ", bytes.Length = "+string bytes.Length) let guidLen, sigptr = sigptrGetZInt32 bytes sigptr - // reading native type blob (CM2), sigptr= "+string sigptr+", guidLen = "+string ( guidLen)) + // reading native type blob CM2, sigptr= "+string sigptr+", guidLen = "+string ( guidLen)) let guid, sigptr = sigptrGetBytes ( guidLen) bytes sigptr - // reading native type blob (CM3), sigptr= "+string sigptr) + // reading native type blob CM3, sigptr= "+string sigptr) let nativeTypeNameLen, sigptr = sigptrGetZInt32 bytes sigptr - // reading native type blob (CM4), sigptr= "+string sigptr+", nativeTypeNameLen = "+string ( nativeTypeNameLen)) + // reading native type blob CM4, sigptr= "+string sigptr+", nativeTypeNameLen = "+string ( nativeTypeNameLen)) let nativeTypeName, sigptr = sigptrGetString ( nativeTypeNameLen) bytes sigptr - // reading native type blob (CM4), sigptr= "+string sigptr+", nativeTypeName = "+nativeTypeName) - // reading native type blob (CM5), sigptr= "+string sigptr) + // reading native type blob CM4, sigptr= "+string sigptr+", nativeTypeName = "+nativeTypeName) + // reading native type blob CM5, sigptr= "+string sigptr) let custMarshallerNameLen, sigptr = sigptrGetZInt32 bytes sigptr - // reading native type blob (CM6), sigptr= "+string sigptr+", custMarshallerNameLen = "+string ( custMarshallerNameLen)) + // reading native type blob CM6, sigptr= "+string sigptr+", custMarshallerNameLen = "+string ( custMarshallerNameLen)) let custMarshallerName, sigptr = sigptrGetString ( custMarshallerNameLen) bytes sigptr - // reading native type blob (CM7), sigptr= "+string sigptr+", custMarshallerName = "+custMarshallerName) + // reading native type blob CM7, sigptr= "+string sigptr+", custMarshallerName = "+custMarshallerName) let cookieStringLen, sigptr = sigptrGetZInt32 bytes sigptr - // reading native type blob (CM8), sigptr= "+string sigptr+", cookieStringLen = "+string ( cookieStringLen)) + // reading native type blob CM8, sigptr= "+string sigptr+", cookieStringLen = "+string ( cookieStringLen)) let cookieString, sigptr = sigptrGetBytes ( cookieStringLen) bytes sigptr - // reading native type blob (CM9), sigptr= "+string sigptr) + // reading native type blob CM9, sigptr= "+string sigptr) ILNativeType.Custom (guid, nativeTypeName, custMarshallerName, cookieString), sigptr elif ntbyte = nt_FIXEDSYSSTRING then let i, sigptr = sigptrGetZInt32 bytes sigptr @@ -3265,12 +3052,12 @@ and sigptrGetILNativeType ctxt bytes sigptr = let additive, sigptr = if sigptr >= bytes.Length then 0, sigptr else sigptrGetZInt32 bytes sigptr - ILNativeType.Array (Some nt, Some(pnum, Some(additive))), sigptr + ILNativeType.Array (Some nt, Some(pnum, Some additive)), sigptr else (ILNativeType.Empty, sigptr) - + // Note, pectxtEager and pevEager must not be captured by the results of this function // As a result, reading the resource offsets in the physical file is done eagerly to avoid holding on to any resources -and seekReadManifestResources (ctxt: ILMetadataReader) (mdv: BinaryView) (pectxtEager: PEReader) (pevEager: BinaryView) = +and seekReadManifestResources (ctxt: ILMetadataReader) canReduceMemory (mdv: BinaryView) (pectxtEager: PEReader) (pevEager: BinaryView) = mkILResources [ for i = 1 to ctxt.getNumRows TableNames.ManifestResource do let (offset, flags, nameIdx, implIdx) = seekReadManifestResourceRow ctxt mdv i @@ -3283,17 +3070,22 @@ and seekReadManifestResources (ctxt: ILMetadataReader) (mdv: BinaryView) (pectxt let start = pectxtEager.anyV2P ("resource", offset + pectxtEager.resourcesAddr) let resourceLength = seekReadInt32 pevEager start let offsetOfBytesFromStartOfPhysicalPEFile = start + 4 + let bytes = + let bytes = pevEager.Slice(offsetOfBytesFromStartOfPhysicalPEFile, resourceLength) #if FABLE_COMPILER - let bytes = seekReadBytes pevEager offsetOfBytesFromStartOfPhysicalPEFile resourceLength - ILResourceLocation.LocalOut bytes + ignore canReduceMemory #else - if pectxtEager.noFileOnDisk then - ILResourceLocation.LocalOut (seekReadBytes pevEager offsetOfBytesFromStartOfPhysicalPEFile resourceLength) - else - ILResourceLocation.LocalIn (ctxt.fileName, offsetOfBytesFromStartOfPhysicalPEFile, resourceLength) + // If we are trying to reduce memory, create a memory mapped file based on the contents. + if canReduceMemory then + ByteMemory.CreateMemoryMappedFile bytes + else #endif + ByteMemory.FromArray(bytes.ToArray()) + ILResourceLocation.Local(bytes.AsReadOnly()) + | ILScopeRef.Module mref -> ILResourceLocation.File (mref, offset) | ILScopeRef.Assembly aref -> ILResourceLocation.Assembly aref + | _ -> failwith "seekReadManifestResources: Invalid ILScopeRef" let r = { Name= readStringHeap ctxt nameIdx @@ -3369,7 +3161,7 @@ let getPdbReader pdbDirPath fileName = file = url)) let docfun url = - match tab.TryGetValue(url) with + match tab.TryGetValue url with | true, doc -> doc | _ -> failwith ("Document with URL " + url + " not found in list of documents in the PDB file") Some (pdbr, docfun) @@ -3377,7 +3169,7 @@ let getPdbReader pdbDirPath fileName = #endif // Note, pectxtEager and pevEager must not be captured by the results of this function -let openMetadataReader (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, pectxtEager: PEReader, pevEager: BinaryView, pectxtCaptured, reduceMemoryUsage, ilGlobals) = +let openMetadataReader (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, pectxtEager: PEReader, pevEager, pectxtCaptured, reduceMemoryUsage) = let mdv = mdfile.GetView() let magic = seekReadUInt16AsInt32 mdv metadataPhysLoc if magic <> 0x5342 then failwith (fileName + ": bad metadata magic number: " + string magic) @@ -3650,11 +3442,11 @@ let openMetadataReader (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, p let inbase = Filename.fileNameOfPath fileName + ": " // All the caches. The sizes are guesstimates for the rough sharing-density of the assembly - let cacheAssemblyRef = mkCacheInt32 reduceMemoryUsage inbase "ILAssemblyRef" (getNumRows TableNames.AssemblyRef) + let cacheAssemblyRef = mkCacheInt32 false inbase "ILAssemblyRef" (getNumRows TableNames.AssemblyRef) let cacheMethodSpecAsMethodData = mkCacheGeneric reduceMemoryUsage inbase "MethodSpecAsMethodData" (getNumRows TableNames.MethodSpec / 20 + 1) let cacheMemberRefAsMemberData = mkCacheGeneric reduceMemoryUsage inbase "MemberRefAsMemberData" (getNumRows TableNames.MemberRef / 20 + 1) let cacheCustomAttr = mkCacheGeneric reduceMemoryUsage inbase "CustomAttr" (getNumRows TableNames.CustomAttribute / 50 + 1) - let cacheTypeRef = mkCacheInt32 reduceMemoryUsage inbase "ILTypeRef" (getNumRows TableNames.TypeRef / 20 + 1) + let cacheTypeRef = mkCacheInt32 false inbase "ILTypeRef" (getNumRows TableNames.TypeRef / 20 + 1) let cacheTypeRefAsType = mkCacheGeneric reduceMemoryUsage inbase "TypeRefAsType" (getNumRows TableNames.TypeRef / 20 + 1) let cacheBlobHeapAsPropertySig = mkCacheGeneric reduceMemoryUsage inbase "BlobHeapAsPropertySig" (getNumRows TableNames.Property / 20 + 1) let cacheBlobHeapAsFieldSig = mkCacheGeneric reduceMemoryUsage inbase "BlobHeapAsFieldSig" (getNumRows TableNames.Field / 20 + 1) @@ -3683,8 +3475,7 @@ let openMetadataReader (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, p // Use an initialization hole let ctxtH = ref None let ctxt: ILMetadataReader = - { ilg=ilGlobals - sorted=sorted + { sorted=sorted getNumRows=getNumRows mdfile=mdfile dataEndPoints = match pectxtCaptured with None -> notlazy [] | Some pectxt -> getDataEndPointsDelayed pectxt ctxtH @@ -3754,7 +3545,7 @@ let openMetadataReader (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, p tableBigness=tableBigness } ctxtH := Some ctxt - let ilModule = seekReadModule ctxt pectxtEager pevEager peinfo (System.Text.Encoding.UTF8.GetString (ilMetadataVersion, 0, ilMetadataVersion.Length)) 1 + let ilModule = seekReadModule ctxt reduceMemoryUsage pectxtEager pevEager peinfo (System.Text.Encoding.UTF8.GetString (ilMetadataVersion, 0, ilMetadataVersion.Length)) 1 let ilAssemblyRefs = lazy [ for i in 1 .. getNumRows TableNames.AssemblyRef do yield seekReadAssemblyRef ctxt i ] ilModule, ilAssemblyRefs @@ -3784,7 +3575,7 @@ let openPEFileReader (fileName, pefile: BinaryFile, pdbDirPath, noFileOnDisk) = optHeaderSize <> 0xf0 then failwith "not a PE file - bad optional header size" let x64adjust = optHeaderSize - 0xe0 let only64 = (optHeaderSize = 0xf0) (* May want to read in the optional header Magic number and check that as well... *) - let platform = match machine with | 0x8664 -> Some(AMD64) | 0x200 -> Some(IA64) | _ -> Some(X86) + let platform = match machine with | 0x8664 -> Some AMD64 | 0x200 -> Some IA64 | _ -> Some X86 let sectionHeadersStartPhysLoc = peOptionalHeaderPhysLoc + optHeaderSize let flags = seekReadUInt16AsInt32 pev (peFileHeaderPhysLoc + 18) @@ -3962,13 +3753,13 @@ let openPEFileReader (fileName, pefile: BinaryFile, pdbDirPath, noFileOnDisk) = let peinfo = (subsys, (subsysMajor, subsysMinor), useHighEnthropyVA, ilOnly, only32, is32bitpreferred, only64, platform, isDll, alignVirt, alignPhys, imageBaseReal) (metadataPhysLoc, metadataSize, peinfo, pectxt, pev, pdb) -let openPE (fileName, pefile, pdbDirPath, reduceMemoryUsage, ilGlobals, noFileOnDisk) = +let openPE (fileName, pefile, pdbDirPath, reduceMemoryUsage, noFileOnDisk) = let (metadataPhysLoc, _metadataSize, peinfo, pectxt, pev, pdb) = openPEFileReader (fileName, pefile, pdbDirPath, noFileOnDisk) - let ilModule, ilAssemblyRefs = openMetadataReader (fileName, pefile, metadataPhysLoc, peinfo, pectxt, pev, Some pectxt, reduceMemoryUsage, ilGlobals) + let ilModule, ilAssemblyRefs = openMetadataReader (fileName, pefile, metadataPhysLoc, peinfo, pectxt, pev, Some pectxt, reduceMemoryUsage) ilModule, ilAssemblyRefs, pdb -let openPEMetadataOnly (fileName, peinfo, pectxtEager, pev, mdfile: BinaryFile, reduceMemoryUsage, ilGlobals) = - openMetadataReader (fileName, mdfile, 0, peinfo, pectxtEager, pev, None, reduceMemoryUsage, ilGlobals) +let openPEMetadataOnly (fileName, peinfo, pectxtEager, pevEager, mdfile: BinaryFile, reduceMemoryUsage) = + openMetadataReader (fileName, mdfile, 0, peinfo, pectxtEager, pevEager, None, reduceMemoryUsage) let ClosePdbReader pdb = #if FX_NO_PDB_READER @@ -3991,7 +3782,6 @@ type ReduceMemoryFlag = Yes | No type ILReaderOptions = { pdbDirPath: string option - ilGlobals: ILGlobals reduceMemoryUsage: ReduceMemoryFlag metadataOnly: MetadataOnlyFlag tryGetMetadataSnapshot: ILReaderTryGetMetadataSnapshot } @@ -4016,16 +3806,25 @@ type ILModuleReaderImpl(ilModule: ILModuleDef, ilAssemblyRefs: Lazy BinaryFile - let ilModule, ilAssemblyRefs, pdb = openPE (fileName, pefile, opts.pdbDirPath, (opts.reduceMemoryUsage = ReduceMemoryFlag.Yes), opts.ilGlobals, true) + let ilModule, ilAssemblyRefs, pdb = openPE (fileName, pefile, opts.pdbDirPath, (opts.reduceMemoryUsage = ReduceMemoryFlag.Yes), true) new ILModuleReaderImpl(ilModule, ilAssemblyRefs, (fun () -> ClosePdbReader pdb)) :> ILModuleReader #else // ++GLOBAL MUTABLE STATE (concurrency safe via locking) -type ILModuleReaderCacheLockToken() = interface LockToken -type ILModuleReaderCacheKey = ILModuleReaderCacheKey of string * DateTime * ILScopeRef * bool * ReduceMemoryFlag * MetadataOnlyFlag -let ilModuleReaderCache = new AgedLookup(stronglyHeldReaderCacheSize, areSimilar=(fun (x, y) -> x = y)) -let ilModuleReaderCacheLock = Lock() +type ILModuleReaderCacheKey = ILModuleReaderCacheKey of string * DateTime * bool * ReduceMemoryFlag * MetadataOnlyFlag + +// Cache to extend the lifetime of a limited number of readers that are otherwise eligible for GC +type ILModuleReaderCache1LockToken() = interface LockToken +let ilModuleReaderCache1 = + new AgedLookup + (stronglyHeldReaderCacheSize, + keepMax=stronglyHeldReaderCacheSize, // only strong entries + areSimilar=(fun (x, y) -> x = y)) +let ilModuleReaderCache1Lock = Lock() + +// // Cache to reuse readers that have already been created and are not yet GC'd +let ilModuleReaderCache2 = new ConcurrentDictionary>(HashIdentity.Structural) let stableFileHeuristicApplies fileName = not noStableFileHeuristic && try FileSystem.IsStableFileHeuristic fileName with _ -> false @@ -4042,49 +3841,70 @@ let createByteFileChunk opts fileName chunk = | Some (start, length) -> File.ReadBinaryChunk(fileName, start, length) ByteFile(fileName, bytes) :> BinaryFile -let tryMemoryMapWholeFile opts fileName = - let file = - try - MemoryMapFile.Create fileName :> BinaryFile - with _ -> - createByteFileChunk opts fileName None - let disposer = - { new IDisposable with - member __.Dispose() = - match file with - | :? MemoryMapFile as m -> m.Close() // Note that the PE file reader is not required after this point for metadata-only reading - | _ -> () } - disposer, file +let createMemoryMapFile fileName = + let mmf, accessor, length = + let fileStream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read) + let length = fileStream.Length + let mmf = MemoryMappedFile.CreateFromFile(fileStream, null, length, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen=false) + mmf, mmf.CreateViewAccessor(0L, fileStream.Length, MemoryMappedFileAccess.Read), length + let safeHolder = + { new obj() with + override x.Finalize() = + (x :?> IDisposable).Dispose() + interface IDisposable with + member x.Dispose() = + GC.SuppressFinalize x + accessor.Dispose() + mmf.Dispose() + stats.memoryMapFileClosedCount <- stats.memoryMapFileClosedCount + 1 } + stats.memoryMapFileOpenedCount <- stats.memoryMapFileOpenedCount + 1 + safeHolder, RawMemoryFile(fileName, safeHolder, accessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), int length) :> BinaryFile let OpenILModuleReaderFromBytes fileName bytes opts = let pefile = ByteFile(fileName, bytes) :> BinaryFile - let ilModule, ilAssemblyRefs, pdb = openPE (fileName, pefile, opts.pdbDirPath, (opts.reduceMemoryUsage = ReduceMemoryFlag.Yes), opts.ilGlobals, true) + let ilModule, ilAssemblyRefs, pdb = openPE (fileName, pefile, opts.pdbDirPath, (opts.reduceMemoryUsage = ReduceMemoryFlag.Yes), true) new ILModuleReaderImpl(ilModule, ilAssemblyRefs, (fun () -> ClosePdbReader pdb)) :> ILModuleReader +let ClearAllILModuleReaderCache() = + ilModuleReaderCache1.Clear(ILModuleReaderCache1LockToken()) + ilModuleReaderCache2.Clear() + let OpenILModuleReader fileName opts = // Pseudo-normalize the paths. - let (ILModuleReaderCacheKey (fullPath,writeStamp,_,_,_,_) as key), keyOk = + let (ILModuleReaderCacheKey (fullPath,writeStamp,_,_,_) as key), keyOk = try - let fullPath = FileSystem.GetFullPathShim(fileName) - let writeTime = FileSystem.GetLastWriteTimeShim(fileName) - let key = ILModuleReaderCacheKey (fullPath, writeTime, opts.ilGlobals.primaryAssemblyScopeRef, opts.pdbDirPath.IsSome, opts.reduceMemoryUsage, opts.metadataOnly) + let fullPath = FileSystem.GetFullPathShim fileName + let writeTime = FileSystem.GetLastWriteTimeShim fileName + let key = ILModuleReaderCacheKey (fullPath, writeTime, opts.pdbDirPath.IsSome, opts.reduceMemoryUsage, opts.metadataOnly) key, true with exn -> System.Diagnostics.Debug.Assert(false, sprintf "Failed to compute key in OpenILModuleReader cache for '%s'. Falling back to uncached. Error = %s" fileName (exn.ToString())) - let fakeKey = ILModuleReaderCacheKey(fileName, System.DateTime.UtcNow, ILScopeRef.Local, false, ReduceMemoryFlag.Yes, MetadataOnlyFlag.Yes) + let fakeKey = ILModuleReaderCacheKey(fileName, System.DateTime.UtcNow, false, ReduceMemoryFlag.Yes, MetadataOnlyFlag.Yes) fakeKey, false - let cacheResult = - if keyOk then - if opts.pdbDirPath.IsSome then None // can't used a cached entry when reading PDBs, since it makes the returned object IDisposable - else ilModuleReaderCacheLock.AcquireLock (fun ltok -> ilModuleReaderCache.TryGet(ltok, key)) + let cacheResult1 = + // can't used a cached entry when reading PDBs, since it makes the returned object IDisposable + if keyOk && opts.pdbDirPath.IsNone then + ilModuleReaderCache1Lock.AcquireLock (fun ltok -> ilModuleReaderCache1.TryGet(ltok, key)) else None - - match cacheResult with + + match cacheResult1 with | Some ilModuleReader -> ilModuleReader | None -> + let cacheResult2 = + // can't used a cached entry when reading PDBs, since it makes the returned object IDisposable + if keyOk && opts.pdbDirPath.IsNone then + ilModuleReaderCache2.TryGetValue key + else + false, Unchecked.defaultof<_> + + let mutable res = Unchecked.defaultof<_> + match cacheResult2 with + | true, weak when weak.TryGetTarget(&res) -> res + | _ -> + let reduceMemoryUsage = (opts.reduceMemoryUsage = ReduceMemoryFlag.Yes) let metadataOnly = (opts.metadataOnly = MetadataOnlyFlag.Yes) @@ -4104,7 +3924,7 @@ let OpenILModuleReader fileName opts = // For metadata-only, always use a temporary, short-lived PE file reader, preferably over a memory mapped file. // Then use the metadata blob as the long-lived memory resource. - let disposer, pefileEager = tryMemoryMapWholeFile opts fullPath + let disposer, pefileEager = createMemoryMapFile fullPath use _disposer = disposer let (metadataPhysLoc, metadataSize, peinfo, pectxtEager, pevEager, _pdb) = openPEFileReader (fullPath, pefileEager, None, false) let mdfile = @@ -4114,19 +3934,21 @@ let OpenILModuleReader fileName opts = // If tryGetMetadata doesn't give anything, then just read the metadata chunk out of the binary createByteFileChunk opts fullPath (Some (metadataPhysLoc, metadataSize)) - let ilModule, ilAssemblyRefs = openPEMetadataOnly (fullPath, peinfo, pectxtEager, pevEager, mdfile, reduceMemoryUsage, opts.ilGlobals) + let ilModule, ilAssemblyRefs = openPEMetadataOnly (fullPath, peinfo, pectxtEager, pevEager, mdfile, reduceMemoryUsage) new ILModuleReaderImpl(ilModule, ilAssemblyRefs, ignore) else // If we are not doing metadata-only, then just go ahead and read all the bytes and hold them either strongly or weakly // depending on the heuristic let pefile = createByteFileChunk opts fullPath None - let ilModule, ilAssemblyRefs, _pdb = openPE (fullPath, pefile, None, reduceMemoryUsage, opts.ilGlobals, false) + let ilModule, ilAssemblyRefs, _pdb = openPE (fullPath, pefile, None, reduceMemoryUsage, false) new ILModuleReaderImpl(ilModule, ilAssemblyRefs, ignore) + let ilModuleReader = ilModuleReader :> ILModuleReader if keyOk then - ilModuleReaderCacheLock.AcquireLock (fun ltok -> ilModuleReaderCache.Put(ltok, key, ilModuleReader)) - - ilModuleReader :> ILModuleReader + ilModuleReaderCache1Lock.AcquireLock (fun ltok -> ilModuleReaderCache1.Put(ltok, key, ilModuleReader)) + ilModuleReaderCache2.[key] <- System.WeakReference<_>(ilModuleReader) + ilModuleReader + else // This case is primarily used in fsc.exe. @@ -4139,26 +3961,27 @@ let OpenILModuleReader fileName opts = // We do however care about avoiding locks on files that prevent their deletion during a // multi-proc build. So use memory mapping, but only for stable files. Other files // still use an in-memory ByteFile - let _disposer, pefile = + let pefile = if alwaysMemoryMapFSC || stableFileHeuristicApplies fullPath then - tryMemoryMapWholeFile opts fullPath + let _, pefile = createMemoryMapFile fullPath + pefile else - let pefile = createByteFileChunk opts fullPath None - let disposer = { new IDisposable with member __.Dispose() = () } - disposer, pefile + createByteFileChunk opts fullPath None - let ilModule, ilAssemblyRefs, pdb = openPE (fullPath, pefile, opts.pdbDirPath, reduceMemoryUsage, opts.ilGlobals, false) + let ilModule, ilAssemblyRefs, pdb = openPE (fullPath, pefile, opts.pdbDirPath, reduceMemoryUsage, false) let ilModuleReader = new ILModuleReaderImpl(ilModule, ilAssemblyRefs, (fun () -> ClosePdbReader pdb)) + let ilModuleReader = ilModuleReader :> ILModuleReader + // Readers with PDB reader disposal logic don't go in the cache. Note the PDB reader is only used in static linking. if keyOk && opts.pdbDirPath.IsNone then - ilModuleReaderCacheLock.AcquireLock (fun ltok -> ilModuleReaderCache.Put(ltok, key, ilModuleReader)) + ilModuleReaderCache1Lock.AcquireLock (fun ltok -> ilModuleReaderCache1.Put(ltok, key, ilModuleReader)) + ilModuleReaderCache2.[key] <- WeakReference<_>(ilModuleReader) - ilModuleReader :> ILModuleReader + ilModuleReader [] module Shim = - open FSharp.Compiler.Lib type IAssemblyReader = abstract GetILModuleReader: filename: string * readerOptions: ILReaderOptions -> ILModuleReader diff --git a/src/fcs-fable/src/absil/ilread.fsi b/src/fcs-fable/src/absil/ilread.fsi old mode 100755 new mode 100644 index 9119e16c91..0ce9cc22a5 --- a/src/fcs-fable/src/absil/ilread.fsi +++ b/src/fcs-fable/src/absil/ilread.fsi @@ -46,8 +46,6 @@ type ReduceMemoryFlag = Yes | No type ILReaderOptions = { pdbDirPath: string option - ilGlobals: ILGlobals - // fsc.exe does not use reduceMemoryUsage (hence keeps MORE caches in AbstractIL and MORE memory mapping and MORE memory hogging but FASTER and SIMPLER file access) // fsi.exe does uses reduceMemoryUsage (hence keeps FEWER caches in AbstractIL and LESS memory mapping and LESS memory hogging but slightly SLOWER file access), because its long running // FCS uses reduceMemoryUsage (hence keeps FEWER caches in AbstractIL and LESS memory mapping and LESS memory hogging), because it is typically long running @@ -75,10 +73,14 @@ type ILModuleReader = inherit System.IDisposable #if !FABLE_COMPILER + /// Open a binary reader, except first copy the entire contents of the binary into /// memory, close the file and ensure any subsequent reads happen from the in-memory store. /// PDB files may not be read with this option. val internal OpenILModuleReader: string -> ILReaderOptions -> ILModuleReader + +val internal ClearAllILModuleReaderCache : unit -> unit + #endif /// Open a binary reader based on the given bytes. diff --git a/src/fcs-fable/src/absil/ilreflect.fs b/src/fcs-fable/src/absil/ilreflect.fs old mode 100755 new mode 100644 index 474997be4e..7f048dd5b9 --- a/src/fcs-fable/src/absil/ilreflect.fs +++ b/src/fcs-fable/src/absil/ilreflect.fs @@ -8,6 +8,7 @@ module internal FSharp.Compiler.AbstractIL.ILRuntimeWriter open System +open System.IO open System.Reflection open System.Reflection.Emit open System.Runtime.InteropServices @@ -16,21 +17,16 @@ open System.Collections.Generic open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.AbstractIL.Internal.Utils open FSharp.Compiler.AbstractIL.Diagnostics open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Range - -open Microsoft.FSharp.Core.Printf - -#if FX_RESHAPED_REFLECTION -open Microsoft.FSharp.Core.ReflectionAdapters -#endif +open FSharp.Core.Printf let codeLabelOrder = ComparisonIdentity.Structural // Convert the output of convCustomAttr -open FSharp.Compiler.AbstractIL.ILAsciiWriter let wrapCustomAttr setCustomAttr (cinfo, bytes) = setCustomAttr(cinfo, bytes) @@ -42,163 +38,163 @@ let wrapCustomAttr setCustomAttr (cinfo, bytes) = let logRefEmitCalls = false type System.Reflection.Emit.AssemblyBuilder with - member asmB.DefineDynamicModuleAndLog(a, b, c) = + member asmB.DefineDynamicModuleAndLog (a, b, c) = #if FX_RESHAPED_REFEMIT ignore b ignore c - let modB = asmB.DefineDynamicModule(a) + let modB = asmB.DefineDynamicModule a #else let modB = asmB.DefineDynamicModule(a, b, c) if logRefEmitCalls then printfn "let moduleBuilder%d = assemblyBuilder%d.DefineDynamicModule(%A, %A, %A)" (abs <| hash modB) (abs <| hash asmB) a b c #endif modB - member asmB.SetCustomAttributeAndLog(cinfo, bytes) = + member asmB.SetCustomAttributeAndLog (cinfo, bytes) = if logRefEmitCalls then printfn "assemblyBuilder%d.SetCustomAttribute(%A, %A)" (abs <| hash asmB) cinfo bytes wrapCustomAttr asmB.SetCustomAttribute (cinfo, bytes) #if !FX_RESHAPED_REFEMIT - member asmB.AddResourceFileAndLog(nm1, nm2, attrs) = + member asmB.AddResourceFileAndLog (nm1, nm2, attrs) = if logRefEmitCalls then printfn "assemblyBuilder%d.AddResourceFile(%A, %A, enum %d)" (abs <| hash asmB) nm1 nm2 (LanguagePrimitives.EnumToValue attrs) asmB.AddResourceFile(nm1, nm2, attrs) #endif - member asmB.SetCustomAttributeAndLog(cab) = + member asmB.SetCustomAttributeAndLog cab = if logRefEmitCalls then printfn "assemblyBuilder%d.SetCustomAttribute(%A)" (abs <| hash asmB) cab - asmB.SetCustomAttribute(cab) + asmB.SetCustomAttribute cab type System.Reflection.Emit.ModuleBuilder with - member modB.GetArrayMethodAndLog(aty, nm, flags, rty, tys) = + member modB.GetArrayMethodAndLog (aty, nm, flags, rty, tys) = if logRefEmitCalls then printfn "moduleBuilder%d.GetArrayMethod(%A, %A, %A, %A, %A)" (abs <| hash modB) aty nm flags rty tys modB.GetArrayMethod(aty, nm, flags, rty, tys) #if !FX_RESHAPED_REFEMIT - member modB.DefineDocumentAndLog(file, lang, vendor, doctype) = + member modB.DefineDocumentAndLog (file, lang, vendor, doctype) = let symDoc = modB.DefineDocument(file, lang, vendor, doctype) if logRefEmitCalls then printfn "let docWriter%d = moduleBuilder%d.DefineDocument(@%A, System.Guid(\"%A\"), System.Guid(\"%A\"), System.Guid(\"%A\"))" (abs <| hash symDoc) (abs <| hash modB) file lang vendor doctype symDoc #endif - member modB.GetTypeAndLog(nameInModule, flag1, flag2) = + member modB.GetTypeAndLog (nameInModule, flag1, flag2) = if logRefEmitCalls then printfn "moduleBuilder%d.GetType(%A, %A, %A) |> ignore" (abs <| hash modB) nameInModule flag1 flag2 modB.GetType(nameInModule, flag1, flag2) - member modB.DefineTypeAndLog(name, attrs) = + member modB.DefineTypeAndLog (name, attrs) = let typB = modB.DefineType(name, attrs) if logRefEmitCalls then printfn "let typeBuilder%d = moduleBuilder%d.DefineType(%A, enum %d)" (abs <| hash typB) (abs <| hash modB) name (LanguagePrimitives.EnumToValue attrs) typB #if !FX_RESHAPED_REFEMIT - member modB.DefineManifestResourceAndLog(name, stream, attrs) = + member modB.DefineManifestResourceAndLog (name, stream, attrs) = if logRefEmitCalls then printfn "moduleBuilder%d.DefineManifestResource(%A, %A, enum %d)" (abs <| hash modB) name stream (LanguagePrimitives.EnumToValue attrs) modB.DefineManifestResource(name, stream, attrs) #endif - member modB.SetCustomAttributeAndLog(cinfo, bytes) = + member modB.SetCustomAttributeAndLog (cinfo, bytes) = if logRefEmitCalls then printfn "moduleBuilder%d.SetCustomAttribute(%A, %A)" (abs <| hash modB) cinfo bytes wrapCustomAttr modB.SetCustomAttribute (cinfo, bytes) type System.Reflection.Emit.ConstructorBuilder with - member consB.SetImplementationFlagsAndLog(attrs) = + member consB.SetImplementationFlagsAndLog attrs = if logRefEmitCalls then printfn "constructorBuilder%d.SetImplementationFlags(enum %d)" (abs <| hash consB) (LanguagePrimitives.EnumToValue attrs) - consB.SetImplementationFlags(attrs) + consB.SetImplementationFlags attrs - member consB.DefineParameterAndLog(n, attr, nm) = + member consB.DefineParameterAndLog (n, attr, nm) = if logRefEmitCalls then printfn "constructorBuilder%d.DefineParameter(%d, enum %d, %A)" (abs <| hash consB) n (LanguagePrimitives.EnumToValue attr) nm consB.DefineParameter(n, attr, nm) - member consB.GetILGeneratorAndLog() = + member consB.GetILGeneratorAndLog () = let ilG = consB.GetILGenerator() if logRefEmitCalls then printfn "let ilg%d = constructorBuilder%d.GetILGenerator()" (abs <| hash ilG) (abs <| hash consB) ilG type System.Reflection.Emit.MethodBuilder with - member methB.SetImplementationFlagsAndLog(attrs) = + member methB.SetImplementationFlagsAndLog attrs = if logRefEmitCalls then printfn "methodBuilder%d.SetImplementationFlags(enum %d)" (abs <| hash methB) (LanguagePrimitives.EnumToValue attrs) - methB.SetImplementationFlags(attrs) + methB.SetImplementationFlags attrs - member methB.SetSignatureAndLog(returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers,parameterTypeOptionalCustomModifiers) = + member methB.SetSignatureAndLog (returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers,parameterTypeOptionalCustomModifiers) = if logRefEmitCalls then printfn "methodBuilder%d.SetSignature(...)" (abs <| hash methB) methB.SetSignature(returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers,parameterTypeOptionalCustomModifiers) - member methB.DefineParameterAndLog(n, attr, nm) = + member methB.DefineParameterAndLog (n, attr, nm) = if logRefEmitCalls then printfn "methodBuilder%d.DefineParameter(%d, enum %d, %A)" (abs <| hash methB) n (LanguagePrimitives.EnumToValue attr) nm methB.DefineParameter(n, attr, nm) - member methB.DefineGenericParametersAndLog(gps) = + member methB.DefineGenericParametersAndLog gps = if logRefEmitCalls then printfn "let gps%d = methodBuilder%d.DefineGenericParameters(%A)" (abs <| hash methB) (abs <| hash methB) gps - methB.DefineGenericParameters(gps) + methB.DefineGenericParameters gps - member methB.GetILGeneratorAndLog() = + member methB.GetILGeneratorAndLog () = let ilG = methB.GetILGenerator() if logRefEmitCalls then printfn "let ilg%d = methodBuilder%d.GetILGenerator()" (abs <| hash ilG) (abs <| hash methB) ilG - member methB.SetCustomAttributeAndLog(cinfo, bytes) = + member methB.SetCustomAttributeAndLog (cinfo, bytes) = if logRefEmitCalls then printfn "methodBuilder%d.SetCustomAttribute(%A, %A)" (abs <| hash methB) cinfo bytes wrapCustomAttr methB.SetCustomAttribute (cinfo, bytes) type System.Reflection.Emit.TypeBuilder with - member typB.CreateTypeAndLog() = + member typB.CreateTypeAndLog () = if logRefEmitCalls then printfn "typeBuilder%d.CreateType()" (abs <| hash typB) #if FX_RESHAPED_REFEMIT typB.CreateTypeInfo().AsType() #else typB.CreateType() #endif - member typB.DefineNestedTypeAndLog(name, attrs) = + member typB.DefineNestedTypeAndLog (name, attrs) = let res = typB.DefineNestedType(name, attrs) if logRefEmitCalls then printfn "let typeBuilder%d = typeBuilder%d.DefineNestedType(\"%s\", enum %d)" (abs <| hash res) (abs <| hash typB) name (LanguagePrimitives.EnumToValue attrs) res - member typB.DefineMethodAndLog(name, attrs, cconv) = + member typB.DefineMethodAndLog (name, attrs, cconv) = let methB = typB.DefineMethod(name, attrs, cconv) if logRefEmitCalls then printfn "let methodBuilder%d = typeBuilder%d.DefineMethod(\"%s\", enum %d, enum %d)" (abs <| hash methB) (abs <| hash typB) name (LanguagePrimitives.EnumToValue attrs) (LanguagePrimitives.EnumToValue cconv) methB - member typB.DefineGenericParametersAndLog(gps) = + member typB.DefineGenericParametersAndLog gps = if logRefEmitCalls then printfn "typeBuilder%d.DefineGenericParameters(%A)" (abs <| hash typB) gps - typB.DefineGenericParameters(gps) + typB.DefineGenericParameters gps - member typB.DefineConstructorAndLog(attrs, cconv, parms) = + member typB.DefineConstructorAndLog (attrs, cconv, parms) = let consB = typB.DefineConstructor(attrs, cconv, parms) if logRefEmitCalls then printfn "let constructorBuilder%d = typeBuilder%d.DefineConstructor(enum %d, CallingConventions.%A, %A)" (abs <| hash consB) (abs <| hash typB) (LanguagePrimitives.EnumToValue attrs) cconv parms consB - member typB.DefineFieldAndLog(nm, ty: System.Type, attrs) = + member typB.DefineFieldAndLog (nm, ty: System.Type, attrs) = let fieldB = typB.DefineField(nm, ty, attrs) if logRefEmitCalls then printfn "let fieldBuilder%d = typeBuilder%d.DefineField(\"%s\", typeof<%s>, enum %d)" (abs <| hash fieldB) (abs <| hash typB) nm ty.FullName (LanguagePrimitives.EnumToValue attrs) fieldB - member typB.DefinePropertyAndLog(nm, attrs, ty: System.Type, args) = + member typB.DefinePropertyAndLog (nm, attrs, ty: System.Type, args) = if logRefEmitCalls then printfn "typeBuilder%d.DefineProperty(\"%A\", enum %d, typeof<%s>, %A)" (abs <| hash typB) nm (LanguagePrimitives.EnumToValue attrs) ty.FullName args typB.DefineProperty(nm, attrs, ty, args) - member typB.DefineEventAndLog(nm, attrs, ty: System.Type) = + member typB.DefineEventAndLog (nm, attrs, ty: System.Type) = if logRefEmitCalls then printfn "typeBuilder%d.DefineEvent(\"%A\", enum %d, typeof<%A>)" (abs <| hash typB) nm (LanguagePrimitives.EnumToValue attrs) ty.FullName typB.DefineEvent(nm, attrs, ty) - member typB.SetParentAndLog(ty: System.Type) = + member typB.SetParentAndLog (ty: System.Type) = if logRefEmitCalls then printfn "typeBuilder%d.SetParent(typeof<%s>)" (abs <| hash typB) ty.FullName - typB.SetParent(ty) + typB.SetParent ty - member typB.AddInterfaceImplementationAndLog(ty) = + member typB.AddInterfaceImplementationAndLog ty = if logRefEmitCalls then printfn "typeBuilder%d.AddInterfaceImplementation(%A)" (abs <| hash typB) ty - typB.AddInterfaceImplementation(ty) + typB.AddInterfaceImplementation ty - member typB.InvokeMemberAndLog(nm, _flags, args) = + member typB.InvokeMemberAndLog (nm, _flags, args) = #if FX_RESHAPED_REFEMIT - let t = typB.CreateTypeAndLog() + let t = typB.CreateTypeAndLog () let m = if t <> null then t.GetMethod(nm, (args |> Seq.map(fun x -> x.GetType()) |> Seq.toArray)) else null if m <> null then m.Invoke(null, args) - else raise (MissingMethodException(nm)) + else raise (MissingMethodException nm) #else if logRefEmitCalls then printfn "typeBuilder%d.InvokeMember(\"%s\", enum %d, null, null, %A, Globalization.CultureInfo.InvariantCulture)" (abs <| hash typB) nm (LanguagePrimitives.EnumToValue _flags) args typB.InvokeMember(nm, _flags, null, null, args, Globalization.CultureInfo.InvariantCulture) #endif - member typB.SetCustomAttributeAndLog(cinfo, bytes) = + member typB.SetCustomAttributeAndLog (cinfo, bytes) = if logRefEmitCalls then printfn "typeBuilder%d.SetCustomAttribute(%A, %A)" (abs <| hash typB) cinfo bytes wrapCustomAttr typB.SetCustomAttribute (cinfo, bytes) @@ -207,51 +203,51 @@ type System.Reflection.Emit.OpCode with member opcode.RefEmitName = (string (System.Char.ToUpper(opcode.Name.[0])) + opcode.Name.[1..]).Replace(".", "_").Replace("_i4", "_I4") type System.Reflection.Emit.ILGenerator with - member ilG.DeclareLocalAndLog(ty: System.Type, isPinned) = + member ilG.DeclareLocalAndLog (ty: System.Type, isPinned) = if logRefEmitCalls then printfn "ilg%d.DeclareLocal(typeof<%s>, %b)" (abs <| hash ilG) ty.FullName isPinned ilG.DeclareLocal(ty, isPinned) - member ilG.MarkLabelAndLog(lab) = + member ilG.MarkLabelAndLog lab = if logRefEmitCalls then printfn "ilg%d.MarkLabel(label%d_%d)" (abs <| hash ilG) (abs <| hash ilG) (abs <| hash lab) - ilG.MarkLabel(lab) + ilG.MarkLabel lab #if !FX_RESHAPED_REFEMIT - member ilG.MarkSequencePointAndLog(symDoc, l1, c1, l2, c2) = + member ilG.MarkSequencePointAndLog (symDoc, l1, c1, l2, c2) = if logRefEmitCalls then printfn "ilg%d.MarkSequencePoint(docWriter%d, %A, %A, %A, %A)" (abs <| hash ilG) (abs <| hash symDoc) l1 c1 l2 c2 ilG.MarkSequencePoint(symDoc, l1, c1, l2, c2) #endif - member ilG.BeginExceptionBlockAndLog() = + member ilG.BeginExceptionBlockAndLog () = if logRefEmitCalls then printfn "ilg%d.BeginExceptionBlock()" (abs <| hash ilG) ilG.BeginExceptionBlock() - member ilG.EndExceptionBlockAndLog() = + member ilG.EndExceptionBlockAndLog () = if logRefEmitCalls then printfn "ilg%d.EndExceptionBlock()" (abs <| hash ilG) ilG.EndExceptionBlock() - member ilG.BeginFinallyBlockAndLog() = + member ilG.BeginFinallyBlockAndLog () = if logRefEmitCalls then printfn "ilg%d.BeginFinallyBlock()" (abs <| hash ilG) ilG.BeginFinallyBlock() - member ilG.BeginCatchBlockAndLog(ty) = + member ilG.BeginCatchBlockAndLog ty = if logRefEmitCalls then printfn "ilg%d.BeginCatchBlock(%A)" (abs <| hash ilG) ty - ilG.BeginCatchBlock(ty) + ilG.BeginCatchBlock ty - member ilG.BeginExceptFilterBlockAndLog() = + member ilG.BeginExceptFilterBlockAndLog () = if logRefEmitCalls then printfn "ilg%d.BeginExceptFilterBlock()" (abs <| hash ilG) ilG.BeginExceptFilterBlock() - member ilG.BeginFaultBlockAndLog() = + member ilG.BeginFaultBlockAndLog () = if logRefEmitCalls then printfn "ilg%d.BeginFaultBlock()" (abs <| hash ilG) ilG.BeginFaultBlock() - member ilG.DefineLabelAndLog() = + member ilG.DefineLabelAndLog () = let lab = ilG.DefineLabel() if logRefEmitCalls then printfn "let label%d_%d = ilg%d.DefineLabel()" (abs <| hash ilG) (abs <| hash lab) (abs <| hash ilG) lab member x.EmitAndLog (op: OpCode) = if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s)" (abs <| hash x) op.RefEmitName - x.Emit(op) + x.Emit op member x.EmitAndLog (op: OpCode, v: Label) = if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s, label%d_%d)" (abs <| hash x) op.RefEmitName (abs <| hash x) (abs <| hash v) x.Emit(op, v) @@ -287,7 +283,7 @@ let inline flagsIf b x = if b then x else enum 0 module Zmap = let force x m str = match Zmap.tryFind x m with Some y -> y | None -> failwithf "Zmap.force: %s: x = %+A" str x -let equalTypes (s: Type) (t: Type) = s.Equals(t) +let equalTypes (s: Type) (t: Type) = s.Equals t let equalTypeLists ss tt = List.lengthsEqAndForall2 equalTypes ss tt let equalTypeArrays ss tt = Array.lengthsEqAndForall2 equalTypes ss tt @@ -308,16 +304,14 @@ let convAssemblyRef (aref: ILAssemblyRef) = asmName.Name <- aref.Name (match aref.PublicKey with | None -> () - | Some (PublicKey bytes) -> asmName.SetPublicKey(bytes) - | Some (PublicKeyToken bytes) -> asmName.SetPublicKeyToken(bytes)) - let setVersion (major, minor, build, rev) = - asmName.Version <- System.Version (int32 major, int32 minor, int32 build, int32 rev) + | Some (PublicKey bytes) -> asmName.SetPublicKey bytes + | Some (PublicKeyToken bytes) -> asmName.SetPublicKeyToken bytes) + let setVersion (version: ILVersionInfo) = + asmName.Version <- System.Version (int32 version.Major, int32 version.Minor, int32 version.Build, int32 version.Revision) Option.iter setVersion aref.Version // asmName.ProcessorArchitecture <- System.Reflection.ProcessorArchitecture.MSIL -#if !FX_RESHAPED_GLOBALIZATION - //Option.iter (fun name -> asmName.CultureInfo <- System.Globalization.CultureInfo.CreateSpecificCulture(name)) aref.Locale + //Option.iter (fun name -> asmName.CultureInfo <- System.Globalization.CultureInfo.CreateSpecificCulture name) aref.Locale asmName.CultureInfo <- System.Globalization.CultureInfo.InvariantCulture -#endif asmName /// The global environment. @@ -327,6 +321,23 @@ type cenv = generatePdb: bool resolveAssemblyRef: (ILAssemblyRef -> Choice option) } + override x.ToString() = "" + +let convResolveAssemblyRef (cenv: cenv) (asmref: ILAssemblyRef) qualifiedName = + let assembly = + match cenv.resolveAssemblyRef asmref with + | Some (Choice1Of2 path) -> + FileSystem.AssemblyLoadFrom path + | Some (Choice2Of2 assembly) -> + assembly + | None -> + let asmName = convAssemblyRef asmref + FileSystem.AssemblyLoad asmName + let typT = assembly.GetType qualifiedName + match typT with + | null -> error(Error(FSComp.SR.itemNotFoundDuringDynamicCodeGen ("type", qualifiedName, asmref.QualifiedName), range0)) + | res -> res + /// Convert an Abstract IL type reference to Reflection.Emit System.Type value. // This ought to be an adequate substitute for this whole function, but it needs // to be thoroughly tested. @@ -338,25 +349,15 @@ let convTypeRefAux (cenv: cenv) (tref: ILTypeRef) = let qualifiedName = (String.concat "+" (tref.Enclosing @ [ tref.Name ])).Replace(",", @"\,") match tref.Scope with | ILScopeRef.Assembly asmref -> - let assembly = - match cenv.resolveAssemblyRef asmref with - | Some (Choice1Of2 path) -> - FileSystem.AssemblyLoadFrom(path) - | Some (Choice2Of2 assembly) -> - assembly - | None -> - let asmName = convAssemblyRef asmref - FileSystem.AssemblyLoad(asmName) - let typT = assembly.GetType(qualifiedName) - match typT with - | null -> error(Error(FSComp.SR.itemNotFoundDuringDynamicCodeGen ("type", qualifiedName, asmref.QualifiedName), range0)) - | res -> res + convResolveAssemblyRef cenv asmref qualifiedName | ILScopeRef.Module _ | ILScopeRef.Local _ -> - let typT = Type.GetType(qualifiedName) + let typT = Type.GetType qualifiedName match typT with | null -> error(Error(FSComp.SR.itemNotFoundDuringDynamicCodeGen ("type", qualifiedName, ""), range0)) | res -> res + | ILScopeRef.PrimaryAssembly -> + convResolveAssemblyRef cenv cenv.ilg.primaryAssemblyRef qualifiedName @@ -403,7 +404,7 @@ let envUpdateCreatedTypeRef emEnv (tref: ILTypeRef) = // The (TypeBuilder :> Type) does not implement all the methods that a Type proper does. let typT, typB, typeDef, _createdTypOpt = Zmap.force tref emEnv.emTypMap "envGetTypeDef: failed" if typB.IsCreated() then - let ty = typB.CreateTypeAndLog() + let ty = typB.CreateTypeAndLog () #if ENABLE_MONO_SUPPORT // Mono has a bug where executing code that includes an array type // match "match x with :? C[] -> ..." before the full loading of an object of type @@ -413,7 +414,7 @@ let envUpdateCreatedTypeRef emEnv (tref: ILTypeRef) = // a constructor. It is not usable in partial trust code. if runningOnMono && ty.IsClass && not ty.IsAbstract && not ty.IsGenericType && not ty.IsGenericTypeDefinition then try - System.Runtime.Serialization.FormatterServices.GetUninitializedObject(ty) |> ignore + System.Runtime.Serialization.FormatterServices.GetUninitializedObject ty |> ignore with e -> () #endif {emEnv with emTypMap = Zmap.add tref (typT, typB, typeDef, Some ty) emEnv.emTypMap} @@ -477,11 +478,13 @@ let envGetLabel emEnv name = Zmap.find name emEnv.emLabels let envPushTyvars emEnv tys = {emEnv with emTyvars = tys :: emEnv.emTyvars} + let envPopTyvars emEnv = {emEnv with emTyvars = List.tail emEnv.emTyvars} + let envGetTyvar emEnv u16 = match emEnv.emTyvars with | [] -> failwith "envGetTyvar: not scope of type vars" - | tvs::_ -> + | tvs :: _ -> let i = int32 u16 if i<0 || i>= Array.length tvs then failwith (sprintf "want tyvar #%d, but only had %d tyvars" i (Array.length tvs)) @@ -490,7 +493,8 @@ let envGetTyvar emEnv u16 = let isEmittedTypeRef emEnv tref = Zmap.mem tref emEnv.emTypMap -let envAddEntryPt emEnv mref = {emEnv with emEntryPts = mref::emEnv.emEntryPts} +let envAddEntryPt emEnv mref = {emEnv with emEntryPts = mref :: emEnv.emEntryPts} + let envPopEntryPts emEnv = {emEnv with emEntryPts = []}, emEnv.emEntryPts //---------------------------------------------------------------------------- @@ -660,9 +664,6 @@ let TypeBuilderInstantiationT = ty let typeIsNotQueryable (ty: Type) = -#if FX_RESHAPED_REFLECTION - let ty = ty.GetTypeInfo() -#endif (ty :? TypeBuilder) || ((ty.GetType()).Equals(TypeBuilderInstantiationT)) //---------------------------------------------------------------------------- // convFieldSpec @@ -704,7 +705,7 @@ let convFieldSpec cenv emEnv fspec = // convMethodRef //---------------------------------------------------------------------------- let queryableTypeGetMethodBySearch cenv emEnv parentT (mref: ILMethodRef) = - assert(not (typeIsNotQueryable(parentT))) + assert(not (typeIsNotQueryable parentT)) let cconv = (if mref.CallingConv.IsStatic then BindingFlags.Static else BindingFlags.Instance) let methInfos = parentT.GetMethods(cconv ||| BindingFlags.Public ||| BindingFlags.NonPublic) |> Array.toList (* First, filter on name, if unique, then binding "done" *) @@ -737,12 +738,12 @@ let queryableTypeGetMethodBySearch cenv emEnv parentT (mref: ILMethodRef) = else Array.forall2 satisfiesParameter args ps let select (methInfo: MethodInfo) = - (* mref implied Types *) + // mref implied Types let mtyargTIs = getGenericArgumentsOfMethod methInfo if mtyargTIs.Length <> mref.GenericArity then false (* method generic arity mismatch *) else - (* methInfo implied Types *) + // methInfo implied Types let methodParameters = methInfo.GetParameters() let argTypes = mref.ArgTypes |> List.toArray if argTypes.Length <> methodParameters.Length then false (* method argument length mismatch *) else @@ -776,7 +777,7 @@ let queryableTypeGetMethodBySearch cenv emEnv parentT (mref: ILMethodRef) = | Some methInfo -> methInfo (* return MethodInfo for (generic) type's (generic) method *) let queryableTypeGetMethod cenv emEnv parentT (mref: ILMethodRef) = - assert(not (typeIsNotQueryable(parentT))) + assert(not (typeIsNotQueryable parentT)) if mref.GenericArity = 0 then let tyargTs = getGenericArgumentsOfType parentT let argTs, resT = @@ -791,11 +792,7 @@ let queryableTypeGetMethod cenv emEnv parentT (mref: ILMethodRef) = parentT.GetMethod(mref.Name, cconv ||| BindingFlags.Public ||| BindingFlags.NonPublic, null, argTs, -#if FX_RESHAPED_REFLECTION - (null: obj[])) -#else (null: ParameterModifier[])) -#endif // This can fail if there is an ambiguity w.r.t. return type with _ -> null if (isNonNull methInfo && equalTypes resT methInfo.ReturnType) then @@ -847,10 +844,7 @@ let convMethodSpec cenv emEnv (mspec: ILMethodSpec) = methInfo methInfo -//---------------------------------------------------------------------------- -// - QueryableTypeGetConstructors: get a constructor on a non-TypeBuilder type -//---------------------------------------------------------------------------- - +/// Get a constructor on a non-TypeBuilder type let queryableTypeGetConstructor cenv emEnv (parentT: Type) (mref: ILMethodRef) = let tyargTs = getGenericArgumentsOfType parentT let reqArgTs = @@ -865,10 +859,7 @@ let queryableTypeGetConstructor cenv emEnv (parentT: Type) (mref: ILMethodRef) = let nonQueryableTypeGetConstructor (parentTI: Type) (consInfo: ConstructorInfo) : ConstructorInfo = if parentTI.IsGenericType then TypeBuilder.GetConstructor(parentTI, consInfo) else consInfo -//---------------------------------------------------------------------------- -// convConstructorSpec (like convMethodSpec) -//---------------------------------------------------------------------------- - +/// convConstructorSpec (like convMethodSpec) let convConstructorSpec cenv emEnv (mspec: ILMethodSpec) = let mref = mspec.MethodRef let parentTI = convType cenv emEnv mspec.DeclaringType @@ -888,38 +879,30 @@ let convConstructorSpec cenv emEnv (mspec: ILMethodSpec) = | null -> error(Error(FSComp.SR.itemNotFoundInTypeDuringDynamicCodeGen ("constructor", "", parentTI.FullName, parentTI.Assembly.FullName), range0)) | _ -> res -//---------------------------------------------------------------------------- -// emitLabelMark -//---------------------------------------------------------------------------- - let emitLabelMark emEnv (ilG: ILGenerator) (label: ILCodeLabel) = let lab = envGetLabel emEnv label - ilG.MarkLabelAndLog(lab) + ilG.MarkLabelAndLog lab -//---------------------------------------------------------------------------- -// emitInstr cenv - I_arith -//---------------------------------------------------------------------------- - ///Emit comparison instructions. let emitInstrCompare emEnv (ilG: ILGenerator) comp targ = match comp with - | BI_beq -> ilG.EmitAndLog(OpCodes.Beq, envGetLabel emEnv targ) - | BI_bge -> ilG.EmitAndLog(OpCodes.Bge, envGetLabel emEnv targ) - | BI_bge_un -> ilG.EmitAndLog(OpCodes.Bge_Un, envGetLabel emEnv targ) - | BI_bgt -> ilG.EmitAndLog(OpCodes.Bgt, envGetLabel emEnv targ) - | BI_bgt_un -> ilG.EmitAndLog(OpCodes.Bgt_Un, envGetLabel emEnv targ) - | BI_ble -> ilG.EmitAndLog(OpCodes.Ble, envGetLabel emEnv targ) - | BI_ble_un -> ilG.EmitAndLog(OpCodes.Ble_Un, envGetLabel emEnv targ) - | BI_blt -> ilG.EmitAndLog(OpCodes.Blt, envGetLabel emEnv targ) - | BI_blt_un -> ilG.EmitAndLog(OpCodes.Blt_Un, envGetLabel emEnv targ) - | BI_bne_un -> ilG.EmitAndLog(OpCodes.Bne_Un, envGetLabel emEnv targ) - | BI_brfalse -> ilG.EmitAndLog(OpCodes.Brfalse, envGetLabel emEnv targ) - | BI_brtrue -> ilG.EmitAndLog(OpCodes.Brtrue, envGetLabel emEnv targ) + | BI_beq -> ilG.EmitAndLog (OpCodes.Beq, envGetLabel emEnv targ) + | BI_bge -> ilG.EmitAndLog (OpCodes.Bge, envGetLabel emEnv targ) + | BI_bge_un -> ilG.EmitAndLog (OpCodes.Bge_Un, envGetLabel emEnv targ) + | BI_bgt -> ilG.EmitAndLog (OpCodes.Bgt, envGetLabel emEnv targ) + | BI_bgt_un -> ilG.EmitAndLog (OpCodes.Bgt_Un, envGetLabel emEnv targ) + | BI_ble -> ilG.EmitAndLog (OpCodes.Ble, envGetLabel emEnv targ) + | BI_ble_un -> ilG.EmitAndLog (OpCodes.Ble_Un, envGetLabel emEnv targ) + | BI_blt -> ilG.EmitAndLog (OpCodes.Blt, envGetLabel emEnv targ) + | BI_blt_un -> ilG.EmitAndLog (OpCodes.Blt_Un, envGetLabel emEnv targ) + | BI_bne_un -> ilG.EmitAndLog (OpCodes.Bne_Un, envGetLabel emEnv targ) + | BI_brfalse -> ilG.EmitAndLog (OpCodes.Brfalse, envGetLabel emEnv targ) + | BI_brtrue -> ilG.EmitAndLog (OpCodes.Brtrue, envGetLabel emEnv targ) /// Emit the volatile. prefix let emitInstrVolatile (ilG: ILGenerator) = function - | Volatile -> ilG.EmitAndLog(OpCodes.Volatile) + | Volatile -> ilG.EmitAndLog OpCodes.Volatile | Nonvolatile -> () /// Emit the align. prefix @@ -932,12 +915,12 @@ let emitInstrAlign (ilG: ILGenerator) = function /// Emit the tail. prefix if necessary let emitInstrTail (ilG: ILGenerator) tail emitTheCall = match tail with - | Tailcall -> ilG.EmitAndLog(OpCodes.Tailcall); emitTheCall(); ilG.EmitAndLog(OpCodes.Ret) + | Tailcall -> ilG.EmitAndLog OpCodes.Tailcall; emitTheCall(); ilG.EmitAndLog OpCodes.Ret | Normalcall -> emitTheCall() let emitInstrNewobj cenv emEnv (ilG: ILGenerator) mspec varargs = match varargs with - | None -> ilG.EmitAndLog(OpCodes.Newobj, convConstructorSpec cenv emEnv mspec) + | None -> ilG.EmitAndLog (OpCodes.Newobj, convConstructorSpec cenv emEnv mspec) | Some _varargTys -> failwith "emit: pending new varargs" // XXX - gap let emitSilverlightCheck (ilG: ILGenerator) = @@ -954,7 +937,7 @@ let emitInstrCall cenv emEnv (ilG: ILGenerator) opCall tail (mspec: ILMethodSpec else let minfo = convMethodSpec cenv emEnv mspec match varargs with - | None -> ilG.EmitAndLog(opCall, minfo) + | None -> ilG.EmitAndLog (opCall, minfo) | Some varargTys -> ilG.EmitCall (opCall, minfo, convTypesToArray cenv emEnv varargTys) ) @@ -986,47 +969,47 @@ let setArrayMethInfo n ty = let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = match instr with - | AI_add -> ilG.EmitAndLog(OpCodes.Add) - | AI_add_ovf -> ilG.EmitAndLog(OpCodes.Add_Ovf) - | AI_add_ovf_un -> ilG.EmitAndLog(OpCodes.Add_Ovf_Un) - | AI_and -> ilG.EmitAndLog(OpCodes.And) - | AI_div -> ilG.EmitAndLog(OpCodes.Div) - | AI_div_un -> ilG.EmitAndLog(OpCodes.Div_Un) - | AI_ceq -> ilG.EmitAndLog(OpCodes.Ceq) - | AI_cgt -> ilG.EmitAndLog(OpCodes.Cgt) - | AI_cgt_un -> ilG.EmitAndLog(OpCodes.Cgt_Un) - | AI_clt -> ilG.EmitAndLog(OpCodes.Clt) - | AI_clt_un -> ilG.EmitAndLog(OpCodes.Clt_Un) + | AI_add -> ilG.EmitAndLog OpCodes.Add + | AI_add_ovf -> ilG.EmitAndLog OpCodes.Add_Ovf + | AI_add_ovf_un -> ilG.EmitAndLog OpCodes.Add_Ovf_Un + | AI_and -> ilG.EmitAndLog OpCodes.And + | AI_div -> ilG.EmitAndLog OpCodes.Div + | AI_div_un -> ilG.EmitAndLog OpCodes.Div_Un + | AI_ceq -> ilG.EmitAndLog OpCodes.Ceq + | AI_cgt -> ilG.EmitAndLog OpCodes.Cgt + | AI_cgt_un -> ilG.EmitAndLog OpCodes.Cgt_Un + | AI_clt -> ilG.EmitAndLog OpCodes.Clt + | AI_clt_un -> ilG.EmitAndLog OpCodes.Clt_Un // conversion | AI_conv dt -> match dt with - | DT_I -> ilG.EmitAndLog(OpCodes.Conv_I) - | DT_I1 -> ilG.EmitAndLog(OpCodes.Conv_I1) - | DT_I2 -> ilG.EmitAndLog(OpCodes.Conv_I2) - | DT_I4 -> ilG.EmitAndLog(OpCodes.Conv_I4) - | DT_I8 -> ilG.EmitAndLog(OpCodes.Conv_I8) - | DT_U -> ilG.EmitAndLog(OpCodes.Conv_U) - | DT_U1 -> ilG.EmitAndLog(OpCodes.Conv_U1) - | DT_U2 -> ilG.EmitAndLog(OpCodes.Conv_U2) - | DT_U4 -> ilG.EmitAndLog(OpCodes.Conv_U4) - | DT_U8 -> ilG.EmitAndLog(OpCodes.Conv_U8) - | DT_R -> ilG.EmitAndLog(OpCodes.Conv_R_Un) - | DT_R4 -> ilG.EmitAndLog(OpCodes.Conv_R4) - | DT_R8 -> ilG.EmitAndLog(OpCodes.Conv_R8) + | DT_I -> ilG.EmitAndLog OpCodes.Conv_I + | DT_I1 -> ilG.EmitAndLog OpCodes.Conv_I1 + | DT_I2 -> ilG.EmitAndLog OpCodes.Conv_I2 + | DT_I4 -> ilG.EmitAndLog OpCodes.Conv_I4 + | DT_I8 -> ilG.EmitAndLog OpCodes.Conv_I8 + | DT_U -> ilG.EmitAndLog OpCodes.Conv_U + | DT_U1 -> ilG.EmitAndLog OpCodes.Conv_U1 + | DT_U2 -> ilG.EmitAndLog OpCodes.Conv_U2 + | DT_U4 -> ilG.EmitAndLog OpCodes.Conv_U4 + | DT_U8 -> ilG.EmitAndLog OpCodes.Conv_U8 + | DT_R -> ilG.EmitAndLog OpCodes.Conv_R_Un + | DT_R4 -> ilG.EmitAndLog OpCodes.Conv_R4 + | DT_R8 -> ilG.EmitAndLog OpCodes.Conv_R8 | DT_REF -> failwith "AI_conv DT_REF?" // XXX - check // conversion - ovf checks | AI_conv_ovf dt -> match dt with - | DT_I -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I) - | DT_I1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I1) - | DT_I2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I2) - | DT_I4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I4) - | DT_I8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I8) - | DT_U -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U) - | DT_U1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U1) - | DT_U2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U2) - | DT_U4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U4) - | DT_U8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U8) + | DT_I -> ilG.EmitAndLog OpCodes.Conv_Ovf_I + | DT_I1 -> ilG.EmitAndLog OpCodes.Conv_Ovf_I1 + | DT_I2 -> ilG.EmitAndLog OpCodes.Conv_Ovf_I2 + | DT_I4 -> ilG.EmitAndLog OpCodes.Conv_Ovf_I4 + | DT_I8 -> ilG.EmitAndLog OpCodes.Conv_Ovf_I8 + | DT_U -> ilG.EmitAndLog OpCodes.Conv_Ovf_U + | DT_U1 -> ilG.EmitAndLog OpCodes.Conv_Ovf_U1 + | DT_U2 -> ilG.EmitAndLog OpCodes.Conv_Ovf_U2 + | DT_U4 -> ilG.EmitAndLog OpCodes.Conv_Ovf_U4 + | DT_U8 -> ilG.EmitAndLog OpCodes.Conv_Ovf_U8 | DT_R -> failwith "AI_conv_ovf DT_R?" // XXX - check | DT_R4 -> failwith "AI_conv_ovf DT_R4?" // XXX - check | DT_R8 -> failwith "AI_conv_ovf DT_R8?" // XXX - check @@ -1034,92 +1017,92 @@ let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = // conversion - ovf checks and unsigned | AI_conv_ovf_un dt -> match dt with - | DT_I -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I_Un) - | DT_I1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I1_Un) - | DT_I2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I2_Un) - | DT_I4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I4_Un) - | DT_I8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I8_Un) - | DT_U -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U_Un) - | DT_U1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U1_Un) - | DT_U2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U2_Un) - | DT_U4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U4_Un) - | DT_U8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U8_Un) + | DT_I -> ilG.EmitAndLog OpCodes.Conv_Ovf_I_Un + | DT_I1 -> ilG.EmitAndLog OpCodes.Conv_Ovf_I1_Un + | DT_I2 -> ilG.EmitAndLog OpCodes.Conv_Ovf_I2_Un + | DT_I4 -> ilG.EmitAndLog OpCodes.Conv_Ovf_I4_Un + | DT_I8 -> ilG.EmitAndLog OpCodes.Conv_Ovf_I8_Un + | DT_U -> ilG.EmitAndLog OpCodes.Conv_Ovf_U_Un + | DT_U1 -> ilG.EmitAndLog OpCodes.Conv_Ovf_U1_Un + | DT_U2 -> ilG.EmitAndLog OpCodes.Conv_Ovf_U2_Un + | DT_U4 -> ilG.EmitAndLog OpCodes.Conv_Ovf_U4_Un + | DT_U8 -> ilG.EmitAndLog OpCodes.Conv_Ovf_U8_Un | DT_R -> failwith "AI_conv_ovf_un DT_R?" // XXX - check | DT_R4 -> failwith "AI_conv_ovf_un DT_R4?" // XXX - check | DT_R8 -> failwith "AI_conv_ovf_un DT_R8?" // XXX - check | DT_REF -> failwith "AI_conv_ovf_un DT_REF?" // XXX - check - | AI_mul -> ilG.EmitAndLog(OpCodes.Mul) - | AI_mul_ovf -> ilG.EmitAndLog(OpCodes.Mul_Ovf) - | AI_mul_ovf_un -> ilG.EmitAndLog(OpCodes.Mul_Ovf_Un) - | AI_rem -> ilG.EmitAndLog(OpCodes.Rem) - | AI_rem_un -> ilG.EmitAndLog(OpCodes.Rem_Un) - | AI_shl -> ilG.EmitAndLog(OpCodes.Shl) - | AI_shr -> ilG.EmitAndLog(OpCodes.Shr) - | AI_shr_un -> ilG.EmitAndLog(OpCodes.Shr_Un) - | AI_sub -> ilG.EmitAndLog(OpCodes.Sub) - | AI_sub_ovf -> ilG.EmitAndLog(OpCodes.Sub_Ovf) - | AI_sub_ovf_un -> ilG.EmitAndLog(OpCodes.Sub_Ovf_Un) - | AI_xor -> ilG.EmitAndLog(OpCodes.Xor) - | AI_or -> ilG.EmitAndLog(OpCodes.Or) - | AI_neg -> ilG.EmitAndLog(OpCodes.Neg) - | AI_not -> ilG.EmitAndLog(OpCodes.Not) - | AI_ldnull -> ilG.EmitAndLog(OpCodes.Ldnull) - | AI_dup -> ilG.EmitAndLog(OpCodes.Dup) - | AI_pop -> ilG.EmitAndLog(OpCodes.Pop) - | AI_ckfinite -> ilG.EmitAndLog(OpCodes.Ckfinite) - | AI_nop -> ilG.EmitAndLog(OpCodes.Nop) - | AI_ldc (DT_I4, ILConst.I4 i32) -> ilG.EmitAndLog(OpCodes.Ldc_I4, i32) + | AI_mul -> ilG.EmitAndLog OpCodes.Mul + | AI_mul_ovf -> ilG.EmitAndLog OpCodes.Mul_Ovf + | AI_mul_ovf_un -> ilG.EmitAndLog OpCodes.Mul_Ovf_Un + | AI_rem -> ilG.EmitAndLog OpCodes.Rem + | AI_rem_un -> ilG.EmitAndLog OpCodes.Rem_Un + | AI_shl -> ilG.EmitAndLog OpCodes.Shl + | AI_shr -> ilG.EmitAndLog OpCodes.Shr + | AI_shr_un -> ilG.EmitAndLog OpCodes.Shr_Un + | AI_sub -> ilG.EmitAndLog OpCodes.Sub + | AI_sub_ovf -> ilG.EmitAndLog OpCodes.Sub_Ovf + | AI_sub_ovf_un -> ilG.EmitAndLog OpCodes.Sub_Ovf_Un + | AI_xor -> ilG.EmitAndLog OpCodes.Xor + | AI_or -> ilG.EmitAndLog OpCodes.Or + | AI_neg -> ilG.EmitAndLog OpCodes.Neg + | AI_not -> ilG.EmitAndLog OpCodes.Not + | AI_ldnull -> ilG.EmitAndLog OpCodes.Ldnull + | AI_dup -> ilG.EmitAndLog OpCodes.Dup + | AI_pop -> ilG.EmitAndLog OpCodes.Pop + | AI_ckfinite -> ilG.EmitAndLog OpCodes.Ckfinite + | AI_nop -> ilG.EmitAndLog OpCodes.Nop + | AI_ldc (DT_I4, ILConst.I4 i32) -> ilG.EmitAndLog (OpCodes.Ldc_I4, i32) | AI_ldc (DT_I8, ILConst.I8 i64) -> ilG.Emit(OpCodes.Ldc_I8, i64) | AI_ldc (DT_R4, ILConst.R4 r32) -> ilG.Emit(OpCodes.Ldc_R4, r32) | AI_ldc (DT_R8, ILConst.R8 r64) -> ilG.Emit(OpCodes.Ldc_R8, r64) | AI_ldc (_, _ ) -> failwith "emitInstrI_arith (AI_ldc (ty, const)) iltyped" - | I_ldarg u16 -> ilG.EmitAndLog(OpCodes.Ldarg, int16 u16) - | I_ldarga u16 -> ilG.EmitAndLog(OpCodes.Ldarga, int16 u16) + | I_ldarg u16 -> ilG.EmitAndLog (OpCodes.Ldarg, int16 u16) + | I_ldarga u16 -> ilG.EmitAndLog (OpCodes.Ldarga, int16 u16) | I_ldind (align, vol, dt) -> emitInstrAlign ilG align emitInstrVolatile ilG vol match dt with - | DT_I -> ilG.EmitAndLog(OpCodes.Ldind_I) - | DT_I1 -> ilG.EmitAndLog(OpCodes.Ldind_I1) - | DT_I2 -> ilG.EmitAndLog(OpCodes.Ldind_I2) - | DT_I4 -> ilG.EmitAndLog(OpCodes.Ldind_I4) - | DT_I8 -> ilG.EmitAndLog(OpCodes.Ldind_I8) + | DT_I -> ilG.EmitAndLog OpCodes.Ldind_I + | DT_I1 -> ilG.EmitAndLog OpCodes.Ldind_I1 + | DT_I2 -> ilG.EmitAndLog OpCodes.Ldind_I2 + | DT_I4 -> ilG.EmitAndLog OpCodes.Ldind_I4 + | DT_I8 -> ilG.EmitAndLog OpCodes.Ldind_I8 | DT_R -> failwith "emitInstr cenv: ldind R" - | DT_R4 -> ilG.EmitAndLog(OpCodes.Ldind_R4) - | DT_R8 -> ilG.EmitAndLog(OpCodes.Ldind_R8) + | DT_R4 -> ilG.EmitAndLog OpCodes.Ldind_R4 + | DT_R8 -> ilG.EmitAndLog OpCodes.Ldind_R8 | DT_U -> failwith "emitInstr cenv: ldind U" - | DT_U1 -> ilG.EmitAndLog(OpCodes.Ldind_U1) - | DT_U2 -> ilG.EmitAndLog(OpCodes.Ldind_U2) - | DT_U4 -> ilG.EmitAndLog(OpCodes.Ldind_U4) + | DT_U1 -> ilG.EmitAndLog OpCodes.Ldind_U1 + | DT_U2 -> ilG.EmitAndLog OpCodes.Ldind_U2 + | DT_U4 -> ilG.EmitAndLog OpCodes.Ldind_U4 | DT_U8 -> failwith "emitInstr cenv: ldind U8" - | DT_REF -> ilG.EmitAndLog(OpCodes.Ldind_Ref) - | I_ldloc u16 -> ilG.EmitAndLog(OpCodes.Ldloc, int16 u16) - | I_ldloca u16 -> ilG.EmitAndLog(OpCodes.Ldloca, int16 u16) - | I_starg u16 -> ilG.EmitAndLog(OpCodes.Starg, int16 u16) + | DT_REF -> ilG.EmitAndLog OpCodes.Ldind_Ref + | I_ldloc u16 -> ilG.EmitAndLog (OpCodes.Ldloc, int16 u16) + | I_ldloca u16 -> ilG.EmitAndLog (OpCodes.Ldloca, int16 u16) + | I_starg u16 -> ilG.EmitAndLog (OpCodes.Starg, int16 u16) | I_stind (align, vol, dt) -> emitInstrAlign ilG align emitInstrVolatile ilG vol match dt with - | DT_I -> ilG.EmitAndLog(OpCodes.Stind_I) - | DT_I1 -> ilG.EmitAndLog(OpCodes.Stind_I1) - | DT_I2 -> ilG.EmitAndLog(OpCodes.Stind_I2) - | DT_I4 -> ilG.EmitAndLog(OpCodes.Stind_I4) - | DT_I8 -> ilG.EmitAndLog(OpCodes.Stind_I8) + | DT_I -> ilG.EmitAndLog OpCodes.Stind_I + | DT_I1 -> ilG.EmitAndLog OpCodes.Stind_I1 + | DT_I2 -> ilG.EmitAndLog OpCodes.Stind_I2 + | DT_I4 -> ilG.EmitAndLog OpCodes.Stind_I4 + | DT_I8 -> ilG.EmitAndLog OpCodes.Stind_I8 | DT_R -> failwith "emitInstr cenv: stind R" - | DT_R4 -> ilG.EmitAndLog(OpCodes.Stind_R4) - | DT_R8 -> ilG.EmitAndLog(OpCodes.Stind_R8) - | DT_U -> ilG.EmitAndLog(OpCodes.Stind_I) // NOTE: unsigned -> int conversion - | DT_U1 -> ilG.EmitAndLog(OpCodes.Stind_I1) // NOTE: follows code ilwrite.fs - | DT_U2 -> ilG.EmitAndLog(OpCodes.Stind_I2) // NOTE: is it ok? - | DT_U4 -> ilG.EmitAndLog(OpCodes.Stind_I4) // NOTE: it is generated by bytearray tests - | DT_U8 -> ilG.EmitAndLog(OpCodes.Stind_I8) // NOTE: unsigned -> int conversion - | DT_REF -> ilG.EmitAndLog(OpCodes.Stind_Ref) - | I_stloc u16 -> ilG.EmitAndLog(OpCodes.Stloc, int16 u16) - | I_br targ -> ilG.EmitAndLog(OpCodes.Br, envGetLabel emEnv targ) - | I_jmp mspec -> ilG.EmitAndLog(OpCodes.Jmp, convMethodSpec cenv emEnv mspec) + | DT_R4 -> ilG.EmitAndLog OpCodes.Stind_R4 + | DT_R8 -> ilG.EmitAndLog OpCodes.Stind_R8 + | DT_U -> ilG.EmitAndLog OpCodes.Stind_I // NOTE: unsigned -> int conversion + | DT_U1 -> ilG.EmitAndLog OpCodes.Stind_I1 // NOTE: follows code ilwrite.fs + | DT_U2 -> ilG.EmitAndLog OpCodes.Stind_I2 // NOTE: is it ok? + | DT_U4 -> ilG.EmitAndLog OpCodes.Stind_I4 // NOTE: it is generated by bytearray tests + | DT_U8 -> ilG.EmitAndLog OpCodes.Stind_I8 // NOTE: unsigned -> int conversion + | DT_REF -> ilG.EmitAndLog OpCodes.Stind_Ref + | I_stloc u16 -> ilG.EmitAndLog (OpCodes.Stloc, int16 u16) + | I_br targ -> ilG.EmitAndLog (OpCodes.Br, envGetLabel emEnv targ) + | I_jmp mspec -> ilG.EmitAndLog (OpCodes.Jmp, convMethodSpec cenv emEnv mspec) | I_brcmp (comp, targ) -> emitInstrCompare emEnv ilG comp targ | I_switch labels -> ilG.Emit(OpCodes.Switch, Array.ofList (List.map (envGetLabel emEnv) labels)) - | I_ret -> ilG.EmitAndLog(OpCodes.Ret) + | I_ret -> ilG.EmitAndLog OpCodes.Ret | I_call (tail, mspec, varargs) -> emitSilverlightCheck ilG @@ -1150,114 +1133,114 @@ let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = convTypesToArray cenv emEnv varargTys)) | I_ldftn mspec -> - ilG.EmitAndLog(OpCodes.Ldftn, convMethodSpec cenv emEnv mspec) + ilG.EmitAndLog (OpCodes.Ldftn, convMethodSpec cenv emEnv mspec) | I_newobj (mspec, varargs) -> emitInstrNewobj cenv emEnv ilG mspec varargs - | I_throw -> ilG.EmitAndLog(OpCodes.Throw) - | I_endfinally -> ilG.EmitAndLog(OpCodes.Endfinally) - | I_endfilter -> ilG.EmitAndLog(OpCodes.Endfilter) - | I_leave label -> ilG.EmitAndLog(OpCodes.Leave, envGetLabel emEnv label) - | I_ldsfld (vol, fspec) -> emitInstrVolatile ilG vol; ilG.EmitAndLog(OpCodes.Ldsfld, convFieldSpec cenv emEnv fspec) - | I_ldfld (align, vol, fspec) -> emitInstrAlign ilG align; emitInstrVolatile ilG vol; ilG.EmitAndLog(OpCodes.Ldfld, convFieldSpec cenv emEnv fspec) - | I_ldsflda fspec -> ilG.EmitAndLog(OpCodes.Ldsflda, convFieldSpec cenv emEnv fspec) - | I_ldflda fspec -> ilG.EmitAndLog(OpCodes.Ldflda, convFieldSpec cenv emEnv fspec) + | I_throw -> ilG.EmitAndLog OpCodes.Throw + | I_endfinally -> ilG.EmitAndLog OpCodes.Endfinally + | I_endfilter -> ilG.EmitAndLog OpCodes.Endfilter + | I_leave label -> ilG.EmitAndLog (OpCodes.Leave, envGetLabel emEnv label) + | I_ldsfld (vol, fspec) -> emitInstrVolatile ilG vol; ilG.EmitAndLog (OpCodes.Ldsfld, convFieldSpec cenv emEnv fspec) + | I_ldfld (align, vol, fspec) -> emitInstrAlign ilG align; emitInstrVolatile ilG vol; ilG.EmitAndLog (OpCodes.Ldfld, convFieldSpec cenv emEnv fspec) + | I_ldsflda fspec -> ilG.EmitAndLog (OpCodes.Ldsflda, convFieldSpec cenv emEnv fspec) + | I_ldflda fspec -> ilG.EmitAndLog (OpCodes.Ldflda, convFieldSpec cenv emEnv fspec) | I_stsfld (vol, fspec) -> emitInstrVolatile ilG vol - ilG.EmitAndLog(OpCodes.Stsfld, convFieldSpec cenv emEnv fspec) + ilG.EmitAndLog (OpCodes.Stsfld, convFieldSpec cenv emEnv fspec) | I_stfld (align, vol, fspec) -> emitInstrAlign ilG align emitInstrVolatile ilG vol - ilG.EmitAndLog(OpCodes.Stfld, convFieldSpec cenv emEnv fspec) - - | I_ldstr s -> ilG.EmitAndLog(OpCodes.Ldstr, s) - | I_isinst ty -> ilG.EmitAndLog(OpCodes.Isinst, convType cenv emEnv ty) - | I_castclass ty -> ilG.EmitAndLog(OpCodes.Castclass, convType cenv emEnv ty) - | I_ldtoken (ILToken.ILType ty) -> ilG.EmitAndLog(OpCodes.Ldtoken, convTypeOrTypeDef cenv emEnv ty) - | I_ldtoken (ILToken.ILMethod mspec) -> ilG.EmitAndLog(OpCodes.Ldtoken, convMethodSpec cenv emEnv mspec) - | I_ldtoken (ILToken.ILField fspec) -> ilG.EmitAndLog(OpCodes.Ldtoken, convFieldSpec cenv emEnv fspec) - | I_ldvirtftn mspec -> ilG.EmitAndLog(OpCodes.Ldvirtftn, convMethodSpec cenv emEnv mspec) + ilG.EmitAndLog (OpCodes.Stfld, convFieldSpec cenv emEnv fspec) + + | I_ldstr s -> ilG.EmitAndLog (OpCodes.Ldstr, s) + | I_isinst ty -> ilG.EmitAndLog (OpCodes.Isinst, convType cenv emEnv ty) + | I_castclass ty -> ilG.EmitAndLog (OpCodes.Castclass, convType cenv emEnv ty) + | I_ldtoken (ILToken.ILType ty) -> ilG.EmitAndLog (OpCodes.Ldtoken, convTypeOrTypeDef cenv emEnv ty) + | I_ldtoken (ILToken.ILMethod mspec) -> ilG.EmitAndLog (OpCodes.Ldtoken, convMethodSpec cenv emEnv mspec) + | I_ldtoken (ILToken.ILField fspec) -> ilG.EmitAndLog (OpCodes.Ldtoken, convFieldSpec cenv emEnv fspec) + | I_ldvirtftn mspec -> ilG.EmitAndLog (OpCodes.Ldvirtftn, convMethodSpec cenv emEnv mspec) // Value type instructions - | I_cpobj ty -> ilG.EmitAndLog(OpCodes.Cpobj, convType cenv emEnv ty) - | I_initobj ty -> ilG.EmitAndLog(OpCodes.Initobj, convType cenv emEnv ty) + | I_cpobj ty -> ilG.EmitAndLog (OpCodes.Cpobj, convType cenv emEnv ty) + | I_initobj ty -> ilG.EmitAndLog (OpCodes.Initobj, convType cenv emEnv ty) | I_ldobj (align, vol, ty) -> emitInstrAlign ilG align emitInstrVolatile ilG vol - ilG.EmitAndLog(OpCodes.Ldobj, convType cenv emEnv ty) + ilG.EmitAndLog (OpCodes.Ldobj, convType cenv emEnv ty) | I_stobj (align, vol, ty) -> emitInstrAlign ilG align emitInstrVolatile ilG vol - ilG.EmitAndLog(OpCodes.Stobj, convType cenv emEnv ty) + ilG.EmitAndLog (OpCodes.Stobj, convType cenv emEnv ty) - | I_box ty -> ilG.EmitAndLog(OpCodes.Box, convType cenv emEnv ty) - | I_unbox ty -> ilG.EmitAndLog(OpCodes.Unbox, convType cenv emEnv ty) - | I_unbox_any ty -> ilG.EmitAndLog(OpCodes.Unbox_Any, convType cenv emEnv ty) - | I_sizeof ty -> ilG.EmitAndLog(OpCodes.Sizeof, convType cenv emEnv ty) + | I_box ty -> ilG.EmitAndLog (OpCodes.Box, convType cenv emEnv ty) + | I_unbox ty -> ilG.EmitAndLog (OpCodes.Unbox, convType cenv emEnv ty) + | I_unbox_any ty -> ilG.EmitAndLog (OpCodes.Unbox_Any, convType cenv emEnv ty) + | I_sizeof ty -> ilG.EmitAndLog (OpCodes.Sizeof, convType cenv emEnv ty) // Generalized array instructions. // In AbsIL these instructions include // both the single-dimensional variants (with ILArrayShape == ILArrayShape.SingleDimensional) // and calls to the "special" multi-dimensional "methods" such as - // newobj void string[, ]::.ctor(int32, int32) - // call string string[, ]::Get(int32, int32) - // call string& string[, ]::Address(int32, int32) - // call void string[, ]::Set(int32, int32, string) + // newobj void string[, ] :: .ctor(int32, int32) + // call string string[, ] :: Get(int32, int32) + // call string& string[, ] :: Address(int32, int32) + // call void string[, ] :: Set(int32, int32, string) // The IL reader transforms calls of this form to the corresponding // generalized instruction with the corresponding ILArrayShape // argument. This is done to simplify the IL and make it more uniform. // The IL writer then reverses this when emitting the binary. | I_ldelem dt -> match dt with - | DT_I -> ilG.EmitAndLog(OpCodes.Ldelem_I) - | DT_I1 -> ilG.EmitAndLog(OpCodes.Ldelem_I1) - | DT_I2 -> ilG.EmitAndLog(OpCodes.Ldelem_I2) - | DT_I4 -> ilG.EmitAndLog(OpCodes.Ldelem_I4) - | DT_I8 -> ilG.EmitAndLog(OpCodes.Ldelem_I8) + | DT_I -> ilG.EmitAndLog OpCodes.Ldelem_I + | DT_I1 -> ilG.EmitAndLog OpCodes.Ldelem_I1 + | DT_I2 -> ilG.EmitAndLog OpCodes.Ldelem_I2 + | DT_I4 -> ilG.EmitAndLog OpCodes.Ldelem_I4 + | DT_I8 -> ilG.EmitAndLog OpCodes.Ldelem_I8 | DT_R -> failwith "emitInstr cenv: ldelem R" - | DT_R4 -> ilG.EmitAndLog(OpCodes.Ldelem_R4) - | DT_R8 -> ilG.EmitAndLog(OpCodes.Ldelem_R8) + | DT_R4 -> ilG.EmitAndLog OpCodes.Ldelem_R4 + | DT_R8 -> ilG.EmitAndLog OpCodes.Ldelem_R8 | DT_U -> failwith "emitInstr cenv: ldelem U" - | DT_U1 -> ilG.EmitAndLog(OpCodes.Ldelem_U1) - | DT_U2 -> ilG.EmitAndLog(OpCodes.Ldelem_U2) - | DT_U4 -> ilG.EmitAndLog(OpCodes.Ldelem_U4) + | DT_U1 -> ilG.EmitAndLog OpCodes.Ldelem_U1 + | DT_U2 -> ilG.EmitAndLog OpCodes.Ldelem_U2 + | DT_U4 -> ilG.EmitAndLog OpCodes.Ldelem_U4 | DT_U8 -> failwith "emitInstr cenv: ldelem U8" - | DT_REF -> ilG.EmitAndLog(OpCodes.Ldelem_Ref) + | DT_REF -> ilG.EmitAndLog OpCodes.Ldelem_Ref | I_stelem dt -> match dt with - | DT_I -> ilG.EmitAndLog(OpCodes.Stelem_I) - | DT_I1 -> ilG.EmitAndLog(OpCodes.Stelem_I1) - | DT_I2 -> ilG.EmitAndLog(OpCodes.Stelem_I2) - | DT_I4 -> ilG.EmitAndLog(OpCodes.Stelem_I4) - | DT_I8 -> ilG.EmitAndLog(OpCodes.Stelem_I8) + | DT_I -> ilG.EmitAndLog OpCodes.Stelem_I + | DT_I1 -> ilG.EmitAndLog OpCodes.Stelem_I1 + | DT_I2 -> ilG.EmitAndLog OpCodes.Stelem_I2 + | DT_I4 -> ilG.EmitAndLog OpCodes.Stelem_I4 + | DT_I8 -> ilG.EmitAndLog OpCodes.Stelem_I8 | DT_R -> failwith "emitInstr cenv: stelem R" - | DT_R4 -> ilG.EmitAndLog(OpCodes.Stelem_R4) - | DT_R8 -> ilG.EmitAndLog(OpCodes.Stelem_R8) + | DT_R4 -> ilG.EmitAndLog OpCodes.Stelem_R4 + | DT_R8 -> ilG.EmitAndLog OpCodes.Stelem_R8 | DT_U -> failwith "emitInstr cenv: stelem U" | DT_U1 -> failwith "emitInstr cenv: stelem U1" | DT_U2 -> failwith "emitInstr cenv: stelem U2" | DT_U4 -> failwith "emitInstr cenv: stelem U4" | DT_U8 -> failwith "emitInstr cenv: stelem U8" - | DT_REF -> ilG.EmitAndLog(OpCodes.Stelem_Ref) + | DT_REF -> ilG.EmitAndLog OpCodes.Stelem_Ref | I_ldelema (ro, _isNativePtr, shape, ty) -> - if (ro = ReadonlyAddress) then ilG.EmitAndLog(OpCodes.Readonly) + if (ro = ReadonlyAddress) then ilG.EmitAndLog OpCodes.Readonly if (shape = ILArrayShape.SingleDimensional) - then ilG.EmitAndLog(OpCodes.Ldelema, convType cenv emEnv ty) + then ilG.EmitAndLog (OpCodes.Ldelema, convType cenv emEnv ty) else let aty = convType cenv emEnv (ILType.Array(shape, ty)) let ety = aty.GetElementType() let rty = ety.MakeByRefType() - let meth = modB.GetArrayMethodAndLog(aty, "Address", System.Reflection.CallingConventions.HasThis, rty, Array.create shape.Rank (typeof) ) - ilG.EmitAndLog(OpCodes.Call, meth) + let meth = modB.GetArrayMethodAndLog (aty, "Address", System.Reflection.CallingConventions.HasThis, rty, Array.create shape.Rank (typeof) ) + ilG.EmitAndLog (OpCodes.Call, meth) | I_ldelem_any (shape, ty) -> - if (shape = ILArrayShape.SingleDimensional) then ilG.EmitAndLog(OpCodes.Ldelem, convType cenv emEnv ty) + if (shape = ILArrayShape.SingleDimensional) then ilG.EmitAndLog (OpCodes.Ldelem, convType cenv emEnv ty) else let aty = convType cenv emEnv (ILType.Array(shape, ty)) let ety = aty.GetElementType() @@ -1268,11 +1251,11 @@ let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = getArrayMethInfo shape.Rank ety else #endif - modB.GetArrayMethodAndLog(aty, "Get", System.Reflection.CallingConventions.HasThis, ety, Array.create shape.Rank (typeof) ) - ilG.EmitAndLog(OpCodes.Call, meth) + modB.GetArrayMethodAndLog (aty, "Get", System.Reflection.CallingConventions.HasThis, ety, Array.create shape.Rank (typeof) ) + ilG.EmitAndLog (OpCodes.Call, meth) | I_stelem_any (shape, ty) -> - if (shape = ILArrayShape.SingleDimensional) then ilG.EmitAndLog(OpCodes.Stelem, convType cenv emEnv ty) + if (shape = ILArrayShape.SingleDimensional) then ilG.EmitAndLog (OpCodes.Stelem, convType cenv emEnv ty) else let aty = convType cenv emEnv (ILType.Array(shape, ty)) let ety = aty.GetElementType() @@ -1283,23 +1266,23 @@ let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = setArrayMethInfo shape.Rank ety else #endif - modB.GetArrayMethodAndLog(aty, "Set", System.Reflection.CallingConventions.HasThis, (null: Type), Array.append (Array.create shape.Rank (typeof)) (Array.ofList [ ety ])) - ilG.EmitAndLog(OpCodes.Call, meth) + modB.GetArrayMethodAndLog (aty, "Set", System.Reflection.CallingConventions.HasThis, (null: Type), Array.append (Array.create shape.Rank (typeof)) (Array.ofList [ ety ])) + ilG.EmitAndLog (OpCodes.Call, meth) | I_newarr (shape, ty) -> if (shape = ILArrayShape.SingleDimensional) - then ilG.EmitAndLog(OpCodes.Newarr, convType cenv emEnv ty) + then ilG.EmitAndLog (OpCodes.Newarr, convType cenv emEnv ty) else let aty = convType cenv emEnv (ILType.Array(shape, ty)) - let meth = modB.GetArrayMethodAndLog(aty, ".ctor", System.Reflection.CallingConventions.HasThis, (null: Type), Array.create shape.Rank (typeof)) - ilG.EmitAndLog(OpCodes.Newobj, meth) - - | I_ldlen -> ilG.EmitAndLog(OpCodes.Ldlen) - | I_mkrefany ty -> ilG.EmitAndLog(OpCodes.Mkrefany, convType cenv emEnv ty) - | I_refanytype -> ilG.EmitAndLog(OpCodes.Refanytype) - | I_refanyval ty -> ilG.EmitAndLog(OpCodes.Refanyval, convType cenv emEnv ty) - | I_rethrow -> ilG.EmitAndLog(OpCodes.Rethrow) - | I_break -> ilG.EmitAndLog(OpCodes.Break) + let meth = modB.GetArrayMethodAndLog (aty, ".ctor", System.Reflection.CallingConventions.HasThis, (null: Type), Array.create shape.Rank (typeof)) + ilG.EmitAndLog (OpCodes.Newobj, meth) + + | I_ldlen -> ilG.EmitAndLog OpCodes.Ldlen + | I_mkrefany ty -> ilG.EmitAndLog (OpCodes.Mkrefany, convType cenv emEnv ty) + | I_refanytype -> ilG.EmitAndLog OpCodes.Refanytype + | I_refanyval ty -> ilG.EmitAndLog (OpCodes.Refanyval, convType cenv emEnv ty) + | I_rethrow -> ilG.EmitAndLog OpCodes.Rethrow + | I_break -> ilG.EmitAndLog OpCodes.Break | I_seqpoint src -> #if FX_RESHAPED_REFEMIT ignore src @@ -1307,21 +1290,21 @@ let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = #else if cenv.generatePdb && not (src.Document.File.EndsWithOrdinal("stdin")) then let guid x = match x with None -> Guid.Empty | Some g -> Guid(g: byte[]) in - let symDoc = modB.DefineDocumentAndLog(src.Document.File, guid src.Document.Language, guid src.Document.Vendor, guid src.Document.DocumentType) - ilG.MarkSequencePointAndLog(symDoc, src.Line, src.Column, src.EndLine, src.EndColumn) + let symDoc = modB.DefineDocumentAndLog (src.Document.File, guid src.Document.Language, guid src.Document.Vendor, guid src.Document.DocumentType) + ilG.MarkSequencePointAndLog (symDoc, src.Line, src.Column, src.EndLine, src.EndColumn) #endif - | I_arglist -> ilG.EmitAndLog(OpCodes.Arglist) - | I_localloc -> ilG.EmitAndLog(OpCodes.Localloc) + | I_arglist -> ilG.EmitAndLog OpCodes.Arglist + | I_localloc -> ilG.EmitAndLog OpCodes.Localloc | I_cpblk (align, vol) -> emitInstrAlign ilG align emitInstrVolatile ilG vol - ilG.EmitAndLog(OpCodes.Cpblk) + ilG.EmitAndLog OpCodes.Cpblk | I_initblk (align, vol) -> emitInstrAlign ilG align emitInstrVolatile ilG vol - ilG.EmitAndLog(OpCodes.Initblk) + ilG.EmitAndLog OpCodes.Initblk | EI_ldlen_multi (_, m) -> emitInstr cenv modB emEnv ilG (mkLdcInt32 m) @@ -1335,9 +1318,9 @@ let emitCode cenv modB emEnv (ilG: ILGenerator) (code: ILCode) = let pc2lab = Dictionary() let emEnv = (emEnv, code.Labels) ||> Seq.fold (fun emEnv (KeyValue(label, pc)) -> - let lab = ilG.DefineLabelAndLog() + let lab = ilG.DefineLabelAndLog () pc2lab.[pc] <- - match pc2lab.TryGetValue(pc) with + match pc2lab.TryGetValue pc with | true, labels -> lab :: labels | _ -> [lab] envSetLabel emEnv label lab) @@ -1348,14 +1331,14 @@ let emitCode cenv modB emEnv (ilG: ILGenerator) (code: ILCode) = let add lab action = let pc = lab2pc.[lab] pc2action.[pc] <- - match pc2action.TryGetValue(pc) with + match pc2action.TryGetValue pc with | true, actions -> actions @ [action] | _ -> [action] for e in code.Exceptions do let (startTry, _endTry) = e.Range - add startTry (fun () -> ilG.BeginExceptionBlockAndLog() |> ignore) + add startTry (fun () -> ilG.BeginExceptionBlockAndLog () |> ignore) match e.Clause with | ILExceptionClause.Finally(startHandler, endHandler) -> @@ -1379,16 +1362,16 @@ let emitCode cenv modB emEnv (ilG: ILGenerator) (code: ILCode) = let instrs = code.Instrs for pc = 0 to instrs.Length do - match pc2action.TryGetValue(pc) with + match pc2action.TryGetValue pc with | true, actions -> for action in actions do action() | _ -> () - match pc2lab.TryGetValue(pc) with + match pc2lab.TryGetValue pc with | true, labels -> for lab in labels do - ilG.MarkLabelAndLog(lab) + ilG.MarkLabelAndLog lab | _ -> () if pc < instrs.Length then @@ -1399,7 +1382,7 @@ let emitCode cenv modB emEnv (ilG: ILGenerator) (code: ILCode) = let emitLocal cenv emEnv (ilG: ILGenerator) (local: ILLocal) = let ty = convType cenv emEnv local.Type - let locBuilder = ilG.DeclareLocalAndLog(ty, local.IsPinned) + let locBuilder = ilG.DeclareLocalAndLog (ty, local.IsPinned) #if !FX_NO_PDB_WRITER match local.DebugInfo with | Some(nm, start, finish) -> locBuilder.SetLocalSymInfo(nm, start, finish) @@ -1445,11 +1428,7 @@ let buildGenParamsPass1 _emEnv defineGenericParameters (gps: ILGenericParameterD let buildGenParamsPass1b cenv emEnv (genArgs: Type array) (gps: ILGenericParameterDefs) = -#if FX_RESHAPED_REFLECTION - let genpBs = genArgs |> Array.map (fun x -> (x.GetTypeInfo() :?> GenericTypeParameterBuilder)) -#else let genpBs = genArgs |> Array.map (fun x -> (x :?> GenericTypeParameterBuilder)) -#endif gps |> List.iteri (fun i (gp: ILGenericParameterDef) -> let gpB = genpBs.[i] // the Constraints are either the parent (base) type or interfaces. @@ -1458,7 +1437,7 @@ let buildGenParamsPass1b cenv emEnv (genArgs: Type array) (gps: ILGenericParamet // set base type constraint (match baseTs with [ ] -> () // Q: should a baseType be set? It is in some samples. Should this be a failure case? - | [ baseT ] -> gpB.SetBaseTypeConstraint(baseT) + | [ baseT ] -> gpB.SetBaseTypeConstraint baseT | _ -> failwith "buildGenParam: multiple base types" ) // set interface constraints (interfaces that instances of gp must meet) @@ -1476,7 +1455,7 @@ let buildGenParamsPass1b cenv emEnv (genArgs: Type array) (gps: ILGenericParamet let flags = if gp.HasNotNullableValueTypeConstraint then flags ||| GenericParameterAttributes.NotNullableValueTypeConstraint else flags let flags = if gp.HasDefaultConstructorConstraint then flags ||| GenericParameterAttributes.DefaultConstructorConstraint else flags - gpB.SetGenericParameterAttributes(flags) + gpB.SetGenericParameterAttributes flags ) //---------------------------------------------------------------------------- // emitParameter @@ -1500,20 +1479,46 @@ let emitParameter cenv emEnv (defineParameter: int * ParameterAttributes * strin //---------------------------------------------------------------------------- // buildMethodPass2 //---------------------------------------------------------------------------- - + +#if !FX_RESHAPED_REFEMIT || NETCOREAPP3_0 + +let enablePInvoke = true + +#else + +// We currently build targeting netcoreapp2_1, and will continue to do so through this VS cycle +// but we can run on Netcoreapp3.0 so ... use reflection to invoke the api, when we are executing on netcoreapp3.0 +let definePInvokeMethod = + typeof.GetMethod("DefinePInvokeMethod", [| + typeof + typeof + typeof + typeof + typeof + typeof + typeof + typeof + typeof + typeof + typeof + typeof + typeof |]) + +let enablePInvoke = definePInvokeMethod <> null +#endif + let rec buildMethodPass2 cenv tref (typB: TypeBuilder) emEnv (mdef: ILMethodDef) = let attrs = mdef.Attributes let implflags = mdef.ImplAttributes let cconv = convCallConv mdef.CallingConv - let mref = mkRefToILMethod (tref, mdef) + let mref = mkRefToILMethod (tref, mdef) let emEnv = - if mdef.IsEntryPoint && isNil mdef.ParameterTypes then + if mdef.IsEntryPoint && isNil mdef.ParameterTypes then envAddEntryPt emEnv (typB, mdef.Name) else emEnv match mdef.Body.Contents with -#if !FX_RESHAPED_REFEMIT - | MethodBody.PInvoke p -> + | MethodBody.PInvoke p when enablePInvoke -> let argtys = convTypesToArray cenv emEnv mdef.ParameterTypes let rty = convType cenv emEnv mdef.Return.Type @@ -1535,21 +1540,30 @@ let rec buildMethodPass2 cenv tref (typB: TypeBuilder) emEnv (mdef: ILMethodDef) (* p.CharBestFit *) (* p.NoMangle *) - let methB = typB.DefinePInvokeMethod(mdef.Name, p.Where.Name, p.Name, attrs, cconv, rty, null, null, argtys, null, null, pcc, pcs) - methB.SetImplementationFlagsAndLog(implflags) - envBindMethodRef emEnv mref methB +#if !FX_RESHAPED_REFEMIT || NETCOREAPP3_0 + // DefinePInvokeMethod was removed in early versions of coreclr, it was added back in NETCORE_APP3_0. + // It has always been available in the desktop framework + let methB = typB.DefinePInvokeMethod(mdef.Name, p.Where.Name, p.Name, attrs, cconv, rty, null, null, argtys, null, null, pcc, pcs) +#else + // We currently build targeting netcoreapp2_1, and will continue to do so through this VS cycle + // but we can run on Netcoreapp3.0 so ... use reflection to invoke the api, when we are executing on netcoreapp3.0 + let methB = + System.Diagnostics.Debug.Assert(definePInvokeMethod <> null, "Runtime does not have DefinePInvokeMethod") // Absolutely can't happen + definePInvokeMethod.Invoke(typB, [| mdef.Name; p.Where.Name; p.Name; attrs; cconv; rty; null; null; argtys; null; null; pcc; pcs |]) :?> MethodBuilder #endif + methB.SetImplementationFlagsAndLog implflags + envBindMethodRef emEnv mref methB | _ -> match mdef.Name with | ".cctor" | ".ctor" -> - let consB = typB.DefineConstructorAndLog(attrs, cconv, convTypesToArray cenv emEnv mdef.ParameterTypes) - consB.SetImplementationFlagsAndLog(implflags) + let consB = typB.DefineConstructorAndLog (attrs, cconv, convTypesToArray cenv emEnv mdef.ParameterTypes) + consB.SetImplementationFlagsAndLog implflags envBindConsRef emEnv mref consB | _name -> // The return/argument types may involve the generic parameters - let methB = typB.DefineMethodAndLog(mdef.Name, attrs, cconv) + let methB = typB.DefineMethodAndLog (mdef.Name, attrs, cconv) // Method generic type parameters buildGenParamsPass1 emEnv methB.DefineGenericParametersAndLog mdef.GenericParams @@ -1568,10 +1582,10 @@ let rec buildMethodPass2 cenv tref (typB: TypeBuilder) emEnv (mdef: ILMethodDef) let returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers = mdef.Return |> convReturnModifiers cenv emEnv let returnType = convType cenv emEnv mdef.Return.Type - methB.SetSignatureAndLog(returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers,parameterTypeOptionalCustomModifiers) + methB.SetSignatureAndLog (returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers,parameterTypeOptionalCustomModifiers) let emEnv = envPopTyvars emEnv - methB.SetImplementationFlagsAndLog(implflags) + methB.SetImplementationFlagsAndLog implflags envBindMethodRef emEnv mref methB @@ -1591,7 +1605,7 @@ let rec buildMethodPass3 cenv tref modB (typB: TypeBuilder) emEnv (mdef: ILMetho // Constructors can not have generic parameters assert isNil mdef.GenericParams // Value parameters - let defineParameter (i, attr, name) = consB.DefineParameterAndLog(i+1, attr, name) + let defineParameter (i, attr, name) = consB.DefineParameterAndLog (i+1, attr, name) mdef.Parameters |> List.iteri (emitParameter cenv emEnv defineParameter) // Body emitMethodBody cenv modB emEnv consB.GetILGenerator mdef.Name mdef.Body @@ -1605,11 +1619,11 @@ let rec buildMethodPass3 cenv tref modB (typB: TypeBuilder) emEnv (mdef: ILMetho (getGenericArgumentsOfMethod methB)) if not (Array.isEmpty mdef.Return.CustomAttrs.AsArray) then - let retB = methB.DefineParameterAndLog(0, System.Reflection.ParameterAttributes.Retval, null) + let retB = methB.DefineParameterAndLog (0, System.Reflection.ParameterAttributes.Retval, null) emitCustomAttrs cenv emEnv (wrapCustomAttr retB.SetCustomAttribute) mdef.Return.CustomAttrs // Value parameters - let defineParameter (i, attr, name) = methB.DefineParameterAndLog(i+1, attr, name) + let defineParameter (i, attr, name) = methB.DefineParameterAndLog (i+1, attr, name) mdef.Parameters |> List.iteri (fun a b -> emitParameter cenv emEnv defineParameter a b) // Body if not isPInvoke then @@ -1629,7 +1643,7 @@ let buildFieldPass2 cenv tref (typB: TypeBuilder) emEnv (fdef: ILFieldDef) = match fdef.Data with | Some d -> typB.DefineInitializedData(fdef.Name, d, attrs) | None -> - typB.DefineFieldAndLog(fdef.Name, fieldT, attrs) + typB.DefineFieldAndLog (fdef.Name, fieldT, attrs) // set default value let emEnv = @@ -1647,8 +1661,8 @@ let buildFieldPass2 cenv tref (typB: TypeBuilder) emEnv (fdef: ILFieldDef) = // => its underlying type cannot be explicitly specified and will be inferred at the very moment of first field definition // => here we cannot detect if underlying type is already set so as a conservative solution we delay initialization of fields // to the end of pass2 (types and members are already created but method bodies are yet not emitted) - { emEnv with delayedFieldInits = (fun() -> fieldB.SetConstant(convFieldInit initial))::emEnv.delayedFieldInits } - fdef.Offset |> Option.iter (fun offset -> fieldB.SetOffset(offset)) + { emEnv with delayedFieldInits = (fun() -> fieldB.SetConstant(convFieldInit initial)) :: emEnv.delayedFieldInits } + fdef.Offset |> Option.iter (fun offset -> fieldB.SetOffset offset) // custom attributes: done on pass 3 as they may reference attribute constructors generated on // pass 2. let fref = mkILFieldRef (tref, fdef.Name, fdef.FieldType) @@ -1667,7 +1681,7 @@ let buildPropertyPass2 cenv tref (typB: TypeBuilder) emEnv (prop: ILPropertyDef) let attrs = flagsIf prop.IsRTSpecialName PropertyAttributes.RTSpecialName ||| flagsIf prop.IsSpecialName PropertyAttributes.SpecialName - let propB = typB.DefinePropertyAndLog(prop.Name, attrs, convType cenv emEnv prop.PropertyType, convTypesToArray cenv emEnv prop.Args) + let propB = typB.DefinePropertyAndLog (prop.Name, attrs, convType cenv emEnv prop.PropertyType, convTypesToArray cenv emEnv prop.Args) prop.SetMethod |> Option.iter (fun mref -> propB.SetSetMethod(envGetMethB emEnv mref)) prop.GetMethod |> Option.iter (fun mref -> propB.SetGetMethod(envGetMethB emEnv mref)) @@ -1691,7 +1705,7 @@ let buildEventPass3 cenv (typB: TypeBuilder) emEnv (eventDef: ILEventDef) = let attrs = flagsIf eventDef.IsSpecialName EventAttributes.SpecialName ||| flagsIf eventDef.IsRTSpecialName EventAttributes.RTSpecialName assert eventDef.EventType.IsSome - let eventB = typB.DefineEventAndLog(eventDef.Name, attrs, convType cenv emEnv eventDef.EventType.Value) + let eventB = typB.DefineEventAndLog (eventDef.Name, attrs, convType cenv emEnv eventDef.EventType.Value) eventDef.AddMethod |> (fun mref -> eventB.SetAddOnMethod(envGetMethB emEnv mref)) eventDef.RemoveMethod |> (fun mref -> eventB.SetRemoveOnMethod(envGetMethB emEnv mref)) @@ -1715,7 +1729,7 @@ let buildMethodImplsPass3 cenv _tref (typB: TypeBuilder) emEnv (mimpl: IL.ILMeth // typeAttributesOf* //---------------------------------------------------------------------------- -let typeAttrbutesOfTypeDefKind x = +let typeAttributesOfTypeDefKind x = match x with // required for a TypeBuilder | ILTypeDefKind.Class -> TypeAttributes.Class @@ -1724,14 +1738,14 @@ let typeAttrbutesOfTypeDefKind x = | ILTypeDefKind.Enum -> TypeAttributes.Class | ILTypeDefKind.Delegate -> TypeAttributes.Class -let typeAttrbutesOfTypeAccess x = +let typeAttributesOfTypeAccess x = match x with | ILTypeDefAccess.Public -> TypeAttributes.Public | ILTypeDefAccess.Private -> TypeAttributes.NotPublic | ILTypeDefAccess.Nested macc -> match macc with | ILMemberAccess.Assembly -> TypeAttributes.NestedAssembly - | ILMemberAccess.CompilerControlled -> failwith "Nested compiler controled." + | ILMemberAccess.CompilerControlled -> failwith "Nested compiler controlled." | ILMemberAccess.FamilyAndAssembly -> TypeAttributes.NestedFamANDAssem | ILMemberAccess.FamilyOrAssembly -> TypeAttributes.NestedFamORAssem | ILMemberAccess.Family -> TypeAttributes.NestedFamily @@ -1789,7 +1803,7 @@ let rec buildTypeDefPass1 cenv emEnv (modB: ModuleBuilder) rootTypeBuilder nesti // Q: would it be ok to use typB :> Type ? // Maybe not, recall TypeBuilder maybe subtype of Type, but it is not THE Type. let nameInModule = tref.QualifiedName - modB.GetTypeAndLog(nameInModule, false, false) + modB.GetTypeAndLog (nameInModule, false, false) let emEnv = envBindTypeRef emEnv tref (typT, typB, tdef) // recurse on nested types @@ -1811,7 +1825,7 @@ let rec buildTypeDefPass1b cenv nesting emEnv (tdef: ILTypeDef) = let genArgs = getGenericArgumentsOfType (typB.AsType()) let emEnv = envPushTyvars emEnv genArgs // Parent may reference types being defined, so has to come after it's Pass1 creation - tdef.Extends |> Option.iter (fun ty -> typB.SetParentAndLog(convType cenv emEnv ty)) + tdef.Extends |> Option.iter (fun ty -> typB.SetParentAndLog (convType cenv emEnv ty)) // build constraints on ILGenericParameterDefs. Constraints may reference types being defined, // so have to come after all types are created buildGenParamsPass1b cenv emEnv genArgs tdef.GenericParams @@ -1828,7 +1842,7 @@ let rec buildTypeDefPass2 cenv nesting emEnv (tdef: ILTypeDef) = let typB = envGetTypB emEnv tref let emEnv = envPushTyvars emEnv (getGenericArgumentsOfType (typB.AsType())) // add interface impls - tdef.Implements |> convTypes cenv emEnv |> List.iter (fun implT -> typB.AddInterfaceImplementationAndLog(implT)) + tdef.Implements |> convTypes cenv emEnv |> List.iter (fun implT -> typB.AddInterfaceImplementationAndLog implT) // add methods, properties let emEnv = Array.fold (buildMethodPass2 cenv tref typB) emEnv tdef.Methods.AsArray let emEnv = List.fold (buildFieldPass2 cenv tref typB) emEnv tdef.Fields.AsList @@ -1920,7 +1934,7 @@ let rec getTypeRefsInType (allTypes: CollectTypes) ty acc = | CollectTypes.ValueTypesOnly -> acc | CollectTypes.All -> getTypeRefsInType allTypes eltType acc | ILType.Value tspec -> - // We usee CollectTypes.All because the .NET type loader appears to always eagerly require all types + // We use CollectTypes.All because the .NET type loader appears to always eagerly require all types // referred to in an instantiation of a generic value type tspec.TypeRef :: List.foldBack (getTypeRefsInType CollectTypes.All) tspec.GenericArgs acc | ILType.Boxed tspec -> @@ -1975,13 +1989,10 @@ let createTypeRef (visited: Dictionary<_, _>, created: Dictionary<_, _>) emEnv t if verbose2 then dprintf "- considering reference to type %s\n" typB.FullName // Re-run traverseTypeDef if we've never visited the type. - if not (visited.ContainsKey(tref)) then + if not (visited.ContainsKey tref) then visited.[tref] <- true let tdef = envGetTypeDef emEnv tref if verbose2 then dprintf "- traversing type %s\n" typB.FullName -#if FX_NO_APP_DOMAINS - traverseTypeDef tref tdef -#else // This looks like a special case (perhaps bogus) of the dependency logic above, where // we require the type r.Name, though with "nestingToProbe" being the enclosing types of the // type being defined. @@ -1994,7 +2005,7 @@ let createTypeRef (visited: Dictionary<_, _>, created: Dictionary<_, _>) emEnv t match emEnv.emTypMap.TryFind typeRef with | Some(_, tb, _, _) -> if not (tb.IsCreated()) then - tb.CreateTypeAndLog() |> ignore + tb.CreateTypeAndLog () |> ignore tb.Assembly | None -> null ) @@ -2005,13 +2016,13 @@ let createTypeRef (visited: Dictionary<_, _>, created: Dictionary<_, _>) emEnv t traverseTypeDef tref tdef finally System.AppDomain.CurrentDomain.remove_TypeResolve typeCreationHandler -#endif + // At this point, we've done everything we can to prepare the type for loading by eagerly forcing the // load of other types. Everything else is up to the implementation of System.Reflection.Emit. - if not (created.ContainsKey(tref)) then + if not (created.ContainsKey tref) then created.[tref] <- true if verbose2 then dprintf "- creating type %s\n" typB.FullName - typB.CreateTypeAndLog() |> ignore + typB.CreateTypeAndLog () |> ignore traverseTypeRef tref @@ -2065,13 +2076,11 @@ let buildModuleFragment cenv emEnv (asmB: AssemblyBuilder) (modB: ModuleBuilder) m.Resources.AsList |> List.iter (fun r -> let attribs = (match r.Access with ILResourceAccess.Public -> ResourceAttributes.Public | ILResourceAccess.Private -> ResourceAttributes.Private) match r.Location with - | ILResourceLocation.LocalIn (file, start, len) -> - let bytes = FileSystem.ReadAllBytesShim(file).[start .. start + len - 1] - modB.DefineManifestResourceAndLog(r.Name, new System.IO.MemoryStream(bytes), attribs) - | ILResourceLocation.LocalOut bytes -> - modB.DefineManifestResourceAndLog(r.Name, new System.IO.MemoryStream(bytes), attribs) + | ILResourceLocation.Local bytes -> + use stream = bytes.AsStream() + modB.DefineManifestResourceAndLog (r.Name, stream, attribs) | ILResourceLocation.File (mr, _) -> - asmB.AddResourceFileAndLog(r.Name, mr.Name, attribs) + asmB.AddResourceFileAndLog (r.Name, mr.Name, attribs) | ILResourceLocation.Assembly _ -> failwith "references to resources other assemblies may not be emitted using System.Reflection") #endif @@ -2080,7 +2089,7 @@ let buildModuleFragment cenv emEnv (asmB: AssemblyBuilder) (modB: ModuleBuilder) //---------------------------------------------------------------------------- // test hook //---------------------------------------------------------------------------- -let defineDynamicAssemblyAndLog(asmName, flags, asmDir: string) = +let defineDynamicAssemblyAndLog (asmName, flags, asmDir: string) = #if FX_NO_APP_DOMAINS let asmB = AssemblyBuilder.DefineDynamicAssembly(asmName, flags) #else @@ -2106,14 +2115,14 @@ let mkDynamicAssemblyAndModule (assemblyName, optimize, debugInfo, collectible) #else else AssemblyBuilderAccess.RunAndSave #endif - let asmB = defineDynamicAssemblyAndLog(asmName, asmAccess, asmDir) + let asmB = defineDynamicAssemblyAndLog (asmName, asmAccess, asmDir) if not optimize then let daType = typeof let daCtor = daType.GetConstructor [| typeof |] let daBuilder = new CustomAttributeBuilder(daCtor, [| System.Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations ||| System.Diagnostics.DebuggableAttribute.DebuggingModes.Default |]) - asmB.SetCustomAttributeAndLog(daBuilder) + asmB.SetCustomAttributeAndLog daBuilder - let modB = asmB.DefineDynamicModuleAndLog(assemblyName, filename, debugInfo) + let modB = asmB.DefineDynamicModuleAndLog (assemblyName, filename, debugInfo) asmB, modB let emitModuleFragment (ilg, emEnv, asmB: AssemblyBuilder, modB: ModuleBuilder, modul: IL.ILModuleDef, debugInfo: bool, resolveAssemblyRef, tryFindSysILTypeRef) = @@ -2128,11 +2137,11 @@ let emitModuleFragment (ilg, emEnv, asmB: AssemblyBuilder, modB: ModuleBuilder, // invoke entry point methods let execEntryPtFun ((typB: TypeBuilder), methodName) () = try - ignore (typB.InvokeMemberAndLog(methodName, BindingFlags.InvokeMethod ||| BindingFlags.Public ||| BindingFlags.Static, [| |])) + ignore (typB.InvokeMemberAndLog (methodName, BindingFlags.InvokeMethod ||| BindingFlags.Public ||| BindingFlags.Static, [| |])) None with | :? System.Reflection.TargetInvocationException as e -> - Some(e.InnerException) + Some e.InnerException let emEnv, entryPts = envPopEntryPts emEnv let execs = List.map execEntryPtFun entryPts diff --git a/src/fcs-fable/src/absil/ilsign.fs b/src/fcs-fable/src/absil/ilsign.fs index 6b51af598d..6fbc1ca452 100644 --- a/src/fcs-fable/src/absil/ilsign.fs +++ b/src/fcs-fable/src/absil/ilsign.fs @@ -11,43 +11,43 @@ open System.Reflection.PortableExecutable open System.Security.Cryptography open System.Runtime.InteropServices - type KeyType = + type KeyType = | Public | KeyPair let ALG_TYPE_RSA = int (2 <<< 9) let ALG_CLASS_KEY_EXCHANGE = int (5 <<< 13) - let ALG_CLASS_SIGNATURE = int(1 <<< 13) - let CALG_RSA_KEYX = int(ALG_CLASS_KEY_EXCHANGE ||| ALG_TYPE_RSA) - let CALG_RSA_SIGN = int(ALG_CLASS_SIGNATURE ||| ALG_TYPE_RSA) - - let ALG_CLASS_HASH = int(4 <<< 13) - let ALG_TYPE_ANY = int(0) - let CALG_SHA1 = int(ALG_CLASS_HASH ||| ALG_TYPE_ANY ||| 4) - let CALG_SHA_256 = int(ALG_CLASS_HASH ||| ALG_TYPE_ANY ||| 12) - let CALG_SHA_384 = int(ALG_CLASS_HASH ||| ALG_TYPE_ANY ||| 13) - let CALG_SHA_512 = int(ALG_CLASS_HASH ||| ALG_TYPE_ANY ||| 14) - - let PUBLICKEYBLOB = int(0x6) - let PRIVATEKEYBLOB = int(0x7) - let BLOBHEADER_CURRENT_BVERSION = int(0x2) - let BLOBHEADER_LENGTH = int(20) - let RSA_PUB_MAGIC = int(0x31415352) - let RSA_PRIV_MAGIC = int(0x32415352) + let ALG_CLASS_SIGNATURE = int (1 <<< 13) + let CALG_RSA_KEYX = int (ALG_CLASS_KEY_EXCHANGE ||| ALG_TYPE_RSA) + let CALG_RSA_SIGN = int (ALG_CLASS_SIGNATURE ||| ALG_TYPE_RSA) + + let ALG_CLASS_HASH = int (4 <<< 13) + let ALG_TYPE_ANY = int 0 + let CALG_SHA1 = int (ALG_CLASS_HASH ||| ALG_TYPE_ANY ||| 4) + let CALG_SHA_256 = int (ALG_CLASS_HASH ||| ALG_TYPE_ANY ||| 12) + let CALG_SHA_384 = int (ALG_CLASS_HASH ||| ALG_TYPE_ANY ||| 13) + let CALG_SHA_512 = int (ALG_CLASS_HASH ||| ALG_TYPE_ANY ||| 14) + + let PUBLICKEYBLOB = int 0x6 + let PRIVATEKEYBLOB = int 0x7 + let BLOBHEADER_CURRENT_BVERSION = int 0x2 + let BLOBHEADER_LENGTH = int 20 + let RSA_PUB_MAGIC = int 0x31415352 + let RSA_PRIV_MAGIC = int 0x32415352 let getResourceString (_, str) = str - [] - type ByteArrayUnion = - struct - [] - val UnderlyingArray: byte[] + [] + type ByteArrayUnion = + [] + val UnderlyingArray: byte[] - []val ImmutableArray: ImmutableArray - new (immutableArray:ImmutableArray) = { UnderlyingArray = Array.empty; ImmutableArray = immutableArray} - end + [] + val ImmutableArray: ImmutableArray - let getUnderlyingArray (array:ImmutableArray) =ByteArrayUnion(array).UnderlyingArray + new (immutableArray: ImmutableArray) = { UnderlyingArray = Array.empty; ImmutableArray = immutableArray} + + let getUnderlyingArray (array: ImmutableArray) =ByteArrayUnion(array).UnderlyingArray // Compute a hash over the elements of an assembly manifest file that should // remain static (skip checksum, Authenticode signatures and strong name signature blob) @@ -64,8 +64,8 @@ open System.Runtime.InteropServices | PEMagic.PE32Plus -> peHeaderOffset + 0x90,0xF0 // offsetof(IMAGE_OPTIONAL_HEADER64, DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY]), sizeof(IMAGE_OPTIONAL_HEADER64) | _ -> raise (BadImageFormatException(getResourceString(FSComp.SR.ilSignInvalidMagicValue()))) - let allHeadersSize = peHeaderOffset + peHeaderSize + int(peHeaders.CoffHeader.NumberOfSections) * 0x28; // sizeof(IMAGE_SECTION_HEADER) - let allHeaders = + let allHeadersSize = peHeaderOffset + peHeaderSize + int (peHeaders.CoffHeader.NumberOfSections) * 0x28; // sizeof(IMAGE_SECTION_HEADER) + let allHeaders = let array:byte[] = Array.zeroCreate allHeadersSize peReader.GetEntireImage().GetContent().CopyTo(0, array, 0, allHeadersSize) array @@ -78,7 +78,7 @@ open System.Runtime.InteropServices // Hash content of all sections let signatureDirectory = peHeaders.CorHeader.StrongNameSignatureDirectory let signatureStart = - match peHeaders.TryGetDirectoryOffset(signatureDirectory) with + match peHeaders.TryGetDirectoryOffset signatureDirectory with | true, value -> value | _ -> raise (BadImageFormatException(getResourceString(FSComp.SR.ilSignBadImageFormat()))) let signatureEnd = signatureStart + signatureDirectory.Size @@ -104,7 +104,7 @@ open System.Runtime.InteropServices () hashAlgorithm.GetHashAndReset() - type BlobReader = + type BlobReader = val mutable _blob:byte[] val mutable _offset:int new (blob:byte[]) = { _blob = blob; _offset = 0; } @@ -112,7 +112,7 @@ open System.Runtime.InteropServices member x.ReadInt32:int = let offset = x._offset x._offset <- offset + 4 - int(x._blob.[offset]) ||| (int (x._blob.[offset + 1]) <<< 8) ||| (int (x._blob.[offset + 2]) <<< 16) ||| (int (x._blob.[offset + 3]) <<< 24) + int (x._blob.[offset]) ||| (int (x._blob.[offset + 1]) <<< 8) ||| (int (x._blob.[offset + 2]) <<< 16) ||| (int (x._blob.[offset + 3]) <<< 24) member x.ReadBigInteger (length:int):byte[] = let arr:byte[] = Array.zeroCreate length @@ -121,35 +121,35 @@ open System.Runtime.InteropServices arr |> Array.rev let RSAParamatersFromBlob (blob:byte[]) keyType = - let mutable reader = BlobReader(blob) + let mutable reader = BlobReader blob if reader.ReadInt32 <> 0x00000207 && keyType = KeyType.KeyPair then raise (CryptographicException(getResourceString(FSComp.SR.ilSignPrivateKeyExpected()))) reader.ReadInt32 |>ignore // ALG_ID if reader.ReadInt32 <> RSA_PRIV_MAGIC then raise (CryptographicException(getResourceString(FSComp.SR.ilSignRsaKeyExpected()))) // 'RSA2' - let byteLen, halfLen = + let byteLen, halfLen = let bitLen = reader.ReadInt32 match bitLen % 16 with | 0 -> (bitLen / 8, bitLen / 16) | _ -> raise (CryptographicException(getResourceString(FSComp.SR.ilSignInvalidBitLen()))) let mutable key = RSAParameters() - key.Exponent <- reader.ReadBigInteger(4) - key.Modulus <- reader.ReadBigInteger(byteLen) - key.P <- reader.ReadBigInteger(halfLen) - key.Q <- reader.ReadBigInteger(halfLen) - key.DP <- reader.ReadBigInteger(halfLen) - key.DQ <- reader.ReadBigInteger(halfLen) - key.InverseQ <- reader.ReadBigInteger(halfLen) - key.D <- reader.ReadBigInteger(byteLen) + key.Exponent <- reader.ReadBigInteger 4 + key.Modulus <- reader.ReadBigInteger byteLen + key.P <- reader.ReadBigInteger halfLen + key.Q <- reader.ReadBigInteger halfLen + key.DP <- reader.ReadBigInteger halfLen + key.DQ <- reader.ReadBigInteger halfLen + key.InverseQ <- reader.ReadBigInteger halfLen + key.D <- reader.ReadBigInteger byteLen key - let toCLRKeyBlob (rsaParameters:RSAParameters) (algId:int) : byte[] = + let toCLRKeyBlob (rsaParameters:RSAParameters) (algId:int) : byte[] = let validateRSAField (field:byte[]) expected (name:string) = - if field <> null && field.Length <> expected then + if field <> null && field.Length <> expected then raise (CryptographicException(String.Format(getResourceString(FSComp.SR.ilSignInvalidRSAParams()), name))) - // The original FCall this helper emulates supports other algId's - however, the only algid we need to support is CALG_RSA_KEYX. We will not port the codepaths dealing with other algid's. + // The original FCall this helper emulates supports other algId's - however, the only algid we need to support is CALG_RSA_KEYX. We will not port the codepaths dealing with other algid's. if algId <> CALG_RSA_KEYX then raise (CryptographicException(getResourceString(FSComp.SR.ilSignInvalidAlgId()))) - // Validate the RSA structure first. + // Validate the RSA structure first. if rsaParameters.Modulus = null then raise (CryptographicException(String.Format(getResourceString(FSComp.SR.ilSignInvalidRSAParams()), "Modulus"))) if rsaParameters.Exponent = null || rsaParameters.Exponent.Length > 4 then raise (CryptographicException(String.Format(getResourceString(FSComp.SR.ilSignInvalidRSAParams()), "Exponent"))) @@ -159,11 +159,11 @@ open System.Runtime.InteropServices // We assume that if P != null, then so are Q, DP, DQ, InverseQ and D and indicate KeyPair RSA Parameters let isPrivate = if rsaParameters.P <> null then - validateRSAField (rsaParameters.P) halfModulusLength "P" - validateRSAField (rsaParameters.Q) halfModulusLength "Q" - validateRSAField (rsaParameters.DP) halfModulusLength "DP" - validateRSAField (rsaParameters.InverseQ) halfModulusLength "InverseQ" - validateRSAField (rsaParameters.D) halfModulusLength "D" + validateRSAField rsaParameters.P halfModulusLength "P" + validateRSAField rsaParameters.Q halfModulusLength "Q" + validateRSAField rsaParameters.DP halfModulusLength "DP" + validateRSAField rsaParameters.InverseQ halfModulusLength "InverseQ" + validateRSAField rsaParameters.D halfModulusLength "D" true else false @@ -171,33 +171,33 @@ open System.Runtime.InteropServices use ms = new MemoryStream() use bw = new BinaryWriter(ms) - bw.Write(int(CALG_RSA_SIGN)) // CLRHeader.aiKeyAlg - bw.Write(int(CALG_SHA1)) // CLRHeader.aiHashAlg - bw.Write(int(modulusLength + BLOBHEADER_LENGTH)) // CLRHeader.KeyLength + bw.Write(int CALG_RSA_SIGN) // CLRHeader.aiKeyAlg + bw.Write(int CALG_SHA1) // CLRHeader.aiHashAlg + bw.Write(int (modulusLength + BLOBHEADER_LENGTH)) // CLRHeader.KeyLength - // Write out the BLOBHEADER - bw.Write(byte(if isPrivate = true then PRIVATEKEYBLOB else PUBLICKEYBLOB)) // BLOBHEADER.bType - bw.Write(byte(BLOBHEADER_CURRENT_BVERSION)) // BLOBHEADER.bVersion - bw.Write(int16(0)) // BLOBHEADER.wReserved - bw.Write(int(CALG_RSA_SIGN)) // BLOBHEADER.aiKeyAlg + // Write out the BLOBHEADER + bw.Write(byte (if isPrivate = true then PRIVATEKEYBLOB else PUBLICKEYBLOB)) // BLOBHEADER.bType + bw.Write(byte BLOBHEADER_CURRENT_BVERSION) // BLOBHEADER.bVersion + bw.Write(int16 0) // BLOBHEADER.wReserved + bw.Write(int CALG_RSA_SIGN) // BLOBHEADER.aiKeyAlg - // Write the RSAPubKey header - bw.Write(int(if isPrivate then RSA_PRIV_MAGIC else RSA_PUB_MAGIC)) // RSAPubKey.magic - bw.Write(int(modulusLength * 8)) // RSAPubKey.bitLen + // Write the RSAPubKey header + bw.Write(int (if isPrivate then RSA_PRIV_MAGIC else RSA_PUB_MAGIC)) // RSAPubKey.magic + bw.Write(int (modulusLength * 8)) // RSAPubKey.bitLen let expAsDword = - let mutable buffer = int(0) + let mutable buffer = int 0 for i in 0 .. rsaParameters.Exponent.Length - 1 do - buffer <- (buffer <<< 8) ||| int(rsaParameters.Exponent.[i]) + buffer <- (buffer <<< 8) ||| int (rsaParameters.Exponent.[i]) buffer - bw.Write(expAsDword) // RSAPubKey.pubExp - bw.Write(rsaParameters.Modulus |> Array.rev) // Copy over the modulus for both public and private + bw.Write expAsDword // RSAPubKey.pubExp + bw.Write(rsaParameters.Modulus |> Array.rev) // Copy over the modulus for both public and private if isPrivate = true then do bw.Write(rsaParameters.P |> Array.rev) - bw.Write(rsaParameters.Q |> Array.rev) - bw.Write(rsaParameters.DP |> Array.rev) - bw.Write(rsaParameters.DQ |> Array.rev) + bw.Write(rsaParameters.Q |> Array.rev) + bw.Write(rsaParameters.DP |> Array.rev) + bw.Write(rsaParameters.DQ |> Array.rev) bw.Write(rsaParameters.InverseQ |> Array.rev) bw.Write(rsaParameters.D |> Array.rev) @@ -216,15 +216,15 @@ open System.Runtime.InteropServices let signatureDirectory = peHeaders.CorHeader.StrongNameSignatureDirectory let signatureOffset = if signatureDirectory.Size > signature.Length then raise (BadImageFormatException(getResourceString(FSComp.SR.ilSignInvalidSignatureSize()))) - match peHeaders.TryGetDirectoryOffset(signatureDirectory) with - | false, _ -> raise (BadImageFormatException(getResourceString(FSComp.SR.ilSignNoSignatureDirectory()))) - | true, signatureOffset -> int64(signatureOffset) + match peHeaders.TryGetDirectoryOffset signatureDirectory with + | false, _ -> raise (BadImageFormatException(getResourceString(FSComp.SR.ilSignNoSignatureDirectory()))) + | true, signatureOffset -> int64 signatureOffset stream.Seek(signatureOffset, SeekOrigin.Begin) |>ignore stream.Write(signature, 0, signature.Length) let corHeaderFlagsOffset = int64(peHeaders.CorHeaderStartOffset + 16) // offsetof(IMAGE_COR20_HEADER, Flags) stream.Seek(corHeaderFlagsOffset, SeekOrigin.Begin) |>ignore - stream.WriteByte((byte)(peHeaders.CorHeader.Flags ||| CorFlags.StrongNameSigned)) + stream.WriteByte (byte (peHeaders.CorHeader.Flags ||| CorFlags.StrongNameSigned)) () let signStream stream keyBlob = @@ -241,11 +241,11 @@ open System.Runtime.InteropServices let signatureSize (pk:byte[]) = if pk.Length < 25 then raise (CryptographicException(getResourceString(FSComp.SR.ilSignInvalidPKBlob()))) - let mutable reader = BlobReader(pk) - reader.ReadBigInteger(12) |> ignore // Skip CLRHeader - reader.ReadBigInteger(8) |> ignore // Skip BlobHeader + let mutable reader = BlobReader pk + reader.ReadBigInteger 12 |> ignore // Skip CLRHeader + reader.ReadBigInteger 8 |> ignore // Skip BlobHeader let magic = reader.ReadInt32 // Read magic - if not (magic = RSA_PRIV_MAGIC || magic = RSA_PUB_MAGIC) then // RSAPubKey.magic + if not (magic = RSA_PRIV_MAGIC || magic = RSA_PUB_MAGIC) then // RSAPubKey.magic raise (CryptographicException(getResourceString(FSComp.SR.ilSignInvalidPKBlob()))) let x = reader.ReadInt32 / 8 x @@ -254,5 +254,5 @@ open System.Runtime.InteropServices let getPublicKeyForKeyPair keyBlob = use rsa = RSA.Create() rsa.ImportParameters(RSAParamatersFromBlob keyBlob KeyType.KeyPair) - let rsaParameters = rsa.ExportParameters(false) + let rsaParameters = rsa.ExportParameters false toCLRKeyBlob rsaParameters CALG_RSA_KEYX diff --git a/src/fcs-fable/src/absil/ilsupp.fs b/src/fcs-fable/src/absil/ilsupp.fs old mode 100755 new mode 100644 index 5f9932662d..5773486388 --- a/src/fcs-fable/src/absil/ilsupp.fs +++ b/src/fcs-fable/src/absil/ilsupp.fs @@ -2,22 +2,16 @@ module internal FSharp.Compiler.AbstractIL.Internal.Support - -let DateTime1970Jan01 = new System.DateTime(1970,1,1,0,0,0,System.DateTimeKind.Utc) (* ECMA Spec (Oct2002), Part II, 24.2.2 PE File Header. *) -let absilWriteGetTimeStamp () = (System.DateTime.UtcNow - DateTime1970Jan01).TotalSeconds |> int - -open Internal.Utilities open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.Internal -open FSharp.Compiler.AbstractIL.Internal.Bytes -open FSharp.Compiler.AbstractIL.Diagnostics open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.AbstractIL.Internal.NativeRes +open FSharp.Compiler.AbstractIL.Internal.Utils #if FX_NO_CORHOST_SIGNER open FSharp.Compiler.AbstractIL.Internal.StrongNameSign #endif + open System open System.IO -open System.Text open System.Reflection #if !FX_NO_SYMBOLSTORE @@ -26,36 +20,37 @@ open System.Diagnostics.SymbolStore open System.Runtime.InteropServices open System.Runtime.CompilerServices -#if !FX_NO_LINKEDRESOURCES + +let DateTime1970Jan01 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc) (* ECMA Spec (Oct2002), Part II, 24.2.2 PE File Header. *) +let absilWriteGetTimeStamp () = (DateTime.UtcNow - DateTime1970Jan01).TotalSeconds |> int + // Force inline, so GetLastWin32Error calls are immediately after interop calls as seen by FxCop under Debug build. let inline ignore _x = () // Native Resource linking/unlinking type IStream = System.Runtime.InteropServices.ComTypes.IStream -#endif -let check _action (hresult) = - if uint32 hresult >= 0x80000000ul then - System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(hresult) +let check _action (hresult) = + if uint32 hresult >= 0x80000000ul then + System.Runtime.InteropServices.Marshal.ThrowExceptionForHR hresult //printf "action = %s, hresult = 0x%nx \n" action hresult - -type PEFileType = X86 | X64 let MAX_PATH = 260 let E_FAIL = 0x80004005 -let bytesToWord ((b0: byte), (b1: byte)) = - (int16)b0 ||| ((int16)b1 <<< 8) -let bytesToDWord ((b0: byte), (b1: byte), (b2: byte), (b3: byte)) = - (int)b0 ||| ((int)b1 <<< 8) ||| ((int)b2 <<< 16) ||| ((int)b3 <<< 24) +let bytesToWord ((b0: byte), (b1: byte)) = + int16 b0 ||| (int16 b1 <<< 8) + +let bytesToDWord ((b0: byte), (b1: byte), (b2: byte), (b3: byte)) = + int b0 ||| (int b1 <<< 8) ||| (int b2 <<< 16) ||| (int b3 <<< 24) + let bytesToQWord ((b0: byte), (b1: byte), (b2: byte), (b3: byte), (b4: byte), (b5: byte), (b6: byte), (b7: byte)) = - (int64)b0 ||| ((int64)b1 <<< 8) ||| ((int64)b2 <<< 16) ||| ((int64)b3 <<< 24) ||| ((int64)b4 <<< 32) ||| ((int64)b5 <<< 40) ||| ((int64)b6 <<< 48) ||| ((int64)b7 <<< 56) - -let dwToBytes n = [| (byte)(n &&& 0xff) ; (byte)((n >>> 8) &&& 0xff) ; (byte)((n >>> 16) &&& 0xff) ; (byte)((n >>> 24) &&& 0xff) |], 4 -let wToBytes (n: int16) = [| (byte)(n &&& 0xffs) ; (byte)((n >>> 8) &&& 0xffs) |], 2 + int64 b0 ||| (int64 b1 <<< 8) ||| (int64 b2 <<< 16) ||| (int64 b3 <<< 24) ||| (int64 b4 <<< 32) ||| (int64 b5 <<< 40) ||| (int64 b6 <<< 48) ||| (int64 b7 <<< 56) + +let dwToBytes n = [| byte (n &&& 0xff) ; byte ((n >>> 8) &&& 0xff) ; byte ((n >>> 16) &&& 0xff) ; byte ((n >>> 24) &&& 0xff) |], 4 +let wToBytes (n: int16) = [| byte (n &&& 0xffs) ; byte ((n >>> 8) &&& 0xffs) |], 2 -#if !FX_NO_LINKEDRESOURCES // REVIEW: factor these classes under one hierarchy, use reflection for creation from buffer and toBytes() // Though, everything I'd like to unify is static - metaclasses? type IMAGE_FILE_HEADER (m: int16, secs: int16, tds: int32, ptst: int32, nos: int32, soh: int16, c: int16) = @@ -66,47 +61,47 @@ type IMAGE_FILE_HEADER (m: int16, secs: int16, tds: int32, ptst: int32, nos: int let mutable numberOfSymbols = nos let mutable sizeOfOptionalHeader = soh let mutable characteristics = c - + member x.Machine with get() = machine - and set(value) = machine <- value - + and set value = machine <- value + member x.NumberOfSections with get() = numberOfSections - and set(value) = numberOfSections <- value - + and set value = numberOfSections <- value + member x.TimeDateStamp with get() = timeDateStamp - and set(value) = timeDateStamp <- value - + and set value = timeDateStamp <- value + member x.PointerToSymbolTable with get() = pointerToSymbolTable - and set(value) = pointerToSymbolTable <- value - + and set value = pointerToSymbolTable <- value + member x.NumberOfSymbols with get() = numberOfSymbols - and set(value) = numberOfSymbols <- value - - member x.SizeOfOptionalHeader + and set value = numberOfSymbols <- value + + member x.SizeOfOptionalHeader with get() = sizeOfOptionalHeader - and set(value) = sizeOfOptionalHeader <- value - + and set value = sizeOfOptionalHeader <- value + member x.Characteristics with get() = characteristics - and set(value) = characteristics <- value - - static member Width + and set value = characteristics <- value + + static member Width with get() = 20 - + member x.toBytes () = let buf = ByteBuffer.Create IMAGE_FILE_HEADER.Width - buf.EmitUInt16 ((uint16)machine) - buf.EmitUInt16 ((uint16)numberOfSections) + buf.EmitUInt16 (uint16 machine) + buf.EmitUInt16 (uint16 numberOfSections) buf.EmitInt32 timeDateStamp buf.EmitInt32 pointerToSymbolTable buf.EmitInt32 numberOfSymbols - buf.EmitUInt16 ((uint16)sizeOfOptionalHeader) - buf.EmitUInt16 ((uint16)characteristics) + buf.EmitUInt16 (uint16 sizeOfOptionalHeader) + buf.EmitUInt16 (uint16 characteristics) buf.Close() let bytesToIFH (buffer: byte[]) (offset: int) = @@ -131,54 +126,54 @@ type IMAGE_SECTION_HEADER(n: int64, ai: int32, va: int32, srd: int32, prd: int32 let mutable numberOfRelocations = nr let mutable numberOfLineNumbers = nl let mutable characteristics = c - + member x.Name with get() = name - and set(value) = name <- value - + and set value = name <- value + member x.PhysicalAddress with get() = addressInfo - and set(value) = addressInfo <- value - + and set value = addressInfo <- value + member x.VirtualSize with get() = addressInfo - and set(value) = addressInfo <- value - + and set value = addressInfo <- value + member x.VirtualAddress with get() = virtualAddress - and set(value) = virtualAddress <- value - + and set value = virtualAddress <- value + member x.SizeOfRawData with get() = sizeOfRawData - and set(value) = sizeOfRawData <- value - + and set value = sizeOfRawData <- value + member x.PointerToRawData with get() = pointerToRawData - and set(value) = pointerToRawData <- value - + and set value = pointerToRawData <- value + member x.PointerToRelocations with get() = pointerToRelocations - and set(value) = pointerToRelocations <- value - + and set value = pointerToRelocations <- value + member x.PointerToLineNumbers with get() = pointerToLineNumbers - and set(value) = pointerToLineNumbers <- value - + and set value = pointerToLineNumbers <- value + member x.NumberOfRelocations with get() = numberOfRelocations - and set(value) = numberOfRelocations <- value - + and set value = numberOfRelocations <- value + member x.NumberOfLineNumbers with get() = numberOfLineNumbers - and set(value) = numberOfLineNumbers <- value - + and set value = numberOfLineNumbers <- value + member x.Characteristics with get() = characteristics - and set(value) = characteristics <- value - - static member Width + and set value = characteristics <- value + + static member Width with get() = 40 - + member x.toBytes () = let buf = ByteBuffer.Create IMAGE_SECTION_HEADER.Width buf.EmitInt64 name @@ -188,11 +183,11 @@ type IMAGE_SECTION_HEADER(n: int64, ai: int32, va: int32, srd: int32, prd: int32 buf.EmitInt32 pointerToRawData buf.EmitInt32 pointerToRelocations buf.EmitInt32 pointerToLineNumbers - buf.EmitUInt16 ((uint16)numberOfRelocations) - buf.EmitUInt16 ((uint16)numberOfLineNumbers) + buf.EmitUInt16 (uint16 numberOfRelocations) + buf.EmitUInt16 (uint16 numberOfLineNumbers) buf.EmitInt32 characteristics buf.Close() - + let bytesToISH (buffer: byte[]) (offset: int) = if (buffer.Length - offset) < IMAGE_SECTION_HEADER.Width then @@ -215,40 +210,40 @@ type IMAGE_SYMBOL(n: int64, v: int32, sn: int16, t: int16, sc: byte, nas: byte) let mutable stype = t let mutable storageClass = sc let mutable numberOfAuxSymbols = nas - + member x.Name with get() = name - and set(v) = name <- v - + and set v = name <- v + member x.Value with get() = value - and set(v) = value <- v - + and set v = value <- v + member x.SectionNumber with get() = sectionNumber - and set(v) = sectionNumber <- v - + and set v = sectionNumber <- v + member x.Type with get() = stype - and set(v) = stype <- v - + and set v = stype <- v + member x.StorageClass with get() = storageClass - and set(v) = storageClass <- v - + and set v = storageClass <- v + member x.NumberOfAuxSymbols with get() = numberOfAuxSymbols - and set(v) = numberOfAuxSymbols <- v - + and set v = numberOfAuxSymbols <- v + static member Width with get() = 18 - + member x.toBytes() = let buf = ByteBuffer.Create IMAGE_SYMBOL.Width buf.EmitInt64 name buf.EmitInt32 value - buf.EmitUInt16 ((uint16)sectionNumber) - buf.EmitUInt16 ((uint16)stype) + buf.EmitUInt16 (uint16 sectionNumber) + buf.EmitUInt16 (uint16 stype) buf.EmitByte storageClass buf.EmitByte numberOfAuxSymbols buf.Close() @@ -262,45 +257,45 @@ let bytesToIS (buffer: byte[]) (offset: int) = bytesToWord(buffer.[offset+14], buffer.[offset+15]), // Type buffer.[offset+16], // StorageClass buffer.[offset+17]) // NumberOfAuxSymbols - + type IMAGE_RELOCATION(va: int32, sti: int32, t: int16) = let mutable virtualAddress = va // Also RelocCount let mutable symbolTableIndex = sti let mutable ty = t // type - + member x.VirtualAddress with get() = virtualAddress - and set(v) = virtualAddress <- v - + and set v = virtualAddress <- v + member x.RelocCount with get() = virtualAddress - and set(v) = virtualAddress <- v - + and set v = virtualAddress <- v + member x.SymbolTableIndex with get() = symbolTableIndex - and set(v) = symbolTableIndex <- v - + and set v = symbolTableIndex <- v + member x.Type with get() = ty - and set(v) = ty <- v - + and set v = ty <- v + static member Width with get() = 10 - + member x.toBytes() = let buf = ByteBuffer.Create IMAGE_RELOCATION.Width buf.EmitInt32 virtualAddress buf.EmitInt32 symbolTableIndex - buf.EmitUInt16 ((uint16)ty) + buf.EmitUInt16 (uint16 ty) buf.Close() - + let bytesToIR (buffer: byte[]) (offset: int) = if (buffer.Length - offset) < IMAGE_RELOCATION.Width then invalidArg "buffer" "buffer too small to fit an IMAGE_RELOCATION" IMAGE_RELOCATION( bytesToDWord(buffer.[offset], buffer.[offset+1], buffer.[offset+2], buffer.[offset+3]), bytesToDWord(buffer.[offset+4], buffer.[offset+5], buffer.[offset+6], buffer.[offset+7]), bytesToWord(buffer.[offset+8], buffer.[offset+9])) - + type IMAGE_RESOURCE_DIRECTORY(c: int32, tds: int32, mjv: int16, mnv: int16, nne: int16, nie: int16) = let mutable characteristics = c let mutable timeDateStamp = tds @@ -308,43 +303,43 @@ type IMAGE_RESOURCE_DIRECTORY(c: int32, tds: int32, mjv: int16, mnv: int16, nne: let mutable minorVersion = mnv let mutable numberOfNamedEntries = nne let mutable numberOfIdEntries = nie - + member x.Characteristics with get() = characteristics - and set(v) = characteristics <- v - + and set v = characteristics <- v + member x.TimeDateStamp with get() = timeDateStamp - and set(v) = timeDateStamp <- v - + and set v = timeDateStamp <- v + member x.MajorVersion with get() = majorVersion - and set(v) = majorVersion <- v - + and set v = majorVersion <- v + member x.MinorVersion with get() = minorVersion - and set(v) = minorVersion <- v - + and set v = minorVersion <- v + member x.NumberOfNamedEntries with get() = numberOfNamedEntries - and set(v) = numberOfNamedEntries <- v - + and set v = numberOfNamedEntries <- v + member x.NumberOfIdEntries with get() = numberOfIdEntries - and set(v) = numberOfIdEntries <- v - + and set v = numberOfIdEntries <- v + static member Width = 16 - + member x.toBytes () = let buf = ByteBuffer.Create IMAGE_RESOURCE_DIRECTORY.Width buf.EmitInt32 characteristics buf.EmitInt32 timeDateStamp - buf.EmitUInt16 ((uint16)majorVersion) - buf.EmitUInt16 ((uint16)minorVersion) - buf.EmitUInt16 ((uint16)numberOfNamedEntries) - buf.EmitUInt16 ((uint16)numberOfIdEntries) + buf.EmitUInt16 (uint16 majorVersion) + buf.EmitUInt16 (uint16 minorVersion) + buf.EmitUInt16 (uint16 numberOfNamedEntries) + buf.EmitUInt16 (uint16 numberOfIdEntries) buf.Close() - + let bytesToIRD (buffer: byte[]) (offset: int) = if (buffer.Length - offset) < IMAGE_RESOURCE_DIRECTORY.Width then invalidArg "buffer" "buffer too small to fit an IMAGE_RESOURCE_DIRECTORY" @@ -354,76 +349,76 @@ let bytesToIRD (buffer: byte[]) (offset: int) = bytesToWord(buffer.[offset+10], buffer.[offset+11]), // MinorVersion bytesToWord(buffer.[offset+12], buffer.[offset+13]), // NumberOfNamedEntries bytesToWord(buffer.[offset+14], buffer.[offset+15])) // NumberOfIdEntries - + type IMAGE_RESOURCE_DIRECTORY_ENTRY(n: int32, o: int32) = let mutable name = n let mutable offset = o - + member x.Name with get() = name - and set(v) = name <- v - + and set v = name <- v + member x.OffsetToData with get() = offset - and set(v) = offset <- v - + and set v = offset <- v + member x.OffsetToDirectory with get() = offset &&& 0x7fffffff - + member x.DataIsDirectory with get() = (offset &&& 0x80000000) <> 0 - + static member Width = 8 - - member x.toBytes () = + + member x.toBytes () = let buf = ByteBuffer.Create IMAGE_RESOURCE_DIRECTORY_ENTRY.Width buf.EmitInt32 name buf.EmitInt32 offset buf.Close() - + let bytesToIRDE (buffer: byte[]) (offset: int) = if (buffer.Length - offset) < IMAGE_RESOURCE_DIRECTORY_ENTRY.Width then invalidArg "buffer" "buffer too small to fit an IMAGE_RESOURCE_DIRECTORY_ENTRY" IMAGE_RESOURCE_DIRECTORY_ENTRY( bytesToDWord(buffer.[offset], buffer.[offset+1], buffer.[offset+2], buffer.[offset+3]), // Name bytesToDWord(buffer.[offset+4], buffer.[offset+5], buffer.[offset+6], buffer.[offset+7])) // Offset - + type IMAGE_RESOURCE_DATA_ENTRY(o: int32, s: int32, c: int32, r: int32) = let mutable offsetToData = o let mutable size = s let mutable codePage = c let mutable reserved = r - + member x.OffsetToData with get() = offsetToData - and set(v) = offsetToData <- v + and set v = offsetToData <- v member x.Size with get() = size - and set(v) = size <- v + and set v = size <- v member x.CodePage with get() = codePage - and set(v) = codePage <- v + and set v = codePage <- v member x.Reserved with get() = reserved - and set(v) = reserved <- v - + and set v = reserved <- v + static member Width = 16 - - member x.toBytes() = + + member x.toBytes() = let buf = ByteBuffer.Create IMAGE_RESOURCE_DATA_ENTRY.Width buf.EmitInt32 offsetToData buf.EmitInt32 size buf.EmitInt32 codePage buf.EmitInt32 reserved - + let bytesToIRDataE (buffer: byte[]) (offset: int) = - if (buffer.Length - offset) < IMAGE_RESOURCE_DATA_ENTRY.Width then + if (buffer.Length - offset) < IMAGE_RESOURCE_DATA_ENTRY.Width then invalidArg "buffer" "buffer too small to fit an IMAGE_RESOURCE_DATA_ENTRY" IMAGE_RESOURCE_DATA_ENTRY(bytesToDWord(buffer.[offset], buffer.[offset+1], buffer.[offset+2], buffer.[offset+3]), // OffsetToData bytesToDWord(buffer.[offset+4], buffer.[offset+5], buffer.[offset+6], buffer.[offset+7]), // Size bytesToDWord(buffer.[offset+8], buffer.[offset+9], buffer.[offset+10], buffer.[offset+11]), // CodePage bytesToDWord(buffer.[offset+12], buffer.[offset+13], buffer.[offset+14], buffer.[offset+15])) // Reserved - - + + type ResFormatHeader() = let mutable dwDataSize = 0 let mutable dwHeaderSize = 32 // The eventual supposed size of this structure in memory @@ -434,37 +429,45 @@ type ResFormatHeader() = let mutable wLangID = 0s let mutable dwVersion = 0 let mutable dwCharacteristics = 0 - + member x.DataSize with get() = dwDataSize - and set(v) = dwDataSize <- v + and set v = dwDataSize <- v + member x.HeaderSize with get() = dwHeaderSize - and set(v) = dwHeaderSize <- v + and set v = dwHeaderSize <- v + member x.TypeID with get() = dwTypeID - and set(v) = dwTypeID <- v + and set v = dwTypeID <- v + member x.NameID with get() = dwNameID - and set(v) = dwNameID <- v + and set v = dwNameID <- v + member x.DataVersion with get() = dwDataVersion - and set(v) = dwDataVersion <- v + and set v = dwDataVersion <- v + member x.MemFlags with get() = wMemFlags - and set(v) = wMemFlags <- v + and set v = wMemFlags <- v + member x.LangID with get() = wLangID - and set(v) = wLangID <- v + and set v = wLangID <- v + member x.Version with get() = dwVersion - and set(v) = dwVersion <- v + and set v = dwVersion <- v + member x.Characteristics with get() = dwCharacteristics - and set(v) = dwCharacteristics <- v - + and set v = dwCharacteristics <- v + static member Width = 32 - + member x.toBytes() = let buf = ByteBuffer.Create ResFormatHeader.Width buf.EmitInt32 dwDataSize @@ -472,12 +475,12 @@ type ResFormatHeader() = buf.EmitInt32 dwTypeID buf.EmitInt32 dwNameID buf.EmitInt32 dwDataVersion - buf.EmitUInt16 ((uint16)wMemFlags) - buf.EmitUInt16 ((uint16)wLangID) + buf.EmitUInt16 (uint16 wMemFlags) + buf.EmitUInt16 (uint16 wLangID) buf.EmitInt32 dwVersion buf.EmitInt32 dwCharacteristics buf.Close() - + type ResFormatNode(tid: int32, nid: int32, lid: int32, dataOffset: int32, pbLinkedResource: byte[]) = let mutable resHdr = ResFormatHeader() let mutable dataEntry = Unchecked.defaultof @@ -485,39 +488,35 @@ type ResFormatNode(tid: int32, nid: int32, lid: int32, dataOffset: int32, pbLink let mutable wzType = Unchecked.defaultof let mutable cName = 0 let mutable wzName = Unchecked.defaultof - - do + + do if (tid &&& 0x80000000) <> 0 then // REVIEW: Are names and types mutually exclusive? The C++ code didn't seem to think so, but I can't find any documentation - resHdr.TypeID <- 0 + resHdr.TypeID <- 0 let mtid = tid &&& 0x7fffffff - cType <- bytesToDWord(pbLinkedResource.[mtid], pbLinkedResource.[mtid+1], pbLinkedResource.[mtid+2], pbLinkedResource.[mtid+3]) - wzType <- Bytes.zeroCreate ((cType + 1) * 2) + cType <- bytesToDWord(pbLinkedResource.[mtid], pbLinkedResource.[mtid+1], pbLinkedResource.[mtid+2], pbLinkedResource.[mtid+3]) + wzType <- Bytes.zeroCreate ((cType + 1) * 2) Bytes.blit pbLinkedResource 4 wzType 0 (cType * 2) else - resHdr.TypeID <- (0xffff ||| ((tid &&& 0xffff) <<< 16)) - + resHdr.TypeID <- (0xffff ||| ((tid &&& 0xffff) <<< 16)) + if (nid &&& 0x80000000) <> 0 then - resHdr.NameID <- 0 + resHdr.NameID <- 0 let mnid = nid &&& 0x7fffffff - cName <- bytesToDWord(pbLinkedResource.[mnid], pbLinkedResource.[mnid+1], pbLinkedResource.[mnid+2], pbLinkedResource.[mnid+3]) - wzName <- Bytes.zeroCreate ((cName + 1) * 2) + cName <- bytesToDWord(pbLinkedResource.[mnid], pbLinkedResource.[mnid+1], pbLinkedResource.[mnid+2], pbLinkedResource.[mnid+3]) + wzName <- Bytes.zeroCreate ((cName + 1) * 2) Bytes.blit pbLinkedResource 4 wzName 0 (cName * 2) else resHdr.NameID <- (0xffff ||| ((nid &&& 0xffff) <<< 16)) - - resHdr.LangID <- (int16)lid - dataEntry <- bytesToIRDataE pbLinkedResource dataOffset + + resHdr.LangID <- (int16)lid + dataEntry <- bytesToIRDataE pbLinkedResource dataOffset resHdr.DataSize <- dataEntry.Size - - member x.ResHdr - with get() = resHdr - member x.DataEntry - with get() = dataEntry - member x.Type - with get() = wzType - member x.Name - with get() = wzName - + + member x.ResHdr = resHdr + member x.DataEntry = dataEntry + member x.Type = wzType + member x.Name = wzName + member x.Save(ulLinkedResourceBaseRVA: int32, pbLinkedResource: byte[], pUnlinkedResource: byte[], offset: int) = // Dump them to pUnlinkedResource // For each resource write header and data @@ -528,23 +527,23 @@ type ResFormatNode(tid: int32, nid: int32, lid: int32, dataOffset: int32, pbLink resHdr.HeaderSize <- resHdr.HeaderSize + ((cType + 1) * 2) - 4 if Unchecked.defaultof <> wzName then resHdr.HeaderSize <- resHdr.HeaderSize + ((cName + 1) * 2) - 4 - + let SaveChunk(p: byte[], sz: int) = if Unchecked.defaultof <> pUnlinkedResource then Bytes.blit p 0 pUnlinkedResource (!unlinkedResourceOffset + offset) sz unlinkedResourceOffset := !unlinkedResourceOffset + sz size := !size + sz - + () - + // ---- Constant part of the header: DWORD, DWORD SaveChunk(dwToBytes resHdr.DataSize) SaveChunk(dwToBytes resHdr.HeaderSize) - + let mutable dwFiller = 0 - + if Unchecked.defaultof <> wzType then - SaveChunk(wzType,((cType + 1) * 2)) + SaveChunk(wzType, ((cType + 1) * 2)) dwFiller <- dwFiller + cType + 1 else SaveChunk(dwToBytes resHdr.TypeID) @@ -553,200 +552,50 @@ type ResFormatNode(tid: int32, nid: int32, lid: int32, dataOffset: int32, pbLink dwFiller <- dwFiller + cName + 1 else SaveChunk(dwToBytes resHdr.NameID) - + let bNil = Bytes.zeroCreate 3 - + // Align remaining fields on DWORD (nb. poor bit twiddling code taken from ildasm's dres.cpp) if (dwFiller &&& 0x1) <> 0 then SaveChunk(bNil, 2) - - //---- Constant part of the header: DWORD,WORD,WORD,DWORD,DWORD + + //---- Constant part of the header: DWORD, WORD, WORD, DWORD, DWORD SaveChunk(dwToBytes resHdr.DataVersion) SaveChunk(wToBytes resHdr.MemFlags) SaveChunk(wToBytes resHdr.LangID) SaveChunk(dwToBytes resHdr.Version) SaveChunk(dwToBytes resHdr.Characteristics) - + //---- Header done, now data // just copying to make the code a bit cleaner - can blit if this ends up being a liability let pbData = pbLinkedResource.[(dataEntry.OffsetToData - ulLinkedResourceBaseRVA) ..] SaveChunk(pbData, dataEntry.Size) - - dwFiller <- dataEntry.Size &&& 0x3 + + dwFiller <- dataEntry.Size &&& 0x3 if dwFiller <> 0 then SaveChunk(bNil, 4 - dwFiller) - - !size -let linkNativeResources (unlinkedResources: byte[] list) (ulLinkedResourceBaseRVA: int32) (fileType: PEFileType) (outputFilePath: string) = - let nPEFileType = match fileType with X86 -> 0 | X64 -> 2 - let mutable tempResFiles: string list = [] - let mutable objBytes: byte[] = [||] - - let unlinkedResources = unlinkedResources |> List.filter (fun arr -> arr.Length > 0) - if isNil unlinkedResources then // bail if there's nothing to link - objBytes - else - // Part 1: Write unlinked resources to an object file for linking - // check if the first dword is 0x0 - let firstDWord = bytesToDWord(unlinkedResources.[0].[0], unlinkedResources.[0].[1], unlinkedResources.[0].[2], unlinkedResources.[0].[3]) - if firstDWord = 0 then - // build the command line invocation string for cvtres.exe - let corSystemDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() - // We'll use the current dir and a random file name rather than System.IO.Path.GetTempFileName - // to try and prevent the command line invocation string from being > MAX_PATH - - let outputFilePaths = - if outputFilePath = "" then - [ FileSystem.GetTempPathShim() ] - else - [ FileSystem.GetTempPathShim() ; (outputFilePath + "\\") ] + !size - // Get a unique random file - let rec GetUniqueRandomFileName(path) = - let tfn = path + System.IO.Path.GetRandomFileName() - if FileSystem.SafeExists(tfn) then - GetUniqueRandomFileName(path) - else - tfn - - - let machine = if 2 = nPEFileType then "X64" else "X86" - let cmdLineArgsPreamble = sprintf "/NOLOGO /READONLY /MACHINE:%s" machine - - let cvtres = corSystemDir + "cvtres.exe " - - let createCvtresArgs path = - let tempObjFileName = GetUniqueRandomFileName(path) - let mutable cmdLineArgs = sprintf "%s \"/Out:%s\"" cmdLineArgsPreamble tempObjFileName - let mutable resFiles: string list = [] - - for _ulr in unlinkedResources do - let tempResFileName = GetUniqueRandomFileName(path) - resFiles <- tempResFileName :: resFiles - cmdLineArgs <- cmdLineArgs + " \"" + tempResFileName + "\"" - let trf = resFiles - let cmd = cmdLineArgs - cmd,tempObjFileName,trf - - let cmdLineArgs,tempObjFileName,tempResFileNames = - let attempts = - outputFilePaths |> - List.map (fun path -> createCvtresArgs path) |> - List.filter (fun ((argstring: string),(_t: string),(_f: string list)) -> (cvtres.Length + argstring.Length) < MAX_PATH) - let invoc,tmp,files = - match attempts with - | [] -> createCvtresArgs ".\\" // hope for the best... - | (i,t,f) :: _rest -> i,t,f // use the first one, since they're listed in order of precedence - tempResFiles <- files - (invoc,tmp,files) - - let cvtresInvocation = cvtres + cmdLineArgs - - try - let mutable iFiles = 0 - - for ulr in unlinkedResources do - // REVIEW: What can go wrong here? What happens when the various file calls fail - // dump the unlinked resource bytes into the temp file - System.IO.File.WriteAllBytes(tempResFileNames.[iFiles], ulr) - iFiles <- iFiles + 1 - - // call cvtres.exe using the full cmd line string we've generated - - // check to see if the generated string is too long - if it is, fail with E_FAIL - if cvtresInvocation.Length >= MAX_PATH then - System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(E_FAIL) - - // REVIEW: We really shouldn't be calling out to cvtres - let mutable psi = System.Diagnostics.ProcessStartInfo(cvtres) - psi.Arguments <- cmdLineArgs - psi.CreateNoWindow <- true ; // REVIEW: For some reason, this still creates a window unless WindowStyle is set to hidden - psi.WindowStyle <- System.Diagnostics.ProcessWindowStyle.Hidden - let p = System.Diagnostics.Process.Start(psi) - - // Wait for the process to finish - p.WaitForExit() - - check "Process.Start" p.ExitCode // TODO: really need to check against 0 - - // Conversion was successful, so read the object file - objBytes <- FileSystem.ReadAllBytesShim(tempObjFileName) - //Array.Copy(objBytes, pbUnlinkedResource, pbUnlinkedResource.Length) - FileSystem.FileDelete(tempObjFileName) - finally - // clean up the temp files - List.iter (fun tempResFileName -> FileSystem.FileDelete(tempResFileName)) tempResFiles - - // Part 2: Read the COFF file held in pbUnlinkedResource, spit it out into pResBuffer and apply the COFF fixups - // pResBuffer will become the .rsrc section of the PE file - if (objBytes = Unchecked.defaultof) then - System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(E_FAIL) - - let hMod = bytesToIFH objBytes 0 - - if hMod.SizeOfOptionalHeader <> 0s then - System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(E_FAIL) - - let rsrc01Name = 0x313024637273722eL // ".rsrc$01" - let rsrc02Name = 0x323024637273722eL // ".rsrc$02" - let nullHdr = Unchecked.defaultof - let mutable rsrc01 = nullHdr - let mutable rsrc02 = nullHdr - - for i = 0 to (int)hMod.NumberOfSections do - let pSection = bytesToISH objBytes (IMAGE_FILE_HEADER.Width + (IMAGE_SECTION_HEADER.Width * i)) - if pSection.Name = rsrc01Name then - rsrc01 <- pSection - else if pSection.Name = rsrc02Name then - rsrc02 <- pSection - - if (nullHdr = rsrc01) || (nullHdr = rsrc02) then - // One of the rsrc sections wasn't found - System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(E_FAIL) - - let size = rsrc01.SizeOfRawData + rsrc02.SizeOfRawData - - let pResBuffer = Bytes.zeroCreate size - - // Copy over the raw data - Bytes.blit objBytes rsrc01.PointerToRawData pResBuffer 0 rsrc01.SizeOfRawData - - // map all the relocs in .rsrc$01 using the reloc and symbol tables in the COFF object - let symbolTableHead = hMod.PointerToSymbolTable - let IMAGE_SYM_CLASS_STATIC = 0x3uy - let IMAGE_SYM_TYPE_NULL = 0x0s - - let GetSymbolEntry (buffer: byte[]) (idx: int) = - bytesToIS buffer (symbolTableHead + (idx * IMAGE_SYMBOL.Width) ) - - for iReloc = 0 to (int)(rsrc01.NumberOfRelocations - 1s) do - let pReloc = bytesToIR objBytes (rsrc01.PointerToRelocations + (iReloc * IMAGE_RELOCATION.Width)) - let IdxSymbol = pReloc.SymbolTableIndex - let pSymbolEntry = GetSymbolEntry objBytes IdxSymbol - - // Ensure the symbol entry is valid for a resource - if ((pSymbolEntry.StorageClass <> IMAGE_SYM_CLASS_STATIC) || - (pSymbolEntry.Type <> IMAGE_SYM_TYPE_NULL) || - (pSymbolEntry.SectionNumber <> 3s)) then - System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(E_FAIL) - - // Ensure that RVA is a valid address inside rsrc02 - if pSymbolEntry.Value >= rsrc02.SizeOfRawData then - // pSymbolEntry.Value is too big - System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(E_FAIL) - - // store the value - let vBuff, vSize = dwToBytes (ulLinkedResourceBaseRVA + rsrc01.SizeOfRawData + pSymbolEntry.Value) - //Bytes.blit objBytes rsrc02.PointerToRawData pResBuffer pReloc.VirtualAddress rsrc02.SizeOfRawData - Bytes.blit vBuff 0 pResBuffer pReloc.VirtualAddress vSize - // Copy $02 (resource raw into pResBuffer - Bytes.blit objBytes rsrc02.PointerToRawData pResBuffer rsrc01.SizeOfRawData rsrc02.SizeOfRawData - - // return the buffer - pResBuffer - -let unlinkResource (ulLinkedResourceBaseRVA: int32) (pbLinkedResource: byte[]) = +let linkNativeResources (unlinkedResources: byte[] list) (ulLinkedResourceBaseRVA: int32) = + let resources = + unlinkedResources + |> Seq.map (fun s -> new MemoryStream(s)) + |> Seq.map (fun s -> + let res = CvtResFile.ReadResFile s + s.Dispose() + res) + |> Seq.collect id + // See MakeWin32ResourceList https://github.com/dotnet/roslyn/blob/f40b89234db51da1e1153c14af184e618504be41/src/Compilers/Core/Portable/Compilation/Compilation.cs + |> Seq.map (fun r -> + Win32Resource(data = r.data, codePage = 0u, languageId = uint32 r.LanguageId, + id = int (int16 r.pstringName.Ordinal), name = r.pstringName.theString, + typeId = int (int16 r.pstringType.Ordinal), typeName = r.pstringType.theString)) + let bb = new System.Reflection.Metadata.BlobBuilder() + NativeResourceWriter.SerializeWin32Resources(bb, resources, ulLinkedResourceBaseRVA) + bb.ToArray() + +let unlinkResource (ulLinkedResourceBaseRVA: int32) (pbLinkedResource: byte[]) = let mutable nResNodes = 0 let pirdType = bytesToIRD pbLinkedResource 0 @@ -755,8 +604,8 @@ let unlinkResource (ulLinkedResourceBaseRVA: int32) (pbLinkedResource: byte[]) = // determine entry buffer size // TODO: coalesce these two loops - for iEntry = 0 to ((int)nEntries - 1) do - pirdeType <- bytesToIRDE pbLinkedResource (IMAGE_RESOURCE_DIRECTORY.Width + (iEntry * IMAGE_RESOURCE_DIRECTORY_ENTRY.Width)) + for iEntry = 0 to (int nEntries - 1) do + pirdeType <- bytesToIRDE pbLinkedResource (IMAGE_RESOURCE_DIRECTORY.Width + (iEntry * IMAGE_RESOURCE_DIRECTORY_ENTRY.Width)) if pirdeType.DataIsDirectory then let nameBase = pirdeType.OffsetToDirectory @@ -764,26 +613,26 @@ let unlinkResource (ulLinkedResourceBaseRVA: int32) (pbLinkedResource: byte[]) = let mutable pirdeName = Unchecked.defaultof let nEntries2 = pirdName.NumberOfNamedEntries + pirdName.NumberOfIdEntries - for iEntry2 = 0 to ((int)nEntries2 - 1) do - pirdeName <- bytesToIRDE pbLinkedResource (nameBase + (iEntry2 * IMAGE_RESOURCE_DIRECTORY_ENTRY.Width)) + for iEntry2 = 0 to (int nEntries2 - 1) do + pirdeName <- bytesToIRDE pbLinkedResource (nameBase + (iEntry2 * IMAGE_RESOURCE_DIRECTORY_ENTRY.Width)) if pirdeName.DataIsDirectory then let langBase = pirdeName.OffsetToDirectory let pirdLang = bytesToIRD pbLinkedResource langBase let nEntries3 = pirdLang.NumberOfNamedEntries + pirdLang.NumberOfIdEntries - - nResNodes <- nResNodes + ((int)nEntries3) + + nResNodes <- nResNodes + (int nEntries3) else - nResNodes <- nResNodes + 1 + nResNodes <- nResNodes + 1 else - nResNodes <- nResNodes + 1 + nResNodes <- nResNodes + 1 let pResNodes: ResFormatNode [] = Array.zeroCreate nResNodes - nResNodes <- 0 + nResNodes <- 0 // fill out the entry buffer - for iEntry = 0 to ((int)nEntries - 1) do - pirdeType <- bytesToIRDE pbLinkedResource (IMAGE_RESOURCE_DIRECTORY.Width + (iEntry * IMAGE_RESOURCE_DIRECTORY_ENTRY.Width)) + for iEntry = 0 to (int nEntries - 1) do + pirdeType <- bytesToIRDE pbLinkedResource (IMAGE_RESOURCE_DIRECTORY.Width + (iEntry * IMAGE_RESOURCE_DIRECTORY_ENTRY.Width)) let dwTypeID = pirdeType.Name // Need to skip VERSION and RT_MANIFEST resources // REVIEW: ideally we shouldn't allocate space for these, or rename properly so we don't get the naming conflict @@ -793,9 +642,9 @@ let unlinkResource (ulLinkedResourceBaseRVA: int32) (pbLinkedResource: byte[]) = let pirdName = bytesToIRD pbLinkedResource nameBase let mutable pirdeName = Unchecked.defaultof let nEntries2 = pirdName.NumberOfNamedEntries + pirdName.NumberOfIdEntries - - for iEntry2 = 0 to ((int)nEntries2 - 1) do - pirdeName <- bytesToIRDE pbLinkedResource (nameBase + (iEntry2 * IMAGE_RESOURCE_DIRECTORY_ENTRY.Width)) + + for iEntry2 = 0 to (int nEntries2 - 1) do + pirdeName <- bytesToIRDE pbLinkedResource (nameBase + (iEntry2 * IMAGE_RESOURCE_DIRECTORY_ENTRY.Width)) let dwNameID = pirdeName.Name if pirdeName.DataIsDirectory then @@ -803,36 +652,36 @@ let unlinkResource (ulLinkedResourceBaseRVA: int32) (pbLinkedResource: byte[]) = let pirdLang = bytesToIRD pbLinkedResource langBase let mutable pirdeLang = Unchecked.defaultof let nEntries3 = pirdLang.NumberOfNamedEntries + pirdLang.NumberOfIdEntries - - for iEntry3 = 0 to ((int)nEntries3 - 1) do - pirdeLang <- bytesToIRDE pbLinkedResource (langBase + (iEntry3 * IMAGE_RESOURCE_DIRECTORY_ENTRY.Width)) + + for iEntry3 = 0 to (int nEntries3 - 1) do + pirdeLang <- bytesToIRDE pbLinkedResource (langBase + (iEntry3 * IMAGE_RESOURCE_DIRECTORY_ENTRY.Width)) let dwLangID = pirdeLang.Name - + if pirdeLang.DataIsDirectory then // Resource hierarchy exceeds three levels System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(E_FAIL) else if (not skipResource) then let rfn = ResFormatNode(dwTypeID, dwNameID, dwLangID, pirdeLang.OffsetToData, pbLinkedResource) - pResNodes.[nResNodes] <- rfn - nResNodes <- nResNodes + 1 + pResNodes.[nResNodes] <- rfn + nResNodes <- nResNodes + 1 else if (not skipResource) then let rfn = ResFormatNode(dwTypeID, dwNameID, 0, pirdeName.OffsetToData, pbLinkedResource) - pResNodes.[nResNodes] <- rfn - nResNodes <- nResNodes + 1 + pResNodes.[nResNodes] <- rfn + nResNodes <- nResNodes + 1 else if (not skipResource) then let rfn = ResFormatNode(dwTypeID, 0, 0, pirdeType.OffsetToData, pbLinkedResource) // REVIEW: I believe these 0s are what's causing the duplicate res naming problems - pResNodes.[nResNodes] <- rfn - nResNodes <- nResNodes + 1 + pResNodes.[nResNodes] <- rfn + nResNodes <- nResNodes + 1 // Ok, all tree leaves are in ResFormatNode structs, and nResNodes ptrs are in pResNodes let mutable size = 0 if nResNodes <> 0 then - size <- size + ResFormatHeader.Width ; // sizeof(ResFormatHeader) + size <- size + ResFormatHeader.Width ; // sizeof ResFormatHeader for i = 0 to (nResNodes - 1) do - size <- size + pResNodes.[i].Save(ulLinkedResourceBaseRVA, pbLinkedResource, Unchecked.defaultof, 0) + size <- size + pResNodes.[i].Save(ulLinkedResourceBaseRVA, pbLinkedResource, Unchecked.defaultof, 0) let pResBuffer = Bytes.zeroCreate size @@ -849,14 +698,13 @@ let unlinkResource (ulLinkedResourceBaseRVA: int32) (pbLinkedResource: byte[]) = resBufferOffset <- resBufferOffset + pResNodes.[i].Save(ulLinkedResourceBaseRVA, pbLinkedResource, pResBuffer, resBufferOffset) pResBuffer -#endif #if !FX_NO_PDB_WRITER // PDB Writing [] [] -type IMetaDataDispenser = +type IMetaDataDispenser = abstract DefineScope: unit -> unit // need this here to fill the first vtable slot abstract OpenScope: [] szScope: string * [] dwOpenFlags: Int32 * [] riid: System.Guid byref * [] punk: Object byref -> unit @@ -865,7 +713,7 @@ type IMetaDataDispenser = [] type IMetadataImport = abstract Placeholder: unit -> unit - + [] [] [] @@ -879,9 +727,9 @@ type ISymUnmanagedDocumentWriter = abstract SetSource: sourceSize: int * [] source: byte[] -> unit abstract SetCheckSum: algorithmId: System.Guid * checkSumSize: int * [] checkSum: byte [] -> unit -// Struct used to retrieve info on the debug output +// Struct used to retrieve info on the debug output [] -type ImageDebugDirectory = +type ImageDebugDirectory = val Characteristics: int32 val TimeDateStamp: int32 val MajorVersion: int16 @@ -890,7 +738,7 @@ type ImageDebugDirectory = val SizeOfData: int32 val AddressOfRawData: int32 val PointerToRawData: int32 - + [] [] type ISymUnmanagedWriter2 = @@ -898,14 +746,14 @@ type ISymUnmanagedWriter2 = language: System.Guid byref * languageVendor: System.Guid byref * documentType: System.Guid byref * - [] RetVal: ISymUnmanagedDocumentWriter byref -> unit - abstract SetUserEntryPoint: entryMethod: uint32 -> unit + [] RetVal: ISymUnmanagedDocumentWriter byref -> unit + abstract SetUserEntryPoint: entryMethod: uint32 -> unit abstract OpenMethod: meth: int -> unit - abstract CloseMethod: unit -> unit - abstract OpenScope: startOffset: int * pRetVal: int byref -> unit + abstract CloseMethod: unit -> unit + abstract OpenScope: startOffset: int * pRetVal: int byref -> unit abstract CloseScope: endOffset: int -> unit - abstract SetScopeRange: scopeID: int * startOffset: int * endOffset: int -> unit - abstract DefineLocalVariable: [] varname: string * + abstract SetScopeRange: scopeID: int * startOffset: int * endOffset: int -> unit + abstract DefineLocalVariable: [] varName: string * attributes: int * cSig: int * []signature: byte[] * @@ -915,7 +763,7 @@ type ISymUnmanagedWriter2 = addr3: int * startOffset: int * endOffset: int -> unit - abstract DefineParameter: [] paramname: string * + abstract DefineParameter: [] paramName: string * attributes: int * sequence: int * addressKind: int * @@ -923,7 +771,7 @@ type ISymUnmanagedWriter2 = addr2: int * addr3: int -> unit abstract DefineField: parent: int * - [] fieldname: string * + [] fieldName: string * attributes: int * cSig: int * []signature: byte[] * @@ -931,7 +779,7 @@ type ISymUnmanagedWriter2 = addr1: int * addr2: int * addr3: int -> unit - abstract DefineGlobalVariable: [] globalvarname: string * + abstract DefineGlobalVariable: [] globalVarName: string * attributes: int * cSig: int * []signature: byte[] * @@ -941,7 +789,7 @@ type ISymUnmanagedWriter2 = addr3: int -> unit abstract Close: unit -> unit abstract SetSymAttribute: parent: int * - [] attname: string * + [] attName: string * cData: int * []data: byte[] -> unit abstract OpenNamespace: [] nsname: string -> unit @@ -958,7 +806,7 @@ type ISymUnmanagedWriter2 = stream: IStream * fullBuild: bool -> unit abstract GetDebugInfo: iDD: ImageDebugDirectory byref * - cData: int * + cData: int * pcData: int byref * []data: byte[] -> unit abstract DefineSequencePoints: document: ISymUnmanagedDocumentWriter * @@ -970,16 +818,16 @@ type ISymUnmanagedWriter2 = []endColumns: int [] -> unit abstract RemapToken: oldToken: int * newToken: int -> unit abstract Initialize2: emitter: nativeint * - [] tempfilename: string * + [] tempFileName: string * stream: IStream * fullBuild: bool * - [] finalfilename: string -> unit - abstract DefineConstant: [] constname: string * + [] finalFileName: string -> unit + abstract DefineConstant: [] constName: string * value: Object * cSig: int * []signature: byte[] -> unit abstract Abort: unit -> unit - abstract DefineLocalVariable2: [] localvarname2: string * + abstract DefineLocalVariable2: [] localVarName2: string * attributes: int * sigToken: int * addressKind: int * @@ -987,17 +835,17 @@ type ISymUnmanagedWriter2 = addr2: int * addr3: int * startOffset: int * - endOffset: int -> unit - abstract DefineGlobalVariable2: [] globalvarname2: string * + endOffset: int -> unit + abstract DefineGlobalVariable2: [] globalVarName2: string * attributes: int * sigToken: int * addressKind: int * addr1: int * addr2: int * - addr3: int -> unit - abstract DefineConstant2: [] constantname2: string * + addr3: int -> unit + abstract DefineConstant2: [] constantName2: string * value: Object * - sigToken: int -> unit + sigToken: int -> unit abstract OpenMethod2: method2: int * isect: int * offset: int -> unit @@ -1016,30 +864,30 @@ type idd = let pdbInitialize (binaryName: string) (pdbName: string) = // collect necessary COM types let CorMetaDataDispenser = System.Type.GetTypeFromProgID("CLRMetaData.CorMetaDataDispenser") - - // get the importer pointer + + // get the importer pointer let mdd = System.Activator.CreateInstance(CorMetaDataDispenser) :?> IMetaDataDispenser let mutable IID_IMetaDataEmit = new Guid("BA3FEE4C-ECB9-4E41-83B7-183FA41CD859") let mutable o = Object() mdd.OpenScope(binaryName, 0x1, &IID_IMetaDataEmit, &o) // 0x1 = ofWrite let emitterPtr = Marshal.GetComInterfaceForObject(o, typeof) - let writer = - try + let writer = + try let writer = Activator.CreateInstance(System.Type.GetTypeFromProgID("CorSymWriter_SxS")) :?> ISymUnmanagedWriter2 writer.Initialize(emitterPtr, pdbName, Unchecked.defaultof, true) writer - finally + finally // Marshal.GetComInterfaceForObject adds an extra ref for emitterPtr if IntPtr.Zero <> emitterPtr then - Marshal.Release(emitterPtr) |> ignore - + Marshal.Release emitterPtr |> ignore + { symWriter = writer } [] do() -let pdbCloseDocument(documentWriter: PdbDocumentWriter) = +let pdbCloseDocument(documentWriter: PdbDocumentWriter) = Marshal.ReleaseComObject (documentWriter.symDocWriter) |> ignore @@ -1057,7 +905,7 @@ let pdbClose (writer: PdbWriter) dllFilename pdbFilename = let rc = Marshal.ReleaseComObject(writer.symWriter) for i = 0 to (rc - 1) do Marshal.ReleaseComObject(writer.symWriter) |> ignore - + let isLocked filename = try use x = File.Open (filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None) @@ -1082,18 +930,18 @@ let guidSourceHashMD5 = System.Guid(0x406ea660u, 0x64cfus, 0x4c82us, 0xb6uy, 0xf let hashSizeOfMD5 = 16 // If the FIPS algorithm policy is enabled on the computer (e.g., for US government employees and contractors) -// then obtaining the MD5 implementation in BCL will throw. -// In this case, catch the failure, and not set a checksum. +// then obtaining the MD5 implementation in BCL will throw. +// In this case, catch the failure, and not set a checksum. let internal setCheckSum (url: string, writer: ISymUnmanagedDocumentWriter) = try - use file = FileSystem.FileStreamReadShim(url) + use file = FileSystem.FileStreamReadShim url use md5 = System.Security.Cryptography.MD5.Create() - let checkSum = md5.ComputeHash(file) + let checkSum = md5.ComputeHash file if (checkSum.Length = hashSizeOfMD5) then writer.SetCheckSum (guidSourceHashMD5, hashSizeOfMD5, checkSum) with _ -> () -let pdbDefineDocument (writer: PdbWriter) (url: string) = +let pdbDefineDocument (writer: PdbWriter) (url: string) = //3F5162F8-07C6-11D3-9053-00C04FA302A1 //let mutable corSymLanguageTypeCSharp = System.Guid(0x3F5162F8u, 0x07C6us, 0x11D3us, 0x90uy, 0x53uy, 0x00uy, 0xC0uy, 0x4Fuy, 0xA3uy, 0x02uy, 0xA1uy) let mutable corSymLanguageTypeFSharp = System.Guid(0xAB4F38C9u, 0xB6E6us, 0x43baus, 0xBEuy, 0x3Buy, 0x58uy, 0x08uy, 0x0Buy, 0x2Cuy, 0xCCuy, 0xE3uy) @@ -1104,35 +952,35 @@ let pdbDefineDocument (writer: PdbWriter) (url: string) = setCheckSum (url, docWriter) { symDocWriter = docWriter } -let pdbOpenMethod (writer: PdbWriter) (methodToken: int32) = - writer.symWriter.OpenMethod(methodToken) +let pdbOpenMethod (writer: PdbWriter) (methodToken: int32) = + writer.symWriter.OpenMethod methodToken -let pdbCloseMethod (writer: PdbWriter) = +let pdbCloseMethod (writer: PdbWriter) = writer.symWriter.CloseMethod() - -let pdbOpenScope (writer: PdbWriter) (startOffset: int32) = + +let pdbOpenScope (writer: PdbWriter) (startOffset: int32) = let mutable retInt = 0 writer.symWriter.OpenScope(startOffset, &retInt) check "action" (retInt) -let pdbCloseScope (writer: PdbWriter) (endOffset: int32) = - writer.symWriter.CloseScope(endOffset) +let pdbCloseScope (writer: PdbWriter) (endOffset: int32) = + writer.symWriter.CloseScope endOffset -let pdbDefineLocalVariable (writer: PdbWriter) (name: string) (signature: byte[]) (addr1: int32) = - writer.symWriter.DefineLocalVariable(name, 0, signature.Length, signature, (int)System.Diagnostics.SymbolStore.SymAddressKind.ILOffset, addr1, 0, 0, 0, 0) +let pdbDefineLocalVariable (writer: PdbWriter) (name: string) (signature: byte[]) (addr1: int32) = + writer.symWriter.DefineLocalVariable(name, 0, signature.Length, signature, int System.Diagnostics.SymbolStore.SymAddressKind.ILOffset, addr1, 0, 0, 0, 0) -let pdbSetMethodRange (writer: PdbWriter) (docWriter1: PdbDocumentWriter) (startLine: int) (startCol: int) (docWriter2: PdbDocumentWriter) (endLine: int) (endCol: int) = +let pdbSetMethodRange (writer: PdbWriter) (docWriter1: PdbDocumentWriter) (startLine: int) (startCol: int) (docWriter2: PdbDocumentWriter) (endLine: int) (endCol: int) = writer.symWriter.SetMethodSourceRange(docWriter1.symDocWriter, startLine, startCol, docWriter2.symDocWriter, endLine, endCol) -let pdbDefineSequencePoints (writer: PdbWriter) (docWriter: PdbDocumentWriter) (pts: (int * int * int * int * int)[]) = - let offsets = (Array.map (fun (x,_,_,_,_) -> x) pts) - let lines = (Array.map (fun (_,x,_,_,_) -> x) pts) - let columns = (Array.map (fun (_,_,x,_,_) -> x) pts) - let endLines = (Array.map (fun (_,_,_,x,_) -> x) pts) - let endColumns = (Array.map (fun (_,_,_,_,x) -> x) pts) +let pdbDefineSequencePoints (writer: PdbWriter) (docWriter: PdbDocumentWriter) (pts: (int * int * int * int * int)[]) = + let offsets = (Array.map (fun (x, _, _, _, _) -> x) pts) + let lines = (Array.map (fun (_, x, _, _, _) -> x) pts) + let columns = (Array.map (fun (_, _, x, _, _) -> x) pts) + let endLines = (Array.map (fun (_, _, _, x, _) -> x) pts) + let endColumns = (Array.map (fun (_, _, _, _, x) -> x) pts) writer.symWriter.DefineSequencePoints(docWriter.symDocWriter, pts.Length, offsets, lines, columns, endLines, endColumns) -let pdbWriteDebugInfo (writer: PdbWriter) = +let pdbWriteDebugInfo (writer: PdbWriter) = let mutable iDD = new ImageDebugDirectory() let mutable length = 0 writer.symWriter.GetDebugInfo(&iDD, 0, &length, null) @@ -1140,8 +988,8 @@ let pdbWriteDebugInfo (writer: PdbWriter) = writer.symWriter.GetDebugInfo(&iDD, length, &length, data) { iddCharacteristics = iDD.Characteristics - iddMajorVersion = (int32)iDD.MajorVersion - iddMinorVersion = (int32)iDD.MinorVersion + iddMajorVersion = int32 iDD.MajorVersion + iddMinorVersion = int32 iDD.MinorVersion iddType = iDD.Type iddData = data} #endif @@ -1155,7 +1003,7 @@ type PdbMethod = { symMethod: ISymbolMethod } type PdbVariable = { symVariable: ISymbolVariable } type PdbMethodScope = { symScope: ISymbolScope } -type PdbSequencePoint = +type PdbSequencePoint = { pdbSeqPointOffset: int pdbSeqPointDocument: PdbDocument pdbSeqPointLine: int @@ -1163,73 +1011,73 @@ type PdbSequencePoint = pdbSeqPointEndLine: int pdbSeqPointEndColumn: int } -let pdbReadOpen (moduleName: string) (path: string) : PdbReader = +let pdbReadOpen (moduleName: string) (path: string) : PdbReader = let CorMetaDataDispenser = System.Type.GetTypeFromProgID("CLRMetaData.CorMetaDataDispenser") let mutable IID_IMetaDataImport = new Guid("7DAC8207-D3AE-4c75-9B67-92801A497D44") let mdd = System.Activator.CreateInstance(CorMetaDataDispenser) :?> IMetaDataDispenser let mutable o: Object = new Object() - mdd.OpenScope(moduleName, 0, &IID_IMetaDataImport, &o) + mdd.OpenScope(moduleName, 0, &IID_IMetaDataImport, &o) let importerPtr = Marshal.GetComInterfaceForObject(o, typeof) - try + try #if ENABLE_MONO_SUPPORT - // ISymWrapper.dll is not available as a compile-time dependency for the cross-platform compiler, since it is Windows-only - // Access it via reflection instead.System.Diagnostics.SymbolStore.SymBinder - try - let isym = System.Reflection.Assembly.Load("ISymWrapper, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a") - let symbolBinder = isym.CreateInstance("System.Diagnostics.SymbolStore.SymBinder") - let symbolBinderTy = symbolBinder.GetType() - let reader = symbolBinderTy.InvokeMember("GetReader",BindingFlags.Public ||| BindingFlags.InvokeMethod ||| BindingFlags.Instance, null,symbolBinder,[| box importerPtr; box moduleName; box path |]) - { symReader = reader :?> ISymbolReader } - with _ -> - { symReader = null } -#else + // ISymWrapper.dll is not available as a compile-time dependency for the cross-platform compiler, since it is Windows-only + // Access it via reflection instead.System.Diagnostics.SymbolStore.SymBinder + try + let isym = System.Reflection.Assembly.Load("ISymWrapper, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a") + let symbolBinder = isym.CreateInstance("System.Diagnostics.SymbolStore.SymBinder") + let symbolBinderTy = symbolBinder.GetType() + let reader = symbolBinderTy.InvokeMember("GetReader", BindingFlags.Public ||| BindingFlags.InvokeMethod ||| BindingFlags.Instance, null, symbolBinder, [| box importerPtr; box moduleName; box path |]) + { symReader = reader :?> ISymbolReader } + with _ -> + { symReader = null } +#else let symbolBinder = new System.Diagnostics.SymbolStore.SymBinder() { symReader = symbolBinder.GetReader(importerPtr, moduleName, path) } #endif finally // Marshal.GetComInterfaceForObject adds an extra ref for importerPtr if IntPtr.Zero <> importerPtr then - Marshal.Release(importerPtr) |> ignore + Marshal.Release importerPtr |> ignore // The symbol reader's finalize method will clean up any unmanaged resources. // If file locks persist, we may want to manually invoke finalize let pdbReadClose (_reader: PdbReader) : unit = () -let pdbReaderGetMethod (reader: PdbReader) (token: int32) : PdbMethod = - { symMethod = reader.symReader.GetMethod(System.Diagnostics.SymbolStore.SymbolToken(token)) } +let pdbReaderGetMethod (reader: PdbReader) (token: int32) : PdbMethod = + { symMethod = reader.symReader.GetMethod(SymbolToken token) } -let pdbReaderGetMethodFromDocumentPosition (reader: PdbReader) (document: PdbDocument) (line: int) (column: int) : PdbMethod = +let pdbReaderGetMethodFromDocumentPosition (reader: PdbReader) (document: PdbDocument) (line: int) (column: int) : PdbMethod = { symMethod = reader.symReader.GetMethodFromDocumentPosition(document.symDocument, line, column) } -let pdbReaderGetDocuments (reader: PdbReader) : PdbDocument[] = +let pdbReaderGetDocuments (reader: PdbReader) : PdbDocument[] = let arr = reader.symReader.GetDocuments() Array.map (fun i -> { symDocument=i }) arr -let pdbReaderGetDocument (reader: PdbReader) (url: string) (language: byte[]) (languageVendor: byte[]) (documentType: byte[]) : PdbDocument = - { symDocument = reader.symReader.GetDocument(url, System.Guid(language), System.Guid(languageVendor), System.Guid(documentType)) } +let pdbReaderGetDocument (reader: PdbReader) (url: string) (language: byte[]) (languageVendor: byte[]) (documentType: byte[]) : PdbDocument = + { symDocument = reader.symReader.GetDocument(url, Guid language, Guid languageVendor, System.Guid documentType) } -let pdbDocumentGetURL (document: PdbDocument) : string = +let pdbDocumentGetURL (document: PdbDocument) : string = document.symDocument.URL -let pdbDocumentGetType (document: PdbDocument) : byte[] (* guid *) = +let pdbDocumentGetType (document: PdbDocument) : byte[] (* guid *) = let guid = document.symDocument.DocumentType guid.ToByteArray() -let pdbDocumentGetLanguage (document: PdbDocument) : byte[] (* guid *) = +let pdbDocumentGetLanguage (document: PdbDocument) : byte[] (* guid *) = let guid = document.symDocument.Language guid.ToByteArray() -let pdbDocumentGetLanguageVendor (document: PdbDocument) : byte[] = +let pdbDocumentGetLanguageVendor (document: PdbDocument) : byte[] = let guid = document.symDocument.LanguageVendor guid.ToByteArray() - -let pdbDocumentFindClosestLine (document: PdbDocument) (line: int) : int = - document.symDocument.FindClosestLine(line) -let pdbMethodGetToken (meth: PdbMethod) : int32 = +let pdbDocumentFindClosestLine (document: PdbDocument) (line: int) : int = + document.symDocument.FindClosestLine line + +let pdbMethodGetToken (meth: PdbMethod) : int32 = let token = meth.symMethod.Token token.GetToken() - + let pdbMethodGetSequencePoints (meth: PdbMethod) : PdbSequencePoint[] = let pSize = meth.symMethod.SequencePointCount let offsets = Array.zeroCreate pSize @@ -1238,37 +1086,37 @@ let pdbMethodGetSequencePoints (meth: PdbMethod) : PdbSequencePoint[] = let cols = Array.zeroCreate pSize let endLines = Array.zeroCreate pSize let endColumns = Array.zeroCreate pSize - + meth.symMethod.GetSequencePoints(offsets, docs, lines, cols, endLines, endColumns) - Array.init pSize (fun i -> + Array.init pSize (fun i -> { pdbSeqPointOffset = offsets.[i] pdbSeqPointDocument = { symDocument = docs.[i] } pdbSeqPointLine = lines.[i] pdbSeqPointColumn = cols.[i] pdbSeqPointEndLine = endLines.[i] - pdbSeqPointEndColumn = endColumns.[i] }) + pdbSeqPointEndColumn = endColumns.[i] }) -let pdbScopeGetChildren (scope: PdbMethodScope) : PdbMethodScope[] = +let pdbScopeGetChildren (scope: PdbMethodScope) : PdbMethodScope[] = let arr = scope.symScope.GetChildren() Array.map (fun i -> { symScope=i }) arr -let pdbScopeGetOffsets (scope: PdbMethodScope) : int * int = +let pdbScopeGetOffsets (scope: PdbMethodScope) : int * int = (scope.symScope.StartOffset, scope.symScope.EndOffset) -let pdbScopeGetLocals (scope: PdbMethodScope) : PdbVariable[] = +let pdbScopeGetLocals (scope: PdbMethodScope) : PdbVariable[] = let arr = scope.symScope.GetLocals() Array.map (fun i -> { symVariable=i }) arr -let pdbVariableGetName (variable: PdbVariable) : string = +let pdbVariableGetName (variable: PdbVariable) : string = variable.symVariable.Name -let pdbVariableGetSignature (variable: PdbVariable) : byte[] = +let pdbVariableGetSignature (variable: PdbVariable) : byte[] = variable.symVariable.GetSignature() // The tuple is (AddressKind, AddressField1) -let pdbVariableGetAddressAttributes (variable: PdbVariable) : (int32 * int32) = - (int32 variable.symVariable.AddressKind,variable.symVariable.AddressField1) +let pdbVariableGetAddressAttributes (variable: PdbVariable) : (int32 * int32) = + (int32 variable.symVariable.AddressKind, variable.symVariable.AddressField1) #endif // Key signing @@ -1279,27 +1127,27 @@ type pubkeyOptions = byte[] * bool #if FX_NO_CORHOST_SIGNER -let signerOpenPublicKeyFile filePath = FileSystem.ReadAllBytesShim(filePath) +let signerOpenPublicKeyFile filePath = FileSystem.ReadAllBytesShim filePath -let signerOpenKeyPairFile filePath = FileSystem.ReadAllBytesShim(filePath) +let signerOpenKeyPairFile filePath = FileSystem.ReadAllBytesShim filePath -let signerGetPublicKeyForKeyPair (kp: keyPair) : pubkey = +let signerGetPublicKeyForKeyPair (kp: keyPair) : pubkey = let reply = (StrongNameSign.getPublicKeyForKeyPair kp) reply -let signerGetPublicKeyForKeyContainer (_kcName: keyContainerName) : pubkey = +let signerGetPublicKeyForKeyContainer (_kcName: keyContainerName) : pubkey = raise (NotImplementedException("signerGetPublicKeyForKeyContainer is not yet implemented")) - -let signerCloseKeyContainer (_kc: keyContainerName) : unit = + +let signerCloseKeyContainer (_kc: keyContainerName) : unit = raise (NotImplementedException("signerCloseKeyContainer is not yet implemented")) -let signerSignatureSize (pk: pubkey) : int = +let signerSignatureSize (pk: pubkey) : int = (StrongNameSign.signatureSize pk) let signerSignFileWithKeyPair (fileName: string) (kp: keyPair) : unit = (StrongNameSign.signFile fileName kp) -let signerSignFileWithKeyContainer (_fileName: string) (_kcName: keyContainerName) : unit = +let signerSignFileWithKeyContainer (_fileName: string) (_kcName: keyContainerName) : unit = raise (NotImplementedException("signerSignFileWithKeyContainer is not yet implemented")) #else @@ -1310,10 +1158,10 @@ type UnusedCOMMethod = unit -> unit [] type ICLRMetaHost = [] - abstract GetRuntime: + abstract GetRuntime: [] version: string * [] interfaceId: System.Guid -> [] System.Object - + // Methods that we don't need are stubbed out for now... abstract GetVersionFromFile: UnusedCOMMethod abstract EnumerateInstalledRuntimes: UnusedCOMMethod @@ -1332,10 +1180,10 @@ type ICLRStrongName = abstract GetHashFromFileW: UnusedCOMMethod abstract GetHashFromHandle: UnusedCOMMethod abstract StrongNameCompareAssemblies: UnusedCOMMethod - + [] abstract StrongNameFreeBuffer: [] pbMemory: nativeint -> unit - + abstract StrongNameGetBlob: UnusedCOMMethod abstract StrongNameGetBlobFromImage: UnusedCOMMethod @@ -1346,7 +1194,7 @@ type ICLRStrongName = [] cbKeyBlob: uint32 * [] ppbPublicKeyBlob: nativeint byref * [] pcbPublicKeyBlob: uint32 byref -> unit - + abstract StrongNameHashSize: UnusedCOMMethod [] @@ -1364,7 +1212,7 @@ type ICLRStrongName = [] cbKeyBlob: uint32 * [] ppbSignatureBlob: nativeint * [] pcbSignatureBlob: uint32 byref -> unit - + abstract StrongNameSignatureGenerationEx: UnusedCOMMethod [] @@ -1372,7 +1220,7 @@ type ICLRStrongName = [] pbPublicKeyBlob: byte[] * [] cbPublicKeyBlob: uint32 * [] pcbSize: uint32 byref -> unit - + abstract StrongNameSignatureVerification: UnusedCOMMethod [] @@ -1380,12 +1228,12 @@ type ICLRStrongName = [] pwzFilePath: string * [] fForceVerification: bool * [] pfWasVerified: bool byref -> [] bool - + abstract StrongNameSignatureVerificationFromImage: UnusedCOMMethod abstract StrongNameTokenFromAssembly: UnusedCOMMethod abstract StrongNameTokenFromAssemblyEx: UnusedCOMMethod abstract StrongNameTokenFromPublicKey: UnusedCOMMethod - + [] [] @@ -1402,7 +1250,7 @@ type ICLRRuntimeInfo = abstract GetInterface : [] coClassId: System.Guid * [] interfaceId: System.Guid -> []System.Object - + [] [] let CreateInterface ( @@ -1411,9 +1259,9 @@ let CreateInterface ( ([] _metaHost : ICLRMetaHost byref)) : unit = failwith "CreateInterface" -let signerOpenPublicKeyFile filePath = FileSystem.ReadAllBytesShim(filePath) +let signerOpenPublicKeyFile filePath = FileSystem.ReadAllBytesShim filePath -let signerOpenKeyPairFile filePath = FileSystem.ReadAllBytesShim(filePath) +let signerOpenKeyPairFile filePath = FileSystem.ReadAllBytesShim filePath let mutable iclrsn: ICLRStrongName option = None let getICLRStrongName () = @@ -1424,7 +1272,7 @@ let getICLRStrongName () = let CLSID_CLRMetaHost = System.Guid(0x9280188Du, 0x0E8Eus, 0x4867us, 0xB3uy, 0x0Cuy, 0x7Fuy, 0xA8uy, 0x38uy, 0x84uy, 0xE8uy, 0xDEuy) let IID_ICLRMetaHost = System.Guid(0xD332DB9Eu, 0xB9B3us, 0x4125us, 0x82uy, 0x07uy, 0xA1uy, 0x48uy, 0x84uy, 0xF5uy, 0x32uy, 0x16uy) let clrRuntimeInfoGuid = System.Guid(0xBD39D1D2u, 0xBA2Fus, 0x486aus, 0x89uy, 0xB0uy, 0xB4uy, 0xB0uy, 0xCBuy, 0x46uy, 0x68uy, 0x91uy) - + let runtimeVer = System.Runtime.InteropServices.RuntimeEnvironment.GetSystemVersion() let mutable metaHost = Unchecked.defaultof CreateInterface(CLSID_CLRMetaHost, IID_ICLRMetaHost, &metaHost) @@ -1434,25 +1282,25 @@ let getICLRStrongName () = let sn = runtimeInfo.GetInterface(CLSID_CLRStrongName, IID_ICLRStrongName) :?> ICLRStrongName if Unchecked.defaultof = sn then failwith "Unable to obtain ICLRStrongName object" - iclrsn <- Some(sn) + iclrsn <- Some sn sn - | Some(sn) -> sn + | Some sn -> sn let signerGetPublicKeyForKeyPair kp = - if IL.runningOnMono then - let snt = System.Type.GetType("Mono.Security.StrongName") + if runningOnMono then + let snt = System.Type.GetType("Mono.Security.StrongName") let sn = System.Activator.CreateInstance(snt, [| box kp |]) - snt.InvokeMember("PublicKey", (BindingFlags.GetProperty ||| BindingFlags.Instance ||| BindingFlags.Public), null, sn, [| |], Globalization.CultureInfo.InvariantCulture) :?> byte[] + snt.InvokeMember("PublicKey", (BindingFlags.GetProperty ||| BindingFlags.Instance ||| BindingFlags.Public), null, sn, [| |], Globalization.CultureInfo.InvariantCulture) :?> byte[] else let mutable pSize = 0u let mutable pBuffer: nativeint = (nativeint)0 let iclrSN = getICLRStrongName() iclrSN.StrongNameGetPublicKey(Unchecked.defaultof, kp, (uint32) kp.Length, &pBuffer, &pSize) |> ignore - let mutable keybuffer: byte [] = Bytes.zeroCreate ((int)pSize) + let mutable keybuffer: byte [] = Bytes.zeroCreate (int pSize) // Copy the marshalled data over - we'll have to free this ourselves - Marshal.Copy(pBuffer, keybuffer, 0, (int)pSize) - iclrSN.StrongNameFreeBuffer(pBuffer) |> ignore + Marshal.Copy(pBuffer, keybuffer, 0, int pSize) + iclrSN.StrongNameFreeBuffer pBuffer |> ignore keybuffer let signerGetPublicKeyForKeyContainer kc = @@ -1460,18 +1308,18 @@ let signerGetPublicKeyForKeyContainer kc = let mutable pBuffer: nativeint = (nativeint)0 let iclrSN = getICLRStrongName() iclrSN.StrongNameGetPublicKey(kc, Unchecked.defaultof, 0u, &pBuffer, &pSize) |> ignore - let mutable keybuffer: byte [] = Bytes.zeroCreate ((int)pSize) + let mutable keybuffer: byte [] = Bytes.zeroCreate (int pSize) // Copy the marshalled data over - we'll have to free this ourselves later - Marshal.Copy(pBuffer, keybuffer, 0, (int)pSize) - iclrSN.StrongNameFreeBuffer(pBuffer) |> ignore + Marshal.Copy(pBuffer, keybuffer, 0, int pSize) + iclrSN.StrongNameFreeBuffer pBuffer |> ignore keybuffer - -let signerCloseKeyContainer kc = + +let signerCloseKeyContainer kc = let iclrSN = getICLRStrongName() - iclrSN.StrongNameKeyDelete(kc) |> ignore + iclrSN.StrongNameKeyDelete kc |> ignore -let signerSignatureSize (pk: byte[]) = - if IL.runningOnMono then +let signerSignatureSize (pk: byte[]) = + if runningOnMono then if pk.Length > 32 then pk.Length - 32 else 128 else let mutable pSize = 0u @@ -1479,9 +1327,9 @@ let signerSignatureSize (pk: byte[]) = iclrSN.StrongNameSignatureSize(pk, uint32 pk.Length, &pSize) |> ignore int pSize -let signerSignFileWithKeyPair fileName kp = - if IL.runningOnMono then - let snt = System.Type.GetType("Mono.Security.StrongName") +let signerSignFileWithKeyPair fileName kp = + if runningOnMono then + let snt = System.Type.GetType("Mono.Security.StrongName") let sn = System.Activator.CreateInstance(snt, [| box kp |]) let conv (x: obj) = if (unbox x: bool) then 0 else -1 snt.InvokeMember("Sign", (BindingFlags.InvokeMethod ||| BindingFlags.Instance ||| BindingFlags.Public), null, sn, [| box fileName |], Globalization.CultureInfo.InvariantCulture) |> conv |> check "Sign" diff --git a/src/fcs-fable/src/absil/ilsupp.fsi b/src/fcs-fable/src/absil/ilsupp.fsi old mode 100755 new mode 100644 index 48e7de602b..a32cdb605f --- a/src/fcs-fable/src/absil/ilsupp.fsi +++ b/src/fcs-fable/src/absil/ilsupp.fsi @@ -29,20 +29,14 @@ open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.IL -#if !FX_NO_LINKEDRESOURCES type IStream = System.Runtime.InteropServices.ComTypes.IStream -#endif /// Unmanaged resource file linker - for native resources (not managed ones). /// The function may be called twice, once with a zero-RVA and /// arbitrary buffer, and once with the real buffer. The size of the /// required buffer is returned. -type PEFileType = X86 | X64 - -#if !FX_NO_LINKEDRESOURCES -val linkNativeResources: unlinkedResources:byte[] list -> rva:int32 -> PEFileType -> tempFilePath:string -> byte[] +val linkNativeResources: unlinkedResources:byte[] list -> rva:int32 -> byte[] val unlinkResource: int32 -> byte[] -> byte[] -#endif #if !FX_NO_PDB_WRITER /// PDB reader and associated types diff --git a/src/fcs-fable/src/absil/ilwrite.fs b/src/fcs-fable/src/absil/ilwrite.fs old mode 100755 new mode 100644 index 3b00d55a9f..d86a2a710c --- a/src/fcs-fable/src/absil/ilwrite.fs +++ b/src/fcs-fable/src/absil/ilwrite.fs @@ -6,17 +6,14 @@ open System.Collections.Generic open System.IO open Internal.Utilities -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.ILAsciiWriter -open FSharp.Compiler.AbstractIL.IL -open FSharp.Compiler.AbstractIL.Diagnostics -open FSharp.Compiler.AbstractIL.Extensions.ILX.Types -open FSharp.Compiler.AbstractIL.Internal -open FSharp.Compiler.AbstractIL.Internal.BinaryConstants -open FSharp.Compiler.AbstractIL.Internal.Support -open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler.AbstractIL.Diagnostics +open FSharp.Compiler.AbstractIL.Internal +open FSharp.Compiler.AbstractIL.Internal.BinaryConstants +open FSharp.Compiler.AbstractIL.Internal.Support +open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.AbstractIL.Internal.Utils open FSharp.Compiler.AbstractIL.ILPdbWriter -open FSharp.Compiler.DiagnosticMessage open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Range #if FX_NO_CORHOST_SIGNER @@ -49,8 +46,8 @@ let dw2 n = byte ((n >>> 16) &&& 0xFFL) let dw1 n = byte ((n >>> 8) &&& 0xFFL) let dw0 n = byte (n &&& 0xFFL) -let bitsOfSingle (x: float32) = System.BitConverter.ToInt32(System.BitConverter.GetBytes(x), 0) -let bitsOfDouble (x: float) = System.BitConverter.DoubleToInt64Bits(x) +let bitsOfSingle (x: float32) = System.BitConverter.ToInt32(System.BitConverter.GetBytes x, 0) +let bitsOfDouble (x: float) = System.BitConverter.DoubleToInt64Bits x let emitBytesViaBuffer f = let bb = ByteBuffer.Create 10 in f bb; bb.Close() @@ -87,16 +84,16 @@ type ByteBuffer with buf.EmitByte 0x0uy // Emit compressed untagged integer - member buf.EmitZUntaggedIndex nm sz big idx = + member buf.EmitZUntaggedIndex big idx = if big then buf.EmitInt32 idx - elif idx > 0xffff then -#if NETSTANDARD1_6 - let trace = "no stack trace on.NET Standard 1.6" -#else - let trace = (new System.Diagnostics.StackTrace()).ToString() -#endif - failwithf "EmitZUntaggedIndex: index into table '%d' is too big for small address or simple index, idx = %d, big = %A, size of table = %d, stack = %s" nm idx big sz trace - else buf.EmitInt32AsUInt16 idx + else + // Note, we can have idx=0x10000 generated for method table idx + 1 for just beyond last index of method table. + // This indicates that a MethodList, FieldList, PropertyList or EventList has zero entries + // For this case, the EmitInt32AsUInt16 writes a 0 (null) into the field. Binary readers respect this as an empty + // list of methods/fields/properties/events. + if idx > 0x10000 then + System.Diagnostics.Debug.Assert (false, "EmitZUntaggedIndex: too big for small address or simple index") + buf.EmitInt32AsUInt16 idx // Emit compressed tagged integer member buf.EmitZTaggedIndex tag nbits big idx = @@ -161,18 +158,18 @@ type ILStrongNameSigner = static member OpenPublicKeyOptions s p = PublicKeyOptionsSigner((Support.signerOpenPublicKeyFile s), p) - static member OpenPublicKey pubkey = PublicKeySigner(pubkey) + static member OpenPublicKey pubkey = PublicKeySigner pubkey static member OpenKeyPairFile s = KeyPair(Support.signerOpenKeyPairFile s) - static member OpenKeyContainer s = KeyContainer(s) + static member OpenKeyContainer s = KeyContainer s member s.Close() = match s with | PublicKeySigner _ | PublicKeyOptionsSigner _ | KeyPair _ -> () - | KeyContainer containerName -> Support.signerCloseKeyContainer(containerName) + | KeyContainer containerName -> Support.signerCloseKeyContainer containerName member s.IsFullySigned = match s with @@ -191,7 +188,7 @@ type ILStrongNameSigner = member s.SignatureSize = let pkSignatureSize pk = - try Support.signerSignatureSize(pk) + try Support.signerSignatureSize pk with e -> failwith ("A call to StrongNameSignatureSize failed ("+e.Message+")") 0x80 @@ -452,26 +449,21 @@ type MetadataTable<'T> = member tbl.AddSharedEntry x = let n = tbl.rows.Count + 1 tbl.dict.[x] <- n - tbl.rows.Add(x) + tbl.rows.Add x n member tbl.AddUnsharedEntry x = let n = tbl.rows.Count + 1 - tbl.rows.Add(x) + tbl.rows.Add x n member tbl.FindOrAddSharedEntry x = #if DEBUG tbl.lookups <- tbl.lookups + 1 #endif -#if FABLE_COMPILER - let ok, res = tbl.dict.TryGetValue(x) -#else - let mutable res = Unchecked.defaultof<_> - let ok = tbl.dict.TryGetValue(x, &res) -#endif - if ok then res - else tbl.AddSharedEntry x + match tbl.dict.TryGetValue x with + | true, res -> res + | _ -> tbl.AddSharedEntry x /// This is only used in one special place - see further below. @@ -481,8 +473,8 @@ type MetadataTable<'T> = h.Clear() t |> Array.iteri (fun i x -> h.[x] <- (i+1)) - member tbl.AddUniqueEntry nm geterr x = - if tbl.dict.ContainsKey x then failwith ("duplicate entry '"+geterr x+"' in "+nm+" table") + member tbl.AddUniqueEntry nm getter x = + if tbl.dict.ContainsKey x then failwith ("duplicate entry '"+getter x+"' in "+nm+" table") else tbl.AddSharedEntry x member tbl.GetTableEntry x = tbl.dict.[x] @@ -549,9 +541,9 @@ type TypeDefTableKey = TdKey of string list (* enclosing *) * string (* type nam type MetadataTable = | Shared of MetadataTable | Unshared of MetadataTable - member t.FindOrAddSharedEntry(x) = match t with Shared u -> u.FindOrAddSharedEntry(x) | Unshared u -> failwithf "FindOrAddSharedEntry: incorrect table kind, u.name = %s" u.name - member t.AddSharedEntry(x) = match t with | Shared u -> u.AddSharedEntry(x) | Unshared u -> failwithf "AddSharedEntry: incorrect table kind, u.name = %s" u.name - member t.AddUnsharedEntry(x) = match t with Unshared u -> u.AddUnsharedEntry(x) | Shared u -> failwithf "AddUnsharedEntry: incorrect table kind, u.name = %s" u.name + member t.FindOrAddSharedEntry x = match t with Shared u -> u.FindOrAddSharedEntry x | Unshared u -> failwithf "FindOrAddSharedEntry: incorrect table kind, u.name = %s" u.name + member t.AddSharedEntry x = match t with | Shared u -> u.AddSharedEntry x | Unshared u -> failwithf "AddSharedEntry: incorrect table kind, u.name = %s" u.name + member t.AddUnsharedEntry x = match t with Unshared u -> u.AddUnsharedEntry x | Shared u -> failwithf "AddUnsharedEntry: incorrect table kind, u.name = %s" u.name member t.GenericRowsOfTable = match t with Unshared u -> u.EntriesAsArray |> Array.map (fun x -> x.GenericRow) | Shared u -> u.EntriesAsArray |> Array.map (fun x -> x.GenericRow) member t.SetRowsOfSharedTable rows = match t with Shared u -> u.SetRowsOfTable (Array.map SharedRow rows) | Unshared u -> failwithf "SetRowsOfSharedTable: incorrect table kind, u.name = %s" u.name member t.Count = match t with Unshared u -> u.Count | Shared u -> u.Count @@ -610,6 +602,7 @@ type cenv = member cenv.GetCode() = cenv.codeChunks.Close() + override x.ToString() = "" let FindOrAddSharedRow (cenv: cenv) tbl x = cenv.GetTable(tbl).FindOrAddSharedEntry x @@ -713,10 +706,10 @@ let rec GetIdxForTypeDef cenv key = let rec GetAssemblyRefAsRow cenv (aref: ILAssemblyRef) = AssemblyRefRow - ((match aref.Version with None -> 0us | Some (x, _, _, _) -> x), - (match aref.Version with None -> 0us | Some (_, y, _, _) -> y), - (match aref.Version with None -> 0us | Some (_, _, z, _) -> z), - (match aref.Version with None -> 0us | Some (_, _, _, w) -> w), + ((match aref.Version with None -> 0us | Some version -> version.Major), + (match aref.Version with None -> 0us | Some version -> version.Minor), + (match aref.Version with None -> 0us | Some version -> version.Build), + (match aref.Version with None -> 0us | Some version -> version.Revision), ((match aref.PublicKey with Some (PublicKey _) -> 0x0001 | _ -> 0x0000) ||| (if aref.Retargetable then 0x0100 else 0x0000)), BlobIndex (match aref.PublicKey with @@ -762,6 +755,7 @@ let GetScopeRefAsImplementationElem cenv scoref = | ILScopeRef.Local -> (i_AssemblyRef, 0) | ILScopeRef.Assembly aref -> (i_AssemblyRef, GetAssemblyRefAsIdx cenv aref) | ILScopeRef.Module mref -> (i_File, GetModuleRefAsFileIdx cenv mref) + | ILScopeRef.PrimaryAssembly -> (i_AssemblyRef, GetAssemblyRefAsIdx cenv cenv.ilg.primaryAssemblyRef) // -------------------------------------------------------------------- // Type references, types etc. @@ -773,14 +767,9 @@ let rec GetTypeRefAsTypeRefRow cenv (tref: ILTypeRef) = SharedRow [| ResolutionScope (rs1, rs2); nelem; nselem |] and GetTypeRefAsTypeRefIdx cenv tref = -#if FABLE_COMPILER - let ok, res = cenv.trefCache.TryGetValue(tref) -#else - let mutable res = 0 - let ok = cenv.trefCache.TryGetValue(tref, &res) -#endif - if ok then res - else + match cenv.trefCache.TryGetValue tref with + | true, res -> res + | _ -> let res = FindOrAddSharedRow cenv TableNames.TypeRef (GetTypeRefAsTypeRefRow cenv tref) cenv.trefCache.[tref] <- res res @@ -794,6 +783,7 @@ and GetResolutionScopeAsElem cenv (scoref, enc) = | ILScopeRef.Local -> (rs_Module, 1) | ILScopeRef.Assembly aref -> (rs_AssemblyRef, GetAssemblyRefAsIdx cenv aref) | ILScopeRef.Module mref -> (rs_ModuleRef, GetModuleRefAsIdx cenv mref) + | ILScopeRef.PrimaryAssembly -> (rs_AssemblyRef, GetAssemblyRefAsIdx cenv cenv.ilg.primaryAssemblyRef) else let enc2, n2 = List.frontAndBack enc (rs_TypeRef, GetTypeDescAsTypeRefIdx cenv (scoref, enc2, n2)) @@ -815,7 +805,7 @@ let getTypeDefOrRefAsUncodedToken (tag, idx) = else failwith "getTypeDefOrRefAsUncodedToken" getUncodedToken tab idx -// REVIEW: write into an accumuating buffer +// REVIEW: write into an accumulating buffer let EmitArrayShape (bb: ByteBuffer) (ILArrayShape shape) = let sized = List.filter (function (_, Some _) -> true | _ -> false) shape let lobounded = List.filter (function (Some _, _) -> true | _ -> false) shape @@ -843,7 +833,7 @@ let callconvToByte ntypars (Callconv (hasthis, bcc)) = | ILArgConvention.VarArg -> e_IMAGE_CEE_CS_CALLCONV_VARARG) -// REVIEW: write into an accumuating buffer +// REVIEW: write into an accumulating buffer let rec EmitTypeSpec cenv env (bb: ByteBuffer) (et, tspec: ILTypeSpec) = if isNil tspec.GenericArgs then bb.EmitByte et @@ -879,27 +869,25 @@ and GetTypeAsTypeSpecIdx cenv env ty = FindOrAddSharedRow cenv TableNames.TypeSpec (GetTypeAsTypeSpecRow cenv env ty) and EmitType cenv env bb ty = + let ilg = cenv.ilg match ty with - // REVIEW: what are these doing here? - | ILType.Value tspec when tspec.Name = "System.String" -> bb.EmitByte et_STRING - | ILType.Value tspec when tspec.Name = "System.Object" -> bb.EmitByte et_OBJECT - | ty when isILSByteTy ty -> bb.EmitByte et_I1 - | ty when isILInt16Ty ty -> bb.EmitByte et_I2 - | ty when isILInt32Ty ty -> bb.EmitByte et_I4 - | ty when isILInt64Ty ty -> bb.EmitByte et_I8 - | ty when isILByteTy ty -> bb.EmitByte et_U1 - | ty when isILUInt16Ty ty -> bb.EmitByte et_U2 - | ty when isILUInt32Ty ty -> bb.EmitByte et_U4 - | ty when isILUInt64Ty ty -> bb.EmitByte et_U8 - | ty when isILDoubleTy ty -> bb.EmitByte et_R8 - | ty when isILSingleTy ty -> bb.EmitByte et_R4 - | ty when isILBoolTy ty -> bb.EmitByte et_BOOLEAN - | ty when isILCharTy ty -> bb.EmitByte et_CHAR - | ty when isILStringTy ty -> bb.EmitByte et_STRING - | ty when isILObjectTy ty -> bb.EmitByte et_OBJECT - | ty when isILIntPtrTy ty -> bb.EmitByte et_I - | ty when isILUIntPtrTy ty -> bb.EmitByte et_U - | ty when isILTypedReferenceTy ty -> bb.EmitByte et_TYPEDBYREF + | ty when isILSByteTy ilg ty -> bb.EmitByte et_I1 + | ty when isILInt16Ty ilg ty -> bb.EmitByte et_I2 + | ty when isILInt32Ty ilg ty -> bb.EmitByte et_I4 + | ty when isILInt64Ty ilg ty -> bb.EmitByte et_I8 + | ty when isILByteTy ilg ty -> bb.EmitByte et_U1 + | ty when isILUInt16Ty ilg ty -> bb.EmitByte et_U2 + | ty when isILUInt32Ty ilg ty -> bb.EmitByte et_U4 + | ty when isILUInt64Ty ilg ty -> bb.EmitByte et_U8 + | ty when isILDoubleTy ilg ty -> bb.EmitByte et_R8 + | ty when isILSingleTy ilg ty -> bb.EmitByte et_R4 + | ty when isILBoolTy ilg ty -> bb.EmitByte et_BOOLEAN + | ty when isILCharTy ilg ty -> bb.EmitByte et_CHAR + | ty when isILStringTy ilg ty -> bb.EmitByte et_STRING + | ty when isILObjectTy ilg ty -> bb.EmitByte et_OBJECT + | ty when isILIntPtrTy ilg ty -> bb.EmitByte et_I + | ty when isILUIntPtrTy ilg ty -> bb.EmitByte et_U + | ty when isILTypedReferenceTy ilg ty -> bb.EmitByte et_TYPEDBYREF | ILType.Boxed tspec -> EmitTypeSpec cenv env bb (et_CLASS, tspec) | ILType.Value tspec -> EmitTypeSpec cenv env bb (et_VALUETYPE, tspec) @@ -953,7 +941,7 @@ and EmitCallsig cenv env bb (callconv, args: ILTypes, ret, varargs: ILVarArgs, g and GetCallsigAsBytes cenv env x = emitBytesViaBuffer (fun bb -> EmitCallsig cenv env bb x) -// REVIEW: write into an accumuating buffer +// REVIEW: write into an accumulating buffer and EmitTypes cenv env bb (inst: ILTypes) = inst |> List.iter (EmitType cenv env bb) @@ -985,7 +973,7 @@ let rec GetNativeTypeAsBlobIdx cenv (ty: ILNativeType) = and GetNativeTypeAsBytes ty = emitBytesViaBuffer (fun bb -> EmitNativeType bb ty) -// REVIEW: write into an accumuating buffer +// REVIEW: write into an accumulating buffer and EmitNativeType bb ty = if List.memAssoc ty (Lazy.force ILNativeTypeRevMap) then bb.EmitByte (List.assoc ty (Lazy.force ILNativeTypeRevMap)) @@ -1044,7 +1032,7 @@ and EmitNativeType bb ty = let rec GetFieldInitAsBlobIdx cenv (x: ILFieldInit) = GetBytesAsBlobIdx cenv (emitBytesViaBuffer (fun bb -> GetFieldInit bb x)) -// REVIEW: write into an accumuating buffer +// REVIEW: write into an accumulating buffer and GetFieldInit (bb: ByteBuffer) x = match x with | ILFieldInit.String b -> bb.EmitBytes (System.Text.Encoding.Unicode.GetBytes b) @@ -1102,7 +1090,7 @@ let GetTypeAccessFlags access = | ILTypeDefAccess.Nested ILMemberAccess.Public -> 0x00000002 | ILTypeDefAccess.Nested ILMemberAccess.Private -> 0x00000003 | ILTypeDefAccess.Nested ILMemberAccess.Family -> 0x00000004 - | ILTypeDefAccess.Nested ILMemberAccess.CompilerControlled -> failwith "bad type acccess" + | ILTypeDefAccess.Nested ILMemberAccess.CompilerControlled -> failwith "bad type access" | ILTypeDefAccess.Nested ILMemberAccess.FamilyAndAssembly -> 0x00000006 | ILTypeDefAccess.Nested ILMemberAccess.FamilyOrAssembly -> 0x00000007 | ILTypeDefAccess.Nested ILMemberAccess.Assembly -> 0x00000005 @@ -1267,7 +1255,7 @@ and GetFieldDefAsFieldDefIdx cenv tidx fd = // -------------------------------------------------------------------- // ILMethodRef --> ILMethodDef. // -// Only successfuly converts ILMethodRef's referring to +// Only successfully converts ILMethodRef's referring to // methods in the module being emitted. // -------------------------------------------------------------------- @@ -1448,7 +1436,7 @@ and GetFieldSpecAsMemberRefIdx cenv env fspec = let fenv = envForFieldSpec fspec FindOrAddSharedRow cenv TableNames.MemberRef (GetFieldSpecAsMemberRefRow cenv env fenv fspec) -// REVIEW: write into an accumuating buffer +// REVIEW: write into an accumulating buffer and EmitFieldSpecSig cenv env (bb: ByteBuffer) (fspec: ILFieldSpec) = bb.EmitByte e_IMAGE_CEE_CS_CALLCONV_FIELD EmitType cenv env bb fspec.FormalType @@ -1564,8 +1552,8 @@ type CodeBuffer = member codebuf.EmitUncodedToken u = codebuf.EmitInt32 u - member codebuf.RecordReqdStringFixup stringidx = - codebuf.reqdStringFixupsInMethod <- (codebuf.code.Position, stringidx) :: codebuf.reqdStringFixupsInMethod + member codebuf.RecordReqdStringFixup stringIdx = + codebuf.reqdStringFixupsInMethod <- (codebuf.code.Position, stringIdx) :: codebuf.reqdStringFixupsInMethod // Write a special value in that we check later when applying the fixup codebuf.EmitInt32 0xdeadbeef @@ -1601,7 +1589,7 @@ module Codebuf = go 0 (Array.length arr) let applyBrFixups (origCode : byte[]) origExnClauses origReqdStringFixups (origAvailBrFixups: Dictionary) origReqdBrFixups origSeqPoints origScopes = - let orderedOrigReqdBrFixups = origReqdBrFixups |> List.sortBy (fun (_, fixuploc, _) -> fixuploc) + let orderedOrigReqdBrFixups = origReqdBrFixups |> List.sortBy (fun (_, fixupLoc, _) -> fixupLoc) let newCode = ByteBuffer.Create origCode.Length @@ -1737,11 +1725,11 @@ module Codebuf = // Now apply the adjusted fixups in the new code newReqdBrFixups |> List.iter (fun (newFixupLoc, endOfInstr, tg, small) -> - match newAvailBrFixups.TryGetValue(tg) with + match newAvailBrFixups.TryGetValue tg with | true, n -> let relOffset = n - endOfInstr if small then - if Bytes.get newCode newFixupLoc <> 0x98 then failwith "br fixupsanity check failed" + if Bytes.get newCode newFixupLoc <> 0x98 then failwith "br fixup sanity check failed" newCode.[newFixupLoc] <- b0 relOffset else checkFixup32 newCode newFixupLoc 0xf00dd00fl @@ -2107,7 +2095,7 @@ module Codebuf = let roots, found = (false, roots) ||> List.mapFold (fun found (r, children) -> if found then ((r, children), true) - elif contains x r then ((r, x::children), true) + elif contains x r then ((r, x :: children), true) else ((r, children), false)) if found then roots @@ -2180,17 +2168,17 @@ module Codebuf = let pc2pos = Array.zeroCreate (instrs.Length+1) let pc2labs = Dictionary() for KeyValue (lab, pc) in code.Labels do - match pc2labs.TryGetValue(pc) with + match pc2labs.TryGetValue pc with | true, labels -> pc2labs.[pc] <- lab :: labels | _ -> pc2labs.[pc] <- [lab] // Emit the instructions for pc = 0 to instrs.Length do - match pc2labs.TryGetValue(pc) with + match pc2labs.TryGetValue pc with | true, labels -> for lab in labels do - codebuf.RecordAvailBrFixup(lab) + codebuf.RecordAvailBrFixup lab | _ -> () pc2pos.[pc] <- codebuf.code.Position if pc < instrs.Length then @@ -2702,7 +2690,7 @@ and GenEventPass3 cenv env (md: ILEventDef) = let rec GetResourceAsManifestResourceRow cenv r = let data, impl = - let embedManagedResources (bytes: byte[]) = + let embedManagedResources (bytes: ReadOnlyByteMemory) = // Embedded managed resources must be word-aligned. However resource format is // not specified in ECMA. Some mscorlib resources appear to be non-aligned - it seems it doesn't matter.. let offset = cenv.resources.Position @@ -2711,12 +2699,11 @@ let rec GetResourceAsManifestResourceRow cenv r = let resourceSize = bytes.Length cenv.resources.EmitPadding pad cenv.resources.EmitInt32 resourceSize - cenv.resources.EmitBytes bytes + cenv.resources.EmitByteMemory bytes Data (alignedOffset, true), (i_File, 0) match r.Location with - | ILResourceLocation.LocalIn _ -> embedManagedResources (r.GetBytes()) - | ILResourceLocation.LocalOut bytes -> embedManagedResources bytes + | ILResourceLocation.Local bytes -> embedManagedResources bytes | ILResourceLocation.File (mref, offset) -> ULong offset, (i_File, GetModuleRefAsFileIdx cenv mref) | ILResourceLocation.Assembly aref -> ULong 0x0, (i_AssemblyRef, GetAssemblyRefAsIdx cenv aref) @@ -2829,13 +2816,13 @@ and GenExportedTypesPass3 cenv (ce: ILExportedTypesAndForwarders) = // manifest --> generate Assembly row // -------------------------------------------------------------------- -and GetManifsetAsAssemblyRow cenv m = +and GetManifestAsAssemblyRow cenv m = UnsharedRow [|ULong m.AuxModuleHashAlgorithm - UShort (match m.Version with None -> 0us | Some (x, _, _, _) -> x) - UShort (match m.Version with None -> 0us | Some (_, y, _, _) -> y) - UShort (match m.Version with None -> 0us | Some (_, _, z, _) -> z) - UShort (match m.Version with None -> 0us | Some (_, _, _, w) -> w) + UShort (match m.Version with None -> 0us | Some version -> version.Major) + UShort (match m.Version with None -> 0us | Some version -> version.Minor) + UShort (match m.Version with None -> 0us | Some version -> version.Build) + UShort (match m.Version with None -> 0us | Some version -> version.Revision) ULong ( (match m.AssemblyLongevity with | ILAssemblyLongevity.Unspecified -> 0x0000 @@ -2845,7 +2832,7 @@ and GetManifsetAsAssemblyRow cenv m = | ILAssemblyLongevity.PlatformSystem -> 0x0008) ||| (if m.Retargetable then 0x100 else 0x0) ||| // Setting these causes peverify errors. Hence both ilread and ilwrite ignore them and refuse to set them. - // Any debugging customattributes will automatically propagate + // Any debugging customAttributes will automatically propagate // REVIEW: No longer appears to be the case (if m.JitTracking then 0x8000 else 0x0) ||| (match m.PublicKey with None -> 0x0000 | Some _ -> 0x0001) ||| 0x0000) @@ -2854,7 +2841,7 @@ and GetManifsetAsAssemblyRow cenv m = (match m.Locale with None -> StringE 0 | Some x -> StringE (GetStringHeapIdx cenv x)) |] and GenManifestPass3 cenv m = - let aidx = AddUnsharedRow cenv TableNames.Assembly (GetManifsetAsAssemblyRow cenv m) + let aidx = AddUnsharedRow cenv TableNames.Assembly (GetManifestAsAssemblyRow cenv m) GenSecurityDeclsPass3 cenv (hds_Assembly, aidx) m.SecurityDecls.AsList GenCustomAttrsPass3Or4 cenv (hca_Assembly, aidx) m.CustomAttrs GenExportedTypesPass3 cenv m.ExportedTypes @@ -3035,19 +3022,17 @@ let generateIL requiredDataFixups (desiredMetadataVersion, generatePdb, ilg : IL //===================================================================== // TABLES+BLOBS --> PHYSICAL METADATA+BLOBS //===================================================================== -let chunk sz next = ({addr=next; size=sz}, next + sz) +let chunk sz next = ({addr=next; size=sz}, next + sz) +let emptychunk next = ({addr=next; size=0}, next) let nochunk next = ({addr= 0x0;size= 0x0; }, next) let count f arr = Array.fold (fun x y -> x + f y) 0x0 arr -module FileSystemUtilites = +module FileSystemUtilities = open System open System.Reflection open System.Globalization -#if FX_RESHAPED_REFLECTION - open Microsoft.FSharp.Core.ReflectionAdapters -#endif let progress = try System.Environment.GetEnvironmentVariable("FSharp_DebugSetFilePermissions") <> null with _ -> false let setExecutablePermission (filename: string) = @@ -3101,9 +3086,8 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca let (mdtableVersionMajor, mdtableVersionMinor) = metadataSchemaVersionSupportedByCLRVersion desiredMetadataVersion - let version = - let (a, b, c, _) = desiredMetadataVersion - System.Text.Encoding.UTF8.GetBytes (sprintf "v%d.%d.%d" a b c) + let version = + System.Text.Encoding.UTF8.GetBytes (sprintf "v%d.%d.%d" desiredMetadataVersion.Major desiredMetadataVersion.Minor desiredMetadataVersion.Build) let paddedVersionLength = align 0x4 (Array.length version) @@ -3153,8 +3137,8 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca // If there are any generic parameters in the binary we're emitting then mark that // table as sorted, otherwise don't. This maximizes the number of assemblies we emit // which have an ECMA-v.1. compliant set of sorted tables. - (if tableSize (TableNames.GenericParam) > 0 then 0x00000400 else 0x00000000) ||| - (if tableSize (TableNames.GenericParamConstraint) > 0 then 0x00001000 else 0x00000000) ||| + (if tableSize TableNames.GenericParam > 0 then 0x00000400 else 0x00000000) ||| + (if tableSize TableNames.GenericParamConstraint > 0 then 0x00001000 else 0x00000000) ||| 0x00000200 reportTime showTimes "Layout Header of Tables" @@ -3214,10 +3198,8 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca let codedTables = - let sizesTable = Array.map Array.length sortedTables let bignessTable = Array.map (fun rows -> Array.length rows >= 0x10000) sortedTables let bigness (tab: int32) = bignessTable.[tab] - let size (tab: int32) = sizesTable.[tab] let codedBigness nbits tab = (tableSize tab) >= (0x10000 >>> nbits) @@ -3341,12 +3323,10 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca | _ when t = RowElementTags.ULong -> tablesBuf.EmitInt32 n | _ when t = RowElementTags.Data -> recordRequiredDataFixup requiredDataFixups tablesBuf (tablesStreamStart + tablesBuf.Position) (n, false) | _ when t = RowElementTags.DataResources -> recordRequiredDataFixup requiredDataFixups tablesBuf (tablesStreamStart + tablesBuf.Position) (n, true) - | _ when t = RowElementTags.Guid -> tablesBuf.EmitZUntaggedIndex -3 guidsStreamPaddedSize guidsBig (guidAddress n) - | _ when t = RowElementTags.Blob -> tablesBuf.EmitZUntaggedIndex -2 blobsStreamPaddedSize blobsBig (blobAddress n) - | _ when t = RowElementTags.String -> tablesBuf.EmitZUntaggedIndex -1 stringsStreamPaddedSize stringsBig (stringAddress n) - | _ when t <= RowElementTags.SimpleIndexMax -> - let tnum = t - RowElementTags.SimpleIndexMin - tablesBuf.EmitZUntaggedIndex tnum (size tnum) (bigness tnum) n + | _ when t = RowElementTags.Guid -> tablesBuf.EmitZUntaggedIndex guidsBig (guidAddress n) + | _ when t = RowElementTags.Blob -> tablesBuf.EmitZUntaggedIndex blobsBig (blobAddress n) + | _ when t = RowElementTags.String -> tablesBuf.EmitZUntaggedIndex stringsBig (stringAddress n) + | _ when t <= RowElementTags.SimpleIndexMax -> tablesBuf.EmitZUntaggedIndex (bigness (t - RowElementTags.SimpleIndexMin)) n | _ when t <= RowElementTags.TypeDefOrRefOrSpecMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.TypeDefOrRefOrSpecMin) 2 tdorBigness n | _ when t <= RowElementTags.TypeOrMethodDefMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.TypeOrMethodDefMin) 1 tomdBigness n | _ when t <= RowElementTags.HasConstantMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.HasConstantMin) 2 hcBigness n @@ -3530,8 +3510,8 @@ let writeDirectory os dict = let writeBytes (os: BinaryWriter) (chunk: byte[]) = os.Write(chunk, 0, chunk.Length) let writeBinaryAndReportMappings (outfile, - ilg: ILGlobals, pdbfile: string option, signer: ILStrongNameSigner option, portablePDB, embeddedPDB, - embedAllSource, embedSourceList, sourceLink, emitTailcalls, deterministic, showTimes, dumpDebugInfo ) + ilg: ILGlobals, pdbfile: string option, signer: ILStrongNameSigner option, portablePDB, embeddedPDB, + embedAllSource, embedSourceList, sourceLink, checksumAlgorithm, emitTailcalls, deterministic, showTimes, dumpDebugInfo, pathMap) modul normalizeAssemblyRefs = // Store the public key from the signer into the manifest. This means it will be written // to the binary and also acts as an indicator to leave space for delay sign @@ -3574,20 +3554,20 @@ let writeBinaryAndReportMappings (outfile, let os = try // Ensure the output directory exists otherwise it will fail - let dir = Path.GetDirectoryName(outfile) - if not (Directory.Exists(dir)) then Directory.CreateDirectory(dir) |>ignore - new BinaryWriter(FileSystem.FileStreamCreateShim(outfile)) + let dir = Path.GetDirectoryName outfile + if not (Directory.Exists dir) then Directory.CreateDirectory dir |>ignore + new BinaryWriter(FileSystem.FileStreamCreateShim outfile) with e -> failwith ("Could not open file for writing (binary mode): " + outfile) - let pdbData, pdbOpt, debugDirectoryChunk, debugDataChunk, debugEmbeddedPdbChunk, textV2P, mappings = + let pdbData, pdbOpt, debugDirectoryChunk, debugDataChunk, debugChecksumPdbChunk, debugEmbeddedPdbChunk, debugDeterministicPdbChunk, textV2P, mappings = try let imageBaseReal = modul.ImageBase // FIXED CHOICE let alignVirt = modul.VirtualAlignment // FIXED CHOICE let alignPhys = modul.PhysicalAlignment // FIXED CHOICE - let isItanium = modul.Platform = Some(IA64) + let isItanium = modul.Platform = Some IA64 let numSections = 3 // .text, .sdata, .reloc @@ -3642,11 +3622,12 @@ let writeBinaryAndReportMappings (outfile, match ilg.primaryAssemblyScopeRef with | ILScopeRef.Local -> failwith "Expected mscorlib to be ILScopeRef.Assembly was ILScopeRef.Local" | ILScopeRef.Module(_) -> failwith "Expected mscorlib to be ILScopeRef.Assembly was ILScopeRef.Module" - | ILScopeRef.Assembly(aref) -> + | ILScopeRef.PrimaryAssembly -> failwith "Expected mscorlib to be ILScopeRef.Assembly was ILScopeRef.PrimaryAssembly" + | ILScopeRef.Assembly aref -> match aref.Version with - | Some (2us, _, _, _) -> parseILVersion "2.0.50727.0" + | Some version when version.Major = 2us -> parseILVersion "2.0.50727.0" | Some v -> v - | None -> failwith "Expected msorlib to have a version number" + | None -> failwith "Expected mscorlib to have a version number" let entryPointToken, code, codePadding, metadata, data, resources, requiredDataFixups, pdbData, mappings, guidStart = writeILMetadataAndCode ((pdbfile <> None), desiredMetadataVersion, ilg, emitTailcalls, deterministic, showTimes) modul next normalizeAssemblyRefs @@ -3685,81 +3666,87 @@ let writeBinaryAndReportMappings (outfile, let pdbOpt = match portablePDB with | true -> - let (uncompressedLength, contentId, stream) as pdbStream = - generatePortablePdb embedAllSource embedSourceList sourceLink showTimes pdbData deterministic + let (uncompressedLength, contentId, stream, algorithmName, checkSum) as pdbStream = + generatePortablePdb embedAllSource embedSourceList sourceLink checksumAlgorithm showTimes pdbData pathMap - if embeddedPDB then Some (compressPortablePdbStream uncompressedLength contentId stream) - else Some (pdbStream) + if embeddedPDB then + let uncompressedLength, contentId, stream = compressPortablePdbStream uncompressedLength contentId stream + Some (uncompressedLength, contentId, stream, algorithmName, checkSum) + else Some pdbStream | _ -> None - let debugDirectoryChunk, next = - chunk (if pdbfile = None then - 0x0 - else if embeddedPDB && portablePDB then - sizeof_IMAGE_DEBUG_DIRECTORY * 2 + let debugDirectoryChunk, next = + chunk (if pdbfile = None then + 0x0 else - sizeof_IMAGE_DEBUG_DIRECTORY + sizeof_IMAGE_DEBUG_DIRECTORY * 2 + + (if embeddedPDB then sizeof_IMAGE_DEBUG_DIRECTORY else 0) + + (if deterministic then sizeof_IMAGE_DEBUG_DIRECTORY else 0) ) next + // The debug data is given to us by the PDB writer and appears to // typically be the type of the data plus the PDB file name. We fill // this in after we've written the binary. We approximate the size according // to what PDB writers seem to require and leave extra space just in case... let debugDataJustInCase = 40 - let debugDataChunk, next = + let debugDataChunk, next = chunk (align 0x4 (match pdbfile with | None -> 0 | Some f -> (24 - + System.Text.Encoding.Unicode.GetByteCount(f) // See bug 748444 + + System.Text.Encoding.Unicode.GetByteCount f // See bug 748444 + debugDataJustInCase))) next - let debugEmbeddedPdbChunk, next = - let streamLength = - match pdbOpt with - | Some (_, _, stream) -> int(stream.Length) - | None -> 0 - chunk (align 0x4 (match embeddedPDB with - | true -> 8 + streamLength - | _ -> 0 )) next + let debugChecksumPdbChunk, next = + chunk (align 0x4 (match pdbOpt with + | Some (_, _, _, algorithmName, checkSum) -> + let alg = System.Text.Encoding.UTF8.GetBytes(algorithmName) + let size = alg.Length + 1 + checkSum.Length + size + | None -> 0)) next + + let debugEmbeddedPdbChunk, next = + if embeddedPDB then + let streamLength = + match pdbOpt with + | Some (_, _, stream, _, _) -> int stream.Length + | None -> 0 + chunk (align 0x4 (match embeddedPDB with + | true -> 8 + streamLength + | _ -> 0 )) next + else + nochunk next + + let debugDeterministicPdbChunk, next = + if deterministic then emptychunk next + else nochunk next + let textSectionSize = next - textSectionAddr let nextPhys = align alignPhys (textSectionPhysLoc + textSectionSize) let textSectionPhysSize = nextPhys - textSectionPhysLoc let next = align alignVirt (textSectionAddr + textSectionSize) - - // .RSRC SECTION (DATA) + + // .RSRC SECTION (DATA) let dataSectionPhysLoc = nextPhys let dataSectionAddr = next let dataSectionVirtToPhys v = v - dataSectionAddr + dataSectionPhysLoc - - let resourceFormat = if modul.Is64Bit then Support.X64 else Support.X86 - - let nativeResources = + let nativeResources = match modul.NativeResources with | [] -> [||] | resources -> -#if ENABLE_MONO_SUPPORT - if runningOnMono then - [||] - else -#endif -#if FX_NO_LINKEDRESOURCES - ignore resources - ignore resourceFormat - [||] -#else - let unlinkedResources = - resources |> List.map (function - | ILNativeResource.Out bytes -> bytes - | ILNativeResource.In (fileName, linkedResourceBase, start, len) -> - let linkedResource = File.ReadBinaryChunk (fileName, start, len) - unlinkResource linkedResourceBase linkedResource) - - begin - try linkNativeResources unlinkedResources next resourceFormat (Path.GetDirectoryName(outfile)) - with e -> failwith ("Linking a native resource failed: "+e.Message+"") - end -#endif + let unlinkedResources = + resources |> List.map (function + | ILNativeResource.Out bytes -> bytes + | ILNativeResource.In (fileName, linkedResourceBase, start, len) -> + let linkedResource = File.ReadBinaryChunk (fileName, start, len) + unlinkResource linkedResourceBase linkedResource) + + begin + try linkNativeResources unlinkedResources next + with e -> failwith ("Linking a native resource failed: "+e.Message+"") + end + let nativeResourcesSize = nativeResources.Length let nativeResourcesChunk, next = chunk nativeResourcesSize next @@ -3819,35 +3806,39 @@ let writeBinaryAndReportMappings (outfile, if pCurrent <> pExpected then failwith ("warning: "+chunkName+" not where expected, pCurrent = "+string pCurrent+", p.addr = "+string pExpected) writeBytes os chunk - + let writePadding (os: BinaryWriter) _comment sz = if sz < 0 then failwith "writePadding: size < 0" for i = 0 to sz - 1 do os.Write 0uy - + // Now we've computed all the offsets, write the image - + write (Some msdosHeaderChunk.addr) os "msdos header" msdosHeader - + write (Some peSignatureChunk.addr) os "pe signature" [| |] - + writeInt32 os 0x4550 - + write (Some peFileHeaderChunk.addr) os "pe file header" [| |] - - if (modul.Platform = Some(AMD64)) then + + if (modul.Platform = Some AMD64) then writeInt32AsUInt16 os 0x8664 // Machine - IMAGE_FILE_MACHINE_AMD64 elif isItanium then writeInt32AsUInt16 os 0x200 else writeInt32AsUInt16 os 0x014c // Machine - IMAGE_FILE_MACHINE_I386 - + writeInt32AsUInt16 os numSections - let pdbData = + let pdbData = + // Hash code, data and metadata if deterministic then - // Hash code, data and metadata - use sha = System.Security.Cryptography.SHA1.Create() // IncrementalHash is core only + use sha = + match checksumAlgorithm with + | HashAlgorithm.Sha1 -> System.Security.Cryptography.SHA1.Create() :> System.Security.Cryptography.HashAlgorithm + | HashAlgorithm.Sha256 -> System.Security.Cryptography.SHA256.Create() :> System.Security.Cryptography.HashAlgorithm + let hCode = sha.ComputeHash code let hData = sha.ComputeHash data let hMeta = sha.ComputeHash metadata @@ -3863,8 +3854,9 @@ let writeBinaryAndReportMappings (outfile, // Use last 4 bytes for timestamp - High bit set, to stop tool chains becoming confused let timestamp = int final.[16] ||| (int final.[17] <<< 8) ||| (int final.[18] <<< 16) ||| (int (final.[19] ||| 128uy) <<< 24) writeInt32 os timestamp + // Update pdbData with new guid and timestamp. Portable and embedded PDBs don't need the ModuleID - // Full and PdbOnly aren't supported under deterministic builds currently, they rely on non-determinsitic Windows native code + // Full and PdbOnly aren't supported under deterministic builds currently, they rely on non-deterministic Windows native code { pdbData with ModuleID = final.[0..15] ; Timestamp = timestamp } else writeInt32 os timestamp // date since 1970 @@ -4148,20 +4140,22 @@ let writeBinaryAndReportMappings (outfile, if pdbfile.IsSome then write (Some (textV2P debugDirectoryChunk.addr)) os "debug directory" (Array.create debugDirectoryChunk.size 0x0uy) write (Some (textV2P debugDataChunk.addr)) os "debug data" (Array.create debugDataChunk.size 0x0uy) + write (Some (textV2P debugChecksumPdbChunk.addr)) os "debug checksum" (Array.create debugChecksumPdbChunk.size 0x0uy) if embeddedPDB then write (Some (textV2P debugEmbeddedPdbChunk.addr)) os "debug data" (Array.create debugEmbeddedPdbChunk.size 0x0uy) + if deterministic then + write (Some (textV2P debugDeterministicPdbChunk.addr)) os "debug deterministic" Array.empty + writePadding os "end of .text" (dataSectionPhysLoc - textSectionPhysLoc - textSectionSize) - // DATA SECTION -#if !FX_NO_LINKEDRESOURCES + // DATA SECTION match nativeResources with | [||] -> () | resources -> write (Some (dataSectionVirtToPhys nativeResourcesChunk.addr)) os "raw native resources" [| |] writeBytes os resources -#endif if dummydatap.size <> 0x0 then write (Some (dataSectionVirtToPhys dummydatap.addr)) os "dummy data" [| 0x0uy |] @@ -4194,10 +4188,10 @@ let writeBinaryAndReportMappings (outfile, os.Dispose() try - FileSystemUtilites.setExecutablePermission outfile + FileSystemUtilities.setExecutablePermission outfile with _ -> () - pdbData, pdbOpt, debugDirectoryChunk, debugDataChunk, debugEmbeddedPdbChunk, textV2P, mappings + pdbData, pdbOpt, debugDirectoryChunk, debugDataChunk, debugChecksumPdbChunk, debugEmbeddedPdbChunk, debugDeterministicPdbChunk, textV2P, mappings // Looks like a finally with e -> @@ -4222,11 +4216,11 @@ let writeBinaryAndReportMappings (outfile, try let idd = match pdbOpt with - | Some (originalLength, contentId, stream) -> + | Some (originalLength, contentId, stream, algorithmName, checkSum) -> if embeddedPDB then - embedPortablePdbInfo originalLength contentId stream showTimes fpdb debugDataChunk debugEmbeddedPdbChunk + embedPortablePdbInfo originalLength contentId stream showTimes fpdb debugDataChunk debugEmbeddedPdbChunk debugDeterministicPdbChunk debugChecksumPdbChunk algorithmName checkSum embeddedPDB deterministic else - writePortablePdbInfo contentId stream showTimes fpdb debugDataChunk + writePortablePdbInfo contentId stream showTimes fpdb pathMap debugDataChunk debugDeterministicPdbChunk debugChecksumPdbChunk algorithmName checkSum embeddedPDB deterministic | None -> #if FX_NO_PDB_WRITER Array.empty @@ -4236,7 +4230,7 @@ let writeBinaryAndReportMappings (outfile, reportTime showTimes "Generate PDB Info" // Now we have the debug data we can go back and fill in the debug directory in the image - let fs2 = FileSystem.FileStreamWriteExistingShim(outfile) + let fs2 = FileSystem.FileStreamWriteExistingShim outfile let os2 = new BinaryWriter(fs2) try // write the IMAGE_DEBUG_DIRECTORY @@ -4247,16 +4241,17 @@ let writeBinaryAndReportMappings (outfile, writeInt32AsUInt16 os2 i.iddMajorVersion writeInt32AsUInt16 os2 i.iddMinorVersion writeInt32 os2 i.iddType - writeInt32 os2 i.iddData.Length // IMAGE_DEBUG_DIRECTORY.SizeOfData - writeInt32 os2 i.iddChunk.addr // IMAGE_DEBUG_DIRECTORY.AddressOfRawData - writeInt32 os2 (textV2P i.iddChunk.addr) // IMAGE_DEBUG_DIRECTORY.PointerToRawData + writeInt32 os2 i.iddData.Length // IMAGE_DEBUG_DIRECTORY.SizeOfData + writeInt32 os2 i.iddChunk.addr // IMAGE_DEBUG_DIRECTORY.AddressOfRawData + writeInt32 os2 (textV2P i.iddChunk.addr) // IMAGE_DEBUG_DIRECTORY.PointerToRawData // Write the Debug Data for i in idd do - // write the debug raw data as given us by the PDB writer - os2.BaseStream.Seek (int64 (textV2P i.iddChunk.addr), SeekOrigin.Begin) |> ignore - if i.iddChunk.size < i.iddData.Length then failwith "Debug data area is not big enough. Debug info may not be usable" - writeBytes os2 i.iddData + if i.iddChunk.size <> 0 then + // write the debug raw data as given us by the PDB writer + os2.BaseStream.Seek (int64 (textV2P i.iddChunk.addr), SeekOrigin.Begin) |> ignore + if i.iddChunk.size < i.iddData.Length then failwith "Debug data area is not big enough. Debug info may not be usable" + writeBytes os2 i.iddData os2.Dispose() with e -> failwith ("Error while writing debug directory entry: "+e.Message) @@ -4265,9 +4260,7 @@ let writeBinaryAndReportMappings (outfile, with e -> reraise() - end - ignore debugDataChunk - ignore debugEmbeddedPdbChunk + end reportTime showTimes "Finalize PDB" /// Sign the binary. No further changes to binary allowed past this point! @@ -4295,14 +4288,16 @@ type options = embedAllSource: bool embedSourceList: string list sourceLink: string + checksumAlgorithm: HashAlgorithm signer: ILStrongNameSigner option - emitTailcalls : bool - deterministic : bool + emitTailcalls: bool + deterministic: bool showTimes: bool - dumpDebugInfo: bool } + dumpDebugInfo: bool + pathMap: PathMap } let WriteILBinary (outfile, (args: options), modul, normalizeAssemblyRefs) = writeBinaryAndReportMappings (outfile, args.ilg, args.pdbfile, args.signer, args.portablePDB, args.embeddedPDB, args.embedAllSource, - args.embedSourceList, args.sourceLink, args.emitTailcalls, args.deterministic, args.showTimes, args.dumpDebugInfo) modul normalizeAssemblyRefs + args.embedSourceList, args.sourceLink, args.checksumAlgorithm, args.emitTailcalls, args.deterministic, args.showTimes, args.dumpDebugInfo, args.pathMap) modul normalizeAssemblyRefs |> ignore diff --git a/src/fcs-fable/src/absil/ilwrite.fsi b/src/fcs-fable/src/absil/ilwrite.fsi old mode 100755 new mode 100644 index e7b2aaf3f4..9dba89c9b6 --- a/src/fcs-fable/src/absil/ilwrite.fsi +++ b/src/fcs-fable/src/absil/ilwrite.fsi @@ -1,11 +1,13 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. /// The IL Binary writer. -module internal FSharp.Compiler.AbstractIL.ILBinaryWriter +module internal FSharp.Compiler.AbstractIL.ILBinaryWriter -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.Internal -open FSharp.Compiler.AbstractIL.IL +open Internal.Utilities +open FSharp.Compiler.AbstractIL +open FSharp.Compiler.AbstractIL.Internal +open FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler.AbstractIL.ILPdbWriter [] type ILStrongNameSigner = @@ -23,11 +25,13 @@ type options = embedAllSource: bool embedSourceList: string list sourceLink: string + checksumAlgorithm: HashAlgorithm signer : ILStrongNameSigner option emitTailcalls: bool deterministic: bool showTimes : bool - dumpDebugInfo : bool } + dumpDebugInfo : bool + pathMap : PathMap } /// Write a binary to the file system. Extra configuration parameters can also be specified. val WriteILBinary: filename: string * options: options * input: ILModuleDef * (ILAssemblyRef -> ILAssemblyRef) -> unit diff --git a/src/fcs-fable/src/absil/ilwritepdb.fs b/src/fcs-fable/src/absil/ilwritepdb.fs index 09c765ed41..564cd99083 100644 --- a/src/fcs-fable/src/absil/ilwritepdb.fs +++ b/src/fcs-fable/src/absil/ilwritepdb.fs @@ -10,12 +10,12 @@ open System.IO.Compression open System.Reflection open System.Reflection.Metadata open System.Reflection.Metadata.Ecma335 -open System.Reflection.PortableExecutable +open System.Text open Internal.Utilities -open FSharp.Compiler.AbstractIL.IL -open FSharp.Compiler.AbstractIL.Diagnostics +open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Support open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.AbstractIL.Internal.Utils open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Range @@ -29,11 +29,11 @@ type BlobBuildingStream () = override this.CanWrite = true override this.CanRead = false override this.CanSeek = false - override this.Length = int64(builder.Count) + override this.Length = int64 (builder.Count) override this.Write(buffer: byte array, offset: int, count: int) = builder.WriteBytes(buffer, offset, count) - override this.WriteByte(value: byte) = builder.WriteByte(value) - member this.WriteInt32(value: int) = builder.WriteInt32(value) + override this.WriteByte(value: byte) = builder.WriteByte value + member this.WriteInt32(value: int) = builder.WriteInt32 value member this.ToImmutableArray() = builder.ToImmutableArray() member this.TryWriteBytes(stream: Stream, length: int) = builder.TryWriteBytes(stream, length) @@ -125,6 +125,27 @@ type idd = iddData: byte[] iddChunk: BinaryChunk } +/// The specified Hash algorithm to use on portable pdb files. +type HashAlgorithm = + | Sha1 + | Sha256 + +// Document checksum algorithms +let guidSha1 = Guid("ff1816ec-aa5e-4d10-87f7-6f4963833460") +let guidSha2 = Guid("8829d00f-11b8-4213-878b-770e8597ac16") + +let checkSum (url: string) (checksumAlgorithm: HashAlgorithm) = + try + use file = FileSystem.FileStreamReadShim url + let guid, alg = + match checksumAlgorithm with + | HashAlgorithm.Sha1 -> guidSha1, System.Security.Cryptography.SHA1.Create() :> System.Security.Cryptography.HashAlgorithm + | HashAlgorithm.Sha256 -> guidSha2, System.Security.Cryptography.SHA256.Create() :> System.Security.Cryptography.HashAlgorithm + + let checkSum = alg.ComputeHash file + Some (guid, checkSum) + with _ -> None + //--------------------------------------------------------------------- // Portable PDB Writer //--------------------------------------------------------------------- @@ -135,11 +156,11 @@ let pdbGetCvDebugInfo (mvid: byte[]) (timestamp: int32) (filepath: string) (cvCh let path = (System.Text.Encoding.UTF8.GetBytes filepath) let buffer = Array.zeroCreate (sizeof + mvid.Length + sizeof + path.Length + 1) let (offset, size) = (0, sizeof) // Magic Number RSDS dword: 0x53445352L - Buffer.BlockCopy(BitConverter.GetBytes(cvMagicNumber), 0, buffer, offset, size) + Buffer.BlockCopy(BitConverter.GetBytes cvMagicNumber, 0, buffer, offset, size) let (offset, size) = (offset + size, mvid.Length) // mvid Guid Buffer.BlockCopy(mvid, 0, buffer, offset, size) let (offset, size) = (offset + size, sizeof) // # of pdb files generated (1) - Buffer.BlockCopy(BitConverter.GetBytes(1), 0, buffer, offset, size) + Buffer.BlockCopy(BitConverter.GetBytes 1, 0, buffer, offset, size) let (offset, size) = (offset + size, path.Length) // Path to pdb string Buffer.BlockCopy(path, 0, buffer, offset, size) buffer @@ -153,44 +174,68 @@ let pdbGetCvDebugInfo (mvid: byte[]) (timestamp: int32) (filepath: string) (cvCh } let pdbMagicNumber= 0x4244504dL -let pdbGetPdbDebugInfo (embeddedPDBChunk: BinaryChunk) (uncompressedLength: int64) (stream: MemoryStream) = +let pdbGetEmbeddedPdbDebugInfo (embeddedPdbChunk: BinaryChunk) (uncompressedLength: int64) (stream: MemoryStream) = let iddPdbBuffer = let buffer = Array.zeroCreate (sizeof + sizeof + int(stream.Length)) let (offset, size) = (0, sizeof) // Magic Number dword: 0x4244504dL - Buffer.BlockCopy(BitConverter.GetBytes(pdbMagicNumber), 0, buffer, offset, size) + Buffer.BlockCopy(BitConverter.GetBytes pdbMagicNumber, 0, buffer, offset, size) let (offset, size) = (offset + size, sizeof) // Uncompressed size Buffer.BlockCopy(BitConverter.GetBytes((int uncompressedLength)), 0, buffer, offset, size) let (offset, size) = (offset + size, int(stream.Length)) // Uncompressed size Buffer.BlockCopy(stream.ToArray(), 0, buffer, offset, size) buffer { iddCharacteristics = 0 // Reserved - iddMajorVersion = 0 // VersionMajor should be 0 + iddMajorVersion = 0x0100 // VersionMajor should be 0x0100 iddMinorVersion = 0x0100 // VersionMinor should be 0x0100 iddType = 17 // IMAGE_DEBUG_TYPE_EMBEDDEDPDB iddTimestamp = 0 iddData = iddPdbBuffer // Path name to the pdb file when built - iddChunk = embeddedPDBChunk + iddChunk = embeddedPdbChunk } -let pdbGetDebugInfo (mvid: byte[]) (timestamp: int32) (filepath: string) (cvChunk: BinaryChunk) (embeddedPDBChunk: BinaryChunk option) (uncompressedLength: int64) (stream: MemoryStream option) = - match stream, embeddedPDBChunk with - | None, _ | _, None -> [| pdbGetCvDebugInfo mvid timestamp filepath cvChunk |] - | Some s, Some chunk -> [| pdbGetCvDebugInfo mvid timestamp filepath cvChunk; pdbGetPdbDebugInfo chunk uncompressedLength s |] +let pdbChecksumDebugInfo timestamp (checksumPdbChunk: BinaryChunk) (algorithmName:string) (checksum: byte[]) = + let iddBuffer = + let alg = Encoding.UTF8.GetBytes(algorithmName) + let buffer = Array.zeroCreate (alg.Length + 1 + checksum.Length) + Buffer.BlockCopy(alg, 0, buffer, 0, alg.Length) + Buffer.BlockCopy(checksum, 0, buffer, alg.Length + 1, checksum.Length) + buffer + { iddCharacteristics = 0 // Reserved + iddMajorVersion = 1 // VersionMajor should be 1 + iddMinorVersion = 0 // VersionMinor should be 0 + iddType = 19 // IMAGE_DEBUG_TYPE_CHECKSUMPDB + iddTimestamp = timestamp + iddData = iddBuffer // Path name to the pdb file when built + iddChunk = checksumPdbChunk + } -// Document checksum algorithms -let guidSourceHashMD5 = System.Guid(0x406ea660u, 0x64cfus, 0x4c82us, 0xb6uy, 0xf0uy, 0x42uy, 0xd4uy, 0x81uy, 0x72uy, 0xa7uy, 0x99uy) //406ea660-64cf-4c82-b6f0-42d48172a799 -let hashSizeOfMD5 = 16 +let pdbGetPdbDebugDeterministicInfo (deterministicPdbChunk: BinaryChunk) = + { iddCharacteristics = 0 // Reserved + iddMajorVersion = 0 // VersionMajor should be 0 + iddMinorVersion = 0 // VersionMinor should be 00 + iddType = 16 // IMAGE_DEBUG_TYPE_DETERMINISTIC + iddTimestamp = 0 + iddData = Array.empty // No DATA + iddChunk = deterministicPdbChunk + } -// If the FIPS algorithm policy is enabled on the computer (e.g., for US government employees and contractors) -// then obtaining the MD5 implementation in BCL will throw. -// In this case, catch the failure, and not set a checksum. -let checkSum (url: string) = - try - use file = FileSystem.FileStreamReadShim(url) - use md5 = System.Security.Cryptography.MD5.Create() - let checkSum = md5.ComputeHash(file) - Some (guidSourceHashMD5, checkSum) - with _ -> None +let pdbGetDebugInfo (contentId: byte[]) (timestamp: int32) (filepath: string) + (cvChunk: BinaryChunk) + (embeddedPdbChunk: BinaryChunk option) + (deterministicPdbChunk: BinaryChunk) + (checksumPdbChunk: BinaryChunk) (algorithmName:string) (checksum: byte []) + (uncompressedLength: int64) (stream: MemoryStream option) + (embeddedPdb: bool) (deterministic: bool) = + [| yield pdbGetCvDebugInfo contentId timestamp filepath cvChunk + yield pdbChecksumDebugInfo timestamp checksumPdbChunk algorithmName checksum + if embeddedPdb then + match stream, embeddedPdbChunk with + | None, _ | _, None -> () + | Some s, Some chunk -> + yield pdbGetEmbeddedPdbDebugInfo chunk uncompressedLength s + if deterministic then + yield pdbGetPdbDebugDeterministicInfo deterministicPdbChunk + |] //------------------------------------------------------------------------------ // PDB Writer. The function [WritePdbInfo] abstracts the @@ -200,7 +245,7 @@ let checkSum (url: string) = // This function takes output file name and returns debug file name. let getDebugFileName outfile (portablePDB: bool) = #if ENABLE_MONO_SUPPORT - if IL.runningOnMono && not portablePDB then + if runningOnMono && not portablePDB then outfile + ".mdb" else #else @@ -216,10 +261,10 @@ let sortMethods showTimes info = let getRowCounts tableRowCounts = let builder = ImmutableArray.CreateBuilder(tableRowCounts |> Array.length) - tableRowCounts |> Seq.iter(fun x -> builder.Add(x)) + tableRowCounts |> Seq.iter(fun x -> builder.Add x) builder.MoveToImmutable() -let generatePortablePdb (embedAllSource: bool) (embedSourceList: string list) (sourceLink: string) showTimes (info: PdbData) isDeterministic = +let generatePortablePdb (embedAllSource: bool) (embedSourceList: string list) (sourceLink: string) checksumAlgorithm showTimes (info: PdbData) (pathMap: PathMap) = sortMethods showTimes info let externalRowCounts = getRowCounts info.TableRowCounts let docs = @@ -229,19 +274,20 @@ let generatePortablePdb (embedAllSource: bool) (embedSourceList: string list) (s let metadata = MetadataBuilder() let serializeDocumentName (name: string) = + let name = PathMap.apply pathMap name let count s c = s |> Seq.filter(fun ch -> if c = ch then true else false) |> Seq.length let s1, s2 = '/', '\\' let separator = if (count name s1) >= (count name s2) then s1 else s2 let writer = new BlobBuilder() - writer.WriteByte(byte(separator)) + writer.WriteByte(byte separator) for part in name.Split( [| separator |] ) do - let partIndex = MetadataTokens.GetHeapOffset(BlobHandle.op_Implicit(metadata.GetOrAddBlobUTF8(part))) - writer.WriteCompressedInteger(int(partIndex)) + let partIndex = MetadataTokens.GetHeapOffset(BlobHandle.op_Implicit(metadata.GetOrAddBlobUTF8 part)) + writer.WriteCompressedInteger(int partIndex) - metadata.GetOrAddBlob(writer) + metadata.GetOrAddBlob writer let corSymLanguageTypeId = System.Guid(0xAB4F38C9u, 0xB6E6us, 0x43baus, 0xBEuy, 0x3Buy, 0x58uy, 0x08uy, 0x0Buy, 0x2Cuy, 0xCCuy, 0xE3uy) let embeddedSourceId = System.Guid(0x0e8a571bu, 0x6926us, 0x466eus, 0xb4uy, 0xaduy, 0x8auy, 0xb0uy, 0x46uy, 0x11uy, 0xf5uy, 0xfeuy) @@ -265,56 +311,56 @@ let generatePortablePdb (embedAllSource: bool) (embedSourceList: string list) (s if not embedAllSource && not isInList || not (File.Exists file) then None else - let stream = File.OpenRead(file) + let stream = File.OpenRead file let length64 = stream.Length - if length64 > int64(Int32.MaxValue) then raise (new IOException("File is too long")) + if length64 > int64 (Int32.MaxValue) then raise (new IOException("File is too long")) let builder = new BlobBuildingStream() - let length = int(length64) + let length = int length64 if length < sourceCompressionThreshold then - builder.WriteInt32(0) + builder.WriteInt32 0 builder.TryWriteBytes(stream, length) |> ignore else - builder.WriteInt32(length) |>ignore + builder.WriteInt32 length |>ignore use deflater = new DeflateStream(builder, CompressionMode.Compress, true) - stream.CopyTo(deflater) |> ignore + stream.CopyTo deflater |> ignore Some (builder.ToImmutableArray()) let mutable index = new Dictionary(docs.Length) - let docLength = docs.Length + if String.IsNullOrEmpty(sourceLink) then 1 else 0 + let docLength = docs.Length + if String.IsNullOrEmpty sourceLink then 1 else 0 metadata.SetCapacity(TableIndex.Document, docLength) for doc in docs do let handle = - match checkSum doc.File with + match checkSum doc.File checksumAlgorithm with | Some (hashAlg, checkSum) -> let dbgInfo = (serializeDocumentName doc.File, - metadata.GetOrAddGuid(hashAlg), + metadata.GetOrAddGuid hashAlg, metadata.GetOrAddBlob(checkSum.ToImmutableArray()), - metadata.GetOrAddGuid(corSymLanguageTypeId)) |> metadata.AddDocument + metadata.GetOrAddGuid corSymLanguageTypeId) |> metadata.AddDocument match includeSource doc.File with | None -> () | Some blob -> - metadata.AddCustomDebugInformation(DocumentHandle.op_Implicit(dbgInfo), - metadata.GetOrAddGuid(embeddedSourceId), - metadata.GetOrAddBlob(blob)) |> ignore + metadata.AddCustomDebugInformation(DocumentHandle.op_Implicit dbgInfo, + metadata.GetOrAddGuid embeddedSourceId, + metadata.GetOrAddBlob blob) |> ignore dbgInfo | None -> let dbgInfo = (serializeDocumentName doc.File, metadata.GetOrAddGuid(System.Guid.Empty), metadata.GetOrAddBlob(ImmutableArray.Empty), - metadata.GetOrAddGuid(corSymLanguageTypeId)) |> metadata.AddDocument + metadata.GetOrAddGuid corSymLanguageTypeId) |> metadata.AddDocument dbgInfo index.Add(doc.File, handle) - if not (String.IsNullOrEmpty(sourceLink)) then - let fs = File.OpenRead(sourceLink) + if not (String.IsNullOrEmpty sourceLink) then + let fs = File.OpenRead sourceLink let ms = new MemoryStream() - fs.CopyTo(ms) + fs.CopyTo ms metadata.AddCustomDebugInformation( ModuleDefinitionHandle.op_Implicit(EntityHandle.ModuleDefinition), - metadata.GetOrAddGuid(sourceLinkId), + metadata.GetOrAddGuid sourceLinkId, metadata.GetOrAddBlob(ms.ToArray())) |> ignore index @@ -369,43 +415,75 @@ let generatePortablePdb (embedAllSource: bool) (embedSourceList: string list) (s builder.WriteCompressedInteger( 0 ) builder.WriteCompressedInteger( MetadataTokens.GetRowNumber(DocumentHandle.op_Implicit(getDocumentHandle (sps.[i].Document))) ) else + //============================================================================================================================================= // Sequence-point-record - let offsetDelta = - if i > 0 then sps.[i].Offset - sps.[i - 1].Offset // delta from previous offset - else sps.[i].Offset // delta IL offset - - if i < 1 || offsetDelta <> 0 then // ILOffset must not be 0 - builder.WriteCompressedInteger(offsetDelta) - - if sps.[i].Line = 0xfeefee && sps.[i].EndLine = 0xfeefee then // Hidden-sequence-point-record - builder.WriteCompressedInteger(0) - builder.WriteCompressedInteger(0) - else // Non-hidden-sequence-point-record - let deltaLines = sps.[i].EndLine - sps.[i].Line // lines - builder.WriteCompressedInteger(deltaLines) - - let deltaColumns = sps.[i].EndColumn - sps.[i].Column // Columns + // Validate these with magic numbers according to the portable pdb spec Sequence point dexcription: + // https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md#methoddebuginformation-table-0x31 + // + // So the spec is actually bit iffy!!!!! (More like guidelines really. ) + // It uses code similar to this to validate the values + // if (result < 0 || result >= ushort.MaxValue) // be errorfull + // Spec Says 0x10000 and value max = 0xFFFF but it can't even be = to maxvalue, and so the range is 0 .. 0xfffe inclusive + //============================================================================================================================================= + + let capValue v maxValue = + if v < 0 then 0 + elif v > maxValue then maxValue + else v + + let capOffset v = capValue v 0xfffe + let capLine v = capValue v 0x1ffffffe + let capColumn v = capValue v 0xfffe + + let offset = capOffset sps.[i].Offset + let startLine = capLine sps.[i].Line + let endLine = capLine sps.[i].EndLine + let startColumn = capColumn sps.[i].Column + let endColumn = capColumn sps.[i].EndColumn + + let offsetDelta = // delta from previous offset + if i > 0 then offset - capOffset sps.[i - 1].Offset + else offset + + if i < 1 || offsetDelta > 0 then + builder.WriteCompressedInteger offsetDelta + + // Check for hidden-sequence-point-record + if startLine = 0xfeefee || + endLine = 0xfeefee || + (startColumn = 0 && endColumn = 0) || + ((endLine - startLine) = 0 && (endColumn - startColumn) = 0) + then + // Hidden-sequence-point-record + builder.WriteCompressedInteger 0 + builder.WriteCompressedInteger 0 + else + // Non-hidden-sequence-point-record + let deltaLines = endLine - startLine // lines + builder.WriteCompressedInteger deltaLines + + let deltaColumns = endColumn - startColumn // Columns if deltaLines = 0 then - builder.WriteCompressedInteger(deltaColumns) + builder.WriteCompressedInteger deltaColumns else - builder.WriteCompressedSignedInteger(deltaColumns) + builder.WriteCompressedSignedInteger deltaColumns if previousNonHiddenStartLine < 0 then // delta Start Line & Column: - builder.WriteCompressedInteger(sps.[i].Line) - builder.WriteCompressedInteger(sps.[i].Column) + builder.WriteCompressedInteger startLine + builder.WriteCompressedInteger startColumn else - builder.WriteCompressedSignedInteger(sps.[i].Line - previousNonHiddenStartLine) - builder.WriteCompressedSignedInteger(sps.[i].Column - previousNonHiddenStartColumn) + builder.WriteCompressedSignedInteger(startLine - previousNonHiddenStartLine) + builder.WriteCompressedSignedInteger(startColumn - previousNonHiddenStartColumn) - previousNonHiddenStartLine <- sps.[i].Line - previousNonHiddenStartColumn <- sps.[i].Column + previousNonHiddenStartLine <- startLine + previousNonHiddenStartColumn <- startColumn - getDocumentHandle singleDocumentIndex, metadata.GetOrAddBlob(builder) + getDocumentHandle singleDocumentIndex, metadata.GetOrAddBlob builder metadata.AddMethodDebugInformation(docHandle, sequencePointBlob) |> ignore // Write the scopes - let nextHandle handle = MetadataTokens.LocalVariableHandle(MetadataTokens.GetRowNumber(LocalVariableHandle.op_Implicit(handle)) + 1) + let nextHandle handle = MetadataTokens.LocalVariableHandle(MetadataTokens.GetRowNumber(LocalVariableHandle.op_Implicit handle) + 1) let writeMethodScope scope = let scopeSorter (scope1: PdbMethodScope) (scope2: PdbMethodScope) = if scope1.StartOffset > scope2.StartOffset then 1 @@ -445,46 +523,49 @@ let generatePortablePdb (embedAllSource: bool) (embedSourceList: string list) (s let entryPoint = match info.EntryPoint with - | None -> MetadataTokens.MethodDefinitionHandle(0) - | Some x -> MetadataTokens.MethodDefinitionHandle(x) - - let deterministicIdProvider isDeterministic : System.Func, BlobContentId> = - match isDeterministic with - | false -> null - | true -> - let convert (content: IEnumerable) = - use sha = System.Security.Cryptography.SHA1.Create() // IncrementalHash is core only - let hash = content - |> Seq.collect (fun c -> c.GetBytes().Array |> sha.ComputeHash) - |> Array.ofSeq |> sha.ComputeHash - BlobContentId.FromHash(hash) - System.Func, BlobContentId>( convert ) - - let serializer = PortablePdbBuilder(metadata, externalRowCounts, entryPoint, deterministicIdProvider isDeterministic) + | None -> MetadataTokens.MethodDefinitionHandle 0 + | Some x -> MetadataTokens.MethodDefinitionHandle x + + // Compute the contentId for the pdb. Always do it deterministically, since we have to compute the anyway. + // The contentId is the hash of the ID using whichever algorithm has been specified to the compiler + let mutable contentHash = Array.empty + + let algorithmName, hashAlgorithm = + match checksumAlgorithm with + | HashAlgorithm.Sha1 -> "SHA1", System.Security.Cryptography.SHA1.Create() :> System.Security.Cryptography.HashAlgorithm + | HashAlgorithm.Sha256 -> "SHA256", System.Security.Cryptography.SHA256.Create() :> System.Security.Cryptography.HashAlgorithm + let idProvider: System.Func, BlobContentId> = + let convert (content: IEnumerable) = + let contentBytes = content |> Seq.collect (fun c -> c.GetBytes()) |> Array.ofSeq + contentHash <- contentBytes |> hashAlgorithm.ComputeHash + BlobContentId.FromHash contentHash + System.Func, BlobContentId>(convert) + + let serializer = PortablePdbBuilder(metadata, externalRowCounts, entryPoint, idProvider) let blobBuilder = new BlobBuilder() - let contentId= serializer.Serialize(blobBuilder) + let contentId= serializer.Serialize blobBuilder let portablePdbStream = new MemoryStream() - blobBuilder.WriteContentTo(portablePdbStream) + blobBuilder.WriteContentTo portablePdbStream reportTime showTimes "PDB: Created" - (portablePdbStream.Length, contentId, portablePdbStream) + (portablePdbStream.Length, contentId, portablePdbStream, algorithmName, contentHash) let compressPortablePdbStream (uncompressedLength: int64) (contentId: BlobContentId) (stream: MemoryStream) = let compressedStream = new MemoryStream() use compressionStream = new DeflateStream(compressedStream, CompressionMode.Compress,true) - stream.WriteTo(compressionStream) + stream.WriteTo compressionStream (uncompressedLength, contentId, compressedStream) -let writePortablePdbInfo (contentId: BlobContentId) (stream: MemoryStream) showTimes fpdb cvChunk = +let writePortablePdbInfo (contentId: BlobContentId) (stream: MemoryStream) showTimes fpdb pathMap cvChunk deterministicPdbChunk checksumPdbChunk algName checksum embeddedPdb deterministicPdb = try FileSystem.FileDelete fpdb with _ -> () use pdbFile = new FileStream(fpdb, FileMode.Create, FileAccess.ReadWrite) - stream.WriteTo(pdbFile) + stream.WriteTo pdbFile reportTime showTimes "PDB: Closed" - pdbGetDebugInfo (contentId.Guid.ToByteArray()) (int32 (contentId.Stamp)) fpdb cvChunk None 0L None + pdbGetDebugInfo (contentId.Guid.ToByteArray()) (int32 (contentId.Stamp)) (PathMap.apply pathMap fpdb) cvChunk None deterministicPdbChunk checksumPdbChunk algName checksum 0L None embeddedPdb deterministicPdb -let embedPortablePdbInfo (uncompressedLength: int64) (contentId: BlobContentId) (stream: MemoryStream) showTimes fpdb cvChunk pdbChunk = +let embedPortablePdbInfo (uncompressedLength: int64) (contentId: BlobContentId) (stream: MemoryStream) showTimes fpdb cvChunk pdbChunk deterministicPdbChunk checksumPdbChunk algName checksum embeddedPdb deterministicPdb = reportTime showTimes "PDB: Closed" - let fn = Path.GetFileName(fpdb) - pdbGetDebugInfo (contentId.Guid.ToByteArray()) (int32 (contentId.Stamp)) fn cvChunk (Some pdbChunk) uncompressedLength (Some stream) + let fn = Path.GetFileName fpdb + pdbGetDebugInfo (contentId.Guid.ToByteArray()) (int32 (contentId.Stamp)) fn cvChunk (Some pdbChunk) deterministicPdbChunk checksumPdbChunk algName checksum uncompressedLength (Some stream) embeddedPdb deterministicPdb #if !FX_NO_PDB_WRITER //--------------------------------------------------------------------- @@ -499,7 +580,7 @@ let writePdbInfo showTimes f fpdb info cvChunk = try pdbw := pdbInitialize f fpdb - with _ -> error(Error(FSComp.SR.ilwriteErrorCreatingPdb(fpdb), rangeCmdArgs)) + with _ -> error(Error(FSComp.SR.ilwriteErrorCreatingPdb fpdb, rangeCmdArgs)) match info.EntryPoint with | None -> () @@ -609,22 +690,22 @@ let (?) this memb (args:'Args) : 'R = // Get array of 'obj' arguments for the reflection call let args = if typeof<'Args> = typeof then [| |] - elif FSharpType.IsTuple typeof<'Args> then Microsoft.FSharp.Reflection.FSharpValue.GetTupleFields(args) + elif FSharpType.IsTuple typeof<'Args> then Microsoft.FSharp.Reflection.FSharpValue.GetTupleFields args else [| box args |] // Get methods and perform overload resolution let methods = this.GetType().GetMethods() let bestMatch = methods |> Array.tryFind (fun mi -> mi.Name = memb && mi.GetParameters().Length = args.Length) match bestMatch with - | Some(mi) -> unbox(mi.Invoke(this, args)) - | None -> error(Error(FSComp.SR.ilwriteMDBMemberMissing(memb), rangeCmdArgs)) + | Some mi -> unbox(mi.Invoke(this, args)) + | None -> error(Error(FSComp.SR.ilwriteMDBMemberMissing memb, rangeCmdArgs)) // Creating instances of needed classes from 'Mono.CompilerServices.SymbolWriter' assembly let monoCompilerSvc = new AssemblyName("Mono.CompilerServices.SymbolWriter, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756") let ctor (asmName: AssemblyName) clsName (args: obj[]) = - let asm = Assembly.Load(asmName) - let ty = asm.GetType(clsName) + let asm = Assembly.Load asmName + let ty = asm.GetType clsName System.Activator.CreateInstance(ty, args) let createSourceMethodImpl (name: string) (token: int) (namespaceID: int) = @@ -651,7 +732,7 @@ let writeMdbInfo fmdb f info = let docs = [| for doc in info.Documents do let doc = wr?DefineDocument(doc.File) - let unit = wr?DefineCompilationUnit(doc) + let unit = wr?DefineCompilationUnit doc yield doc, unit |] let getDocument i = @@ -680,11 +761,11 @@ let writeMdbInfo fmdb f info = for local in scope.Locals do wr?DefineLocalVariable(local.Index, local.Name) for child in scope.Children do - writeScope(child) + writeScope child wr?CloseScope(scope.EndOffset) match meth.RootScope with | None -> () - | Some rootscope -> writeScope(rootscope) + | Some rootscope -> writeScope rootscope // Finished generating debug information for the curretn method @@ -693,7 +774,7 @@ let writeMdbInfo fmdb f info = // Finalize - MDB requires the MVID of the generated .NET module let moduleGuid = new System.Guid(info.ModuleID |> Array.map byte) - wr?WriteSymbolFile(moduleGuid) + wr?WriteSymbolFile moduleGuid #endif //--------------------------------------------------------------------- diff --git a/src/fcs-fable/src/absil/ilwritepdb.fsi b/src/fcs-fable/src/absil/ilwritepdb.fsi index a291ce4667..748e178a46 100644 --- a/src/fcs-fable/src/absil/ilwritepdb.fsi +++ b/src/fcs-fable/src/absil/ilwritepdb.fsi @@ -3,7 +3,8 @@ /// The ILPdbWriter module internal FSharp.Compiler.AbstractIL.ILPdbWriter -open FSharp.Compiler.AbstractIL.IL +open Internal.Utilities +open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Range open System.Collections.Generic @@ -82,10 +83,14 @@ type idd = iddData: byte[]; iddChunk: BinaryChunk } -val generatePortablePdb : embedAllSource:bool -> embedSourceList:string list -> sourceLink: string -> showTimes:bool -> info:PdbData -> isDeterministic:bool -> (int64 * BlobContentId * MemoryStream) +type HashAlgorithm = + | Sha1 + | Sha256 + +val generatePortablePdb : embedAllSource: bool -> embedSourceList: string list -> sourceLink: string -> checksumAlgorithm: HashAlgorithm -> showTimes: bool -> info: PdbData -> pathMap:PathMap -> (int64 * BlobContentId * MemoryStream * string * byte[]) val compressPortablePdbStream : uncompressedLength:int64 -> contentId:BlobContentId -> stream:MemoryStream -> (int64 * BlobContentId * MemoryStream) -val embedPortablePdbInfo : uncompressedLength:int64 -> contentId:BlobContentId -> stream:MemoryStream -> showTimes:bool -> fpdb:string -> cvChunk:BinaryChunk -> pdbChunk:BinaryChunk -> idd[] -val writePortablePdbInfo : contentId:BlobContentId -> stream:MemoryStream -> showTimes:bool -> fpdb:string -> cvChunk:BinaryChunk -> idd[] +val embedPortablePdbInfo: uncompressedLength: int64 -> contentId: BlobContentId -> stream: MemoryStream -> showTimes: bool -> fpdb: string -> cvChunk: BinaryChunk -> pdbChunk: BinaryChunk -> deterministicPdbChunk: BinaryChunk -> checksumPdbChunk: BinaryChunk -> algorithmName: string -> checksum: byte[] -> embeddedPDB: bool -> deterministic: bool -> idd[] +val writePortablePdbInfo: contentId: BlobContentId -> stream: MemoryStream -> showTimes: bool -> fpdb: string -> pathMap: PathMap -> cvChunk: BinaryChunk -> deterministicPdbChunk: BinaryChunk -> checksumPdbChunk: BinaryChunk -> algorithmName: string -> checksum: byte[] -> embeddedPDB: bool -> deterministic: bool -> idd[] #if !FX_NO_PDB_WRITER val writePdbInfo : showTimes:bool -> f:string -> fpdb:string -> info:PdbData -> cvChunk:BinaryChunk -> idd[] diff --git a/src/fcs-fable/src/absil/ilx.fs b/src/fcs-fable/src/absil/ilx.fs old mode 100755 new mode 100644 index 56d264a6dc..2b364186c9 --- a/src/fcs-fable/src/absil/ilx.fs +++ b/src/fcs-fable/src/absil/ilx.fs @@ -3,9 +3,6 @@ /// Defines an extension of the IL algebra module internal FSharp.Compiler.AbstractIL.Extensions.ILX.Types -open Internal.Utilities -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Library diff --git a/src/fcs-fable/src/absil/ilx.fsi b/src/fcs-fable/src/absil/ilx.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/absil/zmap.fs b/src/fcs-fable/src/absil/zmap.fs old mode 100755 new mode 100644 index 9644a135c1..5378c26295 --- a/src/fcs-fable/src/absil/zmap.fs +++ b/src/fcs-fable/src/absil/zmap.fs @@ -37,11 +37,11 @@ module internal Zmap = let choose f (m: Zmap<_,_>) = m.First(f) let chooseL f (m: Zmap<_,_>) = - m.Fold (fun k v s -> match f k v with None -> s | Some x -> x::s) [] + m.Fold (fun k v s -> match f k v with None -> s | Some x -> x :: s) [] let ofList ord xs = Internal.Utilities.Collections.Tagged.Map<_,_>.FromList(ord,xs) - let keys (m: Zmap<_,_>) = m.Fold (fun k _ s -> k::s) [] - let values (m: Zmap<_,_>) = m.Fold (fun _ v s -> v::s) [] + let keys (m: Zmap<_,_>) = m.Fold (fun k _ s -> k :: s) [] + let values (m: Zmap<_,_>) = m.Fold (fun _ v s -> v :: s) [] let memberOf m k = mem k m diff --git a/src/fcs-fable/src/absil/zmap.fsi b/src/fcs-fable/src/absil/zmap.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/absil/zset.fs b/src/fcs-fable/src/absil/zset.fs old mode 100755 new mode 100644 index 5d6588a598..aee52eb68e --- a/src/fcs-fable/src/absil/zset.fs +++ b/src/fcs-fable/src/absil/zset.fs @@ -3,9 +3,7 @@ namespace FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library -open Internal.Utilities open Internal.Utilities.Collections.Tagged open System.Collections.Generic diff --git a/src/fcs-fable/src/absil/zset.fsi b/src/fcs-fable/src/absil/zset.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/assemblyinfo/assemblyinfo.FSharp.Compiler.Service.MSBuild.v14.dll.fs b/src/fcs-fable/src/assemblyinfo/assemblyinfo.FSharp.Compiler.Service.MSBuild.v14.dll.fs deleted file mode 100644 index 4eddab4910..0000000000 --- a/src/fcs-fable/src/assemblyinfo/assemblyinfo.FSharp.Compiler.Service.MSBuild.v14.dll.fs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.FSharp -open System.Reflection -open System.Runtime.InteropServices - -[] -[] -[] -[] - -[] -[] -do() diff --git a/src/fcs-fable/src/assemblyinfo/assemblyinfo.FSharp.Interactive.Service.dll.fs b/src/fcs-fable/src/assemblyinfo/assemblyinfo.FSharp.Interactive.Service.dll.fs deleted file mode 100644 index bd3ce5c648..0000000000 --- a/src/fcs-fable/src/assemblyinfo/assemblyinfo.FSharp.Interactive.Service.dll.fs +++ /dev/null @@ -1,8 +0,0 @@ -#light -namespace Microsoft.FSharp -open System.Reflection -[] -[] -[] -[] -do() diff --git a/src/fcs-fable/src/buildfromsource.cmd b/src/fcs-fable/src/buildfromsource.cmd deleted file mode 100644 index ed0892e4e0..0000000000 --- a/src/fcs-fable/src/buildfromsource.cmd +++ /dev/null @@ -1,30 +0,0 @@ -@if "%_echo%"=="" echo off - -set __scriptpath=%~dp0 - -rem build tools -dotnet restore "%__scriptpath%buildtools\fslex\fslex.fsproj" -if ERRORLEVEL 1 echo Error: failed && goto :failure -dotnet publish "%__scriptpath%buildtools\fslex\fslex.fsproj" -o "%__scriptpath%..\Tools\fslex" -if ERRORLEVEL 1 echo Error: failed && goto :failure -dotnet restore "%__scriptpath%buildtools\fsyacc\fsyacc.fsproj" -if ERRORLEVEL 1 echo Error: failed && goto :failure -dotnet publish "%__scriptpath%buildtools\fsyacc\fsyacc.fsproj" -o "%__scriptpath%..\Tools\fsyacc" -if ERRORLEVEL 1 echo Error: failed && goto :failure - -rem build and pack tools -dotnet restore "%__scriptpath%buildfromsource\FSharp.Compiler.nuget\FSharp.Compiler.nuget.fsproj" -if ERRORLEVEL 1 echo Error: failed && goto :failure -dotnet pack "%__scriptpath%buildfromsource\FSharp.Compiler.nuget\FSharp.Compiler.nuget.fsproj" -c Release -if ERRORLEVEL 1 echo Error: failed && goto :failure - -goto :success - -REM ------ exit ------------------------------------- -:failure -endlocal -exit /b 1 - -:success -endlocal -exit /b 0 diff --git a/src/fcs-fable/src/buildtools/buildtools.proj b/src/fcs-fable/src/buildtools/buildtools.proj deleted file mode 100644 index 593f086dd0..0000000000 --- a/src/fcs-fable/src/buildtools/buildtools.proj +++ /dev/null @@ -1,32 +0,0 @@ - - - - Debug - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/fcs-fable/src/buildtools/buildtools.targets b/src/fcs-fable/src/buildtools/buildtools.targets deleted file mode 100644 index 8aaf703ad0..0000000000 --- a/src/fcs-fable/src/buildtools/buildtools.targets +++ /dev/null @@ -1,61 +0,0 @@ - - - - - dotnet - dotnet.exe - - $(DOTNET_HOST_PATH) - $(DotNetExe) - - - $(DotNetExePath) - - - - - - - $(ArtifactsDir)\bin\fslex\Proto\netcoreapp2.0\fslex.dll - - - - - - - - - - - - - - - - - - - $(ArtifactsDir)\bin\fsyacc\Proto\netcoreapp2.0\fsyacc.dll - - - - - - - - - - - - - - - diff --git a/src/fcs-fable/src/buildtools/fslex/App.config b/src/fcs-fable/src/buildtools/fslex/App.config deleted file mode 100644 index e1b09eda9f..0000000000 --- a/src/fcs-fable/src/buildtools/fslex/App.config +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/buildtools/fslex/Arg.fs b/src/fcs-fable/src/buildtools/fslex/Arg.fs deleted file mode 100644 index a1f63bd963..0000000000 --- a/src/fcs-fable/src/buildtools/fslex/Arg.fs +++ /dev/null @@ -1,133 +0,0 @@ -// (c) Microsoft Corporation 2005-2009. - -#if INTERNALIZED_FSLEXYACC_RUNTIME -namespace Internal.Utilities -#else -namespace Microsoft.FSharp.Text -#endif - - -type ArgType = - | ClearArg of bool ref - | FloatArg of (float -> unit) - | IntArg of (int -> unit) - | RestArg of (string -> unit) - | SetArg of bool ref - | StringArg of (string -> unit) - | UnitArg of (unit -> unit) - static member Clear r = ClearArg r - static member Float r = FloatArg r - static member Int r = IntArg r - static member Rest r = RestArg r - static member Set r = SetArg r - static member String r = StringArg r - static member Unit r = UnitArg r - - -type ArgInfo (name,action,help) = - member x.Name = name - member x.ArgType = action - member x.HelpText = help - -exception Bad of string -exception HelpText of string - -[] -type ArgParser() = - static let getUsage specs u = - let sbuf = new System.Text.StringBuilder 100 - let pstring (s:string) = sbuf.Append s |> ignore - let pendline s = pstring s; pstring "\n" - pendline u; - List.iter (fun (arg:ArgInfo) -> - match arg.Name, arg.ArgType, arg.HelpText with - | (s, (UnitArg _ | SetArg _ | ClearArg _), helpText) -> pstring "\t"; pstring s; pstring ": "; pendline helpText - | (s, StringArg _, helpText) -> pstring "\t"; pstring s; pstring " : "; pendline helpText - | (s, IntArg _, helpText) -> pstring "\t"; pstring s; pstring " : "; pendline helpText - | (s, FloatArg _, helpText) -> pstring "\t"; pstring s; pstring " : "; pendline helpText - | (s, RestArg _, helpText) -> pstring "\t"; pstring s; pstring " ...: "; pendline helpText) - specs; - pstring "\t"; pstring "--help"; pstring ": "; pendline "display this list of options"; - pstring "\t"; pstring "-help"; pstring ": "; pendline "display this list of options"; - sbuf.ToString() - - - static member ParsePartial(cursor,argv,argSpecs:seq,?other,?usageText) = - let other = defaultArg other (fun _ -> ()) - let usageText = defaultArg usageText "" - let nargs = Array.length argv - incr cursor; - let argSpecs = argSpecs |> Seq.toList - let specs = argSpecs |> List.map (fun (arg:ArgInfo) -> arg.Name, arg.ArgType) - while !cursor < nargs do - let arg = argv.[!cursor] - let rec findMatchingArg args = - match args with - | ((s, action) :: _) when s = arg -> - let getSecondArg () = - if !cursor + 1 >= nargs then - raise(Bad("option "+s+" needs an argument.\n"+getUsage argSpecs usageText)); - argv.[!cursor+1] - - match action with - | UnitArg f -> - f (); - incr cursor - | SetArg f -> - f := true; - incr cursor - | ClearArg f -> - f := false; - incr cursor - | StringArg f-> - let arg2 = getSecondArg() - f arg2; - cursor := !cursor + 2 - | IntArg f -> - let arg2 = getSecondArg () - let arg2 = try int32 arg2 with _ -> raise(Bad(getUsage argSpecs usageText)) in - f arg2; - cursor := !cursor + 2; - | FloatArg f -> - let arg2 = getSecondArg() - let arg2 = try float arg2 with _ -> raise(Bad(getUsage argSpecs usageText)) in - f arg2; - cursor := !cursor + 2; - | RestArg f -> - incr cursor; - while !cursor < nargs do - f (argv.[!cursor]); - incr cursor; - - | (_ :: more) -> findMatchingArg more - | [] -> - if arg = "-help" || arg = "--help" || arg = "/help" || arg = "/help" || arg = "/?" then - raise (HelpText (getUsage argSpecs usageText)) - // Note: for '/abc/def' does not count as an argument - // Note: '/abc' does - elif arg.Length>0 && (arg.[0] = '-' || (arg.[0] = '/' && not (arg.Length > 1 && arg.[1..].Contains ("/")))) then - raise (Bad ("unrecognized argument: "+ arg + "\n" + getUsage argSpecs usageText)) - else - other arg; - incr cursor - findMatchingArg specs - - static member Usage (specs,?usage) = - let usage = defaultArg usage "" - System.Console.Error.WriteLine (getUsage (Seq.toList specs) usage) - - #if FX_NO_COMMAND_LINE_ARGS - #else - static member Parse (specs,?other,?usageText) = - let current = ref 0 - let argv = System.Environment.GetCommandLineArgs() - try ArgParser.ParsePartial (current, argv, specs, ?other=other, ?usageText=usageText) - with - | Bad h - | HelpText h -> - System.Console.Error.WriteLine h; - System.Console.Error.Flush(); - System.Environment.Exit(1); - | e -> - reraise() - #endif diff --git a/src/fcs-fable/src/buildtools/fslex/Arg.fsi b/src/fcs-fable/src/buildtools/fslex/Arg.fsi deleted file mode 100644 index 367f69f959..0000000000 --- a/src/fcs-fable/src/buildtools/fslex/Arg.fsi +++ /dev/null @@ -1,50 +0,0 @@ -// (c) Microsoft Corporation 2005-2009. - -/// A simple command-line argument processor. -#if INTERNALIZED_FSLEXYACC_RUNTIME -namespace Internal.Utilities -#else -namespace Microsoft.FSharp.Text -#endif - -/// The spec value describes the action of the argument, -/// and whether it expects a following parameter. -[] -type ArgType = - static member Clear : bool ref -> ArgType - static member Float : (float -> unit) -> ArgType - static member Int : (int -> unit) -> ArgType - static member Rest : (string -> unit) -> ArgType - static member Set : bool ref -> ArgType - static member String : (string -> unit) -> ArgType - static member Unit : (unit -> unit) -> ArgType - -type ArgInfo = - new : name:string * action:ArgType * help:string -> ArgInfo - /// Return the name of the argument - member Name : string - /// Return the argument type and action of the argument - member ArgType : ArgType - /// Return the usage help associated with the argument - member HelpText : string - -[] -type ArgParser = - #if FX_NO_COMMAND_LINE_ARGS - #else - - /// Parse some of the arguments given by 'argv', starting at the given position - [] - static member ParsePartial: cursor: int ref * argv: string[] * arguments:seq * ?otherArgs: (string -> unit) * ?usageText:string -> unit - - /// Parse the arguments given by System.Environment.GetEnvironmentVariables() - /// according to the argument processing specifications "specs". - /// Args begin with "-". Non-arguments are passed to "f" in - /// order. "use" is printed as part of the usage line if an error occurs. - - static member Parse: arguments:seq * ?otherArgs: (string -> unit) * ?usageText:string -> unit - #endif - - /// Prints the help for each argument. - static member Usage : arguments:seq * ?usage:string -> unit - diff --git a/src/fcs-fable/src/buildtools/fslex/Lexing.fs b/src/fcs-fable/src/buildtools/fslex/Lexing.fs deleted file mode 100644 index 8337717d6f..0000000000 --- a/src/fcs-fable/src/buildtools/fslex/Lexing.fs +++ /dev/null @@ -1,423 +0,0 @@ -// (c) Microsoft Corporation 2005-2009. - -#nowarn "47" // recursive initialization of LexBuffer - - -#if INTERNALIZED_FSLEXYACC_RUNTIME -namespace Internal.Utilities.Text.Lexing - -#else -namespace Microsoft.FSharp.Text.Lexing -#endif - - open System.Collections.Generic - - // REVIEW: This type showed up on a parsing-intensive performance measurement. Consider whether it can be a struct-record later when we have this feature. -jomo -#if INTERNALIZED_FSLEXYACC_RUNTIME - type internal Position = -#else - type Position = -#endif - { pos_fname : string; - pos_lnum : int; -#if INTERNALIZED_FSLEXYACC_RUNTIME - pos_orig_lnum : int; -#endif - pos_bol : int; - pos_cnum : int; } - member x.FileName = x.pos_fname - member x.Line = x.pos_lnum -#if INTERNALIZED_FSLEXYACC_RUNTIME - member x.OriginalLine = x.pos_orig_lnum -#endif - member x.Char = x.pos_cnum - member x.AbsoluteOffset = x.pos_cnum - member x.StartOfLine = x.pos_bol - member x.StartOfLineAbsoluteOffset = x.pos_bol - member x.Column = x.pos_cnum - x.pos_bol - member pos.NextLine = - { pos with -#if INTERNALIZED_FSLEXYACC_RUNTIME - pos_orig_lnum = pos.OriginalLine + 1; -#endif - pos_lnum = pos.Line+1; - pos_bol = pos.AbsoluteOffset } - member pos.EndOfToken(n) = {pos with pos_cnum=pos.pos_cnum + n } - member pos.AsNewLinePos() = pos.NextLine - member pos.ShiftColumnBy(by) = {pos with pos_cnum = pos.pos_cnum + by} - static member Empty = - { pos_fname=""; - pos_lnum= 0; -#if INTERNALIZED_FSLEXYACC_RUNTIME - pos_orig_lnum = 0; -#endif - pos_bol= 0; - pos_cnum=0 } - static member FirstLine(filename) = - { pos_fname=filename; -#if INTERNALIZED_FSLEXYACC_RUNTIME - pos_orig_lnum = 1; -#endif - pos_lnum= 1; - pos_bol= 0; - pos_cnum=0 } - -#if INTERNALIZED_FSLEXYACC_RUNTIME - type internal LexBufferFiller<'char> = -#else - type LexBufferFiller<'char> = -#endif - { fillSync : (LexBuffer<'char> -> unit) option - fillAsync : (LexBuffer<'char> -> Async) option } - - and [] -#if INTERNALIZED_FSLEXYACC_RUNTIME - internal LexBuffer<'char>(filler: LexBufferFiller<'char>) as this = -#else - LexBuffer<'char>(filler: LexBufferFiller<'char>) as this = -#endif - let context = new Dictionary(1) in - let extendBufferSync = (fun () -> match filler.fillSync with Some refill -> refill this | None -> invalidOp "attempt to read synchronously from an asynchronous lex buffer") - let extendBufferAsync = (fun () -> match filler.fillAsync with Some refill -> refill this | None -> invalidOp "attempt to read asynchronously from a synchronous lex buffer") - let mutable buffer=[||]; - /// number of valid charactes beyond bufferScanStart - let mutable bufferMaxScanLength=0; - /// count into the buffer when scanning - let mutable bufferScanStart=0; - /// number of characters scanned so far - let mutable bufferScanLength=0; - /// length of the scan at the last accepting state - let mutable lexemeLength=0; - /// action related to the last accepting state - let mutable bufferAcceptAction=0; - let mutable eof = false; - let mutable startPos = Position.Empty ; - let mutable endPos = Position.Empty - - // Throw away all the input besides the lexeme - - let discardInput () = - let keep = Array.sub buffer bufferScanStart bufferScanLength - let nkeep = keep.Length - Array.blit keep 0 buffer 0 nkeep; - bufferScanStart <- 0; - bufferMaxScanLength <- nkeep - - - member lexbuf.EndOfScan () : int = - // Printf.eprintf "endOfScan, lexBuffer.lexemeLength = %d\n" lexBuffer.lexemeLength; - if bufferAcceptAction < 0 then - failwith "unrecognized input" - - // Printf.printf "endOfScan %d state %d on unconsumed input '%c' (%d)\n" a s (Char.chr inp) inp; - // Printf.eprintf "accept, lexeme = %s\n" (lexeme lexBuffer); - lexbuf.StartPos <- endPos; - lexbuf.EndPos <- endPos.EndOfToken(lexbuf.LexemeLength); - bufferAcceptAction - - member lexbuf.StartPos - with get() = startPos - and set(b) = startPos <- b - - member lexbuf.EndPos - with get() = endPos - and set(b) = endPos <- b - - member lexbuf.Lexeme = Array.sub buffer bufferScanStart lexemeLength - member lexbuf.LexemeChar(n) = buffer.[n+bufferScanStart] - - member lexbuf.BufferLocalStore = (context :> IDictionary<_,_>) - member lexbuf.LexemeLength with get() : int = lexemeLength and set v = lexemeLength <- v - member internal lexbuf.Buffer with get() : 'char[] = buffer and set v = buffer <- v - member internal lexbuf.BufferMaxScanLength with get() = bufferMaxScanLength and set v = bufferMaxScanLength <- v - member internal lexbuf.BufferScanLength with get() = bufferScanLength and set v = bufferScanLength <- v - member internal lexbuf.BufferScanStart with get() : int = bufferScanStart and set v = bufferScanStart <- v - member internal lexbuf.BufferAcceptAction with get() = bufferAcceptAction and set v = bufferAcceptAction <- v - member internal lexbuf.RefillBuffer = extendBufferSync - member internal lexbuf.AsyncRefillBuffer = extendBufferAsync - - static member LexemeString(lexbuf:LexBuffer) = - new System.String(lexbuf.Buffer,lexbuf.BufferScanStart,lexbuf.LexemeLength) - - member lexbuf.IsPastEndOfStream - with get() = eof - and set(b) = eof <- b - - member lexbuf.DiscardInput() = discardInput () - - member x.BufferScanPos = bufferScanStart + bufferScanLength - - member lexbuf.EnsureBufferSize n = - if lexbuf.BufferScanPos + n >= buffer.Length then - let repl = Array.zeroCreate (lexbuf.BufferScanPos + n) - Array.blit buffer bufferScanStart repl bufferScanStart bufferScanLength; - buffer <- repl - - static member FromReadFunctions (syncRead : ('char[] * int * int -> int) option, asyncRead : ('char[] * int * int -> Async) option) : LexBuffer<'char> = - let extension= Array.zeroCreate 4096 - let fillers = - { fillSync = - match syncRead with - | None -> None - | Some read -> - Some (fun lexBuffer -> - let n = read(extension,0,extension.Length) - lexBuffer.EnsureBufferSize n; - Array.blit extension 0 lexBuffer.Buffer lexBuffer.BufferScanPos n; - lexBuffer.BufferMaxScanLength <- lexBuffer.BufferScanLength + n); - fillAsync = - match asyncRead with - | None -> None - | Some read -> - Some (fun lexBuffer -> - async { - let! n = read(extension,0,extension.Length) - lexBuffer.EnsureBufferSize n; - Array.blit extension 0 lexBuffer.Buffer lexBuffer.BufferScanPos n; - lexBuffer.BufferMaxScanLength <- lexBuffer.BufferScanLength + n }) } - new LexBuffer<_>(fillers) - - // A full type signature is required on this method because it is used at more specific types within its own scope - static member FromFunction (f : 'char[] * int * int -> int) : LexBuffer<'char> = LexBuffer<_>.FromReadFunctions(Some(f),None) - static member FromAsyncFunction (f : 'char[] * int * int -> Async) : LexBuffer<'char> = LexBuffer<_>.FromReadFunctions(None,Some(f)) - - static member FromCharFunction f : LexBuffer = - LexBuffer.FromFunction(fun (buff,start,len) -> - let buff2 = Array.zeroCreate len - let n = f buff2 len - Array.blit buff2 0 buff start len - n) - static member FromByteFunction f : LexBuffer = - LexBuffer.FromFunction(fun (buff,start,len) -> - let buff2 = Array.zeroCreate len - let n = f buff2 len - Array.blit buff2 0 buff start len - n) - - // A full type signature is required on this method because it is used at more specific types within its own scope - static member FromArray (s: 'char[]) : LexBuffer<'char> = - let lexBuffer = - new LexBuffer<_> - { fillSync = Some (fun _ -> ()); - fillAsync = Some (fun _ -> async { return () }) } - let buffer = Array.copy s - lexBuffer.Buffer <- buffer; - lexBuffer.BufferMaxScanLength <- buffer.Length; - lexBuffer - - static member FromBytes (arr) = LexBuffer.FromArray(arr) - static member FromChars (arr) = LexBuffer.FromArray(arr) - static member FromString (s:string) = LexBuffer.FromChars (s.ToCharArray()) - - static member FromTextReader (tr:System.IO.TextReader) : LexBuffer = - LexBuffer.FromFunction(tr.Read) - - static member FromBinaryReader (br:System.IO.BinaryReader) : LexBuffer = - LexBuffer.FromFunction(br.Read) - - static member FromStream (stream:System.IO.Stream) : LexBuffer = - LexBuffer.FromReadFunctions(Some(stream.Read),Some(fun (buf,offset,len) -> stream.AsyncRead(buf,offset=offset,count=len))) - - module GenericImplFragments = - let startInterpret(lexBuffer:LexBuffer<_>)= - lexBuffer.BufferScanStart <- lexBuffer.BufferScanStart + lexBuffer.LexemeLength; - lexBuffer.BufferMaxScanLength <- lexBuffer.BufferMaxScanLength - lexBuffer.LexemeLength; - lexBuffer.BufferScanLength <- 0; - lexBuffer.LexemeLength <- 0; - lexBuffer.BufferAcceptAction <- -1; - - let afterRefill (trans: uint16[] array,sentinel,lexBuffer:LexBuffer<_>,scanUntilSentinel,endOfScan,state,eofPos) = - // end of file occurs if we couldn't extend the buffer - if lexBuffer.BufferScanLength = lexBuffer.BufferMaxScanLength then - let snew = int trans.[state].[eofPos] // == EOF - if snew = sentinel then - endOfScan() - else - if lexBuffer.IsPastEndOfStream then failwith "End of file on lexing stream"; - lexBuffer.IsPastEndOfStream <- true; - // Printf.printf "state %d --> %d on eof\n" state snew; - scanUntilSentinel(lexBuffer,snew) - else - scanUntilSentinel(lexBuffer, state) - - let onAccept (lexBuffer:LexBuffer<_>,a) = - lexBuffer.LexemeLength <- lexBuffer.BufferScanLength; - lexBuffer.BufferAcceptAction <- a; - - open GenericImplFragments - - [] -#if INTERNALIZED_FSLEXYACC_RUNTIME - type internal AsciiTables(trans: uint16[] array, accept: uint16[]) = -#else - type AsciiTables(trans: uint16[] array, accept: uint16[]) = -#endif - let rec scanUntilSentinel(lexBuffer, state) = - let sentinel = 255 * 256 + 255 - // Return an endOfScan after consuming the input - let a = int accept.[state] - if a <> sentinel then - onAccept (lexBuffer,a) - - if lexBuffer.BufferScanLength = lexBuffer.BufferMaxScanLength then - lexBuffer.DiscardInput(); - lexBuffer.RefillBuffer (); - // end of file occurs if we couldn't extend the buffer - afterRefill (trans,sentinel,lexBuffer,scanUntilSentinel,lexBuffer.EndOfScan,state,256 (* == EOF *) ) - else - // read a character - end the scan if there are no further transitions - let inp = int(lexBuffer.Buffer.[lexBuffer.BufferScanPos]) - let snew = int trans.[state].[inp] - if snew = sentinel then - lexBuffer.EndOfScan() - else - lexBuffer.BufferScanLength <- lexBuffer.BufferScanLength + 1; - // Printf.printf "state %d --> %d on '%c' (%d)\n" state snew (Char.chr inp) inp; - scanUntilSentinel(lexBuffer, snew) - - /// Interpret tables for an ascii lexer generated by fslex. - member tables.Interpret(initialState,lexBuffer : LexBuffer) = - startInterpret(lexBuffer) - scanUntilSentinel(lexBuffer, initialState) - - /// Interpret tables for an ascii lexer generated by fslex. - member tables.AsyncInterpret(initialState,lexBuffer : LexBuffer) = - - let rec scanUntilSentinel(lexBuffer,state) : Async = - async { - let sentinel = 255 * 256 + 255 - // Return an endOfScan after consuming the input - let a = int accept.[state] - if a <> sentinel then - onAccept (lexBuffer,a) - - if lexBuffer.BufferScanLength = lexBuffer.BufferMaxScanLength then - lexBuffer.DiscardInput(); - do! lexBuffer.AsyncRefillBuffer (); - // end of file occurs if we couldn't extend the buffer - return! afterRefill (trans,sentinel,lexBuffer,scanUntilSentinel,endOfScan,state,256 (* == EOF *) ) - else - // read a character - end the scan if there are no further transitions - let inp = int(lexBuffer.Buffer.[lexBuffer.BufferScanPos]) - let snew = int trans.[state].[inp] - if snew = sentinel then - return! endOfScan() - else - lexBuffer.BufferScanLength <- lexBuffer.BufferScanLength + 1; - return! scanUntilSentinel(lexBuffer,snew) - } - and endOfScan() = - async { return lexBuffer.EndOfScan() } - startInterpret(lexBuffer) - scanUntilSentinel(lexBuffer, initialState) - - - static member Create(trans,accept) = new AsciiTables(trans,accept) - - [] -#if INTERNALIZED_FSLEXYACC_RUNTIME - type internal UnicodeTables(trans: uint16[] array, accept: uint16[]) = -#else - type UnicodeTables(trans: uint16[] array, accept: uint16[]) = -#endif - let sentinel = 255 * 256 + 255 - let numUnicodeCategories = 30 - let numLowUnicodeChars = 128 - let numSpecificUnicodeChars = (trans.[0].Length - 1 - numLowUnicodeChars - numUnicodeCategories)/2 - let lookupUnicodeCharacters (state,inp) = - let inpAsInt = int inp - // Is it a fast ASCII character? - if inpAsInt < numLowUnicodeChars then - int trans.[state].[inpAsInt] - else - // Search for a specific unicode character - let baseForSpecificUnicodeChars = numLowUnicodeChars - let rec loop i = - if i >= numSpecificUnicodeChars then - // OK, if we failed then read the 'others' entry in the alphabet, - // which covers all Unicode characters not covered in other - // ways - let baseForUnicodeCategories = numLowUnicodeChars+numSpecificUnicodeChars*2 - let unicodeCategory = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(inp) - //System.Console.WriteLine("inp = {0}, unicodeCategory = {1}", [| box inp; box unicodeCategory |]); - int trans.[state].[baseForUnicodeCategories + int32 unicodeCategory] - else - // This is the specific unicode character - let c = char (int trans.[state].[baseForSpecificUnicodeChars+i*2]) - //System.Console.WriteLine("c = {0}, inp = {1}, i = {2}", [| box c; box inp; box i |]); - // OK, have we found the entry for a specific unicode character? - if c = inp - then int trans.[state].[baseForSpecificUnicodeChars+i*2+1] - else loop(i+1) - - loop 0 - let eofPos = numLowUnicodeChars + 2*numSpecificUnicodeChars + numUnicodeCategories - - let rec scanUntilSentinel(lexBuffer,state) = - // Return an endOfScan after consuming the input - let a = int accept.[state] - if a <> sentinel then - onAccept(lexBuffer,a) - - if lexBuffer.BufferScanLength = lexBuffer.BufferMaxScanLength then - lexBuffer.DiscardInput(); - lexBuffer.RefillBuffer (); - // end of file occurs if we couldn't extend the buffer - afterRefill (trans,sentinel,lexBuffer,scanUntilSentinel,lexBuffer.EndOfScan,state,eofPos) - else - // read a character - end the scan if there are no further transitions - let inp = lexBuffer.Buffer.[lexBuffer.BufferScanPos] - - // Find the new state - let snew = lookupUnicodeCharacters (state,inp) - - if snew = sentinel then - lexBuffer.EndOfScan() - else - lexBuffer.BufferScanLength <- lexBuffer.BufferScanLength + 1; - // Printf.printf "state %d --> %d on '%c' (%d)\n" s snew (char inp) inp; - scanUntilSentinel(lexBuffer,snew) - - // Each row for the Unicode table has format - // 128 entries for ASCII characters - // A variable number of 2*UInt16 entries for SpecificUnicodeChars - // 30 entries, one for each UnicodeCategory - // 1 entry for EOF - - member tables.Interpret(initialState,lexBuffer : LexBuffer) = - startInterpret(lexBuffer) - scanUntilSentinel(lexBuffer, initialState) - - member tables.AsyncInterpret(initialState,lexBuffer : LexBuffer) = - - let rec scanUntilSentinel(lexBuffer, state) = - async { - // Return an endOfScan after consuming the input - let a = int accept.[state] - if a <> sentinel then - onAccept(lexBuffer,a) - - if lexBuffer.BufferScanLength = lexBuffer.BufferMaxScanLength then - lexBuffer.DiscardInput(); - lexBuffer.RefillBuffer (); - // end of file occurs if we couldn't extend the buffer - return! afterRefill (trans,sentinel,lexBuffer,scanUntilSentinel,endOfScan,state,eofPos) - else - // read a character - end the scan if there are no further transitions - let inp = lexBuffer.Buffer.[lexBuffer.BufferScanPos] - - // Find the new state - let snew = lookupUnicodeCharacters (state,inp) - - if snew = sentinel then - return! endOfScan() - else - lexBuffer.BufferScanLength <- lexBuffer.BufferScanLength + 1; - return! scanUntilSentinel(lexBuffer, snew) - } - and endOfScan() = - async { return lexBuffer.EndOfScan() } - startInterpret(lexBuffer) - scanUntilSentinel(lexBuffer, initialState) - - static member Create(trans,accept) = new UnicodeTables(trans,accept) diff --git a/src/fcs-fable/src/buildtools/fslex/Lexing.fsi b/src/fcs-fable/src/buildtools/fslex/Lexing.fsi deleted file mode 100644 index e31ad411aa..0000000000 --- a/src/fcs-fable/src/buildtools/fslex/Lexing.fsi +++ /dev/null @@ -1,151 +0,0 @@ -//========================================================================== -// LexBuffers are for use with automatically generated lexical analyzers, -// in particular those produced by 'fslex'. -// -// (c) Microsoft Corporation 2005-2008. -//=========================================================================== - -#if INTERNALIZED_FSLEXYACC_RUNTIME -namespace Internal.Utilities.Text.Lexing -#else -namespace Microsoft.FSharp.Text.Lexing -#endif - -open System.Collections.Generic - -/// Position information stored for lexing tokens -// -// Note: this is an OCaml compat record type. -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal Position = -#else -type Position = -#endif - { /// The file name for the position - pos_fname: string; - /// The line number for the position - pos_lnum: int; -#if INTERNALIZED_FSLEXYACC_RUNTIME - /// The line number for the position in the original source file - pos_orig_lnum : int; -#endif - /// The absolute offset of the beginning of the line - pos_bol: int; - /// The absolute offset of the column for the position - pos_cnum: int; } - /// The file name associated with the input stream. - member FileName : string - /// The line number in the input stream, assuming fresh positions have been updated - /// using AsNewLinePos() and by modifying the EndPos property of the LexBuffer. - member Line : int -#if INTERNALIZED_FSLEXYACC_RUNTIME - /// The line number for the position in the input stream, assuming fresh positions have been updated - /// using AsNewLinePos() - member OriginalLine : int -#endif - [] - member Char : int - /// The character number in the input stream - member AbsoluteOffset : int - /// Return absolute offset of the start of the line marked by the position - member StartOfLineAbsoluteOffset : int - /// Return the column number marked by the position, i.e. the difference between the AbsoluteOffset and the StartOfLineAbsoluteOffset - member Column : int - // Given a position just beyond the end of a line, return a position at the start of the next line - member NextLine : Position - - /// Given a position at the start of a token of length n, return a position just beyond the end of the token - member EndOfToken: n:int -> Position - /// Gives a position shifted by specified number of characters - member ShiftColumnBy: by:int -> Position - - [] - member AsNewLinePos : unit -> Position - - /// Get an arbitrary position, with the empty string as filename, and - static member Empty : Position - - /// Get a position corresponding to the first line (line number 1) in a given file - static member FirstLine : filename:string -> Position - -[] -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal LexBuffer<'char> = -#else -/// Input buffers consumed by lexers generated by fslex.exe -type LexBuffer<'char> = -#endif - /// The start position for the lexeme - member StartPos: Position with get,set - /// The end position for the lexeme - member EndPos: Position with get,set - /// The matched string - member Lexeme: 'char array - - /// Fast helper to turn the matched characters into a string, avoiding an intermediate array - static member LexemeString : LexBuffer -> string - - /// The length of the matched string - member LexemeLength: int - /// Fetch a particular character in the matched string - member LexemeChar: int -> 'char - - /// Dynamically typed, non-lexically scoped parameter table - member BufferLocalStore : IDictionary - - /// True if the refill of the buffer ever failed , or if explicitly set to true. - member IsPastEndOfStream: bool with get,set - /// Remove all input, though don't discard the current lexeme - member DiscardInput: unit -> unit - - /// Create a lex buffer suitable for byte lexing that reads characters from the given array - static member FromBytes: byte[] -> LexBuffer - /// Create a lex buffer suitable for Unicode lexing that reads characters from the given array - static member FromChars: char[] -> LexBuffer - /// Create a lex buffer suitable for Unicode lexing that reads characters from the given string - static member FromString: string -> LexBuffer - /// Create a lex buffer that reads character or byte inputs by using the given function - static member FromFunction: ('char[] * int * int -> int) -> LexBuffer<'char> - /// Create a lex buffer that asynchronously reads character or byte inputs by using the given function - static member FromAsyncFunction: ('char[] * int * int -> Async) -> LexBuffer<'char> - - - [.FromFunction instead")>] - static member FromCharFunction: (char[] -> int -> int) -> LexBuffer - [.FromFunction instead")>] - static member FromByteFunction: (byte[] -> int -> int) -> LexBuffer - - /// Create a lex buffer suitable for use with a Unicode lexer that reads character inputs from the given text reader - static member FromTextReader: System.IO.TextReader -> LexBuffer - /// Create a lex buffer suitable for use with ASCII byte lexing that reads byte inputs from the given binary reader - static member FromBinaryReader: System.IO.BinaryReader -> LexBuffer - - -/// The type of tables for an ascii lexer generated by fslex. -[] -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal AsciiTables = -#else -type AsciiTables = -#endif - static member Create : uint16[] array * uint16[] -> AsciiTables - /// Interpret tables for an ascii lexer generated by fslex. - member Interpret: initialState:int * LexBuffer -> int - /// Interpret tables for an ascii lexer generated by fslex, processing input asynchronously - member AsyncInterpret: initialState:int * LexBuffer -> Async - - -/// The type of tables for an unicode lexer generated by fslex. -[] -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal UnicodeTables = -#else -type UnicodeTables = -#endif - static member Create : uint16[] array * uint16[] -> UnicodeTables - /// Interpret tables for a unicode lexer generated by fslex. - member Interpret: initialState:int * LexBuffer -> int - - /// Interpret tables for a unicode lexer generated by fslex, processing input asynchronously - member AsyncInterpret: initialState:int * LexBuffer -> Async - diff --git a/src/fcs-fable/src/buildtools/fslex/Parsing.fs b/src/fcs-fable/src/buildtools/fslex/Parsing.fs deleted file mode 100644 index 01dccfb610..0000000000 --- a/src/fcs-fable/src/buildtools/fslex/Parsing.fs +++ /dev/null @@ -1,514 +0,0 @@ -// (c) Microsoft Corporation 2005-2009. - -#if INTERNALIZED_FSLEXYACC_RUNTIME - -namespace Internal.Utilities.Text.Parsing -open Internal.Utilities -open Internal.Utilities.Text.Lexing - -#else -namespace Microsoft.FSharp.Text.Parsing -open Microsoft.FSharp.Text.Lexing -#endif - - - -open System -open System.Collections.Generic - -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal IParseState = -#else -type IParseState = -#endif - abstract InputRange: int -> Position * Position - abstract InputEndPosition: int -> Position - abstract InputStartPosition: int -> Position - abstract ResultRange: Position * Position - abstract GetInput: int -> obj - abstract ParserLocalStore : IDictionary - abstract RaiseError<'b> : unit -> 'b - -//------------------------------------------------------------------------- -// This context is passed to the error reporter when a syntax error occurs - -[] -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal ParseErrorContext<'tok> -#else -type ParseErrorContext<'tok> -#endif - (//lexbuf: LexBuffer<_>, - stateStack:int list, - parseState: IParseState, - reduceTokens: int list, - currentToken: 'tok option, - reducibleProductions: int list list, - shiftableTokens: int list , - message : string) = - //member x.LexBuffer = lexbuf - member x.StateStack = stateStack - member x.ReduceTokens = reduceTokens - member x.CurrentToken = currentToken - member x.ParseState = parseState - member x.ReducibleProductions = reducibleProductions - member x.ShiftTokens = shiftableTokens - member x.Message = message - - -//------------------------------------------------------------------------- -// This is the data structure emitted as code by FSYACC. - -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal Tables<'tok> = -#else -type Tables<'tok> = -#endif - { reductions: (IParseState -> obj) array; - endOfInputTag: int; - tagOfToken: 'tok -> int; - dataOfToken: 'tok -> obj; - actionTableElements: uint16[]; - actionTableRowOffsets: uint16[]; - reductionSymbolCounts: uint16[]; - immediateActions: uint16[]; - gotos: uint16[]; - sparseGotoTableRowOffsets: uint16[]; - stateToProdIdxsTableElements: uint16[]; - stateToProdIdxsTableRowOffsets: uint16[]; - productionToNonTerminalTable: uint16[]; - /// For fsyacc.exe, this entry is filled in by context from the generated parser file. If no 'parse_error' function - /// is defined by the user then ParseHelpers.parse_error is used by default (ParseHelpers is opened - /// at the top of the generated parser file) - parseError: ParseErrorContext<'tok> -> unit; - numTerminals: int; - tagOfErrorTerminal: int } - -//------------------------------------------------------------------------- -// An implementation of stacks. - -// This type is in System.dll so for the moment we can't use it in FSharp.Core.dll -//type Stack<'a> = System.Collections.Generic.Stack<'a> - -#if INTERNALIZED_FSLEXYACC_RUNTIME -type Stack<'a>(n) = -#else -type internal Stack<'a>(n) = -#endif - let mutable contents = Array.zeroCreate<'a>(n) - let mutable count = 0 - - member buf.Ensure newSize = - let oldSize = Array.length contents - if newSize > oldSize then - let old = contents - contents <- Array.zeroCreate (max newSize (oldSize * 2)); - Array.blit old 0 contents 0 count; - - member buf.Count = count - member buf.Pop() = count <- count - 1 - member buf.Peep() = contents.[count - 1] - member buf.Top(n) = [ for x in contents.[max 0 (count-n)..count - 1] -> x ] |> List.rev - member buf.Push(x) = - buf.Ensure(count + 1); - contents.[count] <- x; - count <- count + 1 - - member buf.IsEmpty = (count = 0) -#if __DEBUG - member buf.PrintStack() = - for i = 0 to (count - 1) do -#if FX_NO_CONSOLE - () -#else - System.Console.Write("{0}{1}",(contents.[i]),if i=count-1 then ":" else "-") -#endif -#endif -exception RecoverableParseError -exception Accept of obj - -#if __DEBUG -module Flags = - let mutable debug = false -#endif - -#if INTERNALIZED_FSLEXYACC_RUNTIME -module internal Implementation = -#else -module Implementation = -#endif - - // Definitions shared with fsyacc - let anyMarker = 0xffff - let shiftFlag = 0x0000 - let reduceFlag = 0x4000 - let errorFlag = 0x8000 - let acceptFlag = 0xc000 - let actionMask = 0xc000 - - let actionValue action = action &&& (~~~ actionMask) - let actionKind action = action &&& actionMask - - //------------------------------------------------------------------------- - // Read the tables written by FSYACC. - - type AssocTable(elemTab:uint16[], offsetTab:uint16[]) = - let cache = new Dictionary<_,_>(2000) - - member t.readAssoc (minElemNum,maxElemNum,defaultValueOfAssoc,keyToFind) = - // do a binary chop on the table - let elemNumber : int = (minElemNum+maxElemNum)/2 - if elemNumber = maxElemNum - then defaultValueOfAssoc - else - let x = int elemTab.[elemNumber*2] - if keyToFind = x then - int elemTab.[elemNumber*2+1] - elif keyToFind < x then t.readAssoc (minElemNum ,elemNumber,defaultValueOfAssoc,keyToFind) - else t.readAssoc (elemNumber+1,maxElemNum,defaultValueOfAssoc,keyToFind) - - member t.Read(rowNumber ,keyToFind) = - - // First check the sparse lookaside table - // Performance note: without this lookaside table the binary chop in readAssoc - // takes up around 10% of of parsing time - // for parsing intensive samples such as the bootstrapped F# compiler. - // - // Note: using a .NET Dictionary for this int -> int table looks like it could be sub-optimal. - // Some other better sparse lookup table may be better. - let mutable res = 0 - let cacheKey = (rowNumber <<< 16) ||| keyToFind - let ok = cache.TryGetValue(cacheKey, &res) - if ok then res - else - let headOfTable = int offsetTab.[rowNumber] - let firstElemNumber = headOfTable + 1 - let numberOfElementsInAssoc = int elemTab.[headOfTable*2] - let defaultValueOfAssoc = int elemTab.[headOfTable*2+1] - let res = t.readAssoc (firstElemNumber,(firstElemNumber+numberOfElementsInAssoc),defaultValueOfAssoc,keyToFind) - cache.[cacheKey] <- res - res - - // Read all entries in the association table - // Used during error recovery to find all valid entries in the table - member x.ReadAll(n) = - let headOfTable = int offsetTab.[n] - let firstElemNumber = headOfTable + 1 - let numberOfElementsInAssoc = int32 elemTab.[headOfTable*2] - let defaultValueOfAssoc = int elemTab.[headOfTable*2+1] - [ for i in firstElemNumber .. (firstElemNumber+numberOfElementsInAssoc-1) -> - (int elemTab.[i*2], int elemTab.[i*2+1]) ], defaultValueOfAssoc - - type IdxToIdxListTable(elemTab:uint16[], offsetTab:uint16[]) = - - // Read all entries in a row of the table - member x.ReadAll(n) = - let headOfTable = int offsetTab.[n] - let firstElemNumber = headOfTable + 1 - let numberOfElements = int32 elemTab.[headOfTable] - [ for i in firstElemNumber .. (firstElemNumber+numberOfElements-1) -> int elemTab.[i] ] - - //------------------------------------------------------------------------- - // interpret the tables emitted by FSYACC. - - [] - [] - type ValueInfo = - val value: obj - val startPos: Position - val endPos: Position - new(value,startPos,endPos) = { value=value; startPos=startPos;endPos=endPos } - - let interpret (tables: Tables<'tok>) lexer (lexbuf : LexBuffer<_>) initialState = - let localStore = new Dictionary() in - localStore.["LexBuffer"] <- lexbuf; -#if __DEBUG - if Flags.debug then System.Console.WriteLine("\nParser: interpret tables"); -#endif - let stateStack : Stack = new Stack<_>(100) - stateStack.Push(initialState); - let valueStack = new Stack(100) - let mutable haveLookahead = false - let mutable lookaheadToken = Unchecked.defaultof<'tok> - let mutable lookaheadEndPos = Unchecked.defaultof - let mutable lookaheadStartPos = Unchecked.defaultof - let mutable finished = false - // After an error occurs, we suppress errors until we've shifted three tokens in a row. - let mutable errorSuppressionCountDown = 0 - - // When we hit the end-of-file we don't fail straight away but rather keep permitting shift - // and reduce against the last token in the token stream 20 times or until we've accepted - // or exhausted the stack. This allows error recovery rules of the form - // input : realInput EOF | realInput error EOF | error EOF - // where consuming one EOF to trigger an error doesn't result in overall parse failure - // catastrophe and the loss of intermediate results. - // - let mutable inEofCountDown = false - let mutable eofCountDown = 20 // Number of EOFs to supply at the end for error recovery - // The 100 here means a maximum of 100 elements for each rule - let ruleStartPoss = (Array.zeroCreate 100 : Position array) - let ruleEndPoss = (Array.zeroCreate 100 : Position array) - let ruleValues = (Array.zeroCreate 100 : obj array) - let lhsPos = (Array.zeroCreate 2 : Position array) - let reductions = tables.reductions - let actionTable = new AssocTable(tables.actionTableElements, tables.actionTableRowOffsets) - let gotoTable = new AssocTable(tables.gotos, tables.sparseGotoTableRowOffsets) - let stateToProdIdxsTable = new IdxToIdxListTable(tables.stateToProdIdxsTableElements, tables.stateToProdIdxsTableRowOffsets) - - let parseState = - { new IParseState with - member p.InputRange(n) = ruleStartPoss.[n-1], ruleEndPoss.[n-1]; - member p.InputStartPosition(n) = ruleStartPoss.[n-1] - member p.InputEndPosition(n) = ruleEndPoss.[n-1]; - member p.GetInput(n) = ruleValues.[n-1]; - member p.ResultRange = (lhsPos.[0], lhsPos.[1]); - member p.ParserLocalStore = (localStore :> IDictionary<_,_>); - member p.RaiseError() = raise RecoverableParseError (* NOTE: this binding tests the fairly complex logic associated with an object expression implementing a generic abstract method *) - } - -#if __DEBUG - let report haveLookahead lookaheadToken = - if haveLookahead then sprintf "%A" lookaheadToken - else "[TBC]" -#endif - - // Pop the stack until we can shift the 'error' token. If 'tokenOpt' is given - // then keep popping until we can shift both the 'error' token and the token in 'tokenOpt'. - // This is used at end-of-file to make sure we can shift both the 'error' token and the 'EOF' token. - let rec popStackUntilErrorShifted(tokenOpt) = - // Keep popping the stack until the "error" terminal is shifted -#if __DEBUG - if Flags.debug then System.Console.WriteLine("popStackUntilErrorShifted"); -#endif - if stateStack.IsEmpty then -#if __DEBUG - if Flags.debug then - System.Console.WriteLine("state stack empty during error recovery - generating parse error"); -#endif - failwith "parse error"; - - let currState = stateStack.Peep() -#if __DEBUG - if Flags.debug then - System.Console.WriteLine("In state {0} during error recovery", currState); -#endif - - let action = actionTable.Read(currState, tables.tagOfErrorTerminal) - - if actionKind action = shiftFlag && - (match tokenOpt with - | None -> true - | Some(token) -> - let nextState = actionValue action - actionKind (actionTable.Read(nextState, tables.tagOfToken(token))) = shiftFlag) then - -#if __DEBUG - if Flags.debug then System.Console.WriteLine("shifting error, continuing with error recovery"); -#endif - let nextState = actionValue action - // The "error" non terminal needs position information, though it tends to be unreliable. - // Use the StartPos/EndPos from the lex buffer - valueStack.Push(ValueInfo(box (), lexbuf.StartPos, lexbuf.EndPos)); - stateStack.Push(nextState) - else - if valueStack.IsEmpty then - failwith "parse error"; -#if __DEBUG - if Flags.debug then - System.Console.WriteLine("popping stack during error recovery"); -#endif - valueStack.Pop(); - stateStack.Pop(); - popStackUntilErrorShifted(tokenOpt) - - while not finished do - if stateStack.IsEmpty then - finished <- true - else - let state = stateStack.Peep() -#if __DEBUG - if Flags.debug then (Console.Write("{0} value(state), state ",valueStack.Count); stateStack.PrintStack()) -#endif - let action = - let immediateAction = int tables.immediateActions.[state] - if not (immediateAction = anyMarker) then - // Action has been pre-determined, no need to lookahead - // Expecting it to be a Reduce action on a non-fakeStartNonTerminal ? - immediateAction - else - // Lookahead required to determine action - if not haveLookahead then - if lexbuf.IsPastEndOfStream then - // When the input runs out, keep supplying the last token for eofCountDown times - if eofCountDown>0 then - haveLookahead <- true - eofCountDown <- eofCountDown - 1 - inEofCountDown <- true - else - haveLookahead <- false - else - lookaheadToken <- lexer lexbuf - lookaheadStartPos <- lexbuf.StartPos - lookaheadEndPos <- lexbuf.EndPos - haveLookahead <- true; - - let tag = - if haveLookahead then tables.tagOfToken lookaheadToken - else tables.endOfInputTag - - // Printf.printf "state %d\n" state - actionTable.Read(state,tag) - - let kind = actionKind action - if kind = shiftFlag then ( - if errorSuppressionCountDown > 0 then - errorSuppressionCountDown <- errorSuppressionCountDown - 1; -#if __DEBUG - if Flags.debug then Console.WriteLine("shifting, reduced errorRecoverylevel to {0}\n", errorSuppressionCountDown); -#endif - let nextState = actionValue action - if not haveLookahead then failwith "shift on end of input!"; - let data = tables.dataOfToken lookaheadToken - valueStack.Push(ValueInfo(data, lookaheadStartPos, lookaheadEndPos)); - stateStack.Push(nextState); -#if __DEBUG - if Flags.debug then Console.WriteLine("shift/consume input {0}, shift to state {1}", report haveLookahead lookaheadToken, nextState); -#endif - haveLookahead <- false - - ) elif kind = reduceFlag then - let prod = actionValue action - let reduction = reductions.[prod] - let n = int tables.reductionSymbolCounts.[prod] - // pop the symbols, populate the values and populate the locations -#if __DEBUG - if Flags.debug then Console.Write("reduce popping {0} values/states, lookahead {1}", n, report haveLookahead lookaheadToken); -#endif - - lhsPos.[0] <- Position.Empty; - lhsPos.[1] <- Position.Empty; - for i = 0 to n - 1 do - if valueStack.IsEmpty then failwith "empty symbol stack"; - let topVal = valueStack.Peep() - valueStack.Pop(); - stateStack.Pop(); - ruleValues.[(n-i)-1] <- topVal.value; - ruleStartPoss.[(n-i)-1] <- topVal.startPos; - ruleEndPoss.[(n-i)-1] <- topVal.endPos; - if lhsPos.[1] = Position.Empty then lhsPos.[1] <- topVal.endPos; - if not (topVal.startPos = Position.Empty) then lhsPos.[0] <- topVal.startPos - done; - - try - // Printf.printf "reduce %d\n" prod; - let redResult = reduction parseState - valueStack.Push(ValueInfo(redResult, lhsPos.[0], lhsPos.[1])); - let currState = stateStack.Peep() - let newGotoState = gotoTable.Read(int tables.productionToNonTerminalTable.[prod], currState) - stateStack.Push(newGotoState) -#if __DEBUG - if Flags.debug then Console.WriteLine(" goto state {0}", newGotoState) -#endif - with - | Accept res -> - finished <- true; - valueStack.Push(ValueInfo(res, lhsPos.[0], lhsPos.[1])) - | RecoverableParseError -> -#if __DEBUG - if Flags.debug then Console.WriteLine("RecoverableParseErrorException...\n"); -#endif - popStackUntilErrorShifted(None); - // User code raised a Parse_error. Don't report errors again until three tokens have been shifted - errorSuppressionCountDown <- 3 - elif kind = errorFlag then ( -#if __DEBUG - if Flags.debug then Console.Write("ErrorFlag... "); -#endif - // Silently discard inputs and don't report errors - // until three tokens in a row have been shifted -#if __DEBUG - if Flags.debug then printfn "error on token '%A' " (if haveLookahead then Some(lookaheadToken) else None); -#endif - if errorSuppressionCountDown > 0 then - // If we're in the end-of-file count down then we're very keen to 'Accept'. - // We can only do this by repeatedly popping the stack until we can shift both an 'error' token - // and an EOF token. - if inEofCountDown && eofCountDown < 10 then -#if __DEBUG - if Flags.debug then printfn "poppin stack, lokking to shift both 'error' and that token, during end-of-file error recovery" ; -#endif - popStackUntilErrorShifted(if haveLookahead then Some(lookaheadToken) else None); - - // If we don't haveLookahead then the end-of-file count down is over and we have no further options. - if not haveLookahead then - failwith "parse error: unexpected end of file" - -#if __DEBUG - if Flags.debug then printfn "discarding token '%A' during error suppression" (if haveLookahead then Some(lookaheadToken) else None); -#endif - // Discard the token - haveLookahead <- false - // Try again to shift three tokens - errorSuppressionCountDown <- 3 - else ( - - let currentToken = if haveLookahead then Some(lookaheadToken) else None - let actions,defaultAction = actionTable.ReadAll(state) - let explicit = Set.ofList [ for (tag,_action) in actions -> tag ] - - let shiftableTokens = - [ for (tag,action) in actions do - if (actionKind action) = shiftFlag then - yield tag - if actionKind defaultAction = shiftFlag then - for tag in 0 .. tables.numTerminals-1 do - if not (explicit.Contains(tag)) then - yield tag ] in - - let stateStack = stateStack.Top(12) in - let reducibleProductions = - [ for state in stateStack do - yield stateToProdIdxsTable.ReadAll(state) ] - - let reduceTokens = - [ for (tag,action) in actions do - if actionKind(action) = reduceFlag then - yield tag - if actionKind(defaultAction) = reduceFlag then - for tag in 0 .. tables.numTerminals-1 do - if not (explicit.Contains(tag)) then - yield tag ] in - //let activeRules = stateStack |> List.iter (fun state -> - let errorContext = new ParseErrorContext<'tok>(stateStack,parseState, reduceTokens,currentToken,reducibleProductions, shiftableTokens, "syntax error") - tables.parseError(errorContext); - popStackUntilErrorShifted(None); - errorSuppressionCountDown <- 3; -#if __DEBUG - if Flags.debug then System.Console.WriteLine("generated syntax error and shifted error token, haveLookahead = {0}\n", haveLookahead); -#endif - ) - ) elif kind = acceptFlag then - finished <- true -#if __DEBUG - else - if Flags.debug then System.Console.WriteLine("ALARM!!! drop through case in parser"); -#endif - done; - // OK, we're done - read off the overall generated value - valueStack.Peep().value - -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal Tables<'tok> with -#else -type Tables<'tok> with -#endif - member tables.Interpret (lexer,lexbuf,initialState) = - Implementation.interpret tables lexer lexbuf initialState - -#if INTERNALIZED_FSLEXYACC_RUNTIME -module internal ParseHelpers = -#else -module ParseHelpers = -#endif - let parse_error (_s:string) = () - let parse_error_rich = (None : (ParseErrorContext<_> -> unit) option) diff --git a/src/fcs-fable/src/buildtools/fslex/Parsing.fsi b/src/fcs-fable/src/buildtools/fslex/Parsing.fsi deleted file mode 100644 index 2fef45975a..0000000000 --- a/src/fcs-fable/src/buildtools/fslex/Parsing.fsi +++ /dev/null @@ -1,130 +0,0 @@ -//========================================================================== -// (c) Microsoft Corporation 2005-2009. -//========================================================================= - -#if INTERNALIZED_FSLEXYACC_RUNTIME -namespace Internal.Utilities.Text.Parsing -open Internal.Utilities -open Internal.Utilities.Text.Lexing -#else -namespace Microsoft.FSharp.Text.Parsing -open Microsoft.FSharp.Text.Lexing -#endif - -open System.Collections.Generic - -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal IParseState = -#else -/// The information accessible via the parseState value within parser actions. -type IParseState = -#endif - /// Get the start and end position for the terminal or non-terminal at a given index matched by the production - abstract InputRange: index:int -> Position * Position - /// Get the end position for the terminal or non-terminal at a given index matched by the production - abstract InputEndPosition: int -> Position - /// Get the start position for the terminal or non-terminal at a given index matched by the production - abstract InputStartPosition: int -> Position - /// Get the full range of positions matched by the production - abstract ResultRange: Position * Position - /// Get the value produced by the terminal or non-terminal at the given position - abstract GetInput : int -> obj - /// Get the store of local values associated with this parser - // Dynamically typed, non-lexically scoped local store - abstract ParserLocalStore : IDictionary - /// Raise an error in this parse context - abstract RaiseError<'b> : unit -> 'b - - -[] -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal ParseErrorContext<'tok> = -#else -/// The context provided when a parse error occurs -type ParseErrorContext<'tok> = -#endif - /// The stack of state indexes active at the parse error - member StateStack : int list - /// The state active at the parse error - member ParseState : IParseState - /// The tokens that would cause a reduction at the parse error - member ReduceTokens: int list - /// The stack of productions that would be reduced at the parse error - member ReducibleProductions : int list list - /// The token that caused the parse error - member CurrentToken : 'tok option - /// The token that would cause a shift at the parse error - member ShiftTokens : int list - /// The message associated with the parse error - member Message : string - -/// Tables generated by fsyacc -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal Tables<'tok> = -#else -/// The type of the tables contained in a file produced by the fsyacc.exe parser generator. -type Tables<'tok> = -#endif - { /// The reduction table - reductions: (IParseState -> obj) array ; - /// The token number indicating the end of input - endOfInputTag: int; - /// A function to compute the tag of a token - tagOfToken: 'tok -> int; - /// A function to compute the data carried by a token - dataOfToken: 'tok -> obj; - /// The sparse action table elements - actionTableElements: uint16[]; - /// The sparse action table row offsets - actionTableRowOffsets: uint16[]; - /// The number of symbols for each reduction - reductionSymbolCounts: uint16[]; - /// The immediate action table - immediateActions: uint16[]; - /// The sparse goto table - gotos: uint16[]; - /// The sparse goto table row offsets - sparseGotoTableRowOffsets: uint16[]; - /// The sparse table for the productions active for each state - stateToProdIdxsTableElements: uint16[]; - /// The sparse table offsets for the productions active for each state - stateToProdIdxsTableRowOffsets: uint16[]; - /// This table is logically part of the Goto table - productionToNonTerminalTable: uint16[]; - /// This function is used to hold the user specified "parse_error" or "parse_error_rich" functions - parseError: ParseErrorContext<'tok> -> unit; - /// The total number of terminals - numTerminals: int; - /// The tag of the error terminal - tagOfErrorTerminal: int } - - /// Interpret the parser table taking input from the given lexer, using the given lex buffer, and the given start state. - /// Returns an object indicating the final synthesized value for the parse. - member Interpret : lexer:(LexBuffer<'char> -> 'tok) * lexbuf:LexBuffer<'char> * startState:int -> obj - -#if INTERNALIZED_FSLEXYACC_RUNTIME -exception internal Accept of obj -exception internal RecoverableParseError -#else -/// Indicates an accept action has occured -exception Accept of obj -/// Indicates a parse error has occured and parse recovery is in progress -exception RecoverableParseError -#endif - -#if __DEBUG -module internal Flags = - val mutable debug : bool -#endif - -#if INTERNALIZED_FSLEXYACC_RUNTIME -module internal ParseHelpers = -#else -/// Helpers used by generated parsers. -module ParseHelpers = -#endif - /// The default implementation of the parse_error_rich function - val parse_error_rich: (ParseErrorContext<'tok> -> unit) option - /// The default implementation of the parse_error function - val parse_error: string -> unit - diff --git a/src/fcs-fable/src/buildtools/fslex/fslex.fs b/src/fcs-fable/src/buildtools/fslex/fslex.fs deleted file mode 100644 index 98966fdfaf..0000000000 --- a/src/fcs-fable/src/buildtools/fslex/fslex.fs +++ /dev/null @@ -1,222 +0,0 @@ -// (c) Microsoft Corporation 2005-2009. - -module internal FsLexYacc.FsLex.Driver - -open FsLexYacc.FsLex -open FsLexYacc.FsLex.AST -open FsLexYacc.FsLex.Parser -open Printf -open Internal.Utilities -open Internal.Utilities.Text.Lexing -open System -open System.Collections.Generic -open System.IO - -//------------------------------------------------------------------ -// This code is duplicated from Microsoft.FSharp.Compiler.UnicodeLexing - -type Lexbuf = LexBuffer - -/// Standard utility to create a Unicode LexBuffer -/// -/// One small annoyance is that LexBuffers and not IDisposable. This means -/// we can't just return the LexBuffer object, since the file it wraps wouldn't -/// get closed when we're finished with the LexBuffer. Hence we return the stream, -/// the reader and the LexBuffer. The caller should dispose the first two when done. -let UnicodeFileAsLexbuf (filename,codePage : int option) : FileStream * StreamReader * Lexbuf = - // Use the .NET functionality to auto-detect the unicode encoding - // It also presents the bytes read to the lexer in UTF8 decoded form - let stream = new FileStream(filename,FileMode.Open,FileAccess.Read,FileShare.Read) - let reader = - match codePage with - | None -> new StreamReader(stream,true) - | Some n -> new StreamReader(stream,System.Text.Encoding.GetEncoding(n)) - let lexbuf = LexBuffer.FromFunction(reader.Read) - lexbuf.EndPos <- Position.FirstLine(filename) - stream, reader, lexbuf - -//------------------------------------------------------------------ -// This is the program proper - -let input = ref None -let out = ref None -let inputCodePage = ref None -let light = ref None - -let mutable lexlib = "FSharp.Text.Lexing" - -let usage = - [ ArgInfo ("-o", ArgType.String (fun s -> out := Some s), "Name the output file.") - ArgInfo ("--codepage", ArgType.Int (fun i -> inputCodePage := Some i), "Assume input lexer specification file is encoded with the given codepage.") - ArgInfo ("--light", ArgType.Unit (fun () -> light := Some true), "(ignored)") - ArgInfo ("--light-off", ArgType.Unit (fun () -> light := Some false), "Add #light \"off\" to the top of the generated file") - ArgInfo ("--lexlib", ArgType.String (fun s -> lexlib <- s), "Specify the namespace for the implementation of the lexer table interpreter (default FSharp.Text.Lexing)") - ArgInfo ("--unicode", ArgType.Set unicode, "Produce a lexer for use with 16-bit unicode characters.") - ] - -let _ = ArgParser.Parse(usage, (fun x -> match !input with Some _ -> failwith "more than one input given" | None -> input := Some x), "fslex ") - -let outputInt (os: TextWriter) (n:int) = os.Write(string n) - -let outputCodedUInt16 (os: #TextWriter) (n:int) = - os.Write n - os.Write "us; " - -let sentinel = 255 * 256 + 255 - -let lineCount = ref 0 -let cfprintfn (os: #TextWriter) fmt = Printf.kfprintf (fun () -> incr lineCount; os.WriteLine()) os fmt - -let main() = - try - let filename = (match !input with Some x -> x | None -> failwith "no input given") - let domain = if !unicode then "Unicode" else "Ascii" - let spec = - let stream,reader,lexbuf = UnicodeFileAsLexbuf(filename, !inputCodePage) - use stream = stream - use reader = reader - try - Parser.spec Lexer.token lexbuf - with e -> - eprintf "%s(%d,%d): error: %s" filename lexbuf.StartPos.Line lexbuf.StartPos.Column - (match e with - | Failure s -> s - | _ -> e.Message) - exit 1 - printfn "compiling to dfas (can take a while...)" - let perRuleData, dfaNodes = AST.Compile spec - let dfaNodes = dfaNodes |> List.sortBy (fun n -> n.Id) - - printfn "%d states" dfaNodes.Length - printfn "writing output" - - let output = - match !out with - | Some x -> x - | _ -> - Path.Combine (Path.GetDirectoryName filename,Path.GetFileNameWithoutExtension(filename)) + ".fs" - use os = System.IO.File.CreateText output - - if (!light = Some(false)) || (!light = None && (Path.HasExtension(output) && Path.GetExtension(output) = ".ml")) then - cfprintfn os "#light \"off\"" - - let printLinesIfCodeDefined (code,pos:Position) = - if pos <> Position.Empty // If bottom code is unspecified, then position is empty. - then - cfprintfn os "# %d \"%s\"" pos.Line pos.FileName - cfprintfn os "%s" code - - printLinesIfCodeDefined spec.TopCode - let code = fst spec.TopCode - lineCount := !lineCount + code.Replace("\r","").Split([| '\n' |]).Length - cfprintfn os "# %d \"%s\"" !lineCount output - - cfprintfn os "let trans : uint16[] array = " - cfprintfn os " [| " - if !unicode then - let specificUnicodeChars = GetSpecificUnicodeChars() - // This emits a (numLowUnicodeChars+NumUnicodeCategories+(2*#specificUnicodeChars)+1) * #states array of encoded UInt16 values - - // Each row for the Unicode table has format - // 128 entries for ASCII characters - // A variable number of 2*UInt16 entries for SpecificUnicodeChars - // 30 entries, one for each UnicodeCategory - // 1 entry for EOF - // - // Each entry is an encoded UInt16 value indicating the next state to transition to for this input. - // - // For the SpecificUnicodeChars the entries are char/next-state pairs. - for state in dfaNodes do - cfprintfn os " (* State %d *)" state.Id - fprintf os " [| " - let trans = - let dict = new Dictionary<_,_>() - state.Transitions |> List.iter dict.Add - dict - let emit n = - if trans.ContainsKey(n) then - outputCodedUInt16 os trans.[n].Id - else - outputCodedUInt16 os sentinel - for i = 0 to numLowUnicodeChars-1 do - let c = char i - emit (EncodeChar c) - for c in specificUnicodeChars do - outputCodedUInt16 os (int c) - emit (EncodeChar c) - for i = 0 to NumUnicodeCategories-1 do - emit (EncodeUnicodeCategoryIndex i) - emit Eof - cfprintfn os "|];" - done - - else - // Each row for the ASCII table has format - // 256 entries for ASCII characters - // 1 entry for EOF - // - // Each entry is an encoded UInt16 value indicating the next state to transition to for this input. - - // This emits a (256+1) * #states array of encoded UInt16 values - for state in dfaNodes do - cfprintfn os " (* State %d *)" state.Id - fprintf os " [|" - let trans = - let dict = new Dictionary<_,_>() - state.Transitions |> List.iter dict.Add - dict - let emit n = - if trans.ContainsKey(n) then - outputCodedUInt16 os trans.[n].Id - else - outputCodedUInt16 os sentinel - for i = 0 to 255 do - let c = char i - emit (EncodeChar c) - emit Eof - cfprintfn os "|];" - done - - cfprintfn os " |] " - - fprintf os "let actions : uint16[] = [|" - for state in dfaNodes do - if state.Accepted.Length > 0 then - outputCodedUInt16 os (snd state.Accepted.Head) - else - outputCodedUInt16 os sentinel - done - cfprintfn os "|]" - cfprintfn os "let _fslex_tables = %s.%sTables.Create(trans,actions)" lexlib domain - - cfprintfn os "let rec _fslex_dummy () = _fslex_dummy() " - - // These actions push the additional start state and come first, because they are then typically inlined into later - // rules. This means more tailcalls are taken as direct branches, increasing efficiency and - // improving stack usage on platforms that do not take tailcalls. - for ((startNode, actions),(ident,args,_)) in List.zip perRuleData spec.Rules do - cfprintfn os "// Rule %s" ident - cfprintfn os "and %s %s lexbuf =" ident (String.Join(" ",Array.ofList args)) - cfprintfn os " match _fslex_tables.Interpret(%d,lexbuf) with" startNode.Id - actions |> Seq.iteri (fun i (code:string, pos) -> - cfprintfn os " | %d -> ( " i - cfprintfn os "# %d \"%s\"" pos.Line pos.FileName - let lines = code.Split([| '\r'; '\n' |], StringSplitOptions.RemoveEmptyEntries) - for line in lines do - cfprintfn os " %s" line - cfprintfn os "# %d \"%s\"" !lineCount output - cfprintfn os " )") - cfprintfn os " | _ -> failwith \"%s\"" ident - - - cfprintfn os "" - - printLinesIfCodeDefined spec.BottomCode - cfprintfn os "# 3000000 \"%s\"" output - - with e -> - eprintf "FSLEX: error FSL000: %s" (match e with Failure s -> s | e -> e.ToString()) - exit 1 - - -let result = main() diff --git a/src/fcs-fable/src/buildtools/fslex/fslex.fsproj b/src/fcs-fable/src/buildtools/fslex/fslex.fsproj deleted file mode 100644 index 9e21a860d8..0000000000 --- a/src/fcs-fable/src/buildtools/fslex/fslex.fsproj +++ /dev/null @@ -1,22 +0,0 @@ - - - - Exe - netcoreapp2.0 - INTERNALIZED_FSLEXYACC_RUNTIME;$(DefineConstant) - - - - - - - - - - - - - - - - diff --git a/src/fcs-fable/src/buildtools/fslex/fslexast.fs b/src/fcs-fable/src/buildtools/fslex/fslexast.fs deleted file mode 100644 index 64e914a013..0000000000 --- a/src/fcs-fable/src/buildtools/fslex/fslexast.fs +++ /dev/null @@ -1,409 +0,0 @@ -(* (c) Microsoft Corporation 2005-2008. *) - -module internal FsLexYacc.FsLex.AST - -open System.Collections.Generic -open FSharp.Text -open Microsoft.FSharp.Collections -open Internal.Utilities -open Internal.Utilities.Text.Lexing - -let (|KeyValue|) (kvp:KeyValuePair<_,_>) = kvp.Key,kvp.Value - -type Ident = string -type Code = string * Position - -type Alphabet = uint32 - -let Eof : Alphabet = 0xFFFFFFFEu -let Epsilon : Alphabet = 0xFFFFFFFFu - - -let unicode = ref false - -let unicodeCategories = - dict - [| "Pe", System.Globalization.UnicodeCategory.ClosePunctuation; // (Pe) - "Pc", System.Globalization.UnicodeCategory.ConnectorPunctuation; // (Pc) - "Cc", System.Globalization.UnicodeCategory.Control; // (Cc) - "Sc", System.Globalization.UnicodeCategory.CurrencySymbol; // (Sc) - "Pd", System.Globalization.UnicodeCategory.DashPunctuation; // (Pd) - "Nd", System.Globalization.UnicodeCategory.DecimalDigitNumber; // (Nd) - "Me", System.Globalization.UnicodeCategory.EnclosingMark; // (Me) - "Pf", System.Globalization.UnicodeCategory.FinalQuotePunctuation; // (Pf) - "Cf", enum 15; //System.Globalization.UnicodeCategory.Format; // (Cf) - "Pi", System.Globalization.UnicodeCategory.InitialQuotePunctuation; // (Pi) - "Nl", System.Globalization.UnicodeCategory.LetterNumber; // (Nl) - "Zl", System.Globalization.UnicodeCategory.LineSeparator; // (Zl) - "Ll", System.Globalization.UnicodeCategory.LowercaseLetter; // (Ll) - "Sm", System.Globalization.UnicodeCategory.MathSymbol; // (Sm) - "Lm", System.Globalization.UnicodeCategory.ModifierLetter; // (Lm) - "Sk", System.Globalization.UnicodeCategory.ModifierSymbol; // (Sk) - "Mn", System.Globalization.UnicodeCategory.NonSpacingMark; // (Mn) - "Ps", System.Globalization.UnicodeCategory.OpenPunctuation; // (Ps) - "Lo", System.Globalization.UnicodeCategory.OtherLetter; // (Lo) - "Cn", System.Globalization.UnicodeCategory.OtherNotAssigned; // (Cn) - "No", System.Globalization.UnicodeCategory.OtherNumber; // (No) - "Po", System.Globalization.UnicodeCategory.OtherPunctuation; // (Po) - "So", System.Globalization.UnicodeCategory.OtherSymbol; // (So) - "Zp", System.Globalization.UnicodeCategory.ParagraphSeparator; // (Zp) - "Co", System.Globalization.UnicodeCategory.PrivateUse; // (Co) - "Zs", System.Globalization.UnicodeCategory.SpaceSeparator; // (Zs) - "Mc", System.Globalization.UnicodeCategory.SpacingCombiningMark; // (Mc) - "Cs", System.Globalization.UnicodeCategory.Surrogate; // (Cs) - "Lt", System.Globalization.UnicodeCategory.TitlecaseLetter; // (Lt) - "Lu", System.Globalization.UnicodeCategory.UppercaseLetter; // (Lu) - |] - -let NumUnicodeCategories = unicodeCategories.Count -let _ = assert (NumUnicodeCategories = 30) // see table interpreter -let encodedUnicodeCategoryBase = 0xFFFFFF00u -let EncodeUnicodeCategoryIndex(idx:int) = encodedUnicodeCategoryBase + uint32 idx -let EncodeUnicodeCategory(s:string) = - if not (!unicode) then - failwith "unicode category classes may only be used if --unicode is specified"; - if unicodeCategories.ContainsKey(s) then - EncodeUnicodeCategoryIndex (int32 unicodeCategories.[s]) - else - failwithf "invalid Unicode category: '%s'" s - -let IsUnicodeCategory(x:Alphabet) = (encodedUnicodeCategoryBase <= x) && (x < encodedUnicodeCategoryBase + uint32 NumUnicodeCategories) -let UnicodeCategoryIndex(x:Alphabet) = (x - encodedUnicodeCategoryBase) - -let numLowUnicodeChars = 128 -let _ = assert (numLowUnicodeChars = 128) // see table interpreter -let specificUnicodeChars = new Dictionary<_,_>() -let specificUnicodeCharsDecode = new Dictionary<_,_>() -let EncodeChar(c:char) = - let x = System.Convert.ToUInt32 c - if !unicode then - if x < uint32 numLowUnicodeChars then x - else - if not(specificUnicodeChars.ContainsKey(c)) then - let idx = uint32 numLowUnicodeChars + uint32 specificUnicodeChars.Count - specificUnicodeChars.[c] <- idx - specificUnicodeCharsDecode.[idx] <- c - specificUnicodeChars.[c] - else - if x >= 256u then failwithf "the Unicode character '%c' may not be used unless --unicode is specified" c; - x -let DecodeChar(x:Alphabet) = - if !unicode then - if x < uint32 numLowUnicodeChars then System.Convert.ToChar x - else specificUnicodeCharsDecode.[x] - else - if x >= 256u then failwithf "the Unicode character '%x' may not be used unless --unicode is specified" x; - System.Convert.ToChar x - - - -let NumSpecificUnicodeChars() = specificUnicodeChars.Count -let GetSpecificUnicodeChars() = - specificUnicodeChars - |> Seq.sortBy (fun (KeyValue(k,v)) -> v) - |> Seq.map (fun (KeyValue(k,v)) -> k) - -let GetSingleCharAlphabet() = - if !unicode - then Set.ofList [ for c in 0..numLowUnicodeChars-1 do yield (char c) - for c in GetSpecificUnicodeChars() do yield c ] - else Set.ofList [ for x in 0..255 -> (char x) ] - -let GetAlphabet() = - if !unicode - then Set.ofList [ for c in GetSingleCharAlphabet() do yield EncodeChar c - for uc in 0 .. NumUnicodeCategories-1 do yield EncodeUnicodeCategoryIndex uc ] - else Set.ofList [ for c in GetSingleCharAlphabet() do yield EncodeChar c ] - - -//let DecodeAlphabet (x:Alphabet) = System.Convert.ToChar(x) - -(* -for i in 0 .. 65535 do - let c = char i - if System.Char.GetUnicodeCategory c = System.Globalization.UnicodeCategory.PrivateUse then - printfn "i = %x" i -*) - -type Spec = - { TopCode: Code; - Macros: (Ident * Regexp) list; - Rules: (Ident * Ident list * Clause list) list; - BottomCode: Code } -and Clause = Regexp * Code -and Regexp = - | Alt of Regexp list - | Seq of Regexp list - | Inp of Input - | Star of Regexp - | Macro of Ident -and Input = - | Alphabet of Alphabet - | UnicodeCategory of string - | Any - | NotCharSet of Set - -type NodeId = int - -type NfaNode = - { Id: NodeId; - Name: string; - Transitions: Dictionary; - Accepted: (int * int) list } - -type DfaNode = - { Id: int; - Name: string; - mutable Transitions: (Alphabet * DfaNode) list; - Accepted: (int * int) list } - -type MultiMap<'a,'b> = Dictionary<'a,'b list> -let LookupMultiMap (trDict:MultiMap<_,_>) a = - if trDict.ContainsKey(a) then trDict.[a] else [] - -let AddToMultiMap (trDict:MultiMap<_,_>) a b = - let prev = LookupMultiMap trDict a - trDict.[a] <- b::prev - -type NfaNodeMap() = - let map = new Dictionary(100) - member x.Item with get(nid) = map.[nid] - member x.Count = map.Count - - member x.NewNfaNode(trs,ac) = - let nodeId = map.Count+1 // ID zero is reserved - let trDict = new Dictionary<_,_>(List.length trs) - for (a,b) in trs do - AddToMultiMap trDict a b - - let node : NfaNode = {Id=nodeId; Name=string nodeId; Transitions=trDict; Accepted=ac} - map.[nodeId] <-node; - node - -let LexerStateToNfa (macros: Map) (clauses: Clause list) = - - /// Table allocating node ids - let nfaNodeMap = new NfaNodeMap() - - /// Compile a regular expression into the NFA - let rec CompileRegexp re dest = - match re with - | Alt res -> - let trs = res |> List.map (fun re -> (Epsilon,CompileRegexp re dest)) - nfaNodeMap.NewNfaNode(trs,[]) - | Seq res -> - List.foldBack (CompileRegexp) res dest - | Inp (Alphabet c) -> - nfaNodeMap.NewNfaNode([(c, dest)],[]) - - | Star re -> - let nfaNode = nfaNodeMap.NewNfaNode([(Epsilon, dest)],[]) - let sre = CompileRegexp re nfaNode - AddToMultiMap nfaNode.Transitions Epsilon sre - nfaNodeMap.NewNfaNode([(Epsilon,sre); (Epsilon,dest)],[]) - | Macro m -> - if not (macros.ContainsKey(m)) then failwith ("The macro "+m+" is not defined"); - CompileRegexp (macros.[m]) dest - - // These cases unwind the difficult cases in the syntax that rely on knowing the - // entire alphabet. - // - // Note we've delayed the expension of these until we've worked out all the 'special' Unicode characters - // mentioned in the entire lexer spec, i.e. we wait until GetAlphabet returns a reliable and stable answer. - | Inp (UnicodeCategory uc) -> - let re = Alt([ yield Inp(Alphabet(EncodeUnicodeCategory uc)) - // Also include any specific characters in this category - for c in GetSingleCharAlphabet() do - if System.Char.GetUnicodeCategory(c) = unicodeCategories.[uc] then - yield Inp(Alphabet(EncodeChar(c))) ]) - CompileRegexp re dest - - | Inp Any -> - let re = Alt([ for n in GetAlphabet() do yield Inp(Alphabet(n)) ]) - CompileRegexp re dest - - | Inp (NotCharSet chars) -> - let re = Alt [ // Include any characters from those in the alphabet besides those that are not immediately excluded - for c in GetSingleCharAlphabet() do - let ec = EncodeChar c - if not (chars.Contains(ec)) then - yield Inp(Alphabet(ec)) - - // Include all unicode categories - // That is, negations _only_ exclude precisely the given set of characters. You can't - // exclude whole classes of characters as yet - if !unicode then - let ucs = chars |> Set.map(DecodeChar >> System.Char.GetUnicodeCategory) - for KeyValue(nm,uc) in unicodeCategories do - //if ucs.Contains(uc) then - // do printfn "warning: the unicode category '\\%s' ('%s') is automatically excluded by this character set negation. Consider adding this to the negation." nm (uc.ToString()) - // yield! [] - //else - yield Inp(Alphabet(EncodeUnicodeCategory nm)) - ] - CompileRegexp re dest - - let actions = new System.Collections.Generic.List<_>() - - /// Compile an acceptance of a regular expression into the NFA - let sTrans macros nodeId (regexp,code) = - let actionId = actions.Count - actions.Add(code) - let sAccept = nfaNodeMap.NewNfaNode([],[(nodeId,actionId)]) - CompileRegexp regexp sAccept - - let trs = clauses |> List.mapi (fun n x -> (Epsilon,sTrans macros n x)) - let nfaStartNode = nfaNodeMap.NewNfaNode(trs,[]) - nfaStartNode,(actions |> Seq.readonly), nfaNodeMap - -// TODO: consider a better representation here. -type internal NfaNodeIdSetBuilder = HashSet - -type internal NfaNodeIdSet(nodes: NfaNodeIdSetBuilder) = - // BEWARE: the next line is performance critical - let s = nodes |> Seq.toArray |> (fun arr -> Array.sortInPlaceWith compare arr; arr) // 19 - - // These are all surprisingly slower: - //let s = nodes |> Seq.toArray |> Array.sort - //let s = nodes |> Seq.toArray |> Array.sortWith compare // 76 - //let s = nodes |> Seq.toArray |> (fun arr -> Array.sortInPlace arr; arr) // 76 - - member x.Representation = s - member x.Elements = s - member x.Fold f z = Array.fold f z s - interface System.IComparable with - member x.CompareTo(y:obj) = - let y = (y :?> NfaNodeIdSet) - let xr = x.Representation - let yr = y.Representation - let c = compare xr.Length yr.Length - if c <> 0 then c else - let n = yr.Length - let rec go i = - if i >= n then 0 else - let c = compare xr.[i] yr.[i] - if c <> 0 then c else - go (i+1) - go 0 - - override x.Equals(y:obj) = - match y with - | :? NfaNodeIdSet as y -> - let xr = x.Representation - let yr = y.Representation - let n = yr.Length - xr.Length = n && - (let rec go i = (i < n) && xr.[i] = yr.[i] && go (i+1) - go 0) - | _ -> false - - override x.GetHashCode() = hash s - - member x.IsEmpty = (s.Length = 0) - member x.Iterate f = s |> Array.iter f - -type NodeSetSet = Set - -let newDfaNodeId = - let i = ref 0 - fun () -> let res = !i in incr i; res - -let NfaToDfa (nfaNodeMap:NfaNodeMap) nfaStartNode = - let numNfaNodes = nfaNodeMap.Count - let rec EClosure1 (acc:NfaNodeIdSetBuilder) (n:NfaNode) = - if not (acc.Contains(n.Id)) then - acc.Add(n.Id) |> ignore; - if n.Transitions.ContainsKey(Epsilon) then - match n.Transitions.[Epsilon] with - | [] -> () // this Clause is an optimization - the list is normally empty - | tr -> - //printfn "n.Id = %A, #Epsilon = %d" n.Id tr.Length - tr |> List.iter (EClosure1 acc) - - let EClosure (moves:list) = - let acc = new NfaNodeIdSetBuilder(HashIdentity.Structural) - for i in moves do - EClosure1 acc nfaNodeMap.[i]; - new NfaNodeIdSet(acc) - - // Compute all the immediate one-step moves for a set of NFA states, as a dictionary - // mapping inputs to destination lists - let ComputeMoves (nset:NfaNodeIdSet) = - let moves = new MultiMap<_,_>() - nset.Iterate(fun nodeId -> - for (KeyValue(inp,dests)) in nfaNodeMap.[nodeId].Transitions do - if inp <> Epsilon then - match dests with - | [] -> () // this Clause is an optimization - the list is normally empty - | tr -> tr |> List.iter(fun dest -> AddToMultiMap moves inp dest.Id)) - moves - - let acc = new NfaNodeIdSetBuilder(HashIdentity.Structural) - EClosure1 acc nfaStartNode; - let nfaSet0 = new NfaNodeIdSet(acc) - - let dfaNodes = ref (Map.empty) - - let GetDfaNode nfaSet = - if (!dfaNodes).ContainsKey(nfaSet) then - (!dfaNodes).[nfaSet] - else - let dfaNode = - { Id= newDfaNodeId(); - Name = nfaSet.Fold (fun s nid -> nfaNodeMap.[nid].Name+"-"+s) ""; - Transitions=[]; - Accepted= nfaSet.Elements - |> Seq.map (fun nid -> nfaNodeMap.[nid].Accepted) - |> List.concat } - //Printf.printfn "id = %d" dfaNode.Id; - - dfaNodes := (!dfaNodes).Add(nfaSet,dfaNode); - dfaNode - - let workList = ref [nfaSet0] - let doneSet = ref Set.empty - - //let count = ref 0 - let rec Loop () = - match !workList with - | [] -> () - | nfaSet ::t -> - workList := t; - if (!doneSet).Contains(nfaSet) then - Loop () - else - let moves = ComputeMoves nfaSet - for (KeyValue(inp,movesForInput)) in moves do - assert (inp <> Epsilon); - let moveSet = EClosure movesForInput; - if not moveSet.IsEmpty then - //incr count - let dfaNode = GetDfaNode nfaSet - dfaNode.Transitions <- (inp, GetDfaNode moveSet) :: dfaNode.Transitions; - (* Printf.printf "%d (%s) : %s --> %d (%s)\n" dfaNode.Id dfaNode.Name (match inp with EncodeChar c -> String.make 1 c | LEof -> "eof") moveSetDfaNode.Id moveSetDfaNode.Name;*) - workList := moveSet :: !workList; - - doneSet := (!doneSet).Add(nfaSet); - - - Loop() - Loop(); - //Printf.printfn "count = %d" !count; - let ruleStartNode = GetDfaNode nfaSet0 - let ruleNodes = - (!dfaNodes) - |> Seq.map (fun kvp -> kvp.Value) - |> Seq.toList - |> List.sortBy (fun s -> s.Id) - ruleStartNode,ruleNodes - -let Compile spec = - List.foldBack - (fun (name,args,clauses) (perRuleData,dfaNodes) -> - let nfa, actions, nfaNodeMap = LexerStateToNfa (Map.ofList spec.Macros) clauses - let ruleStartNode, ruleNodes = NfaToDfa nfaNodeMap nfa - //Printf.printfn "name = %s, ruleStartNode = %O" name ruleStartNode.Id; - (ruleStartNode,actions) :: perRuleData, ruleNodes @ dfaNodes) - spec.Rules - ([],[]) - diff --git a/src/fcs-fable/src/buildtools/fslex/fslexlex.fs b/src/fcs-fable/src/buildtools/fslex/fslexlex.fs deleted file mode 100644 index b29bd10f84..0000000000 --- a/src/fcs-fable/src/buildtools/fslex/fslexlex.fs +++ /dev/null @@ -1,735 +0,0 @@ -# 1 "fslexlex.fsl" - -(* (c) Microsoft Corporation 2005-2008. *) - -module internal FsLexYacc.FsLex.Lexer - -open FsLexYacc.FsLex.AST -open FsLexYacc.FsLex.Parser -open Internal.Utilities -open Internal.Utilities.Text.Lexing -open System.Text - -let escape c = - match c with - | '\\' -> '\\' - | '\'' -> '\'' - | 'n' -> '\n' - | 't' -> '\t' - | 'b' -> '\b' - | 'r' -> '\r' - | c -> c - -let lexeme (lexbuf : LexBuffer) = new System.String(lexbuf.Lexeme) -let newline (lexbuf:LexBuffer<_>) = lexbuf.EndPos <- lexbuf.EndPos.NextLine - -let unexpected_char lexbuf = - failwith ("Unexpected character '"+(lexeme lexbuf)+"'") - -let digit d = - if d >= '0' && d <= '9' then int32 d - int32 '0' - else failwith "digit" - -let hexdigit d = - if d >= '0' && d <= '9' then digit d - else if d >= 'a' && d <= 'f' then int32 d - int32 'a' + 10 - else if d >= 'A' && d <= 'F' then int32 d - int32 'A' + 10 - else failwithf "bad hexdigit: %c" d - -let trigraph c1 c2 c3 = - char (digit c1 * 100 + digit c2 * 10 + digit c3) - -let hexgraph c1 c2 = - char (hexdigit c1 * 16 + hexdigit c2) - -let unicodegraph_short (s:string) = - if s.Length <> 4 then failwith "unicodegraph"; - char(hexdigit s.[0] * 4096 + hexdigit s.[1] * 256 + hexdigit s.[2] * 16 + hexdigit s.[3]) - -let unicodegraph_long (s:string) = - if s.Length <> 8 then failwith "unicodegraph_long"; - let high = hexdigit s.[0] * 4096 + hexdigit s.[1] * 256 + hexdigit s.[2] * 16 + hexdigit s.[3] in - let low = hexdigit s.[4] * 4096 + hexdigit s.[5] * 256 + hexdigit s.[6] * 16 + hexdigit s.[7] in - if high = 0 then None, char low - else - (* A surrogate pair - see http://www.unicode.org/unicode/uni2book/ch03.pdf, section 3.7 *) - Some (char(0xD800 + ((high * 0x10000 + low - 0x10000) / 0x400))), - char(0xDF30 + ((high * 0x10000 + low - 0x10000) % 0x400)) - - -# 60 "fslexlex.fs" -let trans : uint16[] array = - [| - (* State 0 *) - [| 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 4us; 8us; 8us; 5us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 2us; 8us; 8us; 8us; 8us; 1us; 3us; 9us; 6us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 7us; |]; - (* State 1 *) - [| 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 15us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 14us; 65535us; |]; - (* State 2 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 3 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 13us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 4 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 5 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 12us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 6 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 11us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 7 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 8 *) - [| 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 65535us; 10us; 10us; 65535us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 65535us; 10us; 10us; 10us; 10us; 65535us; 65535us; 65535us; 65535us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 65535us; |]; - (* State 9 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 10 *) - [| 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 65535us; 10us; 10us; 65535us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 65535us; 10us; 10us; 10us; 10us; 65535us; 65535us; 65535us; 65535us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 10us; 65535us; |]; - (* State 11 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 12 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 13 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 14 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 16us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 15 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 14us; 65535us; 65535us; 65535us; 65535us; 14us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 14us; 65535us; 65535us; 65535us; 65535us; 65535us; 14us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 14us; 65535us; 65535us; 65535us; 14us; 65535us; 14us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 16 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 17 *) - [| 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 22us; 20us; 24us; 24us; 21us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 22us; 24us; 19us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 24us; 18us; 24us; 24us; 24us; 24us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 22us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 24us; 23us; |]; - (* State 18 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 27us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 27us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 19 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 20 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 21 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 26us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 22 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 25us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 25us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 23 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 24 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 25 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 25us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 25us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 25us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 26 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 27 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 28 *) - [| 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 35us; 33us; 38us; 38us; 34us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 35us; 38us; 32us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 36us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 38us; 31us; 38us; 38us; 38us; 38us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 30us; 38us; 29us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 38us; 37us; |]; - (* State 29 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 30 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 31 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 43us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 43us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 32 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 33 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 34 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 42us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 35 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 41us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 41us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 36 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 39us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 37 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 38 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 39 *) - [| 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 65535us; 40us; 40us; 65535us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 65535us; |]; - (* State 40 *) - [| 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 65535us; 40us; 40us; 65535us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 40us; 65535us; |]; - (* State 41 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 41us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 41us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 41us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 42 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 43 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 44 *) - [| 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 49us; 47us; 51us; 51us; 48us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 49us; 51us; 46us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 51us; 45us; 51us; 51us; 51us; 51us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 49us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 50us; |]; - (* State 45 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 54us; 65535us; 65535us; 55us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 56us; 65535us; 65535us; 65535us; 65535us; 56us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 56us; 65535us; 65535us; 65535us; 65535us; 65535us; 56us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 56us; 65535us; 65535us; 65535us; 56us; 65535us; 56us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 46 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 47 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 48 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 53us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 49 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 52us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 52us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 50 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 51 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 52 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 52us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 52us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 52us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 53 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 54 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 55 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 54us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 56 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 57 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 58 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 59us; 59us; 59us; 59us; 59us; 59us; 59us; 59us; 59us; 59us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 59 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 60 *) - [| 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 69us; 70us; 87us; 87us; 71us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 69us; 87us; 68us; 87us; 87us; 87us; 87us; 66us; 81us; 82us; 76us; 75us; 87us; 85us; 74us; 86us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 78us; 87us; 77us; 87us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 79us; 87us; 80us; 84us; 83us; 87us; 65us; 72us; 72us; 72us; 63us; 72us; 72us; 72us; 72us; 72us; 72us; 64us; 72us; 72us; 72us; 62us; 72us; 61us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 72us; 67us; 73us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 87us; 88us; |]; - (* State 61 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 136us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 62 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 132us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 63 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 130us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 64 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 128us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 65 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 126us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 66 *) - [| 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 96us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 95us; 65535us; |]; - (* State 67 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 68 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 69 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 94us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 94us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 70 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 71 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 93us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 72 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 73 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 74 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 75 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 76 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 77 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 78 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 79 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 80 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 81 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 91us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 82 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 83 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 84 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 85 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 86 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 89us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 87 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 88 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 89 *) - [| 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 65535us; 90us; 90us; 65535us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 65535us; |]; - (* State 90 *) - [| 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 65535us; 90us; 90us; 65535us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 90us; 65535us; |]; - (* State 91 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 92 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 93 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 94 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 94us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 94us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 95 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 125us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 96 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 95us; 65535us; 65535us; 65535us; 65535us; 95us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 97us; 97us; 97us; 97us; 97us; 97us; 97us; 97us; 97us; 97us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 101us; 101us; 101us; 101us; 101us; 101us; 101us; 101us; 101us; 101us; 101us; 101us; 101us; 101us; 101us; 101us; 101us; 101us; 101us; 101us; 100us; 101us; 101us; 101us; 101us; 101us; 65535us; 95us; 65535us; 65535us; 65535us; 65535us; 65535us; 95us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 95us; 65535us; 65535us; 65535us; 95us; 65535us; 95us; 99us; 65535us; 65535us; 98us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 97 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 122us; 122us; 122us; 122us; 122us; 122us; 122us; 122us; 122us; 122us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 98 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 119us; 119us; 119us; 119us; 119us; 119us; 119us; 119us; 119us; 119us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 119us; 119us; 119us; 119us; 119us; 119us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 119us; 119us; 119us; 119us; 119us; 119us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 99 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 114us; 114us; 114us; 114us; 114us; 114us; 114us; 114us; 114us; 114us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 114us; 114us; 114us; 114us; 114us; 114us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 114us; 114us; 114us; 114us; 114us; 114us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 100 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 104us; 104us; 104us; 104us; 104us; 104us; 104us; 104us; 104us; 104us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 104us; 104us; 104us; 104us; 104us; 104us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 105us; 105us; 105us; 105us; 105us; 105us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 101 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 102us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 102 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 103us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 103 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 104 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 106us; 106us; 106us; 106us; 106us; 106us; 106us; 106us; 106us; 106us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 106us; 106us; 106us; 106us; 106us; 106us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 106us; 106us; 106us; 106us; 106us; 106us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 105 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 103us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 106us; 106us; 106us; 106us; 106us; 106us; 106us; 106us; 106us; 106us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 106us; 106us; 106us; 106us; 106us; 106us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 106us; 106us; 106us; 106us; 106us; 106us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 106 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 107us; 107us; 107us; 107us; 107us; 107us; 107us; 107us; 107us; 107us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 107us; 107us; 107us; 107us; 107us; 107us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 107us; 107us; 107us; 107us; 107us; 107us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 107 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 108us; 108us; 108us; 108us; 108us; 108us; 108us; 108us; 108us; 108us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 108us; 108us; 108us; 108us; 108us; 108us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 108us; 108us; 108us; 108us; 108us; 108us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 108 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 109us; 109us; 109us; 109us; 109us; 109us; 109us; 109us; 109us; 109us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 109us; 109us; 109us; 109us; 109us; 109us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 109us; 109us; 109us; 109us; 109us; 109us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 109 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 110us; 110us; 110us; 110us; 110us; 110us; 110us; 110us; 110us; 110us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 110us; 110us; 110us; 110us; 110us; 110us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 110us; 110us; 110us; 110us; 110us; 110us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 110 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 111us; 111us; 111us; 111us; 111us; 111us; 111us; 111us; 111us; 111us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 111us; 111us; 111us; 111us; 111us; 111us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 111us; 111us; 111us; 111us; 111us; 111us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 111 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 112us; 112us; 112us; 112us; 112us; 112us; 112us; 112us; 112us; 112us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 112us; 112us; 112us; 112us; 112us; 112us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 112us; 112us; 112us; 112us; 112us; 112us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 112 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 113us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 113 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 114 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 115us; 115us; 115us; 115us; 115us; 115us; 115us; 115us; 115us; 115us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 115us; 115us; 115us; 115us; 115us; 115us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 115us; 115us; 115us; 115us; 115us; 115us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 115 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 116us; 116us; 116us; 116us; 116us; 116us; 116us; 116us; 116us; 116us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 116us; 116us; 116us; 116us; 116us; 116us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 116us; 116us; 116us; 116us; 116us; 116us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 116 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 117us; 117us; 117us; 117us; 117us; 117us; 117us; 117us; 117us; 117us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 117us; 117us; 117us; 117us; 117us; 117us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 117us; 117us; 117us; 117us; 117us; 117us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 117 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 118us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 118 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 119 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 120us; 120us; 120us; 120us; 120us; 120us; 120us; 120us; 120us; 120us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 120us; 120us; 120us; 120us; 120us; 120us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 120us; 120us; 120us; 120us; 120us; 120us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 120 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 121us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 121 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 122 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 123us; 123us; 123us; 123us; 123us; 123us; 123us; 123us; 123us; 123us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 123 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 124us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 124 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 125 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 126 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 127us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 127 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 128 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 129us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 129 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 130 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 92us; 131us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 131 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 132 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 133us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 133 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 134us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 134 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 135us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 135 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 136 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 137us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 137 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 138us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 138 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - |] -let actions : uint16[] = [|65535us; 7us; 1us; 7us; 3us; 7us; 7us; 5us; 6us; 7us; 6us; 4us; 3us; 2us; 65535us; 65535us; 0us; 65535us; 5us; 1us; 2us; 5us; 3us; 4us; 5us; 3us; 2us; 0us; 65535us; 0us; 1us; 8us; 3us; 4us; 8us; 5us; 8us; 7us; 8us; 6us; 6us; 5us; 4us; 2us; 65535us; 7us; 3us; 4us; 7us; 5us; 6us; 7us; 5us; 4us; 0us; 65535us; 1us; 65535us; 65535us; 2us; 65535us; 15us; 15us; 15us; 15us; 15us; 31us; 11us; 12us; 13us; 14us; 31us; 15us; 16us; 17us; 18us; 19us; 20us; 21us; 22us; 23us; 24us; 25us; 26us; 27us; 28us; 31us; 31us; 32us; 30us; 30us; 29us; 15us; 14us; 13us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 10us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 9us; 65535us; 65535us; 65535us; 65535us; 8us; 65535us; 65535us; 7us; 65535us; 65535us; 6us; 5us; 15us; 4us; 15us; 3us; 15us; 2us; 15us; 15us; 15us; 1us; 15us; 15us; 0us; |] -let _fslex_tables = Internal.Utilities.Text.Lexing.UnicodeTables.Create(trans,actions) -let rec _fslex_dummy () = _fslex_dummy() -(* Rule token *) -and token (lexbuf : Internal.Utilities.Text.Lexing.LexBuffer<_>) = _fslex_token 60 lexbuf -(* Rule string *) -and string p buff (lexbuf : Internal.Utilities.Text.Lexing.LexBuffer<_>) = _fslex_string p buff 44 lexbuf -(* Rule code *) -and code p buff (lexbuf : Internal.Utilities.Text.Lexing.LexBuffer<_>) = _fslex_code p buff 28 lexbuf -(* Rule codestring *) -and codestring buff (lexbuf : Internal.Utilities.Text.Lexing.LexBuffer<_>) = _fslex_codestring buff 17 lexbuf -(* Rule comment *) -and comment p (lexbuf : Internal.Utilities.Text.Lexing.LexBuffer<_>) = _fslex_comment p 0 lexbuf -(* Rule token *) -and _fslex_token _fslex_state lexbuf = - match _fslex_tables.Interpret(_fslex_state,lexbuf) with - | 0 -> ( -# 76 "fslexlex.fsl" - RULE -# 361 "fslexlex.fs" - ) - | 1 -> ( -# 77 "fslexlex.fsl" - PARSE -# 366 "fslexlex.fs" - ) - | 2 -> ( -# 78 "fslexlex.fsl" - EOF -# 371 "fslexlex.fs" - ) - | 3 -> ( -# 79 "fslexlex.fsl" - LET -# 376 "fslexlex.fs" - ) - | 4 -> ( -# 80 "fslexlex.fsl" - AND -# 381 "fslexlex.fs" - ) - | 5 -> ( -# 82 "fslexlex.fsl" - let s = lexeme lexbuf in - CHAR (if s.[1] = '\\' then escape s.[2] else s.[1]) -# 387 "fslexlex.fs" - ) - | 6 -> ( -# 86 "fslexlex.fsl" - let s = lexeme lexbuf in - CHAR (trigraph s.[2] s.[3] s.[4]) -# 393 "fslexlex.fs" - ) - | 7 -> ( -# 90 "fslexlex.fsl" - let s = lexeme lexbuf in - CHAR (hexgraph s.[3] s.[4]) -# 399 "fslexlex.fs" - ) - | 8 -> ( -# 94 "fslexlex.fsl" - let s = lexeme lexbuf in - CHAR (unicodegraph_short s.[3..6]) -# 405 "fslexlex.fs" - ) - | 9 -> ( -# 98 "fslexlex.fsl" - let s = lexeme lexbuf in - match (unicodegraph_long s.[3..10]) with - | None, c -> CHAR(c) - | Some _ , _ -> failwith "Unicode characters needing surrogate pairs are not yet supported by this tool" -# 413 "fslexlex.fs" - ) - | 10 -> ( -# 104 "fslexlex.fsl" - let s = (lexeme lexbuf).[2..3] in - UNICODE_CATEGORY (s) -# 419 "fslexlex.fs" - ) - | 11 -> ( -# 107 "fslexlex.fsl" - let p = lexbuf.StartPos in - let buff = (new StringBuilder 100) in - // adjust the first line to get even indentation for all lines w.r.t. the left hand margin - buff.Append (String.replicate (lexbuf.StartPos.Column+1) " ") |> ignore; - code p buff lexbuf -# 428 "fslexlex.fs" - ) - | 12 -> ( -# 113 "fslexlex.fsl" - string lexbuf.StartPos (new StringBuilder 100) lexbuf -# 433 "fslexlex.fs" - ) - | 13 -> ( -# 115 "fslexlex.fsl" - token lexbuf -# 438 "fslexlex.fs" - ) - | 14 -> ( -# 116 "fslexlex.fsl" - newline lexbuf; token lexbuf -# 443 "fslexlex.fs" - ) - | 15 -> ( -# 117 "fslexlex.fsl" - IDENT (lexeme lexbuf) -# 448 "fslexlex.fs" - ) - | 16 -> ( -# 118 "fslexlex.fsl" - BAR -# 453 "fslexlex.fs" - ) - | 17 -> ( -# 119 "fslexlex.fsl" - DOT -# 458 "fslexlex.fs" - ) - | 18 -> ( -# 120 "fslexlex.fsl" - PLUS -# 463 "fslexlex.fs" - ) - | 19 -> ( -# 121 "fslexlex.fsl" - STAR -# 468 "fslexlex.fs" - ) - | 20 -> ( -# 122 "fslexlex.fsl" - QMARK -# 473 "fslexlex.fs" - ) - | 21 -> ( -# 123 "fslexlex.fsl" - EQUALS -# 478 "fslexlex.fs" - ) - | 22 -> ( -# 124 "fslexlex.fsl" - LBRACK -# 483 "fslexlex.fs" - ) - | 23 -> ( -# 125 "fslexlex.fsl" - RBRACK -# 488 "fslexlex.fs" - ) - | 24 -> ( -# 126 "fslexlex.fsl" - LPAREN -# 493 "fslexlex.fs" - ) - | 25 -> ( -# 127 "fslexlex.fsl" - RPAREN -# 498 "fslexlex.fs" - ) - | 26 -> ( -# 128 "fslexlex.fsl" - UNDERSCORE -# 503 "fslexlex.fs" - ) - | 27 -> ( -# 129 "fslexlex.fsl" - HAT -# 508 "fslexlex.fs" - ) - | 28 -> ( -# 130 "fslexlex.fsl" - DASH -# 513 "fslexlex.fs" - ) - | 29 -> ( -# 131 "fslexlex.fsl" - ignore(comment lexbuf.StartPos lexbuf); token lexbuf -# 518 "fslexlex.fs" - ) - | 30 -> ( -# 132 "fslexlex.fsl" - token lexbuf -# 523 "fslexlex.fs" - ) - | 31 -> ( -# 133 "fslexlex.fsl" - unexpected_char lexbuf -# 528 "fslexlex.fs" - ) - | 32 -> ( -# 134 "fslexlex.fsl" - EOF -# 533 "fslexlex.fs" - ) - | _ -> failwith "token" -(* Rule string *) -and _fslex_string p buff _fslex_state lexbuf = - match _fslex_tables.Interpret(_fslex_state,lexbuf) with - | 0 -> ( -# 136 "fslexlex.fsl" - newline lexbuf; string p buff lexbuf -# 542 "fslexlex.fs" - ) - | 1 -> ( -# 138 "fslexlex.fsl" - let _ = buff.Append (escape (lexeme lexbuf).[1]) in - string p buff lexbuf -# 548 "fslexlex.fs" - ) - | 2 -> ( -# 141 "fslexlex.fsl" - let s = lexeme lexbuf in - let _ = buff.Append (trigraph s.[1] s.[2] s.[3]) in - string p buff lexbuf -# 555 "fslexlex.fs" - ) - | 3 -> ( -# 144 "fslexlex.fsl" - STRING (buff.ToString()) -# 560 "fslexlex.fs" - ) - | 4 -> ( -# 145 "fslexlex.fsl" - newline lexbuf; - let _ = buff.Append System.Environment.NewLine in - string p buff lexbuf -# 567 "fslexlex.fs" - ) - | 5 -> ( -# 149 "fslexlex.fsl" - let _ = buff.Append (lexeme lexbuf) in - string p buff lexbuf -# 573 "fslexlex.fs" - ) - | 6 -> ( -# 151 "fslexlex.fsl" - failwith (Printf.sprintf "end of file in string started at (%d,%d)" p.pos_lnum (p.pos_cnum - p.pos_bol)) -# 578 "fslexlex.fs" - ) - | 7 -> ( -# 152 "fslexlex.fsl" - let _ = buff.Append (lexeme lexbuf).[0] in - string p buff lexbuf -# 584 "fslexlex.fs" - ) - | _ -> failwith "string" -(* Rule code *) -and _fslex_code p buff _fslex_state lexbuf = - match _fslex_tables.Interpret(_fslex_state,lexbuf) with - | 0 -> ( -# 155 "fslexlex.fsl" - CODE (buff.ToString(), p) -# 593 "fslexlex.fs" - ) - | 1 -> ( -# 156 "fslexlex.fsl" - let _ = buff.Append (lexeme lexbuf) in - ignore(code p buff lexbuf); - let _ = buff.Append "}" in - code p buff lexbuf -# 601 "fslexlex.fs" - ) - | 2 -> ( -# 161 "fslexlex.fsl" - let _ = buff.Append (lexeme lexbuf) in - code p buff lexbuf -# 607 "fslexlex.fs" - ) - | 3 -> ( -# 163 "fslexlex.fsl" - let _ = buff.Append (lexeme lexbuf) in - ignore(codestring buff lexbuf); - code p buff lexbuf -# 614 "fslexlex.fs" - ) - | 4 -> ( -# 166 "fslexlex.fsl" - newline lexbuf; - let _ = buff.Append System.Environment.NewLine in - code p buff lexbuf -# 621 "fslexlex.fs" - ) - | 5 -> ( -# 170 "fslexlex.fsl" - let _ = buff.Append (lexeme lexbuf) in - code p buff lexbuf -# 627 "fslexlex.fs" - ) - | 6 -> ( -# 173 "fslexlex.fsl" - let _ = buff.Append (lexeme lexbuf) in - code p buff lexbuf -# 633 "fslexlex.fs" - ) - | 7 -> ( -# 175 "fslexlex.fsl" - EOF -# 638 "fslexlex.fs" - ) - | 8 -> ( -# 176 "fslexlex.fsl" - let _ = buff.Append (lexeme lexbuf).[0] in - code p buff lexbuf -# 644 "fslexlex.fs" - ) - | _ -> failwith "code" -(* Rule codestring *) -and _fslex_codestring buff _fslex_state lexbuf = - match _fslex_tables.Interpret(_fslex_state,lexbuf) with - | 0 -> ( -# 181 "fslexlex.fsl" - let _ = buff.Append (lexeme lexbuf) in - codestring buff lexbuf -# 654 "fslexlex.fs" - ) - | 1 -> ( -# 183 "fslexlex.fsl" - let _ = buff.Append (lexeme lexbuf) in - buff.ToString() -# 660 "fslexlex.fs" - ) - | 2 -> ( -# 185 "fslexlex.fsl" - newline lexbuf; - let _ = buff.Append System.Environment.NewLine in - codestring buff lexbuf -# 667 "fslexlex.fs" - ) - | 3 -> ( -# 189 "fslexlex.fsl" - let _ = buff.Append (lexeme lexbuf) in - codestring buff lexbuf -# 673 "fslexlex.fs" - ) - | 4 -> ( -# 191 "fslexlex.fsl" - failwith "unterminated string in code" -# 678 "fslexlex.fs" - ) - | 5 -> ( -# 192 "fslexlex.fsl" - let _ = buff.Append (lexeme lexbuf).[0] in - codestring buff lexbuf -# 684 "fslexlex.fs" - ) - | _ -> failwith "codestring" -(* Rule comment *) -and _fslex_comment p _fslex_state lexbuf = - match _fslex_tables.Interpret(_fslex_state,lexbuf) with - | 0 -> ( -# 196 "fslexlex.fsl" - comment p lexbuf -# 693 "fslexlex.fs" - ) - | 1 -> ( -# 197 "fslexlex.fsl" - ignore(try string lexbuf.StartPos (new StringBuilder 100) lexbuf - with Failure s -> failwith (s + "\n" + Printf.sprintf "error while processing string nested in comment started at (%d,%d)" p.pos_lnum (p.pos_cnum - p.pos_bol))); - comment p lexbuf -# 700 "fslexlex.fs" - ) - | 2 -> ( -# 200 "fslexlex.fsl" - ignore(try comment p lexbuf with Failure s -> failwith (s + "\n" + Printf.sprintf "error while processing nested comment started at (%d,%d)" p.pos_lnum (p.pos_cnum - p.pos_bol))); - comment p lexbuf -# 706 "fslexlex.fs" - ) - | 3 -> ( -# 202 "fslexlex.fsl" - newline lexbuf; comment p lexbuf -# 711 "fslexlex.fs" - ) - | 4 -> ( -# 203 "fslexlex.fsl" - () -# 716 "fslexlex.fs" - ) - | 5 -> ( -# 204 "fslexlex.fsl" - failwith (Printf.sprintf "end of file in comment started at (%d,%d)" p.pos_lnum (p.pos_cnum - p.pos_bol)) -# 721 "fslexlex.fs" - ) - | 6 -> ( -# 205 "fslexlex.fsl" - comment p lexbuf -# 726 "fslexlex.fs" - ) - | 7 -> ( -# 206 "fslexlex.fsl" - comment p lexbuf -# 731 "fslexlex.fs" - ) - | _ -> failwith "comment" - -# 3000000 "fslexlex.fs" diff --git a/src/fcs-fable/src/buildtools/fslex/fslexpars.fs b/src/fcs-fable/src/buildtools/fslex/fslexpars.fs deleted file mode 100644 index 87268dcb7f..0000000000 --- a/src/fcs-fable/src/buildtools/fslex/fslexpars.fs +++ /dev/null @@ -1,651 +0,0 @@ -// Implementation file for parser generated by fsyacc -module internal FsLexYacc.FsLex.Parser -#nowarn "64";; // turn off warnings that type variables used in production annotations are instantiated to concrete type -open Internal.Utilities.Text.Lexing -open Internal.Utilities.Text.Parsing.ParseHelpers -# 1 "fslexpars.fsy" - -(* (c) Microsoft Corporation 2005-2008. *) - -open FsLexYacc.FsLex -open FsLexYacc.FsLex.AST - - -# 14 "fslexpars.fs" -// This type is the type of tokens accepted by the parser -type token = - | EOF - | BAR - | DOT - | PLUS - | STAR - | QMARK - | EQUALS - | UNDERSCORE - | LBRACK - | RBRACK - | HAT - | DASH - | RULE - | PARSE - | LET - | AND - | LPAREN - | RPAREN - | UNICODE_CATEGORY of (string) - | CHAR of (char) - | CODE of (AST.Code) - | STRING of (string) - | IDENT of (string) -// This type is used to give symbolic names to token indexes, useful for error messages -type tokenId = - | TOKEN_EOF - | TOKEN_BAR - | TOKEN_DOT - | TOKEN_PLUS - | TOKEN_STAR - | TOKEN_QMARK - | TOKEN_EQUALS - | TOKEN_UNDERSCORE - | TOKEN_LBRACK - | TOKEN_RBRACK - | TOKEN_HAT - | TOKEN_DASH - | TOKEN_RULE - | TOKEN_PARSE - | TOKEN_LET - | TOKEN_AND - | TOKEN_LPAREN - | TOKEN_RPAREN - | TOKEN_UNICODE_CATEGORY - | TOKEN_CHAR - | TOKEN_CODE - | TOKEN_STRING - | TOKEN_IDENT - | TOKEN_end_of_input - | TOKEN_error -// This type is used to give symbolic names to token indexes, useful for error messages -type nonTerminalId = - | NONTERM__startspec - | NONTERM_spec - | NONTERM_codeopt - | NONTERM_Macros - | NONTERM_macro - | NONTERM_Rules - | NONTERM_rule - | NONTERM_args - | NONTERM_optbar - | NONTERM_clauses - | NONTERM_clause - | NONTERM_regexp - | NONTERM_charset - -// This function maps tokens to integer indexes -let tagOfToken (t:token) = - match t with - | EOF -> 0 - | BAR -> 1 - | DOT -> 2 - | PLUS -> 3 - | STAR -> 4 - | QMARK -> 5 - | EQUALS -> 6 - | UNDERSCORE -> 7 - | LBRACK -> 8 - | RBRACK -> 9 - | HAT -> 10 - | DASH -> 11 - | RULE -> 12 - | PARSE -> 13 - | LET -> 14 - | AND -> 15 - | LPAREN -> 16 - | RPAREN -> 17 - | UNICODE_CATEGORY _ -> 18 - | CHAR _ -> 19 - | CODE _ -> 20 - | STRING _ -> 21 - | IDENT _ -> 22 - -// This function maps integer indexes to symbolic token ids -let tokenTagToTokenId (tokenIdx:int) = - match tokenIdx with - | 0 -> TOKEN_EOF - | 1 -> TOKEN_BAR - | 2 -> TOKEN_DOT - | 3 -> TOKEN_PLUS - | 4 -> TOKEN_STAR - | 5 -> TOKEN_QMARK - | 6 -> TOKEN_EQUALS - | 7 -> TOKEN_UNDERSCORE - | 8 -> TOKEN_LBRACK - | 9 -> TOKEN_RBRACK - | 10 -> TOKEN_HAT - | 11 -> TOKEN_DASH - | 12 -> TOKEN_RULE - | 13 -> TOKEN_PARSE - | 14 -> TOKEN_LET - | 15 -> TOKEN_AND - | 16 -> TOKEN_LPAREN - | 17 -> TOKEN_RPAREN - | 18 -> TOKEN_UNICODE_CATEGORY - | 19 -> TOKEN_CHAR - | 20 -> TOKEN_CODE - | 21 -> TOKEN_STRING - | 22 -> TOKEN_IDENT - | 25 -> TOKEN_end_of_input - | 23 -> TOKEN_error - | _ -> failwith "tokenTagToTokenId: bad token" - -/// This function maps production indexes returned in syntax errors to strings representing the non terminal that would be produced by that production -let prodIdxToNonTerminal (prodIdx:int) = - match prodIdx with - | 0 -> NONTERM__startspec - | 1 -> NONTERM_spec - | 2 -> NONTERM_codeopt - | 3 -> NONTERM_codeopt - | 4 -> NONTERM_Macros - | 5 -> NONTERM_Macros - | 6 -> NONTERM_macro - | 7 -> NONTERM_Rules - | 8 -> NONTERM_Rules - | 9 -> NONTERM_rule - | 10 -> NONTERM_args - | 11 -> NONTERM_args - | 12 -> NONTERM_optbar - | 13 -> NONTERM_optbar - | 14 -> NONTERM_clauses - | 15 -> NONTERM_clauses - | 16 -> NONTERM_clause - | 17 -> NONTERM_regexp - | 18 -> NONTERM_regexp - | 19 -> NONTERM_regexp - | 20 -> NONTERM_regexp - | 21 -> NONTERM_regexp - | 22 -> NONTERM_regexp - | 23 -> NONTERM_regexp - | 24 -> NONTERM_regexp - | 25 -> NONTERM_regexp - | 26 -> NONTERM_regexp - | 27 -> NONTERM_regexp - | 28 -> NONTERM_regexp - | 29 -> NONTERM_regexp - | 30 -> NONTERM_regexp - | 31 -> NONTERM_charset - | 32 -> NONTERM_charset - | 33 -> NONTERM_charset - | _ -> failwith "prodIdxToNonTerminal: bad production index" - -let _fsyacc_endOfInputTag = 25 -let _fsyacc_tagOfErrorTerminal = 23 - -// This function gets the name of a token as a string -let token_to_string (t:token) = - match t with - | EOF -> "EOF" - | BAR -> "BAR" - | DOT -> "DOT" - | PLUS -> "PLUS" - | STAR -> "STAR" - | QMARK -> "QMARK" - | EQUALS -> "EQUALS" - | UNDERSCORE -> "UNDERSCORE" - | LBRACK -> "LBRACK" - | RBRACK -> "RBRACK" - | HAT -> "HAT" - | DASH -> "DASH" - | RULE -> "RULE" - | PARSE -> "PARSE" - | LET -> "LET" - | AND -> "AND" - | LPAREN -> "LPAREN" - | RPAREN -> "RPAREN" - | UNICODE_CATEGORY _ -> "UNICODE_CATEGORY" - | CHAR _ -> "CHAR" - | CODE _ -> "CODE" - | STRING _ -> "STRING" - | IDENT _ -> "IDENT" - -// This function gets the data carried by a token as an object -let _fsyacc_dataOfToken (t:token) = - match t with - | EOF -> (null : System.Object) - | BAR -> (null : System.Object) - | DOT -> (null : System.Object) - | PLUS -> (null : System.Object) - | STAR -> (null : System.Object) - | QMARK -> (null : System.Object) - | EQUALS -> (null : System.Object) - | UNDERSCORE -> (null : System.Object) - | LBRACK -> (null : System.Object) - | RBRACK -> (null : System.Object) - | HAT -> (null : System.Object) - | DASH -> (null : System.Object) - | RULE -> (null : System.Object) - | PARSE -> (null : System.Object) - | LET -> (null : System.Object) - | AND -> (null : System.Object) - | LPAREN -> (null : System.Object) - | RPAREN -> (null : System.Object) - | UNICODE_CATEGORY _fsyacc_x -> Microsoft.FSharp.Core.Operators.box _fsyacc_x - | CHAR _fsyacc_x -> Microsoft.FSharp.Core.Operators.box _fsyacc_x - | CODE _fsyacc_x -> Microsoft.FSharp.Core.Operators.box _fsyacc_x - | STRING _fsyacc_x -> Microsoft.FSharp.Core.Operators.box _fsyacc_x - | IDENT _fsyacc_x -> Microsoft.FSharp.Core.Operators.box _fsyacc_x -let _fsyacc_gotos = [| 0us; 65535us; 1us; 65535us; 0us; 1us; 2us; 65535us; 0us; 2us; 5us; 6us; 2us; 65535us; 2us; 3us; 8us; 9us; 2us; 65535us; 2us; 8us; 8us; 8us; 2us; 65535us; 4us; 5us; 15us; 16us; 2us; 65535us; 4us; 14us; 15us; 14us; 2us; 65535us; 17us; 18us; 23us; 24us; 1us; 65535us; 20us; 21us; 2us; 65535us; 21us; 22us; 27us; 28us; 2us; 65535us; 21us; 26us; 27us; 26us; 10us; 65535us; 12us; 13us; 13us; 37us; 21us; 29us; 27us; 29us; 29us; 37us; 37us; 37us; 38us; 37us; 39us; 37us; 43us; 38us; 44us; 39us; 5us; 65535us; 46us; 47us; 47us; 55us; 49us; 50us; 50us; 55us; 55us; 55us; |] -let _fsyacc_sparseGotoTableRowOffsets = [|0us; 1us; 3us; 6us; 9us; 12us; 15us; 18us; 21us; 23us; 26us; 29us; 40us; |] -let _fsyacc_stateToProdIdxsTableElements = [| 1us; 0us; 1us; 0us; 1us; 1us; 1us; 1us; 1us; 1us; 1us; 1us; 1us; 1us; 1us; 2us; 1us; 5us; 1us; 5us; 1us; 6us; 1us; 6us; 1us; 6us; 6us; 6us; 23us; 24us; 25us; 26us; 27us; 2us; 7us; 8us; 1us; 7us; 1us; 7us; 1us; 9us; 1us; 9us; 1us; 9us; 1us; 9us; 1us; 9us; 1us; 9us; 1us; 11us; 1us; 11us; 1us; 13us; 2us; 14us; 15us; 1us; 14us; 1us; 14us; 6us; 16us; 23us; 24us; 25us; 26us; 27us; 1us; 16us; 1us; 17us; 1us; 18us; 1us; 19us; 1us; 20us; 1us; 21us; 1us; 22us; 6us; 23us; 23us; 24us; 25us; 26us; 27us; 6us; 23us; 24us; 25us; 26us; 27us; 27us; 6us; 23us; 24us; 25us; 26us; 27us; 28us; 1us; 24us; 1us; 25us; 1us; 26us; 1us; 27us; 1us; 28us; 1us; 28us; 2us; 29us; 30us; 2us; 29us; 33us; 1us; 29us; 1us; 30us; 2us; 30us; 33us; 1us; 30us; 2us; 31us; 32us; 1us; 32us; 1us; 32us; 2us; 33us; 33us; |] -let _fsyacc_stateToProdIdxsTableRowOffsets = [|0us; 2us; 4us; 6us; 8us; 10us; 12us; 14us; 16us; 18us; 20us; 22us; 24us; 26us; 33us; 36us; 38us; 40us; 42us; 44us; 46us; 48us; 50us; 52us; 54us; 56us; 58us; 61us; 63us; 65us; 72us; 74us; 76us; 78us; 80us; 82us; 84us; 86us; 93us; 100us; 107us; 109us; 111us; 113us; 115us; 117us; 119us; 122us; 125us; 127us; 129us; 132us; 134us; 137us; 139us; 141us; |] -let _fsyacc_action_rows = 56 -let _fsyacc_actionTableElements = [|1us; 16387us; 20us; 7us; 0us; 49152us; 1us; 16388us; 14us; 10us; 1us; 32768us; 12us; 4us; 1us; 32768us; 22us; 17us; 1us; 16387us; 20us; 7us; 0us; 16385us; 0us; 16386us; 1us; 16388us; 14us; 10us; 0us; 16389us; 1us; 32768us; 22us; 11us; 1us; 32768us; 6us; 12us; 8us; 32768us; 0us; 33us; 7us; 34us; 8us; 46us; 16us; 44us; 18us; 32us; 19us; 31us; 21us; 35us; 22us; 36us; 12us; 16390us; 0us; 33us; 1us; 43us; 3us; 40us; 4us; 41us; 5us; 42us; 7us; 34us; 8us; 46us; 16us; 44us; 18us; 32us; 19us; 31us; 21us; 35us; 22us; 36us; 1us; 16392us; 15us; 15us; 1us; 32768us; 22us; 17us; 0us; 16391us; 1us; 16394us; 22us; 23us; 1us; 32768us; 6us; 19us; 1us; 32768us; 13us; 20us; 1us; 16396us; 1us; 25us; 8us; 32768us; 0us; 33us; 7us; 34us; 8us; 46us; 16us; 44us; 18us; 32us; 19us; 31us; 21us; 35us; 22us; 36us; 0us; 16393us; 1us; 16394us; 22us; 23us; 0us; 16395us; 0us; 16397us; 1us; 16399us; 1us; 27us; 8us; 32768us; 0us; 33us; 7us; 34us; 8us; 46us; 16us; 44us; 18us; 32us; 19us; 31us; 21us; 35us; 22us; 36us; 0us; 16398us; 13us; 32768us; 0us; 33us; 1us; 43us; 3us; 40us; 4us; 41us; 5us; 42us; 7us; 34us; 8us; 46us; 16us; 44us; 18us; 32us; 19us; 31us; 20us; 30us; 21us; 35us; 22us; 36us; 0us; 16400us; 0us; 16401us; 0us; 16402us; 0us; 16403us; 0us; 16404us; 0us; 16405us; 0us; 16406us; 11us; 16407us; 0us; 33us; 3us; 40us; 4us; 41us; 5us; 42us; 7us; 34us; 8us; 46us; 16us; 44us; 18us; 32us; 19us; 31us; 21us; 35us; 22us; 36us; 11us; 16411us; 0us; 33us; 3us; 40us; 4us; 41us; 5us; 42us; 7us; 34us; 8us; 46us; 16us; 44us; 18us; 32us; 19us; 31us; 21us; 35us; 22us; 36us; 13us; 32768us; 0us; 33us; 1us; 43us; 3us; 40us; 4us; 41us; 5us; 42us; 7us; 34us; 8us; 46us; 16us; 44us; 17us; 45us; 18us; 32us; 19us; 31us; 21us; 35us; 22us; 36us; 0us; 16408us; 0us; 16409us; 0us; 16410us; 8us; 32768us; 0us; 33us; 7us; 34us; 8us; 46us; 16us; 44us; 18us; 32us; 19us; 31us; 21us; 35us; 22us; 36us; 8us; 32768us; 0us; 33us; 7us; 34us; 8us; 46us; 16us; 44us; 18us; 32us; 19us; 31us; 21us; 35us; 22us; 36us; 0us; 16412us; 2us; 32768us; 10us; 49us; 19us; 52us; 2us; 32768us; 9us; 48us; 19us; 52us; 0us; 16413us; 1us; 32768us; 19us; 52us; 2us; 32768us; 9us; 51us; 19us; 52us; 0us; 16414us; 1us; 16415us; 11us; 53us; 1us; 32768us; 19us; 54us; 0us; 16416us; 1us; 16417us; 19us; 52us; |] -let _fsyacc_actionTableRowOffsets = [|0us; 2us; 3us; 5us; 7us; 9us; 11us; 12us; 13us; 15us; 16us; 18us; 20us; 29us; 42us; 44us; 46us; 47us; 49us; 51us; 53us; 55us; 64us; 65us; 67us; 68us; 69us; 71us; 80us; 81us; 95us; 96us; 97us; 98us; 99us; 100us; 101us; 102us; 114us; 126us; 140us; 141us; 142us; 143us; 152us; 161us; 162us; 165us; 168us; 169us; 171us; 174us; 175us; 177us; 179us; 180us; |] -let _fsyacc_reductionSymbolCounts = [|1us; 5us; 1us; 0us; 0us; 2us; 4us; 3us; 1us; 6us; 0us; 2us; 0us; 1us; 3us; 1us; 2us; 1us; 1us; 1us; 1us; 1us; 1us; 2us; 2us; 2us; 2us; 3us; 3us; 3us; 4us; 1us; 3us; 2us; |] -let _fsyacc_productionToNonTerminalTable = [|0us; 1us; 2us; 2us; 3us; 3us; 4us; 5us; 5us; 6us; 7us; 7us; 8us; 8us; 9us; 9us; 10us; 11us; 11us; 11us; 11us; 11us; 11us; 11us; 11us; 11us; 11us; 11us; 11us; 11us; 11us; 12us; 12us; 12us; |] -let _fsyacc_immediateActions = [|65535us; 49152us; 65535us; 65535us; 65535us; 65535us; 16385us; 16386us; 65535us; 16389us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 16391us; 65535us; 65535us; 65535us; 65535us; 65535us; 16393us; 65535us; 16395us; 16397us; 65535us; 65535us; 16398us; 65535us; 16400us; 16401us; 16402us; 16403us; 16404us; 16405us; 16406us; 65535us; 65535us; 65535us; 16408us; 16409us; 16410us; 65535us; 65535us; 16412us; 65535us; 65535us; 16413us; 65535us; 65535us; 16414us; 65535us; 65535us; 16416us; 65535us; |] -let _fsyacc_reductions () = [| -# 246 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : AST.Spec)) in - Microsoft.FSharp.Core.Operators.box - ( - ( - raise (Internal.Utilities.Text.Parsing.Accept(Microsoft.FSharp.Core.Operators.box _1)) - ) - : '_startspec)); -# 255 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'codeopt)) in - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'Macros)) in - let _4 = (let data = parseState.GetInput(4) in (Microsoft.FSharp.Core.Operators.unbox data : 'Rules)) in - let _5 = (let data = parseState.GetInput(5) in (Microsoft.FSharp.Core.Operators.unbox data : 'codeopt)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 24 "fslexpars.fsy" - { TopCode=_1;Macros=_2;Rules=_4;BottomCode=_5 } - ) -# 24 "fslexpars.fsy" - : AST.Spec)); -# 269 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : AST.Code)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 25 "fslexpars.fsy" - _1 - ) -# 25 "fslexpars.fsy" - : 'codeopt)); -# 280 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 25 "fslexpars.fsy" - "", (parseState.ResultRange |> fst) - ) -# 25 "fslexpars.fsy" - : 'codeopt)); -# 290 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 26 "fslexpars.fsy" - [] - ) -# 26 "fslexpars.fsy" - : 'Macros)); -# 300 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'macro)) in - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'Macros)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 26 "fslexpars.fsy" - _1 :: _2 - ) -# 26 "fslexpars.fsy" - : 'Macros)); -# 312 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : string)) in - let _4 = (let data = parseState.GetInput(4) in (Microsoft.FSharp.Core.Operators.unbox data : 'regexp)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 27 "fslexpars.fsy" - (_2, _4) - ) -# 27 "fslexpars.fsy" - : 'macro)); -# 324 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'rule)) in - let _3 = (let data = parseState.GetInput(3) in (Microsoft.FSharp.Core.Operators.unbox data : 'Rules)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 28 "fslexpars.fsy" - _1 :: _3 - ) -# 28 "fslexpars.fsy" - : 'Rules)); -# 336 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'rule)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 28 "fslexpars.fsy" - [_1] - ) -# 28 "fslexpars.fsy" - : 'Rules)); -# 347 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : string)) in - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'args)) in - let _5 = (let data = parseState.GetInput(5) in (Microsoft.FSharp.Core.Operators.unbox data : 'optbar)) in - let _6 = (let data = parseState.GetInput(6) in (Microsoft.FSharp.Core.Operators.unbox data : 'clauses)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 29 "fslexpars.fsy" - (_1,_2,_6) - ) -# 29 "fslexpars.fsy" - : 'rule)); -# 361 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 30 "fslexpars.fsy" - [] - ) -# 30 "fslexpars.fsy" - : 'args)); -# 371 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : string)) in - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'args)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 30 "fslexpars.fsy" - _1 :: _2 - ) -# 30 "fslexpars.fsy" - : 'args)); -# 383 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 31 "fslexpars.fsy" - - ) -# 31 "fslexpars.fsy" - : 'optbar)); -# 393 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 31 "fslexpars.fsy" - - ) -# 31 "fslexpars.fsy" - : 'optbar)); -# 403 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'clause)) in - let _3 = (let data = parseState.GetInput(3) in (Microsoft.FSharp.Core.Operators.unbox data : 'clauses)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 32 "fslexpars.fsy" - _1 :: _3 - ) -# 32 "fslexpars.fsy" - : 'clauses)); -# 415 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'clause)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 32 "fslexpars.fsy" - [_1] - ) -# 32 "fslexpars.fsy" - : 'clauses)); -# 426 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'regexp)) in - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : AST.Code)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 33 "fslexpars.fsy" - _1, _2 - ) -# 33 "fslexpars.fsy" - : 'clause)); -# 438 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : char)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 35 "fslexpars.fsy" - Inp(Alphabet(EncodeChar _1)) - ) -# 35 "fslexpars.fsy" - : 'regexp)); -# 449 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : string)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 36 "fslexpars.fsy" - Inp(UnicodeCategory _1) - ) -# 36 "fslexpars.fsy" - : 'regexp)); -# 460 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 37 "fslexpars.fsy" - Inp(Alphabet(Eof)) - ) -# 37 "fslexpars.fsy" - : 'regexp)); -# 470 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 38 "fslexpars.fsy" - Inp Any - ) -# 38 "fslexpars.fsy" - : 'regexp)); -# 480 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : string)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 39 "fslexpars.fsy" - Seq([ for n in 0 .. _1.Length - 1 -> Inp(Alphabet(EncodeChar _1.[n]))]) - ) -# 39 "fslexpars.fsy" - : 'regexp)); -# 491 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : string)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 40 "fslexpars.fsy" - Macro(_1) - ) -# 40 "fslexpars.fsy" - : 'regexp)); -# 502 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'regexp)) in - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'regexp)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 41 "fslexpars.fsy" - Seq[_1;_2] - ) -# 41 "fslexpars.fsy" - : 'regexp)); -# 514 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'regexp)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 42 "fslexpars.fsy" - Seq[_1;Star _1] - ) -# 42 "fslexpars.fsy" - : 'regexp)); -# 525 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'regexp)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 43 "fslexpars.fsy" - Star _1 - ) -# 43 "fslexpars.fsy" - : 'regexp)); -# 536 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'regexp)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 44 "fslexpars.fsy" - Alt[Seq[];_1] - ) -# 44 "fslexpars.fsy" - : 'regexp)); -# 547 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'regexp)) in - let _3 = (let data = parseState.GetInput(3) in (Microsoft.FSharp.Core.Operators.unbox data : 'regexp)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 45 "fslexpars.fsy" - Alt[_1;_3] - ) -# 45 "fslexpars.fsy" - : 'regexp)); -# 559 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'regexp)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 46 "fslexpars.fsy" - _2 - ) -# 46 "fslexpars.fsy" - : 'regexp)); -# 570 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'charset)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 47 "fslexpars.fsy" - Alt [ for c in _2 -> Inp(Alphabet(c)) ] - ) -# 47 "fslexpars.fsy" - : 'regexp)); -# 581 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _3 = (let data = parseState.GetInput(3) in (Microsoft.FSharp.Core.Operators.unbox data : 'charset)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 48 "fslexpars.fsy" - Inp(NotCharSet(_3)) - ) -# 48 "fslexpars.fsy" - : 'regexp)); -# 592 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : char)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 51 "fslexpars.fsy" - Set.singleton(EncodeChar _1) - ) -# 51 "fslexpars.fsy" - : 'charset)); -# 603 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : char)) in - let _3 = (let data = parseState.GetInput(3) in (Microsoft.FSharp.Core.Operators.unbox data : char)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 52 "fslexpars.fsy" - Set.ofSeq [ for c in _1 .. _3 -> EncodeChar c ] - ) -# 52 "fslexpars.fsy" - : 'charset)); -# 615 "fslexpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'charset)) in - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'charset)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 53 "fslexpars.fsy" - Set.union _1 _2 - ) -# 53 "fslexpars.fsy" - : 'charset)); -|] -# 628 "fslexpars.fs" -let tables () : Internal.Utilities.Text.Parsing.Tables<_> = - { reductions= _fsyacc_reductions (); - endOfInputTag = _fsyacc_endOfInputTag; - tagOfToken = tagOfToken; - dataOfToken = _fsyacc_dataOfToken; - actionTableElements = _fsyacc_actionTableElements; - actionTableRowOffsets = _fsyacc_actionTableRowOffsets; - stateToProdIdxsTableElements = _fsyacc_stateToProdIdxsTableElements; - stateToProdIdxsTableRowOffsets = _fsyacc_stateToProdIdxsTableRowOffsets; - reductionSymbolCounts = _fsyacc_reductionSymbolCounts; - immediateActions = _fsyacc_immediateActions; - gotos = _fsyacc_gotos; - sparseGotoTableRowOffsets = _fsyacc_sparseGotoTableRowOffsets; - tagOfErrorTerminal = _fsyacc_tagOfErrorTerminal; - parseError = (fun (ctxt:Internal.Utilities.Text.Parsing.ParseErrorContext<_>) -> - match parse_error_rich with - | Some f -> f ctxt - | None -> parse_error ctxt.Message); - numTerminals = 26; - productionToNonTerminalTable = _fsyacc_productionToNonTerminalTable } -let engine lexer lexbuf startState = (tables ()).Interpret(lexer, lexbuf, startState) -let spec lexer lexbuf : AST.Spec = - Microsoft.FSharp.Core.Operators.unbox ((tables ()).Interpret(lexer, lexbuf, 0)) diff --git a/src/fcs-fable/src/buildtools/fsyacc/App.config b/src/fcs-fable/src/buildtools/fsyacc/App.config deleted file mode 100644 index e1b09eda9f..0000000000 --- a/src/fcs-fable/src/buildtools/fsyacc/App.config +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/buildtools/fsyacc/Arg.fs b/src/fcs-fable/src/buildtools/fsyacc/Arg.fs deleted file mode 100644 index a1f63bd963..0000000000 --- a/src/fcs-fable/src/buildtools/fsyacc/Arg.fs +++ /dev/null @@ -1,133 +0,0 @@ -// (c) Microsoft Corporation 2005-2009. - -#if INTERNALIZED_FSLEXYACC_RUNTIME -namespace Internal.Utilities -#else -namespace Microsoft.FSharp.Text -#endif - - -type ArgType = - | ClearArg of bool ref - | FloatArg of (float -> unit) - | IntArg of (int -> unit) - | RestArg of (string -> unit) - | SetArg of bool ref - | StringArg of (string -> unit) - | UnitArg of (unit -> unit) - static member Clear r = ClearArg r - static member Float r = FloatArg r - static member Int r = IntArg r - static member Rest r = RestArg r - static member Set r = SetArg r - static member String r = StringArg r - static member Unit r = UnitArg r - - -type ArgInfo (name,action,help) = - member x.Name = name - member x.ArgType = action - member x.HelpText = help - -exception Bad of string -exception HelpText of string - -[] -type ArgParser() = - static let getUsage specs u = - let sbuf = new System.Text.StringBuilder 100 - let pstring (s:string) = sbuf.Append s |> ignore - let pendline s = pstring s; pstring "\n" - pendline u; - List.iter (fun (arg:ArgInfo) -> - match arg.Name, arg.ArgType, arg.HelpText with - | (s, (UnitArg _ | SetArg _ | ClearArg _), helpText) -> pstring "\t"; pstring s; pstring ": "; pendline helpText - | (s, StringArg _, helpText) -> pstring "\t"; pstring s; pstring " : "; pendline helpText - | (s, IntArg _, helpText) -> pstring "\t"; pstring s; pstring " : "; pendline helpText - | (s, FloatArg _, helpText) -> pstring "\t"; pstring s; pstring " : "; pendline helpText - | (s, RestArg _, helpText) -> pstring "\t"; pstring s; pstring " ...: "; pendline helpText) - specs; - pstring "\t"; pstring "--help"; pstring ": "; pendline "display this list of options"; - pstring "\t"; pstring "-help"; pstring ": "; pendline "display this list of options"; - sbuf.ToString() - - - static member ParsePartial(cursor,argv,argSpecs:seq,?other,?usageText) = - let other = defaultArg other (fun _ -> ()) - let usageText = defaultArg usageText "" - let nargs = Array.length argv - incr cursor; - let argSpecs = argSpecs |> Seq.toList - let specs = argSpecs |> List.map (fun (arg:ArgInfo) -> arg.Name, arg.ArgType) - while !cursor < nargs do - let arg = argv.[!cursor] - let rec findMatchingArg args = - match args with - | ((s, action) :: _) when s = arg -> - let getSecondArg () = - if !cursor + 1 >= nargs then - raise(Bad("option "+s+" needs an argument.\n"+getUsage argSpecs usageText)); - argv.[!cursor+1] - - match action with - | UnitArg f -> - f (); - incr cursor - | SetArg f -> - f := true; - incr cursor - | ClearArg f -> - f := false; - incr cursor - | StringArg f-> - let arg2 = getSecondArg() - f arg2; - cursor := !cursor + 2 - | IntArg f -> - let arg2 = getSecondArg () - let arg2 = try int32 arg2 with _ -> raise(Bad(getUsage argSpecs usageText)) in - f arg2; - cursor := !cursor + 2; - | FloatArg f -> - let arg2 = getSecondArg() - let arg2 = try float arg2 with _ -> raise(Bad(getUsage argSpecs usageText)) in - f arg2; - cursor := !cursor + 2; - | RestArg f -> - incr cursor; - while !cursor < nargs do - f (argv.[!cursor]); - incr cursor; - - | (_ :: more) -> findMatchingArg more - | [] -> - if arg = "-help" || arg = "--help" || arg = "/help" || arg = "/help" || arg = "/?" then - raise (HelpText (getUsage argSpecs usageText)) - // Note: for '/abc/def' does not count as an argument - // Note: '/abc' does - elif arg.Length>0 && (arg.[0] = '-' || (arg.[0] = '/' && not (arg.Length > 1 && arg.[1..].Contains ("/")))) then - raise (Bad ("unrecognized argument: "+ arg + "\n" + getUsage argSpecs usageText)) - else - other arg; - incr cursor - findMatchingArg specs - - static member Usage (specs,?usage) = - let usage = defaultArg usage "" - System.Console.Error.WriteLine (getUsage (Seq.toList specs) usage) - - #if FX_NO_COMMAND_LINE_ARGS - #else - static member Parse (specs,?other,?usageText) = - let current = ref 0 - let argv = System.Environment.GetCommandLineArgs() - try ArgParser.ParsePartial (current, argv, specs, ?other=other, ?usageText=usageText) - with - | Bad h - | HelpText h -> - System.Console.Error.WriteLine h; - System.Console.Error.Flush(); - System.Environment.Exit(1); - | e -> - reraise() - #endif diff --git a/src/fcs-fable/src/buildtools/fsyacc/Arg.fsi b/src/fcs-fable/src/buildtools/fsyacc/Arg.fsi deleted file mode 100644 index 367f69f959..0000000000 --- a/src/fcs-fable/src/buildtools/fsyacc/Arg.fsi +++ /dev/null @@ -1,50 +0,0 @@ -// (c) Microsoft Corporation 2005-2009. - -/// A simple command-line argument processor. -#if INTERNALIZED_FSLEXYACC_RUNTIME -namespace Internal.Utilities -#else -namespace Microsoft.FSharp.Text -#endif - -/// The spec value describes the action of the argument, -/// and whether it expects a following parameter. -[] -type ArgType = - static member Clear : bool ref -> ArgType - static member Float : (float -> unit) -> ArgType - static member Int : (int -> unit) -> ArgType - static member Rest : (string -> unit) -> ArgType - static member Set : bool ref -> ArgType - static member String : (string -> unit) -> ArgType - static member Unit : (unit -> unit) -> ArgType - -type ArgInfo = - new : name:string * action:ArgType * help:string -> ArgInfo - /// Return the name of the argument - member Name : string - /// Return the argument type and action of the argument - member ArgType : ArgType - /// Return the usage help associated with the argument - member HelpText : string - -[] -type ArgParser = - #if FX_NO_COMMAND_LINE_ARGS - #else - - /// Parse some of the arguments given by 'argv', starting at the given position - [] - static member ParsePartial: cursor: int ref * argv: string[] * arguments:seq * ?otherArgs: (string -> unit) * ?usageText:string -> unit - - /// Parse the arguments given by System.Environment.GetEnvironmentVariables() - /// according to the argument processing specifications "specs". - /// Args begin with "-". Non-arguments are passed to "f" in - /// order. "use" is printed as part of the usage line if an error occurs. - - static member Parse: arguments:seq * ?otherArgs: (string -> unit) * ?usageText:string -> unit - #endif - - /// Prints the help for each argument. - static member Usage : arguments:seq * ?usage:string -> unit - diff --git a/src/fcs-fable/src/buildtools/fsyacc/Lexing.fs b/src/fcs-fable/src/buildtools/fsyacc/Lexing.fs deleted file mode 100644 index 8337717d6f..0000000000 --- a/src/fcs-fable/src/buildtools/fsyacc/Lexing.fs +++ /dev/null @@ -1,423 +0,0 @@ -// (c) Microsoft Corporation 2005-2009. - -#nowarn "47" // recursive initialization of LexBuffer - - -#if INTERNALIZED_FSLEXYACC_RUNTIME -namespace Internal.Utilities.Text.Lexing - -#else -namespace Microsoft.FSharp.Text.Lexing -#endif - - open System.Collections.Generic - - // REVIEW: This type showed up on a parsing-intensive performance measurement. Consider whether it can be a struct-record later when we have this feature. -jomo -#if INTERNALIZED_FSLEXYACC_RUNTIME - type internal Position = -#else - type Position = -#endif - { pos_fname : string; - pos_lnum : int; -#if INTERNALIZED_FSLEXYACC_RUNTIME - pos_orig_lnum : int; -#endif - pos_bol : int; - pos_cnum : int; } - member x.FileName = x.pos_fname - member x.Line = x.pos_lnum -#if INTERNALIZED_FSLEXYACC_RUNTIME - member x.OriginalLine = x.pos_orig_lnum -#endif - member x.Char = x.pos_cnum - member x.AbsoluteOffset = x.pos_cnum - member x.StartOfLine = x.pos_bol - member x.StartOfLineAbsoluteOffset = x.pos_bol - member x.Column = x.pos_cnum - x.pos_bol - member pos.NextLine = - { pos with -#if INTERNALIZED_FSLEXYACC_RUNTIME - pos_orig_lnum = pos.OriginalLine + 1; -#endif - pos_lnum = pos.Line+1; - pos_bol = pos.AbsoluteOffset } - member pos.EndOfToken(n) = {pos with pos_cnum=pos.pos_cnum + n } - member pos.AsNewLinePos() = pos.NextLine - member pos.ShiftColumnBy(by) = {pos with pos_cnum = pos.pos_cnum + by} - static member Empty = - { pos_fname=""; - pos_lnum= 0; -#if INTERNALIZED_FSLEXYACC_RUNTIME - pos_orig_lnum = 0; -#endif - pos_bol= 0; - pos_cnum=0 } - static member FirstLine(filename) = - { pos_fname=filename; -#if INTERNALIZED_FSLEXYACC_RUNTIME - pos_orig_lnum = 1; -#endif - pos_lnum= 1; - pos_bol= 0; - pos_cnum=0 } - -#if INTERNALIZED_FSLEXYACC_RUNTIME - type internal LexBufferFiller<'char> = -#else - type LexBufferFiller<'char> = -#endif - { fillSync : (LexBuffer<'char> -> unit) option - fillAsync : (LexBuffer<'char> -> Async) option } - - and [] -#if INTERNALIZED_FSLEXYACC_RUNTIME - internal LexBuffer<'char>(filler: LexBufferFiller<'char>) as this = -#else - LexBuffer<'char>(filler: LexBufferFiller<'char>) as this = -#endif - let context = new Dictionary(1) in - let extendBufferSync = (fun () -> match filler.fillSync with Some refill -> refill this | None -> invalidOp "attempt to read synchronously from an asynchronous lex buffer") - let extendBufferAsync = (fun () -> match filler.fillAsync with Some refill -> refill this | None -> invalidOp "attempt to read asynchronously from a synchronous lex buffer") - let mutable buffer=[||]; - /// number of valid charactes beyond bufferScanStart - let mutable bufferMaxScanLength=0; - /// count into the buffer when scanning - let mutable bufferScanStart=0; - /// number of characters scanned so far - let mutable bufferScanLength=0; - /// length of the scan at the last accepting state - let mutable lexemeLength=0; - /// action related to the last accepting state - let mutable bufferAcceptAction=0; - let mutable eof = false; - let mutable startPos = Position.Empty ; - let mutable endPos = Position.Empty - - // Throw away all the input besides the lexeme - - let discardInput () = - let keep = Array.sub buffer bufferScanStart bufferScanLength - let nkeep = keep.Length - Array.blit keep 0 buffer 0 nkeep; - bufferScanStart <- 0; - bufferMaxScanLength <- nkeep - - - member lexbuf.EndOfScan () : int = - // Printf.eprintf "endOfScan, lexBuffer.lexemeLength = %d\n" lexBuffer.lexemeLength; - if bufferAcceptAction < 0 then - failwith "unrecognized input" - - // Printf.printf "endOfScan %d state %d on unconsumed input '%c' (%d)\n" a s (Char.chr inp) inp; - // Printf.eprintf "accept, lexeme = %s\n" (lexeme lexBuffer); - lexbuf.StartPos <- endPos; - lexbuf.EndPos <- endPos.EndOfToken(lexbuf.LexemeLength); - bufferAcceptAction - - member lexbuf.StartPos - with get() = startPos - and set(b) = startPos <- b - - member lexbuf.EndPos - with get() = endPos - and set(b) = endPos <- b - - member lexbuf.Lexeme = Array.sub buffer bufferScanStart lexemeLength - member lexbuf.LexemeChar(n) = buffer.[n+bufferScanStart] - - member lexbuf.BufferLocalStore = (context :> IDictionary<_,_>) - member lexbuf.LexemeLength with get() : int = lexemeLength and set v = lexemeLength <- v - member internal lexbuf.Buffer with get() : 'char[] = buffer and set v = buffer <- v - member internal lexbuf.BufferMaxScanLength with get() = bufferMaxScanLength and set v = bufferMaxScanLength <- v - member internal lexbuf.BufferScanLength with get() = bufferScanLength and set v = bufferScanLength <- v - member internal lexbuf.BufferScanStart with get() : int = bufferScanStart and set v = bufferScanStart <- v - member internal lexbuf.BufferAcceptAction with get() = bufferAcceptAction and set v = bufferAcceptAction <- v - member internal lexbuf.RefillBuffer = extendBufferSync - member internal lexbuf.AsyncRefillBuffer = extendBufferAsync - - static member LexemeString(lexbuf:LexBuffer) = - new System.String(lexbuf.Buffer,lexbuf.BufferScanStart,lexbuf.LexemeLength) - - member lexbuf.IsPastEndOfStream - with get() = eof - and set(b) = eof <- b - - member lexbuf.DiscardInput() = discardInput () - - member x.BufferScanPos = bufferScanStart + bufferScanLength - - member lexbuf.EnsureBufferSize n = - if lexbuf.BufferScanPos + n >= buffer.Length then - let repl = Array.zeroCreate (lexbuf.BufferScanPos + n) - Array.blit buffer bufferScanStart repl bufferScanStart bufferScanLength; - buffer <- repl - - static member FromReadFunctions (syncRead : ('char[] * int * int -> int) option, asyncRead : ('char[] * int * int -> Async) option) : LexBuffer<'char> = - let extension= Array.zeroCreate 4096 - let fillers = - { fillSync = - match syncRead with - | None -> None - | Some read -> - Some (fun lexBuffer -> - let n = read(extension,0,extension.Length) - lexBuffer.EnsureBufferSize n; - Array.blit extension 0 lexBuffer.Buffer lexBuffer.BufferScanPos n; - lexBuffer.BufferMaxScanLength <- lexBuffer.BufferScanLength + n); - fillAsync = - match asyncRead with - | None -> None - | Some read -> - Some (fun lexBuffer -> - async { - let! n = read(extension,0,extension.Length) - lexBuffer.EnsureBufferSize n; - Array.blit extension 0 lexBuffer.Buffer lexBuffer.BufferScanPos n; - lexBuffer.BufferMaxScanLength <- lexBuffer.BufferScanLength + n }) } - new LexBuffer<_>(fillers) - - // A full type signature is required on this method because it is used at more specific types within its own scope - static member FromFunction (f : 'char[] * int * int -> int) : LexBuffer<'char> = LexBuffer<_>.FromReadFunctions(Some(f),None) - static member FromAsyncFunction (f : 'char[] * int * int -> Async) : LexBuffer<'char> = LexBuffer<_>.FromReadFunctions(None,Some(f)) - - static member FromCharFunction f : LexBuffer = - LexBuffer.FromFunction(fun (buff,start,len) -> - let buff2 = Array.zeroCreate len - let n = f buff2 len - Array.blit buff2 0 buff start len - n) - static member FromByteFunction f : LexBuffer = - LexBuffer.FromFunction(fun (buff,start,len) -> - let buff2 = Array.zeroCreate len - let n = f buff2 len - Array.blit buff2 0 buff start len - n) - - // A full type signature is required on this method because it is used at more specific types within its own scope - static member FromArray (s: 'char[]) : LexBuffer<'char> = - let lexBuffer = - new LexBuffer<_> - { fillSync = Some (fun _ -> ()); - fillAsync = Some (fun _ -> async { return () }) } - let buffer = Array.copy s - lexBuffer.Buffer <- buffer; - lexBuffer.BufferMaxScanLength <- buffer.Length; - lexBuffer - - static member FromBytes (arr) = LexBuffer.FromArray(arr) - static member FromChars (arr) = LexBuffer.FromArray(arr) - static member FromString (s:string) = LexBuffer.FromChars (s.ToCharArray()) - - static member FromTextReader (tr:System.IO.TextReader) : LexBuffer = - LexBuffer.FromFunction(tr.Read) - - static member FromBinaryReader (br:System.IO.BinaryReader) : LexBuffer = - LexBuffer.FromFunction(br.Read) - - static member FromStream (stream:System.IO.Stream) : LexBuffer = - LexBuffer.FromReadFunctions(Some(stream.Read),Some(fun (buf,offset,len) -> stream.AsyncRead(buf,offset=offset,count=len))) - - module GenericImplFragments = - let startInterpret(lexBuffer:LexBuffer<_>)= - lexBuffer.BufferScanStart <- lexBuffer.BufferScanStart + lexBuffer.LexemeLength; - lexBuffer.BufferMaxScanLength <- lexBuffer.BufferMaxScanLength - lexBuffer.LexemeLength; - lexBuffer.BufferScanLength <- 0; - lexBuffer.LexemeLength <- 0; - lexBuffer.BufferAcceptAction <- -1; - - let afterRefill (trans: uint16[] array,sentinel,lexBuffer:LexBuffer<_>,scanUntilSentinel,endOfScan,state,eofPos) = - // end of file occurs if we couldn't extend the buffer - if lexBuffer.BufferScanLength = lexBuffer.BufferMaxScanLength then - let snew = int trans.[state].[eofPos] // == EOF - if snew = sentinel then - endOfScan() - else - if lexBuffer.IsPastEndOfStream then failwith "End of file on lexing stream"; - lexBuffer.IsPastEndOfStream <- true; - // Printf.printf "state %d --> %d on eof\n" state snew; - scanUntilSentinel(lexBuffer,snew) - else - scanUntilSentinel(lexBuffer, state) - - let onAccept (lexBuffer:LexBuffer<_>,a) = - lexBuffer.LexemeLength <- lexBuffer.BufferScanLength; - lexBuffer.BufferAcceptAction <- a; - - open GenericImplFragments - - [] -#if INTERNALIZED_FSLEXYACC_RUNTIME - type internal AsciiTables(trans: uint16[] array, accept: uint16[]) = -#else - type AsciiTables(trans: uint16[] array, accept: uint16[]) = -#endif - let rec scanUntilSentinel(lexBuffer, state) = - let sentinel = 255 * 256 + 255 - // Return an endOfScan after consuming the input - let a = int accept.[state] - if a <> sentinel then - onAccept (lexBuffer,a) - - if lexBuffer.BufferScanLength = lexBuffer.BufferMaxScanLength then - lexBuffer.DiscardInput(); - lexBuffer.RefillBuffer (); - // end of file occurs if we couldn't extend the buffer - afterRefill (trans,sentinel,lexBuffer,scanUntilSentinel,lexBuffer.EndOfScan,state,256 (* == EOF *) ) - else - // read a character - end the scan if there are no further transitions - let inp = int(lexBuffer.Buffer.[lexBuffer.BufferScanPos]) - let snew = int trans.[state].[inp] - if snew = sentinel then - lexBuffer.EndOfScan() - else - lexBuffer.BufferScanLength <- lexBuffer.BufferScanLength + 1; - // Printf.printf "state %d --> %d on '%c' (%d)\n" state snew (Char.chr inp) inp; - scanUntilSentinel(lexBuffer, snew) - - /// Interpret tables for an ascii lexer generated by fslex. - member tables.Interpret(initialState,lexBuffer : LexBuffer) = - startInterpret(lexBuffer) - scanUntilSentinel(lexBuffer, initialState) - - /// Interpret tables for an ascii lexer generated by fslex. - member tables.AsyncInterpret(initialState,lexBuffer : LexBuffer) = - - let rec scanUntilSentinel(lexBuffer,state) : Async = - async { - let sentinel = 255 * 256 + 255 - // Return an endOfScan after consuming the input - let a = int accept.[state] - if a <> sentinel then - onAccept (lexBuffer,a) - - if lexBuffer.BufferScanLength = lexBuffer.BufferMaxScanLength then - lexBuffer.DiscardInput(); - do! lexBuffer.AsyncRefillBuffer (); - // end of file occurs if we couldn't extend the buffer - return! afterRefill (trans,sentinel,lexBuffer,scanUntilSentinel,endOfScan,state,256 (* == EOF *) ) - else - // read a character - end the scan if there are no further transitions - let inp = int(lexBuffer.Buffer.[lexBuffer.BufferScanPos]) - let snew = int trans.[state].[inp] - if snew = sentinel then - return! endOfScan() - else - lexBuffer.BufferScanLength <- lexBuffer.BufferScanLength + 1; - return! scanUntilSentinel(lexBuffer,snew) - } - and endOfScan() = - async { return lexBuffer.EndOfScan() } - startInterpret(lexBuffer) - scanUntilSentinel(lexBuffer, initialState) - - - static member Create(trans,accept) = new AsciiTables(trans,accept) - - [] -#if INTERNALIZED_FSLEXYACC_RUNTIME - type internal UnicodeTables(trans: uint16[] array, accept: uint16[]) = -#else - type UnicodeTables(trans: uint16[] array, accept: uint16[]) = -#endif - let sentinel = 255 * 256 + 255 - let numUnicodeCategories = 30 - let numLowUnicodeChars = 128 - let numSpecificUnicodeChars = (trans.[0].Length - 1 - numLowUnicodeChars - numUnicodeCategories)/2 - let lookupUnicodeCharacters (state,inp) = - let inpAsInt = int inp - // Is it a fast ASCII character? - if inpAsInt < numLowUnicodeChars then - int trans.[state].[inpAsInt] - else - // Search for a specific unicode character - let baseForSpecificUnicodeChars = numLowUnicodeChars - let rec loop i = - if i >= numSpecificUnicodeChars then - // OK, if we failed then read the 'others' entry in the alphabet, - // which covers all Unicode characters not covered in other - // ways - let baseForUnicodeCategories = numLowUnicodeChars+numSpecificUnicodeChars*2 - let unicodeCategory = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(inp) - //System.Console.WriteLine("inp = {0}, unicodeCategory = {1}", [| box inp; box unicodeCategory |]); - int trans.[state].[baseForUnicodeCategories + int32 unicodeCategory] - else - // This is the specific unicode character - let c = char (int trans.[state].[baseForSpecificUnicodeChars+i*2]) - //System.Console.WriteLine("c = {0}, inp = {1}, i = {2}", [| box c; box inp; box i |]); - // OK, have we found the entry for a specific unicode character? - if c = inp - then int trans.[state].[baseForSpecificUnicodeChars+i*2+1] - else loop(i+1) - - loop 0 - let eofPos = numLowUnicodeChars + 2*numSpecificUnicodeChars + numUnicodeCategories - - let rec scanUntilSentinel(lexBuffer,state) = - // Return an endOfScan after consuming the input - let a = int accept.[state] - if a <> sentinel then - onAccept(lexBuffer,a) - - if lexBuffer.BufferScanLength = lexBuffer.BufferMaxScanLength then - lexBuffer.DiscardInput(); - lexBuffer.RefillBuffer (); - // end of file occurs if we couldn't extend the buffer - afterRefill (trans,sentinel,lexBuffer,scanUntilSentinel,lexBuffer.EndOfScan,state,eofPos) - else - // read a character - end the scan if there are no further transitions - let inp = lexBuffer.Buffer.[lexBuffer.BufferScanPos] - - // Find the new state - let snew = lookupUnicodeCharacters (state,inp) - - if snew = sentinel then - lexBuffer.EndOfScan() - else - lexBuffer.BufferScanLength <- lexBuffer.BufferScanLength + 1; - // Printf.printf "state %d --> %d on '%c' (%d)\n" s snew (char inp) inp; - scanUntilSentinel(lexBuffer,snew) - - // Each row for the Unicode table has format - // 128 entries for ASCII characters - // A variable number of 2*UInt16 entries for SpecificUnicodeChars - // 30 entries, one for each UnicodeCategory - // 1 entry for EOF - - member tables.Interpret(initialState,lexBuffer : LexBuffer) = - startInterpret(lexBuffer) - scanUntilSentinel(lexBuffer, initialState) - - member tables.AsyncInterpret(initialState,lexBuffer : LexBuffer) = - - let rec scanUntilSentinel(lexBuffer, state) = - async { - // Return an endOfScan after consuming the input - let a = int accept.[state] - if a <> sentinel then - onAccept(lexBuffer,a) - - if lexBuffer.BufferScanLength = lexBuffer.BufferMaxScanLength then - lexBuffer.DiscardInput(); - lexBuffer.RefillBuffer (); - // end of file occurs if we couldn't extend the buffer - return! afterRefill (trans,sentinel,lexBuffer,scanUntilSentinel,endOfScan,state,eofPos) - else - // read a character - end the scan if there are no further transitions - let inp = lexBuffer.Buffer.[lexBuffer.BufferScanPos] - - // Find the new state - let snew = lookupUnicodeCharacters (state,inp) - - if snew = sentinel then - return! endOfScan() - else - lexBuffer.BufferScanLength <- lexBuffer.BufferScanLength + 1; - return! scanUntilSentinel(lexBuffer, snew) - } - and endOfScan() = - async { return lexBuffer.EndOfScan() } - startInterpret(lexBuffer) - scanUntilSentinel(lexBuffer, initialState) - - static member Create(trans,accept) = new UnicodeTables(trans,accept) diff --git a/src/fcs-fable/src/buildtools/fsyacc/Lexing.fsi b/src/fcs-fable/src/buildtools/fsyacc/Lexing.fsi deleted file mode 100644 index e31ad411aa..0000000000 --- a/src/fcs-fable/src/buildtools/fsyacc/Lexing.fsi +++ /dev/null @@ -1,151 +0,0 @@ -//========================================================================== -// LexBuffers are for use with automatically generated lexical analyzers, -// in particular those produced by 'fslex'. -// -// (c) Microsoft Corporation 2005-2008. -//=========================================================================== - -#if INTERNALIZED_FSLEXYACC_RUNTIME -namespace Internal.Utilities.Text.Lexing -#else -namespace Microsoft.FSharp.Text.Lexing -#endif - -open System.Collections.Generic - -/// Position information stored for lexing tokens -// -// Note: this is an OCaml compat record type. -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal Position = -#else -type Position = -#endif - { /// The file name for the position - pos_fname: string; - /// The line number for the position - pos_lnum: int; -#if INTERNALIZED_FSLEXYACC_RUNTIME - /// The line number for the position in the original source file - pos_orig_lnum : int; -#endif - /// The absolute offset of the beginning of the line - pos_bol: int; - /// The absolute offset of the column for the position - pos_cnum: int; } - /// The file name associated with the input stream. - member FileName : string - /// The line number in the input stream, assuming fresh positions have been updated - /// using AsNewLinePos() and by modifying the EndPos property of the LexBuffer. - member Line : int -#if INTERNALIZED_FSLEXYACC_RUNTIME - /// The line number for the position in the input stream, assuming fresh positions have been updated - /// using AsNewLinePos() - member OriginalLine : int -#endif - [] - member Char : int - /// The character number in the input stream - member AbsoluteOffset : int - /// Return absolute offset of the start of the line marked by the position - member StartOfLineAbsoluteOffset : int - /// Return the column number marked by the position, i.e. the difference between the AbsoluteOffset and the StartOfLineAbsoluteOffset - member Column : int - // Given a position just beyond the end of a line, return a position at the start of the next line - member NextLine : Position - - /// Given a position at the start of a token of length n, return a position just beyond the end of the token - member EndOfToken: n:int -> Position - /// Gives a position shifted by specified number of characters - member ShiftColumnBy: by:int -> Position - - [] - member AsNewLinePos : unit -> Position - - /// Get an arbitrary position, with the empty string as filename, and - static member Empty : Position - - /// Get a position corresponding to the first line (line number 1) in a given file - static member FirstLine : filename:string -> Position - -[] -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal LexBuffer<'char> = -#else -/// Input buffers consumed by lexers generated by fslex.exe -type LexBuffer<'char> = -#endif - /// The start position for the lexeme - member StartPos: Position with get,set - /// The end position for the lexeme - member EndPos: Position with get,set - /// The matched string - member Lexeme: 'char array - - /// Fast helper to turn the matched characters into a string, avoiding an intermediate array - static member LexemeString : LexBuffer -> string - - /// The length of the matched string - member LexemeLength: int - /// Fetch a particular character in the matched string - member LexemeChar: int -> 'char - - /// Dynamically typed, non-lexically scoped parameter table - member BufferLocalStore : IDictionary - - /// True if the refill of the buffer ever failed , or if explicitly set to true. - member IsPastEndOfStream: bool with get,set - /// Remove all input, though don't discard the current lexeme - member DiscardInput: unit -> unit - - /// Create a lex buffer suitable for byte lexing that reads characters from the given array - static member FromBytes: byte[] -> LexBuffer - /// Create a lex buffer suitable for Unicode lexing that reads characters from the given array - static member FromChars: char[] -> LexBuffer - /// Create a lex buffer suitable for Unicode lexing that reads characters from the given string - static member FromString: string -> LexBuffer - /// Create a lex buffer that reads character or byte inputs by using the given function - static member FromFunction: ('char[] * int * int -> int) -> LexBuffer<'char> - /// Create a lex buffer that asynchronously reads character or byte inputs by using the given function - static member FromAsyncFunction: ('char[] * int * int -> Async) -> LexBuffer<'char> - - - [.FromFunction instead")>] - static member FromCharFunction: (char[] -> int -> int) -> LexBuffer - [.FromFunction instead")>] - static member FromByteFunction: (byte[] -> int -> int) -> LexBuffer - - /// Create a lex buffer suitable for use with a Unicode lexer that reads character inputs from the given text reader - static member FromTextReader: System.IO.TextReader -> LexBuffer - /// Create a lex buffer suitable for use with ASCII byte lexing that reads byte inputs from the given binary reader - static member FromBinaryReader: System.IO.BinaryReader -> LexBuffer - - -/// The type of tables for an ascii lexer generated by fslex. -[] -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal AsciiTables = -#else -type AsciiTables = -#endif - static member Create : uint16[] array * uint16[] -> AsciiTables - /// Interpret tables for an ascii lexer generated by fslex. - member Interpret: initialState:int * LexBuffer -> int - /// Interpret tables for an ascii lexer generated by fslex, processing input asynchronously - member AsyncInterpret: initialState:int * LexBuffer -> Async - - -/// The type of tables for an unicode lexer generated by fslex. -[] -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal UnicodeTables = -#else -type UnicodeTables = -#endif - static member Create : uint16[] array * uint16[] -> UnicodeTables - /// Interpret tables for a unicode lexer generated by fslex. - member Interpret: initialState:int * LexBuffer -> int - - /// Interpret tables for a unicode lexer generated by fslex, processing input asynchronously - member AsyncInterpret: initialState:int * LexBuffer -> Async - diff --git a/src/fcs-fable/src/buildtools/fsyacc/Parsing.fs b/src/fcs-fable/src/buildtools/fsyacc/Parsing.fs deleted file mode 100644 index 01dccfb610..0000000000 --- a/src/fcs-fable/src/buildtools/fsyacc/Parsing.fs +++ /dev/null @@ -1,514 +0,0 @@ -// (c) Microsoft Corporation 2005-2009. - -#if INTERNALIZED_FSLEXYACC_RUNTIME - -namespace Internal.Utilities.Text.Parsing -open Internal.Utilities -open Internal.Utilities.Text.Lexing - -#else -namespace Microsoft.FSharp.Text.Parsing -open Microsoft.FSharp.Text.Lexing -#endif - - - -open System -open System.Collections.Generic - -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal IParseState = -#else -type IParseState = -#endif - abstract InputRange: int -> Position * Position - abstract InputEndPosition: int -> Position - abstract InputStartPosition: int -> Position - abstract ResultRange: Position * Position - abstract GetInput: int -> obj - abstract ParserLocalStore : IDictionary - abstract RaiseError<'b> : unit -> 'b - -//------------------------------------------------------------------------- -// This context is passed to the error reporter when a syntax error occurs - -[] -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal ParseErrorContext<'tok> -#else -type ParseErrorContext<'tok> -#endif - (//lexbuf: LexBuffer<_>, - stateStack:int list, - parseState: IParseState, - reduceTokens: int list, - currentToken: 'tok option, - reducibleProductions: int list list, - shiftableTokens: int list , - message : string) = - //member x.LexBuffer = lexbuf - member x.StateStack = stateStack - member x.ReduceTokens = reduceTokens - member x.CurrentToken = currentToken - member x.ParseState = parseState - member x.ReducibleProductions = reducibleProductions - member x.ShiftTokens = shiftableTokens - member x.Message = message - - -//------------------------------------------------------------------------- -// This is the data structure emitted as code by FSYACC. - -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal Tables<'tok> = -#else -type Tables<'tok> = -#endif - { reductions: (IParseState -> obj) array; - endOfInputTag: int; - tagOfToken: 'tok -> int; - dataOfToken: 'tok -> obj; - actionTableElements: uint16[]; - actionTableRowOffsets: uint16[]; - reductionSymbolCounts: uint16[]; - immediateActions: uint16[]; - gotos: uint16[]; - sparseGotoTableRowOffsets: uint16[]; - stateToProdIdxsTableElements: uint16[]; - stateToProdIdxsTableRowOffsets: uint16[]; - productionToNonTerminalTable: uint16[]; - /// For fsyacc.exe, this entry is filled in by context from the generated parser file. If no 'parse_error' function - /// is defined by the user then ParseHelpers.parse_error is used by default (ParseHelpers is opened - /// at the top of the generated parser file) - parseError: ParseErrorContext<'tok> -> unit; - numTerminals: int; - tagOfErrorTerminal: int } - -//------------------------------------------------------------------------- -// An implementation of stacks. - -// This type is in System.dll so for the moment we can't use it in FSharp.Core.dll -//type Stack<'a> = System.Collections.Generic.Stack<'a> - -#if INTERNALIZED_FSLEXYACC_RUNTIME -type Stack<'a>(n) = -#else -type internal Stack<'a>(n) = -#endif - let mutable contents = Array.zeroCreate<'a>(n) - let mutable count = 0 - - member buf.Ensure newSize = - let oldSize = Array.length contents - if newSize > oldSize then - let old = contents - contents <- Array.zeroCreate (max newSize (oldSize * 2)); - Array.blit old 0 contents 0 count; - - member buf.Count = count - member buf.Pop() = count <- count - 1 - member buf.Peep() = contents.[count - 1] - member buf.Top(n) = [ for x in contents.[max 0 (count-n)..count - 1] -> x ] |> List.rev - member buf.Push(x) = - buf.Ensure(count + 1); - contents.[count] <- x; - count <- count + 1 - - member buf.IsEmpty = (count = 0) -#if __DEBUG - member buf.PrintStack() = - for i = 0 to (count - 1) do -#if FX_NO_CONSOLE - () -#else - System.Console.Write("{0}{1}",(contents.[i]),if i=count-1 then ":" else "-") -#endif -#endif -exception RecoverableParseError -exception Accept of obj - -#if __DEBUG -module Flags = - let mutable debug = false -#endif - -#if INTERNALIZED_FSLEXYACC_RUNTIME -module internal Implementation = -#else -module Implementation = -#endif - - // Definitions shared with fsyacc - let anyMarker = 0xffff - let shiftFlag = 0x0000 - let reduceFlag = 0x4000 - let errorFlag = 0x8000 - let acceptFlag = 0xc000 - let actionMask = 0xc000 - - let actionValue action = action &&& (~~~ actionMask) - let actionKind action = action &&& actionMask - - //------------------------------------------------------------------------- - // Read the tables written by FSYACC. - - type AssocTable(elemTab:uint16[], offsetTab:uint16[]) = - let cache = new Dictionary<_,_>(2000) - - member t.readAssoc (minElemNum,maxElemNum,defaultValueOfAssoc,keyToFind) = - // do a binary chop on the table - let elemNumber : int = (minElemNum+maxElemNum)/2 - if elemNumber = maxElemNum - then defaultValueOfAssoc - else - let x = int elemTab.[elemNumber*2] - if keyToFind = x then - int elemTab.[elemNumber*2+1] - elif keyToFind < x then t.readAssoc (minElemNum ,elemNumber,defaultValueOfAssoc,keyToFind) - else t.readAssoc (elemNumber+1,maxElemNum,defaultValueOfAssoc,keyToFind) - - member t.Read(rowNumber ,keyToFind) = - - // First check the sparse lookaside table - // Performance note: without this lookaside table the binary chop in readAssoc - // takes up around 10% of of parsing time - // for parsing intensive samples such as the bootstrapped F# compiler. - // - // Note: using a .NET Dictionary for this int -> int table looks like it could be sub-optimal. - // Some other better sparse lookup table may be better. - let mutable res = 0 - let cacheKey = (rowNumber <<< 16) ||| keyToFind - let ok = cache.TryGetValue(cacheKey, &res) - if ok then res - else - let headOfTable = int offsetTab.[rowNumber] - let firstElemNumber = headOfTable + 1 - let numberOfElementsInAssoc = int elemTab.[headOfTable*2] - let defaultValueOfAssoc = int elemTab.[headOfTable*2+1] - let res = t.readAssoc (firstElemNumber,(firstElemNumber+numberOfElementsInAssoc),defaultValueOfAssoc,keyToFind) - cache.[cacheKey] <- res - res - - // Read all entries in the association table - // Used during error recovery to find all valid entries in the table - member x.ReadAll(n) = - let headOfTable = int offsetTab.[n] - let firstElemNumber = headOfTable + 1 - let numberOfElementsInAssoc = int32 elemTab.[headOfTable*2] - let defaultValueOfAssoc = int elemTab.[headOfTable*2+1] - [ for i in firstElemNumber .. (firstElemNumber+numberOfElementsInAssoc-1) -> - (int elemTab.[i*2], int elemTab.[i*2+1]) ], defaultValueOfAssoc - - type IdxToIdxListTable(elemTab:uint16[], offsetTab:uint16[]) = - - // Read all entries in a row of the table - member x.ReadAll(n) = - let headOfTable = int offsetTab.[n] - let firstElemNumber = headOfTable + 1 - let numberOfElements = int32 elemTab.[headOfTable] - [ for i in firstElemNumber .. (firstElemNumber+numberOfElements-1) -> int elemTab.[i] ] - - //------------------------------------------------------------------------- - // interpret the tables emitted by FSYACC. - - [] - [] - type ValueInfo = - val value: obj - val startPos: Position - val endPos: Position - new(value,startPos,endPos) = { value=value; startPos=startPos;endPos=endPos } - - let interpret (tables: Tables<'tok>) lexer (lexbuf : LexBuffer<_>) initialState = - let localStore = new Dictionary() in - localStore.["LexBuffer"] <- lexbuf; -#if __DEBUG - if Flags.debug then System.Console.WriteLine("\nParser: interpret tables"); -#endif - let stateStack : Stack = new Stack<_>(100) - stateStack.Push(initialState); - let valueStack = new Stack(100) - let mutable haveLookahead = false - let mutable lookaheadToken = Unchecked.defaultof<'tok> - let mutable lookaheadEndPos = Unchecked.defaultof - let mutable lookaheadStartPos = Unchecked.defaultof - let mutable finished = false - // After an error occurs, we suppress errors until we've shifted three tokens in a row. - let mutable errorSuppressionCountDown = 0 - - // When we hit the end-of-file we don't fail straight away but rather keep permitting shift - // and reduce against the last token in the token stream 20 times or until we've accepted - // or exhausted the stack. This allows error recovery rules of the form - // input : realInput EOF | realInput error EOF | error EOF - // where consuming one EOF to trigger an error doesn't result in overall parse failure - // catastrophe and the loss of intermediate results. - // - let mutable inEofCountDown = false - let mutable eofCountDown = 20 // Number of EOFs to supply at the end for error recovery - // The 100 here means a maximum of 100 elements for each rule - let ruleStartPoss = (Array.zeroCreate 100 : Position array) - let ruleEndPoss = (Array.zeroCreate 100 : Position array) - let ruleValues = (Array.zeroCreate 100 : obj array) - let lhsPos = (Array.zeroCreate 2 : Position array) - let reductions = tables.reductions - let actionTable = new AssocTable(tables.actionTableElements, tables.actionTableRowOffsets) - let gotoTable = new AssocTable(tables.gotos, tables.sparseGotoTableRowOffsets) - let stateToProdIdxsTable = new IdxToIdxListTable(tables.stateToProdIdxsTableElements, tables.stateToProdIdxsTableRowOffsets) - - let parseState = - { new IParseState with - member p.InputRange(n) = ruleStartPoss.[n-1], ruleEndPoss.[n-1]; - member p.InputStartPosition(n) = ruleStartPoss.[n-1] - member p.InputEndPosition(n) = ruleEndPoss.[n-1]; - member p.GetInput(n) = ruleValues.[n-1]; - member p.ResultRange = (lhsPos.[0], lhsPos.[1]); - member p.ParserLocalStore = (localStore :> IDictionary<_,_>); - member p.RaiseError() = raise RecoverableParseError (* NOTE: this binding tests the fairly complex logic associated with an object expression implementing a generic abstract method *) - } - -#if __DEBUG - let report haveLookahead lookaheadToken = - if haveLookahead then sprintf "%A" lookaheadToken - else "[TBC]" -#endif - - // Pop the stack until we can shift the 'error' token. If 'tokenOpt' is given - // then keep popping until we can shift both the 'error' token and the token in 'tokenOpt'. - // This is used at end-of-file to make sure we can shift both the 'error' token and the 'EOF' token. - let rec popStackUntilErrorShifted(tokenOpt) = - // Keep popping the stack until the "error" terminal is shifted -#if __DEBUG - if Flags.debug then System.Console.WriteLine("popStackUntilErrorShifted"); -#endif - if stateStack.IsEmpty then -#if __DEBUG - if Flags.debug then - System.Console.WriteLine("state stack empty during error recovery - generating parse error"); -#endif - failwith "parse error"; - - let currState = stateStack.Peep() -#if __DEBUG - if Flags.debug then - System.Console.WriteLine("In state {0} during error recovery", currState); -#endif - - let action = actionTable.Read(currState, tables.tagOfErrorTerminal) - - if actionKind action = shiftFlag && - (match tokenOpt with - | None -> true - | Some(token) -> - let nextState = actionValue action - actionKind (actionTable.Read(nextState, tables.tagOfToken(token))) = shiftFlag) then - -#if __DEBUG - if Flags.debug then System.Console.WriteLine("shifting error, continuing with error recovery"); -#endif - let nextState = actionValue action - // The "error" non terminal needs position information, though it tends to be unreliable. - // Use the StartPos/EndPos from the lex buffer - valueStack.Push(ValueInfo(box (), lexbuf.StartPos, lexbuf.EndPos)); - stateStack.Push(nextState) - else - if valueStack.IsEmpty then - failwith "parse error"; -#if __DEBUG - if Flags.debug then - System.Console.WriteLine("popping stack during error recovery"); -#endif - valueStack.Pop(); - stateStack.Pop(); - popStackUntilErrorShifted(tokenOpt) - - while not finished do - if stateStack.IsEmpty then - finished <- true - else - let state = stateStack.Peep() -#if __DEBUG - if Flags.debug then (Console.Write("{0} value(state), state ",valueStack.Count); stateStack.PrintStack()) -#endif - let action = - let immediateAction = int tables.immediateActions.[state] - if not (immediateAction = anyMarker) then - // Action has been pre-determined, no need to lookahead - // Expecting it to be a Reduce action on a non-fakeStartNonTerminal ? - immediateAction - else - // Lookahead required to determine action - if not haveLookahead then - if lexbuf.IsPastEndOfStream then - // When the input runs out, keep supplying the last token for eofCountDown times - if eofCountDown>0 then - haveLookahead <- true - eofCountDown <- eofCountDown - 1 - inEofCountDown <- true - else - haveLookahead <- false - else - lookaheadToken <- lexer lexbuf - lookaheadStartPos <- lexbuf.StartPos - lookaheadEndPos <- lexbuf.EndPos - haveLookahead <- true; - - let tag = - if haveLookahead then tables.tagOfToken lookaheadToken - else tables.endOfInputTag - - // Printf.printf "state %d\n" state - actionTable.Read(state,tag) - - let kind = actionKind action - if kind = shiftFlag then ( - if errorSuppressionCountDown > 0 then - errorSuppressionCountDown <- errorSuppressionCountDown - 1; -#if __DEBUG - if Flags.debug then Console.WriteLine("shifting, reduced errorRecoverylevel to {0}\n", errorSuppressionCountDown); -#endif - let nextState = actionValue action - if not haveLookahead then failwith "shift on end of input!"; - let data = tables.dataOfToken lookaheadToken - valueStack.Push(ValueInfo(data, lookaheadStartPos, lookaheadEndPos)); - stateStack.Push(nextState); -#if __DEBUG - if Flags.debug then Console.WriteLine("shift/consume input {0}, shift to state {1}", report haveLookahead lookaheadToken, nextState); -#endif - haveLookahead <- false - - ) elif kind = reduceFlag then - let prod = actionValue action - let reduction = reductions.[prod] - let n = int tables.reductionSymbolCounts.[prod] - // pop the symbols, populate the values and populate the locations -#if __DEBUG - if Flags.debug then Console.Write("reduce popping {0} values/states, lookahead {1}", n, report haveLookahead lookaheadToken); -#endif - - lhsPos.[0] <- Position.Empty; - lhsPos.[1] <- Position.Empty; - for i = 0 to n - 1 do - if valueStack.IsEmpty then failwith "empty symbol stack"; - let topVal = valueStack.Peep() - valueStack.Pop(); - stateStack.Pop(); - ruleValues.[(n-i)-1] <- topVal.value; - ruleStartPoss.[(n-i)-1] <- topVal.startPos; - ruleEndPoss.[(n-i)-1] <- topVal.endPos; - if lhsPos.[1] = Position.Empty then lhsPos.[1] <- topVal.endPos; - if not (topVal.startPos = Position.Empty) then lhsPos.[0] <- topVal.startPos - done; - - try - // Printf.printf "reduce %d\n" prod; - let redResult = reduction parseState - valueStack.Push(ValueInfo(redResult, lhsPos.[0], lhsPos.[1])); - let currState = stateStack.Peep() - let newGotoState = gotoTable.Read(int tables.productionToNonTerminalTable.[prod], currState) - stateStack.Push(newGotoState) -#if __DEBUG - if Flags.debug then Console.WriteLine(" goto state {0}", newGotoState) -#endif - with - | Accept res -> - finished <- true; - valueStack.Push(ValueInfo(res, lhsPos.[0], lhsPos.[1])) - | RecoverableParseError -> -#if __DEBUG - if Flags.debug then Console.WriteLine("RecoverableParseErrorException...\n"); -#endif - popStackUntilErrorShifted(None); - // User code raised a Parse_error. Don't report errors again until three tokens have been shifted - errorSuppressionCountDown <- 3 - elif kind = errorFlag then ( -#if __DEBUG - if Flags.debug then Console.Write("ErrorFlag... "); -#endif - // Silently discard inputs and don't report errors - // until three tokens in a row have been shifted -#if __DEBUG - if Flags.debug then printfn "error on token '%A' " (if haveLookahead then Some(lookaheadToken) else None); -#endif - if errorSuppressionCountDown > 0 then - // If we're in the end-of-file count down then we're very keen to 'Accept'. - // We can only do this by repeatedly popping the stack until we can shift both an 'error' token - // and an EOF token. - if inEofCountDown && eofCountDown < 10 then -#if __DEBUG - if Flags.debug then printfn "poppin stack, lokking to shift both 'error' and that token, during end-of-file error recovery" ; -#endif - popStackUntilErrorShifted(if haveLookahead then Some(lookaheadToken) else None); - - // If we don't haveLookahead then the end-of-file count down is over and we have no further options. - if not haveLookahead then - failwith "parse error: unexpected end of file" - -#if __DEBUG - if Flags.debug then printfn "discarding token '%A' during error suppression" (if haveLookahead then Some(lookaheadToken) else None); -#endif - // Discard the token - haveLookahead <- false - // Try again to shift three tokens - errorSuppressionCountDown <- 3 - else ( - - let currentToken = if haveLookahead then Some(lookaheadToken) else None - let actions,defaultAction = actionTable.ReadAll(state) - let explicit = Set.ofList [ for (tag,_action) in actions -> tag ] - - let shiftableTokens = - [ for (tag,action) in actions do - if (actionKind action) = shiftFlag then - yield tag - if actionKind defaultAction = shiftFlag then - for tag in 0 .. tables.numTerminals-1 do - if not (explicit.Contains(tag)) then - yield tag ] in - - let stateStack = stateStack.Top(12) in - let reducibleProductions = - [ for state in stateStack do - yield stateToProdIdxsTable.ReadAll(state) ] - - let reduceTokens = - [ for (tag,action) in actions do - if actionKind(action) = reduceFlag then - yield tag - if actionKind(defaultAction) = reduceFlag then - for tag in 0 .. tables.numTerminals-1 do - if not (explicit.Contains(tag)) then - yield tag ] in - //let activeRules = stateStack |> List.iter (fun state -> - let errorContext = new ParseErrorContext<'tok>(stateStack,parseState, reduceTokens,currentToken,reducibleProductions, shiftableTokens, "syntax error") - tables.parseError(errorContext); - popStackUntilErrorShifted(None); - errorSuppressionCountDown <- 3; -#if __DEBUG - if Flags.debug then System.Console.WriteLine("generated syntax error and shifted error token, haveLookahead = {0}\n", haveLookahead); -#endif - ) - ) elif kind = acceptFlag then - finished <- true -#if __DEBUG - else - if Flags.debug then System.Console.WriteLine("ALARM!!! drop through case in parser"); -#endif - done; - // OK, we're done - read off the overall generated value - valueStack.Peep().value - -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal Tables<'tok> with -#else -type Tables<'tok> with -#endif - member tables.Interpret (lexer,lexbuf,initialState) = - Implementation.interpret tables lexer lexbuf initialState - -#if INTERNALIZED_FSLEXYACC_RUNTIME -module internal ParseHelpers = -#else -module ParseHelpers = -#endif - let parse_error (_s:string) = () - let parse_error_rich = (None : (ParseErrorContext<_> -> unit) option) diff --git a/src/fcs-fable/src/buildtools/fsyacc/Parsing.fsi b/src/fcs-fable/src/buildtools/fsyacc/Parsing.fsi deleted file mode 100644 index 2fef45975a..0000000000 --- a/src/fcs-fable/src/buildtools/fsyacc/Parsing.fsi +++ /dev/null @@ -1,130 +0,0 @@ -//========================================================================== -// (c) Microsoft Corporation 2005-2009. -//========================================================================= - -#if INTERNALIZED_FSLEXYACC_RUNTIME -namespace Internal.Utilities.Text.Parsing -open Internal.Utilities -open Internal.Utilities.Text.Lexing -#else -namespace Microsoft.FSharp.Text.Parsing -open Microsoft.FSharp.Text.Lexing -#endif - -open System.Collections.Generic - -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal IParseState = -#else -/// The information accessible via the parseState value within parser actions. -type IParseState = -#endif - /// Get the start and end position for the terminal or non-terminal at a given index matched by the production - abstract InputRange: index:int -> Position * Position - /// Get the end position for the terminal or non-terminal at a given index matched by the production - abstract InputEndPosition: int -> Position - /// Get the start position for the terminal or non-terminal at a given index matched by the production - abstract InputStartPosition: int -> Position - /// Get the full range of positions matched by the production - abstract ResultRange: Position * Position - /// Get the value produced by the terminal or non-terminal at the given position - abstract GetInput : int -> obj - /// Get the store of local values associated with this parser - // Dynamically typed, non-lexically scoped local store - abstract ParserLocalStore : IDictionary - /// Raise an error in this parse context - abstract RaiseError<'b> : unit -> 'b - - -[] -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal ParseErrorContext<'tok> = -#else -/// The context provided when a parse error occurs -type ParseErrorContext<'tok> = -#endif - /// The stack of state indexes active at the parse error - member StateStack : int list - /// The state active at the parse error - member ParseState : IParseState - /// The tokens that would cause a reduction at the parse error - member ReduceTokens: int list - /// The stack of productions that would be reduced at the parse error - member ReducibleProductions : int list list - /// The token that caused the parse error - member CurrentToken : 'tok option - /// The token that would cause a shift at the parse error - member ShiftTokens : int list - /// The message associated with the parse error - member Message : string - -/// Tables generated by fsyacc -#if INTERNALIZED_FSLEXYACC_RUNTIME -type internal Tables<'tok> = -#else -/// The type of the tables contained in a file produced by the fsyacc.exe parser generator. -type Tables<'tok> = -#endif - { /// The reduction table - reductions: (IParseState -> obj) array ; - /// The token number indicating the end of input - endOfInputTag: int; - /// A function to compute the tag of a token - tagOfToken: 'tok -> int; - /// A function to compute the data carried by a token - dataOfToken: 'tok -> obj; - /// The sparse action table elements - actionTableElements: uint16[]; - /// The sparse action table row offsets - actionTableRowOffsets: uint16[]; - /// The number of symbols for each reduction - reductionSymbolCounts: uint16[]; - /// The immediate action table - immediateActions: uint16[]; - /// The sparse goto table - gotos: uint16[]; - /// The sparse goto table row offsets - sparseGotoTableRowOffsets: uint16[]; - /// The sparse table for the productions active for each state - stateToProdIdxsTableElements: uint16[]; - /// The sparse table offsets for the productions active for each state - stateToProdIdxsTableRowOffsets: uint16[]; - /// This table is logically part of the Goto table - productionToNonTerminalTable: uint16[]; - /// This function is used to hold the user specified "parse_error" or "parse_error_rich" functions - parseError: ParseErrorContext<'tok> -> unit; - /// The total number of terminals - numTerminals: int; - /// The tag of the error terminal - tagOfErrorTerminal: int } - - /// Interpret the parser table taking input from the given lexer, using the given lex buffer, and the given start state. - /// Returns an object indicating the final synthesized value for the parse. - member Interpret : lexer:(LexBuffer<'char> -> 'tok) * lexbuf:LexBuffer<'char> * startState:int -> obj - -#if INTERNALIZED_FSLEXYACC_RUNTIME -exception internal Accept of obj -exception internal RecoverableParseError -#else -/// Indicates an accept action has occured -exception Accept of obj -/// Indicates a parse error has occured and parse recovery is in progress -exception RecoverableParseError -#endif - -#if __DEBUG -module internal Flags = - val mutable debug : bool -#endif - -#if INTERNALIZED_FSLEXYACC_RUNTIME -module internal ParseHelpers = -#else -/// Helpers used by generated parsers. -module ParseHelpers = -#endif - /// The default implementation of the parse_error_rich function - val parse_error_rich: (ParseErrorContext<'tok> -> unit) option - /// The default implementation of the parse_error function - val parse_error: string -> unit - diff --git a/src/fcs-fable/src/buildtools/fsyacc/fsyacc.fs b/src/fcs-fable/src/buildtools/fsyacc/fsyacc.fs deleted file mode 100644 index 41d816794d..0000000000 --- a/src/fcs-fable/src/buildtools/fsyacc/fsyacc.fs +++ /dev/null @@ -1,531 +0,0 @@ -(* (c) Microsoft Corporation 2005-2008. *) - -module internal FsLexYacc.FsYacc.Driver - -open System.IO -open System.Collections.Generic -open Printf -open Internal.Utilities -open Internal.Utilities.Text.Lexing - -open FsLexYacc.FsYacc -open FsLexYacc.FsYacc.AST - -//------------------------------------------------------------------ -// This code is duplicated from Microsoft.FSharp.Compiler.UnicodeLexing - -type Lexbuf = LexBuffer - -/// Standard utility to create a Unicode LexBuffer -/// -/// One small annoyance is that LexBuffers and not IDisposable. This means -/// we can't just return the LexBuffer object, since the file it wraps wouldn't -/// get closed when we're finished with the LexBuffer. Hence we return the stream, -/// the reader and the LexBuffer. The caller should dispose the first two when done. -let UnicodeFileAsLexbuf (filename,codePage : int option) : FileStream * StreamReader * Lexbuf = - // Use the .NET functionality to auto-detect the unicode encoding - // It also uses Lexing.from_text_reader to present the bytes read to the lexer in UTF8 decoded form - let stream = new FileStream(filename,FileMode.Open,FileAccess.Read,FileShare.Read) - let reader = - match codePage with - | None -> new StreamReader(stream,true) - | Some n -> new StreamReader(stream,System.Text.Encoding.GetEncoding(n)) - let lexbuf = LexBuffer.FromFunction(reader.Read) - lexbuf.EndPos <- Position.FirstLine(filename); - stream, reader, lexbuf - -//------------------------------------------------------------------ -// This is the program proper - -let input = ref None -let modname= ref None -let internal_module = ref false -let opens= ref [] -let out = ref None -let tokenize = ref false -let compat = ref false -let log = ref false -let light = ref None -let inputCodePage = ref None -let mutable lexlib = "FSharp.Text.Lexing" -let mutable parslib = "FSharp.Text.Parsing" - -let usage = - [ ArgInfo("-o", ArgType.String (fun s -> out := Some s), "Name the output file."); - ArgInfo("-v", ArgType.Unit (fun () -> log := true), "Produce a listing file."); - ArgInfo("--module", ArgType.String (fun s -> modname := Some s), "Define the F# module name to host the generated parser."); - ArgInfo("--internal", ArgType.Unit (fun () -> internal_module := true), "Generate an internal module"); - ArgInfo("--open", ArgType.String (fun s -> opens := !opens @ [s]), "Add the given module to the list of those to open in both the generated signature and implementation."); - ArgInfo("--light", ArgType.Unit (fun () -> light := Some true), "(ignored)"); - ArgInfo("--light-off", ArgType.Unit (fun () -> light := Some false), "Add #light \"off\" to the top of the generated file"); - ArgInfo("--ml-compatibility", ArgType.Set compat, "Support the use of the global state from the 'Parsing' module in FSharp.PowerPack.dll."); - ArgInfo("--tokens", ArgType.Set tokenize, "Simply tokenize the specification file itself."); - ArgInfo("--lexlib", ArgType.String (fun s -> lexlib <- s), "Specify the namespace for the implementation of the lexer (default: FSharp.Text.Lexing)"); - ArgInfo("--parslib", ArgType.String (fun s -> parslib <- s), "Specify the namespace for the implementation of the parser table interpreter (default: FSharp.Text.Parsing)"); - ArgInfo("--codepage", ArgType.Int (fun i -> inputCodePage := Some i), "Assume input lexer specification file is encoded with the given codepage."); ] - -let _ = ArgParser.Parse(usage,(fun x -> match !input with Some _ -> failwith "more than one input given" | None -> input := Some x),"fsyacc ") - -let output_int (os: #TextWriter) (n:int) = os.Write(string n) - -let outputCodedUInt16 (os: #TextWriter) (n:int) = - os.Write n; - os.Write "us; "; - -let shiftFlag = 0x0000 -let reduceFlag = 0x4000 -let errorFlag = 0x8000 -let acceptFlag = 0xc000 -let actionMask = 0xc000 - -let anyMarker = 0xffff - -let actionCoding action = - match action with - | Accept -> acceptFlag - | Shift n -> shiftFlag ||| n - | Reduce n -> reduceFlag ||| n - | Error -> errorFlag - -let main() = - let filename = (match !input with Some x -> x | None -> failwith "no input given") in - let spec = - let stream,reader,lexbuf = UnicodeFileAsLexbuf(filename, !inputCodePage) - use stream = stream - use reader = reader - - try - if !tokenize then begin - while true do - printf "tokenize - getting one token"; - let t = Lexer.token lexbuf in - (*F# printf "tokenize - got %s" (Parser.token_to_string t); F#*) - if t = Parser.EOF then exit 0; - done; - end; - - Parser.spec Lexer.token lexbuf - with e -> - eprintf "%s(%d,%d): error: %s" filename lexbuf.StartPos.Line lexbuf.StartPos.Column e.Message; - exit 1 in - - let has_extension (s:string) = - (s.Length >= 1 && s.[s.Length - 1] = '.') - || Path.HasExtension(s) - - let chop_extension (s:string) = - if not (has_extension s) then invalidArg "s" "the file name does not have an extension" - Path.Combine (Path.GetDirectoryName s,Path.GetFileNameWithoutExtension(s)) - - let checkSuffix (x:string) (y:string) = x.EndsWith(y) - - let output = match !out with Some x -> x | _ -> chop_extension filename + (if checkSuffix filename ".mly" then ".ml" else ".fs") in - let outputi = match !out with Some x -> chop_extension x + (if checkSuffix x ".ml" then ".mli" else ".fsi") | _ -> chop_extension filename + (if checkSuffix filename ".mly" then ".mli" else ".fsi") in - let outputo = - if !log then Some (match !out with Some x -> chop_extension x + ".fsyacc.output" | _ -> chop_extension filename + ".fsyacc.output") - else None - - use os = (File.CreateText output :> TextWriter) - use osi = (File.CreateText outputi :> TextWriter) - - let lineCountOutput = ref 0 - let lineCountSignature = ref 0 - let cos = (os,lineCountOutput) - let cosi = (osi,lineCountSignature) - let cprintf (os:TextWriter,lineCount) fmt = Printf.fprintf os fmt - let cprintfn (os:TextWriter,lineCount) fmt = Printf.kfprintf (fun () -> incr lineCount; os.WriteLine()) os fmt - - let logf = - match outputo with - | None -> (fun f -> ()) - | Some filename -> - let oso = (File.CreateText filename :> TextWriter) - (fun f -> f oso) - - logf (fun oso -> fprintfn oso " Output file describing compiled parser placed in %s and %s" output outputi); - - printfn " building tables"; - let spec1 = ProcessParserSpecAst spec - let (prods,states, startStates,actionTable,immediateActionTable,gotoTable,endOfInputTerminalIdx,errorTerminalIdx,nonTerminals) = - CompilerLalrParserSpec logf spec1 - - let (code,pos) = spec.Header - printfn " %d states" states.Length; - printfn " %d nonterminals" gotoTable.[0].Length; - printfn " %d terminals" actionTable.[0].Length; - printfn " %d productions" prods.Length; - printfn " #rows in action table: %d" actionTable.Length; -(* - printfn "#unique rows in action table: %d" (List.length (Array.foldBack (fun row acc -> insert (Array.to_list row) acc) actionTable [])); - printfn "maximum #different actions per state: %d" (Array.foldBack (fun row acc ->max (List.length (List.foldBack insert (Array.to_list row) [])) acc) actionTable 0); - printfn "average #different actions per state: %d" ((Array.foldBack (fun row acc -> (List.length (List.foldBack insert (Array.to_list row) [])) + acc) actionTable 0) / (Array.length states)); -*) - - cprintfn cos "// Implementation file for parser generated by fsyacc"; - cprintfn cosi "// Signature file for parser generated by fsyacc"; - - if (!light = Some(false)) || (!light = None && checkSuffix output ".ml") then - cprintfn cos "#light \"off\""; - cprintfn cosi "#light \"off\""; - - match !modname with - | None -> () - | Some s -> - match !internal_module with - | true -> - cprintfn cos "module internal %s" s; - cprintfn cosi "module internal %s" s; - | false -> - cprintfn cos "module %s" s; - cprintfn cosi "module %s" s; - - cprintfn cos "#nowarn \"64\";; // turn off warnings that type variables used in production annotations are instantiated to concrete type"; - - for s in !opens do - cprintfn cos "open %s" s; - cprintfn cosi "open %s" s; - - cprintfn cos "open %s" lexlib; - cprintfn cos "open %s.ParseHelpers" parslib; - if !compat then - cprintfn cos "open Microsoft.FSharp.Compatibility.OCaml.Parsing"; - - cprintfn cos "# %d \"%s\"" pos.pos_lnum pos.pos_fname; - cprintfn cos "%s" code; - lineCountOutput := !lineCountOutput + code.Replace("\r","").Split([| '\n' |]).Length; - - cprintfn cos "# %d \"%s\"" !lineCountOutput output; - // Print the datatype for the tokens - cprintfn cos "// This type is the type of tokens accepted by the parser"; - for out in [cos;cosi] do - cprintfn out "type token = "; - for id,typ in spec.Tokens do - match typ with - | None -> cprintfn out " | %s" id - | Some ty -> cprintfn out " | %s of (%s)" id ty; - - // Print the datatype for the token names - cprintfn cos "// This type is used to give symbolic names to token indexes, useful for error messages"; - for out in [cos;cosi] do - cprintfn out "type tokenId = "; - for id,typ in spec.Tokens do - cprintfn out " | TOKEN_%s" id; - cprintfn out " | TOKEN_end_of_input"; - cprintfn out " | TOKEN_error"; - - cprintfn cos "// This type is used to give symbolic names to token indexes, useful for error messages"; - for out in [cos;cosi] do - cprintfn out "type nonTerminalId = "; - for nt in nonTerminals do - cprintfn out " | NONTERM_%s" nt; - - cprintfn cos ""; - cprintfn cos "// This function maps tokens to integer indexes"; - cprintfn cos "let tagOfToken (t:token) = "; - cprintfn cos " match t with"; - spec.Tokens |> List.iteri (fun i (id,typ) -> - cprintfn cos " | %s %s -> %d " id (match typ with Some _ -> "_" | None -> "") i); - cprintfn cosi "/// This function maps tokens to integer indexes"; - cprintfn cosi "val tagOfToken: token -> int"; - - cprintfn cos ""; - cprintfn cos "// This function maps integer indexes to symbolic token ids"; - cprintfn cos "let tokenTagToTokenId (tokenIdx:int) = "; - cprintfn cos " match tokenIdx with"; - spec.Tokens |> List.iteri (fun i (id,typ) -> - cprintfn cos " | %d -> TOKEN_%s " i id) - cprintfn cos " | %d -> TOKEN_end_of_input" endOfInputTerminalIdx; - cprintfn cos " | %d -> TOKEN_error" errorTerminalIdx; - cprintfn cos " | _ -> failwith \"tokenTagToTokenId: bad token\"" - - cprintfn cosi ""; - cprintfn cosi "/// This function maps integer indexes to symbolic token ids"; - cprintfn cosi "val tokenTagToTokenId: int -> tokenId"; - - cprintfn cos ""; - cprintfn cos "/// This function maps production indexes returned in syntax errors to strings representing the non terminal that would be produced by that production"; - cprintfn cos "let prodIdxToNonTerminal (prodIdx:int) = "; - cprintfn cos " match prodIdx with"; - prods |> Array.iteri (fun i (nt,ntIdx,syms,code) -> - cprintfn cos " | %d -> NONTERM_%s " i nt); - cprintfn cos " | _ -> failwith \"prodIdxToNonTerminal: bad production index\"" - - cprintfn cosi ""; - cprintfn cosi "/// This function maps production indexes returned in syntax errors to strings representing the non terminal that would be produced by that production"; - cprintfn cosi "val prodIdxToNonTerminal: int -> nonTerminalId"; - - cprintfn cos ""; - cprintfn cos "let _fsyacc_endOfInputTag = %d " endOfInputTerminalIdx; - cprintfn cos "let _fsyacc_tagOfErrorTerminal = %d" errorTerminalIdx; - cprintfn cos ""; - cprintfn cos "// This function gets the name of a token as a string"; - cprintfn cos "let token_to_string (t:token) = "; - cprintfn cos " match t with "; - spec.Tokens |> List.iteri (fun i (id,typ) -> - cprintfn cos " | %s %s -> \"%s\" " id (match typ with Some _ -> "_" | None -> "") id); - - cprintfn cosi ""; - cprintfn cosi "/// This function gets the name of a token as a string"; - cprintfn cosi "val token_to_string: token -> string"; - - cprintfn cos ""; - cprintfn cos "// This function gets the data carried by a token as an object"; - cprintfn cos "let _fsyacc_dataOfToken (t:token) = "; - cprintfn cos " match t with "; - - for (id,typ) in spec.Tokens do - cprintfn cos " | %s %s -> %s " - id - (match typ with Some _ -> "_fsyacc_x" | None -> "") - (match typ with Some _ -> "Microsoft.FSharp.Core.Operators.box _fsyacc_x" | None -> "(null : System.Object)") - - let tychar = "'cty" - - for (key,_) in spec.Types |> Seq.countBy fst |> Seq.filter (fun (_,n) -> n > 1) do - failwithf "%s is given multiple %%type declarations" key; - - for (key,_) in spec.Tokens |> Seq.countBy fst |> Seq.filter (fun (_,n) -> n > 1) do - failwithf "%s is given %%token declarations" key - - let types = Map.ofList spec.Types - let tokens = Map.ofList spec.Tokens - - let nStates = states.Length - begin - cprintf cos "let _fsyacc_gotos = [| " ; - let numGotoNonTerminals = gotoTable.[0].Length - let gotoIndexes = Array.create numGotoNonTerminals 0 - let gotoTableCurrIndex = ref 0 in - for j = 0 to numGotoNonTerminals-1 do - gotoIndexes.[j] <- !gotoTableCurrIndex; - - (* Count the number of entries in the association table. *) - let count = ref 0 in - for i = 0 to nStates - 1 do - let goto = gotoTable.[i].[j] - match goto with - | None -> () - | Some _ -> incr count - - (* Write the head of the table (i.e. the number of entries and the default value) *) - gotoTableCurrIndex := !gotoTableCurrIndex + 1; - outputCodedUInt16 os !count; - outputCodedUInt16 os anyMarker; - - (* Write the pairs of entries in incremental order by key *) - (* This lets us implement the lookup by a binary chop. *) - for i = 0 to nStates - 1 do - let goto = gotoTable.[i].[j] - match goto with - | None -> () - | Some n -> - gotoTableCurrIndex := !gotoTableCurrIndex + 1; - outputCodedUInt16 os i; - outputCodedUInt16 os n; - cprintfn cos "|]" ; - (* Output offsets into gotos table where the gotos for a particular nonterminal begin *) - cprintf cos "let _fsyacc_sparseGotoTableRowOffsets = [|" ; - for j = 0 to numGotoNonTerminals-1 do - outputCodedUInt16 os gotoIndexes.[j]; - cprintfn cos "|]" ; - end; - - begin - cprintf cos "let _fsyacc_stateToProdIdxsTableElements = [| " ; - let indexes = Array.create states.Length 0 - let currIndex = ref 0 - for j = 0 to states.Length - 1 do - let state = states.[j] - indexes.[j] <- !currIndex; - - (* Write the head of the table (i.e. the number of entries) *) - outputCodedUInt16 os state.Length; - currIndex := !currIndex + state.Length + 1; - - (* Write the pairs of entries in incremental order by key *) - (* This lets us implement the lookup by a binary chop. *) - for prodIdx in state do - outputCodedUInt16 os prodIdx; - cprintfn cos "|]" ; - (* Output offsets into gotos table where the gotos for a particular nonterminal begin *) - cprintf cos "let _fsyacc_stateToProdIdxsTableRowOffsets = [|" ; - for idx in indexes do - outputCodedUInt16 os idx; - cprintfn cos "|]" ; - end; - - begin - let numActionRows = (Array.length actionTable) - let maxActionColumns = Array.length actionTable.[0] - cprintfn cos "let _fsyacc_action_rows = %d" numActionRows; - cprintf cos "let _fsyacc_actionTableElements = [|" ; - let actionIndexes = Array.create numActionRows 0 - - let actionTableCurrIndex = ref 0 - for i = 0 to nStates-1 do - actionIndexes.[i] <- !actionTableCurrIndex; - let actions = actionTable.[i] - let terminalsByAction = new Dictionary<_,int list>(10) - let countPerAction = new Dictionary<_,_>(10) - for terminal = 0 to actions.Length - 1 do - let action = snd actions.[terminal] - if terminalsByAction.ContainsKey action then - terminalsByAction.[action] <- terminal :: terminalsByAction.[action] ; - else - terminalsByAction.[action] <- [terminal]; - if countPerAction.ContainsKey action then - countPerAction.[action] <- countPerAction.[action]+1 - else - countPerAction.[action] <- 1 - - let mostCommonAction = - let mostCommon = ref Error - let max = ref 0 - for (KeyValue(x,y)) in countPerAction do - if y > !max then (mostCommon := x; max := y) - !mostCommon - - (* Count the number of entries in the association table. *) - let count = ref 0 - for (KeyValue(action,terminals)) in terminalsByAction do - for terminals in terminals do - if action <> mostCommonAction then - incr count; - - (* Write the head of the table (i.e. the number of entries and the default value) *) - actionTableCurrIndex := !actionTableCurrIndex + 1; - outputCodedUInt16 os !count; - outputCodedUInt16 os (actionCoding mostCommonAction); - - (* Write the pairs of entries in incremental order by key *) - (* This lets us implement the lookup by a binary chop. *) - for terminal = 0 to Array.length actions-1 do - let action = snd actions.[terminal] in - if action <> mostCommonAction then ( - actionTableCurrIndex := !actionTableCurrIndex + 1; - outputCodedUInt16 os terminal; - outputCodedUInt16 os (actionCoding action); - ); - cprintfn cos "|]" ; - (* Output offsets into actions table where the actions for a particular nonterminal begin *) - cprintf cos "let _fsyacc_actionTableRowOffsets = [|" ; - for j = 0 to numActionRows-1 do - cprintf cos "%a" outputCodedUInt16 actionIndexes.[j]; - cprintfn cos "|]" ; - - end; - begin - cprintf cos "let _fsyacc_reductionSymbolCounts = [|" ; - for nt,ntIdx,syms,code in prods do - cprintf cos "%a" outputCodedUInt16 (List.length syms); - cprintfn cos "|]" ; - end; - begin - cprintf cos "let _fsyacc_productionToNonTerminalTable = [|" ; - for nt,ntIdx,syms,code in prods do - cprintf cos "%a" outputCodedUInt16 ntIdx; - cprintfn cos "|]" ; - end; - begin - cprintf cos "let _fsyacc_immediateActions = [|" ; - for prodIdx in immediateActionTable do - match prodIdx with - | None -> cprintf cos "%a" outputCodedUInt16 anyMarker (* NONE REP *) - | Some act -> cprintf cos "%a" outputCodedUInt16 (actionCoding act) - cprintfn cos "|]" ; - end; - - let getType nt = if types.ContainsKey nt then types.[nt] else "'"+nt - begin - cprintf cos "let _fsyacc_reductions () =" ; - cprintfn cos " [| " ; - for nt,ntIdx,syms,code in prods do - cprintfn cos "# %d \"%s\"" !lineCountOutput output; - cprintfn cos " (fun (parseState : %s.IParseState) ->" parslib - if !compat then - cprintfn cos " Parsing.set_parse_state parseState;" - syms |> List.iteri (fun i sym -> - let tyopt = - match sym with - | Terminal t -> - if tokens.ContainsKey t then - tokens.[t] - else None - | NonTerminal nt -> Some (getType nt) - match tyopt with - | Some ty -> cprintfn cos " let _%d = (let data = parseState.GetInput(%d) in (Microsoft.FSharp.Core.Operators.unbox data : %s)) in" (i+1) (i+1) ty - | None -> ()) - cprintfn cos " Microsoft.FSharp.Core.Operators.box" - cprintfn cos " ("; - cprintfn cos " ("; - match code with - | Some (_,pos) -> cprintfn cos "# %d \"%s\"" pos.pos_lnum pos.pos_fname - | None -> () - match code with - | Some (code,_) -> - let dollar = ref false in - let c = code |> String.collect (fun c -> - if not !dollar && c = '$' then (dollar := true; "") - elif !dollar && c >= '0' && c <= '9' then (dollar := false; "_"+new System.String(c,1)) - elif !dollar then (dollar := false; "$"+new System.String(c,1)) - else new System.String(c,1)) - let lines = c.Split([| '\r'; '\n' |], System.StringSplitOptions.RemoveEmptyEntries); - for line in lines do - cprintfn cos " %s" line; - if !dollar then os.Write '$' - | None -> - cprintfn cos " raise (%s.Accept(Microsoft.FSharp.Core.Operators.box _1))" parslib - cprintfn cos " )"; - // Place the line count back for the type constraint - match code with - | Some (_,pos) -> cprintfn cos "# %d \"%s\"" pos.pos_lnum pos.pos_fname - | None -> () - cprintfn cos " : %s));" (if types.ContainsKey nt then types.[nt] else "'"+nt); - done; - cprintfn cos "|]" ; - end; - cprintfn cos "# %d \"%s\"" !lineCountOutput output; - cprintfn cos "let tables () : %s.Tables<_> = " parslib - cprintfn cos " { reductions= _fsyacc_reductions ();" - cprintfn cos " endOfInputTag = _fsyacc_endOfInputTag;" - cprintfn cos " tagOfToken = tagOfToken;" - cprintfn cos " dataOfToken = _fsyacc_dataOfToken; " - cprintfn cos " actionTableElements = _fsyacc_actionTableElements;" - cprintfn cos " actionTableRowOffsets = _fsyacc_actionTableRowOffsets;" - cprintfn cos " stateToProdIdxsTableElements = _fsyacc_stateToProdIdxsTableElements;" - cprintfn cos " stateToProdIdxsTableRowOffsets = _fsyacc_stateToProdIdxsTableRowOffsets;" - cprintfn cos " reductionSymbolCounts = _fsyacc_reductionSymbolCounts;" - cprintfn cos " immediateActions = _fsyacc_immediateActions;" - cprintfn cos " gotos = _fsyacc_gotos;" - cprintfn cos " sparseGotoTableRowOffsets = _fsyacc_sparseGotoTableRowOffsets;" - cprintfn cos " tagOfErrorTerminal = _fsyacc_tagOfErrorTerminal;" - cprintfn cos " parseError = (fun (ctxt:%s.ParseErrorContext<_>) -> " parslib - cprintfn cos " match parse_error_rich with " - cprintfn cos " | Some f -> f ctxt" - cprintfn cos " | None -> parse_error ctxt.Message);" - - cprintfn cos " numTerminals = %d;" (Array.length actionTable.[0]); - cprintfn cos " productionToNonTerminalTable = _fsyacc_productionToNonTerminalTable }" - cprintfn cos "let engine lexer lexbuf startState = (tables ()).Interpret(lexer, lexbuf, startState)" - - for (id,startState) in List.zip spec.StartSymbols startStates do - if not (types.ContainsKey id) then - failwith ("a %type declaration is required for for start token "+id); - let ty = types.[id] in - cprintfn cos "let %s lexer lexbuf : %s =" id ty; - cprintfn cos " Microsoft.FSharp.Core.Operators.unbox ((tables ()).Interpret(lexer, lexbuf, %d))" startState - - for id in spec.StartSymbols do - if not (types.ContainsKey id) then - failwith ("a %type declaration is required for start token "+id); - let ty = types.[id] in - cprintfn cosi "val %s : (%s.LexBuffer<%s> -> token) -> %s.LexBuffer<%s> -> (%s) " id lexlib tychar lexlib tychar ty; - - logf (fun oso -> oso.Close()) - -let result = - try main() - with e -> - eprintf "FSYACC: error FSY000: %s" (match e with Failure s -> s | e -> e.Message); - exit 1 - diff --git a/src/fcs-fable/src/buildtools/fsyacc/fsyacc.fsproj b/src/fcs-fable/src/buildtools/fsyacc/fsyacc.fsproj deleted file mode 100644 index 286c7a4eb1..0000000000 --- a/src/fcs-fable/src/buildtools/fsyacc/fsyacc.fsproj +++ /dev/null @@ -1,22 +0,0 @@ - - - - Exe - netcoreapp2.0 - INTERNALIZED_FSLEXYACC_RUNTIME;$(DefineConstant) - - - - - - - - - - - - - - - - diff --git a/src/fcs-fable/src/buildtools/fsyacc/fsyaccast.fs b/src/fcs-fable/src/buildtools/fsyacc/fsyaccast.fs deleted file mode 100644 index deb2d3ef8a..0000000000 --- a/src/fcs-fable/src/buildtools/fsyacc/fsyaccast.fs +++ /dev/null @@ -1,1000 +0,0 @@ -// (c) Microsoft Corporation 2005-2007. - -module internal FsLexYacc.FsYacc.AST - -#nowarn "62" // This construct is for ML compatibility. - - -open System -open System.Collections.Generic -open Printf -open Microsoft.FSharp.Collections -open Internal.Utilities -open Internal.Utilities.Text.Lexing - -/// An active pattern that should be in the F# standard library -let (|KeyValue|) (kvp:KeyValuePair<_,_>) = kvp.Key,kvp.Value - - -type Identifier = string -type Code = string * Position - -type ParserSpec= - { Header : Code; - Tokens : (Identifier * string option) list; - Types : (Identifier * string) list; - Associativities: (Identifier * Associativity) list list; - StartSymbols : Identifier list; - Rules : (Identifier * Rule list) list } - -and Rule = Rule of Identifier list * Identifier option * Code option -and Associativity = LeftAssoc | RightAssoc | NonAssoc - -type Terminal = string -type NonTerminal = string -type Symbol = Terminal of Terminal | NonTerminal of NonTerminal -type Symbols = Symbol list - - -//--------------------------------------------------------------------- -// Output Raw Parser Spec AST - -let StringOfSym sym = match sym with Terminal s -> "'" ^ s ^ "'" | NonTerminal s -> s - -let OutputSym os sym = fprintf os "%s" (StringOfSym sym) - -let OutputSyms os syms = - fprintf os "%s" (String.Join(" ",Array.map StringOfSym syms)) - -let OutputTerminalSet os (tset:string seq) = - fprintf os "%s" (String.Join(";", tset |> Seq.toArray)) - -let OutputAssoc os p = - match p with - | LeftAssoc -> fprintf os "left" - | RightAssoc -> fprintf os "right" - | NonAssoc -> fprintf os "nonassoc" - - -//--------------------------------------------------------------------- -// PreProcess Raw Parser Spec AST - -type PrecedenceInfo = - | ExplicitPrec of Associativity * int - | NoPrecedence - -type Production = Production of NonTerminal * PrecedenceInfo * Symbols * Code option - -type ProcessedParserSpec = - { Terminals: (Terminal * PrecedenceInfo) list; - NonTerminals: NonTerminal list; - Productions: Production list; - StartSymbols: NonTerminal list } - - -let ProcessParserSpecAst (spec: ParserSpec) = - let explicitPrecInfo = - spec.Associativities - |> List.mapi (fun n precSpecs -> precSpecs |> List.map (fun (precSym, assoc) -> precSym,ExplicitPrec (assoc, 10000 - n))) - |> List.concat - - for (key,_) in explicitPrecInfo |> Seq.countBy fst |> Seq.filter (fun (_,n) -> n > 1) do - failwithf "%s is given two associativities" key - - let explicitPrecInfo = - explicitPrecInfo |> Map.ofList - - let implicitSymPrecInfo = NoPrecedence - let terminals = List.map fst spec.Tokens @ ["error"]in - let terminalSet = Set.ofList terminals - let IsTerminal z = terminalSet.Contains(z) - let prec_of_terminal sym implicitPrecInfo = - if explicitPrecInfo.ContainsKey(sym) then explicitPrecInfo.[sym] - else match implicitPrecInfo with Some x -> x | None -> implicitSymPrecInfo - - let mkSym s = if IsTerminal s then Terminal s else NonTerminal s - let prods = - spec.Rules |> List.mapi (fun i (nonterm,rules) -> - rules |> List.mapi (fun j (Rule(syms,precsym,code)) -> - let precInfo = - let precsym = List.foldBack (fun x acc -> match acc with Some _ -> acc | None -> match x with z when IsTerminal z -> Some z | _ -> acc) syms precsym - let implicitPrecInfo = NoPrecedence - match precsym with - | None -> implicitPrecInfo - | Some sym -> if explicitPrecInfo.ContainsKey(sym) then explicitPrecInfo.[sym] else implicitPrecInfo - Production(nonterm, precInfo, List.map mkSym syms, code))) - |> List.concat - let nonTerminals = List.map fst spec.Rules - let nonTerminalSet = Set.ofList nonTerminals - let checkNonTerminal nt = - if nt <> "error" && not (nonTerminalSet.Contains(nt)) then - failwith (sprintf "NonTerminal '%s' has no productions" nt) - - for (Production(nt,_,syms,_)) in prods do - for sym in syms do - match sym with - | NonTerminal nt -> - checkNonTerminal nt - | Terminal t -> - if not (IsTerminal t) then failwith (sprintf "token %s is not declared" t) - - if spec.StartSymbols= [] then (failwith "at least one %start declaration is required"); - - for (nt,_) in spec.Types do - checkNonTerminal nt; - - let terminals = terminals |> List.map (fun t -> (t,prec_of_terminal t None)) - - { Terminals=terminals; - NonTerminals=nonTerminals; - Productions=prods; - StartSymbols=spec.StartSymbols } - - -//------------------------------------------------- -// Process LALR(1) grammars to tables - -type ProductionIndex = int -type ProdictionDotIndex = int - -/// Represent (ProductionIndex,ProdictionDotIndex) as one integer -type Item0 = uint32 - -let mkItem0 (prodIdx,dotIdx) : Item0 = (uint32 prodIdx <<< 16) ||| uint32 dotIdx -let prodIdx_of_item0 (item0:Item0) = int32 (item0 >>> 16) -let dotIdx_of_item0 (item0:Item0) = int32 (item0 &&& 0xFFFFu) - -/// Part of the output of CompilerLalrParserSpec -type Action = - | Shift of int - | Reduce of ProductionIndex - | Accept - | Error - -let outputPrecInfo os p = - match p with - | ExplicitPrec (assoc,n) -> fprintf os "explicit %a %d" OutputAssoc assoc n - | NoPrecedence -> fprintf os "noprec" - - -/// LR(0) kernels -type Kernel = Set - -/// Indexes of LR(0) kernels in the KernelTable -type KernelIdx = int - -/// Indexes in the TerminalTable and NonTerminalTable -type TerminalIndex = int -type NonTerminalIndex = int - -/// Representation of Symbols. -/// Ideally would be declared as -/// type SymbolIndex = PTerminal of TerminalIndex | PNonTerminal of NonTerminalIndex -/// but for performance reasons we embed as a simple integer (saves ~10%) -/// -/// We use an active pattern to reverse the embedding. -type SymbolIndex = int -let PTerminal(i:TerminalIndex) : SymbolIndex = -i-1 -let PNonTerminal(i:NonTerminalIndex) : SymbolIndex = i -let (|PTerminal|PNonTerminal|) x = if x < 0 then PTerminal (-(x+1)) else PNonTerminal x - -type SymbolIndexes = SymbolIndex list - -/// Indexes in the LookaheadTable, SpontaneousTable, PropagateTable -/// Embed in a single integer, since these are faster -/// keys for the dictionary hash tables -/// -/// Logically: -/// -/// type KernelItemIndex = KernelItemIdx of KernelIdx * Item0 -type KernelItemIndex = int64 -let KernelItemIdx (i1,i2) = ((int64 i1) <<< 32) ||| int64 i2 - - -/// Indexes into the memoizing table for the Goto computations -/// Embed in a single integer, since these are faster -/// keys for the dictionary hash tables -/// -/// Logically: -/// -/// type GotoItemIndex = GotoItemIdx of KernelIdx * SymbolIndex -type GotoItemIndex = uint64 -let GotoItemIdx (i1:KernelIdx,i2:SymbolIndex) = (uint64 (uint32 i1) <<< 32) ||| uint64 (uint32 i2) -let (|GotoItemIdx|) (i64:uint64) = int32 ((i64 >>> 32) &&& 0xFFFFFFFFUL), int32 (i64 &&& 0xFFFFFFFFUL) - -/// Create a work list and loop until it is exhausted, calling a worker function for -/// each element. Pass a function to queue additional work on the work list -/// to the worker function -let ProcessWorkList start f = - let work = ref (start : 'a list) - let queueWork = (fun x -> work := x :: !work) - let rec loop() = - match !work with - | [] -> () - | x::t -> - work := t; - f queueWork x; - loop() - loop() - -/// A standard utility to compute a least fixed point of a set under a generative computation -let LeastFixedPoint f set = - let acc = ref set - ProcessWorkList (Set.toList set) (fun queueWork item -> - f(item) |> List.iter (fun i2 -> if not (Set.contains i2 !acc) then (acc := Set.add i2 !acc; queueWork i2)) ) - !acc - -/// A general standard memoization utility. Be sure to apply to only one (function) argument to build the -/// residue function! -let Memoize f = - let t = new Dictionary<_,_>(1000) - fun x -> - let ok,v = t.TryGetValue(x) - if ok then v else let res = f x in t.[x] <- res; res - -/// A standard utility to create a dictionary from a list of pairs -let CreateDictionary xs = - let dict = new Dictionary<_,_>() - for x,y in xs do dict.Add(x,y) - dict - -/// Allocate indexes for each non-terminal -type NonTerminalTable(nonTerminals:NonTerminal list) = - let nonterminalsWithIdxs = List.mapi (fun (i:NonTerminalIndex) n -> (i,n)) nonTerminals - let nonterminalIdxs = List.map fst nonterminalsWithIdxs - let a = Array.ofList nonTerminals - let b = CreateDictionary [ for i,x in nonterminalsWithIdxs -> x,i ]; - member table.OfIndex(i) = a.[i] - member table.ToIndex(i) = b.[i] - member table.Indexes = nonterminalIdxs - -/// Allocate indexes for each terminal -type TerminalTable(terminals:(Terminal * PrecedenceInfo) list) = - let terminalsWithIdxs = List.mapi (fun i (t,_) -> (i,t)) terminals - let terminalIdxs = List.map fst terminalsWithIdxs - let a = Array.ofList (List.map fst terminals) - let b = Array.ofList (List.map snd terminals) - let c = CreateDictionary [ for i,x in terminalsWithIdxs -> x,i ] - - member table.OfIndex(i) = a.[i] - member table.PrecInfoOfIndex(i) = b.[i] - member table.ToIndex(i) = c.[i] - member table.Indexes = terminalIdxs - -/// Allocate indexes for each production -type ProductionTable(ntTab:NonTerminalTable, termTab:TerminalTable, nonTerminals:string list, prods: Production list) = - let prodsWithIdxs = List.mapi (fun i n -> (i,n)) prods - let a = - prodsWithIdxs - |> List.map(fun (_,Production(_,_,syms,_)) -> - syms - |> Array.ofList - |> Array.map (function - | Terminal t -> PTerminal (termTab.ToIndex t) - | NonTerminal nt -> PNonTerminal (ntTab.ToIndex nt )) ) - |> Array.ofList - let b = Array.ofList (List.map (fun (_,Production(nt,_,_,_)) -> ntTab.ToIndex nt) prodsWithIdxs) - let c = Array.ofList (List.map (fun (_,Production(_,prec,_,_)) -> prec) prodsWithIdxs) - let productions = - nonTerminals - |> List.map(fun nt -> (ntTab.ToIndex nt, List.choose (fun (i,Production(nt2,prec,syms,_)) -> if nt2=nt then Some i else None) prodsWithIdxs)) - |> CreateDictionary - - member prodTab.Symbols(i) = a.[i] - member prodTab.NonTerminal(i) = b.[i] - member prodTab.Precedence(i) = c.[i] - member prodTab.Symbol i n = - let syms = prodTab.Symbols i - if n >= syms.Length then None else Some (syms.[n]) - member prodTab.Productions = productions - -/// A mutable table maping kernels to sets of lookahead tokens -type LookaheadTable() = - let t = new Dictionary>() - member table.Add(x,y) = - let prev = if t.ContainsKey(x) then t.[x] else Set.empty - t.[x] <- prev.Add(y) - member table.Contains(x,y) = t.ContainsKey(x) && t.[x].Contains(y) - member table.GetLookaheads(idx:KernelItemIndex) = - let ok,v = t.TryGetValue(idx) - if ok then v else Set.empty - member table.Count = t |> Seq.fold(fun acc (KeyValue(_,v)) -> v.Count+acc) 0 - -/// A mutable table giving an index to each LR(0) kernel. Kernels are referred to only by index. -type KernelTable(kernels) = - // Give an index to each LR(0) kernel, and from now on refer to them only by index - // Also develop "kernelItemIdx" to refer to individual items within a kernel - let kernelsAndIdxs = List.mapi (fun i x -> (i,x)) kernels - let kernelIdxs = List.map fst kernelsAndIdxs - let toIdxMap = Map.ofList [ for i,x in kernelsAndIdxs -> x,i ] - let ofIdxMap = Array.ofList kernels - member t.Indexes = kernelIdxs - member t.Index(kernel) = toIdxMap.[kernel] - member t.Kernel(i) = ofIdxMap.[i] - -/// Hold the results of cpmuting the LALR(1) closure of an LR(0) kernel -type Closure1Table() = - let t = new Dictionary>() - member table.Add(a,b) = - if not (t.ContainsKey(a)) then t.[a] <- new HashSet<_>(HashIdentity.Structural) - t.[a].Add(b) - member table.Count = t.Count - member table.IEnumerable = (t :> seq<_>) - member table.Contains(a,b) = t.ContainsKey(a) && t.[a].Contains(b) - -/// A mutable table giving a lookahead set Set for each kernel. The terminals represent the -/// "spontaneous" items for the kernel. TODO: document this more w.r.t. the Dragon book. -type SpontaneousTable() = - let t = new Dictionary>() - member table.Add(a,b) = - if not (t.ContainsKey(a)) then t.[a] <- new HashSet<_>(HashIdentity.Structural) - t.[a].Add(b) - member table.Count = t.Count - member table.IEnumerable = (t :> seq<_>) - -/// A mutable table giving a Set for each kernel. The kernels represent the -/// "propagate" items for the kernel. TODO: document this more w.r.t. the Dragon book. -type PropagateTable() = - let t = new Dictionary>() - member table.Add(a,b) = - if not (t.ContainsKey(a)) then t.[a] <- new HashSet(HashIdentity.Structural) - t.[a].Add(b) - member table.Item - with get(a) = - let ok,v = t.TryGetValue(a) - if ok then v :> seq<_> else Seq.empty - member table.Count = t.Count - - -/// Compile a pre-processed LALR parser spec to tables following the Dragon book algorithm -let CompilerLalrParserSpec logf (spec : ProcessedParserSpec) = - let stopWatch = new System.Diagnostics.Stopwatch() - let reportTime() = printfn " time: %A" stopWatch.Elapsed; stopWatch.Reset(); stopWatch.Start() - stopWatch.Start() - - // Augment the grammar - let fakeStartNonTerminals = spec.StartSymbols |> List.map(fun nt -> "_start"^nt) - let nonTerminals = fakeStartNonTerminals@spec.NonTerminals - let endOfInputTerminal = "$$" - let dummyLookahead = "#" - let dummyPrec = NoPrecedence - let terminals = spec.Terminals @ [(dummyLookahead,dummyPrec); (endOfInputTerminal,dummyPrec)] - let prods = List.map2 (fun a b -> Production(a, dummyPrec,[NonTerminal b],None)) fakeStartNonTerminals spec.StartSymbols @ spec.Productions - let startNonTerminalIdx_to_prodIdx (i:int) = i - - // Build indexed tables - let ntTab = NonTerminalTable(nonTerminals) - let termTab = TerminalTable(terminals) - let prodTab = ProductionTable(ntTab,termTab,nonTerminals,prods) - let dummyLookaheadIdx = termTab.ToIndex dummyLookahead - let endOfInputTerminalIdx = termTab.ToIndex endOfInputTerminal - - let errorTerminalIdx = termTab.ToIndex "error" - - // Compute the FIRST function - printf "computing first function..."; stdout.Flush(); - - let computedFirstTable = - let seed = - Map.ofList - [ for term in termTab.Indexes do yield (PTerminal(term),Set.singleton (Some term)) - for nonTerm in ntTab.Indexes do - yield - (PNonTerminal nonTerm, - List.foldBack - (fun prodIdx acc -> match prodTab.Symbol prodIdx 0 with None -> Set.add None acc | Some _ -> acc) - prodTab.Productions.[nonTerm] - Set.empty) ] - - let add changed ss (x,y) = - let s = Map.find x ss - if Set.contains y s then ss - else (changed := true; Map.add x (Set.add y s) ss) - - let oneRound (ss:Map<_,_>) = - let changed = ref false - let frontier = - let res = ref [] - for nonTermX in ntTab.Indexes do - for prodIdx in prodTab.Productions.[nonTermX] do - let rhs = Array.toList (prodTab.Symbols prodIdx) - let rec place l = - match l with - | (yi::t) -> - res := - List.choose - (function None -> None | Some a -> Some (PNonTerminal nonTermX,Some a)) - (Set.toList ss.[yi]) - @ !res; - if ss.[yi].Contains(None) then place t; - | [] -> - res := (PNonTerminal nonTermX,None) :: !res - place rhs - !res - let ss' = List.fold (add changed) ss frontier - !changed, ss' - - let rec loop ss = - let changed, ss' = oneRound ss - if changed then loop ss' else ss' - loop seed - - - /// Compute the first set of the given sequence of non-terminals. If any of the non-terminals - /// have an empty token in the first set then we have to iterate through those. - let ComputeFirstSetOfTokenList = - Memoize (fun (str,term) -> - let acc = new System.Collections.Generic.List<_>() - let rec add l = - match l with - | [] -> acc.Add(term) - | sym::moreSyms -> - let firstSetOfSym = computedFirstTable.[sym] - firstSetOfSym |> Set.iter (function None -> () | Some v -> acc.Add(v)) - if firstSetOfSym.Contains(None) then add moreSyms - add str; - Set.ofSeq acc) - - // (int,int) representation of LR(0) items - let prodIdx_to_item0 idx = mkItem0(idx,0) - let prec_of_item0 item0 = prodTab.Precedence (prodIdx_of_item0 item0) - let ntIdx_of_item0 item0 = prodTab.NonTerminal (prodIdx_of_item0 item0) - - let lsyms_of_item0 item0 = - let prodIdx = prodIdx_of_item0 item0 - let dotIdx = dotIdx_of_item0 item0 - let syms = prodTab.Symbols prodIdx - if dotIdx <= 0 then [||] else syms.[..dotIdx-1] - - let rsyms_of_item0 item0 = - let prodIdx = prodIdx_of_item0 item0 - let dotIdx = dotIdx_of_item0 item0 - let syms = prodTab.Symbols prodIdx - syms.[dotIdx..] - - let rsym_of_item0 item0 = - let prodIdx = prodIdx_of_item0 item0 - let dotIdx = dotIdx_of_item0 item0 - prodTab.Symbol prodIdx dotIdx - - let advance_of_item0 item0 = - let prodIdx = prodIdx_of_item0 item0 - let dotIdx = dotIdx_of_item0 item0 - mkItem0(prodIdx,dotIdx+1) - let fakeStartNonTerminalsSet = Set.ofList (fakeStartNonTerminals |> List.map ntTab.ToIndex) - - let IsStartItem item0 = fakeStartNonTerminalsSet.Contains(ntIdx_of_item0 item0) - let IsKernelItem item0 = (IsStartItem item0 || dotIdx_of_item0 item0 <> 0) - - let StringOfSym sym = match sym with PTerminal s -> "'" ^ termTab.OfIndex s ^ "'" | PNonTerminal s -> ntTab.OfIndex s - - let OutputSym os sym = fprintf os "%s" (StringOfSym sym) - - let OutputSyms os syms = - fprintf os "%s" (String.Join(" ",Array.map StringOfSym syms)) - - // Print items and other stuff - let OutputItem0 os item0 = - fprintf os " %s -> %a . %a" (ntTab.OfIndex (ntIdx_of_item0 item0)) (* outputPrecInfo precInfo *) OutputSyms (lsyms_of_item0 item0) OutputSyms (rsyms_of_item0 item0) - - let OutputItem0Set os s = - Set.iter (fun item -> fprintfn os "%a" OutputItem0 item) s - - let OutputFirstSet os m = - Set.iter (function None -> fprintf os "" | Some x -> fprintfn os " term %s" x) m - - let OutputFirstMap os m = - Map.iter (fun x y -> fprintf os "first '%a' = " OutputSym x; fprintfn os "%a" OutputFirstSet y) m - - let OutputAction os m = - match m with - | Shift n -> fprintf os " shift %d" n - | Reduce prodIdx -> fprintf os " reduce %s --> %a" (ntTab.OfIndex (prodTab.NonTerminal prodIdx)) OutputSyms (prodTab.Symbols prodIdx) - | Error -> fprintf os " error" - | Accept -> fprintf os " accept" - - let OutputActions os m = - Array.iteri (fun i (prec,action) -> let term = termTab.OfIndex i in fprintfn os " action '%s' (%a): %a" term outputPrecInfo prec OutputAction action) m - - let OutputActionTable os m = - Array.iteri (fun i n -> fprintfn os "state %d:" i; fprintfn os "%a" OutputActions n) m - - let OutputImmediateActions os m = - match m with - | None -> fprintf os "" - | Some a -> OutputAction os a - - let OutputGotos os m = - Array.iteri (fun ntIdx s -> let nonterm = ntTab.OfIndex ntIdx in match s with Some st -> fprintfn os " goto %s: %d" nonterm st | None -> ()) m - - let OutputCombined os m = - Array.iteri (fun i (a,b,c,d) -> - fprintf os "state %d:" i - fprintf os " items:" - fprintf os "%a" OutputItem0Set a - fprintf os " actions:" - fprintf os "%a" OutputActions b - fprintf os " immediate action: " - fprintf os "%a" OutputImmediateActions c - fprintf os " gotos:" - fprintf os "%a" OutputGotos d) m - - let OutputLalrTables os (prods,states, startStates,actionTable,immediateActionTable,gotoTable,endOfInputTerminalIdx,errorTerminalIdx) = - let combined = Array.ofList (List.map2 (fun x (y,(z,w)) -> x,y,z,w) (Array.toList states) (List.zip (Array.toList actionTable) (List.zip (Array.toList immediateActionTable) (Array.toList gotoTable)))) - fprintfn os "------------------------"; - fprintfn os "states = "; - fprintfn os "%a" OutputCombined combined; - fprintfn os "startStates = %s" (String.Join(";",Array.ofList (List.map string startStates))); - fprintfn os "------------------------" - - - // Closure of LR(0) nonTerminals, items etc - let ComputeClosure0NonTerminal = - Memoize (fun nt -> - let seed = (List.foldBack (prodIdx_to_item0 >> Set.add) prodTab.Productions.[nt] Set.empty) - LeastFixedPoint - (fun item0 -> - match rsym_of_item0 item0 with - | None -> [] - | Some(PNonTerminal ntB) -> List.map prodIdx_to_item0 prodTab.Productions.[ntB] - | Some(PTerminal _) -> []) - seed) - - // Close a symbol under epsilon moves - let ComputeClosure0Symbol rsym acc = - match rsym with - | Some (PNonTerminal nt) -> Set.union (ComputeClosure0NonTerminal nt) acc - | _ -> acc - - // Close a set under epsilon moves - let ComputeClosure0 iset = - Set.fold (fun acc x -> ComputeClosure0Symbol (rsym_of_item0 x) acc) iset iset - - // Right symbols after closing under epsilon moves - let RelevantSymbolsOfKernel kernel = - let kernelClosure0 = ComputeClosure0 kernel - Set.fold (fun acc x -> Option.fold (fun acc x -> Set.add x acc) acc (rsym_of_item0 x)) Set.empty kernelClosure0 - - // Goto set of a kernel of LR(0) nonTerminals, items etc - // Input is kernel, output is kernel - let ComputeGotosOfKernel iset sym = - let isetClosure = ComputeClosure0 iset - let acc = new System.Collections.Generic.List<_>(10) - isetClosure |> Set.iter (fun item0 -> - match rsym_of_item0 item0 with - | Some sym2 when sym = sym2 -> acc.Add(advance_of_item0 item0) - | _ -> ()) - Set.ofSeq acc - - // Build the full set of LR(0) kernels - reportTime(); printf "building kernels..."; stdout.Flush(); - let startItems = List.mapi (fun i _ -> prodIdx_to_item0 (startNonTerminalIdx_to_prodIdx i)) fakeStartNonTerminals - let startKernels = List.map Set.singleton startItems - let kernels = - - /// We use a set-of-sets here. F# sets support structural comparison but at the time of writing - /// did not structural hashing. - let acc = ref Set.empty - ProcessWorkList startKernels (fun addToWorkList kernel -> - if not ((!acc).Contains(kernel)) then - acc := (!acc).Add(kernel); - for csym in RelevantSymbolsOfKernel kernel do - let gotoKernel = ComputeGotosOfKernel kernel csym - assert (gotoKernel.Count > 0) - addToWorkList gotoKernel ) - - !acc |> Seq.toList |> List.map (Set.filter IsKernelItem) - - reportTime(); printf "building kernel table..."; stdout.Flush(); - // Give an index to each LR(0) kernel, and from now on refer to them only by index - let kernelTab = new KernelTable(kernels) - let startKernelIdxs = List.map kernelTab.Index startKernels - let startKernelItemIdxs = List.map2 (fun a b -> KernelItemIdx(a,b)) startKernelIdxs startItems - - let outputKernelItemIdx os (kernelIdx,item0) = - fprintf os "kernel %d, item %a" kernelIdx OutputItem0 item0 - - /// A cached version of the "goto" computation on LR(0) kernels - let gotoKernel = - Memoize (fun (GotoItemIdx(kernelIdx,sym)) -> - let gset = ComputeGotosOfKernel (kernelTab.Kernel kernelIdx) sym - if gset.IsEmpty then None else Some (kernelTab.Index gset)) - - /// Iterate (iset,sym) pairs such that (gotoKernel kernelIdx sym) is not empty - let IterateGotosOfKernel kernelIdx f = - for sym in RelevantSymbolsOfKernel (kernelTab.Kernel kernelIdx) do - match gotoKernel (GotoItemIdx(kernelIdx,sym)) with - | None -> () - | Some k -> f sym k - - - // This is used to compute the closure of an LALR(1) kernel - // - // For each item [A --> X.BY, a] in I - // For each production B -> g in G' - // For each terminal b in FIRST(Ya) - // such that [B --> .g, b] is not in I do - // add [B --> .g, b] to I - - let ComputeClosure1 iset = - let acc = new Closure1Table() - ProcessWorkList iset (fun addToWorkList (item0,pretokens:Set) -> - pretokens |> Set.iter (fun pretoken -> - if not (acc.Contains(item0,pretoken)) then - acc.Add(item0,pretoken) |> ignore - let rsyms = rsyms_of_item0 item0 - if rsyms.Length > 0 then - match rsyms.[0] with - | (PNonTerminal ntB) -> - let firstSet = ComputeFirstSetOfTokenList (Array.toList rsyms.[1..],pretoken) - for prodIdx in prodTab.Productions.[ntB] do - addToWorkList (prodIdx_to_item0 prodIdx,firstSet) - | PTerminal _ -> ())) - acc - - // Compute the "spontaneous" and "propagate" maps for each LR(0) kernelItem - // - // Input: The kernal K of a set of LR(0) items I and a grammar symbol X - // - // Output: The lookaheads generated spontaneously by items in I for kernel items - // in goto(I,X) and the items I from which lookaheads are propagated to kernel - // items in goto(I,X) - // - // Method - // 1. Construct LR(0) kernel items (done - above) - // 2. - // TODO: this is very, very slow. - // - // PLAN TO OPTIMIZE THIS; - // - Clarify and comment what's going on here - // - verify if we really have to do these enormouos closure computations - // - assess if it's possible to use the symbol we're looking for to help trim the jset - - reportTime(); printf "computing lookahead relations..."; stdout.Flush(); - - - let spontaneous, propagate = - let closure1OfItem0WithDummy = - Memoize (fun item0 -> ComputeClosure1 [(item0,Set.ofList [dummyLookaheadIdx])]) - - let spontaneous = new SpontaneousTable() - let propagate = new PropagateTable() - let count = ref 0 - - for kernelIdx in kernelTab.Indexes do - printf "."; stdout.Flush(); - //printf "kernelIdx = %d\n" kernelIdx; stdout.Flush(); - let kernel = kernelTab.Kernel(kernelIdx) - for item0 in kernel do - let item0Idx = KernelItemIdx(kernelIdx,item0) - let jset = closure1OfItem0WithDummy item0 - //printf "#jset = %d\n" jset.Count; stdout.Flush(); - for (KeyValue(closureItem0, lookaheadTokens)) in jset.IEnumerable do - incr count - match rsym_of_item0 closureItem0 with - | None -> () - | Some rsym -> - match gotoKernel (GotoItemIdx(kernelIdx,rsym)) with - | None -> () - | Some gotoKernelIdx -> - let gotoItem = advance_of_item0 closureItem0 - let gotoItemIdx = KernelItemIdx(gotoKernelIdx,gotoItem) - for lookaheadToken in lookaheadTokens do - if lookaheadToken = dummyLookaheadIdx - then propagate.Add(item0Idx, gotoItemIdx) |> ignore - else spontaneous.Add(gotoItemIdx, lookaheadToken) |> ignore - - - //printfn "#kernelIdxs = %d, count = %d" kernelTab.Indexes.Length !count - spontaneous, - propagate - - //printfn "#spontaneous = %d, #propagate = %d" spontaneous.Count propagate.Count; stdout.Flush(); - - //exit 0; - // Repeatedly use the "spontaneous" and "propagate" maps to build the full set - // of lookaheads for each LR(0) kernelItem. - reportTime(); printf "building lookahead table..."; stdout.Flush(); - let lookaheadTable = - - // Seed the table with the startKernelItems and the spontaneous info - let initialWork = - [ for idx in startKernelItemIdxs do - yield (idx,endOfInputTerminalIdx) - for (KeyValue(kernelItemIdx,lookaheads)) in spontaneous.IEnumerable do - for lookahead in lookaheads do - yield (kernelItemIdx,lookahead) ] - - let acc = new LookaheadTable() - // Compute the closure - ProcessWorkList - initialWork - (fun queueWork (kernelItemIdx,lookahead) -> - acc.Add(kernelItemIdx,lookahead) - for gotoKernelIdx in propagate.[kernelItemIdx] do - if not (acc.Contains(gotoKernelIdx,lookahead)) then - queueWork(gotoKernelIdx,lookahead)) - acc - - //printf "built lookahead table, #lookaheads = %d\n" lookaheadTable.Count; stdout.Flush(); - - reportTime(); printf "building action table..."; stdout.Flush(); - let shiftReduceConflicts = ref 0 - let reduceReduceConflicts = ref 0 - let actionTable, immediateActionTable = - - // Now build the action tables. First a utility to merge the given action - // into the table, taking into account precedences etc. and reporting errors. - let addResolvingPrecedence (arr: _[]) kernelIdx termIdx (precNew, actionNew) = - // printf "DEBUG: state %d: adding action for %s, precNew = %a, actionNew = %a\n" kernelIdx (termTab.OfIndex termIdx) outputPrec precNew OutputAction actionNew; - // We add in order of precedence - however the precedences may be the same, and we give warnings when rpecedence resolution is based on implicit file orderings - - let (precSoFar, actionSoFar) as itemSoFar = arr.[termIdx] - - // printf "DEBUG: state %d: adding action for %s, precNew = %a, precSoFar = %a, actionSoFar = %a\n" kernelIdx (termTab.OfIndex termIdx) outputPrec precNew outputPrec precSoFar OutputAction actionSoFar; - // if compare_prec precSoFar precNew = -1 then failwith "addResolvingPrecedence"; - - let itemNew = (precNew, actionNew) - let winner = - let reportConflict x1 x2 reason = - let reportAction (p, a) = - let an, astr = - match a with - | Shift x -> "shift", sprintf "shift(%d)" x - | Reduce x -> - let nt = prodTab.NonTerminal x - "reduce", prodTab.Symbols x - |> Array.map StringOfSym - |> String.concat " " - |> sprintf "reduce(%s:%s)" (ntTab.OfIndex nt) - | _ -> "", "" - let pstr = - match p with - | ExplicitPrec (assoc,n) -> - let astr = - match assoc with - | LeftAssoc -> "left" - | RightAssoc -> "right" - | NonAssoc -> "nonassoc" - sprintf "[explicit %s %d]" astr n - | NoPrecedence -> - "noprec" - an, "{" + pstr + " " + astr + "}" - let a1n, astr1 = reportAction x1 - let a2n, astr2 = reportAction x2 - printfn " %s/%s error at state %d on terminal %s between %s and %s - assuming the former because %s" a1n a2n kernelIdx (termTab.OfIndex termIdx) astr1 astr2 reason - match itemSoFar,itemNew with - | (_,Shift s1),(_, Shift s2) -> - if actionSoFar <> actionNew then - reportConflict itemSoFar itemNew "internal error" - itemSoFar - - | (((precShift,Shift sIdx) as shiftItem), - ((precReduce,Reduce prodIdx) as reduceItem)) - | (((precReduce,Reduce prodIdx) as reduceItem), - ((precShift,Shift sIdx) as shiftItem)) -> - match precReduce, precShift with - | (ExplicitPrec (_,p1), ExplicitPrec(assocNew,p2)) -> - if p1 < p2 then shiftItem - elif p1 > p2 then reduceItem - else - match assocNew with - | LeftAssoc -> reduceItem - | RightAssoc -> shiftItem - | NonAssoc -> - reportConflict shiftItem reduceItem "we prefer shift on equal precedences" - incr shiftReduceConflicts; - shiftItem - | _ -> - reportConflict shiftItem reduceItem "we prefer shift when unable to compare precedences" - incr shiftReduceConflicts; - shiftItem - | ((_,Reduce prodIdx1),(_, Reduce prodIdx2)) -> - "we prefer the rule earlier in the file" - |> if prodIdx1 < prodIdx2 then reportConflict itemSoFar itemNew else reportConflict itemNew itemSoFar - incr reduceReduceConflicts; - if prodIdx1 < prodIdx2 then itemSoFar else itemNew - | _ -> itemNew - arr.[termIdx] <- winner - - - // This build the action table for one state. - let ComputeActions kernelIdx = - let kernel = kernelTab.Kernel kernelIdx - let arr = Array.create terminals.Length (NoPrecedence,Error) - - //printf "building lookahead table LR(1) items for kernelIdx %d\n" kernelIdx; stdout.Flush(); - - // Compute the LR(1) items based on lookaheads - let items = - [ for item0 in kernel do - let kernelItemIdx = KernelItemIdx(kernelIdx,item0) - let lookaheads = lookaheadTable.GetLookaheads(kernelItemIdx) - yield (item0,lookaheads) ] - |> ComputeClosure1 - - for (KeyValue(item0,lookaheads)) in items.IEnumerable do - - let nonTermA = ntIdx_of_item0 item0 - match rsym_of_item0 item0 with - | Some (PTerminal termIdx) -> - let action = - match gotoKernel (GotoItemIdx(kernelIdx,PTerminal termIdx)) with - | None -> failwith "action on terminal should have found a non-empty goto state" - | Some gkernelItemIdx -> Shift gkernelItemIdx - let prec = termTab.PrecInfoOfIndex termIdx - addResolvingPrecedence arr kernelIdx termIdx (prec, action) - | None -> - for lookahead in lookaheads do - if not (IsStartItem(item0)) then - let prodIdx = prodIdx_of_item0 item0 - let prec = prec_of_item0 item0 - let action = (prec, Reduce prodIdx) - addResolvingPrecedence arr kernelIdx lookahead action - elif lookahead = endOfInputTerminalIdx then - let prec = prec_of_item0 item0 - let action = (prec,Accept) - addResolvingPrecedence arr kernelIdx lookahead action - else () - | _ -> () - - // If there is a single item A -> B C . and no Shift or Accept actions (i.e. only Error or Reduce, so the choice of terminal - // cannot affect what we do) then we emit an immediate reduce action for the rule corresponding to that item - // Also do the same for Accept rules. - let closure = (ComputeClosure0 kernel) - - let immediateAction = - match Set.toList closure with - | [item0] -> - match (rsym_of_item0 item0) with - | None when (let reduceOrErrorAction = function Error | Reduce _ -> true | Shift _ | Accept -> false - termTab.Indexes |> List.forall(fun terminalIdx -> reduceOrErrorAction (snd(arr.[terminalIdx])))) - -> Some (Reduce (prodIdx_of_item0 item0)) - - | None when (let acceptOrErrorAction = function Error | Accept -> true | Shift _ | Reduce _ -> false - List.forall (fun terminalIdx -> acceptOrErrorAction (snd(arr.[terminalIdx]))) termTab.Indexes) - -> Some Accept - - | _ -> None - | _ -> None - - // A -> B C . rules give rise to reductions in favour of errors - for item0 in ComputeClosure0 kernel do - let prec = prec_of_item0 item0 - match rsym_of_item0 item0 with - | None -> - for terminalIdx in termTab.Indexes do - if snd(arr.[terminalIdx]) = Error then - let prodIdx = prodIdx_of_item0 item0 - let action = (prec, (if IsStartItem(item0) then Accept else Reduce prodIdx)) - addResolvingPrecedence arr kernelIdx terminalIdx action - | _ -> () - - arr,immediateAction - - let actionInfo = List.map ComputeActions kernelTab.Indexes - Array.ofList (List.map fst actionInfo), - Array.ofList (List.map snd actionInfo) - - // The goto table is much simpler - it is based on LR(0) kernels alone. - - reportTime(); printf " building goto table..."; stdout.Flush(); - let gotoTable = - let gotos kernelIdx = Array.ofList (List.map (fun nt -> gotoKernel (GotoItemIdx(kernelIdx,PNonTerminal nt))) ntTab.Indexes) - Array.ofList (List.map gotos kernelTab.Indexes) - - reportTime(); printfn " returning tables."; stdout.Flush(); - if !shiftReduceConflicts > 0 then printfn " %d shift/reduce conflicts" !shiftReduceConflicts; stdout.Flush(); - if !reduceReduceConflicts > 0 then printfn " %d reduce/reduce conflicts" !reduceReduceConflicts; stdout.Flush(); - if !shiftReduceConflicts > 0 || !reduceReduceConflicts > 0 then printfn " consider setting precedences explicitly using %%left %%right and %%nonassoc on terminals and/or setting explicit precedence on rules using %%prec" - - /// The final results - let states = kernels |> Array.ofList - let prods = Array.ofList (List.map (fun (Production(nt,prec,syms,code)) -> (nt, ntTab.ToIndex nt, syms,code)) prods) - - logf (fun logStream -> - printfn "writing tables to log"; stdout.Flush(); - OutputLalrTables logStream (prods, states, startKernelIdxs, actionTable, immediateActionTable, gotoTable, (termTab.ToIndex endOfInputTerminal), errorTerminalIdx)); - - let states = states |> Array.map (Set.toList >> List.map prodIdx_of_item0) - (prods, states, startKernelIdxs, - actionTable, immediateActionTable, gotoTable, - (termTab.ToIndex endOfInputTerminal), - errorTerminalIdx, nonTerminals) - - -(* Some examples for testing *) - -(* - -let example1 = - let e = "E" - let t = "Terminal" - let plus = "+" - let mul = "*" - let f = "F" - let lparen = "(" - let rparen = ")" - let id = "id" - - let terminals = [plus; mul; lparen; rparen; id] - let nonTerminals = [e; t; f] - - let p2 = e, (NonAssoc, ExplicitPrec 1), [NonTerminal e; Terminal plus; NonTerminal t], None - let p3 = e, (NonAssoc, ExplicitPrec 2), [NonTerminal t], None in - let p4 = t, (NonAssoc, ExplicitPrec 3), [NonTerminal t; Terminal mul; NonTerminal f], None - let p5 = t, (NonAssoc, ExplicitPrec 4), [NonTerminal f], None - let p6 = f, (NonAssoc, ExplicitPrec 5), [Terminal lparen; NonTerminal e; Terminal rparen], None - let p7 = f, (NonAssoc, ExplicitPrec 6), [Terminal id], None - - let prods = [p2;p3;p4;p5;p6;p7] - Spec(terminals,nonTerminals,prods, [e]) - -let example2 = - let prods = [ "S", (NonAssoc, ExplicitPrec 1), [NonTerminal "C";NonTerminal "C"], None; - "C", (NonAssoc, ExplicitPrec 2), [Terminal "c";NonTerminal "C"], None ; - "C", (NonAssoc, ExplicitPrec 3), [Terminal "d"] , None ]in - Spec(["c";"d"],["S";"C"],prods, ["S"]) - -let example3 = - let terminals = ["+"; "*"; "("; ")"; "id"] - let nonTerminals = ["E"; "Terminal"; "E'"; "F"; "Terminal'"] - let prods = [ "E", (NonAssoc, ExplicitPrec 1), [ NonTerminal "Terminal"; NonTerminal "E'" ], None; - "E'", (NonAssoc, ExplicitPrec 2), [ Terminal "+"; NonTerminal "Terminal"; NonTerminal "E'"], None; - "E'", (NonAssoc, ExplicitPrec 3), [ ], None; - "Terminal", (NonAssoc, ExplicitPrec 4), [ NonTerminal "F"; NonTerminal "Terminal'" ], None; - "Terminal'", (NonAssoc, ExplicitPrec 5), [ Terminal "*"; NonTerminal "F"; NonTerminal "Terminal'"], None; - "Terminal'", (NonAssoc, ExplicitPrec 6), [ ], None; - "F", (NonAssoc, ExplicitPrec 7), [ Terminal "("; NonTerminal "E"; Terminal ")"], None; - "F", (NonAssoc, ExplicitPrec 8), [ Terminal "id"], None ] - Spec(terminals,nonTerminals,prods, ["E"]) - -let example4 = - let terminals = ["+"; "*"; "("; ")"; "id"] - let nonTerminals = ["E"] - let prods = [ "E", (NonAssoc, ExplicitPrec 1), [ NonTerminal "E"; Terminal "+"; NonTerminal "E" ], None; - "E", (NonAssoc, ExplicitPrec 2), [ NonTerminal "E"; Terminal "*"; NonTerminal "E" ], None; - "E", (NonAssoc, ExplicitPrec 3), [ Terminal "("; NonTerminal "E"; Terminal ")"], None; - "E", (NonAssoc, ExplicitPrec 8), [ Terminal "id"], None ] - Spec(terminals,nonTerminals,prods, ["E"]) - -let example5 = - let terminals = ["+"; "*"; "("; ")"; "id"] - let nonTerminals = ["E"] - let prods = [ "E", (NonAssoc, ExplicitPrec 1), [ NonTerminal "E"; Terminal "+"; NonTerminal "E" ], None; - "E", (NonAssoc, ExplicitPrec 2), [ NonTerminal "E"; Terminal "*"; NonTerminal "E" ], None; - "E", (NonAssoc, ExplicitPrec 3), [ Terminal "("; NonTerminal "E"; Terminal ")"], None; - "E", (NonAssoc, ExplicitPrec 8), [ Terminal "id"], None ] - Spec(terminals,nonTerminals,prods, ["E"]) - -let example6 = - let terminals = ["+"; "*"; "("; ")"; "id"; "-"] - let nonTerminals = ["E"] - let prods = [ "E", (RightAssoc, ExplicitPrec 1), [ NonTerminal "E"; Terminal "-"; NonTerminal "E" ], None; - "E", (LeftAssoc, ExplicitPrec 1), [ NonTerminal "E"; Terminal "+"; NonTerminal "E" ], None; - "E", (LeftAssoc, ExplicitPrec 2), [ NonTerminal "E"; Terminal "*"; NonTerminal "E" ], None; - "E", (NonAssoc, ExplicitPrec 3), [ Terminal "("; NonTerminal "E"; Terminal ")"], None; - "E", (NonAssoc, ExplicitPrec 8), [ Terminal "id"], None ] - Spec(terminals,nonTerminals,prods, ["E"]) - - -let example7 = - let prods = [ "S", (NonAssoc, ExplicitPrec 1), [NonTerminal "L";Terminal "="; NonTerminal "R"], None; - "S", (NonAssoc, ExplicitPrec 2), [NonTerminal "R"], None ; - "L", (NonAssoc, ExplicitPrec 3), [Terminal "*"; NonTerminal "R"], None; - "L", (NonAssoc, ExplicitPrec 3), [Terminal "id"], None; - "R", (NonAssoc, ExplicitPrec 3), [NonTerminal "L"], None; ] - Spec(["*";"=";"id"],["S";"L";"R"],prods, ["S"]) - - - -let test ex = CompilerLalrParserSpec stdout ex - -(* let _ = test example2*) -(* let _ = exit 1*) -(* let _ = test example3 -let _ = test example1 -let _ = test example4 -let _ = test example5 -let _ = test example6 *) -*) diff --git a/src/fcs-fable/src/buildtools/fsyacc/fsyacclex.fs b/src/fcs-fable/src/buildtools/fsyacc/fsyacclex.fs deleted file mode 100644 index a035f6fe01..0000000000 --- a/src/fcs-fable/src/buildtools/fsyacc/fsyacclex.fs +++ /dev/null @@ -1,644 +0,0 @@ -# 1 "fsyacclex.fsl" - -(* (c) Microsoft Corporation 2005-2008. *) - -module internal FsLexYacc.FsYacc.Lexer - -open FsLexYacc.FsYacc.AST -open FsLexYacc.FsYacc.Parser -open System.Text -open Internal.Utilities.Text.Lexing - -let lexeme (lexbuf : LexBuffer) = new System.String(lexbuf.Lexeme) -let newline (lexbuf:LexBuffer<_>) = lexbuf.EndPos <- lexbuf.EndPos.NextLine - -let unexpected_char lexbuf = - failwith ("Unexpected character '"+(lexeme lexbuf)+"'") - -let typeDepth = ref 0 -let startPos = ref Position.Empty -let mutable str_buf = new System.Text.StringBuilder() - -let appendBuf (str:string) = str_buf.Append str |> ignore -let clearBuf () = str_buf <- new System.Text.StringBuilder() - - -# 26 "fsyacclex.fs" -let trans : uint16[] array = - [| - (* State 0 *) - [| 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 2us; 6us; 6us; 3us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 7us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 4us; 6us; 6us; 6us; 6us; 1us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 6us; 5us; |]; - (* State 1 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 11us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 2 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 3 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 10us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 4 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 9us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 5 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 6 *) - [| 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 65535us; 8us; 8us; 65535us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 65535us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 65535us; 8us; 8us; 8us; 8us; 65535us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 65535us; |]; - (* State 7 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 8 *) - [| 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 65535us; 8us; 8us; 65535us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 65535us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 65535us; 8us; 8us; 8us; 8us; 65535us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 8us; 65535us; |]; - (* State 9 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 10 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 11 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 12 *) - [| 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 17us; 15us; 19us; 19us; 16us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 17us; 19us; 14us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 19us; 13us; 19us; 19us; 19us; 19us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 17us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 19us; 18us; |]; - (* State 13 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 22us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 22us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 14 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 15 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 16 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 21us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 17 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 20us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 20us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 18 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 19 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 20 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 20us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 20us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 20us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 21 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 22 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 23 *) - [| 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 30us; 26us; 33us; 33us; 27us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 30us; 33us; 29us; 33us; 33us; 33us; 33us; 28us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 31us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 33us; 33us; 33us; 33us; 33us; 33us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 30us; 25us; 33us; 24us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 33us; 32us; |]; - (* State 24 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 25 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 26 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 27 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 41us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 28 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 37us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 38us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 29 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 30 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 36us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 36us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 31 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 34us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 32 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 33 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 34 *) - [| 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 65535us; 35us; 35us; 65535us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 65535us; |]; - (* State 35 *) - [| 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 65535us; 35us; 35us; 65535us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 35us; 65535us; |]; - (* State 36 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 36us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 36us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 36us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 37 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 40us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 38 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 39us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 39 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 40us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 40 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 41 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 42 *) - [| 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 46us; 44us; 51us; 51us; 45us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 46us; 51us; 49us; 51us; 51us; 43us; 51us; 48us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 47us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 51us; 51us; 51us; 51us; 51us; 51us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 46us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 51us; 50us; |]; - (* State 43 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 60us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 44 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 45 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 59us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 46 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 58us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 58us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 47 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 56us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 48 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 52us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 53us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 49 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 50 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 51 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 52 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 55us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 53 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 54us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 54 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 55us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 55 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 56 *) - [| 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 65535us; 57us; 57us; 65535us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 65535us; |]; - (* State 57 *) - [| 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 65535us; 57us; 57us; 65535us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 57us; 65535us; |]; - (* State 58 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 58us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 58us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 58us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 59 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 60 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 61 *) - [| 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 62us; 64us; 63us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 64us; 65535us; |]; - (* State 62 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 63 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 64 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 65 *) - [| 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 72us; 73us; 79us; 79us; 74us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 72us; 79us; 79us; 79us; 79us; 66us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 77us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 78us; 70us; 68us; 79us; 69us; 79us; 79us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 79us; 79us; 79us; 79us; 79us; 79us; 75us; 75us; 75us; 75us; 67us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 75us; 71us; 76us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 79us; 80us; |]; - (* State 66 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 92us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 96us; 65535us; 98us; 65535us; 95us; 65535us; 97us; 94us; 93us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 91us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 67 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 84us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 87us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 68 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 69 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 70 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 71 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 72 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 86us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 86us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 73 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 74 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 85us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 75 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 84us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 76 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 77 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 81us; 65535us; 65535us; 65535us; 65535us; 82us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 78 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 79 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 80 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 81 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 82 *) - [| 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 65535us; 83us; 83us; 65535us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 65535us; |]; - (* State 83 *) - [| 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 65535us; 83us; 83us; 65535us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 83us; 65535us; |]; - (* State 84 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 84us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 85 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 86 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 86us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 86us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 87 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 84us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 88us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 88 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 84us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 89us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 89 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 84us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 90us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 90 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 84us; 65535us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 84us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 91 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 92 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 93 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 120us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 121us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 94 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 116us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 95 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 113us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 96 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 110us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 97 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 106us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 98 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 99us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 99 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 100us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 100 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 101us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 101 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 102us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 102 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 103us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 103 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 104us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 104 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 105us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 105 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 106 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 107us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 107 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 108us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 108 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 109us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 109 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 110 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 111us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 111 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 112us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 112 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 113 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 114us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 114 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 115us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 115 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 116 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 117us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 117 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 118us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 118 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 119us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 119 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 120 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 126us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 121 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 122us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 122 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 123us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 123 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 125us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 125us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 124us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 124 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 125 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 125us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 125us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 124us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 126 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 127us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 127 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 128us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 128 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 130us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 130us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 129us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 129 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - (* State 130 *) - [| 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 130us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 130us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 129us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; |]; - |] -let actions : uint16[] = [|65535us; 5us; 1us; 5us; 5us; 3us; 4us; 5us; 4us; 2us; 1us; 0us; 65535us; 5us; 1us; 2us; 5us; 3us; 4us; 5us; 3us; 2us; 0us; 65535us; 0us; 1us; 2us; 8us; 8us; 4us; 5us; 8us; 7us; 8us; 6us; 6us; 5us; 65535us; 65535us; 65535us; 3us; 2us; 65535us; 7us; 1us; 7us; 2us; 7us; 7us; 5us; 6us; 7us; 65535us; 65535us; 65535us; 4us; 3us; 3us; 2us; 1us; 0us; 65535us; 0us; 1us; 2us; 65535us; 22us; 17us; 11us; 12us; 13us; 14us; 15us; 16us; 22us; 17us; 18us; 22us; 21us; 22us; 23us; 19us; 20us; 20us; 17us; 16us; 15us; 17us; 17us; 17us; 10us; 0us; 1us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 65535us; 9us; 65535us; 65535us; 65535us; 8us; 65535us; 65535us; 7us; 65535us; 65535us; 5us; 65535us; 65535us; 65535us; 4us; 65535us; 65535us; 65535us; 65535us; 6us; 65535us; 65535us; 65535us; 3us; 2us; 65535us; |] -let _fslex_tables = Internal.Utilities.Text.Lexing.UnicodeTables.Create(trans,actions) -let rec _fslex_dummy () = _fslex_dummy() -(* Rule token *) -and token (lexbuf : Internal.Utilities.Text.Lexing.LexBuffer<_>) = _fslex_token 65 lexbuf -(* Rule fs_type *) -and fs_type (lexbuf : Internal.Utilities.Text.Lexing.LexBuffer<_>) = _fslex_fs_type 61 lexbuf -(* Rule header *) -and header p buff (lexbuf : Internal.Utilities.Text.Lexing.LexBuffer<_>) = _fslex_header p buff 42 lexbuf -(* Rule code *) -and code p buff (lexbuf : Internal.Utilities.Text.Lexing.LexBuffer<_>) = _fslex_code p buff 23 lexbuf -(* Rule codestring *) -and codestring buff (lexbuf : Internal.Utilities.Text.Lexing.LexBuffer<_>) = _fslex_codestring buff 12 lexbuf -(* Rule comment *) -and comment (lexbuf : Internal.Utilities.Text.Lexing.LexBuffer<_>) = _fslex_comment 0 lexbuf -(* Rule token *) -and _fslex_token _fslex_state lexbuf = - match _fslex_tables.Interpret(_fslex_state,lexbuf) with - | 0 -> ( -# 35 "fsyacclex.fsl" - let p = lexbuf.StartPos in header p (new StringBuilder 100) lexbuf -# 313 "fsyacclex.fs" - ) - | 1 -> ( -# 36 "fsyacclex.fsl" - PERCENT_PERCENT -# 318 "fsyacclex.fs" - ) - | 2 -> ( -# 37 "fsyacclex.fsl" - typeDepth := 1; startPos := lexbuf.StartPos; clearBuf(); TOKEN (fs_type lexbuf) -# 323 "fsyacclex.fs" - ) - | 3 -> ( -# 38 "fsyacclex.fsl" - TOKEN (None) -# 328 "fsyacclex.fs" - ) - | 4 -> ( -# 39 "fsyacclex.fsl" - START -# 333 "fsyacclex.fs" - ) - | 5 -> ( -# 40 "fsyacclex.fsl" - PREC -# 338 "fsyacclex.fs" - ) - | 6 -> ( -# 41 "fsyacclex.fsl" - typeDepth := 1; startPos := lexbuf.StartPos; clearBuf(); TYPE (match fs_type lexbuf with Some x -> x | None -> failwith "gettype") -# 343 "fsyacclex.fs" - ) - | 7 -> ( -# 42 "fsyacclex.fsl" - LEFT -# 348 "fsyacclex.fs" - ) - | 8 -> ( -# 43 "fsyacclex.fsl" - RIGHT -# 353 "fsyacclex.fs" - ) - | 9 -> ( -# 44 "fsyacclex.fsl" - NONASSOC -# 358 "fsyacclex.fs" - ) - | 10 -> ( -# 45 "fsyacclex.fsl" - ERROR -# 363 "fsyacclex.fs" - ) - | 11 -> ( -# 46 "fsyacclex.fsl" - LESS -# 368 "fsyacclex.fs" - ) - | 12 -> ( -# 47 "fsyacclex.fsl" - GREATER -# 373 "fsyacclex.fs" - ) - | 13 -> ( -# 48 "fsyacclex.fsl" - SEMI -# 378 "fsyacclex.fs" - ) - | 14 -> ( -# 49 "fsyacclex.fsl" - let p = lexbuf.StartPos in - let buff = (new StringBuilder 100) in - // adjust the first line to get even indentation for all lines w.r.t. the left hand margin - buff.Append (String.replicate (lexbuf.StartPos.Column+1) " ") |> ignore; - code p buff lexbuf -# 387 "fsyacclex.fs" - ) - | 15 -> ( -# 54 "fsyacclex.fsl" - token lexbuf -# 392 "fsyacclex.fs" - ) - | 16 -> ( -# 55 "fsyacclex.fsl" - newline lexbuf; token lexbuf -# 397 "fsyacclex.fs" - ) - | 17 -> ( -# 56 "fsyacclex.fsl" - IDENT (lexeme lexbuf) -# 402 "fsyacclex.fs" - ) - | 18 -> ( -# 57 "fsyacclex.fsl" - BAR -# 407 "fsyacclex.fs" - ) - | 19 -> ( -# 58 "fsyacclex.fsl" - ignore(comment lexbuf); token lexbuf -# 412 "fsyacclex.fs" - ) - | 20 -> ( -# 59 "fsyacclex.fsl" - token lexbuf -# 417 "fsyacclex.fs" - ) - | 21 -> ( -# 60 "fsyacclex.fsl" - COLON -# 422 "fsyacclex.fs" - ) - | 22 -> ( -# 61 "fsyacclex.fsl" - unexpected_char lexbuf -# 427 "fsyacclex.fs" - ) - | 23 -> ( -# 62 "fsyacclex.fsl" - EOF -# 432 "fsyacclex.fs" - ) - | _ -> failwith "token" -(* Rule fs_type *) -and _fslex_fs_type _fslex_state lexbuf = - match _fslex_tables.Interpret(_fslex_state,lexbuf) with - | 0 -> ( -# 65 "fsyacclex.fsl" - incr typeDepth; appendBuf(lexeme lexbuf); fs_type lexbuf -# 441 "fsyacclex.fs" - ) - | 1 -> ( -# 67 "fsyacclex.fsl" - decr typeDepth; - if !typeDepth = 0 - then Some(string str_buf) - else appendBuf(lexeme lexbuf); fs_type lexbuf -# 449 "fsyacclex.fs" - ) - | 2 -> ( -# 71 "fsyacclex.fsl" - appendBuf(lexeme lexbuf); fs_type lexbuf -# 454 "fsyacclex.fs" - ) - | _ -> failwith "fs_type" -(* Rule header *) -and _fslex_header p buff _fslex_state lexbuf = - match _fslex_tables.Interpret(_fslex_state,lexbuf) with - | 0 -> ( -# 74 "fsyacclex.fsl" - HEADER (buff.ToString(), p) -# 463 "fsyacclex.fs" - ) - | 1 -> ( -# 75 "fsyacclex.fsl" - newline lexbuf; - ignore <| buff.Append System.Environment.NewLine; - header p buff lexbuf -# 470 "fsyacclex.fs" - ) - | 2 -> ( -# 79 "fsyacclex.fsl" - ignore <| buff.Append (lexeme lexbuf); - header p buff lexbuf -# 476 "fsyacclex.fs" - ) - | 3 -> ( -# 82 "fsyacclex.fsl" - ignore <| buff.Append (lexeme lexbuf); - header p buff lexbuf -# 482 "fsyacclex.fs" - ) - | 4 -> ( -# 85 "fsyacclex.fsl" - ignore <| buff.Append (lexeme lexbuf); - header p buff lexbuf -# 488 "fsyacclex.fs" - ) - | 5 -> ( -# 88 "fsyacclex.fsl" - ignore <| buff.Append (lexeme lexbuf); - ignore(codestring buff lexbuf); - header p buff lexbuf -# 495 "fsyacclex.fs" - ) - | 6 -> ( -# 91 "fsyacclex.fsl" - EOF -# 500 "fsyacclex.fs" - ) - | 7 -> ( -# 92 "fsyacclex.fsl" - ignore <| buff.Append(lexeme lexbuf).[0]; - header p buff lexbuf -# 506 "fsyacclex.fs" - ) - | _ -> failwith "header" -(* Rule code *) -and _fslex_code p buff _fslex_state lexbuf = - match _fslex_tables.Interpret(_fslex_state,lexbuf) with - | 0 -> ( -# 95 "fsyacclex.fsl" - CODE (buff.ToString(), p) -# 515 "fsyacclex.fs" - ) - | 1 -> ( -# 96 "fsyacclex.fsl" - ignore <| buff.Append (lexeme lexbuf); - ignore(code p buff lexbuf); - ignore <| buff.Append "}"; - code p buff lexbuf -# 523 "fsyacclex.fs" - ) - | 2 -> ( -# 100 "fsyacclex.fsl" - newline lexbuf; - ignore <| buff.Append System.Environment.NewLine; - code p buff lexbuf -# 530 "fsyacclex.fs" - ) - | 3 -> ( -# 104 "fsyacclex.fsl" - ignore <| buff.Append (lexeme lexbuf); - code p buff lexbuf -# 536 "fsyacclex.fs" - ) - | 4 -> ( -# 106 "fsyacclex.fsl" - ignore <| buff.Append (lexeme lexbuf); - ignore(codestring buff lexbuf); - code p buff lexbuf -# 543 "fsyacclex.fs" - ) - | 5 -> ( -# 110 "fsyacclex.fsl" - ignore <| buff.Append (lexeme lexbuf); - code p buff lexbuf -# 549 "fsyacclex.fs" - ) - | 6 -> ( -# 113 "fsyacclex.fsl" - ignore <| buff.Append (lexeme lexbuf); - code p buff lexbuf -# 555 "fsyacclex.fs" - ) - | 7 -> ( -# 115 "fsyacclex.fsl" - EOF -# 560 "fsyacclex.fs" - ) - | 8 -> ( -# 116 "fsyacclex.fsl" - ignore <| buff.Append(lexeme lexbuf).[0]; - code p buff lexbuf -# 566 "fsyacclex.fs" - ) - | _ -> failwith "code" -(* Rule codestring *) -and _fslex_codestring buff _fslex_state lexbuf = - match _fslex_tables.Interpret(_fslex_state,lexbuf) with - | 0 -> ( -# 122 "fsyacclex.fsl" - ignore <| buff.Append (lexeme lexbuf); - codestring buff lexbuf -# 576 "fsyacclex.fs" - ) - | 1 -> ( -# 124 "fsyacclex.fsl" - ignore <| buff.Append (lexeme lexbuf); - buff.ToString() -# 582 "fsyacclex.fs" - ) - | 2 -> ( -# 126 "fsyacclex.fsl" - newline lexbuf; - ignore <| buff.Append System.Environment.NewLine; - codestring buff lexbuf -# 589 "fsyacclex.fs" - ) - | 3 -> ( -# 130 "fsyacclex.fsl" - ignore <| buff.Append (lexeme lexbuf); - codestring buff lexbuf -# 595 "fsyacclex.fs" - ) - | 4 -> ( -# 132 "fsyacclex.fsl" - failwith "unterminated string in code" -# 600 "fsyacclex.fs" - ) - | 5 -> ( -# 133 "fsyacclex.fsl" - ignore <| buff.Append(lexeme lexbuf).[0]; - codestring buff lexbuf -# 606 "fsyacclex.fs" - ) - | _ -> failwith "codestring" -(* Rule comment *) -and _fslex_comment _fslex_state lexbuf = - match _fslex_tables.Interpret(_fslex_state,lexbuf) with - | 0 -> ( -# 138 "fsyacclex.fsl" - ignore(comment lexbuf); comment lexbuf -# 615 "fsyacclex.fs" - ) - | 1 -> ( -# 139 "fsyacclex.fsl" - newline lexbuf; comment lexbuf -# 620 "fsyacclex.fs" - ) - | 2 -> ( -# 140 "fsyacclex.fsl" - () -# 625 "fsyacclex.fs" - ) - | 3 -> ( -# 141 "fsyacclex.fsl" - failwith "end of file in comment" -# 630 "fsyacclex.fs" - ) - | 4 -> ( -# 142 "fsyacclex.fsl" - comment lexbuf -# 635 "fsyacclex.fs" - ) - | 5 -> ( -# 143 "fsyacclex.fsl" - comment lexbuf -# 640 "fsyacclex.fs" - ) - | _ -> failwith "comment" - -# 3000000 "fsyacclex.fs" diff --git a/src/fcs-fable/src/buildtools/fsyacc/fsyaccpars.fs b/src/fcs-fable/src/buildtools/fsyacc/fsyaccpars.fs deleted file mode 100644 index c6d614f269..0000000000 --- a/src/fcs-fable/src/buildtools/fsyacc/fsyaccpars.fs +++ /dev/null @@ -1,562 +0,0 @@ -// Implementation file for parser generated by fsyacc -module internal FsLexYacc.FsYacc.Parser -#nowarn "64";; // turn off warnings that type variables used in production annotations are instantiated to concrete type -open Internal.Utilities.Text.Lexing -open Internal.Utilities.Text.Parsing.ParseHelpers -# 1 "fsyaccpars.fsy" - -(* (c) Microsoft Corporation 2005-2008. *) - -// FsLexYacc.FsYacc.Parser - -open FsLexYacc.FsYacc -open FsLexYacc.FsYacc.AST - -#nowarn "62" // This construct is for ML compatibility - - -# 18 "fsyaccpars.fs" -// This type is the type of tokens accepted by the parser -type token = - | TOKEN of (string option) - | TYPE of (string) - | BAR - | PERCENT_PERCENT - | START - | LEFT - | RIGHT - | NONASSOC - | LESS - | GREATER - | COLON - | PREC - | SEMI - | EOF - | ERROR - | HEADER of (AST.Code) - | CODE of (AST.Code) - | IDENT of (string) -// This type is used to give symbolic names to token indexes, useful for error messages -type tokenId = - | TOKEN_TOKEN - | TOKEN_TYPE - | TOKEN_BAR - | TOKEN_PERCENT_PERCENT - | TOKEN_START - | TOKEN_LEFT - | TOKEN_RIGHT - | TOKEN_NONASSOC - | TOKEN_LESS - | TOKEN_GREATER - | TOKEN_COLON - | TOKEN_PREC - | TOKEN_SEMI - | TOKEN_EOF - | TOKEN_ERROR - | TOKEN_HEADER - | TOKEN_CODE - | TOKEN_IDENT - | TOKEN_end_of_input - | TOKEN_error -// This type is used to give symbolic names to token indexes, useful for error messages -type nonTerminalId = - | NONTERM__startspec - | NONTERM_spec - | NONTERM_headeropt - | NONTERM_decls - | NONTERM_decl - | NONTERM_idents - | NONTERM_rules - | NONTERM_rule - | NONTERM_optbar - | NONTERM_optsemi - | NONTERM_clauses - | NONTERM_clause - | NONTERM_syms - | NONTERM_optprec - -// This function maps tokens to integer indexes -let tagOfToken (t:token) = - match t with - | TOKEN _ -> 0 - | TYPE _ -> 1 - | BAR -> 2 - | PERCENT_PERCENT -> 3 - | START -> 4 - | LEFT -> 5 - | RIGHT -> 6 - | NONASSOC -> 7 - | LESS -> 8 - | GREATER -> 9 - | COLON -> 10 - | PREC -> 11 - | SEMI -> 12 - | EOF -> 13 - | ERROR -> 14 - | HEADER _ -> 15 - | CODE _ -> 16 - | IDENT _ -> 17 - -// This function maps integer indexes to symbolic token ids -let tokenTagToTokenId (tokenIdx:int) = - match tokenIdx with - | 0 -> TOKEN_TOKEN - | 1 -> TOKEN_TYPE - | 2 -> TOKEN_BAR - | 3 -> TOKEN_PERCENT_PERCENT - | 4 -> TOKEN_START - | 5 -> TOKEN_LEFT - | 6 -> TOKEN_RIGHT - | 7 -> TOKEN_NONASSOC - | 8 -> TOKEN_LESS - | 9 -> TOKEN_GREATER - | 10 -> TOKEN_COLON - | 11 -> TOKEN_PREC - | 12 -> TOKEN_SEMI - | 13 -> TOKEN_EOF - | 14 -> TOKEN_ERROR - | 15 -> TOKEN_HEADER - | 16 -> TOKEN_CODE - | 17 -> TOKEN_IDENT - | 20 -> TOKEN_end_of_input - | 18 -> TOKEN_error - | _ -> failwith "tokenTagToTokenId: bad token" - -/// This function maps production indexes returned in syntax errors to strings representing the non terminal that would be produced by that production -let prodIdxToNonTerminal (prodIdx:int) = - match prodIdx with - | 0 -> NONTERM__startspec - | 1 -> NONTERM_spec - | 2 -> NONTERM_headeropt - | 3 -> NONTERM_headeropt - | 4 -> NONTERM_decls - | 5 -> NONTERM_decls - | 6 -> NONTERM_decl - | 7 -> NONTERM_decl - | 8 -> NONTERM_decl - | 9 -> NONTERM_decl - | 10 -> NONTERM_decl - | 11 -> NONTERM_decl - | 12 -> NONTERM_idents - | 13 -> NONTERM_idents - | 14 -> NONTERM_rules - | 15 -> NONTERM_rules - | 16 -> NONTERM_rule - | 17 -> NONTERM_optbar - | 18 -> NONTERM_optbar - | 19 -> NONTERM_optsemi - | 20 -> NONTERM_optsemi - | 21 -> NONTERM_clauses - | 22 -> NONTERM_clauses - | 23 -> NONTERM_clause - | 24 -> NONTERM_syms - | 25 -> NONTERM_syms - | 26 -> NONTERM_syms - | 27 -> NONTERM_optprec - | 28 -> NONTERM_optprec - | _ -> failwith "prodIdxToNonTerminal: bad production index" - -let _fsyacc_endOfInputTag = 20 -let _fsyacc_tagOfErrorTerminal = 18 - -// This function gets the name of a token as a string -let token_to_string (t:token) = - match t with - | TOKEN _ -> "TOKEN" - | TYPE _ -> "TYPE" - | BAR -> "BAR" - | PERCENT_PERCENT -> "PERCENT_PERCENT" - | START -> "START" - | LEFT -> "LEFT" - | RIGHT -> "RIGHT" - | NONASSOC -> "NONASSOC" - | LESS -> "LESS" - | GREATER -> "GREATER" - | COLON -> "COLON" - | PREC -> "PREC" - | SEMI -> "SEMI" - | EOF -> "EOF" - | ERROR -> "ERROR" - | HEADER _ -> "HEADER" - | CODE _ -> "CODE" - | IDENT _ -> "IDENT" - -// This function gets the data carried by a token as an object -let _fsyacc_dataOfToken (t:token) = - match t with - | TOKEN _fsyacc_x -> Microsoft.FSharp.Core.Operators.box _fsyacc_x - | TYPE _fsyacc_x -> Microsoft.FSharp.Core.Operators.box _fsyacc_x - | BAR -> (null : System.Object) - | PERCENT_PERCENT -> (null : System.Object) - | START -> (null : System.Object) - | LEFT -> (null : System.Object) - | RIGHT -> (null : System.Object) - | NONASSOC -> (null : System.Object) - | LESS -> (null : System.Object) - | GREATER -> (null : System.Object) - | COLON -> (null : System.Object) - | PREC -> (null : System.Object) - | SEMI -> (null : System.Object) - | EOF -> (null : System.Object) - | ERROR -> (null : System.Object) - | HEADER _fsyacc_x -> Microsoft.FSharp.Core.Operators.box _fsyacc_x - | CODE _fsyacc_x -> Microsoft.FSharp.Core.Operators.box _fsyacc_x - | IDENT _fsyacc_x -> Microsoft.FSharp.Core.Operators.box _fsyacc_x -let _fsyacc_gotos = [| 0us; 65535us; 1us; 65535us; 0us; 1us; 1us; 65535us; 0us; 2us; 2us; 65535us; 2us; 3us; 7us; 8us; 2us; 65535us; 2us; 7us; 7us; 7us; 7us; 65535us; 9us; 10us; 11us; 12us; 13us; 14us; 15us; 16us; 17us; 18us; 19us; 20us; 21us; 22us; 2us; 65535us; 4us; 5us; 23us; 24us; 2us; 65535us; 4us; 23us; 23us; 23us; 1us; 65535us; 26us; 27us; 1us; 65535us; 28us; 29us; 2us; 65535us; 27us; 28us; 33us; 34us; 2us; 65535us; 27us; 32us; 33us; 32us; 4us; 65535us; 27us; 35us; 33us; 35us; 38us; 39us; 40us; 41us; 1us; 65535us; 35us; 36us; |] -let _fsyacc_sparseGotoTableRowOffsets = [|0us; 1us; 3us; 5us; 8us; 11us; 19us; 22us; 25us; 27us; 29us; 32us; 35us; 40us; |] -let _fsyacc_stateToProdIdxsTableElements = [| 1us; 0us; 1us; 0us; 1us; 1us; 1us; 1us; 1us; 1us; 1us; 1us; 1us; 2us; 1us; 5us; 1us; 5us; 1us; 6us; 1us; 6us; 1us; 7us; 1us; 7us; 1us; 8us; 1us; 8us; 1us; 9us; 1us; 9us; 1us; 10us; 1us; 10us; 1us; 11us; 1us; 11us; 1us; 12us; 1us; 12us; 2us; 14us; 15us; 1us; 14us; 1us; 16us; 1us; 16us; 1us; 16us; 1us; 16us; 1us; 16us; 1us; 18us; 1us; 20us; 2us; 21us; 22us; 1us; 21us; 1us; 21us; 1us; 23us; 1us; 23us; 1us; 23us; 1us; 24us; 1us; 24us; 1us; 25us; 1us; 25us; 1us; 28us; 1us; 28us; |] -let _fsyacc_stateToProdIdxsTableRowOffsets = [|0us; 2us; 4us; 6us; 8us; 10us; 12us; 14us; 16us; 18us; 20us; 22us; 24us; 26us; 28us; 30us; 32us; 34us; 36us; 38us; 40us; 42us; 44us; 46us; 49us; 51us; 53us; 55us; 57us; 59us; 61us; 63us; 65us; 68us; 70us; 72us; 74us; 76us; 78us; 80us; 82us; 84us; 86us; 88us; |] -let _fsyacc_action_rows = 44 -let _fsyacc_actionTableElements = [|1us; 16387us; 15us; 6us; 0us; 49152us; 6us; 16388us; 0us; 9us; 1us; 11us; 4us; 13us; 5us; 15us; 6us; 17us; 7us; 19us; 1us; 32768us; 3us; 4us; 1us; 32768us; 17us; 25us; 0us; 16385us; 0us; 16386us; 6us; 16388us; 0us; 9us; 1us; 11us; 4us; 13us; 5us; 15us; 6us; 17us; 7us; 19us; 0us; 16389us; 1us; 16397us; 17us; 21us; 0us; 16390us; 1us; 16397us; 17us; 21us; 0us; 16391us; 1us; 16397us; 17us; 21us; 0us; 16392us; 1us; 16397us; 17us; 21us; 0us; 16393us; 1us; 16397us; 17us; 21us; 0us; 16394us; 1us; 16397us; 17us; 21us; 0us; 16395us; 1us; 16397us; 17us; 21us; 0us; 16396us; 1us; 16399us; 17us; 25us; 0us; 16398us; 1us; 32768us; 10us; 26us; 1us; 16401us; 2us; 30us; 2us; 16410us; 14us; 40us; 17us; 38us; 1us; 16403us; 12us; 31us; 0us; 16400us; 0us; 16402us; 0us; 16404us; 1us; 16406us; 2us; 33us; 2us; 16410us; 14us; 40us; 17us; 38us; 0us; 16405us; 1us; 16411us; 11us; 42us; 1us; 32768us; 16us; 37us; 0us; 16407us; 2us; 16410us; 14us; 40us; 17us; 38us; 0us; 16408us; 2us; 16410us; 14us; 40us; 17us; 38us; 0us; 16409us; 1us; 32768us; 17us; 43us; 0us; 16412us; |] -let _fsyacc_actionTableRowOffsets = [|0us; 2us; 3us; 10us; 12us; 14us; 15us; 16us; 23us; 24us; 26us; 27us; 29us; 30us; 32us; 33us; 35us; 36us; 38us; 39us; 41us; 42us; 44us; 45us; 47us; 48us; 50us; 52us; 55us; 57us; 58us; 59us; 60us; 62us; 65us; 66us; 68us; 70us; 71us; 74us; 75us; 78us; 79us; 81us; |] -let _fsyacc_reductionSymbolCounts = [|1us; 4us; 1us; 0us; 0us; 2us; 2us; 2us; 2us; 2us; 2us; 2us; 2us; 0us; 2us; 1us; 5us; 0us; 1us; 0us; 1us; 3us; 1us; 3us; 2us; 2us; 0us; 0us; 2us; |] -let _fsyacc_productionToNonTerminalTable = [|0us; 1us; 2us; 2us; 3us; 3us; 4us; 4us; 4us; 4us; 4us; 4us; 5us; 5us; 6us; 6us; 7us; 8us; 8us; 9us; 9us; 10us; 10us; 11us; 12us; 12us; 12us; 13us; 13us; |] -let _fsyacc_immediateActions = [|65535us; 49152us; 65535us; 65535us; 65535us; 16385us; 16386us; 65535us; 16389us; 65535us; 16390us; 65535us; 16391us; 65535us; 16392us; 65535us; 16393us; 65535us; 16394us; 65535us; 16395us; 65535us; 16396us; 65535us; 16398us; 65535us; 65535us; 65535us; 65535us; 16400us; 16402us; 16404us; 65535us; 65535us; 16405us; 65535us; 65535us; 16407us; 65535us; 16408us; 65535us; 16409us; 65535us; 16412us; |] -let _fsyacc_reductions () = [| -# 216 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : AST.ParserSpec)) in - Microsoft.FSharp.Core.Operators.box - ( - ( - raise (Internal.Utilities.Text.Parsing.Accept(Microsoft.FSharp.Core.Operators.box _1)) - ) - : '_startspec)); -# 225 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'headeropt)) in - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'decls)) in - let _4 = (let data = parseState.GetInput(4) in (Microsoft.FSharp.Core.Operators.unbox data : 'rules)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 25 "fsyaccpars.fsy" - List.foldBack (fun f x -> f x) _2 { Header=_1;Tokens=[];Types=[];Associativities=[];StartSymbols=[];Rules=_4 } - ) -# 25 "fsyaccpars.fsy" - : AST.ParserSpec)); -# 238 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : AST.Code)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 29 "fsyaccpars.fsy" - _1 - ) -# 29 "fsyaccpars.fsy" - : 'headeropt)); -# 249 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 31 "fsyaccpars.fsy" - "", (parseState.ResultRange |> fst) - ) -# 31 "fsyaccpars.fsy" - : 'headeropt)); -# 259 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 34 "fsyaccpars.fsy" - [] - ) -# 34 "fsyaccpars.fsy" - : 'decls)); -# 269 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'decl)) in - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'decls)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 35 "fsyaccpars.fsy" - _1 :: _2 - ) -# 35 "fsyaccpars.fsy" - : 'decls)); -# 281 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : string option)) in - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'idents)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 38 "fsyaccpars.fsy" - (fun x -> {x with Tokens = x.Tokens @ (List.map (fun x -> (x,_1)) _2)}) - ) -# 38 "fsyaccpars.fsy" - : 'decl)); -# 293 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : string)) in - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'idents)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 39 "fsyaccpars.fsy" - (fun x -> {x with Types = x.Types @ (List.map (fun x -> (x,_1)) _2)} ) - ) -# 39 "fsyaccpars.fsy" - : 'decl)); -# 305 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'idents)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 40 "fsyaccpars.fsy" - (fun x -> {x with StartSymbols = x.StartSymbols @ _2} ) - ) -# 40 "fsyaccpars.fsy" - : 'decl)); -# 316 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'idents)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 41 "fsyaccpars.fsy" - (fun x -> {x with Associativities = x.Associativities @ [(List.map (fun x -> (x,LeftAssoc)) _2)]} ) - ) -# 41 "fsyaccpars.fsy" - : 'decl)); -# 327 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'idents)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 42 "fsyaccpars.fsy" - (fun x -> {x with Associativities = x.Associativities @ [(List.map (fun x -> (x,RightAssoc)) _2)]} ) - ) -# 42 "fsyaccpars.fsy" - : 'decl)); -# 338 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'idents)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 43 "fsyaccpars.fsy" - (fun x -> {x with Associativities = x.Associativities @ [(List.map (fun x -> (x,NonAssoc)) _2)]} ) - ) -# 43 "fsyaccpars.fsy" - : 'decl)); -# 349 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : string)) in - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'idents)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 45 "fsyaccpars.fsy" - _1 :: _2 - ) -# 45 "fsyaccpars.fsy" - : 'idents)); -# 361 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 45 "fsyaccpars.fsy" - [] - ) -# 45 "fsyaccpars.fsy" - : 'idents)); -# 371 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'rule)) in - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'rules)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 46 "fsyaccpars.fsy" - _1 :: _2 - ) -# 46 "fsyaccpars.fsy" - : 'rules)); -# 383 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'rule)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 46 "fsyaccpars.fsy" - [_1] - ) -# 46 "fsyaccpars.fsy" - : 'rules)); -# 394 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : string)) in - let _3 = (let data = parseState.GetInput(3) in (Microsoft.FSharp.Core.Operators.unbox data : 'optbar)) in - let _4 = (let data = parseState.GetInput(4) in (Microsoft.FSharp.Core.Operators.unbox data : 'clauses)) in - let _5 = (let data = parseState.GetInput(5) in (Microsoft.FSharp.Core.Operators.unbox data : 'optsemi)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 47 "fsyaccpars.fsy" - (_1,_4) - ) -# 47 "fsyaccpars.fsy" - : 'rule)); -# 408 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 48 "fsyaccpars.fsy" - - ) -# 48 "fsyaccpars.fsy" - : 'optbar)); -# 418 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 48 "fsyaccpars.fsy" - - ) -# 48 "fsyaccpars.fsy" - : 'optbar)); -# 428 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 49 "fsyaccpars.fsy" - - ) -# 49 "fsyaccpars.fsy" - : 'optsemi)); -# 438 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 49 "fsyaccpars.fsy" - - ) -# 49 "fsyaccpars.fsy" - : 'optsemi)); -# 448 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'clause)) in - let _3 = (let data = parseState.GetInput(3) in (Microsoft.FSharp.Core.Operators.unbox data : 'clauses)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 50 "fsyaccpars.fsy" - _1 :: _3 - ) -# 50 "fsyaccpars.fsy" - : 'clauses)); -# 460 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'clause)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 50 "fsyaccpars.fsy" - [_1] - ) -# 50 "fsyaccpars.fsy" - : 'clauses)); -# 471 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : 'syms)) in - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'optprec)) in - let _3 = (let data = parseState.GetInput(3) in (Microsoft.FSharp.Core.Operators.unbox data : AST.Code)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 51 "fsyaccpars.fsy" - Rule(_1,_2,Some _3) - ) -# 51 "fsyaccpars.fsy" - : 'clause)); -# 484 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _1 = (let data = parseState.GetInput(1) in (Microsoft.FSharp.Core.Operators.unbox data : string)) in - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'syms)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 52 "fsyaccpars.fsy" - _1 :: _2 - ) -# 52 "fsyaccpars.fsy" - : 'syms)); -# 496 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : 'syms)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 52 "fsyaccpars.fsy" - "error" :: _2 - ) -# 52 "fsyaccpars.fsy" - : 'syms)); -# 507 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 52 "fsyaccpars.fsy" - [] - ) -# 52 "fsyaccpars.fsy" - : 'syms)); -# 517 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - Microsoft.FSharp.Core.Operators.box - ( - ( -# 53 "fsyaccpars.fsy" - None - ) -# 53 "fsyaccpars.fsy" - : 'optprec)); -# 527 "fsyaccpars.fs" - (fun (parseState : Internal.Utilities.Text.Parsing.IParseState) -> - let _2 = (let data = parseState.GetInput(2) in (Microsoft.FSharp.Core.Operators.unbox data : string)) in - Microsoft.FSharp.Core.Operators.box - ( - ( -# 53 "fsyaccpars.fsy" - Some _2 - ) -# 53 "fsyaccpars.fsy" - : 'optprec)); -|] -# 539 "fsyaccpars.fs" -let tables () : Internal.Utilities.Text.Parsing.Tables<_> = - { reductions= _fsyacc_reductions (); - endOfInputTag = _fsyacc_endOfInputTag; - tagOfToken = tagOfToken; - dataOfToken = _fsyacc_dataOfToken; - actionTableElements = _fsyacc_actionTableElements; - actionTableRowOffsets = _fsyacc_actionTableRowOffsets; - stateToProdIdxsTableElements = _fsyacc_stateToProdIdxsTableElements; - stateToProdIdxsTableRowOffsets = _fsyacc_stateToProdIdxsTableRowOffsets; - reductionSymbolCounts = _fsyacc_reductionSymbolCounts; - immediateActions = _fsyacc_immediateActions; - gotos = _fsyacc_gotos; - sparseGotoTableRowOffsets = _fsyacc_sparseGotoTableRowOffsets; - tagOfErrorTerminal = _fsyacc_tagOfErrorTerminal; - parseError = (fun (ctxt:Internal.Utilities.Text.Parsing.ParseErrorContext<_>) -> - match parse_error_rich with - | Some f -> f ctxt - | None -> parse_error ctxt.Message); - numTerminals = 21; - productionToNonTerminalTable = _fsyacc_productionToNonTerminalTable } -let engine lexer lexbuf startState = (tables ()).Interpret(lexer, lexbuf, startState) -let spec lexer lexbuf : AST.ParserSpec = - Microsoft.FSharp.Core.Operators.unbox ((tables ()).Interpret(lexer, lexbuf, 0)) diff --git a/src/fcs-fable/src/fsharp/AccessibilityLogic.fs b/src/fcs-fable/src/fsharp/AccessibilityLogic.fs index 009846bf4f..8a8fe70284 100644 --- a/src/fcs-fable/src/fsharp/AccessibilityLogic.fs +++ b/src/fcs-fable/src/fsharp/AccessibilityLogic.fs @@ -7,8 +7,9 @@ open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Infos -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals #if !NO_EXTENSIONTYPING @@ -136,7 +137,7 @@ let private IsILTypeInfoAccessible amap m ad (tcrefOfViewedItem : TyconRef) = match path with | [] -> assert false; true // in this case path should have at least one element | [x] -> IsILTypeDefAccessible amap m ad None x // shortcut for non-nested types - | x::xs -> + | x :: xs -> // check if enclosing type x is accessible. // if yes - create parent tycon for type 'x' and continue with the rest of the path IsILTypeDefAccessible amap m ad None x && @@ -148,7 +149,7 @@ let private IsILTypeInfoAccessible amap m ad (tcrefOfViewedItem : TyconRef) = | (Some (parentTycon, parentPath)) -> match path with | [] -> true // end of path is reached - success - | x::xs -> + | x :: xs -> // check if x is accessible from the parent tycon // if yes - create parent tycon for type 'x' and continue with the rest of the path IsILTypeDefAccessible amap m ad (Some parentTycon) x && diff --git a/src/fcs-fable/src/fsharp/AttributeChecking.fs b/src/fcs-fable/src/fsharp/AttributeChecking.fs index 17e01bdaba..a10bae194c 100644 --- a/src/fcs-fable/src/fsharp/AttributeChecking.fs +++ b/src/fcs-fable/src/fsharp/AttributeChecking.fs @@ -4,6 +4,7 @@ /// on items from name resolution module internal FSharp.Compiler.AttributeChecking +open System open System.Collections.Generic open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Library @@ -12,8 +13,8 @@ open FSharp.Compiler open FSharp.Compiler.Range open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Infos -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals #if !NO_EXTENSIONTYPING @@ -52,7 +53,7 @@ let rec private evalILAttribElem e = let rec private evalFSharpAttribArg g e = match e with - | Expr.Const(c, _, _) -> + | Expr.Const (c, _, _) -> match c with | Const.Bool b -> box b | Const.SByte i -> box i @@ -246,7 +247,6 @@ let MethInfoHasAttribute g m attribSpec minfo = |> Option.isSome - /// Check IL attributes for 'ObsoleteAttribute', returning errors and warnings as data let private CheckILAttributes (g: TcGlobals) isByrefLikeTyconRef cattrs m = let (AttribInfo(tref,_)) = g.attrib_SystemObsolete @@ -265,11 +265,23 @@ let private CheckILAttributes (g: TcGlobals) isByrefLikeTyconRef cattrs m = | _ -> CompleteD +let langVersionPrefix = "--langversion:preview" + /// Check F# attributes for 'ObsoleteAttribute', 'CompilerMessageAttribute' and 'ExperimentalAttribute', /// returning errors and warnings as data -let CheckFSharpAttributes g attribs m = - if isNil attribs then CompleteD - else +let CheckFSharpAttributes (g:TcGlobals) attribs m = + let isExperimentalAttributeDisabled (s:string) = + if g.compilingFslib then + true + else +#if FABLE_COMPILER + g.langVersion.IsPreviewEnabled && (s.ToLowerInvariant().IndexOf(langVersionPrefix) >= 0) +#else + g.langVersion.IsPreviewEnabled && (s.IndexOf(langVersionPrefix, StringComparison.OrdinalIgnoreCase) >= 0) +#endif + + if isNil attribs then CompleteD + else (match TryFindFSharpAttribute g g.attrib_SystemObsolete attribs with | Some(Attrib(_, _, [ AttribStringArg s ], _, _, _, _)) -> WarnD(ObsoleteWarning(s, m)) @@ -283,28 +295,30 @@ let CheckFSharpAttributes g attribs m = | None -> CompleteD ) ++ (fun () -> - + match TryFindFSharpAttribute g g.attrib_CompilerMessageAttribute attribs with - | Some(Attrib(_, _, [ AttribStringArg s ; AttribInt32Arg n ], namedArgs, _, _, _)) -> + | Some(Attrib(_, _, [ AttribStringArg s ; AttribInt32Arg n ], namedArgs, _, _, _)) -> let msg = UserCompilerMessage(s, n, m) let isError = match namedArgs with | ExtractAttribNamedArg "IsError" (AttribBoolArg v) -> v | _ -> false if isError && (not g.compilingFslib || n <> 1204) then ErrorD msg else WarnD msg - | _ -> CompleteD ) ++ (fun () -> - + match TryFindFSharpAttribute g g.attrib_ExperimentalAttribute attribs with - | Some(Attrib(_, _, [ AttribStringArg(s) ], _, _, _, _)) -> - WarnD(Experimental(s, m)) - | Some _ -> + | Some(Attrib(_, _, [ AttribStringArg(s) ], _, _, _, _)) -> + if isExperimentalAttributeDisabled s then + CompleteD + else + WarnD(Experimental(s, m)) + | Some _ -> WarnD(Experimental(FSComp.SR.experimentalConstruct (), m)) - | _ -> + | _ -> CompleteD - ) ++ (fun () -> + ) ++ (fun () -> match TryFindFSharpAttribute g g.attrib_UnverifiableAttribute attribs with | Some _ -> @@ -513,7 +527,7 @@ let IsSecurityAttribute (g: TcGlobals) amap (casmap : Dictionary) ( match attr.TyconRef.TryDeref with | ValueSome _ -> let tcs = tcref.Stamp - match casmap.TryGetValue(tcs) with + match casmap.TryGetValue tcs with | true, c -> c | _ -> let exists = ExistsInEntireHierarchyOfType (fun t -> typeEquiv g t (mkAppTy attr.TyconRef [])) g amap m AllowMultiIntfInstantiations.Yes (mkAppTy tcref []) diff --git a/src/fcs-fable/src/fsharp/AugmentWithHashCompare.fs b/src/fcs-fable/src/fsharp/AugmentWithHashCompare.fs old mode 100755 new mode 100644 index c859fb6388..0e00a30272 --- a/src/fcs-fable/src/fsharp/AugmentWithHashCompare.fs +++ b/src/fcs-fable/src/fsharp/AugmentWithHashCompare.fs @@ -6,12 +6,14 @@ module internal FSharp.Compiler.AugmentWithHashCompare open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.Ast open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.TcGlobals open FSharp.Compiler.Infos +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.XmlDoc let mkIComparableCompareToSlotSig (g: TcGlobals) = TSlotSig("CompareTo", g.mk_IComparable_ty, [], [], [[TSlotParam(Some("obj"), g.obj_ty, false, false, false, [])]], Some g.int_ty) @@ -81,20 +83,20 @@ let mkILLangPrimTy (g: TcGlobals) = mkILNonGenericBoxedTy g.tcref_LanguagePrimit let mkILCallGetComparer (g: TcGlobals) m = let ty = mkILNonGenericBoxedTy g.tcref_System_Collections_IComparer.CompiledRepresentationForNamedType let mspec = mkILNonGenericStaticMethSpecInTy (mkILLangPrimTy g, "get_GenericComparer", [], ty) - mkAsmExpr([IL.mkNormalCall mspec], [], [], [g.IComparer_ty], m) + mkAsmExpr ([IL.mkNormalCall mspec], [], [], [g.IComparer_ty], m) let mkILCallGetEqualityComparer (g: TcGlobals) m = let ty = mkILNonGenericBoxedTy g.tcref_System_Collections_IEqualityComparer.CompiledRepresentationForNamedType let mspec = mkILNonGenericStaticMethSpecInTy (mkILLangPrimTy g, "get_GenericEqualityComparer", [], ty) - mkAsmExpr([IL.mkNormalCall mspec], [], [], [g.IEqualityComparer_ty], m) + mkAsmExpr ([IL.mkNormalCall mspec], [], [], [g.IEqualityComparer_ty], m) let mkThisVar g m ty = mkCompGenLocal m "this" (mkThisTy g ty) -let mkShl g m acce n = mkAsmExpr([ IL.AI_shl ], [], [acce; mkInt g m n], [g.int_ty], m) +let mkShl g m acce n = mkAsmExpr ([ IL.AI_shl ], [], [acce; mkInt g m n], [g.int_ty], m) -let mkShr g m acce n = mkAsmExpr([ IL.AI_shr ], [], [acce; mkInt g m n], [g.int_ty], m) +let mkShr g m acce n = mkAsmExpr ([ IL.AI_shr ], [], [acce; mkInt g m n], [g.int_ty], m) -let mkAdd (g: TcGlobals) m e1 e2 = mkAsmExpr([ IL.AI_add ], [], [e1;e2], [g.int_ty], m) +let mkAdd (g: TcGlobals) m e1 e2 = mkAsmExpr ([ IL.AI_add ], [], [e1;e2], [g.int_ty], m) let mkAddToHashAcc g m e accv acce = mkValSet m accv (mkAdd g m (mkInt g m 0x9e3779b9) @@ -156,10 +158,10 @@ let mkCompareTestConjuncts g m exprs = (a, b) ||> List.foldBack (fun e acc -> let nv, ne = mkCompGenLocal m "n" g.int_ty mkCompGenLet m nv e - (mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.int_ty + (mkCond NoDebugPointAtStickyBinding DebugPointForTarget.No m g.int_ty (mkClt g m ne (mkZero g m)) ne - (mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.int_ty + (mkCond NoDebugPointAtStickyBinding DebugPointForTarget.No m g.int_ty (mkCgt g m ne (mkZero g m)) ne acc))) @@ -170,7 +172,7 @@ let mkEqualsTestConjuncts g m exprs = | [h] -> h | l -> let a, b = List.frontAndBack l - List.foldBack (fun e acc -> mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.bool_ty e acc (mkFalse g m)) a b + List.foldBack (fun e acc -> mkCond NoDebugPointAtStickyBinding DebugPointForTarget.No m g.bool_ty e acc (mkFalse g m)) a b let mkMinimalTy (g: TcGlobals) (tcref: TyconRef) = if tcref.Deref.IsExceptionDecl then [], g.exn_ty @@ -208,8 +210,8 @@ let mkRecdCompare g tcref (tycon: Tycon) = let m = fref.Range mkCallGenericComparisonWithComparerOuter g m fty compe - (mkRecdFieldGetViaExprAddr(thise, fref, tinst, m)) - (mkRecdFieldGetViaExprAddr(thataddre, fref, tinst, m)) + (mkRecdFieldGetViaExprAddr (thise, fref, tinst, m)) + (mkRecdFieldGetViaExprAddr (thataddre, fref, tinst, m)) let expr = mkCompareTestConjuncts g m (List.map mkTest fields) let expr = if tycon.IsStructOrEnumTycon then expr else mkBindNullComparison g m thise thataddre expr @@ -217,7 +219,6 @@ let mkRecdCompare g tcref (tycon: Tycon) = let thatv, expr = mkThatVarBind g m ty thataddrv expr thisv, thatv, expr - /// Build the comparison implementation for a record type when parameterized by a comparer let mkRecdCompareWithComparer g tcref (tycon: Tycon) (_thisv, thise) (_, thate) compe = let m = tycon.Range @@ -232,8 +233,8 @@ let mkRecdCompareWithComparer g tcref (tycon: Tycon) (_thisv, thise) (_, thate) let m = fref.Range mkCallGenericComparisonWithComparerOuter g m fty compe - (mkRecdFieldGetViaExprAddr(thise, fref, tinst, m)) - (mkRecdFieldGetViaExprAddr(thataddre, fref, tinst, m)) + (mkRecdFieldGetViaExprAddr (thise, fref, tinst, m)) + (mkRecdFieldGetViaExprAddr (thataddre, fref, tinst, m)) let expr = mkCompareTestConjuncts g m (List.map mkTest fields) let expr = if tycon.IsStructOrEnumTycon then expr else mkBindNullComparison g m thise thate expr @@ -243,7 +244,6 @@ let mkRecdCompareWithComparer g tcref (tycon: Tycon) (_thisv, thise) (_, thate) let expr = mkCompGenLet m tcv thate expr expr - /// Build the .Equals(that) equality implementation wrapper for a record type let mkRecdEquality g tcref (tycon: Tycon) = let m = tycon.Range @@ -255,8 +255,8 @@ let mkRecdEquality g tcref (tycon: Tycon) = let fref = tcref.MakeNestedRecdFieldRef fspec let m = fref.Range mkCallGenericEqualityEROuter g m fty - (mkRecdFieldGetViaExprAddr(thise, fref, tinst, m)) - (mkRecdFieldGetViaExprAddr(thataddre, fref, tinst, m)) + (mkRecdFieldGetViaExprAddr (thise, fref, tinst, m)) + (mkRecdFieldGetViaExprAddr (thataddre, fref, tinst, m)) let expr = mkEqualsTestConjuncts g m (List.map mkTest fields) let expr = if tycon.IsStructOrEnumTycon then expr else mkBindThatNullEquals g m thise thataddre expr @@ -278,8 +278,8 @@ let mkRecdEqualityWithComparer g tcref (tycon: Tycon) (_thisv, thise) thatobje ( mkCallGenericEqualityWithComparerOuter g m fty compe - (mkRecdFieldGetViaExprAddr(thise, fref, tinst, m)) - (mkRecdFieldGetViaExprAddr(thataddre, fref, tinst, m)) + (mkRecdFieldGetViaExprAddr (thise, fref, tinst, m)) + (mkRecdFieldGetViaExprAddr (thataddre, fref, tinst, m)) let expr = mkEqualsTestConjuncts g m (List.map mkTest fields) let expr = mkBindThatAddr g m ty thataddrv thatv thate expr @@ -299,20 +299,19 @@ let mkExnEquality (g: TcGlobals) exnref (exnc: Tycon) = mkCallGenericEqualityEROuter g m fty (mkExnCaseFieldGet(thise, exnref, i, m)) (mkExnCaseFieldGet(thate, exnref, i, m)) - let expr = mkEqualsTestConjuncts g m (List.mapi mkTest (exnc.AllInstanceFieldsAsList)) + let expr = mkEqualsTestConjuncts g m (List.mapi mkTest exnc.AllInstanceFieldsAsList) let expr = - let mbuilder = new MatchBuilder(NoSequencePointAtInvisibleBinding, m ) + let mbuilder = new MatchBuilder(NoDebugPointAtInvisibleBinding, m ) let cases = [ mkCase(DecisionTreeTest.IsInst(g.exn_ty, mkAppTy exnref []), - mbuilder.AddResultTarget(expr, SuppressSequencePointAtTarget)) ] - let dflt = Some(mbuilder.AddResultTarget(mkFalse g m, SuppressSequencePointAtTarget)) + mbuilder.AddResultTarget(expr, DebugPointForTarget.No)) ] + let dflt = Some(mbuilder.AddResultTarget(mkFalse g m, DebugPointForTarget.No)) let dtree = TDSwitch(thate, cases, dflt, m) mbuilder.Close(dtree, m, g.bool_ty) let expr = mkBindThatNullEquals g m thise thate expr thisv, thatv, expr - /// Build the equality implementation for an exception definition when parameterized by a comparer let mkExnEqualityWithComparer g exnref (exnc: Tycon) (_thisv, thise) thatobje (thatv, thate) compe = let m = exnc.Range @@ -323,13 +322,13 @@ let mkExnEqualityWithComparer g exnref (exnc: Tycon) (_thisv, thise) thatobje (t compe (mkExnCaseFieldGet(thise, exnref, i, m)) (mkExnCaseFieldGet(thataddre, exnref, i, m)) - let expr = mkEqualsTestConjuncts g m (List.mapi mkTest (exnc.AllInstanceFieldsAsList)) + let expr = mkEqualsTestConjuncts g m (List.mapi mkTest exnc.AllInstanceFieldsAsList) let expr = - let mbuilder = new MatchBuilder(NoSequencePointAtInvisibleBinding, m ) + let mbuilder = new MatchBuilder(NoDebugPointAtInvisibleBinding, m ) let cases = [ mkCase(DecisionTreeTest.IsInst(g.exn_ty, mkAppTy exnref []), - mbuilder.AddResultTarget(expr, SuppressSequencePointAtTarget)) ] - let dflt = mbuilder.AddResultTarget(mkFalse g m, SuppressSequencePointAtTarget) + mbuilder.AddResultTarget(expr, DebugPointForTarget.No)) ] + let dflt = mbuilder.AddResultTarget(mkFalse g m, DebugPointForTarget.No) let dtree = TDSwitch(thate, cases, Some dflt, m) mbuilder.Close(dtree, m, g.bool_ty) let expr = mkBindThatAddr g m g.exn_ty thataddrv thatv thate expr @@ -348,7 +347,7 @@ let mkUnionCompare g tcref (tycon: Tycon) = let compe = mkILCallGetComparer g m let expr = - let mbuilder = new MatchBuilder(NoSequencePointAtInvisibleBinding, m ) + let mbuilder = new MatchBuilder(NoDebugPointAtInvisibleBinding, m ) let mkCase ucase = let cref = tcref.MakeNestedUnionCaseRef ucase let m = cref.Range @@ -357,8 +356,8 @@ let mkUnionCompare g tcref (tycon: Tycon) = let mkTest thise thataddre j (argty: RecdField) = mkCallGenericComparisonWithComparerOuter g m argty.FormalType compe - (mkUnionCaseFieldGetProvenViaExprAddr(thise, cref, tinst, j, m)) - (mkUnionCaseFieldGetProvenViaExprAddr(thataddre, cref, tinst, j, m)) + (mkUnionCaseFieldGetProvenViaExprAddr (thise, cref, tinst, j, m)) + (mkUnionCaseFieldGetProvenViaExprAddr (thataddre, cref, tinst, j, m)) let test = if cref.Tycon.IsStructOrEnumTycon then mkCompareTestConjuncts g m (List.mapi (mkTest thise thataddre) rfields) @@ -368,19 +367,19 @@ let mkUnionCompare g tcref (tycon: Tycon) = mkCompGenLet m thisucv (mkUnionCaseProof (thise, cref, tinst, m)) (mkCompGenLet m thatucv (mkUnionCaseProof (thataddre, cref, tinst, m)) (mkCompareTestConjuncts g m (List.mapi (mkTest thisucve thatucve) rfields))) - Some (mkCase(DecisionTreeTest.UnionCase(cref, tinst), mbuilder.AddResultTarget(test, SuppressSequencePointAtTarget))) + Some (mkCase(DecisionTreeTest.UnionCase(cref, tinst), mbuilder.AddResultTarget(test, DebugPointForTarget.No))) let nullary, nonNullary = List.partition Option.isNone (List.map mkCase ucases) if isNil nonNullary then mkZero g m else let cases = nonNullary |> List.map (function (Some c) -> c | None -> failwith "mkUnionCompare") - let dflt = if isNil nullary then None else Some (mbuilder.AddResultTarget(mkZero g m, SuppressSequencePointAtTarget)) + let dflt = if isNil nullary then None else Some (mbuilder.AddResultTarget(mkZero g m, DebugPointForTarget.No)) let dtree = TDSwitch(thise, cases, dflt, m) mbuilder.Close(dtree, m, g.int_ty) let expr = if ucases.Length = 1 then expr else let tagsEqTested = - mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.int_ty + mkCond NoDebugPointAtStickyBinding DebugPointForTarget.No m g.int_ty (mkILAsmCeq g m thistage thattage) expr (mkAsmExpr ([ IL.AI_sub ], [], [thistage; thattage], [g.int_ty], m))in @@ -406,7 +405,7 @@ let mkUnionCompareWithComparer g tcref (tycon: Tycon) (_thisv, thise) (_thatobjv let thattagv, thattage = mkCompGenLocal m "thatTag" g.int_ty let expr = - let mbuilder = new MatchBuilder(NoSequencePointAtInvisibleBinding, m ) + let mbuilder = new MatchBuilder(NoDebugPointAtInvisibleBinding, m ) let mkCase ucase = let cref = tcref.MakeNestedUnionCaseRef ucase let m = cref.Range @@ -416,8 +415,8 @@ let mkUnionCompareWithComparer g tcref (tycon: Tycon) (_thisv, thise) (_thatobjv let mkTest thise thataddre j (argty: RecdField) = mkCallGenericComparisonWithComparerOuter g m argty.FormalType compe - (mkUnionCaseFieldGetProvenViaExprAddr(thise, cref, tinst, j, m)) - (mkUnionCaseFieldGetProvenViaExprAddr(thataddre, cref, tinst, j, m)) + (mkUnionCaseFieldGetProvenViaExprAddr (thise, cref, tinst, j, m)) + (mkUnionCaseFieldGetProvenViaExprAddr (thataddre, cref, tinst, j, m)) let test = if cref.Tycon.IsStructOrEnumTycon then @@ -429,19 +428,19 @@ let mkUnionCompareWithComparer g tcref (tycon: Tycon) (_thisv, thise) (_thatobjv (mkCompGenLet m thatucv (mkUnionCaseProof (thataddre, cref, tinst, m)) (mkCompareTestConjuncts g m (List.mapi (mkTest thisucve thatucve) rfields))) - Some (mkCase(DecisionTreeTest.UnionCase(cref, tinst), mbuilder.AddResultTarget(test, SuppressSequencePointAtTarget))) + Some (mkCase(DecisionTreeTest.UnionCase(cref, tinst), mbuilder.AddResultTarget(test, DebugPointForTarget.No))) let nullary, nonNullary = List.partition Option.isNone (List.map mkCase ucases) if isNil nonNullary then mkZero g m else let cases = nonNullary |> List.map (function (Some c) -> c | None -> failwith "mkUnionCompare") - let dflt = if isNil nullary then None else Some (mbuilder.AddResultTarget(mkZero g m, SuppressSequencePointAtTarget)) + let dflt = if isNil nullary then None else Some (mbuilder.AddResultTarget(mkZero g m, DebugPointForTarget.No)) let dtree = TDSwitch(thise, cases, dflt, m) mbuilder.Close(dtree, m, g.int_ty) let expr = if ucases.Length = 1 then expr else let tagsEqTested = - mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.int_ty + mkCond NoDebugPointAtStickyBinding DebugPointForTarget.No m g.int_ty (mkILAsmCeq g m thistage thattage) expr (mkAsmExpr ([ IL.AI_sub ], [], [thistage; thattage], [g.int_ty], m)) @@ -467,7 +466,7 @@ let mkUnionEquality g tcref (tycon: Tycon) = let thattagv, thattage = mkCompGenLocal m "thatTag" g.int_ty let expr = - let mbuilder = new MatchBuilder(NoSequencePointAtInvisibleBinding, m ) + let mbuilder = new MatchBuilder(NoDebugPointAtInvisibleBinding, m ) let mkCase ucase = let cref = tcref.MakeNestedUnionCaseRef ucase let m = cref.Range @@ -476,8 +475,8 @@ let mkUnionEquality g tcref (tycon: Tycon) = let mkTest thise thataddre j (argty: RecdField) = mkCallGenericEqualityEROuter g m argty.FormalType - (mkUnionCaseFieldGetProvenViaExprAddr(thise, cref, tinst, j, m)) - (mkUnionCaseFieldGetProvenViaExprAddr(thataddre, cref, tinst, j, m)) + (mkUnionCaseFieldGetProvenViaExprAddr (thise, cref, tinst, j, m)) + (mkUnionCaseFieldGetProvenViaExprAddr (thataddre, cref, tinst, j, m)) let test = if cref.Tycon.IsStructOrEnumTycon then @@ -489,19 +488,19 @@ let mkUnionEquality g tcref (tycon: Tycon) = (mkCompGenLet m thatucv (mkUnionCaseProof (thataddre, cref, tinst, m)) (mkEqualsTestConjuncts g m (List.mapi (mkTest thisucve thatucve) rfields))) - Some (mkCase(DecisionTreeTest.UnionCase(cref, tinst), mbuilder.AddResultTarget(test, SuppressSequencePointAtTarget))) + Some (mkCase(DecisionTreeTest.UnionCase(cref, tinst), mbuilder.AddResultTarget(test, DebugPointForTarget.No))) let nullary, nonNullary = List.partition Option.isNone (List.map mkCase ucases) if isNil nonNullary then mkTrue g m else let cases = List.map (function (Some c) -> c | None -> failwith "mkUnionEquality") nonNullary - let dflt = (if isNil nullary then None else Some (mbuilder.AddResultTarget(mkTrue g m, SuppressSequencePointAtTarget))) + let dflt = (if isNil nullary then None else Some (mbuilder.AddResultTarget(mkTrue g m, DebugPointForTarget.No))) let dtree = TDSwitch(thise, cases, dflt, m) mbuilder.Close(dtree, m, g.bool_ty) let expr = if ucases.Length = 1 then expr else let tagsEqTested = - mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.bool_ty + mkCond NoDebugPointAtStickyBinding DebugPointForTarget.No m g.bool_ty (mkILAsmCeq g m thistage thattage) expr (mkFalse g m) @@ -526,7 +525,7 @@ let mkUnionEqualityWithComparer g tcref (tycon: Tycon) (_thisv, thise) thatobje let thataddrv, thataddre = mkThatAddrLocal g m ty let expr = - let mbuilder = new MatchBuilder(NoSequencePointAtInvisibleBinding, m ) + let mbuilder = new MatchBuilder(NoDebugPointAtInvisibleBinding, m ) let mkCase ucase = let cref = tcref.MakeNestedUnionCaseRef ucase let m = cref.Range @@ -537,8 +536,8 @@ let mkUnionEqualityWithComparer g tcref (tycon: Tycon) (_thisv, thise) thatobje let mkTest thise thataddre j (argty: RecdField) = mkCallGenericEqualityWithComparerOuter g m argty.FormalType compe - (mkUnionCaseFieldGetProvenViaExprAddr(thise, cref, tinst, j, m)) - (mkUnionCaseFieldGetProvenViaExprAddr(thataddre, cref, tinst, j, m)) + (mkUnionCaseFieldGetProvenViaExprAddr (thise, cref, tinst, j, m)) + (mkUnionCaseFieldGetProvenViaExprAddr (thataddre, cref, tinst, j, m)) let test = if cref.Tycon.IsStructOrEnumTycon then @@ -551,19 +550,19 @@ let mkUnionEqualityWithComparer g tcref (tycon: Tycon) (_thisv, thise) thatobje (mkCompGenLet m thatucv (mkUnionCaseProof (thataddre, cref, tinst, m)) (mkEqualsTestConjuncts g m (List.mapi (mkTest thisucve thatucve) rfields))) - Some (mkCase(DecisionTreeTest.UnionCase(cref, tinst), mbuilder.AddResultTarget (test, SuppressSequencePointAtTarget))) + Some (mkCase(DecisionTreeTest.UnionCase(cref, tinst), mbuilder.AddResultTarget (test, DebugPointForTarget.No))) let nullary, nonNullary = List.partition Option.isNone (List.map mkCase ucases) if isNil nonNullary then mkTrue g m else let cases = List.map (function (Some c) -> c | None -> failwith "mkUnionEquality") nonNullary - let dflt = if isNil nullary then None else Some (mbuilder.AddResultTarget(mkTrue g m, SuppressSequencePointAtTarget)) + let dflt = if isNil nullary then None else Some (mbuilder.AddResultTarget(mkTrue g m, DebugPointForTarget.No)) let dtree = TDSwitch(thise, cases, dflt, m) mbuilder.Close(dtree, m, g.bool_ty) let expr = if ucases.Length = 1 then expr else let tagsEqTested = - mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.bool_ty + mkCond NoDebugPointAtStickyBinding DebugPointForTarget.No m g.bool_ty (mkILAsmCeq g m thistage thattage) expr (mkFalse g m) @@ -593,7 +592,7 @@ let mkRecdHashWithComparer g tcref (tycon: Tycon) compe = let fty = fspec.FormalType let fref = tcref.MakeNestedRecdFieldRef fspec let m = fref.Range - let e = mkRecdFieldGetViaExprAddr(thise, fref, tinst, m) + let e = mkRecdFieldGetViaExprAddr (thise, fref, tinst, m) mkCallGenericHashWithComparerOuter g m fty compe e @@ -615,7 +614,7 @@ let mkExnHashWithComparer g exnref (exnc: Tycon) compe = mkCallGenericHashWithComparerOuter g m fty compe e let accv, acce = mkMutableCompGenLocal m "i" g.int_ty - let stmt = mkCombineHashGenerators g m (List.mapi mkHash (exnc.AllInstanceFieldsAsList)) (mkLocalValRef accv) acce + let stmt = mkCombineHashGenerators g m (List.mapi mkHash exnc.AllInstanceFieldsAsList) (mkLocalValRef accv) acce let expr = mkCompGenLet m accv (mkZero g m) stmt let expr = mkBindNullHash g m thise expr thisv, expr @@ -626,7 +625,7 @@ let mkUnionHashWithComparer g tcref (tycon: Tycon) compe = let ucases = tycon.UnionCasesAsList let tinst, ty = mkMinimalTy g tcref let thisv, thise = mkThisVar g m ty - let mbuilder = new MatchBuilder(NoSequencePointAtInvisibleBinding, m ) + let mbuilder = new MatchBuilder(NoDebugPointAtInvisibleBinding, m ) let accv, acce = mkMutableCompGenLocal m "i" g.int_ty let mkCase i ucase1 = let c1ref = tcref.MakeNestedUnionCaseRef ucase1 @@ -635,7 +634,7 @@ let mkUnionHashWithComparer g tcref (tycon: Tycon) compe = else let mkHash thise j (rfield: RecdField) = let fty = rfield.FormalType - let e = mkUnionCaseFieldGetProvenViaExprAddr(thise, c1ref, tinst, j, m) + let e = mkUnionCaseFieldGetProvenViaExprAddr (thise, c1ref, tinst, j, m) mkCallGenericHashWithComparerOuter g m fty compe e let test = @@ -650,7 +649,7 @@ let mkUnionHashWithComparer g tcref (tycon: Tycon) compe = (mkCompGenSequential m (mkValSet m (mkLocalValRef accv) (mkInt g m i)) (mkCombineHashGenerators g m (List.mapi (mkHash ucve) ucase1.RecdFields) (mkLocalValRef accv) acce)) - Some(mkCase(DecisionTreeTest.UnionCase(c1ref, tinst), mbuilder.AddResultTarget(test, SuppressSequencePointAtTarget))) + Some(mkCase(DecisionTreeTest.UnionCase(c1ref, tinst), mbuilder.AddResultTarget(test, DebugPointForTarget.No))) let nullary, nonNullary = ucases |> List.mapi mkCase @@ -659,7 +658,7 @@ let mkUnionHashWithComparer g tcref (tycon: Tycon) compe = let dflt = if isNil nullary then None else let tag = mkUnionCaseTagGetViaExprAddr (thise, tcref, tinst, m) - Some(mbuilder.AddResultTarget(tag, SuppressSequencePointAtTarget)) + Some(mbuilder.AddResultTarget(tag, DebugPointForTarget.No)) let dtree = TDSwitch(thise, cases, dflt, m) let stmt = mbuilder.Close(dtree, m, g.int_ty) let expr = mkCompGenLet m accv (mkZero g m) stmt @@ -715,68 +714,67 @@ let CheckAugmentationAttribs isImplementation g amap (tycon: Tycon) = | _, _, None, None, None, None, None, None, None // [] on union/record/struct - | true, _, None, Some(true), None, None, None, Some(true), None + | true, _, None, Some true, None, None, None, Some true, None // [] on union/record/struct - | true, _, None, Some(true), None, None, Some(true), None, None -> + | true, _, None, Some true, None, None, Some true, None, None -> () // [] on union/record/struct - | true, _, None, None, Some(true), None, Some(true), None, None + | true, _, None, None, Some true, None, Some true, None, None // [] on union/record/struct - | true, _, None, None, Some(true), None, None, None, None -> + | true, _, None, None, Some true, None, None, None, None -> if isTrueFSharpStructTycon g tycon then errorR(Error(FSComp.SR.augNoRefEqualsOnStruct(), m)) else () // [] on union/record/struct - | true, true, None, None, None, Some(true), None, None, Some(true) + | true, true, None, None, None, Some true, None, None, Some true // [] - | true, _, None, None, None, Some(true), Some(true), None, None + | true, _, None, None, None, Some true, Some true, None, None // [] - | true, _, None, None, None, Some(true), None, Some(true), None + | true, _, None, None, None, Some true, None, Some true, None // [] on anything - | _, _, None, None, None, None, Some(true), None, None + | _, _, None, None, None, None, Some true, None, None // [] on anything - | _, _, Some(true), None, None, None, Some(true), None, None -> - + | _, _, Some true, None, None, None, Some true, None, None -> () - (* THESE ARE THE ERROR CASES *) + // THESE ARE THE ERROR CASES // [] - | _, _, Some(true), _, _, _, None, _, _ -> + | _, _, Some true, _, _, _, None, _, _ -> errorR(Error(FSComp.SR.augNoEqualityNeedsNoComparison(), m)) // [] - | true, true, _, _, _, None, _, _, Some(true) -> + | true, true, _, _, _, None, _, _, Some true -> errorR(Error(FSComp.SR.augStructCompNeedsStructEquality(), m)) // [] - | true, _, _, _, _, Some(true), None, _, None -> + | true, _, _, _, _, Some true, None, _, None -> errorR(Error(FSComp.SR.augStructEqNeedsNoCompOrStructComp(), m)) // [] - | true, _, _, Some(true), _, _, None, None, _ -> + | true, _, _, Some true, _, _, None, None, _ -> errorR(Error(FSComp.SR.augCustomEqNeedsNoCompOrCustomComp(), m)) // [] - | true, _, _, _, Some(true), Some(true), _, _, _ + | true, _, _, _, Some true, Some true, _, _, _ // [] - | true, _, _, _, Some(true), _, _, _, Some(true) -> + | true, _, _, _, Some true, _, _, _, Some true -> errorR(Error(FSComp.SR.augTypeCantHaveRefEqAndStructAttrs(), m)) // non augmented type, [] // non augmented type, [] // non augmented type, [] - | false, _, _, _, Some(true), _, _, _, _ - | false, _, _, _, _, Some(true), _, _, _ - | false, _, _, _, _, _, _, _, Some(true) -> + | false, _, _, _, Some true, _, _, _, _ + | false, _, _, _, _, Some true, _, _, _ + | false, _, _, _, _, _, _, _, Some true -> errorR(Error(FSComp.SR.augOnlyCertainTypesCanHaveAttrs(), m)) // All other cases | _ -> @@ -802,21 +800,21 @@ let CheckAugmentationAttribs isImplementation g amap (tycon: Tycon) = match attribs with // [] + any equality semantics - | _, _, Some(true), _, _, _, _, _, _ when (hasExplicitEquals || hasExplicitGenericEquals) -> + | _, _, Some true, _, _, _, _, _, _ when (hasExplicitEquals || hasExplicitGenericEquals) -> warning(Error(FSComp.SR.augNoEqNeedsNoObjEquals(), m)) // [] + any comparison semantics - | _, _, _, _, _, _, Some(true), _, _ when (hasExplicitICompare || hasExplicitIGenericCompare) -> + | _, _, _, _, _, _, Some true, _, _ when (hasExplicitICompare || hasExplicitIGenericCompare) -> warning(Error(FSComp.SR.augNoCompCantImpIComp(), m)) // [] + no explicit override Object.Equals + no explicit IStructuralEquatable - | _, _, _, Some(true), _, _, _, _, _ when isImplementation && not hasExplicitEquals && not hasExplicitGenericEquals-> + | _, _, _, Some true, _, _, _, _, _ when isImplementation && not hasExplicitEquals && not hasExplicitGenericEquals-> errorR(Error(FSComp.SR.augCustomEqNeedsObjEquals(), m)) // [] + no explicit IComparable + no explicit IStructuralComparable - | _, _, _, _, _, _, _, Some(true), _ when isImplementation && not hasExplicitICompare && not hasExplicitIGenericCompare -> + | _, _, _, _, _, _, _, Some true, _ when isImplementation && not hasExplicitICompare && not hasExplicitIGenericCompare -> errorR(Error(FSComp.SR.augCustomCompareNeedsIComp(), m)) // [] + any equality semantics - | _, _, _, _, Some(true), _, _, _, _ when (hasExplicitEquals || hasExplicitIGenericCompare) -> + | _, _, _, _, Some true, _, _, _, _ when (hasExplicitEquals || hasExplicitIGenericCompare) -> errorR(Error(FSComp.SR.augRefEqCantHaveObjEquals(), m)) | _ -> @@ -831,9 +829,9 @@ let TyconIsCandidateForAugmentationWithCompare (g: TcGlobals) (tycon: Tycon) = // [< >] | true, true, None, None, None, None, None, None, None // [] - | true, true, None, None, None, Some(true), None, None, Some(true) + | true, true, None, None, None, Some true, None, None, Some true // [] - | true, true, None, None, None, None, None, None, Some(true) -> true + | true, true, None, None, None, None, None, None, Some true -> true // other cases | _ -> false @@ -848,7 +846,7 @@ let TyconIsCandidateForAugmentationWithEquals (g: TcGlobals) (tycon: Tycon) = | true, _, None, None, None, None, _, _, _ // [] // [] - | true, _, None, None, None, Some(true), _, _, _ -> true + | true, _, None, None, None, Some true, _, _, _ -> true // other cases | _ -> false @@ -883,15 +881,19 @@ let nonVirtualMethod c : ValMemberInfo = let unitArg = ValReprInfo.unitArgData let unaryArg = [ ValReprInfo.unnamedTopArg ] let tupArg = [ [ ValReprInfo.unnamedTopArg1; ValReprInfo.unnamedTopArg1 ] ] -let mkValSpec g (tcref: TyconRef) tmty vis slotsig methn ty argData = +let mkValSpec g (tcref: TyconRef) tmty vis slotsig methn ty argData = let m = tcref.Range - let tps = tcref.Typars(m) - let final = isUnionTy g tmty || isRecdTy g tmty || isStructTy g tmty - let membInfo = match slotsig with None -> nonVirtualMethod tcref | Some(slotsig) -> slotImplMethod(final, tcref, slotsig) + let tps = tcref.Typars m + let membInfo = + match slotsig with + | None -> nonVirtualMethod tcref + | Some slotsig -> + let final = isUnionTy g tmty || isRecdTy g tmty || isStructTy g tmty + slotImplMethod(final, tcref, slotsig) let inl = ValInline.Optional let args = ValReprInfo.unnamedTopArg :: argData let topValInfo = Some (ValReprInfo (ValReprInfo.InferTyparInfo tps, args, ValReprInfo.unnamedRetVal)) - NewVal (methn, m, None, ty, Immutable, true, topValInfo, vis, ValNotInRecScope, Some(membInfo), NormalVal, [], inl, XmlDoc.Empty, true, false, false, false, false, false, None, Parent(tcref)) + Construct.NewVal (methn, m, None, ty, Immutable, true, topValInfo, vis, ValNotInRecScope, Some membInfo, NormalVal, [], inl, XmlDoc.Empty, true, false, false, false, false, false, None, Parent tcref) let MakeValsForCompareAugmentation g (tcref: TyconRef) = let m = tcref.Range @@ -899,8 +901,8 @@ let MakeValsForCompareAugmentation g (tcref: TyconRef) = let tps = tcref.Typars m let vis = tcref.TypeReprAccessibility - mkValSpec g tcref tmty vis (Some(mkIComparableCompareToSlotSig g)) "CompareTo" (tps +-> (mkCompareObjTy g tmty)) unaryArg, - mkValSpec g tcref tmty vis (Some(mkGenericIComparableCompareToSlotSig g tmty)) "CompareTo" (tps +-> (mkCompareTy g tmty)) unaryArg + mkValSpec g tcref tmty vis (Some(mkIComparableCompareToSlotSig g)) "CompareTo" (tps +-> (mkCompareObjTy g tmty)) unaryArg, + mkValSpec g tcref tmty vis (Some(mkGenericIComparableCompareToSlotSig g tmty)) "CompareTo" (tps +-> (mkCompareTy g tmty)) unaryArg let MakeValsForCompareWithComparerAugmentation g (tcref: TyconRef) = let m = tcref.Range @@ -915,15 +917,15 @@ let MakeValsForEqualsAugmentation g (tcref: TyconRef) = let vis = tcref.TypeReprAccessibility let tps = tcref.Typars m - let objEqualsVal = mkValSpec g tcref tmty vis (Some(mkEqualsSlotSig g)) "Equals" (tps +-> (mkEqualsObjTy g tmty)) unaryArg - let nocEqualsVal = mkValSpec g tcref tmty vis (if tcref.Deref.IsExceptionDecl then None else Some(mkGenericIEquatableEqualsSlotSig g tmty)) "Equals" (tps +-> (mkEqualsTy g tmty)) unaryArg + let objEqualsVal = mkValSpec g tcref tmty vis (Some(mkEqualsSlotSig g)) "Equals" (tps +-> (mkEqualsObjTy g tmty)) unaryArg + let nocEqualsVal = mkValSpec g tcref tmty vis (if tcref.Deref.IsExceptionDecl then None else Some(mkGenericIEquatableEqualsSlotSig g tmty)) "Equals" (tps +-> (mkEqualsTy g tmty)) unaryArg objEqualsVal, nocEqualsVal let MakeValsForEqualityWithComparerAugmentation g (tcref: TyconRef) = let _, tmty = mkMinimalTy g tcref let vis = tcref.TypeReprAccessibility - let tps = tcref.Typars(tcref.Range) - let objGetHashCodeVal = mkValSpec g tcref tmty vis (Some(mkGetHashCodeSlotSig g)) "GetHashCode" (tps +-> (mkHashTy g tmty)) unitArg + let tps = tcref.Typars tcref.Range + let objGetHashCodeVal = mkValSpec g tcref tmty vis (Some(mkGetHashCodeSlotSig g)) "GetHashCode" (tps +-> (mkHashTy g tmty)) unitArg let withcGetHashCodeVal = mkValSpec g tcref tmty vis (Some(mkIStructuralEquatableGetHashCodeSlotSig g)) "GetHashCode" (tps +-> (mkHashWithComparerTy g tmty)) unaryArg let withcEqualsVal = mkValSpec g tcref tmty vis (Some(mkIStructuralEquatableEqualsSlotSig g)) "Equals" (tps +-> (mkEqualsWithComparerTy g tmty)) tupArg objGetHashCodeVal, withcGetHashCodeVal, withcEqualsVal @@ -931,7 +933,7 @@ let MakeValsForEqualityWithComparerAugmentation g (tcref: TyconRef) = let MakeBindingsForCompareAugmentation g (tycon: Tycon) = let tcref = mkLocalTyconRef tycon let m = tycon.Range - let tps = tycon.Typars(tycon.Range) + let tps = tycon.Typars m let mkCompare comparef = match tycon.GeneratedCompareToValues with | None -> [] @@ -964,11 +966,11 @@ let MakeBindingsForCompareAugmentation g (tycon: Tycon) = let MakeBindingsForCompareWithComparerAugmentation g (tycon: Tycon) = let tcref = mkLocalTyconRef tycon let m = tycon.Range - let tps = tycon.Typars(tycon.Range) + let tps = tycon.Typars m let mkCompare comparef = match tycon.GeneratedCompareToWithComparerValues with | None -> [] - | Some (vref) -> + | Some vref -> let vspec = vref.Deref let _, ty = mkMinimalTy g tcref @@ -990,7 +992,7 @@ let MakeBindingsForCompareWithComparerAugmentation g (tycon: Tycon) = let MakeBindingsForEqualityWithComparerAugmentation (g: TcGlobals) (tycon: Tycon) = let tcref = mkLocalTyconRef tycon let m = tycon.Range - let tps = tycon.Typars(tycon.Range) + let tps = tycon.Typars m let mkStructuralEquatable hashf equalsf = match tycon.GeneratedHashAndEqualsWithComparerValues with | None -> [] @@ -1037,7 +1039,7 @@ let MakeBindingsForEqualityWithComparerAugmentation (g: TcGlobals) (tycon: Tycon let MakeBindingsForEqualsAugmentation (g: TcGlobals) (tycon: Tycon) = let tcref = mkLocalTyconRef tycon let m = tycon.Range - let tps = tycon.Typars(m) + let tps = tycon.Typars m let mkEquals equalsf = match tycon.GeneratedHashAndEqualsValues with | None -> [] @@ -1071,23 +1073,28 @@ let MakeBindingsForEqualsAugmentation (g: TcGlobals) (tycon: Tycon) = elif tycon.IsRecordTycon || tycon.IsStructOrEnumTycon then mkEquals mkRecdEquality else [] -let rec TypeDefinitelyHasEquality g ty = - if isAppTy g ty && HasFSharpAttribute g g.attrib_NoEqualityAttribute (tcrefOfAppTy g ty).Attribs then +let rec TypeDefinitelyHasEquality g ty = + let appTy = tryAppTy g ty + match appTy with + | ValueSome(tcref,_) when HasFSharpAttribute g g.attrib_NoEqualityAttribute tcref.Attribs -> false - elif isTyparTy g ty && - (destTyparTy g ty).Constraints |> List.exists (function TyparConstraint.SupportsEquality _ -> true | _ -> false) then - true - else - match ty with - | SpecialEquatableHeadType g tinst -> - tinst |> List.forall (TypeDefinitelyHasEquality g) - | SpecialNotEquatableHeadType g _ -> - false - | _ -> - // The type is equatable because it has Object.Equals(...) - isAppTy g ty && - let tcref, tinst = destAppTy g ty - // Give a good error for structural types excluded from the equality relation because of their fields - not (TyconIsCandidateForAugmentationWithEquals g tcref.Deref && Option.isNone tcref.GeneratedHashAndEqualsWithComparerValues) && - // Check the (possibly inferred) structural dependencies - (tinst, tcref.TyparsNoRange) ||> List.lengthsEqAndForall2 (fun ty tp -> not tp.EqualityConditionalOn || TypeDefinitelyHasEquality g ty) + | _ -> + if isTyparTy g ty && + (destTyparTy g ty).Constraints |> List.exists (function TyparConstraint.SupportsEquality _ -> true | _ -> false) then + true + else + match ty with + | SpecialEquatableHeadType g tinst -> + tinst |> List.forall (TypeDefinitelyHasEquality g) + | SpecialNotEquatableHeadType g _ -> + false + | _ -> + // The type is equatable because it has Object.Equals(...) + match appTy with + | ValueSome(tcref,tinst) -> + // Give a good error for structural types excluded from the equality relation because of their fields + not (TyconIsCandidateForAugmentationWithEquals g tcref.Deref && Option.isNone tcref.GeneratedHashAndEqualsWithComparerValues) && + // Check the (possibly inferred) structural dependencies + (tinst, tcref.TyparsNoRange) + ||> List.lengthsEqAndForall2 (fun ty tp -> not tp.EqualityConditionalOn || TypeDefinitelyHasEquality g ty) + | _ -> false diff --git a/src/fcs-fable/src/fsharp/AugmentWithHashCompare.fsi b/src/fcs-fable/src/fsharp/AugmentWithHashCompare.fsi old mode 100755 new mode 100644 index 13d3f18f0e..da5b50018f --- a/src/fcs-fable/src/fsharp/AugmentWithHashCompare.fsi +++ b/src/fcs-fable/src/fsharp/AugmentWithHashCompare.fsi @@ -4,22 +4,31 @@ module internal FSharp.Compiler.AugmentWithHashCompare open FSharp.Compiler -open FSharp.Compiler.Tast +open FSharp.Compiler.TypedTree open FSharp.Compiler.TcGlobals val CheckAugmentationAttribs : bool -> TcGlobals -> Import.ImportMap -> Tycon -> unit + val TyconIsCandidateForAugmentationWithCompare : TcGlobals -> Tycon -> bool + val TyconIsCandidateForAugmentationWithEquals : TcGlobals -> Tycon -> bool + val TyconIsCandidateForAugmentationWithHash : TcGlobals -> Tycon -> bool val MakeValsForCompareAugmentation : TcGlobals -> TyconRef -> Val * Val + val MakeValsForCompareWithComparerAugmentation : TcGlobals -> TyconRef -> Val + val MakeValsForEqualsAugmentation : TcGlobals -> TyconRef -> Val * Val + val MakeValsForEqualityWithComparerAugmentation : TcGlobals -> TyconRef -> Val * Val * Val val MakeBindingsForCompareAugmentation : TcGlobals -> Tycon -> Binding list + val MakeBindingsForCompareWithComparerAugmentation : TcGlobals -> Tycon -> Binding list + val MakeBindingsForEqualsAugmentation : TcGlobals -> Tycon -> Binding list + val MakeBindingsForEqualityWithComparerAugmentation : TcGlobals -> Tycon -> Binding list /// This predicate can be used once type inference is complete, before then it is an approximation diff --git a/src/fcs-fable/src/fsharp/CheckFormatStrings.fs b/src/fcs-fable/src/fsharp/CheckFormatStrings.fs old mode 100755 new mode 100644 index 7fd078de82..4b09c88665 --- a/src/fcs-fable/src/fsharp/CheckFormatStrings.fs +++ b/src/fcs-fable/src/fsharp/CheckFormatStrings.fs @@ -4,13 +4,14 @@ module internal FSharp.Compiler.CheckFormatStrings open FSharp.Compiler open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.Ast -open FSharp.Compiler.Range -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.TcGlobals open FSharp.Compiler.ConstraintSolver open FSharp.Compiler.NameResolution +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.TcGlobals type FormatItem = Simple of TType | FuncAndVal @@ -21,7 +22,7 @@ let copyAndFixupFormatTypar m tp = let lowestDefaultPriority = 0 (* See comment on TyparConstraint.DefaultsTo *) let mkFlexibleFormatTypar m tys dflt = - let tp = NewTypar (TyparKind.Type,TyparRigidity.Rigid,Typar(mkSynId m "fmt",HeadTypeStaticReq,true),false,TyparDynamicReq.Yes,[],false,false) + let tp = Construct.NewTypar (TyparKind.Type,TyparRigidity.Rigid,Typar(mkSynId m "fmt",HeadTypeStaticReq,true),false,TyparDynamicReq.Yes,[],false,false) tp.SetConstraints [ TyparConstraint.SimpleChoice (tys,m); TyparConstraint.DefaultsTo (lowestDefaultPriority,dflt,m)] copyAndFixupFormatTypar m tp @@ -34,8 +35,6 @@ let mkFlexibleDecimalFormatTypar (g: TcGlobals) m = let mkFlexibleFloatFormatTypar (g: TcGlobals) m = mkFlexibleFormatTypar m [ g.float_ty; g.float32_ty; g.decimal_ty ] g.float_ty -let isDigit c = ('0' <= c && c <= '9') - type FormatInfoRegister = { mutable leftJustify : bool mutable numPrefixIfPos : char option @@ -54,15 +53,17 @@ let parseFormatStringInternal (m:range) (g: TcGlobals) (context: FormatStringChe let (offset, fmt) = match context with | Some context -> - let length = context.Source.Length - if m.EndLine < context.LineStartPositions.Length then - let startIndex = context.LineStartPositions.[m.StartLine-1] + m.StartColumn - let endIndex = context.LineStartPositions.[m.EndLine-1] + m.EndColumn - 1 - if startIndex < length-3 && context.Source.[startIndex..startIndex+2] = "\"\"\"" then - (3, context.Source.[startIndex+3..endIndex-3]) - elif startIndex < length-2 && context.Source.[startIndex..startIndex+1] = "@\"" then - (2, context.Source.[startIndex+2..endIndex-1]) - else (1, context.Source.[startIndex+1..endIndex-1]) + let sourceText = context.SourceText + let lineStartPositions = context.LineStartPositions + let length = sourceText.Length + if m.EndLine < lineStartPositions.Length then + let startIndex = lineStartPositions.[m.StartLine-1] + m.StartColumn + let endIndex = lineStartPositions.[m.EndLine-1] + m.EndColumn - 1 + if startIndex < length-3 && sourceText.SubTextEquals("\"\"\"", startIndex) then + (3, sourceText.GetSubTextString(startIndex + 3, endIndex - startIndex)) + elif startIndex < length-2 && sourceText.SubTextEquals("@\"", startIndex) then + (2, sourceText.GetSubTextString(startIndex + 2, endIndex + 1 - startIndex)) + else (1, sourceText.GetSubTextString(startIndex + 1, endIndex - startIndex)) else (1, fmt) | None -> (1, fmt) @@ -115,13 +116,13 @@ let parseFormatStringInternal (m:range) (g: TcGlobals) (context: FormatStringChe let rec digitsPrecision i = if i >= len then failwithf "%s" <| FSComp.SR.forBadPrecision() match fmt.[i] with - | c when isDigit c -> digitsPrecision (i+1) + | c when System.Char.IsDigit c -> digitsPrecision (i+1) | _ -> i let precision i = if i >= len then failwithf "%s" <| FSComp.SR.forBadWidth() match fmt.[i] with - | c when isDigit c -> info.precision <- true; false,digitsPrecision (i+1) + | c when System.Char.IsDigit c -> info.precision <- true; false,digitsPrecision (i+1) | '*' -> info.precision <- true; true,(i+1) | _ -> failwithf "%s" <| FSComp.SR.forPrecisionMissingAfterDot() @@ -134,20 +135,20 @@ let parseFormatStringInternal (m:range) (g: TcGlobals) (context: FormatStringChe let rec digitsWidthAndPrecision i = if i >= len then failwithf "%s" <| FSComp.SR.forBadPrecision() match fmt.[i] with - | c when isDigit c -> digitsWidthAndPrecision (i+1) + | c when System.Char.IsDigit c -> digitsWidthAndPrecision (i+1) | _ -> optionalDotAndPrecision i let widthAndPrecision i = if i >= len then failwithf "%s" <| FSComp.SR.forBadPrecision() match fmt.[i] with - | c when isDigit c -> false,digitsWidthAndPrecision i + | c when System.Char.IsDigit c -> false,digitsWidthAndPrecision i | '*' -> true,optionalDotAndPrecision (i+1) | _ -> false,optionalDotAndPrecision i let rec digitsPosition n i = if i >= len then failwithf "%s" <| FSComp.SR.forBadPrecision() match fmt.[i] with - | c when isDigit c -> digitsPosition (n*10 + int c - int '0') (i+1) + | c when System.Char.IsDigit c -> digitsPosition (n*10 + int c - int '0') (i+1) | '$' -> Some n, i+1 | _ -> None, i diff --git a/src/fcs-fable/src/fsharp/CheckFormatStrings.fsi b/src/fcs-fable/src/fsharp/CheckFormatStrings.fsi old mode 100755 new mode 100644 index 10768a9424..91cce79b7d --- a/src/fcs-fable/src/fsharp/CheckFormatStrings.fsi +++ b/src/fcs-fable/src/fsharp/CheckFormatStrings.fsi @@ -9,7 +9,7 @@ module internal FSharp.Compiler.CheckFormatStrings open FSharp.Compiler open FSharp.Compiler.NameResolution -open FSharp.Compiler.Tast +open FSharp.Compiler.TypedTree open FSharp.Compiler.TcGlobals val ParseFormatString : Range.range -> TcGlobals -> formatStringCheckContext: FormatStringCheckContext option -> fmt: string -> bty: TType -> cty: TType -> dty: TType -> (TType * TType) * (Range.range * int) list diff --git a/src/fcs-fable/src/fsharp/CompileOps.fs b/src/fcs-fable/src/fsharp/CompileOps.fs old mode 100755 new mode 100644 index 64240b209b..7083757814 --- a/src/fcs-fable/src/fsharp/CompileOps.fs +++ b/src/fcs-fable/src/fsharp/CompileOps.fs @@ -14,20 +14,27 @@ open Internal.Utilities.Collections open Internal.Utilities.Filename open Internal.Utilities.Text -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler +open FSharp.Compiler.AbstractIL +open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.ILBinaryReader -open FSharp.Compiler.AbstractIL.Internal -open FSharp.Compiler.AbstractIL.Internal.Library +#if !FABLE_COMPILER +open FSharp.Compiler.AbstractIL.ILPdbWriter +#endif +open FSharp.Compiler.AbstractIL.Internal +open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.AbstractIL.Internal.Utils open FSharp.Compiler.AbstractIL.Extensions.ILX -open FSharp.Compiler.AbstractIL.Diagnostics - -open FSharp.Compiler -open FSharp.Compiler.Ast +open FSharp.Compiler.AbstractIL.Diagnostics open FSharp.Compiler.AttributeChecking +open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.ConstraintSolver open FSharp.Compiler.DiagnosticMessage +#if !FABLE_COMPILER +open FSharp.Compiler.DotNetFrameworkDependencies +#endif open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features open FSharp.Compiler.Import open FSharp.Compiler.Infos open FSharp.Compiler.Lexhelp @@ -35,15 +42,25 @@ open FSharp.Compiler.Lib open FSharp.Compiler.MethodCalls open FSharp.Compiler.MethodOverrides open FSharp.Compiler.NameResolution +open FSharp.Compiler.ParseHelpers open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps open FSharp.Compiler.Range open FSharp.Compiler.ReferenceResolver open FSharp.Compiler.SignatureConformance -open FSharp.Compiler.TastPickle +open FSharp.Compiler.TypedTreePickle open FSharp.Compiler.TypeChecker -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals +open FSharp.Compiler.Text +open FSharp.Compiler.XmlDoc + +#if !FABLE_COMPILER +open Microsoft.Interactive.DependencyManager +#endif #if !NO_EXTENSIONTYPING open FSharp.Compiler.ExtensionTyping @@ -68,7 +85,6 @@ let FSharpScriptFileSuffixes = [".fsscript";".fsx"] let doNotRequireNamespaceOrModuleSuffixes = [".mli";".ml"] @ FSharpScriptFileSuffixes let FSharpLightSyntaxFileSuffixes: string list = [ ".fs";".fsscript";".fsx";".fsi" ] - //---------------------------------------------------------------------------- // ERROR REPORTING //-------------------------------------------------------------------------- @@ -94,7 +110,7 @@ let GetRangeOfDiagnostic(err: PhasedDiagnostic) = let rec RangeFromException = function | ErrorFromAddingConstraint(_, err2, _) -> RangeFromException err2 #if !NO_EXTENSIONTYPING - | ExtensionTyping.ProvidedTypeResolutionNoRange(e) -> RangeFromException e + | ExtensionTyping.ProvidedTypeResolutionNoRange e -> RangeFromException e | ExtensionTyping.ProvidedTypeResolution(m, _) #endif | ReservedKeyword(_, m) @@ -105,8 +121,8 @@ let GetRangeOfDiagnostic(err: PhasedDiagnostic) = | FunctionExpected(_, _, m) | BakedInMemberConstraintName(_, m) | StandardOperatorRedefinitionWarning(_, m) - | BadEventTransformation(m) - | ParameterlessStructCtor(m) + | BadEventTransformation m + | ParameterlessStructCtor m | FieldNotMutable (_, _, m) | Recursion (_, _, _, _, m) | InvalidRuntimeCoercion(_, _, _, m) @@ -114,10 +130,10 @@ let GetRangeOfDiagnostic(err: PhasedDiagnostic) = | IndeterminateStaticCoercion (_, _, _, m) | StaticCoercionShouldUseBox (_, _, _, m) | CoercionTargetSealed(_, _, m) - | UpcastUnnecessary(m) + | UpcastUnnecessary m | QuotationTranslator.IgnoringPartOfQuotedTermWarning (_, m) - | TypeTestUnnecessary(m) + | TypeTestUnnecessary m | RuntimeCoercionSourceSealed(_, _, m) | OverrideDoesntOverride(_, _, _, _, _, m) | UnionPatternsBindDifferentNames m @@ -130,7 +146,7 @@ let GetRangeOfDiagnostic(err: PhasedDiagnostic) = | UnitTypeExpectedWithPossiblePropertySetter (_, _, _, _, m) | UnitTypeExpectedWithPossibleAssignment (_, _, _, _, m) | UseOfAddressOfOperator m - | DeprecatedThreadStaticBindingWarning(m) + | DeprecatedThreadStaticBindingWarning m | NonUniqueInferredAbstractSlot (_, _, _, _, _, m) | DefensiveCopyWarning (_, m) | LetRecCheckedAtRuntime m @@ -143,7 +159,6 @@ let GetRangeOfDiagnostic(err: PhasedDiagnostic) = | NumberedError (_, m) | SyntaxError (_, m) | InternalError (_, m) - | FullAbstraction(_, m) | InterfaceNotRevealed(_, _, m) | WrappedError (_, m) | PatternMatchCompilation.MatchIncomplete (_, _, m) @@ -152,10 +167,10 @@ let GetRangeOfDiagnostic(err: PhasedDiagnostic) = | ValNotMutable(_, _, m) | ValNotLocal(_, _, m) | MissingFields(_, m) - | OverrideInIntrinsicAugmentation(m) - | IntfImplInIntrinsicAugmentation(m) - | OverrideInExtrinsicAugmentation(m) - | IntfImplInExtrinsicAugmentation(m) + | OverrideInIntrinsicAugmentation m + | IntfImplInIntrinsicAugmentation m + | OverrideInExtrinsicAugmentation m + | IntfImplInExtrinsicAugmentation m | ValueRestriction(_, _, _, _, m) | LetRecUnsound (_, _, m) | ObsoleteError (_, m) @@ -164,9 +179,9 @@ let GetRangeOfDiagnostic(err: PhasedDiagnostic) = | PossibleUnverifiableCode m | UserCompilerMessage (_, _, m) | Deprecated(_, m) - | LibraryUseOnly(m) + | LibraryUseOnly m | FieldsFromDifferentTypes (_, _, _, m) - | IndeterminateType(m) + | IndeterminateType m | TyconBadArgs(_, _, _, m) -> Some m @@ -175,7 +190,7 @@ let GetRangeOfDiagnostic(err: PhasedDiagnostic) = | ConstrNotContained(_, aval, _, _) -> Some aval.Id.idRange | ExnconstrNotContained(_, aexnc, _, _) -> Some aexnc.Range - | VarBoundTwice(id) + | VarBoundTwice id | UndefinedName(_, _, id, _) -> Some id.idRange @@ -183,9 +198,8 @@ let GetRangeOfDiagnostic(err: PhasedDiagnostic) = | NameClash(_, _, _, m, _, _, _) | UnresolvedOverloading(_, _, _, m) | UnresolvedConversionOperator (_, _, _, m) - | PossibleOverload(_, _, _, m) - | VirtualAugmentationOnNullValuedType(m) - | NonVirtualAugmentationOnNullValuedType(m) + | VirtualAugmentationOnNullValuedType m + | NonVirtualAugmentationOnNullValuedType m | NonRigidTypar(_, _, _, _, _, m) | ConstraintSolverTupleDiffLengths(_, _, _, m, _) | ConstraintSolverInfiniteTypes(_, _, _, _, m, _) @@ -212,16 +226,16 @@ let GetRangeOfDiagnostic(err: PhasedDiagnostic) = | DeprecatedCommandLineOptionSuggestAlternative(_, _, m) | DeprecatedCommandLineOptionNoDescription(_, m) | InternalCommandLineOption(_, m) - | HashIncludeNotAllowedInNonScript(m) - | HashReferenceNotAllowedInNonScript(m) - | HashDirectiveNotAllowedInNonScript(m) + | HashIncludeNotAllowedInNonScript m + | HashReferenceNotAllowedInNonScript m + | HashDirectiveNotAllowedInNonScript m | FileNameNotResolved(_, _, m) | LoadedSourceNotFoundIgnoring(_, m) | MSBuildReferenceResolutionWarning(_, _, m) | MSBuildReferenceResolutionError(_, _, m) | AssemblyNotResolved(_, m) | HashLoadedSourceHasIssues(_, _, m) - | HashLoadedScriptConsideredSource(m) -> + | HashLoadedScriptConsideredSource m -> Some m #if !FABLE_COMPILER // Strip TargetInvocationException wrappers @@ -237,7 +251,7 @@ let GetRangeOfDiagnostic(err: PhasedDiagnostic) = RangeFromException err.Exception let GetDiagnosticNumber(err: PhasedDiagnostic) = - let rec GetFromException(e: exn) = + let rec GetFromException(e: exn) = match e with (* DO NOT CHANGE THESE NUMBERS *) | ErrorFromAddingTypeEquation _ -> 1 @@ -287,7 +301,6 @@ let GetDiagnosticNumber(err: PhasedDiagnostic) = | LibraryUseOnly _ -> 42 | ErrorFromAddingConstraint _ -> 43 | ObsoleteWarning _ -> 44 - | FullAbstraction _ -> 45 | ReservedKeyword _ -> 46 | SelfRefObjCtor _ -> 47 | VirtualAugmentationOnNullValuedType _ -> 48 @@ -372,25 +385,25 @@ let GetDiagnosticNumber(err: PhasedDiagnostic) = #endif | ErrorsFromAddingSubsumptionConstraint (_, _, _, _, _, ContextInfo.DowncastUsedInsteadOfUpcast _, _) -> fst (FSComp.SR.considerUpcast("", "")) | _ -> 193 - GetFromException err.Exception + GetFromException err.Exception let GetWarningLevel err = - match err.Exception with - // Level 5 warnings - | RecursiveUseCheckedAtRuntime _ - | LetRecEvaluatedOutOfOrder _ - | DefensiveCopyWarning _ - | FullAbstraction _ -> 5 - | NumberedError((n, _), _) - | ErrorWithSuggestions((n, _), _, _, _) - | Error((n, _), _) -> - // 1178, tcNoComparisonNeeded1, "The struct, record or union type '%s' is not structurally comparable because the type parameter %s does not satisfy the 'comparison' constraint..." - // 1178, tcNoComparisonNeeded2, "The struct, record or union type '%s' is not structurally comparable because the type '%s' does not satisfy the 'comparison' constraint...." - // 1178, tcNoEqualityNeeded1, "The struct, record or union type '%s' does not support structural equality because the type parameter %s does not satisfy the 'equality' constraint..." - // 1178, tcNoEqualityNeeded2, "The struct, record or union type '%s' does not support structural equality because the type '%s' does not satisfy the 'equality' constraint...." - if (n = 1178) then 5 else 2 - // Level 2 - | _ -> 2 + match err.Exception with + // Level 5 warnings + | RecursiveUseCheckedAtRuntime _ + | LetRecEvaluatedOutOfOrder _ + | DefensiveCopyWarning _ -> 5 + + | NumberedError((n, _), _) + | ErrorWithSuggestions((n, _), _, _, _) + | Error((n, _), _) -> + // 1178, tcNoComparisonNeeded1, "The struct, record or union type '%s' is not structurally comparable because the type parameter %s does not satisfy the 'comparison' constraint..." + // 1178, tcNoComparisonNeeded2, "The struct, record or union type '%s' is not structurally comparable because the type '%s' does not satisfy the 'comparison' constraint...." + // 1178, tcNoEqualityNeeded1, "The struct, record or union type '%s' does not support structural equality because the type parameter %s does not satisfy the 'equality' constraint..." + // 1178, tcNoEqualityNeeded2, "The struct, record or union type '%s' does not support structural equality because the type '%s' does not satisfy the 'equality' constraint...." + if (n = 1178) then 5 else 2 + // Level 2 + | _ -> 2 let warningOn err level specificWarnOn = let n = GetDiagnosticNumber err @@ -402,12 +415,9 @@ let warningOn err level specificWarnOn = | 3180 -> false // abImplicitHeapAllocation - off by default | _ -> level >= GetWarningLevel err -let SplitRelatedDiagnostics(err: PhasedDiagnostic) = - let ToPhased(e) = {Exception=e; Phase = err.Phase} +let SplitRelatedDiagnostics(err: PhasedDiagnostic) : PhasedDiagnostic * PhasedDiagnostic list = + let ToPhased e = {Exception=e; Phase = err.Phase} let rec SplitRelatedException = function - | UnresolvedOverloading(a, overloads, b, c) -> - let related = overloads |> List.map ToPhased - UnresolvedOverloading(a, [], b, c)|>ToPhased, related | ConstraintSolverRelatedInformation(fopt, m2, e) -> let e, related = SplitRelatedException e ConstraintSolverRelatedInformation(fopt, m2, e.Exception)|>ToPhased, related @@ -432,11 +442,11 @@ let SplitRelatedDiagnostics(err: PhasedDiagnostic) = SplitRelatedException e.InnerException #endif | e -> - ToPhased(e), [] - SplitRelatedException(err.Exception) + ToPhased e, [] + SplitRelatedException err.Exception -let DeclareMesssage = FSharp.Compiler.DiagnosticMessage.DeclareResourceString +let DeclareMessage = FSharp.Compiler.DiagnosticMessage.DeclareResourceString #if !FABLE_COMPILER do FSComp.SR.RunStartupValidation() @@ -455,7 +465,6 @@ let ErrorFromApplyingDefault2E() = DeclareResourceString("ErrorFromApplyingDefau let ErrorsFromAddingSubsumptionConstraintE() = DeclareResourceString("ErrorsFromAddingSubsumptionConstraint", "%s%s%s") let UpperCaseIdentifierInPatternE() = DeclareResourceString("UpperCaseIdentifierInPattern", "") let NotUpperCaseConstructorE() = DeclareResourceString("NotUpperCaseConstructor", "") -let PossibleOverloadE() = DeclareResourceString("PossibleOverload", "%s%s") let FunctionExpectedE() = DeclareResourceString("FunctionExpected", "") let BakedInMemberConstraintNameE() = DeclareResourceString("BakedInMemberConstraintName", "%s") let BadEventTransformationE() = DeclareResourceString("BadEventTransformation", "") @@ -557,7 +566,6 @@ let NonUniqueInferredAbstractSlot3E() = DeclareResourceString("NonUniqueInferred let NonUniqueInferredAbstractSlot4E() = DeclareResourceString("NonUniqueInferredAbstractSlot4", "") let Failure3E() = DeclareResourceString("Failure3", "%s") let Failure4E() = DeclareResourceString("Failure4", "%s") -let FullAbstractionE() = DeclareResourceString("FullAbstraction", "%s") let MatchIncomplete1E() = DeclareResourceString("MatchIncomplete1", "") let MatchIncomplete2E() = DeclareResourceString("MatchIncomplete2", "%s") let MatchIncomplete3E() = DeclareResourceString("MatchIncomplete3", "%s") @@ -609,6 +617,7 @@ let (|InvalidArgument|_|) (exn: exn) = match exn with :? ArgumentException as e type StringBuilder() = let buf = System.Text.StringBuilder() member x.Append(s: string) = buf.Append(s) |> ignore; x + member x.AppendLine() = x.Append("\n") override x.ToString() = buf.ToString() module Printf = @@ -617,7 +626,20 @@ module Printf = Printf.kprintf f #endif -let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = +let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) (canSuggestNames: bool) = + + let suggestNames suggestionsF idText = + if canSuggestNames then + let buffer = ErrorResolutionHints.SuggestionBuffer idText + if not buffer.Disabled then + suggestionsF buffer.Add + if not buffer.IsEmpty then + os.Append " " |> ignore + os.Append(FSComp.SR.undefinedNameSuggestionsIntro()) |> ignore + for value in buffer do + os.AppendLine() |> ignore + os.Append " " |> ignore + os.Append(DecompileOpName value) |> ignore let rec OutputExceptionR (os: StringBuilder) error = @@ -627,7 +649,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = if m.StartLine <> m2.StartLine then os.Append(SeeAlsoE().Format (stringOfRange m)) |> ignore - | ConstraintSolverInfiniteTypes(contextInfo, denv, t1, t2, m, m2) -> + | ConstraintSolverInfiniteTypes(denv, contextInfo, t1, t2, m, m2) -> // REVIEW: consider if we need to show _cxs (the type parameter constraints) let t1, t2, _cxs = NicePrint.minimalStringsOfTwoTypes denv t1 t2 os.Append(ConstraintSolverInfiniteTypesE().Format t1 t2) |> ignore @@ -661,16 +683,16 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = let t1, t2, _cxs = NicePrint.minimalStringsOfTwoTypes denv t1 t2 match contextInfo with - | ContextInfo.IfExpression range when range = m -> os.Append(FSComp.SR.ifExpression(t1, t2)) |> ignore - | ContextInfo.CollectionElement (isArray, range) when range = m -> + | ContextInfo.IfExpression range when Range.equals range m -> os.Append(FSComp.SR.ifExpression(t1, t2)) |> ignore + | ContextInfo.CollectionElement (isArray, range) when Range.equals range m -> if isArray then os.Append(FSComp.SR.arrayElementHasWrongType(t1, t2)) |> ignore else os.Append(FSComp.SR.listElementHasWrongType(t1, t2)) |> ignore - | ContextInfo.OmittedElseBranch range when range = m -> os.Append(FSComp.SR.missingElseBranch(t2)) |> ignore - | ContextInfo.ElseBranchResult range when range = m -> os.Append(FSComp.SR.elseBranchHasWrongType(t1, t2)) |> ignore - | ContextInfo.FollowingPatternMatchClause range when range = m -> os.Append(FSComp.SR.followingPatternMatchClauseHasWrongType(t1, t2)) |> ignore - | ContextInfo.PatternMatchGuard range when range = m -> os.Append(FSComp.SR.patternMatchGuardIsNotBool(t2)) |> ignore + | ContextInfo.OmittedElseBranch range when Range.equals range m -> os.Append(FSComp.SR.missingElseBranch(t2)) |> ignore + | ContextInfo.ElseBranchResult range when Range.equals range m -> os.Append(FSComp.SR.elseBranchHasWrongType(t1, t2)) |> ignore + | ContextInfo.FollowingPatternMatchClause range when Range.equals range m -> os.Append(FSComp.SR.followingPatternMatchClauseHasWrongType(t1, t2)) |> ignore + | ContextInfo.PatternMatchGuard range when Range.equals range m -> os.Append(FSComp.SR.patternMatchGuardIsNotBool(t2)) |> ignore | _ -> os.Append(ConstraintSolverTypesNotInEqualityRelation2E().Format t1 t2) |> ignore if m.StartLine <> m2.StartLine then os.Append(SeeAlsoE().Format (stringOfRange m)) |> ignore @@ -698,16 +720,16 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = && typeEquiv g t2 t2' -> let t1, t2, tpcs = NicePrint.minimalStringsOfTwoTypes denv t1 t2 match contextInfo with - | ContextInfo.IfExpression range when range = m -> os.Append(FSComp.SR.ifExpression(t1, t2)) |> ignore - | ContextInfo.CollectionElement (isArray, range) when range = m -> + | ContextInfo.IfExpression range when Range.equals range m -> os.Append(FSComp.SR.ifExpression(t1, t2)) |> ignore + | ContextInfo.CollectionElement (isArray, range) when Range.equals range m -> if isArray then os.Append(FSComp.SR.arrayElementHasWrongType(t1, t2)) |> ignore else os.Append(FSComp.SR.listElementHasWrongType(t1, t2)) |> ignore - | ContextInfo.OmittedElseBranch range when range = m -> os.Append(FSComp.SR.missingElseBranch(t2)) |> ignore - | ContextInfo.ElseBranchResult range when range = m -> os.Append(FSComp.SR.elseBranchHasWrongType(t1, t2)) |> ignore - | ContextInfo.FollowingPatternMatchClause range when range = m -> os.Append(FSComp.SR.followingPatternMatchClauseHasWrongType(t1, t2)) |> ignore - | ContextInfo.PatternMatchGuard range when range = m -> os.Append(FSComp.SR.patternMatchGuardIsNotBool(t2)) |> ignore + | ContextInfo.OmittedElseBranch range when Range.equals range m -> os.Append(FSComp.SR.missingElseBranch(t2)) |> ignore + | ContextInfo.ElseBranchResult range when Range.equals range m -> os.Append(FSComp.SR.elseBranchHasWrongType(t1, t2)) |> ignore + | ContextInfo.FollowingPatternMatchClause range when Range.equals range m -> os.Append(FSComp.SR.followingPatternMatchClauseHasWrongType(t1, t2)) |> ignore + | ContextInfo.PatternMatchGuard range when Range.equals range m -> os.Append(FSComp.SR.patternMatchGuardIsNotBool(t2)) |> ignore | ContextInfo.TupleInRecordFields -> os.Append(ErrorFromAddingTypeEquation1E().Format t2 t1 tpcs) |> ignore os.Append(System.Environment.NewLine + FSComp.SR.commaInsteadOfSemicolonInRecord()) |> ignore @@ -716,7 +738,8 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = os.Append(System.Environment.NewLine + FSComp.SR.derefInsteadOfNot()) |> ignore | _ -> os.Append(ErrorFromAddingTypeEquation1E().Format t2 t1 tpcs) |> ignore - | ErrorFromAddingTypeEquation(_, _, _, _, ((ConstraintSolverTypesNotInEqualityRelation (_, _, _, _, _, contextInfo) ) as e), _) when (match contextInfo with ContextInfo.NoContext -> false | _ -> true) -> + | ErrorFromAddingTypeEquation(_, _, _, _, ((ConstraintSolverTypesNotInEqualityRelation (_, _, _, _, _, contextInfo) ) as e), _) + when (match contextInfo with ContextInfo.NoContext -> false | _ -> true) -> OutputExceptionR os e | ErrorFromAddingTypeEquation(_, _, _, _, ((ConstraintSolverTypesNotInSubsumptionRelation _ | ConstraintSolverError _ ) as e), _) -> @@ -763,7 +786,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = OutputExceptionR os e #if !NO_EXTENSIONTYPING - | ExtensionTyping.ProvidedTypeResolutionNoRange(e) + | ExtensionTyping.ProvidedTypeResolutionNoRange e | ExtensionTyping.ProvidedTypeResolution(_, e) -> OutputExceptionR os e @@ -772,23 +795,100 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = os.Append(e.ContextualErrorMessage) |> ignore #endif - | UnresolvedOverloading(_, _, mtext, _) -> - os.Append(mtext) |> ignore + | UnresolvedOverloading(denv, callerArgs, failure, m) -> + + // extract eventual information (return type and type parameters) + // from ConstraintTraitInfo + let knownReturnType, genericParameterTypes = + match failure with + | NoOverloadsFound (cx=Some cx) + | PossibleCandidates (cx=Some cx) -> cx.ReturnType, cx.ArgumentTypes + | _ -> None, [] + + // prepare message parts (known arguments, known return type, known generic parameters) + let argsMessage, returnType, genericParametersMessage = + + let retTy = + knownReturnType + |> Option.defaultValue (TType.TType_var (Typar.NewUnlinked())) + + let argRepr = + callerArgs.ArgumentNamesAndTypes + |> List.map (fun (name,tTy) -> tTy, {ArgReprInfo.Name = name |> Option.map (fun name -> Ident(name, range.Zero)); ArgReprInfo.Attribs = []}) + + let argsL,retTyL,genParamTysL = NicePrint.prettyLayoutsOfUnresolvedOverloading denv argRepr retTy genericParameterTypes + + match callerArgs.ArgumentNamesAndTypes with + | [] -> None, Layout.showL retTyL, Layout.showL genParamTysL + | items -> + let args = Layout.showL argsL + let prefixMessage = + match items with + | [_] -> FSComp.SR.csNoOverloadsFoundArgumentsPrefixSingular + | _ -> FSComp.SR.csNoOverloadsFoundArgumentsPrefixPlural + Some (prefixMessage args) + , Layout.showL retTyL + , Layout.showL genParamTysL + + let knownReturnType = + match knownReturnType with + | None -> None + | Some _ -> Some (FSComp.SR.csNoOverloadsFoundReturnType returnType) + + let genericParametersMessage = + match genericParameterTypes with + | [] -> None + | [_] -> Some (FSComp.SR.csNoOverloadsFoundTypeParametersPrefixSingular genericParametersMessage) + | _ -> Some (FSComp.SR.csNoOverloadsFoundTypeParametersPrefixPlural genericParametersMessage) + + let overloadMethodInfo displayEnv m (x: OverloadInformation) = + let paramInfo = + match x.error with + | :? ArgDoesNotMatchError as x -> + let nameOrOneBasedIndexMessage = + x.calledArg.NameOpt + |> Option.map (fun n -> FSComp.SR.csOverloadCandidateNamedArgumentTypeMismatch n.idText) + |> Option.defaultValue (FSComp.SR.csOverloadCandidateIndexedArgumentTypeMismatch ((snd x.calledArg.Position) + 1)) + sprintf " // %s" nameOrOneBasedIndexMessage + | _ -> "" + + (NicePrint.stringOfMethInfo x.amap m displayEnv x.methodSlot.Method) + paramInfo + + let nl = System.Environment.NewLine + let formatOverloads (overloads: OverloadInformation list) = + overloads + |> List.map (overloadMethodInfo denv m) + |> List.sort + |> List.map FSComp.SR.formatDashItem + |> String.concat nl + + // assemble final message composing the parts + let msg = + let optionalParts = + [knownReturnType; genericParametersMessage; argsMessage] + |> List.choose id + |> String.concat (nl + nl) + |> function | "" -> nl + | result -> nl + nl + result + nl + nl + + match failure with + | NoOverloadsFound (methodName, overloads, _) -> + FSComp.SR.csNoOverloadsFound methodName + + optionalParts + + (FSComp.SR.csAvailableOverloads (formatOverloads overloads)) + | PossibleCandidates (methodName, [], _) -> + FSComp.SR.csMethodIsOverloaded methodName + | PossibleCandidates (methodName, overloads, _) -> + FSComp.SR.csMethodIsOverloaded methodName + + optionalParts + + FSComp.SR.csCandidates (formatOverloads overloads) + + os.Append msg |> ignore | UnresolvedConversionOperator(denv, fromTy, toTy, _) -> let t1, t2, _tpcs = NicePrint.minimalStringsOfTwoTypes denv fromTy toTy os.Append(FSComp.SR.csTypeDoesNotSupportConversion(t1, t2)) |> ignore - | PossibleOverload(_, minfo, originalError, _) -> - // print original error that describes reason why this overload was rejected - let buf = new StringBuilder() - OutputExceptionR buf originalError - - os.Append(PossibleOverloadE().Format minfo (buf.ToString())) |> ignore - - //| PossibleBestOverload(_, minfo, m) -> - // Printf.bprintf os "\n\nPossible best overload: '%s'." minfo - | FunctionExpected _ -> os.Append(FunctionExpectedE().Format) |> ignore @@ -796,7 +896,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = os.Append(BakedInMemberConstraintNameE().Format nm) |> ignore | StandardOperatorRedefinitionWarning(msg, _) -> - os.Append(msg) |> ignore + os.Append msg |> ignore | BadEventTransformation(_) -> os.Append(BadEventTransformationE().Format) |> ignore @@ -842,14 +942,11 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | UndefinedName(_, k, id, suggestionsF) -> os.Append(k (DecompileOpName id.idText)) |> ignore - let filtered = ErrorResolutionHints.FilterPredictions id.idText suggestionsF - if List.isEmpty filtered |> not then - os.Append(ErrorResolutionHints.FormatPredictions DecompileOpName filtered) |> ignore - + suggestNames suggestionsF id.idText | InternalUndefinedItemRef(f, smr, ccuName, s) -> - let _, errs = f(smr, ccuName, s) - os.Append(errs) |> ignore + let _, errs = f(smr, ccuName, s) + os.Append errs |> ignore | FieldNotMutable _ -> os.Append(FieldNotMutableE().Format) |> ignore @@ -857,7 +954,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | FieldsFromDifferentTypes (_, fref1, fref2, _) -> os.Append(FieldsFromDifferentTypesE().Format fref1.FieldName fref2.FieldName) |> ignore - | VarBoundTwice(id) -> + | VarBoundTwice id -> os.Append(VarBoundTwiceE().Format (DecompileOpName id.idText)) |> ignore | Recursion (denv, id, ty1, ty2, _) -> @@ -954,6 +1051,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | Parser.TOKEN_COLON_QMARK-> getErrorString("Parser.TOKEN.COLON.QMARK") | Parser.TOKEN_INT32_DOT_DOT -> getErrorString("Parser.TOKEN.INT32.DOT.DOT") | Parser.TOKEN_DOT_DOT -> getErrorString("Parser.TOKEN.DOT.DOT") + | Parser.TOKEN_DOT_DOT_HAT -> getErrorString("Parser.TOKEN.DOT.DOT") | Parser.TOKEN_QUOTE -> getErrorString("Parser.TOKEN.QUOTE") | Parser.TOKEN_STAR -> getErrorString("Parser.TOKEN.STAR") | Parser.TOKEN_HIGH_PRECEDENCE_TYAPP -> getErrorString("Parser.TOKEN.HIGH.PRECEDENCE.TYAPP") @@ -1012,6 +1110,8 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | Parser.TOKEN_OLET(_) -> getErrorString("Parser.TOKEN.OLET") | Parser.TOKEN_OBINDER | Parser.TOKEN_BINDER -> getErrorString("Parser.TOKEN.BINDER") + | Parser.TOKEN_OAND_BANG + | Parser.TOKEN_AND_BANG -> getErrorString("Parser.TOKEN.AND.BANG") | Parser.TOKEN_ODO -> getErrorString("Parser.TOKEN.ODO") | Parser.TOKEN_OWITH -> getErrorString("Parser.TOKEN.OWITH") | Parser.TOKEN_OFUNCTION -> getErrorString("Parser.TOKEN.OFUNCTION") @@ -1262,7 +1362,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = match types with | TType_app (maybeUnit, []) :: ts -> match maybeUnit.TypeAbbrev with - | Some ttype when Tastops.isUnitTy g ttype -> true + | Some ttype when isUnitTy g ttype -> true | _ -> hasUnitTType_app ts | _ :: ts -> hasUnitTType_app ts | [] -> false @@ -1378,15 +1478,13 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = os.Append(NonUniqueInferredAbstractSlot3E().Format t1 t2) |> ignore os.Append(NonUniqueInferredAbstractSlot4E().Format) |> ignore - | Error ((_, s), _) -> os.Append(s) |> ignore + | Error ((_, s), _) -> os.Append s |> ignore | ErrorWithSuggestions ((_, s), _, idText, suggestionF) -> os.Append(DecompileOpName s) |> ignore - let filtered = ErrorResolutionHints.FilterPredictions idText suggestionF - if List.isEmpty filtered |> not then - os.Append(ErrorResolutionHints.FormatPredictions DecompileOpName filtered) |> ignore + suggestNames suggestionF idText - | NumberedError ((_, s), _) -> os.Append(s) |> ignore + | NumberedError ((_, s), _) -> os.Append s |> ignore | InternalError (s, _) @@ -1406,8 +1504,6 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = System.Diagnostics.Debug.Assert(false, sprintf "Unexpected exception seen in compiler: %s\n%s" s (exn.ToString())) #endif - | FullAbstraction(s, _) -> os.Append(FullAbstractionE().Format s) |> ignore - | WrappedError (exn, _) -> OutputExceptionR os exn | PatternMatchCompilation.MatchIncomplete (isComp, cexOpt, _) -> @@ -1444,7 +1540,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | PossibleUnverifiableCode _ -> os.Append(PossibleUnverifiableCodeE().Format) |> ignore - | UserCompilerMessage (msg, _, _) -> os.Append(msg) |> ignore + | UserCompilerMessage (msg, _, _) -> os.Append msg |> ignore | Deprecated(s, _) -> os.Append(DeprecatedE().Format s) |> ignore @@ -1468,7 +1564,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = v.DisplayName) |> ignore else match v.MemberInfo with - | Some(membInfo) when + | Some membInfo when begin match membInfo.MemberFlags.MemberKind with | MemberKind.PropertyGet | MemberKind.PropertySet @@ -1503,30 +1599,30 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | IntfImplInExtrinsicAugmentation(_) -> os.Append(IntfImplInExtrinsicAugmentationE().Format) |> ignore - | UnresolvedReferenceError(assemblyname, _) + | UnresolvedReferenceError(assemblyName, _) - | UnresolvedReferenceNoRange(assemblyname) -> - os.Append(UnresolvedReferenceNoRangeE().Format assemblyname) |> ignore + | UnresolvedReferenceNoRange assemblyName -> + os.Append(UnresolvedReferenceNoRangeE().Format assemblyName) |> ignore - | UnresolvedPathReference(assemblyname, pathname, _) + | UnresolvedPathReference(assemblyName, pathname, _) - | UnresolvedPathReferenceNoRange(assemblyname, pathname) -> - os.Append(UnresolvedPathReferenceNoRangeE().Format pathname assemblyname) |> ignore + | UnresolvedPathReferenceNoRange(assemblyName, pathname) -> + os.Append(UnresolvedPathReferenceNoRangeE().Format pathname assemblyName) |> ignore | DeprecatedCommandLineOptionFull(fullText, _) -> - os.Append(fullText) |> ignore + os.Append fullText |> ignore | DeprecatedCommandLineOptionForHtmlDoc(optionName, _) -> - os.Append(FSComp.SR.optsDCLOHtmlDoc(optionName)) |> ignore + os.Append(FSComp.SR.optsDCLOHtmlDoc optionName) |> ignore | DeprecatedCommandLineOptionSuggestAlternative(optionName, altOption, _) -> os.Append(FSComp.SR.optsDCLODeprecatedSuggestAlternative(optionName, altOption)) |> ignore | InternalCommandLineOption(optionName, _) -> - os.Append(FSComp.SR.optsInternalNoDescription(optionName)) |> ignore + os.Append(FSComp.SR.optsInternalNoDescription optionName) |> ignore | DeprecatedCommandLineOptionNoDescription(optionName, _) -> - os.Append(FSComp.SR.optsDCLONoDescription(optionName)) |> ignore + os.Append(FSComp.SR.optsDCLONoDescription optionName) |> ignore | HashIncludeNotAllowedInNonScript(_) -> os.Append(HashIncludeNotAllowedInNonScriptE().Format) |> ignore @@ -1551,10 +1647,10 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = OutputExceptionR os (List.head l) if errors=[] then os.Append(HashLoadedSourceHasIssues1E().Format) |> ignore - Emit(warnings) + Emit warnings else os.Append(HashLoadedSourceHasIssues2E().Format) |> ignore - Emit(errors) + Emit errors | HashLoadedScriptConsideredSource(_) -> os.Append(HashLoadedScriptConsideredSourceE().Format) |> ignore @@ -1597,17 +1693,17 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = System.Diagnostics.Debug.Assert(false, sprintf "Unknown exception seen in compiler: %s" (e.ToString())) #endif - OutputExceptionR os (err.Exception) + OutputExceptionR os err.Exception -// remove any newlines and tabs -let OutputPhasedDiagnostic (os: System.Text.StringBuilder) (err: PhasedDiagnostic) (flattenErrors: bool) = +// remove any newlines and tabs +let OutputPhasedDiagnostic (os: System.Text.StringBuilder) (err: PhasedDiagnostic) (flattenErrors: bool) (canSuggestNames: bool) = let buf = new StringBuilder() - OutputPhasedErrorR buf err + OutputPhasedErrorR buf err canSuggestNames let s = if flattenErrors then ErrorLogger.NormalizeErrorString (buf.ToString()) else buf.ToString() - os.Append(s) |> ignore + os.Append s |> ignore let SanitizeFileName fileName (implicitIncludeDir: string) = // The assert below is almost ok, but it fires in two cases: @@ -1615,13 +1711,13 @@ let SanitizeFileName fileName (implicitIncludeDir: string) = // - if you have a #line directive, e.g. // # 1000 "Line01.fs" // then it also asserts. But these are edge cases that can be fixed later, e.g. in bug 4651. - //System.Diagnostics.Debug.Assert(FileSystem.IsPathRootedShim(fileName), sprintf "filename should be absolute: '%s'" fileName) + //System.Diagnostics.Debug.Assert(FileSystem.IsPathRootedShim fileName, sprintf "filename should be absolute: '%s'" fileName) try - let fullPath = FileSystem.GetFullPathShim(fileName) + let fullPath = FileSystem.GetFullPathShim fileName let currentDir = implicitIncludeDir // if the file name is not rooted in the current directory, return the full path - if not(fullPath.StartsWithOrdinal(currentDir)) then + if not(fullPath.StartsWithOrdinal currentDir) then fullPath // if the file name is rooted in the current directory, return the relative path else @@ -1656,9 +1752,9 @@ type Diagnostic = | Long of bool * DiagnosticDetailedInfo /// returns sequence that contains Diagnostic for the given error + Diagnostic for all related errors -let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorStyle, isError, err: PhasedDiagnostic) = - let outputWhere (showFullPaths, errorStyle) m: DiagnosticLocation = - if m = rangeStartup || m = rangeCmdArgs then +let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorStyle, isError, err: PhasedDiagnostic, canSuggestNames: bool) = + let outputWhere (showFullPaths, errorStyle) m: DiagnosticLocation = + if Range.equals m rangeStartup || Range.equals m rangeCmdArgs then { Range = m; TextRepresentation = ""; IsEmpty = true; File = "" } else let file = m.FileName @@ -1693,7 +1789,7 @@ let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorSt | ErrorStyle.VSErrors -> // Show prefix only for real files. Otherwise, we just want a truncated error like: // parse error FS0031: blah blah - if m<>range0 && m<>rangeStartup && m<>rangeCmdArgs then + if not (Range.equals m range0) && not (Range.equals m rangeStartup) && not (Range.equals m rangeCmdArgs) then let file = file.Replace("/", "\\") let m = mkRange m.FileName (mkPos m.StartLine (m.StartColumn + 1)) (mkPos m.EndLine (m.EndColumn + 1) ) sprintf "%s(%d,%d,%d,%d): " file m.StartLine m.StartColumn m.EndLine m.EndColumn, m, file @@ -1711,7 +1807,7 @@ let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorSt | _ -> let errors = ResizeArray() let report err = - let OutputWhere(err) = + let OutputWhere err = match GetRangeOfDiagnostic err with | Some m -> Some(outputWhere (showFullPaths, errorStyle) m) | None -> None @@ -1725,11 +1821,11 @@ let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorSt { ErrorNumber = errorNumber; Subcategory = subcategory; TextRepresentation = text} let mainError, relatedErrors = SplitRelatedDiagnostics err - let where = OutputWhere(mainError) + let where = OutputWhere mainError let canonical = OutputCanonicalInformation(err.Subcategory(), GetDiagnosticNumber mainError) let message = let os = System.Text.StringBuilder() - OutputPhasedDiagnostic os mainError flattenErrors + OutputPhasedDiagnostic os mainError flattenErrors canSuggestNames os.ToString() let entry: DiagnosticDetailedInfo = { Location = where; Canonical = canonical; Message = message } @@ -1740,11 +1836,11 @@ let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorSt match errorStyle with // Give a canonical string when --vserror. | ErrorStyle.VSErrors -> - let relWhere = OutputWhere(mainError) // mainError? + let relWhere = OutputWhere mainError // mainError? let relCanonical = OutputCanonicalInformation(err.Subcategory(), GetDiagnosticNumber mainError) // Use main error for code let relMessage = let os = System.Text.StringBuilder() - OutputPhasedDiagnostic os err flattenErrors + OutputPhasedDiagnostic os err flattenErrors canSuggestNames os.ToString() let entry: DiagnosticDetailedInfo = { Location = relWhere; Canonical = relCanonical; Message = relMessage} @@ -1752,9 +1848,9 @@ let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorSt | _ -> let os = System.Text.StringBuilder() - OutputPhasedDiagnostic os err flattenErrors + OutputPhasedDiagnostic os err flattenErrors canSuggestNames errors.Add( Diagnostic.Short(isError, os.ToString()) ) - + relatedErrors |> List.iter OutputRelatedError match err with @@ -1773,7 +1869,8 @@ let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorSt /// prints error and related errors to the specified StringBuilder let rec OutputDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorStyle, isError) os (err: PhasedDiagnostic) = - let errors = CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorStyle, isError, err) + // 'true' for "canSuggestNames" is passed last here because we want to report suggestions in fsc.exe and fsi.exe, just not in regular IDE usage. + let errors = CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorStyle, isError, err, true) for e in errors do Printf.bprintf os "\n" match e with @@ -1781,7 +1878,7 @@ let rec OutputDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, erro os.Append txt |> ignore | Diagnostic.Long(_, details) -> match details.Location with - | Some l when not l.IsEmpty -> os.Append(l.TextRepresentation) |> ignore + | Some l when not l.IsEmpty -> os.Append l.TextRepresentation |> ignore | _ -> () os.Append( details.Canonical.TextRepresentation ) |> ignore os.Append( details.Message ) |> ignore @@ -1803,238 +1900,20 @@ let OutputDiagnosticContext prefix fileLineFn os err = #endif //!FABLE_COMPILER -//---------------------------------------------------------------------------- - -let GetFSharpCoreLibraryName () = "FSharp.Core" - -#if !FABLE_COMPILER - -// If necessary assume a reference to the latest .NET Framework FSharp.Core with which those tools are built. -let GetDefaultFSharpCoreReference () = typeof>.Assembly.Location - -type private TypeInThisAssembly = class end - -// Use the ValueTuple that is executing with the compiler if it is from System.ValueTuple -// or the System.ValueTuple.dll that sits alongside the compiler. (Note we always ship one with the compiler) -let GetDefaultSystemValueTupleReference () = - try - let asm = typeof>.Assembly - if asm.FullName.StartsWithOrdinal("System.ValueTuple") then - Some asm.Location - else - let location = Path.GetDirectoryName(typeof.Assembly.Location) - let valueTuplePath = Path.Combine(location, "System.ValueTuple.dll") - if File.Exists(valueTuplePath) then - Some valueTuplePath - else - None - with _ -> None - -let GetFsiLibraryName () = "FSharp.Compiler.Interactive.Settings" - -// This list is the default set of references for "non-project" files. -// -// These DLLs are -// (a) included in the environment used for all .fsx files (see service.fs) -// (b) included in environment for files 'orphaned' from a project context -// -- for orphaned files (files in VS without a project context) -// -- for files given on a command line without --noframework set -let DefaultReferencesForScriptsAndOutOfProjectSources(assumeDotNetFramework) = - [ if assumeDotNetFramework then - yield "System" - yield "System.Xml" - yield "System.Runtime.Remoting" - yield "System.Runtime.Serialization.Formatters.Soap" - yield "System.Data" - yield "System.Drawing" - yield "System.Core" - - // These are the Portable-profile and .NET Standard 1.6 dependencies of FSharp.Core.dll. These are needed - // when an F# sript references an F# profile 7, 78, 259 or .NET Standard 1.6 component which in turn refers - // to FSharp.Core for profile 7, 78, 259 or .NET Standard. - yield "System.Runtime" // lots of types - yield "System.Linq" // System.Linq.Expressions.Expression - yield "System.Reflection" // System.Reflection.ParameterInfo - yield "System.Linq.Expressions" // System.Linq.IQueryable - yield "System.Threading.Tasks" // valuetype [System.Threading.Tasks]System.Threading.CancellationToken - yield "System.IO" // System.IO.TextWriter - //yield "System.Console" // System.Console.Out etc. - yield "System.Net.Requests" // System.Net.WebResponse etc. - yield "System.Collections" // System.Collections.Generic.List - yield "System.Runtime.Numerics" // BigInteger - yield "System.Threading" // OperationCanceledException - - // always include a default reference to System.ValueTuple.dll in scripts and out-of-project sources - match GetDefaultSystemValueTupleReference() with - | None -> () - | Some v -> yield v - - yield "System.Web" - yield "System.Web.Services" - yield "System.Windows.Forms" - yield "System.Numerics" - else - yield Path.Combine(Path.GetDirectoryName(typeof.Assembly.Location), "mscorlib.dll") // mscorlib - yield typeof.Assembly.Location // System.Console - yield typeof.Assembly.Location // System.Collections - yield typeof.Assembly.Location // System.ObjectModel - yield typeof.Assembly.Location // System.IO.FileSystem - yield typeof.Assembly.Location // System.IO - yield typeof.Assembly.Location // System.Linq - yield typeof.Assembly.Location // System.Xml - yield typeof.Assembly.Location // System.Xml.Linq - yield typeof.Assembly.Location // System.Net.Requests - yield typeof.Assembly.Location // System.Runtime.Numerics - yield typeof.Assembly.Location // System.Net.Security - yield typeof.Assembly.Location // System.Security.Claims - yield typeof.Assembly.Location // System.Text.RegularExpressions.Regex - yield typeof.Assembly.Location // System.Threading.Tasks - yield typeof.Assembly.Location // System.Threading - yield typeof.Assembly.Location // FSharp.Core - ] - - -// A set of assemblies to always consider to be system assemblies. A common set of these can be used a shared -// resources between projects in the compiler services. Also all assembles where well-known system types exist -// referenced from TcGlobals must be listed here. -let SystemAssemblies () = - HashSet - [ yield "mscorlib" - yield "netstandard" - yield "System.Runtime" - yield GetFSharpCoreLibraryName() - yield "System" - yield "System.Xml" - yield "System.Runtime.Remoting" - yield "System.Runtime.Serialization.Formatters.Soap" - yield "System.Data" - yield "System.Deployment" - yield "System.Design" - yield "System.Messaging" - yield "System.Drawing" - yield "System.Net" - yield "System.Web" - yield "System.Web.Services" - yield "System.Windows.Forms" - yield "System.Core" - yield "System.Runtime" - yield "System.Observable" - yield "System.Numerics" - yield "System.ValueTuple" - - // Additions for coreclr and portable profiles - yield "System.Collections" - yield "System.Collections.Concurrent" - yield "System.Console" - yield "System.Diagnostics.Debug" - yield "System.Diagnostics.Tools" - yield "System.Globalization" - yield "System.IO" - yield "System.Linq" - yield "System.Linq.Expressions" - yield "System.Linq.Queryable" - yield "System.Net.Requests" - yield "System.Reflection" - yield "System.Reflection.Emit" - yield "System.Reflection.Emit.ILGeneration" - yield "System.Reflection.Extensions" - yield "System.Resources.ResourceManager" - yield "System.Runtime.Extensions" - yield "System.Runtime.InteropServices" - yield "System.Runtime.InteropServices.PInvoke" - yield "System.Runtime.Numerics" - yield "System.Text.Encoding" - yield "System.Text.Encoding.Extensions" - yield "System.Text.RegularExpressions" - yield "System.Threading" - yield "System.Threading.Tasks" - yield "System.Threading.Tasks.Parallel" - yield "System.Threading.Thread" - yield "System.Threading.ThreadPool" - yield "System.Threading.Timer" - - yield "FSharp.Compiler.Interactive.Settings" - yield "Microsoft.Win32.Registry" - yield "System.Diagnostics.Tracing" - yield "System.Globalization.Calendars" - yield "System.Reflection.Primitives" - yield "System.Runtime.Handles" - yield "Microsoft.Win32.Primitives" - yield "System.IO.FileSystem" - yield "System.Net.Primitives" - yield "System.Net.Sockets" - yield "System.Private.Uri" - yield "System.AppContext" - yield "System.Buffers" - yield "System.Collections.Immutable" - yield "System.Diagnostics.DiagnosticSource" - yield "System.Diagnostics.Process" - yield "System.Diagnostics.TraceSource" - yield "System.Globalization.Extensions" - yield "System.IO.Compression" - yield "System.IO.Compression.ZipFile" - yield "System.IO.FileSystem.Primitives" - yield "System.Net.Http" - yield "System.Net.NameResolution" - yield "System.Net.WebHeaderCollection" - yield "System.ObjectModel" - yield "System.Reflection.Emit.Lightweight" - yield "System.Reflection.Metadata" - yield "System.Reflection.TypeExtensions" - yield "System.Runtime.InteropServices.RuntimeInformation" - yield "System.Runtime.Loader" - yield "System.Security.Claims" - yield "System.Security.Cryptography.Algorithms" - yield "System.Security.Cryptography.Cng" - yield "System.Security.Cryptography.Csp" - yield "System.Security.Cryptography.Encoding" - yield "System.Security.Cryptography.OpenSsl" - yield "System.Security.Cryptography.Primitives" - yield "System.Security.Cryptography.X509Certificates" - yield "System.Security.Principal" - yield "System.Security.Principal.Windows" - yield "System.Threading.Overlapped" - yield "System.Threading.Tasks.Extensions" - yield "System.Xml.ReaderWriter" - yield "System.Xml.XDocument" - - ] - -// The set of references entered into the TcConfigBuilder for scripts prior to computing -// the load closure. -// -// REVIEW: it isn't clear if there is any negative effect -// of leaving an assembly off this list. -let BasicReferencesForScriptLoadClosure(useFsiAuxLib, assumeDotNetFramework) = - [ - if assumeDotNetFramework then - -#if COMPILER_SERVICE_ASSUMES_DOTNETCORE_COMPILATION - yield Path.Combine(Path.GetDirectoryName(typeof.Assembly.Location), "mscorlib.dll"); // mscorlib -#else - yield "mscorlib" -#endif - yield GetDefaultFSharpCoreReference() ] @ // Need to resolve these explicitly so they will be found in the reference assemblies directory which is where the .xml files are. - DefaultReferencesForScriptsAndOutOfProjectSources(assumeDotNetFramework) @ - [ if useFsiAuxLib then yield GetFsiLibraryName () ] - -#endif //!FABLE_COMPILER - let (++) x s = x @ [s] #if !FABLE_COMPILER - -//---------------------------------------------------------------------------- +//-------------------------------------------------------------------------- // General file name resolver //-------------------------------------------------------------------------- /// Will return None if the filename is not found. let TryResolveFileUsingPaths(paths, m, name) = let () = - try FileSystem.IsPathRootedShim(name) |> ignore + try FileSystem.IsPathRootedShim name |> ignore with :? System.ArgumentException as e -> error(Error(FSComp.SR.buildProblemWithFilename(name, e.Message), m)) - if FileSystem.IsPathRootedShim(name) && FileSystem.SafeExists name + if FileSystem.IsPathRootedShim name && FileSystem.SafeExists name then Some name else let res = paths |> List.tryPick (fun path -> @@ -2046,7 +1925,7 @@ let TryResolveFileUsingPaths(paths, m, name) = /// Will raise FileNameNotResolved if the filename was not found let ResolveFileUsingPaths(paths, m, name) = match TryResolveFileUsingPaths(paths, m, name) with - | Some(res) -> res + | Some res -> res | None -> let searchMessage = String.concat "\n " paths raise (FileNameNotResolved(name, searchMessage, m)) @@ -2063,14 +1942,14 @@ let GetWarningNumber(m, s: string) = elif s.StartsWithOrdinal("FS") = true then raise (new ArgumentException()) else None with err -> - warning(Error(FSComp.SR.buildInvalidWarningNumber(s), m)) + warning(Error(FSComp.SR.buildInvalidWarningNumber s, m)) None let ComputeMakePathAbsolute implicitIncludeDir (path: string) = try // remove any quotation marks from the path first let path = path.Replace("\"", "") - if not (FileSystem.IsPathRootedShim(path)) + if not (FileSystem.IsPathRootedShim path) then Path.Combine (implicitIncludeDir, path) else path with @@ -2099,13 +1978,13 @@ type VersionFlag = | VersionString of string | VersionFile of string | VersionNone - member x.GetVersionInfo(implicitIncludeDir) = - let vstr = x.GetVersionString(implicitIncludeDir) + member x.GetVersionInfo implicitIncludeDir = + let vstr = x.GetVersionString implicitIncludeDir try IL.parseILVersion vstr - with _ -> errorR(Error(FSComp.SR.buildInvalidVersionString(vstr), rangeStartup)); IL.parseILVersion "0.0.0.0" + with _ -> errorR(Error(FSComp.SR.buildInvalidVersionString vstr, rangeStartup)); IL.parseILVersion "0.0.0.0" - member x.GetVersionString(implicitIncludeDir: string) = + member x.GetVersionString (implicitIncludeDir: string) = #if FABLE_COMPILER ignore implicitIncludeDir "0.0.0.0" @@ -2113,9 +1992,9 @@ type VersionFlag = match x with | VersionString s -> s | VersionFile s -> - let s = if FileSystem.IsPathRootedShim(s) then s else Path.Combine(implicitIncludeDir, s) - if not(FileSystem.SafeExists(s)) then - errorR(Error(FSComp.SR.buildInvalidVersionFile(s), rangeStartup)); "0.0.0.0" + let s = if FileSystem.IsPathRootedShim s then s else Path.Combine(implicitIncludeDir, s) + if not(FileSystem.SafeExists s) then + errorR(Error(FSComp.SR.buildInvalidVersionFile s, rangeStartup)); "0.0.0.0" else use is = System.IO.File.OpenText s is.ReadLine() @@ -2133,9 +2012,9 @@ type IRawFSharpAssemblyData = /// in the language service abstract TryGetILModuleDef: unit -> ILModuleDef option /// The raw F# signature data in the assembly, if any - abstract GetRawFSharpSignatureData: range * ilShortAssemName: string * fileName: string -> (string * (unit -> byte[])) list + abstract GetRawFSharpSignatureData: range * ilShortAssemName: string * fileName: string -> (string * (unit -> ReadOnlyByteMemory)) list /// The raw F# optimization data in the assembly, if any - abstract GetRawFSharpOptimizationData: range * ilShortAssemName: string * fileName: string -> (string * (unit -> byte[])) list + abstract GetRawFSharpOptimizationData: range * ilShortAssemName: string * fileName: string -> (string * (unit -> ReadOnlyByteMemory)) list /// The table of type forwarders in the assembly abstract GetRawTypeForwarders: unit -> ILExportedTypesAndForwarders /// The identity of the module @@ -2150,12 +2029,12 @@ type TimeStampCache(defaultTimeStamp: DateTime) = let files = Dictionary() let projects = Dictionary(HashIdentity.Reference) member cache.GetFileTimeStamp fileName = - let ok, v = files.TryGetValue(fileName) + let ok, v = files.TryGetValue fileName if ok then v else let v = #if !FABLE_COMPILER try - FileSystem.GetLastWriteTimeShim(fileName) + FileSystem.GetLastWriteTimeShim fileName with | :? FileNotFoundException -> #endif @@ -2164,7 +2043,7 @@ type TimeStampCache(defaultTimeStamp: DateTime) = v member cache.GetProjectReferenceTimeStamp (pr: IProjectReference, ctok) = - let ok, v = projects.TryGetValue(pr) + let ok, v = projects.TryGetValue pr if ok then v else let v = defaultArg (pr.TryGetLogicalTimeStamp (cache, ctok)) defaultTimeStamp projects.[pr] <- v @@ -2189,15 +2068,20 @@ and IProjectReference = type AssemblyReference = | AssemblyReference of range * string * IProjectReference option + member x.Range = (let (AssemblyReference(m, _, _)) = x in m) + member x.Text = (let (AssemblyReference(_, text, _)) = x in text) + member x.ProjectReference = (let (AssemblyReference(_, _, contents)) = x in contents) - member x.SimpleAssemblyNameIs(name) = + + member x.SimpleAssemblyNameIs name = (String.Compare(fileNameWithoutExtensionWithValidate false x.Text, name, StringComparison.OrdinalIgnoreCase) = 0) || (let text = x.Text.ToLowerInvariant() not (text.Contains "/") && not (text.Contains "\\") && not (text.Contains ".dll") && not (text.Contains ".exe") && - try let aname = System.Reflection.AssemblyName(x.Text) in aname.Name = name + try let aname = System.Reflection.AssemblyName x.Text in aname.Name = name with _ -> false) + override x.ToString() = sprintf "AssemblyReference(%s)" x.Text type UnresolvedAssemblyReference = UnresolvedAssemblyReference of string * AssemblyReference list @@ -2205,7 +2089,15 @@ type UnresolvedAssemblyReference = UnresolvedAssemblyReference of string * Assem type ResolvedExtensionReference = ResolvedExtensionReference of string * AssemblyReference list * Tainted list #endif -type ImportedBinary = +/// The thread in which compilation calls will be enqueued and done work on. +/// Note: This is currently only used when disposing of type providers and will be extended to all the other type provider calls when compilations can be done in parallel. +/// Right now all calls in FCS to type providers are single-threaded through use of the reactor thread. +type ICompilationThread = + + /// Enqueue work to be done on a compilation thread. + abstract EnqueueWork: (CompilationThreadToken -> unit) -> unit + +type ImportedBinary = { FileName: string RawMetadata: IRawFSharpAssemblyData #if !NO_EXTENSIONTYPING @@ -2216,7 +2108,7 @@ type ImportedBinary = ILAssemblyRefs: ILAssemblyRef list ILScopeRef: ILScopeRef } -type ImportedAssembly = +type ImportedAssembly = { ILScopeRef: ILScopeRef FSharpViewOfMetadata: CcuThunk AssemblyAutoOpenAttributes: string list @@ -2231,23 +2123,19 @@ type AvailableImportedAssembly = | ResolvedImportedAssembly of ImportedAssembly | UnresolvedImportedAssembly of string -type CcuLoadFailureAction = +type CcuLoadFailureAction = | RaiseError | ReturnNone [] type TcConfigBuilder = { mutable primaryAssembly: PrimaryAssembly - mutable autoResolveOpenDirectivesToDlls: bool mutable noFeedback: bool mutable stackReserveSize: int32 option mutable implicitIncludeDir: string (* normally "." *) mutable openDebugInformationForLaterStaticLinking: bool (* only for --standalone *) defaultFSharpBinariesDir: string mutable compilingFslib: bool - mutable compilingFslib20: string option - mutable compilingFslib40: bool - mutable compilingFslibNoBigInt: bool mutable useIncrementalBuilder: bool mutable includes: string list mutable implicitOpens: string list @@ -2257,8 +2145,10 @@ type TcConfigBuilder = mutable implicitlyResolveAssemblies: bool mutable light: bool option mutable conditionalCompilationDefines: string list - mutable loadedSources: (range * string) list + mutable loadedSources: (range * string * string) list + mutable compilerToolPaths: string list mutable referencedDLLs: AssemblyReference list + mutable packageManagerLines: Map mutable projectReferences: IProjectReference list mutable knownUnresolvedReferences: UnresolvedAssemblyReference list reduceMemoryUsage: ReduceMemoryFlag @@ -2270,6 +2160,7 @@ type TcConfigBuilder = mutable mlCompatibility: bool mutable checkOverflow: bool mutable showReferenceResolutions: bool + mutable outputDir : string option mutable outputFile: string option mutable platform: ILPlatform option mutable prefer32Bit: bool @@ -2331,6 +2222,9 @@ type TcConfigBuilder = mutable maxErrors: int mutable abortOnError: bool (* intended for fsi scripts that should exit on first error *) mutable baseAddress: int32 option +#if !FABLE_COMPILER + mutable checksumAlgorithm: HashAlgorithm +#endif #if DEBUG mutable showOptimizationData: bool #endif @@ -2348,7 +2242,7 @@ type TcConfigBuilder = mutable productNameForBannerText: string /// show the MS (c) notice, e.g. with help or fsi? mutable showBanner: bool - + /// show times between passes? mutable showTimes: bool mutable showLoadedAssemblies: bool @@ -2357,6 +2251,7 @@ type TcConfigBuilder = /// show messages about extension type resolution? mutable showExtensionTypeMessages: bool #endif + mutable compilationThread: ICompilationThread /// pause between passes? mutable pause: bool @@ -2377,41 +2272,42 @@ type TcConfigBuilder = mutable emitDebugInfoInQuotations: bool mutable exename: string option - + // If true - the compiler will copy FSharp.Core.dll along the produced binaries mutable copyFSharpCore: CopyFSharpCoreFlag /// When false FSI will lock referenced assemblies requiring process restart, false = disable Shadow Copy false (*default*) mutable shadowCopyReferences: bool + mutable useSdkRefs: bool - /// A function to call to try to get an object that acts as a snapshot of the metadata section of a .NET binary, - /// and from which we can read the metadata. Only used when metadataOnly=true. + /// A function to call to try to get an object that acts as a snapshot of the metadata section of a .NET binary, + /// and from which we can read the metadata. Only used when metadataOnly=true. mutable tryGetMetadataSnapshot: ILReaderTryGetMetadataSnapshot mutable internalTestSpanStackReferring: bool mutable noConditionalErasure: bool + + mutable pathMap: PathMap + + mutable langVersion: LanguageVersion + +#if !FABLE_COMPILER + mutable dependencyProvider: DependencyProvider +#endif } static member Initial = { -#if COMPILER_SERVICE_ASSUMES_DOTNETCORE_COMPILATION - primaryAssembly = PrimaryAssembly.System_Runtime // defaut value, can be overridden using the command line switch -#else - primaryAssembly = PrimaryAssembly.Mscorlib // defaut value, can be overridden using the command line switch -#endif + primaryAssembly = PrimaryAssembly.Mscorlib // default value, can be overridden using the command line switch light = None noFeedback = false stackReserveSize = None conditionalCompilationDefines = [] implicitIncludeDir = String.Empty - autoResolveOpenDirectivesToDlls = false openDebugInformationForLaterStaticLinking = false defaultFSharpBinariesDir = String.Empty compilingFslib = false - compilingFslib20 = None - compilingFslib40 = false - compilingFslibNoBigInt = false useIncrementalBuilder = false useFsiAuxLib = false implicitOpens = [] @@ -2419,7 +2315,9 @@ type TcConfigBuilder = resolutionEnvironment = ResolutionEnvironment.EditingOrCompilation false framework = true implicitlyResolveAssemblies = true + compilerToolPaths = [] referencedDLLs = [] + packageManagerLines = Map.empty projectReferences = [] knownUnresolvedReferences = [] loadedSources = [] @@ -2432,6 +2330,7 @@ type TcConfigBuilder = mlCompatibility = false checkOverflow = false showReferenceResolutions = false + outputDir = None outputFile = None platform = None prefer32Bit = false @@ -2440,7 +2339,7 @@ type TcConfigBuilder = debuginfo = false testFlagEmitFeeFeeAs100001 = false dumpDebugInfo = false - debugSymbolFile = None + debugSymbolFile = None (* Backend configuration *) typeCheckOnly = false @@ -2462,6 +2361,9 @@ type TcConfigBuilder = maxErrors = 100 abortOnError = false baseAddress = None +#if !FABLE_COMPILER + checksumAlgorithm = HashAlgorithm.Sha256 +#endif delaysign = false publicsign = false @@ -2521,6 +2423,9 @@ type TcConfigBuilder = #if !NO_EXTENSIONTYPING showExtensionTypeMessages = false #endif + compilationThread = + let ctok = CompilationThreadToken () + { new ICompilationThread with member __.EnqueueWork work = work ctok } pause = false alwaysCallVirt = true noDebugData = false @@ -2530,29 +2435,56 @@ type TcConfigBuilder = exename = None copyFSharpCore = CopyFSharpCoreFlag.No shadowCopyReferences = false + useSdkRefs = true tryGetMetadataSnapshot = (fun _ -> None) internalTestSpanStackReferring = false noConditionalErasure = false + pathMap = PathMap.empty + langVersion = LanguageVersion("default") +#if !FABLE_COMPILER + dependencyProvider = Unchecked.defaultof +#endif } + // Directories to start probing in + // Algorithm: + // Search for native libraries using: + // 1. Include directories + // 2. compilerToolPath directories + // 3. reference dll's + // 4. The implicit include directory + member private tcConfigB.nativeProbingRoots () = + seq { + yield! tcConfigB.includes + yield! tcConfigB.compilerToolPaths + yield! (tcConfigB.referencedDLLs |> Seq.map(fun ref -> Path.GetDirectoryName(ref.Text))) + yield tcConfigB.implicitIncludeDir + } |> Seq.distinct + static member CreateNew(legacyReferenceResolver, defaultFSharpBinariesDir, reduceMemoryUsage, implicitIncludeDir, isInteractive, isInvalidationSupported, defaultCopyFSharpCore, tryGetMetadataSnapshot) = - Debug.Assert(FileSystem.IsPathRootedShim(implicitIncludeDir), sprintf "implicitIncludeDir should be absolute: '%s'" implicitIncludeDir) + Debug.Assert(FileSystem.IsPathRootedShim implicitIncludeDir, sprintf "implicitIncludeDir should be absolute: '%s'" implicitIncludeDir) - if (String.IsNullOrEmpty(defaultFSharpBinariesDir)) then + if (String.IsNullOrEmpty defaultFSharpBinariesDir) then failwith "Expected a valid defaultFSharpBinariesDir" - { TcConfigBuilder.Initial with - implicitIncludeDir = implicitIncludeDir - defaultFSharpBinariesDir = defaultFSharpBinariesDir - reduceMemoryUsage = reduceMemoryUsage - legacyReferenceResolver = legacyReferenceResolver - isInteractive = isInteractive - isInvalidationSupported = isInvalidationSupported - copyFSharpCore = defaultCopyFSharpCore - tryGetMetadataSnapshot = tryGetMetadataSnapshot - } + let tcConfigBuilder = + { TcConfigBuilder.Initial with + implicitIncludeDir = implicitIncludeDir + defaultFSharpBinariesDir = defaultFSharpBinariesDir + reduceMemoryUsage = reduceMemoryUsage + legacyReferenceResolver = legacyReferenceResolver + isInteractive = isInteractive + isInvalidationSupported = isInvalidationSupported + copyFSharpCore = defaultCopyFSharpCore + tryGetMetadataSnapshot = tryGetMetadataSnapshot + useFsiAuxLib = isInteractive + } +#if !FABLE_COMPILER + tcConfigBuilder.dependencyProvider <- new DependencyProvider(NativeResolutionProbe(tcConfigBuilder.nativeProbingRoots)) +#endif + tcConfigBuilder #if !FABLE_COMPILER @@ -2593,7 +2525,7 @@ type TcConfigBuilder = error(Error(FSComp.SR.buildPdbRequiresDebug(), rangeStartup)) else None - tcConfigB.outputFile <- Some(outfile) + tcConfigB.outputFile <- Some outfile outfile, pdbfile, assemblyName #endif //!FABLE_COMPILER @@ -2628,35 +2560,35 @@ type TcConfigBuilder = let absolutePath = ComputeMakePathAbsolute pathIncludedFrom path let ok = let existsOpt = - try Some(Directory.Exists(absolutePath)) - with e -> warning(Error(FSComp.SR.buildInvalidSearchDirectory(path), m)); None + try Some(Directory.Exists absolutePath) + with e -> warning(Error(FSComp.SR.buildInvalidSearchDirectory path, m)); None match existsOpt with - | Some(exists) -> - if not exists then warning(Error(FSComp.SR.buildSearchDirectoryNotFound(absolutePath), m)) + | Some exists -> + if not exists then warning(Error(FSComp.SR.buildSearchDirectoryNotFound absolutePath, m)) exists | None -> false if ok && not (List.contains absolutePath tcConfigB.includes) then tcConfigB.includes <- tcConfigB.includes ++ absolutePath #endif //!FABLE_COMPILER - member tcConfigB.AddLoadedSource(m, path, pathLoadedFrom) = + member tcConfigB.AddLoadedSource(m, originalPath, pathLoadedFrom) = #if FABLE_COMPILER ignore m - ignore path + ignore originalPath ignore pathLoadedFrom () #else //!FABLE_COMPILER - if FileSystem.IsInvalidPathShim(path) then - warning(Error(FSComp.SR.buildInvalidFilename(path), m)) + if FileSystem.IsInvalidPathShim originalPath then + warning(Error(FSComp.SR.buildInvalidFilename originalPath, m)) else let path = - match TryResolveFileUsingPaths(tcConfigB.includes @ [pathLoadedFrom], m, path) with - | Some(path) -> path + match TryResolveFileUsingPaths(tcConfigB.includes @ [pathLoadedFrom], m, originalPath) with + | Some path -> path | None -> - // File doesn't exist in the paths. Assume it will be in the load-ed from directory. - ComputeMakePathAbsolute pathLoadedFrom path - if not (List.contains path (List.map snd tcConfigB.loadedSources)) then - tcConfigB.loadedSources <- tcConfigB.loadedSources ++ (m, path) + // File doesn't exist in the paths. Assume it will be in the load-ed from directory. + ComputeMakePathAbsolute pathLoadedFrom originalPath + if not (List.contains path (List.map (fun (_, _, path) -> path) tcConfigB.loadedSources)) then + tcConfigB.loadedSources <- tcConfigB.loadedSources ++ (m, originalPath, path) #endif //!FABLE_COMPILER member tcConfigB.AddEmbeddedSourceFile (file) = @@ -2665,15 +2597,33 @@ type TcConfigBuilder = member tcConfigB.AddEmbeddedResource filename = tcConfigB.embedResources <- tcConfigB.embedResources ++ filename + member tcConfigB.AddCompilerToolsByPath (path) = + if not (tcConfigB.compilerToolPaths |> List.exists (fun text -> path = text)) then // NOTE: We keep same paths if range is different. + let compilerToolPath = tcConfigB.compilerToolPaths |> List.tryPick (fun text -> if text = path then Some text else None) + if compilerToolPath.IsNone then + tcConfigB.compilerToolPaths <- tcConfigB.compilerToolPaths ++ path + member tcConfigB.AddReferencedAssemblyByPath (m, path) = - if FileSystem.IsInvalidPathShim(path) then + if FileSystem.IsInvalidPathShim path then warning(Error(FSComp.SR.buildInvalidAssemblyName(path), m)) - elif not (tcConfigB.referencedDLLs |> List.exists (fun ar2 -> m=ar2.Range && path=ar2.Text)) then // NOTE: We keep same paths if range is different. + elif not (tcConfigB.referencedDLLs |> List.exists (fun ar2 -> Range.equals m ar2.Range && path=ar2.Text)) then // NOTE: We keep same paths if range is different. let projectReference = tcConfigB.projectReferences |> List.tryPick (fun pr -> if pr.FileName = path then Some pr else None) tcConfigB.referencedDLLs <- tcConfigB.referencedDLLs ++ AssemblyReference(m, path, projectReference) +#if !FABLE_COMPILER + member tcConfigB.AddDependencyManagerText (packageManager:IDependencyManagerProvider, m, path:string) = + let path = tcConfigB.dependencyProvider.RemoveDependencyManagerKey(packageManager.Key, path) + + match tcConfigB.packageManagerLines |> Map.tryFind packageManager.Key with + | Some lines -> tcConfigB.packageManagerLines <- Map.add packageManager.Key (lines ++ (false, path, m)) tcConfigB.packageManagerLines + | _ -> tcConfigB.packageManagerLines <- Map.add packageManager.Key [false, path, m] tcConfigB.packageManagerLines +#endif + member tcConfigB.RemoveReferencedAssemblyByPath (m, path) = - tcConfigB.referencedDLLs <- tcConfigB.referencedDLLs |> List.filter (fun ar-> ar.Range <> m || ar.Text <> path) + tcConfigB.referencedDLLs <- tcConfigB.referencedDLLs |> List.filter (fun ar -> not (Range.equals ar.Range m) || ar.Text <> path) + + member tcConfigB.AddPathMapping (oldPrefix, newPrefix) = + tcConfigB.pathMap <- tcConfigB.pathMap |> PathMap.addMapping oldPrefix newPrefix static member SplitCommandLineResourceInfo (ri: string) = let p = ri.IndexOf ',' @@ -2686,7 +2636,7 @@ type TcConfigBuilder = let pubpri = String.sub rest (p+1) (rest.Length - p - 1) if pubpri = "public" then file, name, ILResourceAccess.Public elif pubpri = "private" then file, name, ILResourceAccess.Private - else error(Error(FSComp.SR.buildInvalidPrivacy(pubpri), rangeStartup)) + else error(Error(FSComp.SR.buildInvalidPrivacy pubpri, rangeStartup)) else file, rest, ILResourceAccess.Public else @@ -2694,10 +2644,9 @@ type TcConfigBuilder = #if !FABLE_COMPILER -let OpenILBinary(filename, reduceMemoryUsage, ilGlobals, pdbDirPath, shadowCopyReferences, tryGetMetadataSnapshot) = +let OpenILBinary(filename, reduceMemoryUsage, pdbDirPath, shadowCopyReferences, tryGetMetadataSnapshot) = let opts: ILReaderOptions = - { ilGlobals = ilGlobals - metadataOnly = MetadataOnlyFlag.Yes + { metadataOnly = MetadataOnlyFlag.Yes reduceMemoryUsage = reduceMemoryUsage pdbDirPath = pdbDirPath tryGetMetadataSnapshot = tryGetMetadataSnapshot } @@ -2727,7 +2676,7 @@ type AssemblyResolution = resolvedPath: string prepareToolTip: unit -> string sysdir: bool - ilAssemblyRef: ILAssemblyRef option ref + mutable ilAssemblyRef: ILAssemblyRef option } override this.ToString() = sprintf "%s%s" (if this.sysdir then "[sys]" else "") this.resolvedPath @@ -2739,19 +2688,19 @@ type AssemblyResolution = /// is cached. /// /// For project references in the language service, this would result in a build of the project. - /// This is because ``EvaluateRawContents(ctok)`` is used. However this path is only currently used + /// This is because ``EvaluateRawContents ctok`` is used. However this path is only currently used /// in fsi.fs, which does not use project references. // member this.GetILAssemblyRef(ctok, reduceMemoryUsage, tryGetMetadataSnapshot) = cancellable { - match !this.ilAssemblyRef with - | Some(assemblyRef) -> return assemblyRef + match this.ilAssemblyRef with + | Some assemblyRef -> return assemblyRef | None -> let! assemblyRefOpt = cancellable { match this.ProjectReference with | Some r -> - let! contents = r.EvaluateRawContents(ctok) + let! contents = r.EvaluateRawContents ctok match contents with | None -> return None | Some contents -> @@ -2766,13 +2715,12 @@ type AssemblyResolution = | None -> let readerSettings: ILReaderOptions = { pdbDirPath=None - ilGlobals = EcmaMscorlibILGlobals reduceMemoryUsage = reduceMemoryUsage metadataOnly = MetadataOnlyFlag.Yes tryGetMetadataSnapshot = tryGetMetadataSnapshot } use reader = OpenILModuleReader this.resolvedPath readerSettings mkRefToILAssembly reader.ILModuleDef.ManifestOfAssembly - this.ilAssemblyRef := Some(assemblyRef) + this.ilAssemblyRef <- Some assemblyRef return assemblyRef } @@ -2812,52 +2760,38 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = #if FABLE_COMPILER let _ = validate - let fsharpBinariesDirValue = data.defaultFSharpBinariesDir let clrRootValue, targetFrameworkVersionValue = "", "" #else //!FABLE_COMPILER // Validate the inputs - this helps ensure errors in options are shown in visual studio rather than only when built // However we only validate a minimal number of options at the moment - do if validate then try data.version.GetVersionInfo(data.implicitIncludeDir) |> ignore with e -> errorR(e) + do if validate then try data.version.GetVersionInfo(data.implicitIncludeDir) |> ignore with e -> errorR e // clone the input builder to ensure nobody messes with it. let data = { data with pause = data.pause } - let computeKnownDllReference(libraryName) = + let computeKnownDllReference libraryName = let defaultCoreLibraryReference = AssemblyReference(range0, libraryName+".dll", None) let nameOfDll(r: AssemblyReference) = let filename = ComputeMakePathAbsolute data.implicitIncludeDir r.Text - if FileSystem.SafeExists(filename) then - r, Some(filename) - else + if FileSystem.SafeExists filename then + r, Some filename + else // If the file doesn't exist, let reference resolution logic report the error later... - defaultCoreLibraryReference, if r.Range =rangeStartup then Some(filename) else None + defaultCoreLibraryReference, if Range.equals r.Range rangeStartup then Some(filename) else None match data.referencedDLLs |> List.filter (fun assemblyReference -> assemblyReference.SimpleAssemblyNameIs libraryName) with - | [r] -> nameOfDll r - | [] -> - defaultCoreLibraryReference, None - | r:: _ -> - // Recover by picking the first one. - errorR(Error(FSComp.SR.buildMultipleReferencesNotAllowed(libraryName), rangeCmdArgs)) - nameOfDll(r) + | [] -> defaultCoreLibraryReference, None + | [r] + | r :: _ -> nameOfDll r - // Look for an explicit reference to mscorlib and use that to compute clrRoot and targetFrameworkVersion + // Look for an explicit reference to mscorlib/netstandard.dll or System.Runtime.dll and use that to compute clrRoot and targetFrameworkVersion let primaryAssemblyReference, primaryAssemblyExplicitFilenameOpt = computeKnownDllReference(data.primaryAssembly.Name) - let fslibReference, fslibExplicitFilenameOpt = - let (_, fileNameOpt) as res = computeKnownDllReference(GetFSharpCoreLibraryName()) + let fslibReference = + // Look for explicit FSharp.Core reference otherwise use version that was referenced by compiler + let dllReference, fileNameOpt = computeKnownDllReference getFSharpCoreLibraryName match fileNameOpt with - | None -> - // if FSharp.Core was not provided explicitly - use version that was referenced by compiler - AssemblyReference(range0, GetDefaultFSharpCoreReference(), None), None - | _ -> res - - // If either mscorlib.dll/System.Runtime.dll/netstandard.dll or FSharp.Core.dll are explicitly specified then we require the --noframework flag. - // The reason is that some non-default frameworks may not have the default dlls. For example, Client profile does - // not have System.Web.dll. - do if ((primaryAssemblyExplicitFilenameOpt.IsSome || fslibExplicitFilenameOpt.IsSome) && data.framework) then - error(Error(FSComp.SR.buildExplicitCoreLibRequiresNoFramework("--noframework"), rangeStartup)) - - let ilGlobals = mkILGlobals ILScopeRef.Local + | Some _ -> dllReference + | None -> AssemblyReference(range0, getDefaultFSharpCoreLocation, None) // clrRoot: the location of the primary assembly (mscorlib.dll or netstandard.dll or System.Runtime.dll) // @@ -2872,7 +2806,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = | Some primaryAssemblyFilename -> let filename = ComputeMakePathAbsolute data.implicitIncludeDir primaryAssemblyFilename try - let clrRoot = Some(Path.GetDirectoryName(FileSystem.GetFullPathShim(filename))) + let clrRoot = Some(Path.GetDirectoryName(FileSystem.GetFullPathShim filename)) clrRoot, data.legacyReferenceResolver.HighestInstalledNetFrameworkVersion() with e -> // We no longer expect the above to fail but leaving this just in case @@ -2886,45 +2820,17 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = #endif None, data.legacyReferenceResolver.HighestInstalledNetFrameworkVersion() - let systemAssemblies = SystemAssemblies () - - // Look for an explicit reference to FSharp.Core and use that to compute fsharpBinariesDir - // FUTURE: remove this, we only read the binary for the exception it raises - let fsharpBinariesDirValue = -// NOTE: It's not clear why this behaviour has been changed for the NETSTANDARD compilations of the F# compiler -#if NETSTANDARD - ignore ilGlobals - data.defaultFSharpBinariesDir -#else - match fslibExplicitFilenameOpt with - | Some fslibFilename -> - let filename = ComputeMakePathAbsolute data.implicitIncludeDir fslibFilename - if fslibReference.ProjectReference.IsNone then - try - use ilReader = OpenILBinary(filename, data.reduceMemoryUsage, ilGlobals, None, data.shadowCopyReferences, data.tryGetMetadataSnapshot) - () - with e -> - error(Error(FSComp.SR.buildErrorOpeningBinaryFile(filename, e.Message), rangeStartup)) - - let fslibRoot = Path.GetDirectoryName(FileSystem.GetFullPathShim(filename)) - fslibRoot - | _ -> - data.defaultFSharpBinariesDir -#endif + let systemAssemblies = systemAssemblies #endif //!FABLE_COMPILER member x.primaryAssembly = data.primaryAssembly - member x.autoResolveOpenDirectivesToDlls = data.autoResolveOpenDirectivesToDlls member x.noFeedback = data.noFeedback member x.stackReserveSize = data.stackReserveSize member x.implicitIncludeDir = data.implicitIncludeDir member x.openDebugInformationForLaterStaticLinking = data.openDebugInformationForLaterStaticLinking - member x.fsharpBinariesDir = fsharpBinariesDirValue + member x.fsharpBinariesDir = data.defaultFSharpBinariesDir member x.compilingFslib = data.compilingFslib - member x.compilingFslib20 = data.compilingFslib20 - member x.compilingFslib40 = data.compilingFslib40 - member x.compilingFslibNoBigInt = data.compilingFslibNoBigInt member x.useIncrementalBuilder = data.useIncrementalBuilder member x.includes = data.includes member x.implicitOpens = data.implicitOpens @@ -2935,6 +2841,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = member x.light = data.light member x.conditionalCompilationDefines = data.conditionalCompilationDefines member x.loadedSources = data.loadedSources + member x.compilerToolPaths = data.compilerToolPaths member x.referencedDLLs = data.referencedDLLs member x.knownUnresolvedReferences = data.knownUnresolvedReferences member x.clrRoot = clrRootValue @@ -2947,6 +2854,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = member x.mlCompatibility = data.mlCompatibility member x.checkOverflow = data.checkOverflow member x.showReferenceResolutions = data.showReferenceResolutions + member x.outputDir = data.outputDir member x.outputFile = data.outputFile member x.platform = data.platform member x.prefer32Bit = data.prefer32Bit @@ -2987,6 +2895,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = member x.embedAllSource = data.embedAllSource member x.embedSourceList = data.embedSourceList member x.sourceLink = data.sourceLink + member x.packageManagerLines = data.packageManagerLines member x.ignoreSymbolStoreSequencePoints = data.ignoreSymbolStoreSequencePoints member x.internConstantStrings = data.internConstantStrings member x.extraOptimizationIterations = data.extraOptimizationIterations @@ -3000,7 +2909,10 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = member x.flatErrors = data.flatErrors member x.maxErrors = data.maxErrors member x.baseAddress = data.baseAddress - #if DEBUG +#if !FABLE_COMPILER + member x.checksumAlgorithm = data.checksumAlgorithm +#endif +#if DEBUG member x.showOptimizationData = data.showOptimizationData #endif member x.showTerms = data.showTerms @@ -3011,6 +2923,8 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = member x.optSettings = data.optSettings member x.emitTailcalls = data.emitTailcalls member x.deterministic = data.deterministic + member x.pathMap = data.pathMap + member x.langVersion = data.langVersion member x.preferredUiLang = data.preferredUiLang member x.lcid = data.lcid member x.optsOn = data.optsOn @@ -3020,8 +2934,9 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = member x.showLoadedAssemblies = data.showLoadedAssemblies member x.continueAfterParseFailure = data.continueAfterParseFailure #if !NO_EXTENSIONTYPING - member x.showExtensionTypeMessages = data.showExtensionTypeMessages + member x.showExtensionTypeMessages = data.showExtensionTypeMessages #endif + member x.compilationThread = data.compilationThread member x.pause = data.pause member x.alwaysCallVirt = data.alwaysCallVirt member x.noDebugData = data.noDebugData @@ -3030,6 +2945,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = member x.emitDebugInfoInQuotations = data.emitDebugInfoInQuotations member x.copyFSharpCore = data.copyFSharpCore member x.shadowCopyReferences = data.shadowCopyReferences + member x.useSdkRefs = data.useSdkRefs member x.tryGetMetadataSnapshot = data.tryGetMetadataSnapshot member x.internalTestSpanStackReferring = data.internalTestSpanStackReferring member x.noConditionalErasure = data.noConditionalErasure @@ -3039,6 +2955,11 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = TcConfig(builder, validate) member x.legacyReferenceResolver = data.legacyReferenceResolver + +#if !FABLE_COMPILER + member x.dependencyProvider = data.dependencyProvider +#endif + member tcConfig.CloneOfOriginalBuilder = { data with conditionalCompilationDefines=data.conditionalCompilationDefines } @@ -3075,11 +2996,16 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = // // In the current way of doing things, F# Interactive refers to implementation assemblies. yield runtimeRoot - if Directory.Exists(runtimeRootFacades) then + if Directory.Exists runtimeRootFacades then yield runtimeRootFacades // System.Runtime.dll is in /usr/lib/mono/4.5/Facades - if Directory.Exists(runtimeRootWPF) then + if Directory.Exists runtimeRootWPF then yield runtimeRootWPF // PresentationCore.dll is in C:\Windows\Microsoft.NET\Framework\v4.0.30319\WPF + match frameworkRefsPackDirectory with + | Some path when Directory.Exists(path) -> + yield path + | _ -> () + | ResolutionEnvironment.EditingOrCompilation _ -> #if ENABLE_MONO_SUPPORT if runningOnMono then @@ -3088,16 +3014,16 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = // On Mono, the default references come from the implementation assemblies. // This is because we have had trouble reliably using MSBuild APIs to compute DotNetFrameworkReferenceAssembliesRootDirectory on Mono. yield runtimeRoot - if Directory.Exists(runtimeRootFacades) then + if Directory.Exists runtimeRootFacades then yield runtimeRootFacades // System.Runtime.dll is in /usr/lib/mono/4.5/Facades - if Directory.Exists(runtimeRootWPF) then + if Directory.Exists runtimeRootWPF then yield runtimeRootWPF // PresentationCore.dll is in C:\Windows\Microsoft.NET\Framework\v4.0.30319\WPF // On Mono we also add a default reference to the 4.5-api and 4.5-api/Facades directories. let runtimeRootApi = runtimeRootWithoutSlash + "-api" let runtimeRootApiFacades = Path.Combine(runtimeRootApi, "Facades") - if Directory.Exists(runtimeRootApi) then + if Directory.Exists runtimeRootApi then yield runtimeRootApi - if Directory.Exists(runtimeRootApiFacades) then + if Directory.Exists runtimeRootApiFacades then yield runtimeRootApiFacades else #endif @@ -3108,27 +3034,41 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = let frameworkRootVersion = Path.Combine(frameworkRoot, tcConfig.targetFrameworkVersion) yield frameworkRootVersion let facades = Path.Combine(frameworkRootVersion, "Facades") - if Directory.Exists(facades) then + if Directory.Exists facades then yield facades - ] + match frameworkRefsPackDirectory with + | Some path when Directory.Exists(path) -> + yield path + | _ -> () + ] with e -> errorRecovery e range0; [] - member tcConfig.ComputeLightSyntaxInitialStatus(filename) = + member tcConfig.ComputeLightSyntaxInitialStatus filename = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parameter let lower = String.lowercase filename let lightOnByDefault = List.exists (Filename.checkSuffix lower) FSharpLightSyntaxFileSuffixes - if lightOnByDefault then (tcConfig.light <> Some(false)) else (tcConfig.light = Some(true) ) + if lightOnByDefault then (tcConfig.light <> Some false) else (tcConfig.light = Some true ) member tcConfig.GetAvailableLoadedSources() = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parameter - let resolveLoadedSource (m, path) = + let resolveLoadedSource (m, originalPath, path) = try if not(FileSystem.SafeExists(path)) then - error(LoadedSourceNotFoundIgnoring(path, m)) - None - else Some(m, path) + let secondTrial = + tcConfig.includes + |> List.tryPick (fun root -> + let path = ComputeMakePathAbsolute root originalPath + if FileSystem.SafeExists(path) then Some path else None) + + match secondTrial with + | Some path -> Some(m,path) + | None -> + error(LoadedSourceNotFoundIgnoring(path,m)) + None + else Some(m,path) with e -> errorRecovery e m; None + tcConfig.loadedSources |> List.choose resolveLoadedSource |> List.distinct @@ -3142,13 +3082,14 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = /// /// Returning true may mean that the file is locked and/or placed into the /// 'framework' reference set that is potentially shared across multiple compilations. - member tcConfig.IsSystemAssembly (filename: string) = - try - FileSystem.SafeExists filename && + member tcConfig.IsSystemAssembly (filename: string) = + try + FileSystem.SafeExists filename && ((tcConfig.GetTargetFrameworkDirectories() |> List.exists (fun clrRoot -> clrRoot = Path.GetDirectoryName filename)) || - (systemAssemblies.Contains(fileNameWithoutExtension filename))) + (systemAssemblies.Contains (fileNameWithoutExtension filename)) || + isInReferenceAssemblyPackDirectory filename) with _ -> - false + false // This is not the complete set of search paths, it is just the set // that is special to F# (as compared to MSBuild resolution) @@ -3167,7 +3108,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parameter // Only want to resolve certain extensions (otherwise, 'System.Xml' is ambiguous). // MSBuild resolution is limited to .exe and .dll so do the same here. - let ext = System.IO.Path.GetExtension(nm) + let ext = System.IO.Path.GetExtension nm let isNetModule = String.Compare(ext, ".netmodule", StringComparison.OrdinalIgnoreCase)=0 // See if the language service has already produced the contents of the assembly for us, virtually @@ -3180,7 +3121,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = resolvedPath = resolved prepareToolTip = (fun () -> resolved) sysdir = sysdir - ilAssemblyRef = ref None } + ilAssemblyRef = None } | None -> if String.Compare(ext, ".dll", StringComparison.OrdinalIgnoreCase)=0 @@ -3192,14 +3133,20 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = // file is included in the search path. This should ideally already be one of the search paths, but // during some global checks it won't be. We append to the end of the search list so that this is the last // place that is checked. - if m <> range0 && m <> rangeStartup && m <> rangeCmdArgs && FileSystem.IsPathRootedShim m.FileName then + let isPoundRReference (r: range) = + not (Range.equals r range0) && + not (Range.equals r rangeStartup) && + not (Range.equals r rangeCmdArgs) && + FileSystem.IsPathRootedShim r.FileName + + if isPoundRReference m then tcConfig.GetSearchPathsForLibraryFiles() @ [Path.GetDirectoryName(m.FileName)] else tcConfig.GetSearchPathsForLibraryFiles() let resolved = TryResolveFileUsingPaths(searchPaths, m, nm) match resolved with - | Some(resolved) -> + | Some resolved -> let sysdir = tcConfig.IsSystemAssembly resolved Some { originalReference = r @@ -3207,17 +3154,17 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = prepareToolTip = (fun () -> let fusionName = System.Reflection.AssemblyName.GetAssemblyName(resolved).ToString() let line(append: string) = append.Trim([|' '|])+"\n" - line(resolved) + line(fusionName)) + line resolved + line fusionName) sysdir = sysdir - ilAssemblyRef = ref None } + ilAssemblyRef = None } | None -> None else None - member tcConfig.ResolveLibWithDirectories (ccuLoadFaulureAction, r: AssemblyReference) = + member tcConfig.ResolveLibWithDirectories (ccuLoadFailureAction, r: AssemblyReference) = let m, nm = r.Range, r.Text use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parameter // test for both libraries and executables - let ext = System.IO.Path.GetExtension(nm) + let ext = System.IO.Path.GetExtension nm let isExe = (String.Compare(ext, ".exe", StringComparison.OrdinalIgnoreCase) = 0) let isDLL = (String.Compare(ext, ".dll", StringComparison.OrdinalIgnoreCase) = 0) let isNetModule = (String.Compare(ext, ".netmodule", StringComparison.OrdinalIgnoreCase) = 0) @@ -3229,9 +3176,9 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = [AssemblyReference(m, nm+".dll", None);AssemblyReference(m, nm+".exe", None);AssemblyReference(m, nm+".netmodule", None)] match rs |> List.tryPick (fun r -> tcConfig.TryResolveLibWithDirectories r) with - | Some(res) -> Some res + | Some res -> Some res | None -> - match ccuLoadFaulureAction with + match ccuLoadFailureAction with | CcuLoadFailureAction.RaiseError -> let searchMessage = String.concat "\n " (tcConfig.GetSearchPathsForLibraryFiles()) raise (FileNameNotResolved(nm, searchMessage, m)) @@ -3244,7 +3191,11 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = // it must return warnings and errors as data // // NOTE!! if mode=ReportErrors then this method must not raise exceptions. It must just report the errors and recover - static member TryResolveLibsUsingMSBuildRules (tcConfig: TcConfig, originalReferences: AssemblyReference list, errorAndWarningRange: range, mode: ResolveAssemblyReferenceMode) : AssemblyResolution list * UnresolvedAssemblyReference list = + static member TryResolveLibsUsingMSBuildRules (tcConfig: TcConfig, + originalReferences: AssemblyReference list, + errorAndWarningRange: range, + mode: ResolveAssemblyReferenceMode) : AssemblyResolution list * UnresolvedAssemblyReference list = + use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parameter if tcConfig.useSimpleResolution then failwith "MSBuild resolution is not supported." @@ -3289,9 +3240,9 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = let targetProcessorArchitecture = match tcConfig.platform with | None -> "MSIL" - | Some(X86) -> "x86" - | Some(AMD64) -> "amd64" - | Some(IA64) -> "ia64" + | Some X86 -> "x86" + | Some AMD64 -> "amd64" + | Some IA64 -> "ia64" // First, try to resolve everything as a file using simple resolution let resolvedAsFile = @@ -3339,7 +3290,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = resolvedPath=canonicalItemSpec prepareToolTip = (fun () -> resolvedFile.prepareToolTip (originalReference.Text, canonicalItemSpec)) sysdir= tcConfig.IsSystemAssembly canonicalItemSpec - ilAssemblyRef = ref None }) + ilAssemblyRef = None }) (maxIndexOfReference, assemblyResolutions)) // When calculating the resulting resolutions, we're going to use the index of the reference @@ -3373,10 +3324,10 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = else resultingResolutions, unresolvedReferences |> List.map (fun (name, _, r) -> (name, r)) |> List.map UnresolvedAssemblyReference - member tcConfig.PrimaryAssemblyDllReference() = primaryAssemblyReference + member tcConfig.CoreLibraryDllReference() = fslibReference - + #endif //!FABLE_COMPILER let ReportWarning options err = @@ -3405,8 +3356,8 @@ let GetScopedPragmasForHashDirective hd = let GetScopedPragmasForInput input = match input with - | ParsedInput.SigFile (ParsedSigFileInput(scopedPragmas=pragmas)) -> pragmas - | ParsedInput.ImplFile (ParsedImplFileInput(scopedPragmas=pragmas)) -> pragmas + | ParsedInput.SigFile (ParsedSigFileInput (scopedPragmas=pragmas)) -> pragmas + | ParsedInput.ImplFile (ParsedImplFileInput (scopedPragmas=pragmas)) -> pragmas @@ -3477,18 +3428,21 @@ let QualFileNameOfImpls filename specs = | [SynModuleOrNamespace(_, _, kind, _, _, _, _, m)] when not kind.IsModule -> QualFileNameOfFilename m filename | _ -> QualFileNameOfFilename (mkRange filename pos0 pos0) filename -let PrepandPathToQualFileName x (QualifiedNameOfFile(q)) = ComputeQualifiedNameOfFileFromUniquePath (q.idRange, pathOfLid x@[q.idText]) -let PrepandPathToImpl x (SynModuleOrNamespace(p, b, c, d, e, f, g, h)) = SynModuleOrNamespace(x@p, b, c, d, e, f, g, h) -let PrepandPathToSpec x (SynModuleOrNamespaceSig(p, b, c, d, e, f, g, h)) = SynModuleOrNamespaceSig(x@p, b, c, d, e, f, g, h) +let PrependPathToQualFileName x (QualifiedNameOfFile q) = ComputeQualifiedNameOfFileFromUniquePath (q.idRange, pathOfLid x@[q.idText]) +let PrependPathToImpl x (SynModuleOrNamespace(p, b, c, d, e, f, g, h)) = SynModuleOrNamespace(x@p, b, c, d, e, f, g, h) +let PrependPathToSpec x (SynModuleOrNamespaceSig(p, b, c, d, e, f, g, h)) = SynModuleOrNamespaceSig(x@p, b, c, d, e, f, g, h) let PrependPathToInput x inp = match inp with - | ParsedInput.ImplFile (ParsedImplFileInput(b, c, q, d, hd, impls, e)) -> ParsedInput.ImplFile (ParsedImplFileInput(b, c, PrepandPathToQualFileName x q, d, hd, List.map (PrepandPathToImpl x) impls, e)) - | ParsedInput.SigFile (ParsedSigFileInput(b, q, d, hd, specs)) -> ParsedInput.SigFile(ParsedSigFileInput(b, PrepandPathToQualFileName x q, d, hd, List.map (PrepandPathToSpec x) specs)) + | ParsedInput.ImplFile (ParsedImplFileInput (b, c, q, d, hd, impls, e)) -> + ParsedInput.ImplFile (ParsedImplFileInput (b, c, PrependPathToQualFileName x q, d, hd, List.map (PrependPathToImpl x) impls, e)) + + | ParsedInput.SigFile (ParsedSigFileInput (b, q, d, hd, specs)) -> + ParsedInput.SigFile (ParsedSigFileInput (b, PrependPathToQualFileName x q, d, hd, List.map (PrependPathToSpec x) specs)) let ComputeAnonModuleName check defaultNamespace filename (m: range) = let modname = CanonicalizeFilename filename - if check && not (modname |> String.forall (fun c -> System.Char.IsLetterOrDigit(c) || c = '_')) then + if check && not (modname |> String.forall (fun c -> System.Char.IsLetterOrDigit c || c = '_')) then if not (filename.EndsWith("fsx", StringComparison.OrdinalIgnoreCase) || filename.EndsWith("fsscript", StringComparison.OrdinalIgnoreCase)) then warning(Error(FSComp.SR.buildImplicitModuleIsNotLegalIdentifier(modname, (fileNameOfPath filename)), m)) let combined = @@ -3563,8 +3517,8 @@ let PostParseModuleSpec (_i, defaultNamespace, isLastCompiland, filename, intf) -let PostParseModuleImpls (defaultNamespace, filename, isLastCompiland, ParsedImplFile(hashDirectives, impls)) = - match impls |> List.rev |> List.tryPick (function ParsedImplFileFragment.NamedModule(SynModuleOrNamespace(lid, _, _, _, _, _, _, _)) -> Some(lid) | _ -> None) with +let PostParseModuleImpls (defaultNamespace, filename, isLastCompiland, ParsedImplFile (hashDirectives, impls)) = + match impls |> List.rev |> List.tryPick (function ParsedImplFileFragment.NamedModule(SynModuleOrNamespace(lid, _, _, _, _, _, _, _)) -> Some lid | _ -> None) with | Some lid when impls.Length > 1 -> errorR(Error(FSComp.SR.buildMultipleToplevelModules(), rangeOfLid lid)) | _ -> @@ -3581,10 +3535,10 @@ let PostParseModuleImpls (defaultNamespace, filename, isLastCompiland, ParsedImp | _ -> () for hd in hashDirectives do yield! GetScopedPragmasForHashDirective hd ] - ParsedInput.ImplFile(ParsedImplFileInput(filename, isScript, qualName, scopedPragmas, hashDirectives, impls, isLastCompiland)) + ParsedInput.ImplFile (ParsedImplFileInput (filename, isScript, qualName, scopedPragmas, hashDirectives, impls, isLastCompiland)) -let PostParseModuleSpecs (defaultNamespace, filename, isLastCompiland, ParsedSigFile(hashDirectives, specs)) = - match specs |> List.rev |> List.tryPick (function ParsedSigFileFragment.NamedModule(SynModuleOrNamespaceSig(lid, _, _, _, _, _, _, _)) -> Some(lid) | _ -> None) with +let PostParseModuleSpecs (defaultNamespace, filename, isLastCompiland, ParsedSigFile (hashDirectives, specs)) = + match specs |> List.rev |> List.tryPick (function ParsedSigFileFragment.NamedModule(SynModuleOrNamespaceSig(lid, _, _, _, _, _, _, _)) -> Some lid | _ -> None) with | Some lid when specs.Length > 1 -> errorR(Error(FSComp.SR.buildMultipleToplevelModules(), rangeOfLid lid)) | _ -> @@ -3601,7 +3555,7 @@ let PostParseModuleSpecs (defaultNamespace, filename, isLastCompiland, ParsedSig for hd in hashDirectives do yield! GetScopedPragmasForHashDirective hd ] - ParsedInput.SigFile(ParsedSigFileInput(filename, qualName, scopedPragmas, hashDirectives, specs)) + ParsedInput.SigFile (ParsedSigFileInput (filename, qualName, scopedPragmas, hashDirectives, specs)) type ModuleNamesDict = Map> @@ -3626,13 +3580,13 @@ let DeduplicateModuleName (moduleNamesDict: ModuleNamesDict) fileName (qualNameO /// Checks if a ParsedInput is using a module name that was already given and deduplicates the name if needed. let DeduplicateParsedInputModuleName (moduleNamesDict: ModuleNamesDict) input = match input with - | ParsedInput.ImplFile (ParsedImplFileInput.ParsedImplFileInput(fileName, isScript, qualNameOfFile, scopedPragmas, hashDirectives, modules, (isLastCompiland, isExe))) -> + | ParsedInput.ImplFile (ParsedImplFileInput.ParsedImplFileInput (fileName, isScript, qualNameOfFile, scopedPragmas, hashDirectives, modules, (isLastCompiland, isExe))) -> let qualNameOfFileT, moduleNamesDictT = DeduplicateModuleName moduleNamesDict fileName qualNameOfFile - let inputT = ParsedInput.ImplFile(ParsedImplFileInput.ParsedImplFileInput(fileName, isScript, qualNameOfFileT, scopedPragmas, hashDirectives, modules, (isLastCompiland, isExe))) + let inputT = ParsedInput.ImplFile (ParsedImplFileInput.ParsedImplFileInput (fileName, isScript, qualNameOfFileT, scopedPragmas, hashDirectives, modules, (isLastCompiland, isExe))) inputT, moduleNamesDictT - | ParsedInput.SigFile (ParsedSigFileInput.ParsedSigFileInput(fileName, qualNameOfFile, scopedPragmas, hashDirectives, modules)) -> + | ParsedInput.SigFile (ParsedSigFileInput.ParsedSigFileInput (fileName, qualNameOfFile, scopedPragmas, hashDirectives, modules)) -> let qualNameOfFileT, moduleNamesDictT = DeduplicateModuleName moduleNamesDict fileName qualNameOfFile - let inputT = ParsedInput.SigFile (ParsedSigFileInput.ParsedSigFileInput(fileName, qualNameOfFileT, scopedPragmas, hashDirectives, modules)) + let inputT = ParsedInput.SigFile (ParsedSigFileInput.ParsedSigFileInput (fileName, qualNameOfFileT, scopedPragmas, hashDirectives, modules)) inputT, moduleNamesDictT let ParseInput (lexer, errorLogger: ErrorLogger, lexbuf: UnicodeLexing.Lexbuf, defaultNamespace, filename, isLastCompiland) = @@ -3641,7 +3595,7 @@ let ParseInput (lexer, errorLogger: ErrorLogger, lexbuf: UnicodeLexing.Lexbuf, d // - if you have a #line directive, e.g. // # 1000 "Line01.fs" // then it also asserts. But these are edge cases that can be fixed later, e.g. in bug 4651. - //System.Diagnostics.Debug.Assert(System.IO.Path.IsPathRooted(filename), sprintf "should be absolute: '%s'" filename) + //System.Diagnostics.Debug.Assert(System.IO.Path.IsPathRooted filename, sprintf "should be absolute: '%s'" filename) let lower = String.lowercase filename // Delay sending errors and warnings until after the file is parsed. This gives us a chance to scrape the // #nowarn declarations for the file @@ -3661,13 +3615,13 @@ let ParseInput (lexer, errorLogger: ErrorLogger, lexbuf: UnicodeLexing.Lexbuf, d let intfs = Parser.signatureFile lexer lexbuf PostParseModuleSpecs (defaultNamespace, filename, isLastCompiland, intfs) else - delayLogger.Error(Error(FSComp.SR.buildInvalidSourceFileExtension(filename), Range.rangeStartup)) + delayLogger.Error(Error(FSComp.SR.buildInvalidSourceFileExtension filename, Range.rangeStartup)) scopedPragmas <- GetScopedPragmasForInput input input finally // OK, now commit the errors, since the ScopedPragmas will (hopefully) have been scraped let filteringErrorLogger = ErrorLoggerFilteringByScopedPragmas(false, scopedPragmas, errorLogger) - delayLogger.CommitDelayedDiagnostics(filteringErrorLogger) + delayLogger.CommitDelayedDiagnostics filteringErrorLogger #if !FABLE_COMPILER @@ -3679,8 +3633,8 @@ let ParseOneInputLexbuf (tcConfig: TcConfig, lexResourceManager, conditionalComp use unwindbuildphase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse try let skip = true in (* don't report whitespace from lexer *) - let lightSyntaxStatus = LightSyntaxStatus (tcConfig.ComputeLightSyntaxInitialStatus(filename), true) - let lexargs = mkLexargs (filename, conditionalCompilationDefines@tcConfig.conditionalCompilationDefines, lightSyntaxStatus, lexResourceManager, ref [], errorLogger) + let lightSyntaxStatus = LightSyntaxStatus (tcConfig.ComputeLightSyntaxInitialStatus filename, true) + let lexargs = mkLexargs (filename, conditionalCompilationDefines@tcConfig.conditionalCompilationDefines, lightSyntaxStatus, lexResourceManager, [], errorLogger, tcConfig.pathMap) let shortFilename = SanitizeFileName filename tcConfig.implicitIncludeDir let input = Lexhelp.usingLexbufForParsing (lexbuf, filename) (fun lexbuf -> @@ -3713,25 +3667,26 @@ let ParseOneInputLexbuf (tcConfig: TcConfig, lexResourceManager, conditionalComp let flattenModSpec (SynModuleOrNamespaceSig(_, _, _, decls, _, _, _, _)) = flattenSpecs decls let flattenModImpl (SynModuleOrNamespace(_, _, _, decls, _, _, _, _)) = flattenDefns decls match res with - | ParsedInput.SigFile(ParsedSigFileInput(_, _, _, _, specs)) -> + | ParsedInput.SigFile (ParsedSigFileInput (_, _, _, _, specs)) -> dprintf "parsing yielded %d specs" (List.collect flattenModSpec specs).Length - | ParsedInput.ImplFile(ParsedImplFileInput(modules = impls)) -> + | ParsedInput.ImplFile (ParsedImplFileInput (modules = impls)) -> dprintf "parsing yielded %d definitions" (List.collect flattenModImpl impls).Length res ) if verbose then dprintn ("Parsed "+shortFilename) Some input with e -> (* errorR(Failure("parse failed")); *) errorRecovery e rangeStartup; None - + let ParseOneInputFile (tcConfig: TcConfig, lexResourceManager, conditionalCompilationDefines, filename, isLastCompiland, errorLogger, retryLocked) = try let lower = String.lowercase filename if List.exists (Filename.checkSuffix lower) (FSharpSigFileSuffixes@FSharpImplFileSuffixes) then - if not(FileSystem.SafeExists(filename)) then - error(Error(FSComp.SR.buildCouldNotFindSourceFile(filename), rangeStartup)) - // bug 3155: if the file name is indirect, use a full path - let lexbuf = UnicodeLexing.UnicodeFileAsLexbuf(filename, tcConfig.inputCodePage, retryLocked) + if not(FileSystem.SafeExists filename) then + error(Error(FSComp.SR.buildCouldNotFindSourceFile filename, rangeStartup)) + let isFeatureSupported featureId = tcConfig.langVersion.SupportsFeature featureId + use reader = File.OpenReaderAndRetry (filename, tcConfig.inputCodePage, retryLocked) + let lexbuf = UnicodeLexing.StreamReaderAsLexbuf(isFeatureSupported, reader) ParseOneInputLexbuf(tcConfig, lexResourceManager, conditionalCompilationDefines, lexbuf, filename, isLastCompiland, errorLogger) else error(Error(FSComp.SR.buildInvalidSourceFileExtension(SanitizeFileName filename tcConfig.implicitIncludeDir), rangeStartup)) with e -> (* errorR(Failure("parse failed")); *) errorRecovery e rangeStartup; None @@ -3744,10 +3699,10 @@ type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, let resolvedPathToResolution = results |> List.map (fun r -> r.resolvedPath, r) |> Map.ofList /// Add some resolutions to the map of resolution results. - member tcResolutions.AddResolutionResults(newResults) = TcAssemblyResolutions(tcConfig, results @ newResults, unresolved) + member tcResolutions.AddResolutionResults newResults = TcAssemblyResolutions(tcConfig, results @ newResults, unresolved) /// Add some unresolved results. - member tcResolutions.AddUnresolvedReferences(newUnresolved) = TcAssemblyResolutions(tcConfig, results, unresolved @ newUnresolved) + member tcResolutions.AddUnresolvedReferences newUnresolved = TcAssemblyResolutions(tcConfig, results, unresolved @ newUnresolved) /// Get information about referenced DLLs member tcResolutions.GetAssemblyResolutions() = results @@ -3788,24 +3743,18 @@ type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, TcConfig.TryResolveLibsUsingMSBuildRules (tcConfig, assemblyList, rangeStartup, ResolveAssemblyReferenceMode.ReportErrors) TcAssemblyResolutions(tcConfig, resolved, unresolved @ knownUnresolved) - - static member GetAllDllReferences (tcConfig: TcConfig) = - [ + static member GetAllDllReferences (tcConfig: TcConfig) = [ let primaryReference = tcConfig.PrimaryAssemblyDllReference() - yield primaryReference + //yield primaryReference if not tcConfig.compilingFslib then yield tcConfig.CoreLibraryDllReference() let assumeDotNetFramework = primaryReference.SimpleAssemblyNameIs("mscorlib") - if tcConfig.framework then - for s in DefaultReferencesForScriptsAndOutOfProjectSources(assumeDotNetFramework) do + if tcConfig.framework then + for s in defaultReferencesForScriptsAndOutOfProjectSources tcConfig.useFsiAuxLib assumeDotNetFramework tcConfig.useSdkRefs do yield AssemblyReference(rangeStartup, (if s.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) then s else s+".dll"), None) - if tcConfig.useFsiAuxLib then - let name = Path.Combine(tcConfig.fsharpBinariesDir, GetFsiLibraryName() + ".dll") - yield AssemblyReference(rangeStartup, name, None) - yield! tcConfig.referencedDLLs ] @@ -3815,24 +3764,24 @@ type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, let frameworkDLLs, nonFrameworkReferences = resolutions.GetAssemblyResolutions() |> List.partition (fun r -> r.sysdir) let unresolved = resolutions.GetUnresolvedReferences() #if DEBUG - let itFailed = ref false + let mutable itFailed = false let addedText = "\nIf you want to debug this right now, attach a debugger, and put a breakpoint in 'CompileOps.fs' near the text '!itFailed', and you can re-step through the assembly resolution logic." unresolved |> List.iter (fun (UnresolvedAssemblyReference(referenceText, _ranges)) -> if referenceText.Contains("mscorlib") then System.Diagnostics.Debug.Assert(false, sprintf "whoops, did not resolve mscorlib: '%s'%s" referenceText addedText) - itFailed := true) + itFailed <- true) frameworkDLLs |> List.iter (fun x -> if not(FileSystem.IsPathRootedShim(x.resolvedPath)) then System.Diagnostics.Debug.Assert(false, sprintf "frameworkDLL should be absolute path: '%s'%s" x.resolvedPath addedText) - itFailed := true) + itFailed <- true) nonFrameworkReferences |> List.iter (fun x -> if not(FileSystem.IsPathRootedShim(x.resolvedPath)) then System.Diagnostics.Debug.Assert(false, sprintf "nonFrameworkReference should be absolute path: '%s'%s" x.resolvedPath addedText) - itFailed := true) - if !itFailed then + itFailed <- true) + if itFailed then // idea is, put a breakpoint here and then step through let assemblyList = TcAssemblyResolutions.GetAllDllReferences tcConfig let resolutions = TcAssemblyResolutions.ResolveAssemblyReferences (ctok, tcConfig, assemblyList, []) @@ -3852,24 +3801,24 @@ type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, //-------------------------------------------------------------------------- let IsSignatureDataResource (r: ILResource) = - r.Name.StartsWithOrdinal(FSharpSignatureDataResourceName) || - r.Name.StartsWithOrdinal(FSharpSignatureDataResourceName2) + r.Name.StartsWithOrdinal FSharpSignatureDataResourceName || + r.Name.StartsWithOrdinal FSharpSignatureDataResourceName2 let IsOptimizationDataResource (r: ILResource) = - r.Name.StartsWithOrdinal(FSharpOptimizationDataResourceName)|| - r.Name.StartsWithOrdinal(FSharpOptimizationDataResourceName2) + r.Name.StartsWithOrdinal FSharpOptimizationDataResourceName|| + r.Name.StartsWithOrdinal FSharpOptimizationDataResourceName2 let GetSignatureDataResourceName (r: ILResource) = - if r.Name.StartsWithOrdinal(FSharpSignatureDataResourceName) then + if r.Name.StartsWithOrdinal FSharpSignatureDataResourceName then String.dropPrefix r.Name FSharpSignatureDataResourceName - elif r.Name.StartsWithOrdinal(FSharpSignatureDataResourceName2) then + elif r.Name.StartsWithOrdinal FSharpSignatureDataResourceName2 then String.dropPrefix r.Name FSharpSignatureDataResourceName2 else failwith "GetSignatureDataResourceName" let GetOptimizationDataResourceName (r: ILResource) = - if r.Name.StartsWithOrdinal(FSharpOptimizationDataResourceName) then + if r.Name.StartsWithOrdinal FSharpOptimizationDataResourceName then String.dropPrefix r.Name FSharpOptimizationDataResourceName - elif r.Name.StartsWithOrdinal(FSharpOptimizationDataResourceName2) then + elif r.Name.StartsWithOrdinal FSharpOptimizationDataResourceName2 then String.dropPrefix r.Name FSharpOptimizationDataResourceName2 else failwith "GetOptimizationDataResourceName" @@ -3878,16 +3827,18 @@ let IsReflectedDefinitionsResource (r: ILResource) = #if !FABLE_COMPILER -let MakeILResource rname bytes = - { Name = rname - Location = ILResourceLocation.LocalOut bytes +let MakeILResource rName bytes = + { Name = rName + Location = ILResourceLocation.Local(ByteMemory.FromArray(bytes).AsReadOnly()) Access = ILResourceAccess.Public CustomAttrsStored = storeILCustomAttrs emptyILCustomAttrs MetadataIndex = NoMetadataIdx } -let PickleToResource inMem file g scope rname p x = - { Name = rname - Location = (let bytes = pickleObjWithDanglingCcus inMem file g scope p x in ILResourceLocation.LocalOut bytes) +let PickleToResource inMem file (g: TcGlobals) scope rName p x = + let file = PathMap.apply g.pathMap file + + { Name = rName + Location = (let bytes = pickleObjWithDanglingCcus inMem file g scope p x in ILResourceLocation.Local(ByteMemory.FromArray(bytes).AsReadOnly())) Access = ILResourceAccess.Public CustomAttrsStored = storeILCustomAttrs emptyILCustomAttrs MetadataIndex = NoMetadataIdx } @@ -3895,15 +3846,23 @@ let PickleToResource inMem file g scope rname p x = let GetSignatureData (file, ilScopeRef, ilModule, byteReader) : PickledDataWithReferences = unpickleObjWithDanglingCcus file ilScopeRef ilModule unpickleCcuInfo (byteReader()) -let WriteSignatureData (tcConfig: TcConfig, tcGlobals, exportRemapping, ccu: CcuThunk, file, inMem) : ILResource = +let WriteSignatureData (tcConfig: TcConfig, tcGlobals, exportRemapping, ccu: CcuThunk, file, inMem) : ILResource = let mspec = ccu.Contents let mspec = ApplyExportRemappingToEntity tcGlobals exportRemapping mspec // For historical reasons, we use a different resource name for FSharp.Core, so older F# compilers // don't complain when they see the resource. - let rname = if ccu.AssemblyName = GetFSharpCoreLibraryName() then FSharpSignatureDataResourceName2 else FSharpSignatureDataResourceName - PickleToResource inMem file tcGlobals ccu (rname+ccu.AssemblyName) pickleCcuInfo + let rName = if ccu.AssemblyName = getFSharpCoreLibraryName then FSharpSignatureDataResourceName2 else FSharpSignatureDataResourceName + + let includeDir = + if String.IsNullOrEmpty tcConfig.implicitIncludeDir then "" + else + tcConfig.implicitIncludeDir + |> System.IO.Path.GetFullPath + |> PathMap.applyDir tcGlobals.pathMap + + PickleToResource inMem file tcGlobals ccu (rName+ccu.AssemblyName) pickleCcuInfo { mspec=mspec - compileTimeWorkingDir=tcConfig.implicitIncludeDir + compileTimeWorkingDir=includeDir usesQuotations = ccu.UsesFSharp20PlusQuotations } let GetOptimizationData (file, ilScopeRef, ilModule, byteReader) = @@ -3912,8 +3871,8 @@ let GetOptimizationData (file, ilScopeRef, ilModule, byteReader) = let WriteOptimizationData (tcGlobals, file, inMem, ccu: CcuThunk, modulInfo) = // For historical reasons, we use a different resource name for FSharp.Core, so older F# compilers // don't complain when they see the resource. - let rname = if ccu.AssemblyName = GetFSharpCoreLibraryName() then FSharpOptimizationDataResourceName2 else FSharpOptimizationDataResourceName - PickleToResource inMem file tcGlobals ccu (rname+ccu.AssemblyName) Optimizer.p_CcuOptimizationInfo modulInfo + let rName = if ccu.AssemblyName = getFSharpCoreLibraryName then FSharpOptimizationDataResourceName2 else FSharpOptimizationDataResourceName + PickleToResource inMem file tcGlobals ccu (rName+ccu.AssemblyName) Optimizer.p_CcuOptimizationInfo modulInfo //---------------------------------------------------------------------------- // Abstraction for project reference @@ -3921,8 +3880,8 @@ let WriteOptimizationData (tcGlobals, file, inMem, ccu: CcuThunk, modulInfo) = type RawFSharpAssemblyDataBackedByFileOnDisk (ilModule: ILModuleDef, ilAssemblyRefs) = let externalSigAndOptData = ["FSharp.Core"] interface IRawFSharpAssemblyData with - member __.GetAutoOpenAttributes(ilg) = GetAutoOpenAttributes ilg ilModule - member __.GetInternalsVisibleToAttributes(ilg) = GetInternalsVisibleToAttributes ilg ilModule + member __.GetAutoOpenAttributes ilg = GetAutoOpenAttributes ilg ilModule + member __.GetInternalsVisibleToAttributes ilg = GetInternalsVisibleToAttributes ilg ilModule member __.TryGetILModuleDef() = Some ilModule member __.GetRawFSharpSignatureData(m, ilShortAssemName, filename) = let resources = ilModule.Resources.AsList @@ -3937,7 +3896,7 @@ type RawFSharpAssemblyDataBackedByFileOnDisk (ilModule: ILModuleDef, ilAssemblyR let sigFileName = Path.ChangeExtension(filename, "sigdata") if not (FileSystem.SafeExists sigFileName) then error(Error(FSComp.SR.buildExpectedSigdataFile (FileSystem.GetFullPathShim sigFileName), m)) - [ (ilShortAssemName, fun () -> FileSystem.ReadAllBytesShim sigFileName)] + [ (ilShortAssemName, fun () -> ByteMemory.FromFile(sigFileName, FileAccess.Read, canShadowCopy=true).AsReadOnly())] else sigDataReaders sigDataReaders @@ -3952,7 +3911,7 @@ type RawFSharpAssemblyDataBackedByFileOnDisk (ilModule: ILModuleDef, ilAssemblyR let optDataFile = Path.ChangeExtension(filename, "optdata") if not (FileSystem.SafeExists optDataFile) then error(Error(FSComp.SR.buildExpectedFileAlongSideFSharpCore(optDataFile, FileSystem.GetFullPathShim optDataFile), m)) - [ (ilShortAssemName, (fun () -> FileSystem.ReadAllBytesShim optDataFile))] + [ (ilShortAssemName, (fun () -> ByteMemory.FromFile(optDataFile, FileAccess.Read, canShadowCopy=true).AsReadOnly()))] else optDataReaders optDataReaders @@ -3966,7 +3925,7 @@ type RawFSharpAssemblyDataBackedByFileOnDisk (ilModule: ILModuleDef, ilAssemblyR member __.HasAnyFSharpSignatureDataAttribute = let attrs = GetCustomAttributesOfILModule ilModule List.exists IsSignatureDataVersionAttr attrs - member __.HasMatchingFSharpSignatureDataAttribute(ilg) = + member __.HasMatchingFSharpSignatureDataAttribute ilg = let attrs = GetCustomAttributesOfILModule ilModule List.exists (IsMatchingSignatureDataVersionAttr ilg (IL.parseILVersion Internal.Utilities.FSharpEnvironment.FSharpBinaryMetadataFormatRevision)) attrs @@ -3976,7 +3935,7 @@ type RawFSharpAssemblyDataBackedByFileOnDisk (ilModule: ILModuleDef, ilAssemblyR //-------------------------------------------------------------------------- let availableToOptionalCcu = function - | ResolvedCcu(ccu) -> Some(ccu) + | ResolvedCcu ccu -> Some ccu | UnresolvedCcu _ -> None @@ -3988,24 +3947,89 @@ let availableToOptionalCcu = function /// but for F# Interactive it may be based on an underlying mutable TcConfigBuilder. type TcConfigProvider = | TcConfigProvider of (CompilationThreadToken -> TcConfig) - member x.Get(ctok) = (let (TcConfigProvider(f)) = x in f ctok) + member x.Get ctok = (let (TcConfigProvider f) = x in f ctok) /// Get a TcConfigProvider which will return only the exact TcConfig. - static member Constant(tcConfig) = TcConfigProvider(fun _ctok -> tcConfig) + static member Constant tcConfig = TcConfigProvider(fun _ctok -> tcConfig) /// Get a TcConfigProvider which will continue to respect changes in the underlying /// TcConfigBuilder rather than delivering snapshots. - static member BasedOnMutableBuilder(tcConfigB) = TcConfigProvider(fun _ctok -> TcConfig.Create(tcConfigB, validate=false)) + static member BasedOnMutableBuilder tcConfigB = TcConfigProvider(fun _ctok -> TcConfig.Create(tcConfigB, validate=false)) //---------------------------------------------------------------------------- // TcImports //-------------------------------------------------------------------------- - +[] +type TcImportsSafeDisposal + (disposeActions: ResizeArray unit>, +#if !NO_EXTENSIONTYPING + disposeTypeProviderActions: ResizeArray unit>, +#endif + compilationThread: ICompilationThread) = + + let mutable isDisposed = false + + let dispose () = + // disposing deliberately only closes this tcImports, not the ones up the chain + isDisposed <- true + if verbose then + dprintf "disposing of TcImports, %d binaries\n" disposeActions.Count +#if !NO_EXTENSIONTYPING + let actions = disposeTypeProviderActions + if actions.Count > 0 then + compilationThread.EnqueueWork (fun _ -> for action in actions do action()) +#endif + for action in disposeActions do action() + + override _.Finalize() = + dispose () + + interface IDisposable with + + member this.Dispose() = + if not isDisposed then + GC.SuppressFinalize this + dispose () + +#if !NO_EXTENSIONTYPING +// These are hacks in order to allow TcImports to be held as a weak reference inside a type provider. +// The reason is due to older type providers compiled using an older TypeProviderSDK, that SDK used reflection on fields and properties to determine the contract. +// The reflection code has now since been removed, see here: https://github.com/fsprojects/FSharp.TypeProviders.SDK/pull/305. But we still need to work on older type providers. +// One day we can remove these hacks when we deemed most if not all type providers were re-compiled using the newer TypeProviderSDK. +// Yuck. +type TcImportsDllInfoHack = + { + FileName: string + } + +and TcImportsWeakHack (tcImports: WeakReference) = + let mutable dllInfos: TcImportsDllInfoHack list = [] + + member __.SetDllInfos (value: ImportedBinary list) = + dllInfos <- value |> List.map (fun x -> { FileName = x.FileName }) + + member __.Base: TcImportsWeakHack option = + match tcImports.TryGetTarget() with + | true, strong -> + match strong.Base with + | Some (baseTcImports: TcImports) -> + Some baseTcImports.Weak + | _ -> + None + | _ -> + None + + member __.SystemRuntimeContainsType typeName = + match tcImports.TryGetTarget () with + | true, strong -> strong.SystemRuntimeContainsType typeName + | _ -> false +#endif /// Represents a table of imported assemblies with their resolutions. -[] -type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolutions, importsBase: TcImports option, ilGlobalsOpt) = +/// Is a disposable object, but it is recommended not to explicitly call Dispose unless you absolutely know nothing will be using its contents after the disposal. +/// Otherwise, simply allow the GC to collect this and it will properly call Dispose from the finalizer. +and [] TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolutions, importsBase: TcImports option, ilGlobalsOpt, compilationThread: ICompilationThread) as this = let mutable resolutions = initialResolutions let mutable importsBase: TcImports option = importsBase @@ -4013,26 +4037,40 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu let mutable dllTable: NameMap = NameMap.empty let mutable ccuInfos: ImportedAssembly list = [] let mutable ccuTable: NameMap = NameMap.empty - let mutable disposeActions = [] + let disposeActions = ResizeArray() let mutable disposed = false let mutable ilGlobalsOpt = ilGlobalsOpt let mutable tcGlobals = None #if !NO_EXTENSIONTYPING + let disposeTypeProviderActions = ResizeArray() let mutable generatedTypeRoots = new System.Collections.Generic.Dictionary() + let mutable tcImportsWeak = TcImportsWeakHack (WeakReference<_> this) #endif + + let disposal = new TcImportsSafeDisposal(disposeActions, disposeTypeProviderActions, compilationThread) let CheckDisposed() = if disposed then assert false + let dispose () = + CheckDisposed() + (disposal :> IDisposable).Dispose() + static let ccuHasType (ccu: CcuThunk) (nsname: string list) (tname: string) = - match (Some ccu.Contents, nsname) ||> List.fold (fun entityOpt n -> match entityOpt with None -> None | Some entity -> entity.ModuleOrNamespaceType.AllEntitiesByCompiledAndLogicalMangledNames.TryFind n) with + let matchNameSpace (entityOpt: Entity option) n = + match entityOpt with + | None -> None + | Some entity -> + entity.ModuleOrNamespaceType.AllEntitiesByCompiledAndLogicalMangledNames.TryFind n + + match (Some ccu.Contents, nsname) ||> List.fold matchNameSpace with | Some ns -> match Map.tryFind tname ns.ModuleOrNamespaceType.TypesByMangledName with | Some _ -> true | None -> false | None -> false - - member private tcImports.Base = + + member internal tcImports.Base = CheckDisposed() importsBase @@ -4042,40 +4080,49 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu member tcImports.DllTable = CheckDisposed() - dllTable + dllTable + +#if !NO_EXTENSIONTYPING + member tcImports.Weak = + CheckDisposed() + tcImportsWeak +#endif - member tcImports.RegisterCcu(ccuInfo) = + member tcImports.RegisterCcu ccuInfo = CheckDisposed() ccuInfos <- ccuInfos ++ ccuInfo // Assembly Ref Resolution: remove this use of ccu.AssemblyName ccuTable <- NameMap.add (ccuInfo.FSharpViewOfMetadata.AssemblyName) ccuInfo ccuTable - member tcImports.RegisterDll(dllInfo) = + member tcImports.RegisterDll dllInfo = CheckDisposed() dllInfos <- dllInfos ++ dllInfo +#if !NO_EXTENSIONTYPING + tcImportsWeak.SetDllInfos dllInfos +#endif dllTable <- NameMap.add (getNameOfScopeRef dllInfo.ILScopeRef) dllInfo dllTable - member tcImports.GetDllInfos() = + member tcImports.GetDllInfos() : ImportedBinary list = CheckDisposed() match importsBase with - | Some(importsBase)-> importsBase.GetDllInfos() @ dllInfos + | Some importsBase-> importsBase.GetDllInfos() @ dllInfos | None -> dllInfos member tcImports.AllAssemblyResolutions() = CheckDisposed() let ars = resolutions.GetAssemblyResolutions() match importsBase with - | Some(importsBase)-> importsBase.AllAssemblyResolutions() @ ars + | Some importsBase-> importsBase.AllAssemblyResolutions() @ ars | None -> ars member tcImports.TryFindDllInfo (ctok: CompilationThreadToken, m, assemblyName, lookupOnly) = CheckDisposed() let rec look (t: TcImports) = match NameMap.tryFind assemblyName t.DllTable with - | Some res -> Some(res) + | Some res -> Some res | None -> match t.Base with - | Some t2 -> look(t2) + | Some t2 -> look t2 | None -> None match look tcImports with | Some res -> Some res @@ -4087,12 +4134,12 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu member tcImports.FindDllInfo (ctok, m, assemblyName) = match tcImports.TryFindDllInfo (ctok, m, assemblyName, lookupOnly=false) with | Some res -> res - | None -> error(Error(FSComp.SR.buildCouldNotResolveAssembly(assemblyName), m)) + | None -> error(Error(FSComp.SR.buildCouldNotResolveAssembly assemblyName, m)) member tcImports.GetImportedAssemblies() = CheckDisposed() match importsBase with - | Some(importsBase)-> List.append (importsBase.GetImportedAssemblies()) ccuInfos + | Some importsBase-> List.append (importsBase.GetImportedAssemblies()) ccuInfos | None -> ccuInfos member tcImports.GetCcusExcludingBase() = @@ -4108,31 +4155,31 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu CheckDisposed() let rec look (t: TcImports) = match NameMap.tryFind assemblyName t.CcuTable with - | Some res -> Some(res) + | Some res -> Some res | None -> match t.Base with | Some t2 -> look t2 | None -> None match look tcImports with - | Some res -> ResolvedImportedAssembly(res) + | Some res -> ResolvedImportedAssembly res | None -> tcImports.ImplicitLoadIfAllowed(ctok, m, assemblyName, lookupOnly) match look tcImports with - | Some res -> ResolvedImportedAssembly(res) - | None -> UnresolvedImportedAssembly(assemblyName) + | Some res -> ResolvedImportedAssembly res + | None -> UnresolvedImportedAssembly assemblyName member tcImports.FindCcu (ctok, m, assemblyName, lookupOnly) = CheckDisposed() match tcImports.FindCcuInfo(ctok, m, assemblyName, lookupOnly) with - | ResolvedImportedAssembly(importedAssembly) -> ResolvedCcu(importedAssembly.FSharpViewOfMetadata) - | UnresolvedImportedAssembly(assemblyName) -> UnresolvedCcu(assemblyName) + | ResolvedImportedAssembly importedAssembly -> ResolvedCcu(importedAssembly.FSharpViewOfMetadata) + | UnresolvedImportedAssembly assemblyName -> UnresolvedCcu assemblyName member tcImports.FindCcuFromAssemblyRef(ctok, m, assemblyRef: ILAssemblyRef) = CheckDisposed() match tcImports.FindCcuInfo(ctok, m, assemblyRef.Name, lookupOnly=false) with - | ResolvedImportedAssembly(importedAssembly) -> ResolvedCcu(importedAssembly.FSharpViewOfMetadata) + | ResolvedImportedAssembly importedAssembly -> ResolvedCcu(importedAssembly.FSharpViewOfMetadata) | UnresolvedImportedAssembly _ -> UnresolvedCcu(assemblyRef.QualifiedName) @@ -4155,12 +4202,11 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu let g = tcImports.GetTcGlobals() let ilScopeRef = ILScopeRef.Assembly (ILAssemblyRef.FromAssemblyName aname) let fileName = aname.Name + ".dll" - let bytes = assembly.PApplyWithProvider((fun (assembly, provider) -> assembly.GetManifestModuleContents(provider)), m).PUntaint(id, m) - let tcConfig = tcConfigP.Get(ctok) + let bytes = assembly.PApplyWithProvider((fun (assembly, provider) -> assembly.GetManifestModuleContents provider), m).PUntaint(id, m) + let tcConfig = tcConfigP.Get ctok let ilModule, ilAssemblyRefs = let opts: ILReaderOptions = - { ilGlobals = g.ilg - reduceMemoryUsage = tcConfig.reduceMemoryUsage + { reduceMemoryUsage = tcConfig.reduceMemoryUsage pdbDirPath = None metadataOnly = MetadataOnlyFlag.Yes tryGetMetadataSnapshot = tcConfig.tryGetMetadataSnapshot } @@ -4176,19 +4222,22 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu ProviderGeneratedStaticLinkMap= if g.isInteractive then None else Some (ProvidedAssemblyStaticLinkingMap.CreateNew()) ILScopeRef = ilScopeRef ILAssemblyRefs = ilAssemblyRefs } - tcImports.RegisterDll(dllinfo) + tcImports.RegisterDll dllinfo + + let ccuContents = Construct.NewCcuContents ilScopeRef m ilShortAssemName (Construct.NewEmptyModuleOrNamespaceType Namespace) + let ccuData: CcuData = { IsFSharp=false UsesFSharp20PlusQuotations=false InvalidateEvent=(new Event<_>()).Publish IsProviderGenerated = true QualifiedName= Some (assembly.PUntaint((fun a -> a.FullName), m)) - Contents = NewCcuContents ilScopeRef m ilShortAssemName (NewEmptyModuleOrNamespaceType Namespace) + Contents = ccuContents ILScopeRef = ilScopeRef Stamp = newStamp() SourceCodeDirectory = "" FileName = Some fileName - MemberSignatureEquality = (fun ty1 ty2 -> Tastops.typeEquivAux EraseAll g ty1 ty2) + MemberSignatureEquality = (fun ty1 ty2 -> typeEquivAux EraseAll g ty1 ty2) ImportProvidedType = (fun ty -> Import.ImportProvidedType (tcImports.GetImportMap()) m ty) TryGetILModuleDef = (fun () -> Some ilModule) TypeForwarders = Map.empty } @@ -4202,7 +4251,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu IsProviderGenerated = true TypeProviders=[] FSharpOptimizationData = notlazy None } - tcImports.RegisterCcu(ccuinfo) + tcImports.RegisterCcu ccuinfo // Yes, it is generative true, dllinfo.ProviderGeneratedStaticLinkMap @@ -4222,16 +4271,22 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu |> Seq.toList #endif - member tcImports.AttachDisposeAction(action) = + member private tcImports.AttachDisposeAction action = + CheckDisposed() + disposeActions.Add action + +#if !NO_EXTENSIONTYPING + member private tcImports.AttachDisposeTypeProviderAction action = CheckDisposed() - disposeActions <- action :: disposeActions + disposeTypeProviderActions.Add action +#endif // Note: the returned binary reader is associated with the tcImports, i.e. when the tcImports are closed // then the reader is closed. member tcImports.OpenILBinaryModule(ctok, filename, m) = try CheckDisposed() - let tcConfig = tcConfigP.Get(ctok) + let tcConfig = tcConfigP.Get ctok let pdbDirPath = // We open the pdb file if one exists parallel to the binary we // are reading, so that --standalone will preserve debug information. @@ -4239,7 +4294,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu let pdbDir = try Filename.directoryName filename with _ -> "." let pdbFile = (try Filename.chopExtension filename with _ -> filename) + ".pdb" - if FileSystem.SafeExists(pdbFile) then + if FileSystem.SafeExists pdbFile then if verbose then dprintf "reading PDB file %s from directory %s\n" pdbFile pdbDir Some pdbDir else @@ -4247,15 +4302,8 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu else None - let ilGlobals = - // ILScopeRef.Local can be used only for primary assembly (mscorlib or System.Runtime) itself - // Remaining assemblies should be opened using existing ilGlobals (so they can properly locate fundamental types) - match ilGlobalsOpt with - | None -> mkILGlobals ILScopeRef.Local - | Some g -> g - let ilILBinaryReader = - OpenILBinary (filename, tcConfig.reduceMemoryUsage, ilGlobals, pdbDirPath, tcConfig.shadowCopyReferences, tcConfig.tryGetMetadataSnapshot) + OpenILBinary (filename, tcConfig.reduceMemoryUsage, pdbDirPath, tcConfig.shadowCopyReferences, tcConfig.tryGetMetadataSnapshot) tcImports.AttachDisposeAction(fun _ -> (ilILBinaryReader :> IDisposable).Dispose()) ilILBinaryReader.ILModuleDef, ilILBinaryReader.ILAssemblyRefs @@ -4268,11 +4316,11 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu let auxModTable = HashMultiMap(10, HashIdentity.Structural) fun viewedScopeRef -> - let tcConfig = tcConfigP.Get(ctok) + let tcConfig = tcConfigP.Get ctok match viewedScopeRef with | ILScopeRef.Module modref -> let key = modref.Name - if not (auxModTable.ContainsKey(key)) then + if not (auxModTable.ContainsKey key) then let resolution = tcConfig.ResolveLibWithDirectories (CcuLoadFailureAction.RaiseError, AssemblyReference(m, key, None)) |> Option.get let ilModule, _ = tcImports.OpenILBinaryModule(ctok, resolution.resolvedPath, m) auxModTable.[key] <- ilModule @@ -4331,21 +4379,23 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu (typeProviderEnvironment, tcConfig: TcConfig, m, entity: Entity, - injectedNamspace, remainingNamespace, + injectedNamespace, remainingNamespace, provider, st: Tainted option) = match remainingNamespace with - | next::rest -> + | next :: rest -> // Inject the namespace entity - match entity.ModuleOrNamespaceType.ModulesAndNamespacesByDemangledName.TryFind(next) with + match entity.ModuleOrNamespaceType.ModulesAndNamespacesByDemangledName.TryFind next with | Some childEntity -> - tcImports.InjectProvidedNamespaceOrTypeIntoEntity (typeProviderEnvironment, tcConfig, m, childEntity, next::injectedNamspace, rest, provider, st) + tcImports.InjectProvidedNamespaceOrTypeIntoEntity (typeProviderEnvironment, tcConfig, m, childEntity, next :: injectedNamespace, rest, provider, st) | None -> // Build up the artificial namespace if there is not a real one. - let cpath = CompPath(ILScopeRef.Local, injectedNamspace |> List.rev |> List.map (fun n -> (n, ModuleOrNamespaceKind.Namespace)) ) - let newNamespace = NewModuleOrNamespace (Some cpath) taccessPublic (ident(next, rangeStartup)) XmlDoc.Empty [] (MaybeLazy.Strict (NewEmptyModuleOrNamespaceType Namespace)) - entity.ModuleOrNamespaceType.AddModuleOrNamespaceByMutation(newNamespace) - tcImports.InjectProvidedNamespaceOrTypeIntoEntity (typeProviderEnvironment, tcConfig, m, newNamespace, next::injectedNamspace, rest, provider, st) + let cpath = CompPath(ILScopeRef.Local, injectedNamespace |> List.rev |> List.map (fun n -> (n, ModuleOrNamespaceKind.Namespace)) ) + let mid = ident (next, rangeStartup) + let mty = Construct.NewEmptyModuleOrNamespaceType Namespace + let newNamespace = Construct.NewModuleOrNamespace (Some cpath) taccessPublic mid XmlDoc.Empty [] (MaybeLazy.Strict mty) + entity.ModuleOrNamespaceType.AddModuleOrNamespaceByMutation newNamespace + tcImports.InjectProvidedNamespaceOrTypeIntoEntity (typeProviderEnvironment, tcConfig, m, newNamespace, next :: injectedNamespace, rest, provider, st) | [] -> match st with | Some st -> @@ -4356,7 +4406,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu let importProvidedType t = Import.ImportProvidedType (tcImports.GetImportMap()) m t let isSuppressRelocate = tcConfig.isInteractive || st.PUntaint((fun st -> st.IsSuppressRelocate), m) let newEntity = Construct.NewProvidedTycon(typeProviderEnvironment, st, importProvidedType, isSuppressRelocate, m) - entity.ModuleOrNamespaceType.AddProvidedTypeEntity(newEntity) + entity.ModuleOrNamespaceType.AddProvidedTypeEntity newEntity | None -> () entity.entity_tycon_repr <- @@ -4368,13 +4418,13 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu // Add to the existing list of extensions | TProvidedNamespaceExtensionPoint(resolutionFolder, prior) as repr -> if not(prior |> List.exists(fun r->Tainted.EqTainted r provider)) then - TProvidedNamespaceExtensionPoint(resolutionFolder, provider::prior) + TProvidedNamespaceExtensionPoint(resolutionFolder, provider :: prior) else repr | _ -> failwith "Unexpected representation in namespace entity referred to by a type provider" - member tcImports.ImportTypeProviderExtensions + member tcImportsStrong.ImportTypeProviderExtensions (ctok, tcConfig: TcConfig, fileNameOfRuntimeAssembly, ilScopeRefOfRuntimeAssembly, @@ -4392,7 +4442,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu |> List.map (function null -> fileNameOfRuntimeAssembly | s -> s) // For each simple name of a design-time assembly, we take the first matching one in the order they are // specified in the attributes - |> List.distinctBy (fun s -> try Path.GetFileNameWithoutExtension(s) with _ -> s) + |> List.distinctBy (fun s -> try Path.GetFileNameWithoutExtension s with _ -> s) if not (List.isEmpty designTimeAssemblyNames) then @@ -4408,7 +4458,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu { resolutionFolder = tcConfig.implicitIncludeDir outputFile = tcConfig.outputFile showResolutionMessages = tcConfig.showExtensionTypeMessages - referencedAssemblies = Array.distinct [| for r in tcImports.AllAssemblyResolutions() -> r.resolvedPath |] + referencedAssemblies = Array.distinct [| for r in tcImportsStrong.AllAssemblyResolutions() -> r.resolvedPath |] temporaryFolder = FileSystem.GetTempPathShim() } // The type provider should not hold strong references to disposed @@ -4416,20 +4466,28 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu // dispatch via a thunk which gets set to a non-resource-capturing // failing function when the object is disposed. let systemRuntimeContainsType = - // NOTE: do not touch this - let systemRuntimeContainsTypeRef = ref (fun typeName -> tcImports.SystemRuntimeContainsType(typeName)) - tcImports.AttachDisposeAction(fun () -> systemRuntimeContainsTypeRef := (fun _ -> raise (System.ObjectDisposedException("The type provider has been disposed")))) - fun arg -> systemRuntimeContainsTypeRef.Value arg - - let providers = - [ for designTimeAssemblyName in designTimeAssemblyNames do - yield! ExtensionTyping.GetTypeProvidersOfAssembly(fileNameOfRuntimeAssembly, ilScopeRefOfRuntimeAssembly, designTimeAssemblyName, typeProviderEnvironment, - tcConfig.isInvalidationSupported, tcConfig.isInteractive, systemRuntimeContainsType, primaryAssemblyVersion, m) ] - + // NOTE: do not touch this, edit: but we did, we had no choice - TPs cannot hold a strong reference on TcImports "ever". + let tcImports = tcImportsWeak + let mutable systemRuntimeContainsTypeRef = fun typeName -> tcImports.SystemRuntimeContainsType typeName + tcImportsStrong.AttachDisposeTypeProviderAction(fun () -> systemRuntimeContainsTypeRef <- fun _ -> raise (System.ObjectDisposedException("The type provider has been disposed"))) + fun arg -> systemRuntimeContainsTypeRef arg + + let providers = [ + for designTimeAssemblyName in designTimeAssemblyNames do + yield! ExtensionTyping.GetTypeProvidersOfAssembly(fileNameOfRuntimeAssembly, + ilScopeRefOfRuntimeAssembly, + designTimeAssemblyName, + typeProviderEnvironment, + tcConfig.isInvalidationSupported, + tcConfig.isInteractive, + systemRuntimeContainsType, + primaryAssemblyVersion, + tcConfig.compilerToolPaths, + m) ] // Note, type providers are disposable objects. The TcImports owns the provider objects - when/if it is disposed, the providers are disposed. // We ignore all exceptions from provider disposal. for provider in providers do - tcImports.AttachDisposeAction(fun () -> + tcImportsStrong.AttachDisposeTypeProviderAction(fun () -> try provider.PUntaintNoFailure(fun x -> x).Dispose() with e -> @@ -4438,8 +4496,27 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu // Add the invalidation signal handlers to each provider for provider in providers do provider.PUntaint((fun tp -> - let handler = tp.Invalidate.Subscribe(fun _ -> invalidateCcu.Trigger ("The provider '" + fileNameOfRuntimeAssembly + "' reported a change")) - tcImports.AttachDisposeAction(fun () -> try handler.Dispose() with _ -> ())), m) + + // Register the type provider invalidation handler. + // + // 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 closure captures + // 1. an Event value, ultimately this is made available in all CCus as ccu.InvalidateEvent + // 2. any handlers registered to ccu.InvalidateEvent + // 3. a message string + // + // Note that the invalidation handler does not explicitly capture the TcImports. + // The only place where handlers are registered is to ccu.InvalidateEvent is in IncrementalBuilder.fs. + + let capturedInvalidateCcu = invalidateCcu + let capturedMessage = "The provider '" + fileNameOfRuntimeAssembly + "' reported a change" + let handler = tp.Invalidate.Subscribe(fun _ -> capturedInvalidateCcu.Trigger (capturedMessage)) + + // When the TcImports is disposed we detach the invalidation callback + tcImportsStrong.AttachDisposeTypeProviderAction(fun () -> try handler.Dispose() with _ -> ())), m) match providers with | [] -> @@ -4458,7 +4535,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu // for that namespace. let rec loop (providedNamespace: Tainted) = let path = ExtensionTyping.GetProvidedNamespaceAsPath(m, provider, providedNamespace.PUntaint((fun r -> r.NamespaceName), m)) - tcImports.InjectProvidedNamespaceOrTypeIntoEntity (typeProviderEnvironment, tcConfig, m, entityToInjectInto, [], path, provider, None) + tcImportsStrong.InjectProvidedNamespaceOrTypeIntoEntity (typeProviderEnvironment, tcConfig, m, entityToInjectInto, [], path, provider, None) // Inject entities for the types returned by provider.GetTypes(). // @@ -4468,7 +4545,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu let tys = providedNamespace.PApplyArray((fun provider -> provider.GetTypes()), "GetTypes", m) let ptys = [| for ty in tys -> ty.PApply((fun ty -> ty |> ProvidedType.CreateNoContext), m) |] for st in ptys do - tcImports.InjectProvidedNamespaceOrTypeIntoEntity (typeProviderEnvironment, tcConfig, m, entityToInjectInto, [], path, provider, Some st) + tcImportsStrong.InjectProvidedNamespaceOrTypeIntoEntity (typeProviderEnvironment, tcConfig, m, entityToInjectInto, [], path, provider, Some st) for providedNestedNamespace in providedNamespace.PApplyArray((fun provider -> provider.GetNestedNamespaces()), "GetNestedNamespaces", m) do loop providedNestedNamespace @@ -4503,7 +4580,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu member tcImports.PrepareToImportReferencedILAssembly (ctok, m, filename, dllinfo: ImportedBinary) = CheckDisposed() - let tcConfig = tcConfigP.Get(ctok) + let tcConfig = tcConfigP.Get ctok assert dllinfo.RawMetadata.TryGetILModuleDef().IsSome let ilModule = dllinfo.RawMetadata.TryGetILModuleDef().Value let ilScopeRef = dllinfo.ILScopeRef @@ -4530,18 +4607,18 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu TypeProviders = [] #endif FSharpOptimizationData = notlazy None } - tcImports.RegisterCcu(ccuinfo) + tcImports.RegisterCcu ccuinfo let phase2 () = #if !NO_EXTENSIONTYPING ccuinfo.TypeProviders <- tcImports.ImportTypeProviderExtensions (ctok, tcConfig, filename, ilScopeRef, ilModule.ManifestOfAssembly.CustomAttrs.AsList, ccu.Contents, invalidateCcu, m) #endif - [ResolvedImportedAssembly(ccuinfo)] + [ResolvedImportedAssembly ccuinfo] phase2 member tcImports.PrepareToImportReferencedFSharpAssembly (ctok, m, filename, dllinfo: ImportedBinary) = CheckDisposed() #if !NO_EXTENSIONTYPING - let tcConfig = tcConfigP.Get(ctok) + let tcConfig = tcConfigP.Get ctok #endif let ilModule = dllinfo.RawMetadata let ilScopeRef = dllinfo.ILScopeRef @@ -4580,7 +4657,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu #endif TryGetILModuleDef = ilModule.TryGetILModuleDef UsesFSharp20PlusQuotations = minfo.usesQuotations - MemberSignatureEquality= (fun ty1 ty2 -> Tastops.typeEquivAux EraseAll (tcImports.GetTcGlobals()) ty1 ty2) + MemberSignatureEquality= (fun ty1 ty2 -> typeEquivAux EraseAll (tcImports.GetTcGlobals()) ty1 ty2) TypeForwarders = ImportILAssemblyTypeForwarders(tcImports.GetImportMap, m, ilModule.GetRawTypeForwarders()) } let ccu = CcuThunk.Create(ccuName, ccuData) @@ -4596,23 +4673,27 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu let res = data.OptionalFixup(fun nm -> availableToOptionalCcu(tcImports.FindCcu(ctok, m, nm, lookupOnly=false))) if verbose then dprintf "found optimization data for CCU %s\n" ccuName Some res) + let ilg = defaultArg ilGlobalsOpt EcmaMscorlibILGlobals + let ccuinfo = { FSharpViewOfMetadata=ccu - AssemblyAutoOpenAttributes = ilModule.GetAutoOpenAttributes(ilg) - AssemblyInternalsVisibleToAttributes = ilModule.GetInternalsVisibleToAttributes(ilg) + AssemblyAutoOpenAttributes = ilModule.GetAutoOpenAttributes ilg + AssemblyInternalsVisibleToAttributes = ilModule.GetInternalsVisibleToAttributes ilg FSharpOptimizationData=optdata #if !NO_EXTENSIONTYPING IsProviderGenerated = false TypeProviders = [] #endif ILScopeRef = ilScopeRef } + let phase2() = #if !NO_EXTENSIONTYPING match ilModule.TryGetILModuleDef() with | None -> () // no type providers can be used without a real IL Module present | Some ilModule -> - ccuinfo.TypeProviders <- tcImports.ImportTypeProviderExtensions (ctok, tcConfig, filename, ilScopeRef, ilModule.ManifestOfAssembly.CustomAttrs.AsList, ccu.Contents, invalidateCcu, m) + let tps = tcImports.ImportTypeProviderExtensions (ctok, tcConfig, filename, ilScopeRef, ilModule.ManifestOfAssembly.CustomAttrs.AsList, ccu.Contents, invalidateCcu, m) + ccuinfo.TypeProviders <- tps #else () #endif @@ -4640,7 +4721,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu let! contentsOpt = cancellable { match r.ProjectReference with - | Some ilb -> return! ilb.EvaluateRawContents(ctok) + | Some ilb -> return! ilb.EvaluateRawContents ctok | None -> return None } @@ -4669,12 +4750,12 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu #endif ILScopeRef = ilScopeRef ILAssemblyRefs = assemblyData.ILAssemblyRefs } - tcImports.RegisterDll(dllinfo) + tcImports.RegisterDll dllinfo let ilg = defaultArg ilGlobalsOpt EcmaMscorlibILGlobals let phase2 = if assemblyData.HasAnyFSharpSignatureDataAttribute then - if not (assemblyData.HasMatchingFSharpSignatureDataAttribute(ilg)) then - errorR(Error(FSComp.SR.buildDifferentVersionMustRecompile(filename), m)) + if not (assemblyData.HasMatchingFSharpSignatureDataAttribute ilg) then + errorR(Error(FSComp.SR.buildDifferentVersionMustRecompile filename, m)) tcImports.PrepareToImportReferencedILAssembly (ctok, m, filename, dllinfo) else try @@ -4689,7 +4770,6 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu member tcImports.RegisterAndImportReferencedAssemblies (ctok, nms: AssemblyResolution list) = cancellable { CheckDisposed() - let! results = nms |> Cancellable.each (fun nm -> cancellable { @@ -4713,7 +4793,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu CheckDisposed() // If the user is asking for the default framework then also try to resolve other implicit assemblies as they are discovered. // Using this flag to mean 'allow implicit discover of assemblies'. - let tcConfig = tcConfigP.Get(ctok) + let tcConfig = tcConfigP.Get ctok if not lookupOnly && tcConfig.implicitlyResolveAssemblies then let tryFile speculativeFileName = let foundFile = tcImports.TryResolveAssemblyReference (ctok, AssemblyReference (m, speculativeFileName, None), ResolveAssemblyReferenceMode.Speculative) @@ -4748,7 +4828,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu resolutions.TryFindByExactILAssemblyRef (ctok, assemblyRef) |> Option.map (fun r -> r.resolvedPath) member tcImports.TryResolveAssemblyReference(ctok, assemblyReference: AssemblyReference, mode: ResolveAssemblyReferenceMode) : OperationResult = - let tcConfig = tcConfigP.Get(ctok) + let tcConfig = tcConfigP.Get ctok // First try to lookup via the original reference text. match resolutions.TryFindByOriginalReference assemblyReference with | Some assemblyResolution -> @@ -4758,7 +4838,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu try ResultD [tcConfig.ResolveLibWithDirectories assemblyReference] with e -> - ErrorD(e) + ErrorD e #else // Next try to lookup up by the exact full resolved path. match resolutions.TryFindByResolvedPath assemblyReference.Text with @@ -4777,14 +4857,14 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu | None -> ErrorD(AssemblyNotResolved(assemblyReference.Text, assemblyReference.Range)) else - // This is a previously unencounterd assembly. Resolve it and add it to the list. + // This is a previously unencountered assembly. Resolve it and add it to the list. // But don't cache resolution failures because the assembly may appear on the disk later. let resolved, unresolved = TcConfig.TryResolveLibsUsingMSBuildRules(tcConfig, [ assemblyReference ], assemblyReference.Range, mode) match resolved, unresolved with - | (assemblyResolution::_, _) -> + | (assemblyResolution :: _, _) -> resolutions <- resolutions.AddResolutionResults resolved ResultD [assemblyResolution] - | (_, _::_) -> + | (_, _ :: _) -> resolutions <- resolutions.AddUnresolvedReferences unresolved ErrorD(AssemblyNotResolved(assemblyReference.Text, assemblyReference.Range)) | [], [] -> @@ -4800,35 +4880,75 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu // Note: This returns a TcImports object. However, framework TcImports are not currently disposed. The only reason // we dispose TcImports is because we need to dispose type providers, and type providers are never included in the framework DLL set. - // - // If this ever changes then callers may need to begin disposing the TcImports (though remember, not before all derived - // non-framework TcImports built related to this framework TcImports are disposed). + // If a framework set ever includes type providers, you will not have to worry about explicitly calling Dispose as the Finalizer will handle it. static member BuildFrameworkTcImports (ctok, tcConfigP: TcConfigProvider, frameworkDLLs, nonFrameworkDLLs) = cancellable { - let tcConfig = tcConfigP.Get(ctok) + let tcConfig = tcConfigP.Get ctok let tcResolutions = TcAssemblyResolutions.BuildFromPriorResolutions(ctok, tcConfig, frameworkDLLs, []) let tcAltResolutions = TcAssemblyResolutions.BuildFromPriorResolutions(ctok, tcConfig, nonFrameworkDLLs, []) - // Note: TcImports are disposable - the caller owns this object and must dispose - let frameworkTcImports = new TcImports(tcConfigP, tcResolutions, None, None) - - let primaryAssemblyReference = tcConfig.PrimaryAssemblyDllReference() + let frameworkTcImports = new TcImports(tcConfigP, tcResolutions, None, None, tcConfig.compilationThread) + + // Fetch the primaryAssembly from the referenced assemblies otherwise + let primaryAssemblyReference = + let path = frameworkDLLs |> List.tryFind(fun dll -> String.Compare(Path.GetFileNameWithoutExtension(dll.resolvedPath), tcConfig.primaryAssembly.Name, StringComparison.OrdinalIgnoreCase) = 0) + match path with + | Some p -> AssemblyReference(range0, p.resolvedPath, None) + | None -> tcConfig.PrimaryAssemblyDllReference() + let primaryAssemblyResolution = frameworkTcImports.ResolveAssemblyReference(ctok, primaryAssemblyReference, ResolveAssemblyReferenceMode.ReportErrors) let! primaryAssem = frameworkTcImports.RegisterAndImportReferencedAssemblies(ctok, primaryAssemblyResolution) let primaryScopeRef = match primaryAssem with - | (_, [ResolvedImportedAssembly(ccu)]) -> ccu.FSharpViewOfMetadata.ILScopeRef + | (_, [ResolvedImportedAssembly ccu]) -> ccu.FSharpViewOfMetadata.ILScopeRef | _ -> failwith "unexpected" - let ilGlobals = mkILGlobals primaryScopeRef + let primaryAssemblyResolvedPath = + match primaryAssemblyResolution with + | [primaryAssemblyResolution] -> primaryAssemblyResolution.resolvedPath + | _ -> failwith "unexpected" + + let resolvedAssemblies = tcResolutions.GetAssemblyResolutions() + + let readerSettings: ILReaderOptions = + { pdbDirPath=None + reduceMemoryUsage = tcConfig.reduceMemoryUsage + metadataOnly = MetadataOnlyFlag.Yes + tryGetMetadataSnapshot = tcConfig.tryGetMetadataSnapshot } + + let tryFindAssemblyByExportedType manifest (exportedType: ILExportedTypeOrForwarder) = + match exportedType.ScopeRef, primaryScopeRef with + | ILScopeRef.Assembly aref1, ILScopeRef.Assembly aref2 when aref1.EqualsIgnoringVersion aref2 -> + mkRefToILAssembly manifest + |> Some + | _ -> + None + + let tryFindAssemblyThatForwardsToPrimaryAssembly manifest = + manifest.ExportedTypes.TryFindByName "System.Object" + |> Option.bind (tryFindAssemblyByExportedType manifest) + + // Determine what other assemblies could have been the primary assembly + // by checking to see if "System.Object" is an exported type. + let assembliesThatForwardToPrimaryAssembly = + resolvedAssemblies + |> List.choose (fun resolvedAssembly -> + if primaryAssemblyResolvedPath <> resolvedAssembly.resolvedPath then + let reader = OpenILModuleReader resolvedAssembly.resolvedPath readerSettings + reader.ILModuleDef.Manifest + |> Option.bind tryFindAssemblyThatForwardsToPrimaryAssembly + else + None) + + let ilGlobals = mkILGlobals (primaryScopeRef, assembliesThatForwardToPrimaryAssembly) frameworkTcImports.SetILGlobals ilGlobals // Load the rest of the framework DLLs all at once (they may be mutually recursive) - let! _assemblies = frameworkTcImports.RegisterAndImportReferencedAssemblies (ctok, tcResolutions.GetAssemblyResolutions()) + let! _assemblies = frameworkTcImports.RegisterAndImportReferencedAssemblies (ctok, resolvedAssemblies) // These are the DLLs we can search for well-known types - let sysCcus = + let sysCcus = [| for ccu in frameworkTcImports.GetCcusInDeclOrder() do //printfn "found sys ccu %s" ccu.AssemblyName yield ccu |] @@ -4842,7 +4962,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu let fslibCcu = if tcConfig.compilingFslib then // When compiling FSharp.Core.dll, the fslibCcu reference to FSharp.Core.dll is a delayed ccu thunk fixed up during type checking - CcuThunk.CreateDelayed(GetFSharpCoreLibraryName()) + CcuThunk.CreateDelayed getFSharpCoreLibraryName else let fslibCcuInfo = let coreLibraryReference = tcConfig.CoreLibraryDllReference() @@ -4854,41 +4974,43 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu // Are we using a "non-canonical" FSharp.Core? match tcAltResolutions.TryFindByOriginalReference coreLibraryReference with | Some resolution -> Some resolution - | _ -> tcResolutions.TryFindByOriginalReferenceText (GetFSharpCoreLibraryName()) // was the ".dll" elided? + | _ -> tcResolutions.TryFindByOriginalReferenceText (getFSharpCoreLibraryName) // was the ".dll" elided? match resolvedAssemblyRef with | Some coreLibraryResolution -> match frameworkTcImports.RegisterAndImportReferencedAssemblies(ctok, [coreLibraryResolution]) |> Cancellable.runWithoutCancellation with - | (_, [ResolvedImportedAssembly(fslibCcuInfo) ]) -> fslibCcuInfo + | (_, [ResolvedImportedAssembly fslibCcuInfo ]) -> fslibCcuInfo | _ -> error(InternalError("BuildFrameworkTcImports: no successful import of "+coreLibraryResolution.resolvedPath, coreLibraryResolution.originalReference.Range)) | None -> error(InternalError(sprintf "BuildFrameworkTcImports: no resolution of '%s'" coreLibraryReference.Text, rangeStartup)) - IlxSettings.ilxFsharpCoreLibAssemRef := + IlxSettings.ilxFsharpCoreLibAssemRef <- (let scoref = fslibCcuInfo.ILScopeRef match scoref with | ILScopeRef.Assembly aref -> Some aref - | ILScopeRef.Local | ILScopeRef.Module _ -> error(InternalError("not ILScopeRef.Assembly", rangeStartup))) - fslibCcuInfo.FSharpViewOfMetadata - + | ILScopeRef.Local | ILScopeRef.Module _ | ILScopeRef.PrimaryAssembly -> + error(InternalError("not ILScopeRef.Assembly", rangeStartup))) + fslibCcuInfo.FSharpViewOfMetadata + // OK, now we have both mscorlib.dll and FSharp.Core.dll we can create TcGlobals - let tcGlobals = TcGlobals(tcConfig.compilingFslib, ilGlobals, fslibCcu, - tcConfig.implicitIncludeDir, tcConfig.mlCompatibility, - tcConfig.isInteractive, tryFindSysTypeCcu, tcConfig.emitDebugInfoInQuotations, tcConfig.noDebugData ) + let tcGlobals = TcGlobals(tcConfig.compilingFslib, ilGlobals, fslibCcu, + tcConfig.implicitIncludeDir, tcConfig.mlCompatibility, + tcConfig.isInteractive, tryFindSysTypeCcu, tcConfig.emitDebugInfoInQuotations, + tcConfig.noDebugData, tcConfig.pathMap, tcConfig.langVersion) #if DEBUG // the global_g reference cell is used only for debug printing - global_g := Some tcGlobals + global_g <- Some tcGlobals #endif // do this prior to parsing, since parsing IL assembly code may refer to mscorlib #if !NO_INLINE_IL_PARSER - FSharp.Compiler.AbstractIL.Internal.AsciiConstants.parseILGlobals := tcGlobals.ilg + FSharp.Compiler.AbstractIL.Internal.AsciiConstants.parseILGlobals <- tcGlobals.ilg #endif - frameworkTcImports.SetTcGlobals(tcGlobals) + frameworkTcImports.SetTcGlobals tcGlobals return tcGlobals, frameworkTcImports } - member tcImports.ReportUnresolvedAssemblyReferences(knownUnresolved) = + member tcImports.ReportUnresolvedAssemblyReferences knownUnresolved = // Report that an assembly was not resolved. let reportAssemblyNotResolved(file, originalReferences: AssemblyReference list) = originalReferences |> List.iter(fun originalReference -> errorR(AssemblyNotResolved(file, originalReference.Range))) @@ -4896,27 +5018,21 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu |> List.map (function UnresolvedAssemblyReference(file, originalReferences) -> file, originalReferences) |> List.iter reportAssemblyNotResolved - // Note: This returns a TcImports object. TcImports are disposable - the caller owns the returned TcImports object - // and when hosted in Visual Studio or another long-running process must dispose this object. static member BuildNonFrameworkTcImports (ctok, tcConfigP: TcConfigProvider, tcGlobals: TcGlobals, baseTcImports, nonFrameworkReferences, knownUnresolved) = cancellable { - let tcConfig = tcConfigP.Get(ctok) + let tcConfig = tcConfigP.Get ctok let tcResolutions = TcAssemblyResolutions.BuildFromPriorResolutions(ctok, tcConfig, nonFrameworkReferences, knownUnresolved) let references = tcResolutions.GetAssemblyResolutions() - let tcImports = new TcImports(tcConfigP, tcResolutions, Some baseTcImports, Some tcGlobals.ilg) + let tcImports = new TcImports(tcConfigP, tcResolutions, Some baseTcImports, Some tcGlobals.ilg, tcConfig.compilationThread) let! _assemblies = tcImports.RegisterAndImportReferencedAssemblies(ctok, references) - tcImports.ReportUnresolvedAssemblyReferences(knownUnresolved) + tcImports.ReportUnresolvedAssemblyReferences knownUnresolved return tcImports } - // Note: This returns a TcImports object. TcImports are disposable - the caller owns the returned TcImports object - // and if hosted in Visual Studio or another long-running process must dispose this object. However this - // function is currently only used from fsi.exe. If we move to a long-running hosted evaluation service API then - // we should start disposing these objects. static member BuildTcImports(ctok, tcConfigP: TcConfigProvider) = cancellable { - let tcConfig = tcConfigP.Get(ctok) - //let foundationalTcImports, tcGlobals = TcImports.BuildFoundationalTcImports(tcConfigP) + let tcConfig = tcConfigP.Get ctok + //let foundationalTcImports, tcGlobals = TcImports.BuildFoundationalTcImports tcConfigP let frameworkDLLs, nonFrameworkReferences, knownUnresolved = TcAssemblyResolutions.SplitNonFoundationalResolutions(ctok, tcConfig) let! tcGlobals, frameworkTcImports = TcImports.BuildFrameworkTcImports (ctok, tcConfigP, frameworkDLLs, nonFrameworkReferences) let! tcImports = TcImports.BuildNonFrameworkTcImports(ctok, tcConfigP, tcGlobals, frameworkTcImports, nonFrameworkReferences, knownUnresolved) @@ -4925,47 +5041,41 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu interface System.IDisposable with member tcImports.Dispose() = - CheckDisposed() - // disposing deliberately only closes this tcImports, not the ones up the chain - disposed <- true - if verbose then - dprintf "disposing of TcImports, %d binaries\n" disposeActions.Length - let actions = disposeActions - disposeActions <- [] - for action in actions do action() + dispose () override tcImports.ToString() = "TcImports(...)" /// Process #r in F# Interactive. /// Adds the reference to the tcImports and add the ccu to the type checking environment. -let RequireDLL (ctok, tcImports: TcImports, tcEnv, thisAssemblyName, m, file) = +let RequireDLL (ctok, tcImports: TcImports, tcEnv, thisAssemblyName, m, file) = let resolutions = CommitOperationResult(tcImports.TryResolveAssemblyReference(ctok, AssemblyReference(m, file, None), ResolveAssemblyReferenceMode.ReportErrors)) let dllinfos, ccuinfos = tcImports.RegisterAndImportReferencedAssemblies(ctok, resolutions) |> Cancellable.runWithoutCancellation - + let asms = ccuinfos |> List.map (function - | ResolvedImportedAssembly(asm) -> asm - | UnresolvedImportedAssembly(assemblyName) -> error(Error(FSComp.SR.buildCouldNotResolveAssemblyRequiredByFile(assemblyName, file), m))) + | ResolvedImportedAssembly asm -> asm + | UnresolvedImportedAssembly assemblyName -> error(Error(FSComp.SR.buildCouldNotResolveAssemblyRequiredByFile(assemblyName, file), m))) let g = tcImports.GetTcGlobals() let amap = tcImports.GetImportMap() - let tcEnv = (tcEnv, asms) ||> List.fold (fun tcEnv asm -> AddCcuToTcEnv(g, amap, m, tcEnv, thisAssemblyName, asm.FSharpViewOfMetadata, asm.AssemblyAutoOpenAttributes, asm.AssemblyInternalsVisibleToAttributes)) + let buildTcEnv tcEnv asm = + AddCcuToTcEnv(g, amap, m, tcEnv, thisAssemblyName, asm.FSharpViewOfMetadata, asm.AssemblyAutoOpenAttributes, asm.AssemblyInternalsVisibleToAttributes) + let tcEnv = (tcEnv, asms) ||> List.fold buildTcEnv tcEnv, (dllinfos, asms) - - -let ProcessMetaCommandsFromInput - (nowarnF: 'state -> range * string -> 'state, - dllRequireF: 'state -> range * string -> 'state, - loadSourceF: 'state -> range * string -> unit) - (tcConfig: TcConfigBuilder, inp, pathOfMetaCommandSource, state0) = - +let ProcessMetaCommandsFromInput + (nowarnF: 'state -> range * string -> 'state, + dllRequireF: 'state -> range * string -> 'state, + packageRequireF: 'state -> IDependencyManagerProvider * range * string -> 'state, + loadSourceF: 'state -> range * string -> unit) + (tcConfig:TcConfigBuilder, inp, pathOfMetaCommandSource, state0) = + use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse let canHaveScriptMetaCommands = match inp with - | ParsedInput.SigFile(_) -> false - | ParsedInput.ImplFile(ParsedImplFileInput(isScript = isScript)) -> isScript + | ParsedInput.SigFile (_) -> false + | ParsedInput.ImplFile (ParsedImplFileInput (isScript = isScript)) -> isScript let ProcessMetaCommand state hash = let mutable matchedm = range0 @@ -4973,30 +5083,58 @@ let ProcessMetaCommandsFromInput match hash with | ParsedHashDirective("I", args, m) -> if not canHaveScriptMetaCommands then - errorR(HashIncludeNotAllowedInNonScript(m)) + errorR(HashIncludeNotAllowedInNonScript m) match args with | [path] -> - matchedm<-m + matchedm <- m tcConfig.AddIncludePath(m, path, pathOfMetaCommandSource) state | _ -> errorR(Error(FSComp.SR.buildInvalidHashIDirective(), m)) state - | ParsedHashDirective("nowarn", numbers, m) -> - List.fold (fun state d -> nowarnF state (m, d)) state numbers - | ParsedHashDirective(("reference" | "r"), args, m) -> - if not canHaveScriptMetaCommands then - errorR(HashReferenceNotAllowedInNonScript(m)) - match args with - | [path] -> - matchedm<-m - dllRequireF state (m, path) - | _ -> + | ParsedHashDirective("nowarn",numbers,m) -> + List.fold (fun state d -> nowarnF state (m,d)) state numbers + + | ParsedHashDirective(("reference" | "r"),args,m) -> + if not canHaveScriptMetaCommands then + errorR(HashReferenceNotAllowedInNonScript m) + + let reportError = + let report errorType err msg = + let error = err, msg + match errorType with + | ErrorReportType.Warning -> warning(Error(error, m)) + | ErrorReportType.Error -> errorR(Error(error, m)) + ResolvingErrorReport (report) + + match args with + | [path] -> + matchedm <- m + let output = tcConfig.outputDir |> Option.defaultValue "" + let dm = tcConfig.dependencyProvider.TryFindDependencyManagerInPath(tcConfig.compilerToolPaths, output , reportError, path) + match dm with + | _, dependencyManager when not(isNull dependencyManager) -> + if tcConfig.langVersion.SupportsFeature(LanguageFeature.PackageManagement) then + packageRequireF state (dependencyManager, m, path) + else + errorR(Error(FSComp.SR.packageManagementRequiresVFive(), m)) + state + + // #r "Assembly" + | path, _ -> + let p = + if String.IsNullOrWhiteSpace(path) then "" + else path + + dllRequireF state (m, p) + + | _ -> errorR(Error(FSComp.SR.buildInvalidHashrDirective(), m)) state + | ParsedHashDirective("load", args, m) -> if not canHaveScriptMetaCommands then - errorR(HashDirectiveNotAllowedInNonScript(m)) + errorR(HashDirectiveNotAllowedInNonScript m) match args with | _ :: _ -> matchedm<-m @@ -5006,7 +5144,7 @@ let ProcessMetaCommandsFromInput state | ParsedHashDirective("time", args, m) -> if not canHaveScriptMetaCommands then - errorR(HashDirectiveNotAllowedInNonScript(m)) + errorR(HashDirectiveNotAllowedInNonScript m) match args with | [] -> () @@ -5055,11 +5193,11 @@ let ProcessMetaCommandsFromInput decls match inp with - | ParsedInput.SigFile(ParsedSigFileInput(_, _, _, hashDirectives, specs)) -> + | ParsedInput.SigFile (ParsedSigFileInput (_, _, _, hashDirectives, specs)) -> let state = List.fold ProcessMetaCommand state0 hashDirectives let state = List.fold ProcessMetaCommandsFromModuleSpec state specs state - | ParsedInput.ImplFile(ParsedImplFileInput(_, _, _, _, hashDirectives, impls, _)) -> + | ParsedInput.ImplFile (ParsedImplFileInput (_, _, _, _, hashDirectives, impls, _)) -> let state = List.fold ProcessMetaCommand state0 hashDirectives let state = List.fold ProcessMetaCommandsFromModuleImpl state impls state @@ -5067,19 +5205,21 @@ let ProcessMetaCommandsFromInput let ApplyNoWarnsToTcConfig (tcConfig: TcConfig, inp: ParsedInput, pathOfMetaCommandSource) = // Clone let tcConfigB = tcConfig.CloneOfOriginalBuilder - let addNoWarn = fun () (m, s) -> tcConfigB.TurnWarningOff(m, s) - let addReferencedAssemblyByPath = fun () (_m, _s) -> () - let addLoadedSource = fun () (_m, _s) -> () - ProcessMetaCommandsFromInput (addNoWarn, addReferencedAssemblyByPath, addLoadedSource) (tcConfigB, inp, pathOfMetaCommandSource, ()) + let addNoWarn = fun () (m,s) -> tcConfigB.TurnWarningOff(m, s) + let addReferencedAssemblyByPath = fun () (_m,_s) -> () + let addDependencyManagerText = fun () (_prefix,_m,_s) -> () + let addLoadedSource = fun () (_m,_s) -> () + ProcessMetaCommandsFromInput (addNoWarn, addReferencedAssemblyByPath, addDependencyManagerText, addLoadedSource) (tcConfigB, inp, pathOfMetaCommandSource, ()) TcConfig.Create(tcConfigB, validate=false) let ApplyMetaCommandsFromInputToTcConfig (tcConfig: TcConfig, inp: ParsedInput, pathOfMetaCommandSource) = // Clone let tcConfigB = tcConfig.CloneOfOriginalBuilder let getWarningNumber = fun () _ -> () - let addReferencedAssemblyByPath = fun () (m, s) -> tcConfigB.AddReferencedAssemblyByPath(m, s) - let addLoadedSource = fun () (m, s) -> tcConfigB.AddLoadedSource(m, s, pathOfMetaCommandSource) - ProcessMetaCommandsFromInput (getWarningNumber, addReferencedAssemblyByPath, addLoadedSource) (tcConfigB, inp, pathOfMetaCommandSource, ()) + let addReferencedAssemblyByPath = fun () (m,s) -> tcConfigB.AddReferencedAssemblyByPath(m,s) + let addDependencyManagerText = fun () (packageManager, m,s) -> tcConfigB.AddDependencyManagerText(packageManager,m,s) + let addLoadedSource = fun () (m,s) -> tcConfigB.AddLoadedSource(m,s,pathOfMetaCommandSource) + ProcessMetaCommandsFromInput (getWarningNumber, addReferencedAssemblyByPath, addDependencyManagerText, addLoadedSource) (tcConfigB, inp, pathOfMetaCommandSource, ()) TcConfig.Create(tcConfigB, validate=false) //---------------------------------------------------------------------------- @@ -5088,10 +5228,10 @@ let ApplyMetaCommandsFromInputToTcConfig (tcConfig: TcConfig, inp: ParsedInput, let GetAssemblyResolutionInformation(ctok, tcConfig: TcConfig) = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parameter - let assemblyList = TcAssemblyResolutions.GetAllDllReferences(tcConfig) + let assemblyList = TcAssemblyResolutions.GetAllDllReferences tcConfig let resolutions = TcAssemblyResolutions.ResolveAssemblyReferences (ctok, tcConfig, assemblyList, []) resolutions.GetAssemblyResolutions(), resolutions.GetUnresolvedReferences() - + #endif //!FABLE_COMPILER #if FABLE_COMPILER @@ -5150,7 +5290,7 @@ type LoadClosure = /// The list of all sources in the closure with inputs when available Inputs: LoadClosureInput list /// The #load, including those that didn't resolve - OriginalLoadReferences: (range * string) list + OriginalLoadReferences: (range * string * string) list /// The #nowarns NoWarns: (string * range list) list /// Diagnostics seen while processing resolutions @@ -5166,31 +5306,31 @@ type CodeContext = | CompilationAndEvaluation // in fsi.exe | Compilation // in fsc.exe | Editing // in VS - + #if !FABLE_COMPILER -module private ScriptPreprocessClosure = +module ScriptPreprocessClosure = open Internal.Utilities.Text.Lexing /// Represents an input to the closure finding process - type ClosureSource = ClosureSource of filename: string * referenceRange: range * sourceText: string * parseRequired: bool + type ClosureSource = ClosureSource of filename: string * referenceRange: range * sourceText: ISourceText * parseRequired: bool /// Represents an output of the closure finding process type ClosureFile = ClosureFile of string * range * ParsedInput option * (PhasedDiagnostic * bool) list * (PhasedDiagnostic * bool) list * (string * range) list // filename, range, errors, warnings, nowarns type Observed() = let seen = System.Collections.Generic.Dictionary<_, bool>() - member ob.SetSeen(check) = - if not(seen.ContainsKey(check)) then + member ob.SetSeen check = + if not(seen.ContainsKey check) then seen.Add(check, true) - member ob.HaveSeen(check) = - seen.ContainsKey(check) + member ob.HaveSeen check = + seen.ContainsKey check /// Parse a script from source. let ParseScriptText - (filename: string, source: string, tcConfig: TcConfig, codeContext, - lexResourceManager: Lexhelp.LexResourceManager, errorLogger: ErrorLogger) = + (filename: string, sourceText: ISourceText, tcConfig: TcConfig, codeContext, + lexResourceManager: Lexhelp.LexResourceManager, errorLogger: ErrorLogger) = // fsc.exe -- COMPILED\!INTERACTIVE // fsi.exe -- !COMPILED\INTERACTIVE @@ -5202,21 +5342,23 @@ module private ScriptPreprocessClosure = | CodeContext.CompilationAndEvaluation -> ["INTERACTIVE"] | CodeContext.Compilation -> ["COMPILED"] | CodeContext.Editing -> "EDITING" :: (if IsScript filename then ["INTERACTIVE"] else ["COMPILED"]) - let lexbuf = UnicodeLexing.StringAsLexbuf source - + + let isFeatureSupported featureId = tcConfig.langVersion.SupportsFeature featureId + let lexbuf = UnicodeLexing.SourceTextAsLexbuf(isFeatureSupported, sourceText) + let isLastCompiland = (IsScript filename), tcConfig.target.IsExe // The root compiland is last in the list of compilands. ParseOneInputLexbuf (tcConfig, lexResourceManager, defines, lexbuf, filename, isLastCompiland, errorLogger) - + /// Create a TcConfig for load closure starting from a single .fsx file let CreateScriptTextTcConfig (legacyReferenceResolver, defaultFSharpBinariesDir, filename: string, codeContext, useSimpleResolution, useFsiAuxLib, basicReferences, applyCommandLineArgs, - assumeDotNetFramework, tryGetMetadataSnapshot, - reduceMemoryUsage) = + assumeDotNetFramework, useSdkRefs, + tryGetMetadataSnapshot, reduceMemoryUsage) = - let projectDir = Path.GetDirectoryName(filename) + let projectDir = Path.GetDirectoryName filename let isInteractive = (codeContext = CodeContext.CompilationAndEvaluation) let isInvalidationSupported = (codeContext = CodeContext.Editing) @@ -5229,7 +5371,7 @@ module private ScriptPreprocessClosure = applyCommandLineArgs tcConfigB match basicReferences with - | None -> BasicReferencesForScriptLoadClosure(useFsiAuxLib, assumeDotNetFramework) |> List.iter(fun f->tcConfigB.AddReferencedAssemblyByPath(range0, f)) // Add script references + | None -> (basicReferencesForScriptLoadClosure useFsiAuxLib useSdkRefs assumeDotNetFramework) |> List.iter(fun f->tcConfigB.AddReferencedAssemblyByPath(range0, f)) // Add script references | Some rs -> for m, r in rs do tcConfigB.AddReferencedAssemblyByPath(m, r) tcConfigB.resolutionEnvironment <- @@ -5239,21 +5381,23 @@ module private ScriptPreprocessClosure = | CodeContext.CompilationAndEvaluation -> ResolutionEnvironment.CompilationAndEvaluation tcConfigB.framework <- false tcConfigB.useSimpleResolution <- useSimpleResolution - // Indicates that there are some references not in BasicReferencesForScriptLoadClosure which should + // Indicates that there are some references not in basicReferencesForScriptLoadClosure which should // be added conditionally once the relevant version of mscorlib.dll has been detected. tcConfigB.implicitlyResolveAssemblies <- false + tcConfigB.useSdkRefs <- useSdkRefs + TcConfig.Create(tcConfigB, validate=true) - + let ClosureSourceOfFilename(filename, m, inputCodePage, parseRequired) = try - let filename = FileSystem.GetFullPathShim(filename) + let filename = FileSystem.GetFullPathShim filename use stream = FileSystem.FileStreamReadShim filename use reader = match inputCodePage with | None -> new StreamReader(stream, true) - | Some (n: int) -> new StreamReader(stream, Encoding.GetEncoding(n)) + | Some (n: int) -> new StreamReader(stream, Encoding.GetEncoding n) let source = reader.ReadToEnd() - [ClosureSource(filename, m, source, parseRequired)] + [ClosureSource(filename, m, SourceText.ofString source, parseRequired)] with e -> errorRecovery e m [] @@ -5262,12 +5406,13 @@ module private ScriptPreprocessClosure = (tcConfig: TcConfig, inp: ParsedInput, pathOfMetaCommandSource) = let tcConfigB = tcConfig.CloneOfOriginalBuilder - let nowarns = ref [] - let getWarningNumber = fun () (m, s) -> nowarns := (s, m) :: !nowarns + let mutable nowarns = [] + let getWarningNumber = fun () (m, s) -> nowarns <- (s, m) :: nowarns let addReferencedAssemblyByPath = fun () (m, s) -> tcConfigB.AddReferencedAssemblyByPath(m, s) + let addDependencyManagerText = fun () (packageManagerPrefix,m,s) -> tcConfigB.AddDependencyManagerText(packageManagerPrefix,m,s) let addLoadedSource = fun () (m, s) -> tcConfigB.AddLoadedSource(m, s, pathOfMetaCommandSource) try - ProcessMetaCommandsFromInput (getWarningNumber, addReferencedAssemblyByPath, addLoadedSource) (tcConfigB, inp, pathOfMetaCommandSource, ()) + ProcessMetaCommandsFromInput (getWarningNumber, addReferencedAssemblyByPath, addDependencyManagerText, addLoadedSource) (tcConfigB, inp, pathOfMetaCommandSource, ()) with ReportedError _ -> // Recover by using whatever did end up in the tcConfig () @@ -5278,60 +5423,108 @@ module private ScriptPreprocessClosure = // Recover by using a default TcConfig. let tcConfigB = tcConfig.CloneOfOriginalBuilder TcConfig.Create(tcConfigB, validate=false), nowarns - - let FindClosureFiles - (closureSources, tcConfig: TcConfig, codeContext, - lexResourceManager: Lexhelp.LexResourceManager) = - let tcConfig = ref tcConfig - + let FindClosureFiles(mainFile, _m, closureSources, origTcConfig:TcConfig, codeContext, lexResourceManager: Lexhelp.LexResourceManager) = + let mutable tcConfig = origTcConfig + let observedSources = Observed() - let rec loop (ClosureSource(filename, m, source, parseRequired)) = - [ if not (observedSources.HaveSeen(filename)) then + let loadScripts = HashSet<_>() + + // Resolve the packages + let rec resolveDependencyManagerSources scriptName = + if not (loadScripts.Contains scriptName) then + [ for kv in tcConfig.packageManagerLines do + let packageManagerKey, packageManagerLines = kv.Key, kv.Value + match packageManagerLines with + | [] -> () + | (_, _, m)::_ -> + let reportError = + let report errorType err msg = + let error = err, msg + match errorType with + | ErrorReportType.Warning -> warning(Error(error, m)) + | ErrorReportType.Error -> errorR(Error(error, m)) + ResolvingErrorReport (report) + + match origTcConfig.packageManagerLines |> Map.tryFind packageManagerKey with + | Some oldDependencyManagerLines when oldDependencyManagerLines = packageManagerLines -> () + | _ -> + let outputDir = tcConfig.outputDir |> Option.defaultValue "" + match tcConfig.dependencyProvider.TryFindDependencyManagerByKey(tcConfig.compilerToolPaths, outputDir, reportError, packageManagerKey) with + | null -> + errorR(Error(tcConfig.dependencyProvider.CreatePackageManagerUnknownError(tcConfig.compilerToolPaths, outputDir, packageManagerKey, reportError), m)) + + | dependencyManager -> + let inline snd3 (_, b, _) = b + let packageManagerTextLines = packageManagerLines |> List.map snd3 + let result = tcConfig.dependencyProvider.Resolve(dependencyManager, ".fsx", packageManagerTextLines, reportError, executionTfm, executionRid, tcConfig.implicitIncludeDir, mainFile, scriptName) + match result.Success with + | true -> + // Resolution produced no errors + if not (Seq.isEmpty result.Roots) then + let tcConfigB = tcConfig.CloneOfOriginalBuilder + for folder in result.Roots do + tcConfigB.AddIncludePath(m, folder, "") + tcConfigB.packageManagerLines <- tcConfigB.packageManagerLines |> Map.map(fun _ l -> l |> List.map(fun (_, p, m) -> true, p, m)) + tcConfig <- TcConfig.Create(tcConfigB, validate=false) + for script in result.SourceFiles do + let scriptText = File.ReadAllText script + loadScripts.Add script |> ignore + let iSourceText = SourceText.ofString scriptText + yield! loop (ClosureSource(script, m, iSourceText, true)) + + | false -> + // Resolution produced errors update packagerManagerLines entries to note these failure + // failed resolutions will no longer be considered + let tcConfigB = tcConfig.CloneOfOriginalBuilder + tcConfigB.packageManagerLines <- tcConfigB.packageManagerLines |> Map.map(fun _ l -> l |> List.filter(fun (tried, _, _) -> tried)) + tcConfig <- TcConfig.Create(tcConfigB, validate=false)] + else [] + + and loop (ClosureSource(filename, m, sourceText, parseRequired)) = + [ if not (observedSources.HaveSeen(filename)) then observedSources.SetSeen(filename) //printfn "visiting %s" filename - if IsScript(filename) || parseRequired then + if IsScript filename || parseRequired then let parseResult, parseDiagnostics = - let errorLogger = CapturingErrorLogger("FindClosureParse") + let errorLogger = CapturingErrorLogger("FindClosureParse") use _unwindEL = PushErrorLoggerPhaseUntilUnwind (fun _ -> errorLogger) - let result = ParseScriptText (filename, source, !tcConfig, codeContext, lexResourceManager, errorLogger) + let result = ParseScriptText (filename, sourceText, tcConfig, codeContext, lexResourceManager, errorLogger) result, errorLogger.Diagnostics match parseResult with - | Some parsedScriptAst -> - let errorLogger = CapturingErrorLogger("FindClosureMetaCommands") + | Some parsedScriptAst -> + let errorLogger = CapturingErrorLogger("FindClosureMetaCommands") use _unwindEL = PushErrorLoggerPhaseUntilUnwind (fun _ -> errorLogger) - let pathOfMetaCommandSource = Path.GetDirectoryName(filename) - let preSources = (!tcConfig).GetAvailableLoadedSources() + let pathOfMetaCommandSource = Path.GetDirectoryName filename + let preSources = tcConfig.GetAvailableLoadedSources() - let tcConfigResult, noWarns = ApplyMetaCommandsFromInputToTcConfigAndGatherNoWarn (!tcConfig, parsedScriptAst, pathOfMetaCommandSource) - tcConfig := tcConfigResult // We accumulate the tcConfig in order to collect assembly references - - let postSources = (!tcConfig).GetAvailableLoadedSources() - let sources = if preSources.Length < postSources.Length then postSources.[preSources.Length..] else [] + let tcConfigResult, noWarns = ApplyMetaCommandsFromInputToTcConfigAndGatherNoWarn (tcConfig, parsedScriptAst, pathOfMetaCommandSource) + tcConfig <- tcConfigResult // We accumulate the tcConfig in order to collect assembly references + + yield! resolveDependencyManagerSources filename - //for (_, subFile) in sources do - // printfn "visiting %s - has subsource of %s " filename subFile + let postSources = tcConfig.GetAvailableLoadedSources() + let sources = if preSources.Length < postSources.Length then postSources.[preSources.Length..] else [] + yield! resolveDependencyManagerSources filename for (m, subFile) in sources do - if IsScript(subFile) then + if IsScript subFile then for subSource in ClosureSourceOfFilename(subFile, m, tcConfigResult.inputCodePage, false) do yield! loop subSource else yield ClosureFile(subFile, m, None, [], [], []) - - //printfn "yielding source %s" filename - yield ClosureFile(filename, m, Some parsedScriptAst, parseDiagnostics, errorLogger.Diagnostics, !noWarns) + yield ClosureFile(filename, m, Some parsedScriptAst, parseDiagnostics, errorLogger.Diagnostics, noWarns) | None -> - //printfn "yielding source %s (failed parse)" filename + printfn "yielding source %s (failed parse)" filename yield ClosureFile(filename, m, None, parseDiagnostics, [], []) else // Don't traverse into .fs leafs. - //printfn "yielding non-script source %s" filename + printfn "yielding non-script source %s" filename yield ClosureFile(filename, m, None, [], [], []) ] - closureSources |> List.collect loop, !tcConfig + closureSources |> List.collect loop, tcConfig /// Reduce the full directive closure into LoadClosure let GetLoadClosure(ctok, rootFilename, closureFiles, tcConfig: TcConfig, codeContext) = @@ -5344,13 +5537,13 @@ module private ScriptPreprocessClosure = match List.frontAndBack closureFiles with | rest, ClosureFile (filename, m, - Some(ParsedInput.ImplFile(ParsedImplFileInput(name, isScript, qualNameOfFile, scopedPragmas, hashDirectives, implFileFlags, _))), + Some(ParsedInput.ImplFile (ParsedImplFileInput (name, isScript, qualNameOfFile, scopedPragmas, hashDirectives, implFileFlags, _))), parseDiagnostics, metaDiagnostics, nowarns) -> let isLastCompiland = (true, tcConfig.target.IsExe) rest @ [ClosureFile (filename, m, - Some(ParsedInput.ImplFile(ParsedImplFileInput(name, isScript, qualNameOfFile, scopedPragmas, hashDirectives, implFileFlags, isLastCompiland))), + Some(ParsedInput.ImplFile (ParsedImplFileInput (name, isScript, qualNameOfFile, scopedPragmas, hashDirectives, implFileFlags, isLastCompiland))), parseDiagnostics, metaDiagnostics, nowarns)] | _ -> closureFiles @@ -5388,15 +5581,15 @@ module private ScriptPreprocessClosure = match GetRangeOfDiagnostic exn with | Some m -> // Return true if the error was *not* from a #load-ed file. - let isArgParameterWhileNotEditing = (codeContext <> CodeContext.Editing) && (m = range0 || m = rangeStartup || m = rangeCmdArgs) + let isArgParameterWhileNotEditing = (codeContext <> CodeContext.Editing) && (Range.equals m range0 || Range.equals m rangeStartup || Range.equals m rangeCmdArgs) let isThisFileName = (0 = String.Compare(rootFilename, m.FileName, StringComparison.OrdinalIgnoreCase)) isArgParameterWhileNotEditing || isThisFileName | None -> true - + // Filter out non-root errors and warnings let allRootDiagnostics = allRootDiagnostics |> List.filter (fst >> isRootRange) - let result: LoadClosure = + let result: LoadClosure = { SourceFiles = List.groupBy fst sourceFiles |> List.map (map2Of2 (List.map snd)) References = List.groupBy fst references |> List.map (map2Of2 (List.map snd)) UnresolvedReferences = unresolvedReferences @@ -5405,18 +5598,18 @@ module private ScriptPreprocessClosure = OriginalLoadReferences = tcConfig.loadedSources ResolutionDiagnostics = resolutionDiagnostics AllRootFileDiagnostics = allRootDiagnostics - LoadClosureRootFileDiagnostics = loadClosureRootDiagnostics } + LoadClosureRootFileDiagnostics = loadClosureRootDiagnostics } result /// Given source text, find the full load closure. Used from service.fs, when editing a script file let GetFullClosureOfScriptText (ctok, legacyReferenceResolver, defaultFSharpBinariesDir, - filename, source, - codeContext, useSimpleResolution, useFsiAuxLib, + filename, sourceText, codeContext, + useSimpleResolution, useFsiAuxLib, useSdkRefs, lexResourceManager: Lexhelp.LexResourceManager, - applyCommmandLineArgs, assumeDotNetFramework, - tryGetMetadataSnapshot, reduceMemoryUsage) = + applyCommandLineArgs, assumeDotNetFramework, + tryGetMetadataSnapshot, reduceMemoryUsage) = // Resolve the basic references such as FSharp.Core.dll first, before processing any #I directives in the script // @@ -5426,8 +5619,8 @@ module private ScriptPreprocessClosure = let tcConfig = CreateScriptTextTcConfig(legacyReferenceResolver, defaultFSharpBinariesDir, filename, codeContext, useSimpleResolution, - useFsiAuxLib, None, applyCommmandLineArgs, assumeDotNetFramework, - tryGetMetadataSnapshot, reduceMemoryUsage) + useFsiAuxLib, None, applyCommandLineArgs, assumeDotNetFramework, + useSdkRefs, tryGetMetadataSnapshot, reduceMemoryUsage) let resolutions0, _unresolvedReferences = GetAssemblyResolutionInformation(ctok, tcConfig) let references0 = resolutions0 |> List.map (fun r->r.originalReference.Range, r.resolvedPath) |> Seq.distinct |> List.ofSeq @@ -5436,48 +5629,46 @@ module private ScriptPreprocessClosure = let tcConfig = CreateScriptTextTcConfig(legacyReferenceResolver, defaultFSharpBinariesDir, filename, codeContext, useSimpleResolution, useFsiAuxLib, Some references0, - applyCommmandLineArgs, assumeDotNetFramework, tryGetMetadataSnapshot, reduceMemoryUsage) + applyCommandLineArgs, assumeDotNetFramework, useSdkRefs, + tryGetMetadataSnapshot, reduceMemoryUsage) - let closureSources = [ClosureSource(filename, range0, source, true)] - let closureFiles, tcConfig = FindClosureFiles(closureSources, tcConfig, codeContext, lexResourceManager) + let closureSources = [ClosureSource(filename, range0, sourceText, true)] + let closureFiles, tcConfig = FindClosureFiles(filename, range0, closureSources, tcConfig, codeContext, lexResourceManager) GetLoadClosure(ctok, filename, closureFiles, tcConfig, codeContext) - + /// Given source filename, find the full load closure /// Used from fsi.fs and fsc.fs, for #load and command line - let GetFullClosureOfScriptFiles - (ctok, tcConfig: TcConfig, - files:(string*range) list, - codeContext, - lexResourceManager: Lexhelp.LexResourceManager) = - - let mainFile = fst (List.last files) - let closureSources = files |> List.collect (fun (filename, m) -> ClosureSourceOfFilename(filename, m, tcConfig.inputCodePage, true)) - let closureFiles, tcConfig = FindClosureFiles(closureSources, tcConfig, codeContext, lexResourceManager) + let GetFullClosureOfScriptFiles(ctok, tcConfig:TcConfig, files:(string*range) list,codeContext,lexResourceManager: Lexhelp.LexResourceManager) = + let mainFile, mainFileRange = List.last files + let closureSources = files |> List.collect (fun (filename, m) -> ClosureSourceOfFilename(filename, m,tcConfig.inputCodePage,true)) + let closureFiles,tcConfig = FindClosureFiles(mainFile, mainFileRange, closureSources, tcConfig, codeContext, lexResourceManager) GetLoadClosure(ctok, mainFile, closureFiles, tcConfig, codeContext) type LoadClosure with /// Analyze a script text and find the closure of its references. + /// Used from FCS, when editing a script file. + // + /// A temporary TcConfig is created along the way, is why this routine takes so many arguments. We want to be sure to use exactly the + /// same arguments as the rest of the application. static member ComputeClosureOfScriptText (ctok, legacyReferenceResolver, defaultFSharpBinariesDir, - filename: string, source: string, codeContext, useSimpleResolution: bool, - useFsiAuxLib, lexResourceManager: Lexhelp.LexResourceManager, - applyCommmandLineArgs, assumeDotNetFramework, tryGetMetadataSnapshot, reduceMemoryUsage) = + filename: string, sourceText: ISourceText, codeContext, useSimpleResolution: bool, + useFsiAuxLib, useSdkRefs, lexResourceManager: Lexhelp.LexResourceManager, + applyCommandLineArgs, assumeDotNetFramework, tryGetMetadataSnapshot, reduceMemoryUsage) = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse ScriptPreprocessClosure.GetFullClosureOfScriptText - (ctok, legacyReferenceResolver, defaultFSharpBinariesDir, filename, source, - codeContext, useSimpleResolution, useFsiAuxLib, lexResourceManager, - applyCommmandLineArgs, assumeDotNetFramework, tryGetMetadataSnapshot, reduceMemoryUsage) + (ctok, legacyReferenceResolver, defaultFSharpBinariesDir, filename, sourceText, + codeContext, useSimpleResolution, useFsiAuxLib, useSdkRefs, lexResourceManager, + applyCommandLineArgs, assumeDotNetFramework, tryGetMetadataSnapshot, reduceMemoryUsage) /// Analyze a set of script files and find the closure of their references. - static member ComputeClosureOfScriptFiles - (ctok, tcConfig: TcConfig, files:(string*range) list, codeContext, - lexResourceManager: Lexhelp.LexResourceManager) = - + static member ComputeClosureOfScriptFiles + (ctok, tcConfig: TcConfig, files:(string*range) list, codeContext, + lexResourceManager: Lexhelp.LexResourceManager) = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse ScriptPreprocessClosure.GetFullClosureOfScriptFiles (ctok, tcConfig, files, codeContext, lexResourceManager) - - + #endif //!FABLE_COMPILER //---------------------------------------------------------------------------- @@ -5513,11 +5704,8 @@ let CheckSimulateException(tcConfig: TcConfig) = | Some("tc-oom") -> raise(System.OutOfMemoryException()) | Some("tc-an") -> raise(System.ArgumentNullException("simulated")) | Some("tc-invop") -> raise(System.InvalidOperationException()) -#if FX_REDUCED_EXCEPTIONS -#else | Some("tc-av") -> raise(System.AccessViolationException()) | Some("tc-nfn") -> raise(System.NotFiniteNumberException()) -#endif | Some("tc-aor") -> raise(System.ArgumentOutOfRangeException()) | Some("tc-dv0") -> raise(System.DivideByZeroException()) | Some("tc-oe") -> raise(System.OverflowException()) @@ -5546,7 +5734,8 @@ type RootImpls = Zset let qnameOrder = Order.orderBy (fun (q: QualifiedNameOfFile) -> q.Text) type TcState = - { tcsCcu: CcuThunk + { + tcsCcu: CcuThunk tcsCcuType: ModuleOrNamespace tcsNiceNameGen: NiceNameGenerator tcsTcSigEnv: TcEnv @@ -5554,7 +5743,8 @@ type TcState = tcsCreatesGeneratedProvidedTypes: bool tcsRootSigs: RootSigs tcsRootImpls: RootImpls - tcsCcuSig: ModuleOrNamespaceType } + tcsCcuSig: ModuleOrNamespaceType + } member x.NiceNameGenerator = x.tcsNiceNameGen @@ -5572,7 +5762,7 @@ type TcState = // a.fsi + b.fsi + c.fsi (after checking implementation file for c.fs) member x.CcuSig = x.tcsCcuSig - member x.NextStateAfterIncrementalFragment(tcEnvAtEndOfLastInput) = + member x.NextStateAfterIncrementalFragment tcEnvAtEndOfLastInput = { x with tcsTcSigEnv = tcEnvAtEndOfLastInput tcsTcImplEnv = tcEnvAtEndOfLastInput } @@ -5582,7 +5772,7 @@ let GetInitialTcState(m, ccuName, tcConfig: TcConfig, tcGlobals, tcImports: TcIm ignore tcImports // Create a ccu to hold all the results of compilation - let ccuType = NewCcuContents ILScopeRef.Local m ccuName (NewEmptyModuleOrNamespaceType Namespace) + let ccuContents = Construct.NewCcuContents ILScopeRef.Local m ccuName (Construct.NewEmptyModuleOrNamespaceType Namespace) let ccuData: CcuData = { IsFSharp=true @@ -5598,27 +5788,25 @@ let GetInitialTcState(m, ccuName, tcConfig: TcConfig, tcGlobals, tcImports: TcIm QualifiedName= None SourceCodeDirectory = tcConfig.implicitIncludeDir ILScopeRef=ILScopeRef.Local - Contents=ccuType - MemberSignatureEquality= (Tastops.typeEquivAux EraseAll tcGlobals) + Contents=ccuContents + MemberSignatureEquality= typeEquivAux EraseAll tcGlobals TypeForwarders=Map.empty } let ccu = CcuThunk.Create(ccuName, ccuData) // OK, is this is the FSharp.Core CCU then fix it up. if tcConfig.compilingFslib then - tcGlobals.fslibCcu.Fixup(ccu) + tcGlobals.fslibCcu.Fixup ccu { tcsCcu= ccu - tcsCcuType=ccuType + tcsCcuType=ccuContents tcsNiceNameGen=niceNameGen tcsTcSigEnv=tcEnv0 tcsTcImplEnv=tcEnv0 tcsCreatesGeneratedProvidedTypes=false tcsRootSigs = Zmap.empty qnameOrder tcsRootImpls = Zset.empty qnameOrder - tcsCcuSig = NewEmptyModuleOrNamespaceType Namespace } - - + tcsCcuSig = Construct.NewEmptyModuleOrNamespaceType Namespace } /// Typecheck a single file (or interactive entry into F# Interactive) let TypeCheckOneInputEventually (checkForErrors, tcConfig: TcConfig, tcImports: TcImports, tcGlobals, prefixPathOpt, tcSink, tcState: TcState, inp: ParsedInput) = @@ -5629,13 +5817,13 @@ let TypeCheckOneInputEventually (checkForErrors, tcConfig: TcConfig, tcImports: RequireCompilationThread ctok // Everything here requires the compilation thread since it works on the TAST #if !FABLE_COMPILER - CheckSimulateException(tcConfig) + CheckSimulateException tcConfig #endif let m = inp.Range let amap = tcImports.GetImportMap() match inp with - | ParsedInput.SigFile (ParsedSigFileInput(_, qualNameOfFile, _, _, _) as file) -> + | ParsedInput.SigFile (ParsedSigFileInput (_, qualNameOfFile, _, _, _) as file) -> // Check if we've seen this top module signature before. if Zmap.mem qualNameOfFile tcState.tcsRootSigs then @@ -5674,10 +5862,10 @@ let TypeCheckOneInputEventually (checkForErrors, tcConfig: TcConfig, tcImports: return (tcEnv, EmptyTopAttrs, None, ccuSigForFile), tcState - | ParsedInput.ImplFile (ParsedImplFileInput(_, _, qualNameOfFile, _, _, _, _) as file) -> + | ParsedInput.ImplFile (ParsedImplFileInput (_, _, qualNameOfFile, _, _, _, _) as file) -> // Check if we've got an interface for this fragment - let rootSigOpt = tcState.tcsRootSigs.TryFind(qualNameOfFile) + let rootSigOpt = tcState.tcsRootSigs.TryFind qualNameOfFile // Check if we've already seen an implementation for this fragment if Zset.contains qualNameOfFile tcState.tcsRootImpls then @@ -5741,7 +5929,7 @@ let TypeCheckOneInputEventually (checkForErrors, tcConfig: TcConfig, tcImports: /// Typecheck a single file (or interactive entry into F# Interactive) let TypeCheckOneInput (ctok, checkForErrors, tcConfig, tcImports, tcGlobals, prefixPathOpt) tcState inp = // 'use' ensures that the warning handler is restored at the end - use unwindEL = PushErrorLoggerPhaseUntilUnwind(fun oldLogger -> GetErrorLoggerFilteringByScopedPragmas(false, GetScopedPragmasForInput(inp), oldLogger) ) + use unwindEL = PushErrorLoggerPhaseUntilUnwind(fun oldLogger -> GetErrorLoggerFilteringByScopedPragmas(false, GetScopedPragmasForInput inp, oldLogger) ) use unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.TypeCheck TypeCheckOneInputEventually (checkForErrors, tcConfig, tcImports, tcGlobals, prefixPathOpt, TcResultsSink.NoSink, tcState, inp) |> Eventually.force ctok @@ -5766,7 +5954,7 @@ let TypeCheckOneInputAndFinishEventually(checkForErrors, tcConfig: TcConfig, tcI let TypeCheckClosedInputSetFinish (declaredImpls: TypedImplFile list, tcState) = // Publish the latest contents to the CCU - tcState.tcsCcu.Deref.Contents <- NewCcuContents ILScopeRef.Local range0 tcState.tcsCcu.AssemblyName tcState.tcsCcuSig + tcState.tcsCcu.Deref.Contents <- Construct.NewCcuContents ILScopeRef.Local range0 tcState.tcsCcu.AssemblyName tcState.tcsCcuSig // Check all interfaces have implementations tcState.tcsRootSigs |> Zmap.iter (fun qualNameOfFile _ -> @@ -5781,3 +5969,9 @@ let TypeCheckClosedInputSet (ctok, checkForErrors, tcConfig, tcImports, tcGlobal let (tcEnvAtEndOfLastFile, topAttrs, implFiles, _), tcState = TypeCheckMultipleInputsFinish(results, tcState) let tcState, declaredImpls = TypeCheckClosedInputSetFinish (implFiles, tcState) tcState, topAttrs, declaredImpls, tcEnvAtEndOfLastFile + +#if !FABLE_COMPILER +// Existing public APIs delegate to newer implementations +let GetFSharpCoreLibraryName () = getFSharpCoreLibraryName +let DefaultReferencesForScriptsAndOutOfProjectSources assumeDotNetFramework = defaultReferencesForScriptsAndOutOfProjectSources (*useFsiAuxLib*)false assumeDotNetFramework (*useSdkRefs*)false +#endif diff --git a/src/fcs-fable/src/fsharp/CompileOps.fsi b/src/fcs-fable/src/fsharp/CompileOps.fsi old mode 100755 new mode 100644 index 03e92d1b1f..981d601faa --- a/src/fcs-fable/src/fsharp/CompileOps.fsi +++ b/src/fcs-fable/src/fsharp/CompileOps.fsi @@ -6,22 +6,37 @@ module internal FSharp.Compiler.CompileOps open System open System.Text open System.Collections.Generic + +open Internal.Utilities + +open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.ILBinaryReader -open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler -open FSharp.Compiler.TypeChecker -open FSharp.Compiler.Range -open FSharp.Compiler.Ast +#if !FABLE_COMPILER +open FSharp.Compiler.AbstractIL.ILPdbWriter +#endif +open FSharp.Compiler.AbstractIL.Internal +open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Tast +open FSharp.Compiler.Features +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TypeChecker +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals -open Microsoft.FSharp.Core.CompilerServices +open FSharp.Compiler.Text +open FSharp.Core.CompilerServices + #if !NO_EXTENSIONTYPING open FSharp.Compiler.ExtensionTyping #endif +#if !FABLE_COMPILER +open Microsoft.Interactive.DependencyManager +#endif #if DEBUG @@ -49,24 +64,26 @@ val FSharpLightSyntaxFileSuffixes: string list /// Get the name used for FSharp.Core +#if !FABLE_COMPILER val GetFSharpCoreLibraryName: unit -> string +#endif //---------------------------------------------------------------------------- // Parsing inputs //-------------------------------------------------------------------------- -val ComputeQualifiedNameOfFileFromUniquePath: range * string list -> Ast.QualifiedNameOfFile +val ComputeQualifiedNameOfFileFromUniquePath: range * string list -> QualifiedNameOfFile -val PrependPathToInput: Ast.Ident list -> Ast.ParsedInput -> Ast.ParsedInput +val PrependPathToInput: Ident list -> ParsedInput -> ParsedInput -/// State used to de-deuplicate module names along a list of file names +/// State used to de-deduplicate module names along a list of file names type ModuleNamesDict = Map> /// Checks if a ParsedInput is using a module name that was already given and deduplicates the name if needed. -val DeduplicateParsedInputModuleName: ModuleNamesDict -> Ast.ParsedInput -> Ast.ParsedInput * ModuleNamesDict +val DeduplicateParsedInputModuleName: ModuleNamesDict -> ParsedInput -> ParsedInput * ModuleNamesDict /// Parse a single input (A signature file or implementation file) -val ParseInput: (UnicodeLexing.Lexbuf -> Parser.token) * ErrorLogger * UnicodeLexing.Lexbuf * string option * string * isLastCompiland:(bool * bool) -> Ast.ParsedInput +val ParseInput: (UnicodeLexing.Lexbuf -> Parser.token) * ErrorLogger * UnicodeLexing.Lexbuf * string option * string * isLastCompiland:(bool * bool) -> ParsedInput //---------------------------------------------------------------------------- // Error and warnings @@ -82,7 +99,7 @@ val GetDiagnosticNumber: PhasedDiagnostic -> int val SplitRelatedDiagnostics: PhasedDiagnostic -> PhasedDiagnostic * PhasedDiagnostic list /// Output an error to a buffer -val OutputPhasedDiagnostic: StringBuilder -> PhasedDiagnostic -> flattenErrors: bool -> unit +val OutputPhasedDiagnostic: StringBuilder -> PhasedDiagnostic -> flattenErrors: bool -> suggestNames: bool -> unit #if !FABLE_COMPILER @@ -121,7 +138,7 @@ type Diagnostic = | Long of bool * DiagnosticDetailedInfo /// Part of LegacyHostedCompilerForTesting -val CollectDiagnostic: implicitIncludeDir:string * showFullPaths: bool * flattenErrors: bool * errorStyle: ErrorStyle * warning:bool * PhasedDiagnostic -> seq +val CollectDiagnostic: implicitIncludeDir:string * showFullPaths: bool * flattenErrors: bool * errorStyle: ErrorStyle * warning:bool * PhasedDiagnostic * suggestNames: bool -> seq #endif //!FABLE_COMPILER @@ -154,9 +171,9 @@ type IRawFSharpAssemblyData = abstract HasAnyFSharpSignatureDataAttribute: bool abstract HasMatchingFSharpSignatureDataAttribute: ILGlobals -> bool /// The raw F# signature data in the assembly, if any - abstract GetRawFSharpSignatureData: range * ilShortAssemName: string * fileName: string -> (string * (unit -> byte[])) list + abstract GetRawFSharpSignatureData: range * ilShortAssemName: string * fileName: string -> (string * (unit -> ReadOnlyByteMemory)) list /// The raw F# optimization data in the assembly, if any - abstract GetRawFSharpOptimizationData: range * ilShortAssemName: string * fileName: string -> (string * (unit -> byte[])) list + abstract GetRawFSharpOptimizationData: range * ilShortAssemName: string * fileName: string -> (string * (unit -> ReadOnlyByteMemory)) list /// The table of type forwarders in the assembly abstract GetRawTypeForwarders: unit -> ILExportedTypesAndForwarders /// The identity of the module @@ -203,7 +220,7 @@ type AssemblyResolution = /// Whether or not this is an installed system assembly (for example, System.dll) sysdir: bool // Lazily populated ilAssemblyRef for this reference. - ilAssemblyRef: ILAssemblyRef option ref } + mutable ilAssemblyRef: ILAssemblyRef option } type UnresolvedAssemblyReference = UnresolvedAssemblyReference of string * AssemblyReference list @@ -211,6 +228,14 @@ type UnresolvedAssemblyReference = UnresolvedAssemblyReference of string * Assem type ResolvedExtensionReference = ResolvedExtensionReference of string * AssemblyReference list * Tainted list #endif +/// The thread in which compilation calls will be enqueued and done work on. +/// Note: This is currently only used when disposing of type providers and will be extended to all the other type provider calls when compilations can be done in parallel. +/// Right now all calls in FCS to type providers are single-threaded through use of the reactor thread. +type ICompilationThread = + + /// Enqueue work to be done on a compilation thread. + abstract EnqueueWork: (CompilationThreadToken -> unit) -> unit + [] type CompilerTarget = | WinExe @@ -242,16 +267,12 @@ type VersionFlag = [] type TcConfigBuilder = { mutable primaryAssembly: PrimaryAssembly - mutable autoResolveOpenDirectivesToDlls: bool mutable noFeedback: bool mutable stackReserveSize: int32 option mutable implicitIncludeDir: string mutable openDebugInformationForLaterStaticLinking: bool defaultFSharpBinariesDir: string mutable compilingFslib: bool - mutable compilingFslib20: string option - mutable compilingFslib40: bool - mutable compilingFslibNoBigInt: bool mutable useIncrementalBuilder: bool mutable includes: string list mutable implicitOpens: string list @@ -263,9 +284,11 @@ type TcConfigBuilder = mutable light: bool option mutable conditionalCompilationDefines: string list /// Sources added into the build with #load - mutable loadedSources: (range * string) list - + mutable loadedSources: (range * string * string) list + mutable compilerToolPaths: string list mutable referencedDLLs: AssemblyReference list + mutable packageManagerLines: Map + mutable projectReferences: IProjectReference list mutable knownUnresolvedReferences: UnresolvedAssemblyReference list reduceMemoryUsage: ReduceMemoryFlag @@ -277,6 +300,7 @@ type TcConfigBuilder = mutable mlCompatibility:bool mutable checkOverflow:bool mutable showReferenceResolutions:bool + mutable outputDir: string option mutable outputFile: string option mutable platform: ILPlatform option mutable prefer32Bit: bool @@ -331,7 +355,10 @@ type TcConfigBuilder = mutable maxErrors: int mutable abortOnError: bool mutable baseAddress: int32 option - #if DEBUG +#if !FABLE_COMPILER + mutable checksumAlgorithm: HashAlgorithm +#endif +#if DEBUG mutable showOptimizationData: bool #endif mutable showTerms : bool @@ -353,6 +380,7 @@ type TcConfigBuilder = #if !NO_EXTENSIONTYPING mutable showExtensionTypeMessages: bool #endif + mutable compilationThread: ICompilationThread mutable pause: bool mutable alwaysCallVirt: bool mutable noDebugData: bool @@ -364,6 +392,7 @@ type TcConfigBuilder = mutable exename: string option mutable copyFSharpCore: CopyFSharpCoreFlag mutable shadowCopyReferences: bool + mutable useSdkRefs: bool /// A function to call to try to get an object that acts as a snapshot of the metadata section of a .NET binary, /// and from which we can read the metadata. Only used when metadataOnly=true. @@ -374,6 +403,15 @@ type TcConfigBuilder = /// Prevent erasure of conditional attributes and methods so tooling is able analyse them. mutable noConditionalErasure: bool + + mutable pathMap : PathMap + + mutable langVersion : LanguageVersion + +#if !FABLE_COMPILER + mutable dependencyProvider : DependencyProvider +#endif + } static member Initial: TcConfigBuilder @@ -386,7 +424,7 @@ type TcConfigBuilder = isInteractive: bool * isInvalidationSupported: bool * defaultCopyFSharpCore: CopyFSharpCoreFlag * - tryGetMetadataSnapshot: ILReaderTryGetMetadataSnapshot + tryGetMetadataSnapshot: ILReaderTryGetMetadataSnapshot -> TcConfigBuilder #if !FABLE_COMPILER @@ -395,29 +433,25 @@ type TcConfigBuilder = member TurnWarningOff: range * string -> unit member TurnWarningOn: range * string -> unit member AddIncludePath: range * string * string -> unit + member AddCompilerToolsByPath: string -> unit member AddReferencedAssemblyByPath: range * string -> unit member RemoveReferencedAssemblyByPath: range * string -> unit member AddEmbeddedSourceFile: string -> unit member AddEmbeddedResource: string -> unit - - static member SplitCommandLineResourceInfo: string -> string * string * ILResourceAccess + member AddPathMapping: oldPrefix: string * newPrefix: string -> unit + static member SplitCommandLineResourceInfo: string -> string * string * ILResourceAccess - [] // Immutable TcConfig type TcConfig = member primaryAssembly: PrimaryAssembly - member autoResolveOpenDirectivesToDlls: bool member noFeedback: bool member stackReserveSize: int32 option member implicitIncludeDir: string member openDebugInformationForLaterStaticLinking: bool member fsharpBinariesDir: string member compilingFslib: bool - member compilingFslib20: string option - member compilingFslib40: bool - member compilingFslibNoBigInt: bool member useIncrementalBuilder: bool member includes: string list member implicitOpens: string list @@ -429,6 +463,7 @@ type TcConfig = member conditionalCompilationDefines: string list member subsystemVersion: int * int member useHighEntropyVA: bool + member compilerToolPaths: string list member referencedDLLs: AssemblyReference list member reduceMemoryUsage: ReduceMemoryFlag member inputCodePage: int option @@ -437,6 +472,7 @@ type TcConfig = member mlCompatibility:bool member checkOverflow:bool member showReferenceResolutions:bool + member outputDir: string option member outputFile: string option member platform: ILPlatform option member prefer32Bit: bool @@ -490,6 +526,9 @@ type TcConfig = member maxErrors: int member baseAddress: int32 option +#if !FABLE_COMPILER + member checksumAlgorithm: HashAlgorithm +#endif #if DEBUG member showOptimizationData: bool #endif @@ -501,6 +540,7 @@ type TcConfig = member optSettings : Optimizer.OptimizationSettings member emitTailcalls: bool member deterministic: bool + member pathMap: PathMap member preferredUiLang: string option member optsOn : bool member productNameForBannerText: string @@ -511,6 +551,7 @@ type TcConfig = #if !NO_EXTENSIONTYPING member showExtensionTypeMessages: bool #endif + member compilationThread: ICompilationThread member pause: bool member alwaysCallVirt: bool member noDebugData: bool @@ -540,6 +581,9 @@ type TcConfig = member emitDebugInfoInQuotations: bool member copyFSharpCore: CopyFSharpCoreFlag member shadowCopyReferences: bool + member useSdkRefs: bool + member langVersion: LanguageVersion + static member Create: TcConfigBuilder * validate: bool -> TcConfig #if !FABLE_COMPILER @@ -612,6 +656,8 @@ type TcAssemblyResolutions = static member BuildFromPriorResolutions : CompilationThreadToken * TcConfig * AssemblyResolution list * UnresolvedAssemblyReference list -> TcAssemblyResolutions /// Represents a table of imported assemblies with their resolutions. +/// Is a disposable object, but it is recommended not to explicitly call Dispose unless you absolutely know nothing will be using its contents after the disposal. +/// Otherwise, simply allow the GC to collect this and it will properly call Dispose from the finalizer. [] type TcImports = interface System.IDisposable @@ -674,7 +720,7 @@ val GetOptimizationDataResourceName: ILResource -> string #if !FABLE_COMPILER /// Write F# signature data as an IL resource -val WriteSignatureData: TcConfig * TcGlobals * Tastops.Remap * CcuThunk * filename: string * inMem: bool -> ILResource +val WriteSignatureData: TcConfig * TcGlobals * Remap * CcuThunk * filename: string * inMem: bool -> ILResource /// Write F# optimization data as an IL resource val WriteOptimizationData: TcGlobals * filename: string * inMem: bool * CcuThunk * Optimizer.LazyModuleInfo -> ILResource @@ -692,16 +738,16 @@ val WriteOptimizationData: TcGlobals * filename: string * inMem: bool * CcuThunk val RequireDLL: CompilationThreadToken * TcImports * TcEnv * thisAssemblyName: string * referenceRange: range * file: string -> TcEnv * (ImportedBinary list * ImportedAssembly list) /// Processing # commands -val ProcessMetaCommandsFromInput: - (('T -> range * string -> 'T) * ('T -> range * string -> 'T) * ('T -> range * string -> unit)) - -> TcConfigBuilder * Ast.ParsedInput * string * 'T +val ProcessMetaCommandsFromInput : + (('T -> range * string -> 'T) * ('T -> range * string -> 'T) * ('T -> IDependencyManagerProvider * range * string -> 'T) * ('T -> range * string -> unit)) + -> TcConfigBuilder * ParsedInput * string * 'T -> 'T /// Process all the #r, #I etc. in an input -val ApplyMetaCommandsFromInputToTcConfig: TcConfig * Ast.ParsedInput * string -> TcConfig +val ApplyMetaCommandsFromInputToTcConfig: TcConfig * ParsedInput * string -> TcConfig /// Process the #nowarn in an input -val ApplyNoWarnsToTcConfig: TcConfig * Ast.ParsedInput * string -> TcConfig +val ApplyNoWarnsToTcConfig: TcConfig * ParsedInput * string -> TcConfig #endif //!FABLE_COMPILER @@ -710,7 +756,7 @@ val ApplyNoWarnsToTcConfig: TcConfig * Ast.ParsedInput * string -> TcConfig //-------------------------------------------------------------------------- /// Find the scoped #nowarn pragmas with their range information -val GetScopedPragmasForInput: Ast.ParsedInput -> ScopedPragma list +val GetScopedPragmasForInput: ParsedInput -> ScopedPragma list /// Get an error logger that filters the reporting of warnings based on scoped pragma information val GetErrorLoggerFilteringByScopedPragmas: checkFile:bool * ScopedPragma list * ErrorLogger -> ErrorLogger @@ -741,7 +787,7 @@ val GetInitialTcEnv: assemblyName: string * range * TcConfig * TcImports * TcGlo [] /// Represents the incremental type checking state for a set of inputs type TcState = - member NiceNameGenerator: Ast.NiceNameGenerator + member NiceNameGenerator: NiceNameGenerator /// The CcuThunk for the current assembly being checked member Ccu: CcuThunk @@ -762,11 +808,11 @@ type TcState = /// Get the initial type checking state for a set of inputs val GetInitialTcState: - range * string * TcConfig * TcGlobals * TcImports * Ast.NiceNameGenerator * TcEnv -> TcState + range * string * TcConfig * TcGlobals * TcImports * NiceNameGenerator * TcEnv -> TcState /// Check one input, returned as an Eventually computation val TypeCheckOneInputEventually : - checkForErrors:(unit -> bool) * TcConfig * TcImports * TcGlobals * Ast.LongIdent option * NameResolution.TcResultsSink * TcState * Ast.ParsedInput + checkForErrors:(unit -> bool) * TcConfig * TcImports * TcGlobals * LongIdent option * NameResolution.TcResultsSink * TcState * ParsedInput -> Eventually<(TcEnv * TopAttribs * TypedImplFile option * ModuleOrNamespaceType) * TcState> /// Finish the checking of multiple inputs @@ -776,11 +822,11 @@ val TypeCheckMultipleInputsFinish: (TcEnv * TopAttribs * 'T option * 'U) list * val TypeCheckClosedInputSetFinish: TypedImplFile list * TcState -> TcState * TypedImplFile list /// Check a closed set of inputs -val TypeCheckClosedInputSet: CompilationThreadToken * checkForErrors: (unit -> bool) * TcConfig * TcImports * TcGlobals * Ast.LongIdent option * TcState * Ast.ParsedInput list -> TcState * TopAttribs * TypedImplFile list * TcEnv +val TypeCheckClosedInputSet: CompilationThreadToken * checkForErrors: (unit -> bool) * TcConfig * TcImports * TcGlobals * LongIdent option * TcState * ParsedInput list -> TcState * TopAttribs * TypedImplFile list * TcEnv /// Check a single input and finish the checking val TypeCheckOneInputAndFinishEventually : - checkForErrors: (unit -> bool) * TcConfig * TcImports * TcGlobals * Ast.LongIdent option * NameResolution.TcResultsSink * TcState * Ast.ParsedInput + checkForErrors: (unit -> bool) * TcConfig * TcImports * TcGlobals * LongIdent option * NameResolution.TcResultsSink * TcState * ParsedInput -> Eventually<(TcEnv * TopAttribs * TypedImplFile list * ModuleOrNamespaceType list) * TcState> /// Indicates if we should report a warning @@ -821,7 +867,7 @@ type LoadClosure = Inputs: LoadClosureInput list /// The original #load references, including those that didn't resolve - OriginalLoadReferences: (range * string) list + OriginalLoadReferences: (range * string * string) list /// The #nowarns NoWarns: (string * range list) list @@ -841,7 +887,7 @@ type LoadClosure = // /// A temporary TcConfig is created along the way, is why this routine takes so many arguments. We want to be sure to use exactly the /// same arguments as the rest of the application. - static member ComputeClosureOfScriptText: CompilationThreadToken * legacyReferenceResolver: ReferenceResolver.Resolver * defaultFSharpBinariesDir: string * filename: string * source: string * implicitDefines:CodeContext * useSimpleResolution: bool * useFsiAuxLib: bool * lexResourceManager: Lexhelp.LexResourceManager * applyCompilerOptions: (TcConfigBuilder -> unit) * assumeDotNetFramework: bool * tryGetMetadataSnapshot: ILReaderTryGetMetadataSnapshot * reduceMemoryUsage: ReduceMemoryFlag -> LoadClosure + static member ComputeClosureOfScriptText: CompilationThreadToken * legacyReferenceResolver: ReferenceResolver.Resolver * defaultFSharpBinariesDir: string * filename: string * sourceText: ISourceText * implicitDefines:CodeContext * useSimpleResolution: bool * useFsiAuxLib: bool * useSdkRefs: bool * lexResourceManager: Lexhelp.LexResourceManager * applyCompilerOptions: (TcConfigBuilder -> unit) * assumeDotNetFramework: bool * tryGetMetadataSnapshot: ILReaderTryGetMetadataSnapshot * reduceMemoryUsage: ReduceMemoryFlag -> LoadClosure /// Analyze a set of script files and find the closure of their references. The resulting references are then added to the given TcConfig. /// Used from fsi.fs and fsc.fs, for #load and command line. diff --git a/src/fcs-fable/src/fsharp/CompileOptions.fs b/src/fcs-fable/src/fsharp/CompileOptions.fs old mode 100755 new mode 100644 index db87184d21..de818f71f0 --- a/src/fcs-fable/src/fsharp/CompileOptions.fs +++ b/src/fcs-fable/src/fsharp/CompileOptions.fs @@ -6,20 +6,26 @@ module internal FSharp.Compiler.CompileOptions open Internal.Utilities open System +open System.IO open FSharp.Compiler -open FSharp.Compiler.AbstractIL +open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL +#if !FABLE_COMPILER +open FSharp.Compiler.AbstractIL.ILPdbWriter +#endif open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.AbstractIL.Internal.Utils open FSharp.Compiler.AbstractIL.Extensions.ILX open FSharp.Compiler.AbstractIL.Diagnostics open FSharp.Compiler.CompileOps -open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features +open FSharp.Compiler.IlxGen open FSharp.Compiler.Lib open FSharp.Compiler.Range -open FSharp.Compiler.IlxGen +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.ErrorLogger module Attributes = open System.Runtime.CompilerServices @@ -71,7 +77,7 @@ let GetOptionsOfBlock block = let FilterCompilerOptionBlock pred block = match block with | PublicOptions(heading, opts) -> PublicOptions(heading, List.filter pred opts) - | PrivateOptions(opts) -> PrivateOptions(List.filter pred opts) + | PrivateOptions opts -> PrivateOptions(List.filter pred opts) let compilerOptionUsage (CompilerOption(s, tag, spec, _, _)) = let s = if s="--" then "" else s (* s="flag" for "--flag" options. s="--" for "--" option. Adjust printing here for "--" case. *) @@ -178,7 +184,7 @@ module ResponseFile = let parseFile path: Choice = let parseLine (l: string) = match l with - | s when String.IsNullOrWhiteSpace(s) -> None + | s when String.IsNullOrWhiteSpace s -> None | s when l.StartsWithOrdinal("#") -> Some (ResponseFileLine.Comment (s.TrimStart('#'))) | s -> Some (ResponseFileLine.CompilerOptionSpec (s.Trim())) @@ -265,9 +271,9 @@ let ParseCompilerOptions (collectOtherArgument: string -> unit, blocks: Compiler match fullpath with | None -> - errorR(Error(FSComp.SR.optsResponseFileNameInvalid(rsp), rangeCmdArgs)) + errorR(Error(FSComp.SR.optsResponseFileNameInvalid rsp, rangeCmdArgs)) [] - | Some(path) when not (FileSystem.SafeExists path) -> + | Some path when not (FileSystem.SafeExists path) -> errorR(Error(FSComp.SR.optsResponseFileNotFound(rsp, path), rangeCmdArgs)) [] | Some path -> @@ -291,7 +297,7 @@ let ParseCompilerOptions (collectOtherArgument: string -> unit, blocks: Compiler let reportDeprecatedOption errOpt = match errOpt with - | Some(e) -> warning(e) + | Some e -> warning e | None -> () let rec attempt l = @@ -302,7 +308,7 @@ let ParseCompilerOptions (collectOtherArgument: string -> unit, blocks: Compiler | (CompilerOption(s, _, OptionUnit f, d, _) :: _) when optToken = s && argString = "" -> reportDeprecatedOption d f (); t - | (CompilerOption(s, _, OptionSwitch f, d, _) :: _) when getSwitchOpt(optToken) = s && argString = "" -> + | (CompilerOption(s, _, OptionSwitch f, d, _) :: _) when getSwitchOpt optToken = s && argString = "" -> reportDeprecatedOption d f (getSwitch opt); t | (CompilerOption(s, _, OptionSet f, d, _) :: _) when optToken = s && argString = "" -> @@ -321,14 +327,14 @@ let ParseCompilerOptions (collectOtherArgument: string -> unit, blocks: Compiler reportDeprecatedOption d let oa = getOptionArg compilerOption argString if oa <> "" then - f (try int32 (oa) with _ -> + f (try int32 oa with _ -> errorR(Error(FSComp.SR.buildArgInvalidInt(getOptionArg compilerOption argString), rangeCmdArgs)); 0) t | (CompilerOption(s, _, OptionFloat f, d, _) as compilerOption :: _) when optToken = s -> reportDeprecatedOption d let oa = getOptionArg compilerOption argString if oa <> "" then - f (try float (oa) with _ -> + f (try float oa with _ -> errorR(Error(FSComp.SR.buildArgInvalidFloat(getOptionArg compilerOption argString), rangeCmdArgs)); 0.0) t | (CompilerOption(s, _, OptionRest f, d, _) :: _) when optToken = s -> @@ -338,14 +344,14 @@ let ParseCompilerOptions (collectOtherArgument: string -> unit, blocks: Compiler reportDeprecatedOption d let al = getOptionArgList compilerOption argString if al <> [] then - List.iter (fun i -> f (try int32 i with _ -> errorR(Error(FSComp.SR.buildArgInvalidInt(i), rangeCmdArgs)); 0)) al + List.iter (fun i -> f (try int32 i with _ -> errorR(Error(FSComp.SR.buildArgInvalidInt i, rangeCmdArgs)); 0)) al t - | (CompilerOption(s, _, OptionIntListSwitch f, d, _) as compilerOption :: _) when getSwitchOpt(optToken) = s -> + | (CompilerOption(s, _, OptionIntListSwitch f, d, _) as compilerOption :: _) when getSwitchOpt optToken = s -> reportDeprecatedOption d let al = getOptionArgList compilerOption argString if al <> [] then - let switch = getSwitch(opt) - List.iter (fun i -> f (try int32 i with _ -> errorR(Error(FSComp.SR.buildArgInvalidInt(i), rangeCmdArgs)); 0) switch) al + let switch = getSwitch opt + List.iter (fun i -> f (try int32 i with _ -> errorR(Error(FSComp.SR.buildArgInvalidInt i, rangeCmdArgs)); 0) switch) al t // here | (CompilerOption(s, _, OptionStringList f, d, _) as compilerOption :: _) when optToken = s -> @@ -354,11 +360,11 @@ let ParseCompilerOptions (collectOtherArgument: string -> unit, blocks: Compiler if al <> [] then List.iter f (getOptionArgList compilerOption argString) t - | (CompilerOption(s, _, OptionStringListSwitch f, d, _) as compilerOption :: _) when getSwitchOpt(optToken) = s -> + | (CompilerOption(s, _, OptionStringListSwitch f, d, _) as compilerOption :: _) when getSwitchOpt optToken = s -> reportDeprecatedOption d let al = getOptionArgList compilerOption argString if al <> [] then - let switch = getSwitch(opt) + let switch = getSwitch opt List.iter (fun s -> f s switch) (getOptionArgList compilerOption argString) t | (CompilerOption(_, _, OptionGeneral (pred, exec), d, _) :: _) when pred args -> @@ -370,7 +376,7 @@ let ParseCompilerOptions (collectOtherArgument: string -> unit, blocks: Compiler then // want the whole opt token - delimiter and all let unrecOpt = (opt.Split([|':'|]).[0]) - errorR(Error(FSComp.SR.buildUnrecognizedOption(unrecOpt), rangeCmdArgs)) + errorR(Error(FSComp.SR.buildUnrecognizedOption unrecOpt, rangeCmdArgs)) t else (collectOtherArgument opt; t) @@ -411,7 +417,7 @@ let SetOptimizeOn(tcConfigB: TcConfigBuilder) = tcConfigB.doFinalSimplify <- true let SetOptimizeSwitch (tcConfigB: TcConfigBuilder) switch = - if (switch = OptionSwitch.On) then SetOptimizeOn(tcConfigB) else SetOptimizeOff(tcConfigB) + if (switch = OptionSwitch.On) then SetOptimizeOn tcConfigB else SetOptimizeOff tcConfigB let SetTailcallSwitch (tcConfigB: TcConfigBuilder) switch = tcConfigB.emitTailcalls <- (switch = OptionSwitch.On) @@ -419,6 +425,13 @@ let SetTailcallSwitch (tcConfigB: TcConfigBuilder) switch = let SetDeterministicSwitch (tcConfigB: TcConfigBuilder) switch = tcConfigB.deterministic <- (switch = OptionSwitch.On) +let AddPathMapping (tcConfigB: TcConfigBuilder) (pathPair: string) = + match pathPair.Split([|'='|], 2) with + | [| oldPrefix; newPrefix |] -> + tcConfigB.AddPathMapping (oldPrefix, newPrefix) + | _ -> + error(Error(FSComp.SR.optsInvalidPathMapFormat(), rangeCmdArgs)) + let jitoptimizeSwitch (tcConfigB: TcConfigBuilder) switch = tcConfigB.optSettings <- { tcConfigB.optSettings with jitOptUser = Some (switch = OptionSwitch.On) } @@ -438,10 +451,10 @@ let useHighEntropyVASwitch (tcConfigB: TcConfigBuilder) switch = tcConfigB.useHighEntropyVA <- switch = OptionSwitch.On let subSystemVersionSwitch (tcConfigB: TcConfigBuilder) (text: string) = - let fail() = error(Error(FSComp.SR.optsInvalidSubSystemVersion(text), rangeCmdArgs)) + let fail() = error(Error(FSComp.SR.optsInvalidSubSystemVersion text, rangeCmdArgs)) // per spec for 357994: Validate input string, should be two positive integers x.y when x>=4 and y>=0 and both <= 65535 - if System.String.IsNullOrEmpty(text) then + if System.String.IsNullOrEmpty text then fail() else match text.Split('.') with @@ -454,6 +467,9 @@ let subSystemVersionSwitch (tcConfigB: TcConfigBuilder) (text: string) = | _ -> fail() | _ -> fail() +let SetUseSdkSwitch (tcConfigB: TcConfigBuilder) switch = + tcConfigB.useSdkRefs <- (switch = OptionSwitch.On) + let (++) x s = x @ [s] let SetTarget (tcConfigB: TcConfigBuilder)(s: string) = @@ -462,11 +478,11 @@ let SetTarget (tcConfigB: TcConfigBuilder)(s: string) = | "winexe" -> tcConfigB.target <- CompilerTarget.WinExe | "library" -> tcConfigB.target <- CompilerTarget.Dll | "module" -> tcConfigB.target <- CompilerTarget.Module - | _ -> error(Error(FSComp.SR.optsUnrecognizedTarget(s), rangeCmdArgs)) + | _ -> error(Error(FSComp.SR.optsUnrecognizedTarget s, rangeCmdArgs)) let SetDebugSwitch (tcConfigB: TcConfigBuilder) (dtype: string option) (s: OptionSwitch) = match dtype with - | Some(s) -> + | Some s -> match s with | "portable" -> tcConfigB.portablePDB <- true @@ -495,15 +511,17 @@ let SetDebugSwitch (tcConfigB: TcConfigBuilder) (dtype: string option) (s: Optio tcConfigB.jitTracking <- true #endif - | _ -> error(Error(FSComp.SR.optsUnrecognizedDebugType(s), rangeCmdArgs)) + | _ -> error(Error(FSComp.SR.optsUnrecognizedDebugType s, rangeCmdArgs)) | None -> tcConfigB.portablePDB <- false; tcConfigB.embeddedPDB <- false; tcConfigB.jitTracking <- s = OptionSwitch.On tcConfigB.debuginfo <- s = OptionSwitch.On let SetEmbedAllSourceSwitch (tcConfigB: TcConfigBuilder) switch = if (switch = OptionSwitch.On) then tcConfigB.embedAllSource <- true else tcConfigB.embedAllSource <- false -let setOutFileName tcConfigB s = - tcConfigB.outputFile <- Some s +let setOutFileName tcConfigB path = + let outputDir = Path.GetDirectoryName(path) + tcConfigB.outputDir <- Some outputDir + tcConfigB.outputFile <- Some path let setSignatureFile tcConfigB s = tcConfigB.printSignature <- true @@ -524,8 +542,11 @@ let tagFullPDBOnlyPortable = "{full|pdbonly|portable|embedded}" let tagWarnList = "" let tagSymbolList = "" let tagAddress = "
" +let tagAlgorithm = "{SHA1|SHA256}" let tagInt = "" +let tagPathMap = "" let tagNone = "" +let tagLangVersionValues = "{?|version|latest|preview}" // PrintOptionInfo //---------------- @@ -556,29 +577,39 @@ let PrintOptionInfo (tcConfigB:TcConfigBuilder) = // OptionBlock: Input files //------------------------- -let inputFileFlagsBoth (tcConfigB : TcConfigBuilder) = - [ CompilerOption("reference", tagFile, OptionString (fun s -> tcConfigB.AddReferencedAssemblyByPath (rangeStartup, s)), None, - Some (FSComp.SR.optsReference()) ) +let inputFileFlagsBoth (tcConfigB : TcConfigBuilder) = [ + CompilerOption("reference", tagFile, OptionString (fun s -> tcConfigB.AddReferencedAssemblyByPath (rangeStartup, s)), None, Some (FSComp.SR.optsReference())) + CompilerOption("compilertool", tagFile, OptionString (fun s -> tcConfigB.AddCompilerToolsByPath s), None, Some (FSComp.SR.optsCompilerTool())) ] -let referenceFlagAbbrev (tcConfigB: TcConfigBuilder) = - CompilerOption("r", tagFile, OptionString (fun s -> tcConfigB.AddReferencedAssemblyByPath (rangeStartup, s)), None, - Some(FSComp.SR.optsShortFormOf("--reference")) ) +let referenceFlagAbbrev (tcConfigB : TcConfigBuilder) = + CompilerOption("r", tagFile, OptionString (fun s -> tcConfigB.AddReferencedAssemblyByPath (rangeStartup, s)), None, Some(FSComp.SR.optsShortFormOf("--reference"))) + +let compilerToolFlagAbbrev (tcConfigB : TcConfigBuilder) = + CompilerOption("t", tagFile, OptionString (fun s -> tcConfigB.AddCompilerToolsByPath s), None, Some(FSComp.SR.optsShortFormOf("--compilertool"))) -let inputFileFlagsFsi tcConfigB = inputFileFlagsBoth tcConfigB let inputFileFlagsFsc tcConfigB = inputFileFlagsBoth tcConfigB +let inputFileFlagsFsiBase (_tcConfigB: TcConfigBuilder) = +#if NETSTANDARD + [ CompilerOption("usesdkrefs", tagNone, OptionSwitch (SetUseSdkSwitch _tcConfigB), None, Some (FSComp.SR.useSdkRefs())) ] +#else + List.empty +#endif + +let inputFileFlagsFsi (tcConfigB: TcConfigBuilder) = + List.concat [ inputFileFlagsBoth tcConfigB; inputFileFlagsFsiBase tcConfigB] // OptionBlock: Errors and warnings //--------------------------------- let errorsAndWarningsFlags (tcConfigB: TcConfigBuilder) = - let trimFS (s:string) = if s.StartsWithOrdinal("FS") = true then s.Substring(2) else s + let trimFS (s:string) = if s.StartsWithOrdinal("FS") = true then s.Substring 2 else s let trimFStoInt (s:string) = try Some (int32 (trimFS s)) with _ -> - errorR(Error(FSComp.SR.buildArgInvalidInt(s), rangeCmdArgs)) + errorR(Error(FSComp.SR.buildArgInvalidInt s, rangeCmdArgs)) None [ CompilerOption("warnaserror", tagNone, OptionSwitch(fun switch -> @@ -604,7 +635,7 @@ let errorsAndWarningsFlags (tcConfigB: TcConfigBuilder) = CompilerOption("warn", tagInt, OptionInt (fun n -> tcConfigB.errorSeverityOptions <- { tcConfigB.errorSeverityOptions with - WarnLevel = if (n >= 0 && n <= 5) then n else error(Error (FSComp.SR.optsInvalidWarningLevel(n), rangeCmdArgs)) } + WarnLevel = if (n >= 0 && n <= 5) then n else error(Error (FSComp.SR.optsInvalidWarningLevel n, rangeCmdArgs)) } ), None, Some (FSComp.SR.optsWarn())) CompilerOption("nowarn", tagWarnList, OptionStringList (fun n -> @@ -667,12 +698,12 @@ let outputFileFlagsFsc (tcConfigB: TcConfigBuilder) = CompilerOption ("keyfile", tagFile, - OptionString (fun s -> tcConfigB.signer <- Some(s)), None, + OptionString (fun s -> tcConfigB.signer <- Some s), None, Some (FSComp.SR.optsStrongKeyFile())) CompilerOption ("keycontainer", tagString, - OptionString(fun s -> tcConfigB.container <- Some(s)), None, + OptionString(fun s -> tcConfigB.container <- Some s), None, Some(FSComp.SR.optsStrongKeyContainer())) CompilerOption @@ -687,7 +718,7 @@ let outputFileFlagsFsc (tcConfigB: TcConfigBuilder) = tcConfigB.prefer32Bit <- true None | "anycpu" -> None - | _ -> error(Error(FSComp.SR.optsUnknownPlatform(s), rangeCmdArgs))), None, + | _ -> error(Error(FSComp.SR.optsUnknownPlatform s, rangeCmdArgs))), None, Some(FSComp.SR.optsPlatform())) CompilerOption @@ -757,7 +788,7 @@ let codeGenerationFlags isFsi (tcConfigB: TcConfigBuilder) = CompilerOption ("debug", tagFullPDBOnlyPortable, - OptionString (fun s -> SetDebugSwitch tcConfigB (Some(s)) OptionSwitch.On), None, + OptionString (fun s -> SetDebugSwitch tcConfigB (Some s) OptionSwitch.On), None, Some (FSComp.SR.optsDebug(if isFsi then "pdbonly" else "full"))) ] let embed = @@ -792,7 +823,12 @@ let codeGenerationFlags isFsi (tcConfigB: TcConfigBuilder) = ("deterministic", tagNone, OptionSwitch (SetDeterministicSwitch tcConfigB), None, Some (FSComp.SR.optsDeterministic())) - + + CompilerOption + ("pathmap", tagPathMap, + OptionStringList (AddPathMapping tcConfigB), None, + Some (FSComp.SR.optsPathMap())) + CompilerOption ("crossoptimize", tagNone, OptionSwitch (crossOptimizeSwitch tcConfigB), None, @@ -805,28 +841,45 @@ let codeGenerationFlags isFsi (tcConfigB: TcConfigBuilder) = //---------------------- let defineSymbol tcConfigB s = tcConfigB.conditionalCompilationDefines <- s :: tcConfigB.conditionalCompilationDefines - + let mlCompatibilityFlag (tcConfigB: TcConfigBuilder) = CompilerOption ("mlcompatibility", tagNone, OptionUnit (fun () -> tcConfigB.mlCompatibility<-true; tcConfigB.TurnWarningOff(rangeCmdArgs, "62")), None, Some (FSComp.SR.optsMlcompatibility())) +/// LanguageVersion management +let setLanguageVersion (specifiedVersion) = + + let languageVersion = new LanguageVersion(specifiedVersion) + let dumpAllowedValues () = + printfn "%s" (FSComp.SR.optsSupportedLangVersions()) + for v in languageVersion.ValidOptions do printfn "%s" v + for v in languageVersion.ValidVersions do printfn "%s" v +#if FABLE_COMPILER + () +#else + exit 0 +#endif + + if specifiedVersion = "?" then dumpAllowedValues () + if not (languageVersion.ContainsVersion specifiedVersion) then error(Error(FSComp.SR.optsUnrecognizedLanguageVersion specifiedVersion, rangeCmdArgs)) + languageVersion + let languageFlags tcConfigB = [ - CompilerOption - ("checked", tagNone, - OptionSwitch (fun switch -> tcConfigB.checkOverflow <- (switch = OptionSwitch.On)), None, - Some (FSComp.SR.optsChecked())) - - CompilerOption - ("define", tagString, - OptionString (defineSymbol tcConfigB), None, - Some (FSComp.SR.optsDefine())) - + // -langversion:? Display the allowed values for language version + // -langversion: Specify language version such as + // 'default' (latest major version), or + // 'latest' (latest version, including minor versions), + // 'preview' (features for preview) + // or specific versions like '4.7' + CompilerOption("langversion", tagLangVersionValues, OptionString (fun switch -> tcConfigB.langVersion <- setLanguageVersion(switch)), None, Some (FSComp.SR.optsLangVersion())) + + CompilerOption("checked", tagNone, OptionSwitch (fun switch -> tcConfigB.checkOverflow <- (switch = OptionSwitch.On)), None, Some (FSComp.SR.optsChecked())) + CompilerOption("define", tagString, OptionString (defineSymbol tcConfigB), None, Some (FSComp.SR.optsDefine())) mlCompatibilityFlag tcConfigB ] - // OptionBlock: Advanced user options //----------------------------------- @@ -837,30 +890,24 @@ let libFlag (tcConfigB: TcConfigBuilder) = OptionStringList (fun s -> tcConfigB.AddIncludePath (rangeStartup, s, tcConfigB.implicitIncludeDir)), None, Some (FSComp.SR.optsLib())) -let libFlagAbbrev (tcConfigB: TcConfigBuilder) = - CompilerOption - ("I", tagDirList, - OptionStringList (fun s -> tcConfigB.AddIncludePath (rangeStartup, s, tcConfigB.implicitIncludeDir)), None, - Some (FSComp.SR.optsShortFormOf("--lib"))) - let codePageFlag (tcConfigB: TcConfigBuilder) = CompilerOption ("codepage", tagInt, OptionInt (fun n -> #if !FABLE_COMPILER try - System.Text.Encoding.GetEncoding(n) |> ignore + System.Text.Encoding.GetEncoding n |> ignore with :? System.ArgumentException as err -> error(Error(FSComp.SR.optsProblemWithCodepage(n, err.Message), rangeCmdArgs)) #endif - tcConfigB.inputCodePage <- Some(n)), None, + tcConfigB.inputCodePage <- Some n), None, Some (FSComp.SR.optsCodepage())) let preferredUiLang (tcConfigB: TcConfigBuilder) = CompilerOption ("preferreduilang", tagString, - OptionString (fun s -> tcConfigB.preferredUiLang <- Some(s)), None, + OptionString (fun s -> tcConfigB.preferredUiLang <- Some s), None, Some(FSComp.SR.optsPreferredUiLang())) let utf8OutputFlag (tcConfigB: TcConfigBuilder) = @@ -890,7 +937,7 @@ let SetTargetProfile tcConfigB v = | "netcore" -> PrimaryAssembly.System_Runtime // Indicates we assume "netstandard.dll", i.e .NET Standard 2.0 and above | "netstandard" -> PrimaryAssembly.NetStandard - | _ -> error(Error(FSComp.SR.optsInvalidTargetProfile(v), rangeCmdArgs)) + | _ -> error(Error(FSComp.SR.optsInvalidTargetProfile v, rangeCmdArgs)) let advancedFlagsBoth tcConfigB = [ @@ -934,6 +981,18 @@ let advancedFlagsFsc tcConfigB = OptionString (fun s -> tcConfigB.baseAddress <- Some(int32 s)), None, Some (FSComp.SR.optsBaseaddress())) +#if !FABLE_COMPILER + yield CompilerOption + ("checksumalgorithm", tagAlgorithm, + OptionString (fun s -> + tcConfigB.checksumAlgorithm <- + match s.ToUpperInvariant() with + | "SHA1" -> HashAlgorithm.Sha1 + | "SHA256" -> HashAlgorithm.Sha256 + | _ -> error(Error(FSComp.SR.optsUnknownChecksumAlgorithm s, rangeCmdArgs))), None, + Some (FSComp.SR.optsChecksumAlgorithm())) +#endif + yield noFrameworkFlag true tcConfigB yield CompilerOption @@ -989,7 +1048,7 @@ let testFlag tcConfigB = match s with | "StackSpan" -> tcConfigB.internalTestSpanStackReferring <- true | "ErrorRanges" -> tcConfigB.errorStyle <- ErrorStyle.TestErrors - | "Tracking" -> Lib.tracking := true (* general purpose on/off diagnostics flag *) + | "Tracking" -> Lib.tracking <- true (* general purpose on/off diagnostics flag *) | "NoNeedToTailcall" -> tcConfigB.optSettings <- { tcConfigB.optSettings with reportNoNeedToTailcall = true } | "FunctionSizes" -> tcConfigB.optSettings <- { tcConfigB.optSettings with reportFunctionSizes = true } | "TotalSizes" -> tcConfigB.optSettings <- { tcConfigB.optSettings with reportTotalSizes = true } @@ -1001,18 +1060,18 @@ let testFlag tcConfigB = | "DumpDebugInfo" -> tcConfigB.dumpDebugInfo <- true | "ShowLoadedAssemblies" -> tcConfigB.showLoadedAssemblies <- true | "ContinueAfterParseFailure" -> tcConfigB.continueAfterParseFailure <- true - | str -> warning(Error(FSComp.SR.optsUnknownArgumentToTheTestSwitch(str), rangeCmdArgs))), None, + | str -> warning(Error(FSComp.SR.optsUnknownArgumentToTheTestSwitch str, rangeCmdArgs))), None, None) // Not shown in fsc.exe help, no warning on use, motivation is for use from tooling. let editorSpecificFlags (tcConfigB: TcConfigBuilder) = [ CompilerOption("vserrors", tagNone, OptionUnit (fun () -> tcConfigB.errorStyle <- ErrorStyle.VSErrors), None, None) - CompilerOption("validate-type-providers", tagNone, OptionUnit (id), None, None) // preserved for compatibility's sake, no longer has any effect + CompilerOption("validate-type-providers", tagNone, OptionUnit id, None, None) // preserved for compatibility's sake, no longer has any effect CompilerOption("LCID", tagInt, OptionInt ignore, None, None) CompilerOption("flaterrors", tagNone, OptionUnit (fun () -> tcConfigB.flatErrors <- true), None, None) CompilerOption("sqmsessionguid", tagNone, OptionString ignore, None, None) CompilerOption("gccerrors", tagNone, OptionUnit (fun () -> tcConfigB.errorStyle <- ErrorStyle.GccErrors), None, None) - CompilerOption("exename", tagNone, OptionString (fun s -> tcConfigB.exename <- Some(s)), None, None) + CompilerOption("exename", tagNone, OptionString (fun s -> tcConfigB.exename <- Some s), None, None) CompilerOption("maxerrors", tagInt, OptionInt (fun n -> tcConfigB.maxErrors <- n), None, None) CompilerOption("noconditionalerasure", tagNone, OptionUnit (fun () -> tcConfigB.noConditionalErasure <- true), None, None) ] @@ -1025,7 +1084,7 @@ let internalFlags (tcConfigB:TcConfigBuilder) = CompilerOption ("ranges", tagNone, - OptionSet Tastops.DebugPrint.layoutRanges, + OptionSet DebugPrint.layoutRanges, Some(InternalCommandLineOption("--ranges", rangeCmdArgs)), None) CompilerOption @@ -1057,7 +1116,7 @@ let internalFlags (tcConfigB:TcConfigBuilder) = CompilerOption ("simulateException", tagNone, - OptionString (fun s -> tcConfigB.simulateException <- Some(s)), + OptionString (fun s -> tcConfigB.simulateException <- Some s), Some(InternalCommandLineOption("--simulateException", rangeCmdArgs)), Some "Simulate an exception from some part of the compiler") CompilerOption @@ -1204,14 +1263,13 @@ let internalFlags (tcConfigB:TcConfigBuilder) = CompilerOption ("metadataversion", tagString, - OptionString (fun s -> tcConfigB.metadataVersion <- Some(s)), + OptionString (fun s -> tcConfigB.metadataVersion <- Some s), Some(InternalCommandLineOption("metadataversion", rangeCmdArgs)), None) ] - // OptionBlock: Deprecated flags (fsc, service only) //-------------------------------------------------- - + let compilingFsLibFlag (tcConfigB: TcConfigBuilder) = CompilerOption ("compiling-fslib", tagNone, @@ -1219,26 +1277,17 @@ let compilingFsLibFlag (tcConfigB: TcConfigBuilder) = tcConfigB.compilingFslib <- true tcConfigB.TurnWarningOff(rangeStartup, "42") ErrorLogger.reportLibraryOnlyFeatures <- false - IlxSettings.ilxCompilingFSharpCoreLib := true), + IlxSettings.ilxCompilingFSharpCoreLib <- true), Some(InternalCommandLineOption("--compiling-fslib", rangeCmdArgs)), None) -let compilingFsLib20Flag (tcConfigB: TcConfigBuilder) = - CompilerOption - ("compiling-fslib-20", tagNone, - OptionString (fun s -> tcConfigB.compilingFslib20 <- Some s ), - Some(InternalCommandLineOption("--compiling-fslib-20", rangeCmdArgs)), None) +let compilingFsLib20Flag = + CompilerOption ("compiling-fslib-20", tagNone, OptionString (fun _ -> () ), None, None) -let compilingFsLib40Flag (tcConfigB: TcConfigBuilder) = - CompilerOption - ("compiling-fslib-40", tagNone, - OptionUnit (fun () -> tcConfigB.compilingFslib40 <- true ), - Some(InternalCommandLineOption("--compiling-fslib-40", rangeCmdArgs)), None) +let compilingFsLib40Flag = + CompilerOption ("compiling-fslib-40", tagNone, OptionUnit (fun () -> ()), None, None) -let compilingFsLibNoBigIntFlag (tcConfigB: TcConfigBuilder) = - CompilerOption - ("compiling-fslib-nobigint", tagNone, - OptionUnit (fun () -> tcConfigB.compilingFslibNoBigInt <- true ), - Some(InternalCommandLineOption("--compiling-fslib-nobigint", rangeCmdArgs)), None) +let compilingFsLibNoBigIntFlag = + CompilerOption ("compiling-fslib-nobigint", tagNone, OptionUnit (fun () -> () ), None, None) let mlKeywordsFlag = CompilerOption @@ -1253,23 +1302,23 @@ let gnuStyleErrorsFlag tcConfigB = Some(DeprecatedCommandLineOptionNoDescription("--gnu-style-errors", rangeCmdArgs)), None) let deprecatedFlagsBoth tcConfigB = - [ + [ CompilerOption ("light", tagNone, - OptionUnit (fun () -> tcConfigB.light <- Some(true)), + OptionUnit (fun () -> tcConfigB.light <- Some true), Some(DeprecatedCommandLineOptionNoDescription("--light", rangeCmdArgs)), None) CompilerOption ("indentation-syntax", tagNone, - OptionUnit (fun () -> tcConfigB.light <- Some(true)), + OptionUnit (fun () -> tcConfigB.light <- Some true), Some(DeprecatedCommandLineOptionNoDescription("--indentation-syntax", rangeCmdArgs)), None) CompilerOption ("no-indentation-syntax", tagNone, - OptionUnit (fun () -> tcConfigB.light <- Some(false)), + OptionUnit (fun () -> tcConfigB.light <- Some false), Some(DeprecatedCommandLineOptionNoDescription("--no-indentation-syntax", rangeCmdArgs)), None) ] - + let deprecatedFlagsFsi tcConfigB = deprecatedFlagsBoth tcConfigB let deprecatedFlagsFsc tcConfigB = @@ -1298,13 +1347,13 @@ let deprecatedFlagsFsc tcConfigB = CompilerOption ("progress", tagNone, - OptionUnit (fun () -> progress := true), + OptionUnit (fun () -> progress <- true), Some(DeprecatedCommandLineOptionNoDescription("--progress", rangeCmdArgs)), None) compilingFsLibFlag tcConfigB - compilingFsLib20Flag tcConfigB - compilingFsLib40Flag tcConfigB - compilingFsLibNoBigIntFlag tcConfigB + compilingFsLib20Flag + compilingFsLib40Flag + compilingFsLibNoBigIntFlag CompilerOption ("version", tagString, @@ -1368,7 +1417,7 @@ let deprecatedFlagsFsc tcConfigB = CompilerOption ("Ooff", tagNone, - OptionUnit (fun () -> SetOptimizeOff(tcConfigB)), + OptionUnit (fun () -> SetOptimizeOff tcConfigB), Some(DeprecatedCommandLineOptionSuggestAlternative("-Ooff", "--optimize-", rangeCmdArgs)), None) mlKeywordsFlag @@ -1415,8 +1464,10 @@ let abbreviatedFlagsBoth tcConfigB = CompilerOption("O", tagNone, OptionSwitch (SetOptimizeSwitch tcConfigB), None, Some(FSComp.SR.optsShortFormOf("--optimize[+|-]"))) CompilerOption("g", tagNone, OptionSwitch (SetDebugSwitch tcConfigB None), None, Some(FSComp.SR.optsShortFormOf("--debug"))) CompilerOption("i", tagString, OptionUnit (fun () -> tcConfigB.printSignature <- true), None, Some(FSComp.SR.optsShortFormOf("--sig"))) - referenceFlagAbbrev tcConfigB (* -r *) - libFlagAbbrev tcConfigB (* -I *) + CompilerOption("r", tagFile, OptionString (fun s -> tcConfigB.AddReferencedAssemblyByPath (rangeStartup, s)), + None, Some(FSComp.SR.optsShortFormOf("--reference"))) + CompilerOption("I", tagDirList, OptionStringList (fun s -> tcConfigB.AddIncludePath (rangeStartup, s, tcConfigB.implicitIncludeDir)), + None, Some (FSComp.SR.optsShortFormOf("--lib"))) ] let abbreviatedFlagsFsi tcConfigB = abbreviatedFlagsBoth tcConfigB @@ -1563,10 +1614,10 @@ let GetCoreFsiCompilerOptions (tcConfigB: TcConfigBuilder) = let ApplyCommandLineArgs(tcConfigB: TcConfigBuilder, sourceFiles: string list, commandLineArgs) = try - let sourceFilesAcc = ResizeArray(sourceFiles) - let collect name = if not (Filename.isDll name) then sourceFilesAcc.Add(name) + let sourceFilesAcc = ResizeArray sourceFiles + let collect name = if not (Filename.isDll name) then sourceFilesAcc.Add name ParseCompilerOptions(collect, GetCoreServiceCompilerOptions tcConfigB, commandLineArgs) - ResizeArray.toList(sourceFilesAcc) + ResizeArray.toList sourceFilesAcc with e -> errorRecovery e range0 sourceFiles @@ -1578,29 +1629,28 @@ let ApplyCommandLineArgs(tcConfigB: TcConfigBuilder, sourceFiles: string list, c // PrintWholeAssemblyImplementation //---------------------------------------------------------------------------- -let showTermFileCount = ref 0 -let PrintWholeAssemblyImplementation (tcConfig:TcConfig) outfile header expr = +let mutable showTermFileCount = 0 +let PrintWholeAssemblyImplementation g (tcConfig:TcConfig) outfile header expr = if tcConfig.showTerms then if tcConfig.writeTermsToFiles then let filename = outfile + ".terms" - let n = !showTermFileCount - showTermFileCount := n+1 - use f = System.IO.File.CreateText (filename + "-" + string n + "-" + header) - Layout.outL f (Layout.squashTo 192 (DebugPrint.implFilesL expr)) + use f = System.IO.File.CreateText (filename + "-" + string showTermFileCount + "-" + header) + showTermFileCount <- showTermFileCount + 1 + Layout.outL f (Layout.squashTo 192 (DebugPrint.implFilesL g expr)) else dprintf "\n------------------\nshowTerm: %s:\n" header - Layout.outL stderr (Layout.squashTo 192 (DebugPrint.implFilesL expr)) + Layout.outL stderr (Layout.squashTo 192 (DebugPrint.implFilesL g expr)) dprintf "\n------------------\n" //---------------------------------------------------------------------------- // ReportTime //---------------------------------------------------------------------------- -let tPrev = ref None -let nPrev = ref None +let mutable tPrev = None +let mutable nPrev = None let ReportTime (tcConfig:TcConfig) descr = - match !nPrev with + match nPrev with | None -> () | Some prevDescr -> if tcConfig.pause then @@ -1611,16 +1661,10 @@ let ReportTime (tcConfig:TcConfig) descr = | Some("fsc-oom") -> raise(System.OutOfMemoryException()) | Some("fsc-an") -> raise(System.ArgumentNullException("simulated")) | Some("fsc-invop") -> raise(System.InvalidOperationException()) -#if FX_REDUCED_EXCEPTIONS -#else | Some("fsc-av") -> raise(System.AccessViolationException()) -#endif | Some("fsc-aor") -> raise(System.ArgumentOutOfRangeException()) | Some("fsc-dv0") -> raise(System.DivideByZeroException()) -#if FX_REDUCED_EXCEPTIONS -#else | Some("fsc-nfn") -> raise(System.NotFiniteNumberException()) -#endif | Some("fsc-oe") -> raise(System.OverflowException()) | Some("fsc-atmm") -> raise(System.ArrayTypeMismatchException()) | Some("fsc-bif") -> raise(System.BadImageFormatException()) @@ -1643,13 +1687,13 @@ let ReportTime (tcConfig:TcConfig) descr = // make this call unless showTimes has been turned on. let timeNow = System.Diagnostics.Process.GetCurrentProcess().UserProcessorTime.TotalSeconds let maxGen = System.GC.MaxGeneration - let gcNow = [| for i in 0 .. maxGen -> System.GC.CollectionCount(i) |] + let gcNow = [| for i in 0 .. maxGen -> System.GC.CollectionCount i |] let ptime = System.Diagnostics.Process.GetCurrentProcess() let wsNow = ptime.WorkingSet64/1000000L - match !tPrev, !nPrev with + match tPrev, nPrev with | Some (timePrev, gcPrev:int []), Some prevDescr -> - let spanGC = [| for i in 0 .. maxGen -> System.GC.CollectionCount(i) - gcPrev.[i] |] + let spanGC = [| for i in 0 .. maxGen -> System.GC.CollectionCount i - gcPrev.[i] |] dprintf "TIME: %4.1f Delta: %4.1f Mem: %3d" timeNow (timeNow - timePrev) wsNow @@ -1658,9 +1702,9 @@ let ReportTime (tcConfig:TcConfig) descr = prevDescr | _ -> () - tPrev := Some (timeNow, gcNow) + tPrev <- Some (timeNow, gcNow) - nPrev := Some descr + nPrev <- Some descr #endif //!FABLE_COMPILER @@ -1668,10 +1712,10 @@ let ReportTime (tcConfig:TcConfig) descr = // OPTIMIZATION - support - addDllToOptEnv //---------------------------------------------------------------------------- -let AddExternalCcuToOpimizationEnv tcGlobals optEnv (ccuinfo: ImportedAssembly) = +let AddExternalCcuToOptimizationEnv tcGlobals optEnv (ccuinfo: ImportedAssembly) = match ccuinfo.FSharpOptimizationData.Force() with | None -> optEnv - | Some(data) -> Optimizer.BindCcu ccuinfo.FSharpViewOfMetadata data optEnv tcGlobals + | Some data -> Optimizer.BindCcu ccuinfo.FSharpViewOfMetadata data optEnv tcGlobals //---------------------------------------------------------------------------- // OPTIMIZATION - support - optimize @@ -1680,7 +1724,7 @@ let AddExternalCcuToOpimizationEnv tcGlobals optEnv (ccuinfo: ImportedAssembly) let GetInitialOptimizationEnv (tcImports:TcImports, tcGlobals:TcGlobals) = let ccuinfos = tcImports.GetImportedAssemblies() let optEnv = Optimizer.IncrementalOptimizationEnv.Empty - let optEnv = List.fold (AddExternalCcuToOpimizationEnv tcGlobals) optEnv ccuinfos + let optEnv = List.fold (AddExternalCcuToOptimizationEnv tcGlobals) optEnv ccuinfos optEnv let ApplyAllOptimizations (tcConfig:TcConfig, tcGlobals, tcVal, outfile:string, importMap, isIncrementalFragment, optEnv, ccu:CcuThunk, implFiles) = @@ -1692,15 +1736,15 @@ let ApplyAllOptimizations (tcConfig:TcConfig, tcGlobals, tcVal, outfile:string, #if FABLE_COMPILER ignore outfile #else - PrintWholeAssemblyImplementation tcConfig outfile "pass-start" implFiles + PrintWholeAssemblyImplementation tcGlobals tcConfig outfile "pass-start" implFiles #endif #if DEBUG if tcConfig.showOptimizationData then - dprintf "Expression prior to optimization:\n%s\n" (Layout.showL (Layout.squashTo 192 (DebugPrint.implFilesL implFiles))) + dprintf "Expression prior to optimization:\n%s\n" (Layout.showL (Layout.squashTo 192 (DebugPrint.implFilesL tcGlobals implFiles))) if tcConfig.showOptimizationData then - dprintf "CCU prior to optimization:\n%s\n" (Layout.showL (Layout.squashTo 192 (DebugPrint.entityL ccu.Contents))) + dprintf "CCU prior to optimization:\n%s\n" (Layout.showL (Layout.squashTo 192 (DebugPrint.entityL tcGlobals ccu.Contents))) #endif let optEnv0 = optEnv @@ -1783,9 +1827,9 @@ let ApplyAllOptimizations (tcConfig:TcConfig, tcGlobals, tcVal, outfile:string, let implFiles, implFileOptDatas = List.unzip results let assemblyOptData = Optimizer.UnionOptimizationInfos implFileOptDatas - let tassembly = TypedAssemblyAfterOptimization(implFiles) + let tassembly = TypedAssemblyAfterOptimization implFiles #if !FABLE_COMPILER - PrintWholeAssemblyImplementation tcConfig outfile "pass-end" (List.map fst implFiles) + PrintWholeAssemblyImplementation tcGlobals tcConfig outfile "pass-end" (List.map fst implFiles) ReportTime tcConfig ("Ending Optimizations") #endif tassembly, assemblyOptData, optEnvFirstLoop @@ -1833,14 +1877,17 @@ let GenerateIlxCode // by the same references. Only used for static linking. //---------------------------------------------------------------------------- -let NormalizeAssemblyRefs (ctok, tcImports:TcImports) scoref = +let NormalizeAssemblyRefs (ctok, ilGlobals: ILGlobals, tcImports:TcImports) scoref = + let normalizeAssemblyRefByName nm = + match tcImports.TryFindDllInfo (ctok, Range.rangeStartup, nm, lookupOnly=false) with + | Some dllInfo -> dllInfo.ILScopeRef + | None -> scoref + match scoref with | ILScopeRef.Local | ILScopeRef.Module _ -> scoref - | ILScopeRef.Assembly aref -> - match tcImports.TryFindDllInfo (ctok, Range.rangeStartup, aref.Name, lookupOnly=false) with - | Some dllInfo -> dllInfo.ILScopeRef - | None -> scoref + | ILScopeRef.PrimaryAssembly -> normalizeAssemblyRefByName ilGlobals.primaryAssemblyName + | ILScopeRef.Assembly aref -> normalizeAssemblyRefByName aref.Name let GetGeneratedILModuleName (t:CompilerTarget) (s:string) = // return the name of the file as a module name diff --git a/src/fcs-fable/src/fsharp/CompileOptions.fsi b/src/fcs-fable/src/fsharp/CompileOptions.fsi index 09ee39d227..3959b251da 100644 --- a/src/fcs-fable/src/fsharp/CompileOptions.fsi +++ b/src/fcs-fable/src/fsharp/CompileOptions.fsi @@ -2,17 +2,19 @@ module internal FSharp.Compiler.CompileOptions +open System open FSharp.Compiler +open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.CompileOps -open FSharp.Compiler.Tast +open FSharp.Compiler.TypedTree open FSharp.Compiler.Import open FSharp.Compiler.Optimizer open FSharp.Compiler.TcGlobals //---------------------------------------------------------------------------- // Compiler Option Parser -//-------------------------------------------------------------------------- +//---------------------------------------------------------------------------- // For command-line options that can be suffixed with +/- [] @@ -78,7 +80,7 @@ val GetGeneratedILModuleName : CompilerTarget -> string -> string #endif //!FABLE_COMPILER val GetInitialOptimizationEnv : TcImports * TcGlobals -> IncrementalOptimizationEnv -val AddExternalCcuToOpimizationEnv : TcGlobals -> IncrementalOptimizationEnv -> ImportedAssembly -> IncrementalOptimizationEnv +val AddExternalCcuToOptimizationEnv : TcGlobals -> IncrementalOptimizationEnv -> ImportedAssembly -> IncrementalOptimizationEnv val ApplyAllOptimizations : TcConfig * TcGlobals * ConstraintSolver.TcValF * string * ImportMap * bool * IncrementalOptimizationEnv * CcuThunk * TypedImplFile list -> TypedAssemblyAfterOptimization * Optimizer.LazyModuleInfo * IncrementalOptimizationEnv #if !FABLE_COMPILER @@ -88,12 +90,12 @@ val CreateIlxAssemblyGenerator : TcConfig * TcImports * TcGlobals * ConstraintSo val GenerateIlxCode : IlxGen.IlxGenBackend * isInteractiveItExpr:bool * isInteractiveOnMono:bool * TcConfig * TypeChecker.TopAttribs * TypedAssemblyAfterOptimization * fragName:string * IlxGen.IlxAssemblyGenerator -> IlxGen.IlxGenResults // Used during static linking -val NormalizeAssemblyRefs : CompilationThreadToken * TcImports -> (AbstractIL.IL.ILScopeRef -> AbstractIL.IL.ILScopeRef) +val NormalizeAssemblyRefs : CompilationThreadToken * ILGlobals * TcImports -> (AbstractIL.IL.ILScopeRef -> AbstractIL.IL.ILScopeRef) // Miscellany val ignoreFailureOnMono1_1_16 : (unit -> unit) -> unit val mutable enableConsoleColoring : bool -val DoWithColor : System.ConsoleColor -> (unit -> 'a) -> 'a +val DoWithColor : ConsoleColor -> (unit -> 'a) -> 'a val DoWithErrorColor : bool -> (unit -> 'a) -> 'a val ReportTime : TcConfig -> string -> unit val GetAbbrevFlagSet : TcConfigBuilder -> bool -> Set diff --git a/src/fcs-fable/src/fsharp/CompilerGlobalState.fs b/src/fcs-fable/src/fsharp/CompilerGlobalState.fs new file mode 100644 index 0000000000..c734226e11 --- /dev/null +++ b/src/fcs-fable/src/fsharp/CompilerGlobalState.fs @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +/// Defines the global environment for all type checking. + +module FSharp.Compiler.CompilerGlobalState + +open System.Collections.Generic +open FSharp.Compiler.Range +open FSharp.Compiler.PrettyNaming + +/// Generates compiler-generated names. Each name generated also includes the StartLine number of the range passed in +/// at the point of first generation. +/// +/// This type may be accessed concurrently, though in practice it is only used from the compilation thread. +/// It is made concurrency-safe since a global instance of the type is allocated in tast.fs, and it is good +/// policy to make all globally-allocated objects concurrency safe in case future versions of the compiler +/// are used to host multiple concurrent instances of compilation. +type NiceNameGenerator() = + + let lockObj = obj() + let basicNameCounts = new Dictionary(100) + + member x.FreshCompilerGeneratedName (name, m: range) = + lock lockObj (fun () -> + let basicName = GetBasicNameOfPossibleCompilerGeneratedName name + let n = + match basicNameCounts.TryGetValue basicName with + | true, count -> count + | _ -> 0 + let nm = CompilerGeneratedNameSuffix basicName (string m.StartLine + (match n with 0 -> "" | n -> "-" + string n)) + basicNameCounts.[basicName] <- n + 1 + nm) + + member x.Reset () = + lock lockObj (fun () -> + basicNameCounts.Clear() + ) + +/// Generates compiler-generated names marked up with a source code location, but if given the same unique value then +/// return precisely the same name. Each name generated also includes the StartLine number of the range passed in +/// at the point of first generation. +/// +/// This type may be accessed concurrently, though in practice it is only used from the compilation thread. +/// It is made concurrency-safe since a global instance of the type is allocated in tast.fs. +type StableNiceNameGenerator() = + + let lockObj = obj() + + let names = new Dictionary<(string * int64), string>(100) + let basicNameCounts = new Dictionary(100) + + member x.GetUniqueCompilerGeneratedName (name, m: range, uniq) = + lock lockObj (fun () -> + let basicName = GetBasicNameOfPossibleCompilerGeneratedName name + let key = basicName, uniq + match names.TryGetValue key with + | true, nm -> nm + | _ -> + let n = + match basicNameCounts.TryGetValue basicName with + | true, c -> c + | _ -> 0 + let nm = CompilerGeneratedNameSuffix basicName (string m.StartLine + (match n with 0 -> "" | n -> "-" + string n)) + names.[key] <- nm + basicNameCounts.[basicName] <- n + 1 + nm + ) + + member x.Reset () = + lock lockObj (fun () -> + basicNameCounts.Clear() + names.Clear() + ) + +type internal CompilerGlobalState () = + /// A global generator of compiler generated names + // ++GLOBAL MUTABLE STATE (concurrency safe by locking inside NiceNameGenerator) + let globalNng = NiceNameGenerator() + + + /// A global generator of stable compiler generated names + // MUTABLE STATE (concurrency safe by locking inside StableNiceNameGenerator) + let globalStableNameGenerator = StableNiceNameGenerator () + + /// A name generator used by IlxGen for static fields, some generated arguments and other things. + /// REVIEW: this will mean the hosted compiler service is not deterministic. We should at least create a new one + /// of these for each compilation. + let ilxgenGlobalNng = NiceNameGenerator () + + member __.NiceNameGenerator = globalNng + + member __.StableNameGenerator = globalStableNameGenerator + + member __.IlxGenNiceNameGenerator = ilxgenGlobalNng + +/// Unique name generator for stamps attached to lambdas and object expressions +type Unique = int64 + +//++GLOBAL MUTABLE STATE (concurrency-safe) +#if FABLE_COMPILER +let newUnique = let i = ref 0L in fun () -> i := !i + 1L; !i +#else +let newUnique = let i = ref 0L in fun () -> System.Threading.Interlocked.Increment i +#endif + +/// Unique name generator for stamps attached to to val_specs, tycon_specs etc. +//++GLOBAL MUTABLE STATE (concurrency-safe) +#if FABLE_COMPILER +let newStamp = let i = ref 0L in fun () -> i := !i + 1L; !i +#else +let newStamp = let i = ref 0L in fun () -> System.Threading.Interlocked.Increment i +#endif diff --git a/src/fcs-fable/src/fsharp/ConstraintSolver.fs b/src/fcs-fable/src/fsharp/ConstraintSolver.fs old mode 100755 new mode 100644 index c274939156..bd6cf65b72 --- a/src/fcs-fable/src/fsharp/ConstraintSolver.fs +++ b/src/fcs-fable/src/fsharp/ConstraintSolver.fs @@ -27,9 +27,19 @@ // can-unify predicates used in method overload resolution and trait constraint // satisfaction. // +// The two main principles are: +// 1. Ensure any solution that is found is sound (no logic is skipped), +// 2. Because of method overloading and SRTP constraints and other constructs, processing of +// constraints is algorithmic and must proceed in a definite, fixed order. +// Once we start doing resolutions in a particular order we must keep doing them +// in the same order. +// +// There is little use of back-tracking/undo or "retry" in the constraint solver, except in the +// limited case ofs of SRTP solving and method overloading, and some other adhoc limited cases +// like checking for "printf" format strings. As a result there are cases involving +// method overloading and SRTP that the solver "can't solve". This is intentional and by-design. //------------------------------------------------------------------------- - module internal FSharp.Compiler.ConstraintSolver open Internal.Utilities.Collections @@ -37,19 +47,23 @@ open Internal.Utilities.Collections open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.Ast -open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Infos open FSharp.Compiler.AccessibilityLogic open FSharp.Compiler.AttributeChecking +open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features +open FSharp.Compiler.Import +open FSharp.Compiler.InfoReader +open FSharp.Compiler.Infos open FSharp.Compiler.Lib open FSharp.Compiler.MethodCalls open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps open FSharp.Compiler.Range open FSharp.Compiler.Rational -open FSharp.Compiler.InfoReader -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals open FSharp.Compiler.TypeRelations @@ -62,30 +76,35 @@ open FSharp.Compiler.TypeRelations let compgenId = mkSynId range0 unassignedTyparName let NewCompGenTypar (kind, rigid, staticReq, dynamicReq, error) = - NewTypar(kind, rigid, Typar(compgenId, staticReq, true), error, dynamicReq, [], false, false) + Construct.NewTypar(kind, rigid, Typar(compgenId, staticReq, true), error, dynamicReq, [], false, false) -let anon_id m = mkSynId m unassignedTyparName +let AnonTyparId m = mkSynId m unassignedTyparName let NewAnonTypar (kind, m, rigid, var, dyn) = - NewTypar (kind, rigid, Typar(anon_id m, var, true), false, dyn, [], false, false) + Construct.NewTypar (kind, rigid, Typar(AnonTyparId m, var, true), false, dyn, [], false, false) let NewNamedInferenceMeasureVar (_m, rigid, var, id) = - NewTypar(TyparKind.Measure, rigid, Typar(id, var, false), false, TyparDynamicReq.No, [], false, false) + Construct.NewTypar(TyparKind.Measure, rigid, Typar(id, var, false), false, TyparDynamicReq.No, [], false, false) -let NewInferenceMeasurePar () = NewCompGenTypar (TyparKind.Measure, TyparRigidity.Flexible, NoStaticReq, TyparDynamicReq.No, false) +let NewInferenceMeasurePar () = + NewCompGenTypar (TyparKind.Measure, TyparRigidity.Flexible, NoStaticReq, TyparDynamicReq.No, false) -let NewErrorTypar () = NewCompGenTypar (TyparKind.Type, TyparRigidity.Flexible, NoStaticReq, TyparDynamicReq.No, true) +let NewErrorTypar () = + NewCompGenTypar (TyparKind.Type, TyparRigidity.Flexible, NoStaticReq, TyparDynamicReq.No, true) -let NewErrorMeasureVar () = NewCompGenTypar (TyparKind.Measure, TyparRigidity.Flexible, NoStaticReq, TyparDynamicReq.No, true) +let NewErrorMeasureVar () = + NewCompGenTypar (TyparKind.Measure, TyparRigidity.Flexible, NoStaticReq, TyparDynamicReq.No, true) -let NewInferenceType () = mkTyparTy (NewTypar (TyparKind.Type, TyparRigidity.Flexible, Typar(compgenId, NoStaticReq, true), false, TyparDynamicReq.No, [], false, false)) +let NewInferenceType () = + mkTyparTy (Construct.NewTypar (TyparKind.Type, TyparRigidity.Flexible, Typar(compgenId, NoStaticReq, true), false, TyparDynamicReq.No, [], false, false)) -let NewErrorType () = mkTyparTy (NewErrorTypar ()) +let NewErrorType () = + mkTyparTy (NewErrorTypar ()) let NewErrorMeasure () = Measure.Var (NewErrorMeasureVar ()) let NewByRefKindInferenceType (g: TcGlobals) m = - let tp = NewTypar (TyparKind.Type, TyparRigidity.Flexible, Typar(compgenId, HeadTypeStaticReq, true), false, TyparDynamicReq.No, [], false, false) + let tp = Construct.NewTypar (TyparKind.Type, TyparRigidity.Flexible, Typar(compgenId, HeadTypeStaticReq, true), false, TyparDynamicReq.No, [], false, false) if g.byrefkind_InOut_tcr.CanDeref then tp.SetConstraints [TyparConstraint.DefaultsTo(10, TType_app(g.byrefkind_InOut_tcr, []), m)] mkTyparTy tp @@ -104,6 +123,7 @@ let FreshenAndFixupTypars m rigid fctps tinst tpsorig = tps, renaming, tinst let FreshenTypeInst m tpsorig = FreshenAndFixupTypars m TyparRigidity.Flexible [] [] tpsorig + let FreshMethInst m fctps tinst tpsorig = FreshenAndFixupTypars m TyparRigidity.Flexible fctps tinst tpsorig let FreshenTypars m tpsorig = @@ -117,7 +137,6 @@ let FreshenMethInfo m (minfo: MethInfo) = let _, _, tptys = FreshMethInst m (minfo.GetFormalTyparsOfDeclaringType m) minfo.DeclaringTypeInst minfo.FormalMethodTypars tptys - //------------------------------------------------------------------------- // Unification of types: solve/record equality constraints // Subsumption of types: solve/record subtyping constraints @@ -126,62 +145,106 @@ let FreshenMethInfo m (minfo: MethInfo) = [] /// Information about the context of a type equation. type ContextInfo = + /// No context was given. | NoContext + /// The type equation comes from an IF expression. | IfExpression of range + /// The type equation comes from an omitted else branch. | OmittedElseBranch of range + /// The type equation comes from a type check of the result of an else branch. | ElseBranchResult of range + /// The type equation comes from the verification of record fields. | RecordFields + /// The type equation comes from the verification of a tuple in record fields. | TupleInRecordFields + /// The type equation comes from a list or array constructor | CollectionElement of bool * range + /// The type equation comes from a return in a computation expression. + | ReturnInComputationExpression + /// The type equation comes from a yield in a computation expression. | YieldInComputationExpression + /// The type equation comes from a runtime type test. | RuntimeTypeTest of bool + /// The type equation comes from an downcast where a upcast could be used. | DowncastUsedInsteadOfUpcast of bool + /// The type equation comes from a return type of a pattern match clause (not the first clause). | FollowingPatternMatchClause of range + /// The type equation comes from a pattern match guard. | PatternMatchGuard of range + /// The type equation comes from a sequence expression. | SequenceExpression of TType -exception ConstraintSolverTupleDiffLengths of DisplayEnv * TType list * TType list * range * range -exception ConstraintSolverInfiniteTypes of ContextInfo * DisplayEnv * TType * TType * range * range -exception ConstraintSolverTypesNotInEqualityRelation of DisplayEnv * TType * TType * range * range * ContextInfo -exception ConstraintSolverTypesNotInSubsumptionRelation of DisplayEnv * TType * TType * range * range -exception ConstraintSolverMissingConstraint of DisplayEnv * Tast.Typar * Tast.TyparConstraint * range * range +/// Captures relevant information for a particular failed overload resolution. +type OverloadInformation = + { + methodSlot: CalledMeth + amap : ImportMap + error: exn + } + +/// Cases for overload resolution failure that exists in the implementation of the compiler. +type OverloadResolutionFailure = + | NoOverloadsFound of methodName: string + * candidates: OverloadInformation list + * cx: TraitConstraintInfo option + | PossibleCandidates of methodName: string + * candidates: OverloadInformation list // methodNames may be different (with operators?), this is refactored from original logic to assemble overload failure message + * cx: TraitConstraintInfo option + +exception ConstraintSolverTupleDiffLengths of displayEnv: DisplayEnv * TType list * TType list * range * range + +exception ConstraintSolverInfiniteTypes of displayEnv: DisplayEnv * contextInfo: ContextInfo * TType * TType * range * range + +exception ConstraintSolverTypesNotInEqualityRelation of displayEnv: DisplayEnv * TType * TType * range * range * ContextInfo + +exception ConstraintSolverTypesNotInSubsumptionRelation of displayEnv: DisplayEnv * argTy: TType * paramTy: TType * callRange: range * parameterRange: range + +exception ConstraintSolverMissingConstraint of displayEnv: DisplayEnv * Typar * TyparConstraint * range * range + exception ConstraintSolverError of string * range * range + exception ConstraintSolverRelatedInformation of string option * range * exn -exception ErrorFromApplyingDefault of TcGlobals * DisplayEnv * Tast.Typar * TType * exn * range -exception ErrorFromAddingTypeEquation of TcGlobals * DisplayEnv * TType * TType * exn * range -exception ErrorsFromAddingSubsumptionConstraint of TcGlobals * DisplayEnv * TType * TType * exn * ContextInfo * range -exception ErrorFromAddingConstraint of DisplayEnv * exn * range -exception PossibleOverload of DisplayEnv * string * exn * range -exception UnresolvedOverloading of DisplayEnv * exn list * string * range -exception UnresolvedConversionOperator of DisplayEnv * TType * TType * range +exception ErrorFromApplyingDefault of tcGlobals: TcGlobals * displayEnv: DisplayEnv * Typar * TType * exn * range + +exception ErrorFromAddingTypeEquation of tcGlobals: TcGlobals * displayEnv: DisplayEnv * actualTy: TType * expectedTy: TType * exn * range + +exception ErrorsFromAddingSubsumptionConstraint of tcGlobals: TcGlobals * displayEnv: DisplayEnv * actualTy: TType * expectedTy: TType * exn * ContextInfo * parameterRange: range + +exception ErrorFromAddingConstraint of displayEnv: DisplayEnv * exn * range + +exception UnresolvedOverloading of displayEnv: DisplayEnv * callerArgs: CallerArgs * failure: OverloadResolutionFailure * range -let GetPossibleOverloads amap m denv (calledMethGroup: (CalledMeth<_> * exn) list) = - calledMethGroup |> List.map (fun (cmeth, e) -> PossibleOverload(denv, NicePrint.stringOfMethInfo amap m denv cmeth.Method, e, m)) +exception UnresolvedConversionOperator of displayEnv: DisplayEnv * TType * TType * range type TcValF = (ValRef -> ValUseFlag -> TType list -> range -> Expr * TType) type ConstraintSolverState = { g: TcGlobals + amap: Import.ImportMap + InfoReader: InfoReader + + /// The function used to freshen values we encounter during trait constraint solving TcVal: TcValF + /// This table stores all unsolved, ungeneralized trait constraints, indexed by free type variable. /// That is, there will be one entry in this table for each free type variable in /// each outstanding, unsolved, ungeneralized trait constraint. Constraints are removed from the table and resolved @@ -196,34 +259,38 @@ type ConstraintSolverState = InfoReader = infoReader TcVal = tcVal } - type ConstraintSolverEnv = { SolverState: ConstraintSolverState + eContextInfo: ContextInfo + MatchingOnly: bool + m: range + EquivEnv: TypeEquivEnv + DisplayEnv: DisplayEnv } + member csenv.InfoReader = csenv.SolverState.InfoReader + member csenv.g = csenv.SolverState.g + member csenv.amap = csenv.SolverState.amap + override csenv.ToString() = " @ " + csenv.m.ToString() + let MakeConstraintSolverEnv contextInfo css m denv = { SolverState = css m = m eContextInfo = contextInfo - // Indicates that when unifiying ty1 = ty2, only type variables in ty1 may be solved + // Indicates that when unifying ty1 = ty2, only type variables in ty1 may be solved MatchingOnly = false EquivEnv = TypeEquivEnv.Empty DisplayEnv = denv } - -//------------------------------------------------------------------------- -// Occurs check -//------------------------------------------------------------------------- - /// Check whether a type variable occurs in the r.h.s. of a type, e.g. to catch /// infinite equations such as /// 'a = list<'a> @@ -243,6 +310,22 @@ let rec occursCheck g un ty = // Predicates on types //------------------------------------------------------------------------- +/// Some additional solutions are forced prior to generalization (permitWeakResolution=true). These are, roughly speaking, rules +/// for binary-operand constraints arising from constructs such as "1.0 + x" where "x" is an unknown type. THe constraint here +/// involves two type parameters - one for the left, and one for the right. The left is already known to be Double. +/// In this situation (and in the absence of other evidence prior to generalization), constraint solving forces an assumption that +/// the right is also Double - this is "weak" because there is only weak evidence for it. +/// +/// permitWeakResolution also applies to resolutions of multi-type-variable constraints via method overloads. Method overloading gets applied even if +/// only one of the two type variables is known. +/// +/// During code gen we run with permitWeakResolution on, but we only apply it where one of the argument types for the built-in constraint resolution is +/// a variable type. +type PermitWeakResolution = + | Yes + | No + member x.Permit = match x with Yes -> true | No -> false + let rec isNativeIntegerTy g ty = typeEquivAux EraseMeasures g g.nativeint_ty ty || typeEquivAux EraseMeasures g g.unativeint_ty ty || @@ -262,10 +345,10 @@ let isUnsignedIntegerTy g ty = typeEquivAux EraseMeasures g g.unativeint_ty ty || typeEquivAux EraseMeasures g g.uint64_ty ty -let rec isIntegerOrIntegerEnumTy g ty = +let rec IsIntegerOrIntegerEnumTy g ty = isSignedIntegerTy g ty || isUnsignedIntegerTy g ty || - (isEnumTy g ty && isIntegerOrIntegerEnumTy g (underlyingTypeOfEnumTy g ty)) + (isEnumTy g ty && IsIntegerOrIntegerEnumTy g (underlyingTypeOfEnumTy g ty)) let isIntegerTy g ty = isSignedIntegerTy g ty || @@ -286,10 +369,14 @@ let isFpTy g ty = let isDecimalTy g ty = typeEquivAux EraseMeasures g g.decimal_ty ty -let IsNonDecimalNumericOrIntegralEnumType g ty = isIntegerOrIntegerEnumTy g ty || isFpTy g ty +let IsNonDecimalNumericOrIntegralEnumType g ty = IsIntegerOrIntegerEnumTy g ty || isFpTy g ty + let IsNumericOrIntegralEnumType g ty = IsNonDecimalNumericOrIntegralEnumType g ty || isDecimalTy g ty + let IsNonDecimalNumericType g ty = isIntegerTy g ty || isFpTy g ty + let IsNumericType g ty = IsNonDecimalNumericType g ty || isDecimalTy g ty + let IsRelationalType g ty = IsNumericType g ty || isStringTy g ty || isCharTy g ty || isBoolTy g ty // Get measure of type, float<_> or float32<_> or decimal<_> but not float=float<1> or float32=float32<1> or decimal=decimal<1> @@ -301,6 +388,28 @@ let GetMeasureOfType g ty = | _ -> None | _ -> None +let IsCharOrStringType g ty = isCharTy g ty || isStringTy g ty + +/// Checks the argument type for a built-in solution to an op_Addition, op_Subtraction or op_Modulus constraint. +let IsAddSubModType nm g ty = IsNumericOrIntegralEnumType g ty || (nm = "op_Addition" && IsCharOrStringType g ty) + +/// Checks the argument type for a built-in solution to a bitwise operator constraint +let IsBitwiseOpType g ty = IsIntegerOrIntegerEnumTy g ty || (isEnumTy g ty) + +/// Check the other type in a built-in solution for a binary operator. +/// For weak resolution, require a relevant primitive on one side. +/// For strong resolution, a variable type is permitted. +let IsBinaryOpOtherArgType g permitWeakResolution ty = + match permitWeakResolution with + | PermitWeakResolution.No -> + not (isTyparTy g ty) + + | PermitWeakResolution.Yes -> true + +/// Checks the argument type for a built-in solution to a get_Sign constraint. +let IsSignType g ty = + isSignedIntegerTy g ty || isFpTy g ty || isDecimalTy g ty + type TraitConstraintSolution = | TTraitUnsolved | TTraitBuiltIn @@ -385,9 +494,46 @@ let ShowAccessDomain ad = //------------------------------------------------------------------------- // Solve -exception NonRigidTypar of DisplayEnv * string option * range * TType * TType * range -exception LocallyAbortOperationThatFailsToResolveOverload +exception NonRigidTypar of displayEnv: DisplayEnv * string option * range * TType * TType * range + +/// Signal that there is still an unresolved overload in the constraint problem. The +/// unresolved overload constraint remains in the constraint state, and we skip any +/// further processing related to whichever overall adjustment to constraint solver state +/// is being processed. +/// +// NOTE: The addition of this abort+skip appears to be a mistake which has crept into F# type inference, +// and its status is currently under review. See https://github.com/dotnet/fsharp/pull/8294 and others. +// +// Here is the history: +// 1. The local abort was added as part of an attempted performance optimization https://github.com/dotnet/fsharp/pull/1650 +// This change was released in the VS2017 GA release. +// +// 2. However, it also impacts the logic of type inference, by skipping checking. +// Because of this an attempt was made to revert it in https://github.com/dotnet/fsharp/pull/4173. +// +// Unfortunately, existing code had begun to depend on the new behaviours enabled by the +// change, and the revert was abandoned before release in https://github.com/dotnet/fsharp/pull/4348 +// +// Comments on soundness: +// The use of the abort is normally sound because the SRTP constraint +// will be subject to further processing at a later point. +// +// However, it seems likely that the abort may result in other processing associated +// with an overall constraint being skipped (e.g. the processing related to subsequent elements +// of a tuple constraint). +exception AbortForFailedOverloadResolution + +/// This is used at (nearly all) entry points into the constraint solver to make sure that the +/// AbortForFailedOverloadResolution is caught and processing continues. +let inline TryD_IgnoreAbortForFailedOverloadResolution f1 f2 = + TryD f1 (function AbortForFailedOverloadResolution -> CompleteD | exn -> f2 exn) + +/// used to provide detail about non matched argument in overload resolution error message +exception ArgDoesNotMatchError of error: ErrorsFromAddingSubsumptionConstraint * calledMeth: CalledMeth * calledArg: CalledArg * callerArg: CallerArg + +/// Represents a very local condition where we prefer to report errors before stripping type abbreviations. exception LocallyAbortOperationThatLosesAbbrevs + let localAbortD = ErrorD LocallyAbortOperationThatLosesAbbrevs /// Return true if we would rather unify this variable v1 := v2 than vice versa @@ -438,10 +584,10 @@ let FindPreferredTypar vs = let rec find vs = match vs with | [] -> vs - | (v: Typar, e)::vs -> + | (v: Typar, e) :: vs -> match find vs with | [] -> [(v, e)] - | (v', e')::vs' -> + | (v', e') :: vs' -> if PreferUnifyTypar v v' then (v, e) :: vs else (v', e') :: (v, e) :: vs' @@ -544,7 +690,7 @@ let UnifyMeasureWithOne (csenv: ConstraintSolverEnv) trace ms = // If there is at least one non-rigid variable v with exponent e, then we can unify match FindPreferredTypar nonRigidVars with - | (v, e)::vs -> + | (v, e) :: vs -> let unexpandedCons = ListMeasureConOccsWithNonZeroExponents csenv.g false ms let newms = ProdMeasures (List.map (fun (c, e') -> Measure.RationalPower (Measure.Con c, NegRational (DivRational e' e))) unexpandedCons @ List.map (fun (v, e') -> Measure.RationalPower (Measure.Var v, NegRational (DivRational e' e))) (vs @ rigidVars)) @@ -567,7 +713,7 @@ let SimplifyMeasure g vars ms = | [] -> (vars, None) - | (v, e)::vs -> + | (v, e) :: vs -> let newvar = if v.IsCompilerGenerated then NewAnonTypar (TyparKind.Measure, v.Range, TyparRigidity.Flexible, v.StaticReq, v.DynamicReq) else NewNamedInferenceMeasureVar (v.Range, TyparRigidity.Flexible, v.StaticReq, v.Id) let remainingvars = ListSet.remove typarEq v vars @@ -577,7 +723,7 @@ let SimplifyMeasure g vars ms = SubstMeasure v newms match vs with | [] -> (remainingvars, Some newvar) - | _ -> simp (newvar::remainingvars) + | _ -> simp (newvar :: remainingvars) simp vars // Normalize a type ty that forms part of a unit-of-measure-polymorphic type scheme. @@ -597,12 +743,12 @@ let rec SimplifyMeasuresInType g resultFirst ((generalizable, generalized) as pa let generalizable', newlygeneralized = SimplifyMeasure g generalizable unt match newlygeneralized with | None -> (generalizable', generalized) - | Some v -> (generalizable', v::generalized) + | Some v -> (generalizable', v :: generalized) and SimplifyMeasuresInTypes g param tys = match tys with | [] -> param - | ty::tys -> + | ty :: tys -> let param' = SimplifyMeasuresInType g false param ty SimplifyMeasuresInTypes g param' tys @@ -617,7 +763,7 @@ let SimplifyMeasuresInConstraint g param c = let rec SimplifyMeasuresInConstraints g param cs = match cs with | [] -> param - | c::cs -> + | c :: cs -> let param' = SimplifyMeasuresInConstraint g param c SimplifyMeasuresInConstraints g param' cs @@ -636,7 +782,7 @@ let rec GetMeasureVarGcdInType v ty = and GetMeasureVarGcdInTypes v tys = match tys with | [] -> ZeroRational - | ty::tys -> GcdRational (GetMeasureVarGcdInType v ty) (GetMeasureVarGcdInTypes v tys) + | ty :: tys -> GcdRational (GetMeasureVarGcdInType v ty) (GetMeasureVarGcdInTypes v tys) // Normalize the exponents on generalizable variables in a type // by dividing them by their "rational gcd". For example, the type @@ -652,7 +798,6 @@ let NormalizeExponentsInTypeScheme uvars ty = SubstMeasure v (Measure.RationalPower (Measure.Var v', DivRational OneRational expGcd)) v') - // We normalize unit-of-measure-polymorphic type schemes. There // are three reasons for doing this: // (1) to present concise and consistent type schemes to the programmer @@ -687,7 +832,7 @@ let SimplifyMeasuresInTypeScheme g resultFirst (generalizable: Typar list) ty co match uvars with | [] -> generalizable - | _::_ -> + | _ :: _ -> let (_, generalized) = SimplifyMeasuresInType g resultFirst (SimplifyMeasuresInConstraints g (uvars, []) constraints) ty let generalized' = NormalizeExponentsInTypeScheme generalized ty vars @ List.rev generalized' @@ -724,7 +869,7 @@ let rec SolveTyparEqualsType (csenv: ConstraintSolverEnv) ndeep m2 (trace: Optio // The types may still be equivalent due to abbreviations, which we are trying not to eliminate if typeEquiv csenv.g ty1 ty then () else // The famous 'occursCheck' check to catch "infinite types" like 'a = list<'a> - see also https://github.com/Microsoft/visualfsharp/issues/1170 - if occursCheck csenv.g r ty then return! ErrorD (ConstraintSolverInfiniteTypes(csenv.eContextInfo, csenv.DisplayEnv, ty1, ty, m, m2)) else + if occursCheck csenv.g r ty then return! ErrorD (ConstraintSolverInfiniteTypes(csenv.DisplayEnv, csenv.eContextInfo, ty1, ty, m, m2)) else // Note: warn _and_ continue! do! CheckWarnIfRigid csenv ty1 r ty // Record the solution before we solve the constraints, since @@ -732,28 +877,30 @@ let rec SolveTyparEqualsType (csenv: ConstraintSolverEnv) ndeep m2 (trace: Optio // Record a entry in the undo trace if one is provided trace.Exec (fun () -> r.typar_solution <- Some ty) (fun () -> r.typar_solution <- None) - (* dprintf "setting typar %d to type %s at %a\n" r.Stamp ((DebugPrint.showType ty)) outputRange m; *) - // Only solve constraints if this is not an error var if r.IsFromError then () else + // Check to see if this type variable is relevant to any trait constraints. // If so, re-solve the relevant constraints. if csenv.SolverState.ExtraCxs.ContainsKey r.Stamp then - do! RepeatWhileD ndeep (fun ndeep -> SolveRelevantMemberConstraintsForTypar csenv ndeep false trace r) + do! RepeatWhileD ndeep (fun ndeep -> SolveRelevantMemberConstraintsForTypar csenv ndeep PermitWeakResolution.No trace r) + // Re-solve the other constraints associated with this type variable return! solveTypMeetsTyparConstraints csenv ndeep m2 trace ty r | _ -> failwith "SolveTyparEqualsType" } - /// Apply the constraints on 'typar' to the type 'ty' and solveTypMeetsTyparConstraints (csenv: ConstraintSolverEnv) ndeep m2 trace ty (r: Typar) = trackErrors { let g = csenv.g + // Propagate compat flex requirements from 'tp' to 'ty' do! SolveTypIsCompatFlex csenv trace r.IsCompatFlex ty + // Propagate dynamic requirements from 'tp' to 'ty' do! SolveTypDynamicReq csenv trace r.DynamicReq ty + // Propagate static requirements from 'tp' to 'ty' do! SolveTypStaticReq csenv trace r.StaticReq ty @@ -782,7 +929,7 @@ and solveTypMeetsTyparConstraints (csenv: ConstraintSolverEnv) ndeep m2 trace ty | TyparConstraint.SimpleChoice(tys, m2) -> SolveTypeChoice csenv ndeep m2 trace ty tys | TyparConstraint.CoercesTo(ty2, m2) -> SolveTypeSubsumesTypeKeepAbbrevs csenv ndeep m2 trace None ty2 ty | TyparConstraint.MayResolveMember(traitInfo, m2) -> - SolveMemberConstraint csenv false false ndeep m2 trace traitInfo |> OperationResult.ignore + SolveMemberConstraint csenv false PermitWeakResolution.No ndeep m2 trace traitInfo |> OperationResult.ignore } @@ -791,10 +938,35 @@ and SolveAnonInfoEqualsAnonInfo (csenv: ConstraintSolverEnv) m2 (anonInfo1: Anon (match anonInfo1.Assembly, anonInfo2.Assembly with | ccu1, ccu2 -> if not (ccuEq ccu1 ccu2) then ErrorD (ConstraintSolverError(FSComp.SR.tcAnonRecdCcuMismatch(ccu1.AssemblyName, ccu2.AssemblyName), csenv.m,m2)) else ResultD () ) ++ (fun () -> + if not (anonInfo1.SortedNames = anonInfo2.SortedNames) then - let namesText1 = sprintf "%A" (Array.toList anonInfo1.SortedNames) - let namesText2 = sprintf "%A" (Array.toList anonInfo2.SortedNames) - ErrorD (ConstraintSolverError(FSComp.SR.tcAnonRecdFieldNameMismatch(namesText1, namesText2), csenv.m,m2)) + let (|Subset|Superset|Overlap|CompletelyDifferent|) (first, second) = + let first = Set first + let second = Set second + let secondOnly = Set.toList (second - first) + let firstOnly = Set.toList (first - second) + + if second.IsSubsetOf first then + Subset firstOnly + elif second.IsSupersetOf first then + Superset secondOnly + elif Set.intersect first second <> Set.empty then + Overlap(firstOnly, secondOnly) + else + CompletelyDifferent(Seq.toList first) + + let message = + match anonInfo1.SortedNames, anonInfo2.SortedNames with + | Subset missingFields -> + FSComp.SR.tcAnonRecdFieldNameSubset(string missingFields) + | Superset extraFields -> + FSComp.SR.tcAnonRecdFieldNameSuperset(string extraFields) + | Overlap (missingFields, extraFields) -> + FSComp.SR.tcAnonRecdFieldNameMismatch(string missingFields, string extraFields) + | CompletelyDifferent missingFields -> + FSComp.SR.tcAnonRecdFieldNameDifferent(string missingFields) + + ErrorD (ConstraintSolverError(message, csenv.m,m2)) else ResultD ()) @@ -860,8 +1032,9 @@ and private SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m2 trace cxsln t // Back out of expansions of type abbreviations to give improved error messages. // Note: any "normalization" of equations on type variables must respect the trace parameter TryD (fun () -> SolveTypeEqualsType csenv ndeep m2 trace cxsln ty1 ty2) - (function LocallyAbortOperationThatLosesAbbrevs -> ErrorD(ConstraintSolverTypesNotInEqualityRelation(csenv.DisplayEnv, ty1, ty2, csenv.m, m2, csenv.eContextInfo)) - | err -> ErrorD err) + (function + | LocallyAbortOperationThatLosesAbbrevs -> ErrorD(ConstraintSolverTypesNotInEqualityRelation(csenv.DisplayEnv, ty1, ty2, csenv.m, m2, csenv.eContextInfo)) + | err -> ErrorD err) and SolveTypeEqualsTypeEqns csenv ndeep m2 trace cxsln origl1 origl2 = match origl1, origl2 with @@ -871,7 +1044,7 @@ and SolveTypeEqualsTypeEqns csenv ndeep m2 trace cxsln origl1 origl2 = let rec loop l1 l2 = match l1, l2 with | [], [] -> CompleteD - | h1::t1, h2::t2 -> + | h1 :: t1, h2 :: t2 -> SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m2 trace cxsln h1 h2 ++ (fun () -> loop t1 t2) | _ -> ErrorD(ConstraintSolverTupleDiffLengths(csenv.DisplayEnv, origl1, origl2, csenv.m, m2)) @@ -899,6 +1072,7 @@ and SolveTypeSubsumesType (csenv: ConstraintSolverEnv) ndeep m2 (trace: Optional let amap = csenv.amap let aenv = csenv.EquivEnv let denv = csenv.DisplayEnv + match sty1, sty2 with | TType_var tp1, _ -> match aenv.EquivTypars.TryFind tp1 with @@ -914,15 +1088,19 @@ and SolveTypeSubsumesType (csenv: ConstraintSolverEnv) ndeep m2 (trace: Optional | TType_tuple (tupInfo1, l1), TType_tuple (tupInfo2, l2) -> if evalTupInfoIsStruct tupInfo1 <> evalTupInfoIsStruct tupInfo2 then ErrorD (ConstraintSolverError(FSComp.SR.tcTupleStructMismatch(), csenv.m, m2)) else SolveTypeEqualsTypeEqns csenv ndeep m2 trace cxsln l1 l2 (* nb. can unify since no variance *) + | TType_anon (anonInfo1, l1), TType_anon (anonInfo2, l2) -> SolveAnonInfoEqualsAnonInfo csenv m2 anonInfo1 anonInfo2 ++ (fun () -> SolveTypeEqualsTypeEqns csenv ndeep m2 trace cxsln l1 l2) (* nb. can unify since no variance *) + | TType_fun (d1, r1), TType_fun (d2, r2) -> SolveFunTypeEqn csenv ndeep m2 trace cxsln d1 d2 r1 r2 (* nb. can unify since no variance *) + | TType_measure ms1, TType_measure ms2 -> UnifyMeasures csenv trace ms1 ms2 // Enforce the identities float=float<1>, float32=float32<1> and decimal=decimal<1> | (_, TType_app (tc2, [ms])) when (tc2.IsMeasureableReprTycon && typeEquiv csenv.g sty1 (reduceTyconRefMeasureableOrProvided csenv.g tc2 [ms])) -> SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m2 trace cxsln ms (TType_measure Measure.One) + | (TType_app (tc2, [ms]), _) when (tc2.IsMeasureableReprTycon && typeEquiv csenv.g sty2 (reduceTyconRefMeasureableOrProvided csenv.g tc2 [ms])) -> SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m2 trace cxsln ms (TType_measure Measure.One) @@ -973,6 +1151,7 @@ and SolveTypeSubsumesType (csenv: ConstraintSolverEnv) ndeep m2 (trace: Optional let ty2arg = destArrayTy g ty2 SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m2 trace cxsln ty1arg ty2arg | _ -> error(InternalError("destArrayTy", m)) + | _ -> // D :> Head<_> --> C :> Head<_> for the // first interface or super-class C supported by D which @@ -984,14 +1163,14 @@ and SolveTypeSubsumesType (csenv: ConstraintSolverEnv) ndeep m2 (trace: Optional and SolveTypeSubsumesTypeKeepAbbrevs csenv ndeep m2 trace cxsln ty1 ty2 = let denv = csenv.DisplayEnv TryD (fun () -> SolveTypeSubsumesType csenv ndeep m2 trace cxsln ty1 ty2) - (function LocallyAbortOperationThatLosesAbbrevs -> ErrorD(ConstraintSolverTypesNotInSubsumptionRelation(denv, ty1, ty2, csenv.m, m2)) - | err -> ErrorD err) + (function + | LocallyAbortOperationThatLosesAbbrevs -> ErrorD(ConstraintSolverTypesNotInSubsumptionRelation(denv, ty1, ty2, csenv.m, m2)) + | err -> ErrorD err) //------------------------------------------------------------------------- // Solve and record non-equality constraints //------------------------------------------------------------------------- - and SolveTyparSubtypeOfType (csenv: ConstraintSolverEnv) ndeep m2 trace tp ty1 = let g = csenv.g if isObjTy g ty1 then CompleteD @@ -1019,16 +1198,9 @@ and SolveDimensionlessNumericType (csenv: ConstraintSolverEnv) ndeep m2 trace ty /// don't. The type-directed static optimization rules in the library code that makes use of this /// will deal with the problem. /// -/// 2. Some additional solutions are forced prior to generalization (permitWeakResolution=true). These are, roughly speaking, rules -/// for binary-operand constraints arising from constructs such as "1.0 + x" where "x" is an unknown type. THe constraint here -/// involves two type parameters - one for the left, and one for the right. The left is already known to be Double. -/// In this situation (and in the absence of other evidence prior to generalization), constraint solving forces an assumption that -/// the right is also Double - this is "weak" because there is only weak evidence for it. -/// -/// permitWeakResolution also applies to resolutions of multi-type-variable constraints via method overloads. Method overloading gets applied even if -/// only one of the two type variables is known -/// -and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload permitWeakResolution ndeep m2 trace (TTrait(tys, nm, memFlags, argtys, rty, sln)): OperationResult = trackErrors { +/// 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(tys, nm, memFlags, traitObjAndArgTys, rty, sln)) = traitInfo // Do not re-solve if already solved if sln.Value.IsSome then return true else let g = csenv.g @@ -1041,20 +1213,21 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload // Remove duplicates from the set of types in the support let tys = ListSet.setify (typeAEquiv g aenv) tys + // Rebuild the trait info after removing duplicates - let traitInfo = TTrait(tys, nm, memFlags, argtys, rty, sln) + let traitInfo = TTrait(tys, nm, memFlags, traitObjAndArgTys, rty, sln) let rty = GetFSharpViewOfReturnType g rty // Assert the object type if the constraint is for an instance member if memFlags.IsInstance then - match tys, argtys with + match tys, traitObjAndArgTys with | [ty], (h :: _) -> do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace h ty | _ -> do! ErrorD (ConstraintSolverError(FSComp.SR.csExpectedArguments(), m, m2)) // Trait calls are only supported on pseudo type (variables) for e in tys do - do! SolveTypStaticReq csenv trace HeadTypeStaticReq e + do! SolveTypStaticReq csenv trace HeadTypeStaticReq e - let argtys = if memFlags.IsInstance then List.tail argtys else argtys + let argtys = if memFlags.IsInstance then List.tail traitObjAndArgTys else traitObjAndArgTys let minfos = GetRelevantMethodsForTrait csenv permitWeakResolution nm traitInfo @@ -1088,11 +1261,9 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload // decimal<'u> * 'a (let checkRuleAppliesInPreferenceToMethods argty1 argty2 = // Check that at least one of the argument types is numeric - (IsNumericOrIntegralEnumType g argty1) && - // Check that the support of type variables is empty. That is, - // if we're canonicalizing, then having one of the types nominal is sufficient. - // If not, then both must be nominal (i.e. not a type variable). - (permitWeakResolution || not (isTyparTy g argty2)) && + IsNumericOrIntegralEnumType g argty1 && + // Check the other type is nominal, unless using weak resolution + IsBinaryOpOtherArgType g permitWeakResolution argty2 && // This next condition checks that either // - Neither type contributes any methods OR // - We have the special case "decimal<_> * decimal". In this case we have some @@ -1108,14 +1279,18 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace argty2 (mkAppTy tcref [TType_measure ms2]) do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty (mkAppTy tcref [TType_measure (Measure.Prod(ms1, if nm = "op_Multiply" then ms2 else Measure.Inv ms2))]) return TTraitBuiltIn + | _ -> + match GetMeasureOfType g argty2 with | Some (tcref, ms2) -> let ms1 = freshMeasure () do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace argty1 (mkAppTy tcref [TType_measure ms1]) do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty (mkAppTy tcref [TType_measure (Measure.Prod(ms1, if nm = "op_Multiply" then ms2 else Measure.Inv ms2))]) return TTraitBuiltIn + | _ -> + do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace argty2 argty1 do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty argty1 return TTraitBuiltIn @@ -1123,8 +1298,8 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload | _, _, false, ("op_Addition" | "op_Subtraction" | "op_Modulus"), [argty1;argty2] when // Ignore any explicit +/- overloads from any basic integral types (minfos |> List.forall (fun minfo -> isIntegerTy g minfo.ApparentEnclosingType ) && - ( (IsNumericOrIntegralEnumType g argty1 || (nm = "op_Addition" && (isCharTy g argty1 || isStringTy g argty1))) && (permitWeakResolution || not (isTyparTy g argty2)) - || (IsNumericOrIntegralEnumType g argty2 || (nm = "op_Addition" && (isCharTy g argty2 || isStringTy g argty2))) && (permitWeakResolution || not (isTyparTy g argty1)))) -> + ( IsAddSubModType nm g argty1 && IsBinaryOpOtherArgType g permitWeakResolution argty2 + || IsAddSubModType nm g argty2 && IsBinaryOpOtherArgType g permitWeakResolution argty1)) -> do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace argty2 argty1 do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty argty1 return TTraitBuiltIn @@ -1132,8 +1307,8 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload | _, _, false, ("op_LessThan" | "op_LessThanOrEqual" | "op_GreaterThan" | "op_GreaterThanOrEqual" | "op_Equality" | "op_Inequality" ), [argty1;argty2] when // Ignore any explicit overloads from any basic integral types (minfos |> List.forall (fun minfo -> isIntegerTy g minfo.ApparentEnclosingType ) && - ( (IsRelationalType g argty1 && (permitWeakResolution || not (isTyparTy g argty2))) - || (IsRelationalType g argty2 && (permitWeakResolution || not (isTyparTy g argty1))))) -> + ( IsRelationalType g argty1 && IsBinaryOpOtherArgType g permitWeakResolution argty2 + || IsRelationalType g argty2 && IsBinaryOpOtherArgType g permitWeakResolution argty1)) -> do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace argty2 argty1 do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty g.bool_ty return TTraitBuiltIn @@ -1151,21 +1326,21 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty ty return TTraitBuiltIn - | [], _, false, ("DivideByInt"), [argty1;argty2] + | [], _, false, "DivideByInt", [argty1;argty2] when isFpTy g argty1 || isDecimalTy g argty1 -> do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace argty2 g.int_ty do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty argty1 return TTraitBuiltIn // We pretend for uniformity that the 'string' and 'array' types have an indexer property called 'Item' - | [], [ty], true, ("get_Item"), [argty1] + | [], [ty], true, "get_Item", [argty1] when isStringTy g ty -> do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace argty1 g.int_ty do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty g.char_ty return TTraitBuiltIn - | [], [ty], true, ("get_Item"), argtys + | [], [ty], true, "get_Item", argtys when isArrayTy g ty -> if rankOfArrayTy g ty <> argtys.Length then do! ErrorD(ConstraintSolverError(FSComp.SR.csIndexArgumentMismatch((rankOfArrayTy g ty), argtys.Length), m, m2)) @@ -1175,7 +1350,7 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty ety return TTraitBuiltIn - | [], [ty], true, ("set_Item"), argtys + | [], [ty], true, "set_Item", argtys when isArrayTy g ty -> if rankOfArrayTy g ty <> argtys.Length - 1 then do! ErrorD(ConstraintSolverError(FSComp.SR.csIndexArgumentMismatch((rankOfArrayTy g ty), (argtys.Length - 1)), m, m2)) @@ -1187,8 +1362,8 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload return TTraitBuiltIn | [], _, false, ("op_BitwiseAnd" | "op_BitwiseOr" | "op_ExclusiveOr"), [argty1;argty2] - when (isIntegerOrIntegerEnumTy g argty1 || (isEnumTy g argty1)) && (permitWeakResolution || not (isTyparTy g argty2)) - || (isIntegerOrIntegerEnumTy g argty2 || (isEnumTy g argty2)) && (permitWeakResolution || not (isTyparTy g argty1)) -> + when IsBitwiseOpType g argty1 && IsBinaryOpOtherArgType g permitWeakResolution argty2 + || IsBitwiseOpType g argty2 && IsBinaryOpOtherArgType g permitWeakResolution argty1 -> do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace argty2 argty1 do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty argty1 @@ -1196,39 +1371,39 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload return TTraitBuiltIn | [], _, false, ("op_LeftShift" | "op_RightShift"), [argty1;argty2] - when isIntegerOrIntegerEnumTy g argty1 -> + when IsIntegerOrIntegerEnumTy g argty1 -> do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace argty2 g.int_ty do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty argty1 do! SolveDimensionlessNumericType csenv ndeep m2 trace argty1 return TTraitBuiltIn - | _, _, false, ("op_UnaryPlus"), [argty] + | _, _, false, "op_UnaryPlus", [argty] when IsNumericOrIntegralEnumType g argty -> do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty argty return TTraitBuiltIn - | _, _, false, ("op_UnaryNegation"), [argty] + | _, _, false, "op_UnaryNegation", [argty] when isSignedIntegerTy g argty || isFpTy g argty || isDecimalTy g argty -> do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty argty return TTraitBuiltIn - | _, _, true, ("get_Sign"), [] - when (let argty = tys.Head in isSignedIntegerTy g argty || isFpTy g argty || isDecimalTy g argty) -> + | _, _, true, "get_Sign", [] + when IsSignType g tys.Head -> do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty g.int32_ty return TTraitBuiltIn | _, _, false, ("op_LogicalNot" | "op_OnesComplement"), [argty] - when isIntegerOrIntegerEnumTy g argty -> + when IsIntegerOrIntegerEnumTy g argty -> do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty argty do! SolveDimensionlessNumericType csenv ndeep m2 trace argty return TTraitBuiltIn - | _, _, false, ("Abs"), [argty] + | _, _, false, "Abs", [argty] when isSignedIntegerTy g argty || isFpTy g argty || isDecimalTy g argty -> do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty argty @@ -1253,7 +1428,7 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty argty return TTraitBuiltIn - | _, _, false, ("op_Explicit"), [argty] + | _, _, false, "op_Explicit", [argty] when (// The input type. (IsNonDecimalNumericOrIntegralEnumType g argty || isStringTy g argty || isCharTy g argty) && // The output type @@ -1266,7 +1441,7 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload return TTraitBuiltIn - | _, _, false, ("op_Explicit"), [argty] + | _, _, false, "op_Explicit", [argty] when (// The input type. (IsNumericOrIntegralEnumType g argty || isStringTy g argty) && // The output type @@ -1282,7 +1457,7 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty argty1 return TTraitBuiltIn - | _, _, false, ("Atan2"), [argty1; argty2] + | _, _, false, "Atan2", [argty1; argty2] when isFpTy g argty1 -> do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace argty2 argty1 match GetMeasureOfType g argty1 with @@ -1367,13 +1542,17 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload // curried members may not be used to satisfy constraints |> List.choose (fun minfo -> if minfo.IsCurried then None else - let callerArgs = argtys |> List.map (fun argty -> CallerArg(argty, m, false, dummyExpr)) + let callerArgs = + { Unnamed = [ (argtys |> List.map (fun argty -> CallerArg(argty, m, false, dummyExpr))) ] + Named = [ [ ] ] } let minst = FreshenMethInfo m minfo let objtys = minfo.GetObjArgTypes(amap, m, minst) - Some(CalledMeth(csenv.InfoReader, None, false, FreshenMethInfo, m, AccessibleFromEverywhere, minfo, minst, minst, None, objtys, [(callerArgs, [])], false, false, None))) + Some(CalledMeth(csenv.InfoReader, None, false, FreshenMethInfo, m, AccessibleFromEverywhere, minfo, minst, minst, None, objtys, callerArgs, false, false, None))) let methOverloadResult, errors = - trace.CollectThenUndoOrCommit (fun (a, _) -> Option.isSome a) (fun trace -> ResolveOverloading csenv (WithTrace trace) nm ndeep (Some traitInfo) (0, 0) AccessibleFromEverywhere calledMethGroup false (Some rty)) + trace.CollectThenUndoOrCommit + (fun (a, _) -> Option.isSome a) + (fun trace -> ResolveOverloading csenv (WithTrace trace) nm ndeep (Some traitInfo) CallerArgs.Empty AccessibleFromEverywhere calledMethGroup false (Some rty)) match anonRecdPropSearch, recdPropSearch, methOverloadResult with | Some (anonInfo, tinst, i), None, None -> @@ -1411,7 +1590,7 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload // If there's nothing left to learn then raise the errors. // Note: we should likely call MemberConstraintIsReadyForResolution here when permitWeakResolution=false but for stability // reasons we use the more restrictive isNil frees. - if (permitWeakResolution && MemberConstraintIsReadyForWeakResolution csenv traitInfo) || isNil frees then + if (permitWeakResolution.Permit && MemberConstraintIsReadyForWeakResolution csenv traitInfo) || isNil frees then do! errors // Otherwise re-record the trait waiting for canonicalization else @@ -1419,7 +1598,7 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload match errors with | ErrorResult (_, UnresolvedOverloading _) when not ignoreUnresolvedOverload && (not (nm = "op_Explicit" || nm = "op_Implicit")) -> - return! ErrorD LocallyAbortOperationThatFailsToResolveOverload + return! ErrorD AbortForFailedOverloadResolution | _ -> return TTraitUnsolved } @@ -1464,10 +1643,13 @@ and MemberConstraintSolutionOfMethInfo css m minfo minst = let mref = IL.mkRefToILMethod (ilMeth.DeclaringTyconRef.CompiledRepresentationForNamedType, ilMeth.RawMetadata) let iltref = ilMeth.ILExtensionMethodDeclaringTyconRef |> Option.map (fun tcref -> tcref.CompiledRepresentationForNamedType) ILMethSln(ilMeth.ApparentEnclosingType, iltref, mref, minst) + | FSMeth(_, ty, vref, _) -> FSMethSln(ty, vref, minst) + | MethInfo.DefaultStructCtor _ -> error(InternalError("the default struct constructor was the unexpected solution to a trait constraint", m)) + #if !NO_EXTENSIONTYPING | ProvidedMeth(amap, mi, _, m) -> let g = amap.g @@ -1476,12 +1658,13 @@ and MemberConstraintSolutionOfMethInfo css m minfo minst = let objArgVars, objArgs = (if minfo.IsInstance then [mkLocal m "this" minfo.ApparentEnclosingType] else []) |> List.unzip let callMethInfoOpt, callExpr, callExprTy = ProvidedMethodCalls.BuildInvokerExpressionForProvidedMethodCall css.TcVal (g, amap, mi, objArgs, NeverMutates, false, ValUseFlag.NormalValUse, allArgs, m) let closedExprSln = ClosedExprSln (mkLambdas m [] (objArgVars@allArgVars) (callExpr, callExprTy) ) + // If the call is a simple call to an IL method with all the arguments in the natural order, then revert to use ILMethSln. // This is important for calls to operators on generated provided types. There is an (unchecked) condition // that generative providers do not re=order arguments or insert any more information into operator calls. match callMethInfoOpt, callExpr with - | Some methInfo, Expr.Op(TOp.ILCall(_useCallVirt, _isProtected, _, _isNewObj, NormalValUse, _isProp, _noTailCall, ilMethRef, _actualTypeInst, actualMethInst, _ilReturnTys), [], args, m) - when (args, (objArgVars@allArgVars)) ||> List.lengthsEqAndForall2 (fun a b -> match a with Expr.Val(v, _, _) -> valEq v.Deref b | _ -> false) -> + | Some methInfo, Expr.Op (TOp.ILCall (_useCallVirt, _isProtected, _, _isNewObj, NormalValUse, _isProp, _noTailCall, ilMethRef, _actualTypeInst, actualMethInst, _ilReturnTys), [], args, m) + when (args, (objArgVars@allArgVars)) ||> List.lengthsEqAndForall2 (fun a b -> match a with Expr.Val (v, _, _) -> valEq v.Deref b | _ -> false) -> let declaringType = Import.ImportProvidedType amap m (methInfo.PApply((fun x -> x.DeclaringType), m)) if isILAppTy g declaringType then let extOpt = None // EXTENSION METHODS FROM TYPE PROVIDERS: for extension methods coming from the type providers we would have something here. @@ -1500,16 +1683,16 @@ 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 nm (TTrait(tys, _, memFlags, argtys, rty, soln) as traitInfo): MethInfo list = +and GetRelevantMethodsForTrait (csenv: ConstraintSolverEnv) (permitWeakResolution: PermitWeakResolution) nm (TTrait(tys, _, memFlags, argtys, rty, soln) as traitInfo): MethInfo list = let results = - if permitWeakResolution || MemberConstraintSupportIsReadyForDeterminingOverloads csenv traitInfo then + if permitWeakResolution.Permit || MemberConstraintSupportIsReadyForDeterminingOverloads csenv traitInfo then let m = csenv.m let minfos = match memFlags.MemberKind with | MemberKind.Constructor -> tys |> List.map (GetIntrinsicConstructorInfosOfType csenv.SolverState.InfoReader m) | _ -> - tys |> List.map (GetIntrinsicMethInfosOfType csenv.SolverState.InfoReader (Some nm, AccessibleFromSomeFSharpCode, AllowMultiIntfInstantiations.Yes) IgnoreOverrides m) + tys |> List.map (GetIntrinsicMethInfosOfType csenv.SolverState.InfoReader (Some nm) AccessibleFromSomeFSharpCode AllowMultiIntfInstantiations.Yes IgnoreOverrides m) // Merge the sets so we don't get the same minfo from each side // We merge based on whether minfos use identical metadata or not. @@ -1524,6 +1707,7 @@ and GetRelevantMethodsForTrait (csenv: ConstraintSolverEnv) permitWeakResolution |> List.exists (fun minfo2 -> MethInfosEquivByNameAndSig EraseAll true csenv.g csenv.amap m minfo2 minfo1))) else [] + // The trait name "op_Explicit" also covers "op_Implicit", so look for that one too. if nm = "op_Explicit" then results @ GetRelevantMethodsForTrait csenv permitWeakResolution "op_Implicit" (TTrait(tys, "op_Implicit", memFlags, argtys, rty, soln)) @@ -1588,9 +1772,9 @@ and SolveRelevantMemberConstraintsForTypar (csenv: ConstraintSolverEnv) ndeep pe SolveMemberConstraint csenv true permitWeakResolution (ndeep+1) m2 trace traitInfo) and CanonicalizeRelevantMemberConstraints (csenv: ConstraintSolverEnv) ndeep trace tps = - SolveRelevantMemberConstraints csenv ndeep true trace tps + SolveRelevantMemberConstraints csenv ndeep PermitWeakResolution.Yes trace tps -and AddMemberConstraint (csenv: ConstraintSolverEnv) ndeep m2 trace traitInfo support frees = +and AddMemberConstraint (csenv: ConstraintSolverEnv) ndeep m2 (trace: OptionalTrace) traitInfo support (frees: Typar list) = let g = csenv.g let aenv = csenv.EquivEnv let cxst = csenv.SolverState.ExtraCxs @@ -1657,9 +1841,9 @@ and AddConstraint (csenv: ConstraintSolverEnv) ndeep m2 trace tp newConstraint // This works because the types on the r.h.s. of subtype // constraints are head-types and so any further inferences are equational. let collect ty = - let res = ref [] - IterateEntireHierarchyOfType (fun x -> res := x :: !res) g amap m AllowMultiIntfInstantiations.No ty - List.rev !res + let mutable res = [] + IterateEntireHierarchyOfType (fun x -> res <- x :: res) g amap m AllowMultiIntfInstantiations.No ty + List.rev res let parents1 = collect ty1 let parents2 = collect ty2 trackErrors { @@ -1775,7 +1959,7 @@ and AddConstraint (csenv: ConstraintSolverEnv) ndeep m2 trace tp newConstraint | cx :: rest -> let acc = if List.exists (fun cx2 -> implies cx2 cx) acc then acc - else (cx::acc) + else (cx :: acc) eliminateRedundant rest acc eliminateRedundant allCxs [] @@ -1813,7 +1997,7 @@ and SolveTypeSupportsComparison (csenv: ConstraintSolverEnv) ndeep m2 trace ty = AddConstraint csenv ndeep m2 trace destTypar (TyparConstraint.SupportsComparison m) | ValueNone -> // Check it isn't ruled out by the user - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref when HasFSharpAttribute g g.attrib_NoComparisonAttribute tcref.Attribs -> ErrorD (ConstraintSolverError(FSComp.SR.csTypeDoesNotSupportComparison1(NicePrint.minimalStringOfType denv ty), m, m2)) | _ -> @@ -1856,7 +2040,7 @@ and SolveTypeSupportsEquality (csenv: ConstraintSolverEnv) ndeep m2 trace ty = | ValueSome destTypar -> AddConstraint csenv ndeep m2 trace destTypar (TyparConstraint.SupportsEquality m) | _ -> - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref when HasFSharpAttribute g g.attrib_NoEqualityAttribute tcref.Attribs -> ErrorD (ConstraintSolverError(FSComp.SR.csTypeDoesNotSupportEquality1(NicePrint.minimalStringOfType denv ty), m, m2)) | _ -> @@ -1931,7 +2115,7 @@ and SolveTypeIsNonNullableValueType (csenv: ConstraintSolverEnv) ndeep m2 trace | _ -> let underlyingTy = stripTyEqnsAndMeasureEqns g ty if isStructTy g underlyingTy then - if tyconRefEq g g.system_Nullable_tcref (tcrefOfAppTy g underlyingTy) then + if isNullableTy g underlyingTy then return! ErrorD (ConstraintSolverError(FSComp.SR.csTypeParameterCannotBeNullable(), m, m)) else return! ErrorD (ConstraintSolverError(FSComp.SR.csGenericConstructRequiresStructType(NicePrint.minimalStringOfType denv ty), m, m2)) @@ -1990,13 +2174,13 @@ and SolveTypeRequiresDefaultConstructor (csenv: ConstraintSolverEnv) ndeep m2 tr if GetIntrinsicConstructorInfosOfType csenv.InfoReader m ty |> List.exists (fun x -> x.IsNullary && IsMethInfoAccessible amap m AccessibleFromEverywhere x) then - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref when HasFSharpAttribute g g.attrib_AbstractClassAttribute tcref.Attribs -> ErrorD (ConstraintSolverError(FSComp.SR.csGenericConstructRequiresNonAbstract(NicePrint.minimalStringOfType denv origTy), m, m2)) | _ -> CompleteD else - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref when tcref.PreEstablishedHasDefaultConstructor || // F# 3.1 feature: records with CLIMutable attribute should satisfy 'default constructor' constraint @@ -2042,8 +2226,8 @@ and CanMemberSigsMatchUpToCheck // Check all the argument types. if calledObjArgTys.Length <> callerObjArgTys.Length then - if (calledObjArgTys.Length <> 0) then - return! ErrorD(Error (FSComp.SR.csMemberIsNotStatic(minfo.LogicalName), m)) + if calledObjArgTys.Length <> 0 then + return! ErrorD(Error (FSComp.SR.csMemberIsNotStatic(minfo.LogicalName), m)) else return! ErrorD(Error (FSComp.SR.csMemberIsNotInstance(minfo.LogicalName), m)) else @@ -2057,7 +2241,7 @@ and CanMemberSigsMatchUpToCheck | Some calledArg -> if isArray1DTy g calledArg.CalledArgumentType then let paramArrayElemTy = destArrayTy g calledArg.CalledArgumentType - let reflArgInfo = calledArg.ReflArgInfo // propgate the reflected-arg info to each param array argument + let reflArgInfo = calledArg.ReflArgInfo // propagate the reflected-arg info to each param array argument match calledMeth.ParamArrayCallerArgs with | Some args -> for callerArg in args do @@ -2104,26 +2288,27 @@ and CanMemberSigsMatchUpToCheck // // "ty2 casts to ty1" // "a value of type ty2 can be used where a value of type ty1 is expected" -and private SolveTypeSubsumesTypeWithReport (csenv: ConstraintSolverEnv) ndeep m trace cxsln ty1 ty2 = - TryD (fun () -> SolveTypeSubsumesTypeKeepAbbrevs csenv ndeep m trace cxsln ty1 ty2) - (function - | LocallyAbortOperationThatFailsToResolveOverload -> CompleteD - | res -> - match csenv.eContextInfo with - | ContextInfo.RuntimeTypeTest isOperator -> - // test if we can cast other way around - match CollectThenUndo (fun newTrace -> SolveTypeSubsumesTypeKeepAbbrevs csenv ndeep m (OptionalTrace.WithTrace newTrace) cxsln ty2 ty1) with - | OkResult _ -> ErrorD (ErrorsFromAddingSubsumptionConstraint(csenv.g, csenv.DisplayEnv, ty1, ty2, res, ContextInfo.DowncastUsedInsteadOfUpcast isOperator, m)) - | _ -> ErrorD (ErrorsFromAddingSubsumptionConstraint(csenv.g, csenv.DisplayEnv, ty1, ty2, res, ContextInfo.NoContext, m)) - | _ -> ErrorD (ErrorsFromAddingSubsumptionConstraint(csenv.g, csenv.DisplayEnv, ty1, ty2, res, csenv.eContextInfo, m))) +and private SolveTypeSubsumesTypeWithWrappedContextualReport (csenv: ConstraintSolverEnv) ndeep m trace cxsln ty1 ty2 wrapper = + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> SolveTypeSubsumesTypeKeepAbbrevs csenv ndeep m trace cxsln ty1 ty2) + (fun res -> + match csenv.eContextInfo with + | ContextInfo.RuntimeTypeTest isOperator -> + // test if we can cast other way around + match CollectThenUndo (fun newTrace -> SolveTypeSubsumesTypeKeepAbbrevs csenv ndeep m (OptionalTrace.WithTrace newTrace) cxsln ty2 ty1) with + | OkResult _ -> ErrorD (wrapper (ErrorsFromAddingSubsumptionConstraint(csenv.g, csenv.DisplayEnv, ty1, ty2, res, ContextInfo.DowncastUsedInsteadOfUpcast isOperator, m))) + | _ -> ErrorD (wrapper (ErrorsFromAddingSubsumptionConstraint(csenv.g, csenv.DisplayEnv, ty1, ty2, res, ContextInfo.NoContext, m))) + | _ -> ErrorD (wrapper (ErrorsFromAddingSubsumptionConstraint(csenv.g, csenv.DisplayEnv, ty1, ty2, res, csenv.eContextInfo, m)))) +and private SolveTypeSubsumesTypeWithReport (csenv: ConstraintSolverEnv) ndeep m trace cxsln ty1 ty2 = + SolveTypeSubsumesTypeWithWrappedContextualReport (csenv) ndeep m trace cxsln ty1 ty2 id + // ty1: actual // ty2: expected and private SolveTypeEqualsTypeWithReport (csenv: ConstraintSolverEnv) ndeep m trace cxsln actual expected = - TryD (fun () -> SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m trace cxsln actual expected) - (function - | LocallyAbortOperationThatFailsToResolveOverload -> CompleteD - | res -> ErrorD (ErrorFromAddingTypeEquation(csenv.g, csenv.DisplayEnv, actual, expected, res, m))) + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m trace cxsln actual expected) + (fun res -> ErrorD (ErrorFromAddingTypeEquation(csenv.g, csenv.DisplayEnv, actual, expected, res, m))) and ArgsMustSubsumeOrConvert (csenv: ConstraintSolverEnv) @@ -2131,14 +2316,15 @@ and ArgsMustSubsumeOrConvert trace cxsln isConstraint + enforceNullableOptionalsKnownTypes // use known types from nullable optional args? (calledArg: CalledArg) (callerArg: CallerArg<'T>) = trackErrors { let g = csenv.g let m = callerArg.Range - let calledArgTy = AdjustCalledArgType csenv.InfoReader isConstraint calledArg callerArg - do! SolveTypeSubsumesTypeWithReport csenv ndeep m trace cxsln calledArgTy callerArg.Type - if calledArg.IsParamArray && isArray1DTy g calledArgTy && not (isArray1DTy g callerArg.Type) then + let calledArgTy = AdjustCalledArgType csenv.InfoReader isConstraint enforceNullableOptionalsKnownTypes calledArg callerArg + do! SolveTypeSubsumesTypeWithReport csenv ndeep m trace cxsln calledArgTy callerArg.CallerArgumentType + if calledArg.IsParamArray && isArray1DTy g calledArgTy && not (isArray1DTy g callerArg.CallerArgumentType) then return! ErrorD(Error(FSComp.SR.csMethodExpectsParams(), m)) else () } @@ -2149,15 +2335,15 @@ and MustUnify csenv ndeep trace cxsln ty1 ty2 = and MustUnifyInsideUndo csenv ndeep trace cxsln ty1 ty2 = SolveTypeEqualsTypeWithReport csenv ndeep csenv.m (WithTrace trace) cxsln ty1 ty2 -and ArgsMustSubsumeOrConvertInsideUndo (csenv: ConstraintSolverEnv) ndeep trace cxsln isConstraint calledArg (CallerArg(callerArgTy, m, _, _) as callerArg) = - let calledArgTy = AdjustCalledArgType csenv.InfoReader isConstraint calledArg callerArg - SolveTypeSubsumesTypeWithReport csenv ndeep m (WithTrace trace) cxsln calledArgTy callerArgTy +and ArgsMustSubsumeOrConvertInsideUndo (csenv: ConstraintSolverEnv) ndeep trace cxsln isConstraint calledMeth calledArg (CallerArg(callerArgTy, m, _, _) as callerArg) = + let calledArgTy = AdjustCalledArgType csenv.InfoReader isConstraint true calledArg callerArg + SolveTypeSubsumesTypeWithWrappedContextualReport csenv ndeep m (WithTrace trace) cxsln calledArgTy callerArgTy (fun e -> ArgDoesNotMatchError(e :?> _, calledMeth, calledArg, callerArg)) and TypesMustSubsumeOrConvertInsideUndo (csenv: ConstraintSolverEnv) ndeep trace cxsln m calledArgTy callerArgTy = SolveTypeSubsumesTypeWithReport csenv ndeep m trace cxsln calledArgTy callerArgTy and ArgsEquivInsideUndo (csenv: ConstraintSolverEnv) isConstraint calledArg (CallerArg(callerArgTy, m, _, _) as callerArg) = - let calledArgTy = AdjustCalledArgType csenv.InfoReader isConstraint calledArg callerArg + let calledArgTy = AdjustCalledArgType csenv.InfoReader isConstraint true calledArg callerArg if typeEquiv csenv.g calledArgTy callerArgTy then CompleteD else ErrorD(Error(FSComp.SR.csArgumentTypesDoNotMatch(), m)) and ReportNoCandidatesError (csenv: ConstraintSolverEnv) (nUnnamedCallerArgs, nNamedCallerArgs) methodName ad (calledMethGroup: CalledMeth<_> list) isSequential = @@ -2178,7 +2364,7 @@ and ReportNoCandidatesError (csenv: ConstraintSolverEnv) (nUnnamedCallerArgs, nN Error (FSComp.SR.csMemberIsNotAccessible(methodName, (ShowAccessDomain ad)), m) else Error (FSComp.SR.csMemberIsNotAccessible2(methodName, (ShowAccessDomain ad)), m) - | _, ([], (cmeth::_)), _, _, _ -> + | _, ([], (cmeth :: _)), _, _, _ -> // Check all the argument types. if cmeth.CalledObjArgTys(m).Length <> 0 then @@ -2193,12 +2379,11 @@ and ReportNoCandidatesError (csenv: ConstraintSolverEnv) (nUnnamedCallerArgs, nN match cmeth.UnassignedNamedArgs with | CallerNamedArg(id, _) :: _ -> if minfo.IsConstructor then - let predictFields() = - minfo.DeclaringTyconRef.AllInstanceFieldsAsList - |> List.map (fun p -> p.Name.Replace("@", "")) - |> System.Collections.Generic.HashSet + let suggestFields (addToBuffer: string -> unit) = + for p in minfo.DeclaringTyconRef.AllInstanceFieldsAsList do + addToBuffer(p.Name.Replace("@", "")) - ErrorWithSuggestions((msgNum, FSComp.SR.csCtorHasNoArgumentOrReturnProperty(methodName, id.idText, msgText)), id.idRange, id.idText, predictFields) + ErrorWithSuggestions((msgNum, FSComp.SR.csCtorHasNoArgumentOrReturnProperty(methodName, id.idText, msgText)), id.idRange, id.idText, suggestFields) else Error((msgNum, FSComp.SR.csMemberHasNoArgumentOrReturnProperty(methodName, id.idText, msgText)), id.idRange) | [] -> Error((msgNum, msgText), m) @@ -2290,7 +2475,7 @@ and ResolveOverloading methodName // The name of the method being called, for error reporting ndeep // Depth of inference cx // We're doing overload resolution as part of constraint solving, where special rules apply for op_Explicit and op_Implicit constraints. - callerArgCounts // How many named/unnamed args id the caller provide? + (callerArgs: CallerArgs) ad // The access domain of the caller, e.g. a module, type etc. calledMethGroup // The set of methods being called permitOptArgs // Can we supply optional arguments? @@ -2313,7 +2498,7 @@ and ResolveOverloading None, ErrorD (Error (FSComp.SR.csMethodNotFound(methodName), m)), NoTrace | _, [] when not isOpConversion -> - None, ReportNoCandidatesErrorExpr csenv callerArgCounts methodName ad calledMethGroup, NoTrace + None, ReportNoCandidatesErrorExpr csenv callerArgs.CallerArgCounts methodName ad calledMethGroup, NoTrace | _, _ -> @@ -2351,11 +2536,11 @@ and ResolveOverloading alwaysCheckReturn (MustUnifyInsideUndo csenv ndeep newTrace cxsln) (TypesMustSubsumeOrConvertInsideUndo csenv ndeep (WithTrace newTrace) cxsln m) - (ArgsMustSubsumeOrConvertInsideUndo csenv ndeep newTrace cxsln cx.IsSome) + (ArgsMustSubsumeOrConvertInsideUndo csenv ndeep newTrace cxsln cx.IsSome candidate) reqdRetTyOpt candidate) - let failOverloading (msg: string) errors = + let failOverloading overloadResolutionFailure = // Try to extract information to give better error for ambiguous op_Explicit and op_Implicit let convOpData = if isOpConversion then @@ -2370,11 +2555,8 @@ and ResolveOverloading | Some (fromTy, toTy) -> UnresolvedConversionOperator (denv, fromTy, toTy, m) | None -> - // Otherwise collect a list of possible overloads - let overloads = GetPossibleOverloads amap m denv errors - // if list of overloads is not empty - append line with "The available overloads are shown below..." - let msg = if isNil overloads then msg else sprintf "%s %s" msg (FSComp.SR.csSeeAvailableOverloads ()) - UnresolvedOverloading (denv, overloads, msg, m) + // Otherwise pass the overload resolution failure for error printing in CompileOps + UnresolvedOverloading (denv, callerArgs, overloadResolutionFailure, m) match applicable with | [] -> @@ -2390,13 +2572,14 @@ and ResolveOverloading alwaysCheckReturn (MustUnifyInsideUndo csenv ndeep newTrace cxsln) (TypesMustSubsumeOrConvertInsideUndo csenv ndeep (WithTrace newTrace) cxsln m) - (ArgsMustSubsumeOrConvertInsideUndo csenv ndeep newTrace cxsln cx.IsSome) + (ArgsMustSubsumeOrConvertInsideUndo csenv ndeep newTrace cxsln cx.IsSome calledMeth) reqdRetTyOpt calledMeth) with | OkResult _ -> None - | ErrorResult(_, exn) -> Some (calledMeth, exn)) + | ErrorResult(_warnings, exn) -> + Some {methodSlot = calledMeth; amap = amap; error = exn }) - None, ErrorD (failOverloading (FSComp.SR.csNoOverloadsFound methodName) errors), NoTrace + None, ErrorD (failOverloading (NoOverloadsFound (methodName, errors, cx))), NoTrace | [(calledMeth, warns, t)] -> Some calledMeth, OkResult (warns, ()), WithTrace t @@ -2425,7 +2608,7 @@ and ResolveOverloading (calledArg1.CalledArgumentType, calledArg2.CalledArgumentType) ||> compareCond (fun ty1 ty2 -> // Func<_> is always considered better than any other delegate type - match tryDestAppTy csenv.g ty1 with + match tryTcrefOfAppTy csenv.g ty1 with | ValueSome tcref1 when tcref1.DisplayName = "Func" && (match tcref1.PublicPath with Some p -> p.EnclosingPath = [| "System" |] | _ -> false) && @@ -2436,14 +2619,21 @@ and ResolveOverloading | _ when isInByrefTy csenv.g ty2 && typeEquiv csenv.g ty1 (destByrefTy csenv.g ty2) -> true + // T is always better than Nullable from F# 5.0 onwards + | _ when g.langVersion.SupportsFeature(Features.LanguageFeature.NullableOptionalInterop) && + isNullableTy csenv.g ty2 && + typeEquiv csenv.g ty1 (destNullableTy csenv.g ty2) -> + true + | _ -> false) if c <> 0 then c else 0 - let better (candidate: CalledMeth<_>, candidateWarnings, _) (other: CalledMeth<_>, otherwarnings, _) = + /// Check whether one overload is better than another + let better (candidate: CalledMeth<_>, candidateWarnings, _) (other: CalledMeth<_>, otherWarnings, _) = let candidateWarnCount = List.length candidateWarnings - let otherWarnCount = List.length otherwarnings + let otherWarnCount = List.length otherWarnings // Prefer methods that don't give "this code is less generic" warnings // Note: Relies on 'compare' respecting true > false let c = compare (candidateWarnCount = 0) (otherWarnCount = 0) @@ -2457,7 +2647,7 @@ and ResolveOverloading // Prefer methods with more precise param array arg type let c = if candidate.UsesParamArrayConversion && other.UsesParamArrayConversion then - compareTypes candidate.ParamArrayElementType other.ParamArrayElementType + compareTypes (candidate.GetParamArrayElementType()) (other.GetParamArrayElementType()) else 0 if c <> 0 then c else @@ -2472,7 +2662,7 @@ and ResolveOverloading let c = compare (not candidate.HasOptArgs) (not other.HasOptArgs) if c <> 0 then c else - // check regular args. The argument counts will only be different if one is using param args + // check regular unnamed args. The argument counts will only be different if one is using param args let c = if candidate.TotalNumUnnamedCalledArgs = other.TotalNumUnnamedCalledArgs then // For extension members, we also include the object argument type, if any in the comparison set @@ -2513,12 +2703,37 @@ and ResolveOverloading 0 if c <> 0 then c else - // Prefer non-generic methods // Note: Relies on 'compare' respecting true > false let c = compare candidate.CalledTyArgs.IsEmpty other.CalledTyArgs.IsEmpty if c <> 0 then c else + // F# 5.0 rule - prior to F# 5.0 named arguments (on the caller side) were not being taken + // into account when comparing overloads. So adding a name to an argument might mean + // overloads ould no longer be distinguished. We thus look at *all* arguments (whether + // optional or not) as an additional comparison technique. + let c = + if g.langVersion.SupportsFeature(Features.LanguageFeature.NullableOptionalInterop) then + let cs = + let args1 = candidate.AllCalledArgs |> List.concat + let args2 = other.AllCalledArgs |> List.concat + if args1.Length = args2.Length then + (args1, args2) ||> List.map2 compareArg + else + [] + // "all args are at least as good, and one argument is actually better" + if cs |> List.forall (fun x -> x >= 0) && cs |> List.exists (fun x -> x > 0) then + 1 + // "all args are at least as bad, and one argument is actually worse" + elif cs |> List.forall (fun x -> x <= 0) && cs |> List.exists (fun x -> x < 0) then + -1 + // "argument lists are incomparable" + else + 0 + else + 0 + if c <> 0 then c else + 0 @@ -2536,33 +2751,38 @@ and ResolveOverloading match bestMethods with | [(calledMeth, warns, t)] -> Some calledMeth, OkResult (warns, ()), WithTrace t | bestMethods -> - let methodNames = - let methods = - // use the most precise set - // - if after filtering bestMethods still contains something - use it - // - otherwise use applicableMeths or initial set of candidate methods - match bestMethods with - | [] -> - match applicableMeths with - | [] -> candidates - | m -> m |> List.map (fun (x, _, _) -> x) - | m -> m |> List.map (fun (x, _, _) -> x) - - methods - |> List.map (fun cmeth -> NicePrint.stringOfMethInfo amap m denv cmeth.Method) - |> List.sort - let msg = FSComp.SR.csMethodIsOverloaded methodName - let msg = - match methodNames with - | [] -> msg - | names -> sprintf "%s %s" msg (FSComp.SR.csCandidates (String.concat ", " names)) - None, ErrorD (failOverloading msg []), NoTrace + let methods = + let getMethodSlotsAndErrors methodSlot errors = + [ match errors with + | [] -> yield { methodSlot = methodSlot; error = Unchecked.defaultof; amap = amap } + | errors -> for error in errors do yield { methodSlot = methodSlot; error = error; amap = amap } ] + + + // use the most precise set + // - if after filtering bestMethods still contains something - use it + // - otherwise use applicableMeths or initial set of candidate methods + [ match bestMethods with + | [] -> + match applicableMeths with + | [] -> for methodSlot in candidates do yield getMethodSlotsAndErrors methodSlot [] + | m -> for (methodSlot, errors, _) in m do yield getMethodSlotsAndErrors methodSlot errors + | m -> for (methodSlot, errors, _) in m do yield getMethodSlotsAndErrors methodSlot errors ] + + let methods = List.concat methods + + None, ErrorD (failOverloading (PossibleCandidates(methodName, methods,cx))), NoTrace // If we've got a candidate solution: make the final checks - no undo here! // Allow subsumption on arguments. Include the return type. // Unify return types. match calledMethOpt with - | Some calledMeth -> + | Some calledMeth -> + + // Static IL interfaces methods are not supported in lower F# versions. + if calledMeth.Method.IsILMethod && not calledMeth.Method.IsInstance && isInterfaceTy g calledMeth.Method.ApparentEnclosingType then + tryLanguageFeatureRuntimeErrorRecover csenv.InfoReader LanguageFeature.DefaultInterfaceMemberConsumption m + tryLanguageFeatureErrorRecover g.langVersion LanguageFeature.DefaultInterfaceMemberConsumption m + calledMethOpt, trackErrors { do! errors @@ -2577,7 +2797,7 @@ and ResolveOverloading true (MustUnify csenv ndeep trace cxsln) (TypesMustSubsumeOrConvertInsideUndo csenv ndeep trace cxsln m)// REVIEW: this should not be an "InsideUndo" operation - (ArgsMustSubsumeOrConvert csenv ndeep trace cxsln cx.IsSome) + (ArgsMustSubsumeOrConvert csenv ndeep trace cxsln cx.IsSome true) reqdRetTyOpt calledMeth | WithTrace calledMethTrc -> @@ -2600,16 +2820,22 @@ and ResolveOverloading | None -> None, errors +let ResolveOverloadingForCall denv css m methodName ndeep cx callerArgs ad calledMethGroup permitOptArgs reqdRetTyOpt = + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + ResolveOverloading csenv NoTrace methodName ndeep cx callerArgs ad calledMethGroup permitOptArgs reqdRetTyOpt /// This is used before analyzing the types of arguments in a single overload resolution let UnifyUniqueOverloading - (csenv: ConstraintSolverEnv) + denv + css + m callerArgCounts methodName ad (calledMethGroup: CalledMeth list) reqdRetTy // The expected return type, if known = + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv let m = csenv.m // See what candidates we have based on name and arity let candidates = calledMethGroup |> List.filter (fun cmeth -> cmeth.IsCandidate(m, ad)) @@ -2624,7 +2850,7 @@ let UnifyUniqueOverloading true // always check return type (MustUnify csenv ndeep NoTrace None) (TypesMustSubsumeOrConvertInsideUndo csenv ndeep NoTrace None m) - (ArgsMustSubsumeOrConvert csenv ndeep NoTrace None false) // UnifyUniqueOverloading is not called in case of trait call - pass isConstraint=false + (ArgsMustSubsumeOrConvert csenv ndeep NoTrace None false false) // UnifyUniqueOverloading is not called in case of trait call - pass isConstraint=false (Some reqdRetTy) calledMeth return true @@ -2639,15 +2865,17 @@ let UnifyUniqueOverloading | _ -> ResultD false -let EliminateConstraintsForGeneralizedTypars csenv (trace: OptionalTrace) (generalizedTypars: Typars) = - // Remove the global constraints where this type variable appears in the support of the constraint - generalizedTypars - |> List.iter (fun tp -> +/// Remove the global constraints where these type variables appear in the support of the constraint +let EliminateConstraintsForGeneralizedTypars denv css m (trace: OptionalTrace) (generalizedTypars: Typars) = + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + for tp in generalizedTypars do let tpn = tp.Stamp let cxst = csenv.SolverState.ExtraCxs let cxs = cxst.FindAll tpn - cxs |> List.iter (fun cx -> trace.Exec (fun () -> cxst.Remove tpn) (fun () -> (csenv.SolverState.ExtraCxs.Add (tpn, cx)))) - ) + for cx in cxs do + trace.Exec + (fun () -> cxst.Remove tpn) + (fun () -> (csenv.SolverState.ExtraCxs.Add (tpn, cx))) //------------------------------------------------------------------------- @@ -2658,7 +2886,8 @@ let EliminateConstraintsForGeneralizedTypars csenv (trace: OptionalTrace) (gener //------------------------------------------------------------------------- let AddCxTypeEqualsType contextInfo denv css m actual expected = - SolveTypeEqualsTypeWithReport (MakeConstraintSolverEnv contextInfo css m denv) 0 m NoTrace None actual expected + let csenv = MakeConstraintSolverEnv contextInfo css m denv + SolveTypeEqualsTypeWithReport csenv 0 m NoTrace None actual expected |> RaiseOperationResult let UndoIfFailed f = @@ -2678,15 +2907,38 @@ let UndoIfFailed f = ReportWarnings warns true +let UndoIfFailedOrWarnings f = + let trace = Trace.New() + let res = + try + f trace + |> CheckNoErrorsAndGetWarnings + with e -> None + match res with + | Some [] -> + true + | _ -> + trace.Undo() + false + let AddCxTypeEqualsTypeUndoIfFailed denv css m ty1 ty2 = - UndoIfFailed (fun trace -> SolveTypeEqualsTypeKeepAbbrevs (MakeConstraintSolverEnv ContextInfo.NoContext css m denv) 0 m (WithTrace trace) ty1 ty2) + UndoIfFailed (fun trace -> + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + SolveTypeEqualsTypeKeepAbbrevs csenv 0 m (WithTrace trace) ty1 ty2) + +let AddCxTypeEqualsTypeUndoIfFailedOrWarnings denv css m ty1 ty2 = + UndoIfFailedOrWarnings (fun trace -> + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + SolveTypeEqualsTypeKeepAbbrevs csenv 0 m (WithTrace trace) ty1 ty2) let AddCxTypeEqualsTypeMatchingOnlyUndoIfFailed denv css m ty1 ty2 = let csenv = { MakeConstraintSolverEnv ContextInfo.NoContext css m denv with MatchingOnly = true } UndoIfFailed (fun trace -> SolveTypeEqualsTypeKeepAbbrevs csenv 0 m (WithTrace trace) ty1 ty2) let AddCxTypeMustSubsumeTypeUndoIfFailed denv css m ty1 ty2 = - UndoIfFailed (fun trace -> SolveTypeSubsumesTypeKeepAbbrevs (MakeConstraintSolverEnv ContextInfo.NoContext css m denv) 0 m (WithTrace trace) None ty1 ty2) + UndoIfFailed (fun trace -> + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + SolveTypeSubsumesTypeKeepAbbrevs csenv 0 m (WithTrace trace) None ty1 ty2) let AddCxTypeMustSubsumeTypeMatchingOnlyUndoIfFailed denv css m ty1 ty2 = let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv @@ -2694,188 +2946,160 @@ let AddCxTypeMustSubsumeTypeMatchingOnlyUndoIfFailed denv css m ty1 ty2 = UndoIfFailed (fun trace -> SolveTypeSubsumesTypeKeepAbbrevs csenv 0 m (WithTrace trace) None ty1 ty2) let AddCxTypeMustSubsumeType contextInfo denv css m trace ty1 ty2 = - SolveTypeSubsumesTypeWithReport (MakeConstraintSolverEnv contextInfo css m denv) 0 m trace None ty1 ty2 + let csenv = MakeConstraintSolverEnv contextInfo css m denv + SolveTypeSubsumesTypeWithReport csenv 0 m trace None ty1 ty2 |> RaiseOperationResult let AddCxMethodConstraint denv css m trace traitInfo = - TryD (fun () -> + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> trackErrors { do! - SolveMemberConstraint (MakeConstraintSolverEnv ContextInfo.NoContext css m denv) true false 0 m trace traitInfo + SolveMemberConstraint csenv true PermitWeakResolution.No 0 m trace traitInfo |> OperationResult.ignore }) - (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) + (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) |> RaiseOperationResult let AddCxTypeMustSupportNull denv css m trace ty = - TryD (fun () -> SolveTypeSupportsNull (MakeConstraintSolverEnv ContextInfo.NoContext css m denv) 0 m trace ty) - (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> SolveTypeSupportsNull csenv 0 m trace ty) + (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) |> RaiseOperationResult let AddCxTypeMustSupportComparison denv css m trace ty = - TryD (fun () -> SolveTypeSupportsComparison (MakeConstraintSolverEnv ContextInfo.NoContext css m denv) 0 m trace ty) - (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> SolveTypeSupportsComparison csenv 0 m trace ty) + (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) |> RaiseOperationResult let AddCxTypeMustSupportEquality denv css m trace ty = - TryD (fun () -> SolveTypeSupportsEquality (MakeConstraintSolverEnv ContextInfo.NoContext css m denv) 0 m trace ty) - (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> SolveTypeSupportsEquality csenv 0 m trace ty) + (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) |> RaiseOperationResult let AddCxTypeMustSupportDefaultCtor denv css m trace ty = - TryD (fun () -> SolveTypeRequiresDefaultConstructor (MakeConstraintSolverEnv ContextInfo.NoContext css m denv) 0 m trace ty) - (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> SolveTypeRequiresDefaultConstructor csenv 0 m trace ty) + (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) |> RaiseOperationResult let AddCxTypeIsReferenceType denv css m trace ty = - TryD (fun () -> SolveTypeIsReferenceType (MakeConstraintSolverEnv ContextInfo.NoContext css m denv) 0 m trace ty) - (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> SolveTypeIsReferenceType csenv 0 m trace ty) + (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) |> RaiseOperationResult let AddCxTypeIsValueType denv css m trace ty = - TryD (fun () -> SolveTypeIsNonNullableValueType (MakeConstraintSolverEnv ContextInfo.NoContext css m denv) 0 m trace ty) - (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> SolveTypeIsNonNullableValueType csenv 0 m trace ty) + (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) |> RaiseOperationResult let AddCxTypeIsUnmanaged denv css m trace ty = - TryD (fun () -> SolveTypeIsUnmanaged (MakeConstraintSolverEnv ContextInfo.NoContext css m denv) 0 m trace ty) - (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> SolveTypeIsUnmanaged csenv 0 m trace ty) + (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) |> RaiseOperationResult let AddCxTypeIsEnum denv css m trace ty underlying = - TryD (fun () -> SolveTypeIsEnum (MakeConstraintSolverEnv ContextInfo.NoContext css m denv) 0 m trace ty underlying) - (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> SolveTypeIsEnum csenv 0 m trace ty underlying) + (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) |> RaiseOperationResult let AddCxTypeIsDelegate denv css m trace ty aty bty = - TryD (fun () -> SolveTypeIsDelegate (MakeConstraintSolverEnv ContextInfo.NoContext css m denv) 0 m trace ty aty bty) - (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> SolveTypeIsDelegate csenv 0 m trace ty aty bty) + (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) + |> RaiseOperationResult + +let AddCxTyparDefaultsTo denv css m ctxtInfo tp ridx ty = + let csenv = MakeConstraintSolverEnv ctxtInfo css m denv + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> AddConstraint csenv 0 m NoTrace tp (TyparConstraint.DefaultsTo(ridx, ty, m))) + (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) |> RaiseOperationResult +let SolveTypeAsError denv css m ty = + let ty2 = NewErrorType () + assert((destTyparTy css.g ty2).IsFromError) + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + SolveTypeEqualsTypeKeepAbbrevs csenv 0 m NoTrace ty ty2 |> ignore + +let ApplyTyparDefaultAtPriority denv css priority (tp: Typar) = + tp.Constraints |> List.iter (fun tpc -> + match tpc with + | TyparConstraint.DefaultsTo(priority2, ty2, m) when priority2 = priority -> + let ty1 = mkTyparTy tp + if not tp.IsSolved && not (typeEquiv css.g ty1 ty2) then + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> + SolveTyparEqualsType csenv 0 m NoTrace ty1 ty2) + (fun res -> + SolveTypeAsError denv css m ty1 + ErrorD(ErrorFromApplyingDefault(css.g, denv, tp, ty2, res, m))) + |> RaiseOperationResult + | _ -> ()) + +let CreateCodegenState tcVal g amap = + { g = g + amap = amap + TcVal = tcVal + ExtraCxs = HashMultiMap(10, HashIdentity.Structural) + InfoReader = new InfoReader(g, amap) } + let CodegenWitnessThatTypeSupportsTraitConstraint tcVal g amap m (traitInfo: TraitConstraintInfo) argExprs = trackErrors { - let css = - { g = g - amap = amap - TcVal = tcVal - ExtraCxs = HashMultiMap(10, HashIdentity.Structural) - InfoReader = new InfoReader(g, amap) } + let css = CreateCodegenState tcVal g amap let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m (DisplayEnv.Empty g) - let! _res = SolveMemberConstraint csenv true true 0 m NoTrace traitInfo - let sln = - match traitInfo.Solution with - | None -> Choice5Of5() - | Some sln -> - match sln with - | ILMethSln(origTy, extOpt, mref, minst) -> - let metadataTy = convertToTypeWithMetadataIfPossible g origTy - let tcref = tcrefOfAppTy g metadataTy - let mdef = IL.resolveILMethodRef tcref.ILTyconRawMetadata mref - let ilMethInfo = - match extOpt with - | None -> MethInfo.CreateILMeth(amap, m, origTy, mdef) - | Some ilActualTypeRef -> - let actualTyconRef = Import.ImportILTypeRef amap m ilActualTypeRef - MethInfo.CreateILExtensionMeth(amap, m, origTy, actualTyconRef, None, mdef) - Choice1Of5 (ilMethInfo, minst) - | FSMethSln(ty, vref, minst) -> - Choice1Of5 (FSMeth(g, ty, vref, None), minst) - | FSRecdFieldSln(tinst, rfref, isSetProp) -> - Choice2Of5 (tinst, rfref, isSetProp) - | FSAnonRecdFieldSln(anonInfo, tinst, i) -> - Choice3Of5 (anonInfo, tinst, i) - | BuiltInSln -> - Choice5Of5 () - | ClosedExprSln expr -> - Choice4Of5 expr - return! - match sln with - | Choice1Of5(minfo, methArgTys) -> - let argExprs = - // FIX for #421894 - typechecker assumes that coercion can be applied for the trait calls arguments but codegen doesn't emit coercion operations - // result - generation of non-verifyable code - // fix - apply coercion for the arguments (excluding 'receiver' argument in instance calls) - - // flatten list of argument types (looks like trait calls with curried arguments are not supported so we can just convert argument list in straighforward way) - let argTypes = - minfo.GetParamTypes(amap, m, methArgTys) - |> List.concat - // do not apply coercion to the 'receiver' argument - let receiverArgOpt, argExprs = - if minfo.IsInstance then - match argExprs with - | h::t -> Some h, t - | argExprs -> None, argExprs - else None, argExprs - let convertedArgs = (argExprs, argTypes) ||> List.map2 (fun expr expectedTy -> mkCoerceIfNeeded g expectedTy (tyOfExpr g expr) expr) - match receiverArgOpt with - | Some r -> r::convertedArgs - | None -> convertedArgs - - // Fix bug 1281: If we resolve to an instance method on a struct and we haven't yet taken - // the address of the object then go do that - if minfo.IsStruct && minfo.IsInstance && (match argExprs with [] -> false | h :: _ -> not (isByrefTy g (tyOfExpr g h))) then - let h, t = List.headAndTail argExprs - let wrap, h', _readonly, _writeonly = mkExprAddrOfExpr g true false PossiblyMutates h None m - ResultD (Some (wrap (Expr.Op(TOp.TraitCall(traitInfo), [], (h' :: t), m)))) - else - ResultD (Some (MakeMethInfoCall amap m minfo methArgTys argExprs )) - - | Choice2Of5 (tinst, rfref, isSet) -> - let res = - match isSet, rfref.RecdField.IsStatic, argExprs.Length with - | true, true, 1 -> - Some (mkStaticRecdFieldSet (rfref, tinst, argExprs.[0], m)) - | true, false, 2 -> - // If we resolve to an instance field on a struct and we haven't yet taken - // the address of the object then go do that - if rfref.Tycon.IsStructOrEnumTycon && not (isByrefTy g (tyOfExpr g argExprs.[0])) then - let h = List.head argExprs - let wrap, h', _readonly, _writeonly = mkExprAddrOfExpr g true false DefinitelyMutates h None m - Some (wrap (mkRecdFieldSetViaExprAddr (h', rfref, tinst, argExprs.[1], m))) - else - Some (mkRecdFieldSetViaExprAddr (argExprs.[0], rfref, tinst, argExprs.[1], m)) - | false, true, 0 -> - Some (mkStaticRecdFieldGet (rfref, tinst, m)) - | false, false, 1 -> - if rfref.Tycon.IsStructOrEnumTycon && isByrefTy g (tyOfExpr g argExprs.[0]) then - Some (mkRecdFieldGetViaExprAddr (argExprs.[0], rfref, tinst, m)) - else - Some (mkRecdFieldGet g (argExprs.[0], rfref, tinst, m)) - | _ -> None - ResultD res - | Choice3Of5 (anonInfo, tinst, i) -> - let res = - let tupInfo = anonInfo.TupInfo - if evalTupInfoIsStruct tupInfo && isByrefTy g (tyOfExpr g argExprs.[0]) then - Some (mkAnonRecdFieldGetViaExprAddr (anonInfo, argExprs.[0], tinst, i, m)) - else - Some (mkAnonRecdFieldGet g (anonInfo, argExprs.[0], tinst, i, m)) - ResultD res - | Choice4Of5 expr -> ResultD (Some (MakeApplicationAndBetaReduce g (expr, tyOfExpr g expr, [], argExprs, m))) + let! _res = SolveMemberConstraint csenv true PermitWeakResolution.Yes 0 m NoTrace traitInfo - | Choice5Of5 () -> ResultD None + let sln = GenWitnessExpr amap g m traitInfo argExprs + return sln } - let ChooseTyparSolutionAndSolve css denv tp = let g = css.g let amap = css.amap let max, m = ChooseTyparSolutionAndRange g amap tp let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv - TryD (fun () -> SolveTyparEqualsType csenv 0 m NoTrace (mkTyparTy tp) max) - (fun err -> ErrorD(ErrorFromApplyingDefault(g, denv, tp, max, err, m))) + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> SolveTyparEqualsType csenv 0 m NoTrace (mkTyparTy tp) max) + (fun err -> ErrorD(ErrorFromApplyingDefault(g, denv, tp, max, err, m))) |> RaiseOperationResult - let CheckDeclaredTypars denv css m typars1 typars2 = - TryD (fun () -> + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> CollectThenUndo (fun trace -> - SolveTypeEqualsTypeEqns (MakeConstraintSolverEnv ContextInfo.NoContext css m denv) 0 m (WithTrace trace) None + SolveTypeEqualsTypeEqns csenv 0 m (WithTrace trace) None (List.map mkTyparTy typars1) (List.map mkTyparTy typars2))) - (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) + (fun res -> + ErrorD (ErrorFromAddingConstraint(denv, res, m))) + |> RaiseOperationResult + +let CanonicalizePartialInferenceProblem css denv m tps = + // Canonicalize constraints prior to generalization + let csenv = MakeConstraintSolverEnv ContextInfo.NoContext css m denv + TryD_IgnoreAbortForFailedOverloadResolution + (fun () -> CanonicalizeRelevantMemberConstraints csenv 0 NoTrace tps) + (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) |> RaiseOperationResult /// An approximation used during name resolution for intellisense to eliminate extension members which will not diff --git a/src/fcs-fable/src/fsharp/ConstraintSolver.fsi b/src/fcs-fable/src/fsharp/ConstraintSolver.fsi old mode 100755 new mode 100644 index 4626c736bd..2d1107b0a1 --- a/src/fcs-fable/src/fsharp/ConstraintSolver.fsi +++ b/src/fcs-fable/src/fsharp/ConstraintSolver.fsi @@ -5,93 +5,125 @@ module internal FSharp.Compiler.ConstraintSolver open FSharp.Compiler open FSharp.Compiler.AccessibilityLogic -open FSharp.Compiler.Ast open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Tast -open FSharp.Compiler.Range open FSharp.Compiler.Import -open FSharp.Compiler.Tastops -open FSharp.Compiler.TcGlobals open FSharp.Compiler.Infos -open FSharp.Compiler.MethodCalls open FSharp.Compiler.InfoReader +open FSharp.Compiler.MethodCalls +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TcGlobals +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 +val NewAnonTypar: TyparKind * range * TyparRigidity * TyparStaticReq * TyparDynamicReq -> Typar /// Create an inference type variable -val NewInferenceType : unit -> TType +val NewInferenceType: unit -> TType /// Create an inference type variable for the kind of a byref pointer -val NewByRefKindInferenceType : TcGlobals -> range -> TType +val NewByRefKindInferenceType: TcGlobals -> range -> TType /// Create an inference type variable representing an error condition when checking an expression -val NewErrorType : unit -> TType +val NewErrorType: unit -> TType /// Create an inference type variable representing an error condition when checking a measure -val NewErrorMeasure : unit -> Measure +val NewErrorMeasure: unit -> Measure /// Create a list of inference type variables, one for each element in the input list -val NewInferenceTypes : 'a list -> TType list +val NewInferenceTypes: 'a 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. -val FreshenAndFixupTypars : range -> TyparRigidity -> Typars -> TType list -> Typars -> Typars * TyparInst * TType list +val FreshenAndFixupTypars: range -> TyparRigidity -> Typars -> TType list -> Typars -> Typars * TyparInst * TType list -val FreshenTypeInst : range -> Typars -> Typars * TyparInst * TType list +val FreshenTypeInst: range -> Typars -> Typars * TyparInst * TType list -val FreshenTypars : range -> Typars -> TType list +val FreshenTypars: range -> Typars -> TType list -val FreshenMethInfo : range -> MethInfo -> TType list +val FreshenMethInfo: range -> MethInfo -> TType list [] /// Information about the context of a type equation. type ContextInfo = -/// No context was given. -| NoContext -/// The type equation comes from an IF expression. -| IfExpression of range -/// The type equation comes from an omitted else branch. -| OmittedElseBranch of range -/// The type equation comes from a type check of the result of an else branch. -| ElseBranchResult of range -/// The type equation comes from the verification of record fields. -| RecordFields -/// The type equation comes from the verification of a tuple in record fields. -| TupleInRecordFields -/// The type equation comes from a list or array constructor -| CollectionElement of bool * range -/// The type equation comes from a return in a computation expression. -| ReturnInComputationExpression -/// The type equation comes from a yield in a computation expression. -| YieldInComputationExpression -/// The type equation comes from a runtime type test. -| RuntimeTypeTest of bool -/// The type equation comes from an downcast where a upcast could be used. -| DowncastUsedInsteadOfUpcast of bool -/// The type equation comes from a return type of a pattern match clause (not the first clause). -| FollowingPatternMatchClause of range -/// The type equation comes from a pattern match guard. -| PatternMatchGuard of range -/// The type equation comes from a sequence expression. -| SequenceExpression of TType - -exception ConstraintSolverTupleDiffLengths of DisplayEnv * TType list * TType list * range * range -exception ConstraintSolverInfiniteTypes of ContextInfo * DisplayEnv * TType * TType * range * range -exception ConstraintSolverTypesNotInEqualityRelation of DisplayEnv * TType * TType * range * range * ContextInfo -exception ConstraintSolverTypesNotInSubsumptionRelation of DisplayEnv * TType * TType * range * range -exception ConstraintSolverMissingConstraint of DisplayEnv * Typar * TyparConstraint * range * range + + /// No context was given. + | NoContext + + /// The type equation comes from an IF expression. + | IfExpression of range + + /// The type equation comes from an omitted else branch. + | OmittedElseBranch of range + + /// The type equation comes from a type check of the result of an else branch. + | ElseBranchResult of range + + /// The type equation comes from the verification of record fields. + | RecordFields + + /// The type equation comes from the verification of a tuple in record fields. + | TupleInRecordFields + + /// The type equation comes from a list or array constructor + | CollectionElement of bool * range + + /// The type equation comes from a return in a computation expression. + | ReturnInComputationExpression + + /// The type equation comes from a yield in a computation expression. + | YieldInComputationExpression + + /// The type equation comes from a runtime type test. + | RuntimeTypeTest of bool + + /// The type equation comes from an downcast where a upcast could be used. + | DowncastUsedInsteadOfUpcast of bool + + /// The type equation comes from a return type of a pattern match clause (not the first clause). + | FollowingPatternMatchClause of range + + /// The type equation comes from a pattern match guard. + | PatternMatchGuard of range + + /// The type equation comes from a sequence expression. + | SequenceExpression of TType + +/// Captures relevant information for a particular failed overload resolution. +type OverloadInformation = + { + methodSlot: CalledMeth + amap : ImportMap + error: exn + } + +/// Cases for overload resolution failure that exists in the implementation of the compiler. +type OverloadResolutionFailure = + | NoOverloadsFound of methodName: string + * candidates: OverloadInformation list + * cx: TraitConstraintInfo option + | PossibleCandidates of methodName: string + * candidates: OverloadInformation list // methodNames may be different (with operators?), this is refactored from original logic to assemble overload failure message + * cx: TraitConstraintInfo option + +exception ConstraintSolverTupleDiffLengths of displayEnv: DisplayEnv * TType list * TType list * range * range +exception ConstraintSolverInfiniteTypes of displayEnv: DisplayEnv * contextInfo: ContextInfo * TType * TType * range * range +exception ConstraintSolverTypesNotInEqualityRelation of displayEnv: DisplayEnv * TType * TType * range * range * ContextInfo +exception ConstraintSolverTypesNotInSubsumptionRelation of displayEnv: DisplayEnv * argTy: TType * paramTy: TType * callRange: range * parameterRange: range +exception ConstraintSolverMissingConstraint of displayEnv: DisplayEnv * Typar * TyparConstraint * range * range exception ConstraintSolverError of string * range * range exception ConstraintSolverRelatedInformation of string option * range * exn -exception ErrorFromApplyingDefault of TcGlobals * DisplayEnv * Typar * TType * exn * range -exception ErrorFromAddingTypeEquation of TcGlobals * DisplayEnv * TType * TType * exn * range -exception ErrorsFromAddingSubsumptionConstraint of TcGlobals * DisplayEnv * TType * TType * exn * ContextInfo * range -exception ErrorFromAddingConstraint of DisplayEnv * exn * range -exception UnresolvedConversionOperator of DisplayEnv * TType * TType * range -exception PossibleOverload of DisplayEnv * string * exn * range -exception UnresolvedOverloading of DisplayEnv * exn list * string * range -exception NonRigidTypar of DisplayEnv * string option * range * TType * TType * range +exception ErrorFromApplyingDefault of tcGlobals: TcGlobals * displayEnv: DisplayEnv * Typar * TType * exn * range +exception ErrorFromAddingTypeEquation of tcGlobals: TcGlobals * displayEnv: DisplayEnv * actualTy: TType * expectedTy: TType * exn * range +exception ErrorsFromAddingSubsumptionConstraint of tcGlobals: TcGlobals * displayEnv: DisplayEnv * actualTy: TType * expectedTy: TType * exn * ContextInfo * parameterRange: range +exception ErrorFromAddingConstraint of displayEnv: DisplayEnv * exn * range +exception UnresolvedConversionOperator of displayEnv: DisplayEnv * TType * TType * range +exception UnresolvedOverloading of displayEnv: DisplayEnv * callerArgs: CallerArgs * failure: OverloadResolutionFailure * range +exception NonRigidTypar of displayEnv: DisplayEnv * string option * range * TType * TType * range + +exception ArgDoesNotMatchError of error: ErrorsFromAddingSubsumptionConstraint * calledMeth: CalledMeth * calledArg: CalledArg * callerArg: CallerArg /// A function that denotes captured tcVal, Used in constraint solver and elsewhere to get appropriate expressions for a ValRef. type TcValF = (ValRef -> ValUseFlag -> TType list -> range -> Expr * TType) @@ -99,49 +131,70 @@ type TcValF = (ValRef -> ValUseFlag -> TType list -> range -> Expr * TType) type ConstraintSolverState = static member New: TcGlobals * Import.ImportMap * InfoReader * TcValF -> ConstraintSolverState -type ConstraintSolverEnv - -val BakedInTraitConstraintNames : Set - -val MakeConstraintSolverEnv : ContextInfo -> ConstraintSolverState -> range -> DisplayEnv -> ConstraintSolverEnv +val BakedInTraitConstraintNames: Set [] type Trace type OptionalTrace = -| NoTrace -| WithTrace of Trace - -val SimplifyMeasuresInTypeScheme : TcGlobals -> bool -> Typars -> TType -> TyparConstraint list -> Typars -val SolveTyparEqualsType : ConstraintSolverEnv -> int -> range -> OptionalTrace -> TType -> TType -> OperationResult -val SolveTypeEqualsTypeKeepAbbrevs : ConstraintSolverEnv -> int -> range -> OptionalTrace -> TType -> TType -> OperationResult -val CanonicalizeRelevantMemberConstraints : ConstraintSolverEnv -> int -> OptionalTrace -> Typars -> OperationResult -val ResolveOverloading : ConstraintSolverEnv -> OptionalTrace -> string -> ndeep: int -> TraitConstraintInfo option -> int * int -> AccessorDomain -> CalledMeth list -> bool -> TType option -> CalledMeth option * OperationResult -val UnifyUniqueOverloading : ConstraintSolverEnv -> int * int -> string -> AccessorDomain -> CalledMeth list -> TType -> OperationResult -val EliminateConstraintsForGeneralizedTypars : ConstraintSolverEnv -> OptionalTrace -> Typars -> unit - -val CheckDeclaredTypars : DisplayEnv -> ConstraintSolverState -> range -> Typars -> Typars -> unit - -val AddConstraint : ConstraintSolverEnv -> int -> Range.range -> OptionalTrace -> Typar -> TyparConstraint -> OperationResult -val AddCxTypeEqualsType : ContextInfo -> DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> unit -val AddCxTypeEqualsTypeUndoIfFailed : DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> bool -val AddCxTypeEqualsTypeMatchingOnlyUndoIfFailed : DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> bool -val AddCxTypeMustSubsumeType : ContextInfo -> DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> TType -> unit -val AddCxTypeMustSubsumeTypeUndoIfFailed : DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> bool -val AddCxTypeMustSubsumeTypeMatchingOnlyUndoIfFailed : DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> bool -val AddCxMethodConstraint : DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TraitConstraintInfo -> unit -val AddCxTypeMustSupportNull : DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> unit -val AddCxTypeMustSupportComparison : DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> unit -val AddCxTypeMustSupportEquality : DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> unit -val AddCxTypeMustSupportDefaultCtor : DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> unit -val AddCxTypeIsReferenceType : DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> unit -val AddCxTypeIsValueType : DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> unit -val AddCxTypeIsUnmanaged : DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> unit -val AddCxTypeIsEnum : DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> TType -> unit -val AddCxTypeIsDelegate : DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> TType -> TType -> unit - -val CodegenWitnessThatTypeSupportsTraitConstraint : TcValF -> TcGlobals -> ImportMap -> range -> TraitConstraintInfo -> Expr list -> OperationResult - -val ChooseTyparSolutionAndSolve : ConstraintSolverState -> DisplayEnv -> Typar -> unit - -val IsApplicableMethApprox : TcGlobals -> ImportMap -> range -> MethInfo -> TType -> bool + | NoTrace + | WithTrace of Trace + +val SimplifyMeasuresInTypeScheme: TcGlobals -> bool -> Typars -> TType -> TyparConstraint list -> Typars + +val ResolveOverloadingForCall: DisplayEnv -> ConstraintSolverState -> range -> methodName: string -> ndeep: int -> cx: TraitConstraintInfo option -> callerArgs: CallerArgs -> AccessorDomain -> calledMethGroup: CalledMeth list -> permitOptArgs: bool -> reqdRetTyOpt: TType option -> CalledMeth option * OperationResult + +val UnifyUniqueOverloading: DisplayEnv -> ConstraintSolverState -> range -> int * int -> string -> AccessorDomain -> CalledMeth list -> TType -> OperationResult + +/// Remove the global constraints where these type variables appear in the support of the constraint +val EliminateConstraintsForGeneralizedTypars: DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> Typars -> unit + +val CheckDeclaredTypars: DisplayEnv -> ConstraintSolverState -> range -> Typars -> Typars -> unit + +val AddCxTypeEqualsType: ContextInfo -> DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> unit + +val AddCxTypeEqualsTypeUndoIfFailed: DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> bool + +val AddCxTypeEqualsTypeUndoIfFailedOrWarnings: DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> bool + +val AddCxTypeEqualsTypeMatchingOnlyUndoIfFailed: DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> bool + +val AddCxTypeMustSubsumeType: ContextInfo -> DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> TType -> unit + +val AddCxTypeMustSubsumeTypeUndoIfFailed: DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> bool + +val AddCxTypeMustSubsumeTypeMatchingOnlyUndoIfFailed: DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> bool + +val AddCxMethodConstraint: DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TraitConstraintInfo -> unit + +val AddCxTypeMustSupportNull: DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> unit + +val AddCxTypeMustSupportComparison: DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> unit + +val AddCxTypeMustSupportEquality: DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> unit + +val AddCxTypeMustSupportDefaultCtor: DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> unit + +val AddCxTypeIsReferenceType: DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> unit + +val AddCxTypeIsValueType: DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> unit + +val AddCxTypeIsUnmanaged: DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> unit + +val AddCxTypeIsEnum: DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> TType -> unit + +val AddCxTypeIsDelegate: DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> TType -> TType -> unit + +val AddCxTyparDefaultsTo: DisplayEnv -> ConstraintSolverState -> range -> ContextInfo -> Typar -> int -> TType -> unit + +val SolveTypeAsError: DisplayEnv -> ConstraintSolverState -> range -> TType -> unit + +val ApplyTyparDefaultAtPriority: DisplayEnv -> ConstraintSolverState -> priority: int -> Typar -> unit + +val CodegenWitnessThatTypeSupportsTraitConstraint: TcValF -> TcGlobals -> ImportMap -> range -> TraitConstraintInfo -> Expr list -> OperationResult + +val ChooseTyparSolutionAndSolve: ConstraintSolverState -> DisplayEnv -> Typar -> unit + +val IsApplicableMethApprox: TcGlobals -> ImportMap -> range -> MethInfo -> TType -> bool + +val CanonicalizePartialInferenceProblem: ConstraintSolverState -> DisplayEnv -> range -> Typars -> unit \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/DetupleArgs.fs b/src/fcs-fable/src/fsharp/DetupleArgs.fs old mode 100755 new mode 100644 index 7272e33983..511e5cdc03 --- a/src/fcs-fable/src/fsharp/DetupleArgs.fs +++ b/src/fcs-fable/src/fsharp/DetupleArgs.fs @@ -5,13 +5,14 @@ module internal FSharp.Compiler.Detuple open FSharp.Compiler open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.Ast -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.TcGlobals open FSharp.Compiler.Lib +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.XmlDoc -// // This pass has one aim. // - to eliminate tuples allocated at call sites (due to uncurried style) // @@ -150,14 +151,12 @@ let (|TyappAndApp|_|) e = match e with | Expr.App (f, fty, tys, args, m) -> match stripExpr f with - | Expr.App(f2, fty2, tys2, [], m2) -> Some(f2, fty2, tys2 @ tys, args, m2) + | Expr.App (f2, fty2, tys2, [], m2) -> Some(f2, fty2, tys2 @ tys, args, m2) | Expr.App _ -> Some(f, fty, tys, args, m) (* has args, so not combine ty args *) | f -> Some(f, fty, tys, args, m) | _ -> None -//------------------------------------------------------------------------- -// GetValsBoundInExpr -//------------------------------------------------------------------------- +[] module GlobalUsageAnalysis = let bindAccBounds vals (_isInDTree, v) = Zset.add v vals @@ -167,11 +166,6 @@ module GlobalUsageAnalysis = let z = FoldExpr folder z0 expr z - - //------------------------------------------------------------------------- - // GlobalUsageAnalysis - state and ops - //------------------------------------------------------------------------- - type accessor = TupleGet of int * TType list /// Expr information. @@ -199,12 +193,12 @@ module GlobalUsageAnalysis = TopLevelBindings = Zset.empty valOrder IterationIsAtTopLevel = true } - /// Log the use of a value with a particular tuple chape at a callsite + /// Log the use of a value with a particular tuple shape at a callsite /// Note: this routine is called very frequently let logUse (f: Val) tup z = {z with Uses = match Zmap.tryFind f z.Uses with - | Some sites -> Zmap.add f (tup::sites) z.Uses + | Some sites -> Zmap.add f (tup :: sites) z.Uses | None -> Zmap.add f [tup] z.Uses } /// Log the definition of a binding @@ -212,7 +206,6 @@ module GlobalUsageAnalysis = let z = if isInDTree then {z with DecisionTreeBindings = Zset.add v z.DecisionTreeBindings} else z let z = if z.IterationIsAtTopLevel then {z with TopLevelBindings = Zset.add v z.TopLevelBindings} else z z - /// Log the definition of a non-recursive binding let logNonRecBinding z (bind: Binding) = @@ -278,15 +271,15 @@ module GlobalUsageAnalysis = // NO: app but function is not val noInterceptF z origExpr - | Expr.Op(TOp.TupleFieldGet (tupInfo, n), ts, [x], _) when not (evalTupInfoIsStruct tupInfo) -> + | Expr.Op (TOp.TupleFieldGet (tupInfo, n), ts, [x], _) when not (evalTupInfoIsStruct tupInfo) -> let context = TupleGet (n, ts) :: context recognise context x // lambdas end top-level status - | Expr.Lambda(_id, _ctorThisValOpt, _baseValOpt, _vs, body, _, _) -> + | Expr.Lambda (_id, _ctorThisValOpt, _baseValOpt, _vs, body, _, _) -> foldUnderLambda exprF z body - | Expr.TyLambda(_id, _tps, body, _, _) -> + | Expr.TyLambda (_id, _tps, body, _, _) -> foldUnderLambda exprF z body | _ -> @@ -318,23 +311,13 @@ module GlobalUsageAnalysis = z -open GlobalUsageAnalysis - -//------------------------------------------------------------------------- -// misc -//------------------------------------------------------------------------- - let internalError str = raise(Failure(str)) let mkLocalVal m name ty topValInfo = - let compgen = false in (* REVIEW: review: should this be true? *) - NewVal(name, m, None, ty, Immutable, compgen, topValInfo, taccessPublic, ValNotInRecScope, None, NormalVal, [], ValInline.Optional, XmlDoc.Empty, false, false, false, false, false, false, None, ParentNone) - - -//------------------------------------------------------------------------- -// TupleStructure = tuple structure -//------------------------------------------------------------------------- + let compgen = false + Construct.NewVal(name, m, None, ty, Immutable, compgen, topValInfo, taccessPublic, ValNotInRecScope, None, NormalVal, [], ValInline.Optional, XmlDoc.Empty, false, false, false, false, false, false, None, ParentNone) +/// Represents inferred information about a tuple value type TupleStructure = | UnknownTS | TupleTS of TupleStructure list @@ -360,7 +343,7 @@ let checkTS = function /// explicit tuple-structure in expr let rec uncheckedExprTS expr = match expr with - | Expr.Op(TOp.Tuple tupInfo, _tys, args, _) when not (evalTupInfoIsStruct tupInfo) -> + | Expr.Op (TOp.Tuple tupInfo, _tys, args, _) when not (evalTupInfoIsStruct tupInfo) -> TupleTS (List.map uncheckedExprTS args) | _ -> UnknownTS @@ -379,7 +362,7 @@ let rebuildTS g m ts vs = let rec rebuild vs ts = match vs, ts with | [], UnknownTS -> internalError "rebuildTS: not enough fringe to build tuple" - | v::vs, UnknownTS -> (exprForVal m v, v.Type), vs + | v :: vs, UnknownTS -> (exprForVal m v, v.Type), vs | vs, TupleTS tss -> let xtys, vs = List.mapFold rebuild vs tss let xs, tys = List.unzip xtys @@ -405,20 +388,20 @@ let inline isTrivialCP xs = isNil xs let rec minimalCallPattern callPattern = match callPattern with | [] -> [] - | UnknownTS::tss -> + | UnknownTS :: tss -> match minimalCallPattern tss with | [] -> [] (* drop trailing UnknownTS *) - | tss -> UnknownTS::tss (* non triv tss tail *) - | (TupleTS ts)::tss -> TupleTS ts :: minimalCallPattern tss + | tss -> UnknownTS :: tss (* non triv tss tail *) + | (TupleTS ts) :: tss -> TupleTS ts :: minimalCallPattern tss /// Combines a list of callpatterns into one common callpattern. let commonCallPattern callPatterns = let rec andCPs cpA cpB = match cpA, cpB with | [], [] -> [] - | tsA::tsAs, tsB::tsBs -> andTS tsA tsB :: andCPs tsAs tsBs - | _tsA::_tsAs, [] -> [] (* now trim to shortest - UnknownTS :: andCPs tsAs [] *) - | [], _tsB::_tsBs -> [] (* now trim to shortest - UnknownTS :: andCPs [] tsBs *) + | tsA :: tsAs, tsB :: tsBs -> andTS tsA tsB :: andCPs tsAs tsBs + | _tsA :: _tsAs, [] -> [] (* now trim to shortest - UnknownTS :: andCPs tsAs [] *) + | [], _tsB :: _tsBs -> [] (* now trim to shortest - UnknownTS :: andCPs [] tsBs *) List.reduce andCPs callPatterns @@ -484,8 +467,11 @@ let mkTransform g (f: Val) m tps x1Ntys rty (callPattern, tyfringes: (TType list let tys1r = List.collect fst tyfringes (* types for collapsed initial r args *) let tysrN = List.drop tyfringes.Length x1Ntys (* types for remaining args *) let argtys = tys1r @ tysrN - let fCty = mkLambdaTy tps argtys rty - let transformedVal = mkLocalVal f.Range (globalNng.FreshCompilerGeneratedName (f.LogicalName, f.Range)) fCty topValInfo + let fCty = mkLambdaTy tps argtys rty + let transformedVal = + // Ensure that we have an g.CompilerGlobalState + assert(g.CompilerGlobalState |> Option.isSome) + mkLocalVal f.Range (g.CompilerGlobalState.Value.NiceNameGenerator.FreshCompilerGeneratedName (f.LogicalName, f.Range)) fCty topValInfo { transformCallPattern = callPattern transformedFormals = transformedFormals transformedVal = transformedVal } @@ -532,7 +518,7 @@ let decideFormalSuggestedCP g z tys vss = match ts, accessors with | UnknownTS, _ -> UnknownTS | TupleTS _tss, [] -> UnknownTS (* trim it, require the val at this point *) - | TupleTS tss, TupleGet (i, _ty)::accessors -> + | TupleTS tss, TupleGet (i, _ty) :: accessors -> let tss = List.mapNth i (trimTsByAccess accessors) tss TupleTS tss @@ -607,7 +593,7 @@ let determineTransforms g (z : GlobalUsageAnalysis.Results) = let tps, vss, _b, rty = stripTopLambda (e, f.Type) match List.concat vss with | [] -> None // defn has no term args - | arg1::_ -> // consider f + | arg1 :: _ -> // consider f let m = arg1.Range // mark of first arg, mostly for error reporting let callPatterns = sitesCPs sites // callPatterns from sites decideTransform g z f callPatterns (m, tps, vss, rty) // make transform (if required) @@ -616,17 +602,16 @@ let determineTransforms g (z : GlobalUsageAnalysis.Results) = let vtransforms = Zmap.ofList valOrder vtransforms vtransforms - - //------------------------------------------------------------------------- // pass - penv - env of pass //------------------------------------------------------------------------- type penv = - { // The planned transforms - transforms : Zmap - ccu : CcuThunk - g : TcGlobals } + { // The planned transforms + transforms: Zmap + ccu: CcuThunk + g: TcGlobals + } let hasTransfrom penv f = Zmap.tryFind f penv.transforms @@ -641,17 +626,26 @@ let hasTransfrom penv f = Zmap.tryFind f penv.transforms *) type env = - { eg : TcGlobals - prefix : string - m : Range.range } + { + eg: TcGlobals + + prefix: string + + m: Range.range + } + + override __.ToString() = "" let suffixE env s = {env with prefix = env.prefix + s} + let rangeE env m = {env with m = m} -let push b bs = b::bs +let push b bs = b :: bs + let pushL xs bs = xs@bs let newLocal env ty = mkCompGenLocal env.m env.prefix ty + let newLocalN env i ty = mkCompGenLocal env.m (env.prefix + string i) ty let noEffectExpr env bindings x = @@ -671,7 +665,7 @@ let buildProjections env bindings x xtys = xtys |> List.mapi (fun i xty -> let vi, vix = newLocalN env i xty - let bind = mkBind NoSequencePointAtInvisibleBinding vi (mkTupleFieldGet env.eg (tupInfoRef, x, xtys, i, env.m)) + let bind = mkBind NoDebugPointAtInvisibleBinding vi (mkTupleFieldGet env.eg (tupInfoRef, x, xtys, i, env.m)) bind, vix) |> List.unzip @@ -686,7 +680,7 @@ let rec collapseArg env bindings ts (x: Expr) = | UnknownTS, x -> let bindings, vx = noEffectExpr env bindings x bindings, [vx] - | TupleTS tss, Expr.Op(TOp.Tuple tupInfo, _xtys, xs, _) when not (evalTupInfoIsStruct tupInfo) -> + | TupleTS tss, Expr.Op (TOp.Tuple tupInfo, _xtys, xs, _) when not (evalTupInfoIsStruct tupInfo) -> let env = suffixE env "'" collapseArgs env bindings 1 tss xs | TupleTS tss, x -> @@ -701,15 +695,14 @@ let rec collapseArg env bindings ts (x: Expr) = and collapseArgs env bindings n (callPattern) args = match callPattern, args with | [], args -> bindings, args - | ts::tss, arg::args -> + | ts :: tss, arg :: args -> let env1 = suffixE env (string n) let bindings, xty = collapseArg env1 bindings ts arg let bindings, xtys = collapseArgs env bindings (n+1) tss args bindings, xty @ xtys - | _ts::_tss, [] -> + | _ts :: _tss, [] -> internalError "collapseArgs: CallPattern longer than callsite args. REPORT BUG" - //------------------------------------------------------------------------- // pass - app fixup //------------------------------------------------------------------------- @@ -742,7 +735,6 @@ let fixupApp (penv: penv) (fx, fty, tys, args, m) = | _ -> Expr.App (fx, fty, tys, args, m) (* no change, f is expr *) - //------------------------------------------------------------------------- // pass - mubinds - translation support //------------------------------------------------------------------------- @@ -850,21 +842,20 @@ let postTransformExpr (penv: penv) expr = Some (fixupApp penv (f, fty, tys, args, m) ) | _ -> None - let passImplFile penv assembly = - assembly |> RewriteImplFile {PreIntercept =None - PreInterceptBinding=None - PostTransform= postTransformExpr penv - IsUnderQuotations=false } - + assembly |> RewriteImplFile { PreIntercept =None + PreInterceptBinding=None + PostTransform= postTransformExpr penv + IsUnderQuotations=false } //------------------------------------------------------------------------- // entry point //------------------------------------------------------------------------- let DetupleImplFile ccu g expr = - // collect expr info - wanting usage contexts and bindings - let (z : Results) = GetUsageInfoOfImplFile g expr + // Collect expr info - wanting usage contexts and bindings + let z = GetUsageInfoOfImplFile g expr + // For each Val, decide Some "transform", or None if not changing let vtrans = determineTransforms g z diff --git a/src/fcs-fable/src/fsharp/DetupleArgs.fsi b/src/fcs-fable/src/fsharp/DetupleArgs.fsi old mode 100755 new mode 100644 index c76c02b1c4..e830b97200 --- a/src/fcs-fable/src/fsharp/DetupleArgs.fsi +++ b/src/fcs-fable/src/fsharp/DetupleArgs.fsi @@ -3,13 +3,13 @@ module internal FSharp.Compiler.Detuple open FSharp.Compiler.AbstractIL.Internal -open FSharp.Compiler.Tast open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypedTree -val DetupleImplFile : CcuThunk -> TcGlobals -> TypedImplFile -> TypedImplFile +val DetupleImplFile: CcuThunk -> TcGlobals -> TypedImplFile -> TypedImplFile module GlobalUsageAnalysis = - val GetValsBoundInExpr : Expr -> Zset + val GetValsBoundInExpr: Expr -> Zset type accessor @@ -17,17 +17,24 @@ module GlobalUsageAnalysis = /// This could extend to be a full graph view of the expr. /// Later could support "safe" change operations, and optimisations could be in terms of those. type Results = - { /// v -> context / APP inst args - Uses : Zmap; + { + /// v -> context / APP inst args + Uses: Zmap + /// v -> binding repr - Defns : Zmap; + Defns: Zmap + /// bound in a decision tree? - DecisionTreeBindings : Zset; + DecisionTreeBindings: Zset + /// v -> recursive? * v list -- the others in the mutual binding - RecursiveBindings : Zmap; + RecursiveBindings: Zmap + /// val not defined under lambdas - TopLevelBindings : Zset; + TopLevelBindings: Zset + /// top of expr toplevel? (true) - IterationIsAtTopLevel : bool; + IterationIsAtTopLevel: bool } - val GetUsageInfoOfImplFile : TcGlobals -> TypedImplFile -> Results + + val GetUsageInfoOfImplFile: TcGlobals -> TypedImplFile -> Results diff --git a/src/fcs-fable/src/fsharp/Directory.Nuget.props b/src/fcs-fable/src/fsharp/Directory.Nuget.props deleted file mode 100644 index 6521936cfe..0000000000 --- a/src/fcs-fable/src/fsharp/Directory.Nuget.props +++ /dev/null @@ -1,27 +0,0 @@ - - - - https://github.com/Microsoft/visualfsharp/blob/master/License.txt - https://github.com/Microsoft/visualfsharp - Microsoft and F# Software Foundation - Microsoft and F# Software Foundation - Visual F# Compiler FSharp functional programming - (C) Microsoft Corporation. All rights reserved. - - $(GitHeadSha) - [developer build] - - - licenseUrl=$(PackageLicenceUrl); - authors=$(PackageAuthors); - owners=$(PackageOwners); - projectUrl=$(PackageProjectUrl); - copyright=$(PackageCopyright); - tags=$(PackageTags); - githeadsha=$(NormalizedGitHeadSha); - configuration=$(Configuration); - artifactsbindir=$(ArtifactsBinDir); - - - - diff --git a/src/fcs-fable/src/fsharp/Directory.Nuget.targets b/src/fcs-fable/src/fsharp/Directory.Nuget.targets deleted file mode 100644 index e30b155faa..0000000000 --- a/src/fcs-fable/src/fsharp/Directory.Nuget.targets +++ /dev/null @@ -1,11 +0,0 @@ - - - - - $(NuspecProperties); - packageId=$(PackageId); - version=$(PackageVersion); - - - - diff --git a/src/fcs-fable/src/fsharp/DotNetFrameworkDependencies.fs b/src/fcs-fable/src/fsharp/DotNetFrameworkDependencies.fs new file mode 100644 index 0000000000..1bba15548a --- /dev/null +++ b/src/fcs-fable/src/fsharp/DotNetFrameworkDependencies.fs @@ -0,0 +1,460 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +// Functions to retrieve framework dependencies +module internal FSharp.Compiler.DotNetFrameworkDependencies + + open System + open System.Collections.Generic + open System.Diagnostics + open System.Globalization + open System.IO + open System.Reflection + open System.Runtime.InteropServices + open Internal.Utilities + open Internal.Utilities.FSharpEnvironment + + type private TypeInThisAssembly = class end + + let fSharpCompilerLocation = + let location = Path.GetDirectoryName(typeof.Assembly.Location) + match FSharpEnvironment.BinFolderOfDefaultFSharpCompiler (Some location) with + | Some path -> path + | None -> +#if DEBUG + Debug.Print(sprintf """FSharpEnvironment.BinFolderOfDefaultFSharpCompiler (Some '%s') returned None Location + customized incorrectly: algorithm here: https://github.com/dotnet/fsharp/blob/03f3f1c35f82af26593d025dabca57a6ef3ea9a1/src/utils/CompilerLocationUtils.fs#L171""" + location) +#endif + // Use the location of this dll + location + + let getFSharpCoreLibraryName = "FSharp.Core" + let getFsiLibraryName = "FSharp.Compiler.Interactive.Settings" + let getDefaultFSharpCoreLocation = Path.Combine(fSharpCompilerLocation, getFSharpCoreLibraryName + ".dll") + let getDefaultFsiLibraryLocation = Path.Combine(fSharpCompilerLocation, getFsiLibraryName + ".dll") + let implementationAssemblyDir = Path.GetDirectoryName(typeof.Assembly.Location) + + // Use the ValueTuple that is executing with the compiler if it is from System.ValueTuple + // or the System.ValueTuple.dll that sits alongside the compiler. (Note we always ship one with the compiler) + let getDefaultSystemValueTupleReference () = + try + let asm = typeof>.Assembly + if asm.FullName.StartsWith("System.ValueTuple", StringComparison.OrdinalIgnoreCase) then + Some asm.Location + else + let valueTuplePath = Path.Combine(fSharpCompilerLocation, "System.ValueTuple.dll") + if File.Exists(valueTuplePath) then + Some valueTuplePath + else + None + with _ -> None + + // Algorithm: + // use implementation location of obj type, on shared frameworks it will always be in: + // + // dotnet\shared\Microsoft.NETCore.App\sdk-version\System.Private.CoreLib.dll + // + // if that changes we will need to find another way to do this. Hopefully the sdk will eventually provide an API + // use the well know location for obj to traverse the file system towards the + // + // packs\Microsoft.NETCore.App.Ref\sdk-version\netcoreappn.n + // we will rely on the sdk-version match on the two paths to ensure that we get the product that ships with the + // version of the runtime we are executing on + // Use the reference assemblies for the highest netcoreapp tfm that we find in that location. + let version, frameworkRefsPackDirectoryRoot = + try + let version = DirectoryInfo(implementationAssemblyDir).Name + let microsoftNETCoreAppRef = Path.Combine(implementationAssemblyDir, "../../../packs/Microsoft.NETCore.App.Ref") + if Directory.Exists(microsoftNETCoreAppRef) then + Some version, Some microsoftNETCoreAppRef + else + Some version, None + with | _ -> None, None + + // Tries to figure out the tfm for the compiler instance. + // On coreclr it uses the deps.json file + let netcoreTfm = + let file = + try + let asm = Assembly.GetEntryAssembly() + match asm with + | null -> "" + | asm -> + let depsJsonPath = Path.ChangeExtension(asm.Location, "deps.json") + if File.Exists(depsJsonPath) then + File.ReadAllText(depsJsonPath) + else + "" + with _ -> "" + + let tfmPrefix=".NETCoreApp,Version=v" + let pattern = "\"name\": \"" + tfmPrefix + let startPos = + let startPos = file.IndexOf(pattern, StringComparison.OrdinalIgnoreCase) + if startPos >= 0 then startPos + (pattern.Length) else startPos + + let length = + if startPos >= 0 then + let ep = file.IndexOf("\"", startPos) + if ep >= 0 then ep - startPos else ep + else -1 + match startPos, length with + | -1, _ + | _, -1 -> + if isRunningOnCoreClr then + // Running on coreclr but no deps.json was deployed with the host so default to 3.0 + Some "netcoreapp3.1" + else + // Running on desktop + None + | pos, length -> + // use value from the deps.json file + Some ("netcoreapp" + file.Substring(pos, length)) + + // Tries to figure out the tfm for the compiler instance on the Windows desktop. + // On full clr it uses the mscorlib version number + let getWindowsDesktopTfm () = + let defaultMscorlibVersion = 4,8,3815,0 + let desktopProductVersionMonikers = [| + // major, minor, build, revision, moniker + 4, 8, 3815, 0, "net48" + 4, 8, 3761, 0, "net48" + 4, 7, 3190, 0, "net472" + 4, 7, 3062, 0, "net472" + 4, 7, 2600, 0, "net471" + 4, 7, 2558, 0, "net471" + 4, 7, 2053, 0, "net47" + 4, 7, 2046, 0, "net47" + 4, 6, 1590, 0, "net462" + 4, 6, 57, 0, "net462" + 4, 6, 1055, 0, "net461" + 4, 6, 81, 0, "net46" + 4, 0, 30319, 34209, "net452" + 4, 0, 30319, 17020, "net452" + 4, 0, 30319, 18408, "net451" + 4, 0, 30319, 17929, "net45" + 4, 0, 30319, 1, "net4" + |] + + let majorPart, minorPart, buildPart, privatePart= + try + let attrOpt = typeof.Assembly.GetCustomAttributes(typeof) |> Seq.tryHead + match attrOpt with + | Some attr -> + let fv = (downcast attr : AssemblyFileVersionAttribute).Version.Split([|'.'|]) |> Array.map(fun e -> Int32.Parse(e)) + fv.[0], fv.[1], fv.[2], fv.[3] + | _ -> defaultMscorlibVersion + with _ -> defaultMscorlibVersion + + // Get the ProductVersion of this framework compare with table yield compatible monikers + match desktopProductVersionMonikers + |> Array.tryFind (fun (major, minor, build, revision, _) -> + (majorPart >= major) && + (minorPart >= minor) && + (buildPart >= build) && + (privatePart >= revision)) with + | Some (_,_,_,_,moniker) -> + moniker + | None -> + // no TFM could be found, assume latest stable? + "net48" + + /// Gets the tfm E.g netcore3.0, net472 + let executionTfm = + match netcoreTfm with + | Some tfm -> tfm + | _ -> getWindowsDesktopTfm () + + // Computer valid dotnet-rids for this environment: + // https://docs.microsoft.com/en-us/dotnet/core/rid-catalog + // + // Where rid is: win, win-x64, win-x86, osx-x64, linux-x64 etc ... + let executionRid = + let processArchitecture = RuntimeInformation.ProcessArchitecture + let baseRid = + if RuntimeInformation.IsOSPlatform(OSPlatform.Windows) then "win" + elif RuntimeInformation.IsOSPlatform(OSPlatform.OSX) then "osx" + else "linux" + let platformRid = + match processArchitecture with + | Architecture.X64 -> baseRid + "-x64" + | Architecture.X86 -> baseRid + "-x86" + | Architecture.Arm64 -> baseRid + "-arm64" + | _ -> baseRid + "-arm" + platformRid + + let isInReferenceAssemblyPackDirectory filename = + match frameworkRefsPackDirectoryRoot with + | Some root -> + let path = Path.GetDirectoryName(filename) + path.StartsWith(root, StringComparison.OrdinalIgnoreCase) + | _ -> false + + let frameworkRefsPackDirectory = + let tfmPrefix = "netcoreapp" + let tfmCompare c1 c2 = + let deconstructTfmApp (netcoreApp: DirectoryInfo) = + let name = netcoreApp.Name + try + if name.StartsWith(tfmPrefix, StringComparison.InvariantCultureIgnoreCase) then + Some (Double.Parse(name.Substring(tfmPrefix.Length), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture)) + else + None + with _ -> None + + if c1 = c2 then 0 + else + match (deconstructTfmApp c1), (deconstructTfmApp c2) with + | Some c1, Some c2 -> int(c1 - c2) + | None, Some _ -> -1 + | Some _, None -> 1 + | _ -> 0 + + match version, frameworkRefsPackDirectoryRoot with + | Some version, Some root -> + try + let ref = Path.Combine(root, version, "ref") + let highestTfm = DirectoryInfo(ref).GetDirectories() + |> Array.sortWith tfmCompare + |> Array.tryLast + + match highestTfm with + | Some tfm -> Some (Path.Combine(ref, tfm.Name)) + | None -> None + with | _ -> None + | _ -> None + + let getDependenciesOf assemblyReferences = + let assemblies = new Dictionary() + + // Identify path to a dll in the framework directory from a simple name + let frameworkPathFromSimpleName simpleName = + let root = Path.Combine(implementationAssemblyDir, simpleName) + let pathOpt = + [| ""; ".dll"; ".exe" |] + |> Seq.tryPick(fun ext -> + let path = root + ext + if File.Exists(path) then Some path + else None) + match pathOpt with + | Some path -> path + | None -> root + + // Collect all assembly dependencies into assemblies dictionary + let rec traverseDependencies reference = + // Reference can be either path to a file on disk or a Assembly Simple Name + let referenceName, path = + try + if File.Exists(reference) then + // Reference is a path to a file on disk + Path.GetFileNameWithoutExtension(reference), reference + else + // Reference is a SimpleAssembly name + reference, frameworkPathFromSimpleName reference + + with _ -> reference, frameworkPathFromSimpleName reference + + if not (assemblies.ContainsKey(referenceName)) then + try + if File.Exists(path) then + // System.Private.CoreLib doesn't load with reflection + if referenceName = "System.Private.CoreLib" then + assemblies.Add(referenceName, path) + else + try + let asm = System.Reflection.Assembly.LoadFrom(path) + assemblies.Add(referenceName, path) + for reference in asm.GetReferencedAssemblies() do + traverseDependencies reference.Name + with e -> () + with e -> () + + assemblyReferences |> List.iter(traverseDependencies) + assemblies + + // This list is the default set of references for "non-project" files. + // + // These DLLs are + // (a) included in the environment used for all .fsx files (see service.fs) + // (b) included in environment for files 'orphaned' from a project context + // -- for orphaned files (files in VS without a project context) + let getDesktopDefaultReferences useFsiAuxLib = [ + yield "mscorlib" + yield "System" + yield "System.Xml" + yield "System.Runtime.Remoting" + yield "System.Runtime.Serialization.Formatters.Soap" + yield "System.Data" + yield "System.Drawing" + yield "System.Core" + + yield getFSharpCoreLibraryName + if useFsiAuxLib then yield getFsiLibraryName + + // always include a default reference to System.ValueTuple.dll in scripts and out-of-project sources + match getDefaultSystemValueTupleReference () with + | None -> () + | Some v -> yield v + + // These are the Portable-profile and .NET Standard 1.6 dependencies of FSharp.Core.dll. These are needed + // when an F# script references an F# profile 7, 78, 259 or .NET Standard 1.6 component which in turn refers + // to FSharp.Core for profile 7, 78, 259 or .NET Standard. + yield "netstandard" + yield "System.Runtime" // lots of types + yield "System.Linq" // System.Linq.Expressions.Expression + yield "System.Reflection" // System.Reflection.ParameterInfo + yield "System.Linq.Expressions" // System.Linq.IQueryable + yield "System.Threading.Tasks" // valuetype [System.Threading.Tasks]System.Threading.CancellationToken + yield "System.IO" // System.IO.TextWriter + yield "System.Net.Requests" // System.Net.WebResponse etc. + yield "System.Collections" // System.Collections.Generic.List + yield "System.Runtime.Numerics" // BigInteger + yield "System.Threading" // OperationCanceledException + yield "System.Web" + yield "System.Web.Services" + yield "System.Windows.Forms" + yield "System.Numerics" + ] + + let fetchPathsForDefaultReferencesForScriptsAndOutOfProjectSources useFsiAuxLib useSdkRefs assumeDotNetFramework = + let results = + if assumeDotNetFramework then + getDesktopDefaultReferences useFsiAuxLib + else + let dependencies = + let getImplementationReferences () = + // Coreclr supports netstandard assemblies only for now + (getDependenciesOf [ + yield! Directory.GetFiles(implementationAssemblyDir, "*.dll") + yield getDefaultFSharpCoreLocation + if useFsiAuxLib then yield getDefaultFsiLibraryLocation + ]).Values |> Seq.toList + + if useSdkRefs then + // Go fetch references + match frameworkRefsPackDirectory with + | Some path -> + try [ yield! Directory.GetFiles(path, "*.dll") + yield getDefaultFSharpCoreLocation + if useFsiAuxLib then yield getDefaultFsiLibraryLocation + ] + with | _ -> List.empty + | None -> + getImplementationReferences () + else + getImplementationReferences () + dependencies + results + + let defaultReferencesForScriptsAndOutOfProjectSources useFsiAuxLib assumeDotNetFramework useSdkRefs = + fetchPathsForDefaultReferencesForScriptsAndOutOfProjectSources useFsiAuxLib useSdkRefs assumeDotNetFramework + + // A set of assemblies to always consider to be system assemblies. A common set of these can be used a shared + // resources between projects in the compiler services. Also all assemblies where well-known system types exist + // referenced from TcGlobals must be listed here. + let systemAssemblies = + HashSet [ + yield "mscorlib" + yield "netstandard" + yield "System.Runtime" + yield getFSharpCoreLibraryName + + yield "System" + yield "System.Xml" + yield "System.Runtime.Remoting" + yield "System.Runtime.Serialization.Formatters.Soap" + yield "System.Data" + yield "System.Deployment" + yield "System.Design" + yield "System.Messaging" + yield "System.Drawing" + yield "System.Net" + yield "System.Web" + yield "System.Web.Services" + yield "System.Windows.Forms" + yield "System.Core" + yield "System.Runtime" + yield "System.Observable" + yield "System.Numerics" + yield "System.ValueTuple" + + // Additions for coreclr and portable profiles + yield "System.Collections" + yield "System.Collections.Concurrent" + yield "System.Console" + yield "System.Diagnostics.Debug" + yield "System.Diagnostics.Tools" + yield "System.Globalization" + yield "System.IO" + yield "System.Linq" + yield "System.Linq.Expressions" + yield "System.Linq.Queryable" + yield "System.Net.Requests" + yield "System.Reflection" + yield "System.Reflection.Emit" + yield "System.Reflection.Emit.ILGeneration" + yield "System.Reflection.Extensions" + yield "System.Resources.ResourceManager" + yield "System.Runtime.Extensions" + yield "System.Runtime.InteropServices" + yield "System.Runtime.InteropServices.PInvoke" + yield "System.Runtime.Numerics" + yield "System.Text.Encoding" + yield "System.Text.Encoding.Extensions" + yield "System.Text.RegularExpressions" + yield "System.Threading" + yield "System.Threading.Tasks" + yield "System.Threading.Tasks.Parallel" + yield "System.Threading.Thread" + yield "System.Threading.ThreadPool" + yield "System.Threading.Timer" + + yield "FSharp.Compiler.Interactive.Settings" + yield "Microsoft.Win32.Registry" + yield "System.Diagnostics.Tracing" + yield "System.Globalization.Calendars" + yield "System.Reflection.Primitives" + yield "System.Runtime.Handles" + yield "Microsoft.Win32.Primitives" + yield "System.IO.FileSystem" + yield "System.Net.Primitives" + yield "System.Net.Sockets" + yield "System.Private.Uri" + yield "System.AppContext" + yield "System.Buffers" + yield "System.Collections.Immutable" + yield "System.Diagnostics.DiagnosticSource" + yield "System.Diagnostics.Process" + yield "System.Diagnostics.TraceSource" + yield "System.Globalization.Extensions" + yield "System.IO.Compression" + yield "System.IO.Compression.ZipFile" + yield "System.IO.FileSystem.Primitives" + yield "System.Net.Http" + yield "System.Net.NameResolution" + yield "System.Net.WebHeaderCollection" + yield "System.ObjectModel" + yield "System.Reflection.Emit.Lightweight" + yield "System.Reflection.Metadata" + yield "System.Reflection.TypeExtensions" + yield "System.Runtime.InteropServices.RuntimeInformation" + yield "System.Runtime.Loader" + yield "System.Security.Claims" + yield "System.Security.Cryptography.Algorithms" + yield "System.Security.Cryptography.Cng" + yield "System.Security.Cryptography.Csp" + yield "System.Security.Cryptography.Encoding" + yield "System.Security.Cryptography.OpenSsl" + yield "System.Security.Cryptography.Primitives" + yield "System.Security.Cryptography.X509Certificates" + yield "System.Security.Principal" + yield "System.Security.Principal.Windows" + yield "System.Threading.Overlapped" + yield "System.Threading.Tasks.Extensions" + yield "System.Xml.ReaderWriter" + yield "System.Xml.XDocument" + ] + + // The set of references entered into the TcConfigBuilder for scripts prior to computing the load closure. + let basicReferencesForScriptLoadClosure useFsiAuxLib useSdkRefs assumeDotNetFramework = + fetchPathsForDefaultReferencesForScriptsAndOutOfProjectSources useFsiAuxLib useSdkRefs assumeDotNetFramework diff --git a/src/fcs-fable/src/fsharp/ErrorLogger.fs b/src/fcs-fable/src/fsharp/ErrorLogger.fs index 1603d4ede0..ba8ca64860 100755 --- a/src/fcs-fable/src/fsharp/ErrorLogger.fs +++ b/src/fcs-fable/src/fsharp/ErrorLogger.fs @@ -4,6 +4,7 @@ module public FSharp.Compiler.ErrorLogger open FSharp.Compiler open FSharp.Compiler.Range +open FSharp.Compiler.Features open System //------------------------------------------------------------------------ @@ -46,9 +47,9 @@ let rec findOriginalException err = | WrappedError(err, _) -> findOriginalException err | _ -> err -type Suggestions = unit -> Collections.Generic.HashSet +type Suggestions = (string -> unit) -> unit -let NoSuggestions : Suggestions = fun () -> Collections.Generic.HashSet() +let NoSuggestions : Suggestions = ignore /// Thrown when we stop processing the F# Interactive entry or #load. exception StopProcessingExn of exn option with @@ -88,10 +89,10 @@ exception Deprecated of string * range exception Experimental of string * range exception PossibleUnverifiableCode of range -exception UnresolvedReferenceNoRange of (*assemblyname*) string -exception UnresolvedReferenceError of (*assemblyname*) string * range -exception UnresolvedPathReferenceNoRange of (*assemblyname*) string * (*path*) string -exception UnresolvedPathReference of (*assemblyname*) string * (*path*) string * range +exception UnresolvedReferenceNoRange of (*assemblyName*) string +exception UnresolvedReferenceError of (*assemblyName*) string * range +exception UnresolvedPathReferenceNoRange of (*assemblyName*) string * (*path*) string +exception UnresolvedPathReference of (*assemblyName*) string * (*path*) string * range @@ -125,16 +126,16 @@ let inline protectAssemblyExplorationNoReraise dflt1 dflt2 f = // Attach a range if this is a range dual exception. let rec AttachRange m (exn:exn) = - if m = range0 then exn + if Range.equals m range0 then exn else match exn with // Strip TargetInvocationException wrappers #if !FABLE_COMPILER | :? System.Reflection.TargetInvocationException -> AttachRange m exn.InnerException #endif - | UnresolvedReferenceNoRange(a) -> UnresolvedReferenceError(a, m) + | UnresolvedReferenceNoRange a -> UnresolvedReferenceError(a, m) | UnresolvedPathReferenceNoRange(a, p) -> UnresolvedPathReference(a, p, m) - | Failure(msg) -> InternalError(msg + " (Failure)", m) + | Failure msg -> InternalError(msg + " (Failure)", m) #if !FABLE_COMPILER | :? System.ArgumentException as exn -> InternalError(exn.Message + " (ArgumentException)", m) #endif @@ -152,9 +153,9 @@ type Exiter = let QuitProcessExiter = { new Exiter with - member __.Exit(n) = + member __.Exit n = try - System.Environment.Exit(n) + System.Environment.Exit n with _ -> () FSComp.SR.elSysEnvExitDidntExit() @@ -204,7 +205,7 @@ type PhasedDiagnostic = /// Construct a phased error static member Create(exn:exn, phase:BuildPhase) : PhasedDiagnostic = - // FUTURE: renable this assert, which has historically triggered in some compiler service scenarios + // FUTURE: reenable this assert, which has historically triggered in some compiler service scenarios // System.Diagnostics.Debug.Assert(phase<>BuildPhase.DefaultPhase, sprintf "Compile error seen with no phase to attribute it to.%A %s %s" phase exn.Message exn.StackTrace ) {Exception = exn; Phase=phase} @@ -288,7 +289,7 @@ let DiscardErrorsLogger = let AssertFalseErrorLogger = { new ErrorLogger("AssertFalseErrorLogger") with - // TODO: renable these asserts in the compiler service + // TODO: reenable these asserts in the compiler service member x.DiagnosticSink(phasedError, isError) = (* assert false; *) () member x.ErrorCount = (* assert false; *) 0 } @@ -320,7 +321,7 @@ type internal CompileThreadStatic = static member BuildPhase with get() = match box CompileThreadStatic.buildPhase with - // FUTURE: renable these asserts, which have historically fired in some compiler service scernaios + // FUTURE: reenable these asserts, which have historically fired in some compiler service scenarios | null -> (* assert false; *) BuildPhase.DefaultPhase | _ -> CompileThreadStatic.buildPhase and set v = CompileThreadStatic.buildPhase <- v @@ -337,15 +338,28 @@ type internal CompileThreadStatic = module ErrorLoggerExtensions = open System.Reflection + // Dev15.0 shipped with a bug in diasymreader in the portable pdb symbol reader which causes an AV + // This uses a simple heuristic to detect it (the vsversion is < 16.0) + let tryAndDetectDev15 = +#if FABLE_COMPILER + false +#else + let vsVersion = Environment.GetEnvironmentVariable("VisualStudioVersion") + match Double.TryParse vsVersion with + | true, v -> v < 16.0 + | _ -> false +#endif + /// Instruct the exception not to reset itself when thrown again. - let PreserveStackTrace(exn) = + let PreserveStackTrace exn = #if FABLE_COMPILER ignore exn () #else - try - let preserveStackTrace = typeof.GetMethod("InternalPreserveStackTrace", BindingFlags.Instance ||| BindingFlags.NonPublic) - preserveStackTrace.Invoke(exn, null) |> ignore + try + if not tryAndDetectDev15 then + let preserveStackTrace = typeof.GetMethod("InternalPreserveStackTrace", BindingFlags.Instance ||| BindingFlags.NonPublic) + preserveStackTrace.Invoke(exn, null) |> ignore with _ -> // This is probably only the mono case. System.Diagnostics.Debug.Assert(false, "Could not preserve stack trace for watson exception.") @@ -354,10 +368,6 @@ module ErrorLoggerExtensions = /// Reraise an exception if it is one we want to report to Watson. let ReraiseIfWatsonable(exn:exn) = -#if FX_REDUCED_EXCEPTIONS - ignore exn - () -#else match exn with // These few SystemExceptions which we don't report to Watson are because we handle these in some way in Build.fs | :? System.Reflection.TargetInvocationException -> () @@ -366,10 +376,9 @@ module ErrorLoggerExtensions = | :? System.UnauthorizedAccessException -> () | Failure _ // This gives reports for compiler INTERNAL ERRORs | :? System.SystemException -> - PreserveStackTrace(exn) + PreserveStackTrace exn raise exn | _ -> () -#endif type ErrorLogger with @@ -383,7 +392,7 @@ module ErrorLoggerExtensions = match exn with | StopProcessing | ReportedError _ -> - PreserveStackTrace(exn) + PreserveStackTrace exn raise exn | _ -> x.DiagnosticSink(PhasedDiagnostic.Create(exn, CompileThreadStatic.BuildPhase), true) @@ -391,7 +400,7 @@ module ErrorLoggerExtensions = match exn with | StopProcessing | ReportedError _ -> - PreserveStackTrace(exn) + PreserveStackTrace exn raise exn | _ -> x.DiagnosticSink(PhasedDiagnostic.Create(exn, CompileThreadStatic.BuildPhase), false) @@ -399,27 +408,26 @@ module ErrorLoggerExtensions = x.ErrorR exn raise (ReportedError (Some exn)) - member x.SimulateError (ph:PhasedDiagnostic) = + member x.SimulateError (ph: PhasedDiagnostic) = x.DiagnosticSink (ph, true) raise (ReportedError (Some ph.Exception)) - member x.ErrorRecovery (exn:exn) (m:range) = + member x.ErrorRecovery (exn: exn) (m: range) = // Never throws ReportedError. // Throws StopProcessing and exceptions raised by the DiagnosticSink(exn) handler. match exn with +#if !FABLE_COMPILER (* Don't send ThreadAbortException down the error channel *) -#if FX_REDUCED_EXCEPTIONS -#else | :? System.Threading.ThreadAbortException | WrappedError((:? System.Threading.ThreadAbortException), _) -> () #endif | ReportedError _ | WrappedError(ReportedError _, _) -> () | StopProcessing | WrappedError(StopProcessing, _) -> - PreserveStackTrace(exn) + PreserveStackTrace exn raise exn | _ -> try x.ErrorR (AttachRange m exn) // may raise exceptions, e.g. an fsi error sink raises StopProcessing. - ReraiseIfWatsonable(exn) + ReraiseIfWatsonable exn with | ReportedError _ | WrappedError(ReportedError _, _) -> () @@ -453,8 +461,8 @@ let PushThreadBuildPhaseUntilUnwind (phase:BuildPhase) = let PushErrorLoggerPhaseUntilUnwind(errorLoggerTransformer : ErrorLogger -> #ErrorLogger) = let oldErrorLogger = CompileThreadStatic.ErrorLogger let newErrorLogger = errorLoggerTransformer oldErrorLogger - let newInstalled = ref true - let newIsInstalled() = if !newInstalled then () else (assert false; (); (*failwith "error logger used after unwind"*)) // REVIEW: ok to throw? + let mutable newInstalled = true + let newIsInstalled() = if newInstalled then () else (assert false; (); (*failwith "error logger used after unwind"*)) // REVIEW: ok to throw? let chkErrorLogger = { new ErrorLogger("PushErrorLoggerPhaseUntilUnwind") with member __.DiagnosticSink(phasedError, isError) = newIsInstalled(); newErrorLogger.DiagnosticSink(phasedError, isError) member __.ErrorCount = newIsInstalled(); newErrorLogger.ErrorCount } @@ -464,10 +472,10 @@ let PushErrorLoggerPhaseUntilUnwind(errorLoggerTransformer : ErrorLogger -> #Err { new System.IDisposable with member __.Dispose() = CompileThreadStatic.ErrorLogger <- oldErrorLogger - newInstalled := false } + newInstalled <- false } let SetThreadBuildPhaseNoUnwind(phase:BuildPhase) = CompileThreadStatic.BuildPhase <- phase -let SetThreadErrorLoggerNoUnwind(errorLogger) = CompileThreadStatic.ErrorLogger <- errorLogger +let SetThreadErrorLoggerNoUnwind errorLogger = CompileThreadStatic.ErrorLogger <- errorLogger // Global functions are still used by parser and TAST ops. @@ -498,8 +506,8 @@ let deprecatedWithError s m = errorR(Deprecated(s, m)) // Note: global state, but only for compiling FSharp.Core.dll let mutable reportLibraryOnlyFeatures = true -let libraryOnlyError m = if reportLibraryOnlyFeatures then errorR(LibraryUseOnly(m)) -let libraryOnlyWarning m = if reportLibraryOnlyFeatures then warning(LibraryUseOnly(m)) +let libraryOnlyError m = if reportLibraryOnlyFeatures then errorR(LibraryUseOnly m) +let libraryOnlyWarning m = if reportLibraryOnlyFeatures then warning(LibraryUseOnly m) let deprecatedOperator m = deprecatedWithError (FSComp.SR.elDeprecatedOperator()) m let mlCompatWarning s m = warning(UserCompilerMessage(FSComp.SR.mlCompatMessage s, 62, m)) @@ -510,10 +518,10 @@ let suppressErrorReporting f = { new ErrorLogger("suppressErrorReporting") with member __.DiagnosticSink(_phasedError, _isError) = () member __.ErrorCount = 0 } - SetThreadErrorLoggerNoUnwind(errorLogger) + SetThreadErrorLoggerNoUnwind errorLogger f() finally - SetThreadErrorLoggerNoUnwind(errorLogger) + SetThreadErrorLoggerNoUnwind errorLogger let conditionallySuppressErrorReporting cond f = if cond then suppressErrorReporting f else f() @@ -573,7 +581,7 @@ let MapD f xs = let rec loop acc xs = match xs with | [] -> ResultD (List.rev acc) - | h :: t -> f h ++ (fun x -> loop (x::acc) t) + | h :: t -> f h ++ (fun x -> loop (x :: acc) t) loop [] xs @@ -585,8 +593,8 @@ type TrackErrorsBuilder() = member x.Combine(expr1, expr2) = expr1 ++ expr2 member x.While(gd, k) = WhileD gd k member x.Zero() = CompleteD - member x.Delay(fn) = fun () -> fn () - member x.Run(fn) = fn () + member x.Delay fn = fun () -> fn () + member x.Run fn = fn () let trackErrors = TrackErrorsBuilder() @@ -605,7 +613,7 @@ let IterateIdxD f xs = let rec Iterate2D f xs ys = match xs, ys with | [], [] -> CompleteD - | h1 :: t1, h2::t2 -> f h1 h2 ++ (fun () -> Iterate2D f t1 t2) + | h1 :: t1, h2 :: t2 -> f h1 h2 ++ (fun () -> Iterate2D f t1 t2) | _ -> failwith "Iterate2D" /// Keep the warnings, propagate the error to the exception continuation. @@ -618,7 +626,7 @@ let TryD f g = } | res -> res -let rec RepeatWhileD ndeep body = body ndeep ++ (fun x -> if x then RepeatWhileD (ndeep+1) body else CompleteD) +let rec RepeatWhileD nDeep body = body nDeep ++ (fun x -> if x then RepeatWhileD (nDeep+1) body else CompleteD) let AtLeastOneD f l = MapD f l ++ (fun res -> ResultD (List.exists id res)) @@ -649,15 +657,15 @@ let NormalizeErrorString (text : string) = match text.[i] with | '\r' when i + 1 < text.Length && text.[i + 1] = '\n' -> // handle \r\n sequence - replace it with one single space - buf.Append(stringThatIsAProxyForANewlineInFlatErrors) |> ignore + buf.Append stringThatIsAProxyForANewlineInFlatErrors |> ignore 2 | '\n' | '\r' -> - buf.Append(stringThatIsAProxyForANewlineInFlatErrors) |> ignore + buf.Append stringThatIsAProxyForANewlineInFlatErrors |> ignore 1 | c -> // handle remaining chars: control - replace with space, others - keep unchanged - let c = if Char.IsControl(c) then ' ' else c - buf.Append(string c) |> ignore + let c = if Char.IsControl c then ' ' else c + buf.Append c |> ignore 1 i <- i + delta buf.ToString() @@ -680,3 +688,23 @@ type public FSharpErrorSeverityOptions = WarnAsError = [] WarnAsWarn = [] } + + +// See https://github.com/Microsoft/visualfsharp/issues/6417, if a compile of the FSharp.Compiler.Services.dll or other compiler +// binary produces exactly 65536 methods then older versions of the compiler raise a bug. If you hit this bug again then try adding +// this back in. +// let dummyMethodFOrBug6417A() = () +// let dummyMethodFOrBug6417B() = () + +let private tryLanguageFeatureErrorAux (langVersion: LanguageVersion) (langFeature: LanguageFeature) (m: range) error = + if not (langVersion.SupportsFeature langFeature) then + let featureStr = langVersion.GetFeatureString langFeature + let currentVersionStr = langVersion.SpecifiedVersionString + let suggestedVersionStr = langVersion.GetFeatureVersionString langFeature + error (Error(FSComp.SR.chkFeatureNotLanguageSupported(featureStr, currentVersionStr, suggestedVersionStr), m)) + +let internal tryLanguageFeatureError langVersion langFeature m = + tryLanguageFeatureErrorAux langVersion langFeature m error + +let internal tryLanguageFeatureErrorRecover langVersion langFeature m = + tryLanguageFeatureErrorAux langVersion langFeature m errorR \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/ErrorResolutionHints.fs b/src/fcs-fable/src/fsharp/ErrorResolutionHints.fs index f40dd8f914..ca737ea80e 100644 --- a/src/fcs-fable/src/fsharp/ErrorResolutionHints.fs +++ b/src/fcs-fable/src/fsharp/ErrorResolutionHints.fs @@ -5,11 +5,13 @@ module internal FSharp.Compiler.ErrorResolutionHints open Internal.Utilities open FSharp.Compiler.AbstractIL.Internal.Library +open System.Collections +open System.Collections.Generic let maxSuggestions = 5 let minThresholdForSuggestions = 0.7 let highConfidenceThreshold = 0.85 -let minStringLengthForThreshold = 3 +let minStringLengthForSuggestion = 3 /// We report a candidate if its edit distance is <= the threshold. /// The threshold is set to about a quarter of the number of characters. @@ -23,60 +25,82 @@ let IsInEditDistanceProximity idText suggestion = editDistance <= threshold -/// Filters predictions based on edit distance to the given unknown identifier. -let FilterPredictions (idText:string) (suggestionF:ErrorLogger.Suggestions) = +/// Demangles a suggestion +let DemangleOperator (nm: string) = + if nm.StartsWithOrdinal("( ") && nm.EndsWithOrdinal(" )") then + nm.[2..nm.Length - 3] + else + nm + +type SuggestionBufferEnumerator(tail: int, data: KeyValuePair []) = + let mutable current = data.Length + interface IEnumerator with + member __.Current + with get () = + let kvpr = data.[current] + kvpr.Value + interface System.Collections.IEnumerator with + member __.Current with get () = box data.[current].Value + member __.MoveNext() = + current <- current - 1 + current > tail || (current = tail && data.[current] <> Unchecked.defaultof<_>) + member __.Reset () = current <- data.Length + interface System.IDisposable with + member __.Dispose () = () + +type SuggestionBuffer(idText: string) = + let data = Array.zeroCreate>(maxSuggestions) + let mutable tail = maxSuggestions - 1 let uppercaseText = idText.ToUpperInvariant() - let allSuggestions = suggestionF() + let dotIdText = "." + idText + let mutable disableSuggestions = idText.Length < minStringLengthForSuggestion - let demangle (nm:string) = - if nm.StartsWithOrdinal("( ") && nm.EndsWithOrdinal(" )") then - let cleanName = nm.[2..nm.Length - 3] - cleanName - else nm + let insert (k,v) = + let mutable pos = tail + while pos < maxSuggestions && (let kv = data.[pos] in kv.Key < k) do + pos <- pos + 1 - /// Returns `true` if given string is an operator display name, e.g. ( |>> ) - let IsOperatorName (name: string) = - if not (name.StartsWithOrdinal("( ") && name.EndsWithOrdinal(" )")) then - false - else - let name = name.[2..name.Length - 3] - name |> Seq.forall (fun c -> c <> ' ') + if pos > 0 then + if pos >= maxSuggestions || (let kv = data.[pos] in k <> kv.Key || v <> kv.Value) then + if tail < pos - 1 then + for i = tail to pos - 2 do + data.[i] <- data.[i + 1] + data.[pos - 1] <- KeyValuePair(k,v) + if tail > 0 then tail <- tail - 1 - if allSuggestions.Contains idText then [] else // some other parsing error occurred - let dotIdText = "." + idText - allSuggestions - |> Seq.choose (fun suggestion -> - // Because beginning a name with _ is used both to indicate an unused - // value as well as to formally squelch the associated compiler - // error/warning (FS1182), we remove such names from the suggestions, - // both to prevent accidental usages as well as to encourage good taste - if IsOperatorName suggestion || suggestion.StartsWithOrdinal("_") then None else - let suggestion:string = demangle suggestion - let suggestedText = suggestion.ToUpperInvariant() - let similarity = EditDistance.JaroWinklerDistance uppercaseText suggestedText - if similarity >= highConfidenceThreshold || suggestion.EndsWithOrdinal(dotIdText) then - Some(similarity, suggestion) - elif similarity < minThresholdForSuggestions && suggestedText.Length > minStringLengthForThreshold then - None - elif IsInEditDistanceProximity uppercaseText suggestedText then - Some(similarity, suggestion) - else - None) - |> Seq.sortByDescending fst - |> Seq.mapi (fun i x -> i, x) - |> Seq.takeWhile (fun (i, _) -> i < maxSuggestions) - |> Seq.map snd - |> Seq.toList + member __.Add (suggestion: string) = + if not disableSuggestions then + if suggestion = idText then // some other parse error happened + disableSuggestions <- true + + // Because beginning a name with _ is used both to indicate an unused + // value as well as to formally squelch the associated compiler + // error/warning (FS1182), we remove such names from the suggestions, + // both to prevent accidental usages as well as to encourage good taste + if suggestion.Length >= minStringLengthForSuggestion && not (suggestion.StartsWithOrdinal "_") then + let suggestion:string = DemangleOperator suggestion + let suggestedText = suggestion.ToUpperInvariant() + let similarity = EditDistance.JaroWinklerDistance uppercaseText suggestedText + if similarity >= highConfidenceThreshold || + suggestion.EndsWithOrdinal dotIdText || + (similarity >= minThresholdForSuggestions && IsInEditDistanceProximity uppercaseText suggestedText) + then + insert(similarity, suggestion) |> ignore + + member __.Disabled with get () = disableSuggestions + + member __.IsEmpty with get () = disableSuggestions || (tail = maxSuggestions - 1) -/// Formats the given predictions according to the error style. -let FormatPredictions normalizeF (predictions: (float * string) list) = - match predictions with - | [] -> System.String.Empty - | _ -> - let suggestions = - predictions - |> List.map (snd >> normalizeF) - |> List.map (sprintf "%s %s" System.Environment.NewLine) - |> String.concat "" + interface IEnumerable with + member this.GetEnumerator () = + if this.IsEmpty then + Seq.empty.GetEnumerator() + else + new SuggestionBufferEnumerator(tail, data) :> IEnumerator - " " + FSComp.SR.undefinedNameSuggestionsIntro() + suggestions + interface IEnumerable with + member this.GetEnumerator () = + if this.IsEmpty then + Seq.empty.GetEnumerator() :> IEnumerator + else + new SuggestionBufferEnumerator(tail, data) :> IEnumerator diff --git a/src/fcs-fable/src/fsharp/ExtensionTyping.fs b/src/fcs-fable/src/fsharp/ExtensionTyping.fs index f9f1038a04..141e2cd35f 100755 --- a/src/fcs-fable/src/fsharp/ExtensionTyping.fs +++ b/src/fcs-fable/src/fsharp/ExtensionTyping.fs @@ -15,13 +15,15 @@ module internal ExtensionTyping = open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Range open FSharp.Compiler.AbstractIL.IL - open FSharp.Compiler.AbstractIL.Diagnostics // dprintfn open FSharp.Compiler.AbstractIL.Internal.Library // frontAndBack + open Internal.Utilities.FSharpEnvironment type TypeProviderDesignation = TypeProviderDesignation of string - exception ProvidedTypeResolution of range * System.Exception - exception ProvidedTypeResolutionNoRange of System.Exception + exception ProvidedTypeResolution of range * System.Exception + exception ProvidedTypeResolutionNoRange of System.Exception + + let toolingCompatiblePaths() = toolingCompatiblePaths () /// Represents some of the configuration parameters passed to type provider components type ResolutionEnvironment = @@ -29,101 +31,18 @@ module internal ExtensionTyping = outputFile : string option showResolutionMessages : bool referencedAssemblies : string[] - temporaryFolder : string } - - - // Specify the tooling-compatible fragments of a path such as: - // typeproviders/fsharp41/net461/MyProvider.DesignTime.dll - // tools/fsharp41/net461/MyProvider.DesignTime.dll - // See https://github.com/Microsoft/visualfsharp/issues/3736 - - // Represents the FF#-compiler <-> type provider protocol. - // When the API or protocol updates, add a new version moniker to the front of the list here. - let toolingCompatibleTypeProviderProtocolMonikers() = - [ "fsharp41" ] - - // Detect the host tooling context - let toolingCompatibleVersions() = - if typeof.Assembly.GetName().Name = "mscorlib" then - [ "net461"; "net452"; "net451"; "net45"; "netstandard2.0"] - elif typeof.Assembly.GetName().Name = "System.Private.CoreLib" then - [ "netcoreapp2.0"; "netstandard2.0"] - else - System.Diagnostics.Debug.Assert(false, "Couldn't determine runtime tooling context, assuming it supports at least .NET Standard 2.0") - [ "netstandard2.0"] - - - let toolingCompatiblePaths() = - [ for protocol in toolingCompatibleTypeProviderProtocolMonikers() do - for netRuntime in toolingCompatibleVersions() do - yield Path.Combine("typeproviders", protocol, netRuntime) - yield Path.Combine("tools", protocol, netRuntime) - ] + temporaryFolder : string } /// Load a the design-time part of a type-provider into the host process, and look for types /// marked with the TypeProviderAttribute attribute. - let GetTypeProviderImplementationTypes (runTimeAssemblyFileName, designTimeAssemblyNameString, m: range) = + let GetTypeProviderImplementationTypes (runTimeAssemblyFileName, designTimeAssemblyNameString, m:range, compilerToolPaths:string list) = // Report an error, blaming the particular type provider component let raiseError (e: exn) = raise (TypeProviderError(FSComp.SR.etProviderHasWrongDesignerAssembly(typeof.Name, designTimeAssemblyNameString, e.Message), runTimeAssemblyFileName, m)) - // Find and load the designer assembly for the type provider component. - // - // We look in the directories stepping up from the location of the runtime assembly. + let designTimeAssemblyOpt = getTypeProviderAssembly (runTimeAssemblyFileName, designTimeAssemblyNameString, compilerToolPaths, raiseError) - let loadFromLocation designTimeAssemblyPath = - try - Some (FileSystem.AssemblyLoadFrom designTimeAssemblyPath) - with e -> - raiseError e - - let rec searchParentDirChain dir designTimeAssemblyName = - seq { - for subdir in toolingCompatiblePaths() do - let designTimeAssemblyPath = Path.Combine (dir, subdir, designTimeAssemblyName) - if FileSystem.SafeExists designTimeAssemblyPath then - yield loadFromLocation designTimeAssemblyPath - match Path.GetDirectoryName(dir) with - | s when s = "" || s = null || Path.GetFileName(dir) = "packages" || s = dir -> () - | parentDir -> yield! searchParentDirChain parentDir designTimeAssemblyName - } - - let loadFromParentDirRelativeToRuntimeAssemblyLocation designTimeAssemblyName = - let runTimeAssemblyPath = Path.GetDirectoryName runTimeAssemblyFileName - searchParentDirChain runTimeAssemblyPath designTimeAssemblyName - |> Seq.tryHead - |> function - | Some res -> res - | None -> - // The search failed, just load from the first location and report an error - let runTimeAssemblyPath = Path.GetDirectoryName runTimeAssemblyFileName - loadFromLocation (Path.Combine (runTimeAssemblyPath, designTimeAssemblyName)) - - let designTimeAssemblyOpt = - - if designTimeAssemblyNameString.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) then - loadFromParentDirRelativeToRuntimeAssemblyLocation designTimeAssemblyNameString - else - // Cover the case where the ".dll" extension has been left off and no version etc. has been used in the assembly - // string specification. The Name=FullName comparison is particularly strange, and was there to support - // design-time DLLs specified using "x.DesignTIme, Version= ..." long assembly names and GAC loads. - // These kind of design-time assembly specifications are no longer used to our knowledge so that comparison is basically legacy - // and will always succeed. - let name = System.Reflection.AssemblyName (Path.GetFileNameWithoutExtension designTimeAssemblyNameString) - if name.Name.Equals(name.FullName, StringComparison.OrdinalIgnoreCase) then - let designTimeAssemblyName = designTimeAssemblyNameString+".dll" - loadFromParentDirRelativeToRuntimeAssemblyLocation designTimeAssemblyName - else - // Load from the GAC using Assembly.Load. This is legacy since type provider design-time components are - // never in the GAC these days and "x.DesignTIme, Version= ..." specifications are never used. - try - let asmName = System.Reflection.AssemblyName designTimeAssemblyNameString - Some (FileSystem.AssemblyLoad (asmName)) - with e -> - raiseError e - - // If we've find a design-time assembly, look for the public types with TypeProviderAttribute match designTimeAssemblyOpt with | Some loadedDesignTimeAssembly -> try @@ -140,9 +59,7 @@ module internal ExtensionTyping = let StripException (e: exn) = match e with -#if !FX_REDUCED_EXCEPTIONS | :? System.Reflection.TargetInvocationException as e -> e.InnerException -#endif | :? TypeInitializationException as e -> e.InnerException | _ -> e @@ -181,7 +98,7 @@ module internal ExtensionTyping = protect (fun () -> Activator.CreateInstance(typeProviderImplementationType, [| box e|]) :?> ITypeProvider ) elif typeProviderImplementationType.GetConstructor [| |] <> null then - protect (fun () -> Activator.CreateInstance(typeProviderImplementationType) :?> ITypeProvider ) + protect (fun () -> Activator.CreateInstance typeProviderImplementationType :?> ITypeProvider ) else // No appropriate constructor found @@ -196,7 +113,8 @@ module internal ExtensionTyping = isInteractive: bool, systemRuntimeContainsType : string -> bool, systemRuntimeAssemblyVersion : System.Version, - m: range) = + compilerToolPaths: string list, + m:range) = let providerSpecs = try @@ -213,22 +131,28 @@ module internal ExtensionTyping = [ match designTimeAssemblyName, resolutionEnvironment.outputFile with // Check if the attribute is pointing to the file being compiled, in which case ignore it // This checks seems like legacy but is included for compat. - | Some designTimeAssemblyName, Some path when String.Compare(designTimeAssemblyName.Name, Path.GetFileNameWithoutExtension path, StringComparison.OrdinalIgnoreCase) = 0 -> + | Some designTimeAssemblyName, Some path + when String.Compare(designTimeAssemblyName.Name, Path.GetFileNameWithoutExtension path, StringComparison.OrdinalIgnoreCase) = 0 -> () + | Some _, _ -> - for t in GetTypeProviderImplementationTypes (runTimeAssemblyFileName, designTimeAssemblyNameString, m) do - let resolver = CreateTypeProvider (t, runTimeAssemblyFileName, resolutionEnvironment, isInvalidationSupported, isInteractive, systemRuntimeContainsType, systemRuntimeAssemblyVersion, m) + let provImplTypes = GetTypeProviderImplementationTypes (runTimeAssemblyFileName, designTimeAssemblyNameString, m, compilerToolPaths) + for t in provImplTypes do + let resolver = + CreateTypeProvider (t, runTimeAssemblyFileName, resolutionEnvironment, isInvalidationSupported, + isInteractive, systemRuntimeContainsType, systemRuntimeAssemblyVersion, m) match box resolver with | null -> () | _ -> yield (resolver, ilScopeRefOfRuntimeAssembly) + | None, _ -> () ] with :? TypeProviderError as tpe -> - tpe.Iter(fun e -> errorR(NumberedError((e.Number, e.ContextualErrorMessage), m)) ) + tpe.Iter(fun e -> errorR(NumberedError((e.Number, e.ContextualErrorMessage), m)) ) [] - let providers = Tainted<_>.CreateAll(providerSpecs) + let providers = Tainted<_>.CreateAll providerSpecs providers @@ -336,16 +260,18 @@ module internal ExtensionTyping = match ctxt with | NoEntries -> None | Entries(d, _) -> - let ok, res = d.TryGetValue(st) - if ok then Some res else None + match d.TryGetValue st with + | true, res -> Some res + | _ -> None - member ctxt.TryGetTyconRef(st) = + member ctxt.TryGetTyconRef st = match ctxt with | NoEntries -> None | Entries(_, d) -> let d = d.Force() - let ok, res = d.TryGetValue(st) - if ok then Some res else None + match d.TryGetValue st with + | true, res -> Some res + | _ -> None member ctxt.RemapTyconRefs (f: obj->obj) = match ctxt with @@ -362,11 +288,15 @@ module internal ExtensionTyping = [] type ProvidedType (x: System.Type, ctxt: ProvidedTypeContext) = inherit ProvidedMemberInfo(x, ctxt) + let isMeasure = + lazy + x.CustomAttributes + |> Seq.exists (fun a -> a.Constructor.DeclaringType.FullName = typeof.FullName) let provide () = ProvidedCustomAttributeProvider.Create (fun _provider -> x.CustomAttributes) interface IProvidedCustomAttributeProvider with - member __.GetHasTypeProviderEditorHideMethodsAttribute(provider) = provide().GetHasTypeProviderEditorHideMethodsAttribute(provider) - member __.GetDefinitionLocationAttribute(provider) = provide().GetDefinitionLocationAttribute(provider) - member __.GetXmlDocAttributes(provider) = provide().GetXmlDocAttributes(provider) + member __.GetHasTypeProviderEditorHideMethodsAttribute provider = provide().GetHasTypeProviderEditorHideMethodsAttribute provider + member __.GetDefinitionLocationAttribute provider = provide().GetDefinitionLocationAttribute provider + member __.GetXmlDocAttributes provider = provide().GetXmlDocAttributes provider // The type provider spec distinguishes between // - calls that can be made on provided types (i.e. types given by ReturnType, ParameterType, and generic argument types) @@ -381,31 +311,31 @@ module internal ExtensionTyping = member __.Namespace = x.Namespace member __.FullName = x.FullName member __.IsArray = x.IsArray - member __.Assembly = x.Assembly |> ProvidedAssembly.Create ctxt + member __.Assembly = x.Assembly |> ProvidedAssembly.Create member __.GetInterfaces() = x.GetInterfaces() |> ProvidedType.CreateArray ctxt - member __.GetMethods() = x.GetMethods(bindingFlags) |> ProvidedMethodInfo.CreateArray ctxt - member __.GetEvents() = x.GetEvents(bindingFlags) |> ProvidedEventInfo.CreateArray ctxt + member __.GetMethods() = x.GetMethods bindingFlags |> ProvidedMethodInfo.CreateArray ctxt + member __.GetEvents() = x.GetEvents bindingFlags |> ProvidedEventInfo.CreateArray ctxt member __.GetEvent nm = x.GetEvent(nm, bindingFlags) |> ProvidedEventInfo.Create ctxt - member __.GetProperties() = x.GetProperties(bindingFlags) |> ProvidedPropertyInfo.CreateArray ctxt + member __.GetProperties() = x.GetProperties bindingFlags |> ProvidedPropertyInfo.CreateArray ctxt member __.GetProperty nm = x.GetProperty(nm, bindingFlags) |> ProvidedPropertyInfo.Create ctxt - member __.GetConstructors() = x.GetConstructors(bindingFlags) |> ProvidedConstructorInfo.CreateArray ctxt - member __.GetFields() = x.GetFields(bindingFlags) |> ProvidedFieldInfo.CreateArray ctxt + member __.GetConstructors() = x.GetConstructors bindingFlags |> ProvidedConstructorInfo.CreateArray ctxt + member __.GetFields() = x.GetFields bindingFlags |> ProvidedFieldInfo.CreateArray ctxt member __.GetField nm = x.GetField(nm, bindingFlags) |> ProvidedFieldInfo.Create ctxt member __.GetAllNestedTypes() = x.GetNestedTypes(bindingFlags ||| BindingFlags.NonPublic) |> ProvidedType.CreateArray ctxt - member __.GetNestedTypes() = x.GetNestedTypes(bindingFlags) |> ProvidedType.CreateArray ctxt + member __.GetNestedTypes() = x.GetNestedTypes bindingFlags |> ProvidedType.CreateArray ctxt /// Type.GetNestedType(string) can return null if there is no nested type with given name member __.GetNestedType nm = x.GetNestedType (nm, bindingFlags) |> ProvidedType.Create ctxt /// Type.GetGenericTypeDefinition() either returns type or throws exception, null is not permitted member __.GetGenericTypeDefinition() = x.GetGenericTypeDefinition() |> ProvidedType.CreateWithNullCheck ctxt "GenericTypeDefinition" /// Type.BaseType can be null when Type is interface or object member __.BaseType = x.BaseType |> ProvidedType.Create ctxt - member __.GetStaticParameters(provider: ITypeProvider) = provider.GetStaticParameters(x) |> ProvidedParameterInfo.CreateArray ctxt + member __.GetStaticParameters(provider: ITypeProvider) = provider.GetStaticParameters x |> ProvidedParameterInfo.CreateArray ctxt /// Type.GetElementType can be null if i.e. Type is not array\pointer\byref type member __.GetElementType() = x.GetElementType() |> ProvidedType.Create ctxt member __.GetGenericArguments() = x.GetGenericArguments() |> ProvidedType.CreateArray ctxt member __.ApplyStaticArguments(provider: ITypeProvider, fullTypePathAfterArguments, staticArgs: obj[]) = provider.ApplyStaticArguments(x, fullTypePathAfterArguments, staticArgs) |> ProvidedType.Create ctxt - member __.IsVoid = (typeof.Equals(x) || (x.Namespace = "System" && x.Name = "Void")) + member __.IsVoid = (typeof.Equals x || (x.Namespace = "System" && x.Name = "Void")) member __.IsGenericParameter = x.IsGenericParameter member __.IsValueType = x.IsValueType member __.IsByRef = x.IsByRef @@ -414,7 +344,9 @@ module internal ExtensionTyping = member __.IsNestedPublic = x.IsNestedPublic member __.IsEnum = x.IsEnum member __.IsClass = x.IsClass + member __.IsMeasure = isMeasure.Value member __.IsSealed = x.IsSealed + member __.IsAbstract = x.IsAbstract member __.IsInterface = x.IsInterface member __.GetArrayRank() = x.GetArrayRank() member __.GenericParameterPosition = x.GenericParameterPosition @@ -422,7 +354,14 @@ module internal ExtensionTyping = /// Type.GetEnumUnderlyingType either returns type or raises exception, null is not permitted member __.GetEnumUnderlyingType() = x.GetEnumUnderlyingType() - |> ProvidedType.CreateWithNullCheck ctxt "EnumUnderlyingType" + |> ProvidedType.CreateWithNullCheck ctxt "EnumUnderlyingType" + member __.MakePointerType() = ProvidedType.CreateNoContext(x.MakePointerType()) + member __.MakeByRefType() = ProvidedType.CreateNoContext(x.MakeByRefType()) + member __.MakeArrayType() = ProvidedType.CreateNoContext(x.MakeArrayType()) + member __.MakeArrayType rank = ProvidedType.CreateNoContext(x.MakeArrayType(rank)) + member __.MakeGenericType (args: ProvidedType[]) = + let argTypes = args |> Array.map (fun arg -> arg.RawSystemType) + ProvidedType.CreateNoContext(x.MakeGenericType(argTypes)) static member Create ctxt x = match x with null -> null | t -> ProvidedType (t, ctxt) static member CreateWithNullCheck ctxt name x = match x with null -> nullArg name | t -> ProvidedType (t, ctxt) static member CreateArray ctxt xs = match xs with null -> null | _ -> xs |> Array.map (ProvidedType.Create ctxt) @@ -453,7 +392,7 @@ module internal ExtensionTyping = let findAttrib (ty: System.Type) a = findAttribByName ty.FullName a { new IProvidedCustomAttributeProvider with member __.GetAttributeConstructorArgs (provider, attribName) = - attributes(provider) + attributes provider |> Seq.tryFind (findAttribByName attribName) |> Option.map (fun a -> let ctorArgs = @@ -467,19 +406,19 @@ module internal ExtensionTyping = ctorArgs, namedArgs) member __.GetHasTypeProviderEditorHideMethodsAttribute provider = - attributes(provider) + attributes provider |> Seq.exists (findAttrib typeof) - member __.GetDefinitionLocationAttribute(provider) = - attributes(provider) + member __.GetDefinitionLocationAttribute provider = + attributes provider |> Seq.tryFind (findAttrib typeof) |> Option.map (fun a -> (defaultArg (a.NamedArguments |> Seq.tryPick (function Member "FilePath" (Arg (:? string as v)) -> Some v | _ -> None)) null, defaultArg (a.NamedArguments |> Seq.tryPick (function Member "Line" (Arg (:? int as v)) -> Some v | _ -> None)) 0, defaultArg (a.NamedArguments |> Seq.tryPick (function Member "Column" (Arg (:? int as v)) -> Some v | _ -> None)) 0)) - member __.GetXmlDocAttributes(provider) = - attributes(provider) + member __.GetXmlDocAttributes provider = + attributes provider |> Seq.choose (fun a -> if findAttrib typeof a then match a.ConstructorArguments |> Seq.toList with @@ -496,9 +435,9 @@ module internal ExtensionTyping = /// DeclaringType can be null if MemberInfo belongs to Module, not to Type member __.DeclaringType = ProvidedType.Create ctxt x.DeclaringType interface IProvidedCustomAttributeProvider with - member __.GetHasTypeProviderEditorHideMethodsAttribute(provider) = provide().GetHasTypeProviderEditorHideMethodsAttribute(provider) - member __.GetDefinitionLocationAttribute(provider) = provide().GetDefinitionLocationAttribute(provider) - member __.GetXmlDocAttributes(provider) = provide().GetXmlDocAttributes(provider) + member __.GetHasTypeProviderEditorHideMethodsAttribute provider = provide().GetHasTypeProviderEditorHideMethodsAttribute provider + member __.GetDefinitionLocationAttribute provider = provide().GetDefinitionLocationAttribute provider + member __.GetXmlDocAttributes provider = provide().GetXmlDocAttributes provider member __.GetAttributeConstructorArgs (provider, attribName) = provide().GetAttributeConstructorArgs (provider, attribName) and [] @@ -515,20 +454,20 @@ module internal ExtensionTyping = static member Create ctxt x = match x with null -> null | t -> ProvidedParameterInfo (t, ctxt) static member CreateArray ctxt xs = match xs with null -> null | _ -> xs |> Array.map (ProvidedParameterInfo.Create ctxt) // TODO null wrong? interface IProvidedCustomAttributeProvider with - member __.GetHasTypeProviderEditorHideMethodsAttribute(provider) = provide().GetHasTypeProviderEditorHideMethodsAttribute(provider) - member __.GetDefinitionLocationAttribute(provider) = provide().GetDefinitionLocationAttribute(provider) - member __.GetXmlDocAttributes(provider) = provide().GetXmlDocAttributes(provider) + member __.GetHasTypeProviderEditorHideMethodsAttribute provider = provide().GetHasTypeProviderEditorHideMethodsAttribute provider + member __.GetDefinitionLocationAttribute provider = provide().GetDefinitionLocationAttribute provider + member __.GetXmlDocAttributes provider = provide().GetXmlDocAttributes provider member __.GetAttributeConstructorArgs (provider, attribName) = provide().GetAttributeConstructorArgs (provider, attribName) member __.Handle = x override __.Equals y = assert false; match y with :? ProvidedParameterInfo as y -> x.Equals y.Handle | _ -> false override __.GetHashCode() = assert false; x.GetHashCode() and [] - ProvidedAssembly (x: System.Reflection.Assembly, _ctxt) = + ProvidedAssembly (x: System.Reflection.Assembly) = member __.GetName() = x.GetName() member __.FullName = x.FullName - member __.GetManifestModuleContents(provider: ITypeProvider) = provider.GetGeneratedAssemblyContents(x) - static member Create ctxt x = match x with null -> null | t -> ProvidedAssembly (t, ctxt) + member __.GetManifestModuleContents(provider: ITypeProvider) = provider.GetGeneratedAssemblyContents x + static member Create (x: System.Reflection.Assembly) = match x with null -> null | t -> ProvidedAssembly (t) member __.Handle = x override __.Equals y = assert false; match y with :? ProvidedAssembly as y -> x.Equals y.Handle | _ -> false override __.GetHashCode() = assert false; x.GetHashCode() @@ -562,10 +501,13 @@ module internal ExtensionTyping = let staticParams = match provider with | :? ITypeProvider2 as itp2 -> - itp2.GetStaticParametersForMethod(x) + itp2.GetStaticParametersForMethod x | _ -> - // To allow a type provider to depend only on FSharp.Core 4.3.0.0, it can alternatively implement an appropriate method called GetStaticParametersForMethod - let meth = provider.GetType().GetMethod( "GetStaticParametersForMethod", bindingFlags, null, [| typeof |], null) + // To allow a type provider to depend only on FSharp.Core 4.3.0.0, it can alternatively + // implement an appropriate method called GetStaticParametersForMethod + let meth = + provider.GetType().GetMethod( "GetStaticParametersForMethod", bindingFlags, null, + [| typeof |], null) if isNull meth then [| |] else let paramsAsObj = try meth.Invoke(provider, bindingFlags ||| BindingFlags.InvokeMethod, null, [| box x |], null) @@ -582,8 +524,12 @@ module internal ExtensionTyping = | :? ITypeProvider2 as itp2 -> itp2.ApplyStaticArgumentsForMethod(x, fullNameAfterArguments, staticArgs) | _ -> + // To allow a type provider to depend only on FSharp.Core 4.3.0.0, it can alternatively implement a method called GetStaticParametersForMethod - let meth = provider.GetType().GetMethod( "ApplyStaticArgumentsForMethod", bindingFlags, null, [| typeof; typeof; typeof |], null) + let meth = + provider.GetType().GetMethod( "ApplyStaticArgumentsForMethod", bindingFlags, null, + [| typeof; typeof; typeof |], null) + match meth with | null -> failwith (FSComp.SR.estApplyStaticArgumentsForMethodNotImplemented()) | _ -> @@ -635,9 +581,7 @@ module internal ExtensionTyping = static member CreateArray ctxt xs = match xs with null -> null | _ -> xs |> Array.map (ProvidedMethodInfo.Create ctxt) member __.Handle = x -#if !FX_NO_REFLECTION_METADATA_TOKENS member __.MetadataToken = x.MetadataToken -#endif override __.Equals y = assert false; match y with :? ProvidedMethodInfo as y -> x.Equals y.Handle | _ -> false override __.GetHashCode() = assert false; x.GetHashCode() @@ -687,172 +631,105 @@ module internal ExtensionTyping = override __.Equals y = assert false; match y with :? ProvidedConstructorInfo as y -> x.Equals y.Handle | _ -> false override __.GetHashCode() = assert false; x.GetHashCode() - [] - type ProvidedExpr (x: Quotations.Expr, ctxt) = + type ProvidedExprType = + | ProvidedNewArrayExpr of ProvidedType * ProvidedExpr[] +#if PROVIDED_ADDRESS_OF + | ProvidedAddressOfExpr of ProvidedExpr +#endif + | ProvidedNewObjectExpr of ProvidedConstructorInfo * ProvidedExpr[] + | ProvidedWhileLoopExpr of ProvidedExpr * ProvidedExpr + | ProvidedNewDelegateExpr of ProvidedType * ProvidedVar[] * ProvidedExpr + | ProvidedForIntegerRangeLoopExpr of ProvidedVar * ProvidedExpr * ProvidedExpr * ProvidedExpr + | ProvidedSequentialExpr of ProvidedExpr * ProvidedExpr + | ProvidedTryWithExpr of ProvidedExpr * ProvidedVar * ProvidedExpr * ProvidedVar * ProvidedExpr + | ProvidedTryFinallyExpr of ProvidedExpr * ProvidedExpr + | ProvidedLambdaExpr of ProvidedVar * ProvidedExpr + | ProvidedCallExpr of ProvidedExpr option * ProvidedMethodInfo * ProvidedExpr[] + | ProvidedConstantExpr of obj * ProvidedType + | ProvidedDefaultExpr of ProvidedType + | ProvidedNewTupleExpr of ProvidedExpr[] + | ProvidedTupleGetExpr of ProvidedExpr * int + | ProvidedTypeAsExpr of ProvidedExpr * ProvidedType + | ProvidedTypeTestExpr of ProvidedExpr * ProvidedType + | ProvidedLetExpr of ProvidedVar * ProvidedExpr * ProvidedExpr + | ProvidedVarSetExpr of ProvidedVar * ProvidedExpr + | ProvidedIfThenElseExpr of ProvidedExpr * ProvidedExpr * ProvidedExpr + | ProvidedVarExpr of ProvidedVar + + and [] + ProvidedExpr (x: Quotations.Expr, ctxt) = member __.Type = x.Type |> ProvidedType.Create ctxt member __.Handle = x member __.Context = ctxt member __.UnderlyingExpressionString = x.ToString() + member __.GetExprType() = + match x with + | Quotations.Patterns.NewObject(ctor, args) -> + Some (ProvidedNewObjectExpr (ProvidedConstructorInfo.Create ctxt ctor, [| for a in args -> ProvidedExpr.Create ctxt a |])) + | Quotations.Patterns.WhileLoop(guardExpr, bodyExpr) -> + Some (ProvidedWhileLoopExpr (ProvidedExpr.Create ctxt guardExpr, ProvidedExpr.Create ctxt bodyExpr)) + | Quotations.Patterns.NewDelegate(ty, vs, expr) -> + Some (ProvidedNewDelegateExpr(ProvidedType.Create ctxt ty, ProvidedVar.CreateArray ctxt (List.toArray vs), ProvidedExpr.Create ctxt expr)) + | Quotations.Patterns.Call(objOpt, meth, args) -> + Some (ProvidedCallExpr((match objOpt with None -> None | Some obj -> Some (ProvidedExpr.Create ctxt obj)), + ProvidedMethodInfo.Create ctxt meth, [| for a in args -> ProvidedExpr.Create ctxt a |])) + | Quotations.Patterns.DefaultValue ty -> + Some (ProvidedDefaultExpr (ProvidedType.Create ctxt ty)) + | Quotations.Patterns.Value(obj, ty) -> + Some (ProvidedConstantExpr (obj, ProvidedType.Create ctxt ty)) + | Quotations.Patterns.Coerce(arg, ty) -> + Some (ProvidedTypeAsExpr (ProvidedExpr.Create ctxt arg, ProvidedType.Create ctxt ty)) + | Quotations.Patterns.NewTuple args -> + Some (ProvidedNewTupleExpr(ProvidedExpr.CreateArray ctxt (Array.ofList args))) + | Quotations.Patterns.TupleGet(arg, n) -> + Some (ProvidedTupleGetExpr (ProvidedExpr.Create ctxt arg, n)) + | Quotations.Patterns.NewArray(ty, args) -> + Some (ProvidedNewArrayExpr(ProvidedType.Create ctxt ty, ProvidedExpr.CreateArray ctxt (Array.ofList args))) + | Quotations.Patterns.Sequential(e1, e2) -> + Some (ProvidedSequentialExpr(ProvidedExpr.Create ctxt e1, ProvidedExpr.Create ctxt e2)) + | Quotations.Patterns.Lambda(v, body) -> + Some (ProvidedLambdaExpr (ProvidedVar.Create ctxt v, ProvidedExpr.Create ctxt body)) + | Quotations.Patterns.TryFinally(b1, b2) -> + Some (ProvidedTryFinallyExpr (ProvidedExpr.Create ctxt b1, ProvidedExpr.Create ctxt b2)) + | Quotations.Patterns.TryWith(b, v1, e1, v2, e2) -> + Some (ProvidedTryWithExpr (ProvidedExpr.Create ctxt b, ProvidedVar.Create ctxt v1, ProvidedExpr.Create ctxt e1, ProvidedVar.Create ctxt v2, ProvidedExpr.Create ctxt e2)) +#if PROVIDED_ADDRESS_OF + | Quotations.Patterns.AddressOf e -> Some (ProvidedAddressOfExpr (ProvidedExpr.Create ctxt e)) +#endif + | Quotations.Patterns.TypeTest(e, ty) -> + Some (ProvidedTypeTestExpr(ProvidedExpr.Create ctxt e, ProvidedType.Create ctxt ty)) + | Quotations.Patterns.Let(v, e, b) -> + Some (ProvidedLetExpr (ProvidedVar.Create ctxt v, ProvidedExpr.Create ctxt e, ProvidedExpr.Create ctxt b)) + | Quotations.Patterns.ForIntegerRangeLoop (v, e1, e2, e3) -> + Some (ProvidedForIntegerRangeLoopExpr (ProvidedVar.Create ctxt v, ProvidedExpr.Create ctxt e1, ProvidedExpr.Create ctxt e2, ProvidedExpr.Create ctxt e3)) + | Quotations.Patterns.VarSet(v, e) -> + Some (ProvidedVarSetExpr (ProvidedVar.Create ctxt v, ProvidedExpr.Create ctxt e)) + | Quotations.Patterns.IfThenElse(g, t, e) -> + Some (ProvidedIfThenElseExpr (ProvidedExpr.Create ctxt g, ProvidedExpr.Create ctxt t, ProvidedExpr.Create ctxt e)) + | Quotations.Patterns.Var v -> + Some (ProvidedVarExpr (ProvidedVar.Create ctxt v)) + | _ -> None static member Create ctxt t = match box t with null -> null | _ -> ProvidedExpr (t, ctxt) static member CreateArray ctxt xs = match xs with null -> null | _ -> xs |> Array.map (ProvidedExpr.Create ctxt) override __.Equals y = match y with :? ProvidedExpr as y -> x.Equals y.Handle | _ -> false override __.GetHashCode() = x.GetHashCode() - [] - type ProvidedVar (x: Quotations.Var, ctxt) = + and [] + ProvidedVar (x: Quotations.Var, ctxt) = member __.Type = x.Type |> ProvidedType.Create ctxt member __.Name = x.Name member __.IsMutable = x.IsMutable member __.Handle = x member __.Context = ctxt static member Create ctxt t = match box t with null -> null | _ -> ProvidedVar (t, ctxt) - static member Fresh (nm, ty: ProvidedType) = ProvidedVar.Create ty.Context (new Quotations.Var(nm, ty.Handle)) + static member Fresh (nm, ty: ProvidedType) = ProvidedVar.Create ty.Context (Quotations.Var(nm, ty.Handle)) static member CreateArray ctxt xs = match xs with null -> null | _ -> xs |> Array.map (ProvidedVar.Create ctxt) override __.Equals y = match y with :? ProvidedVar as y -> x.Equals y.Handle | _ -> false override __.GetHashCode() = x.GetHashCode() - - /// Detect a provided new-object expression - let (|ProvidedNewObjectExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.NewObject(ctor, args) -> - Some (ProvidedConstructorInfo.Create x.Context ctor, [| for a in args -> ProvidedExpr.Create x.Context a |]) - | _ -> None - - /// Detect a provided while-loop expression - let (|ProvidedWhileLoopExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.WhileLoop(guardExpr, bodyExpr) -> - Some (ProvidedExpr.Create x.Context guardExpr, ProvidedExpr.Create x.Context bodyExpr) - | _ -> None - - /// Detect a provided new-delegate expression - let (|ProvidedNewDelegateExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.NewDelegate(ty, vs, expr) -> - Some (ProvidedType.Create x.Context ty, ProvidedVar.CreateArray x.Context (List.toArray vs), ProvidedExpr.Create x.Context expr) - | _ -> None - - /// Detect a provided call expression - let (|ProvidedCallExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.Call(objOpt, meth, args) -> - Some ((match objOpt with None -> None | Some obj -> Some (ProvidedExpr.Create x.Context obj)), - ProvidedMethodInfo.Create x.Context meth, - [| for a in args -> ProvidedExpr.Create x.Context a |]) - | _ -> None - - /// Detect a provided default-value expression - let (|ProvidedDefaultExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.DefaultValue ty -> Some (ProvidedType.Create x.Context ty) - | _ -> None - - /// Detect a provided constant expression - let (|ProvidedConstantExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.Value(obj, ty) -> Some (obj, ProvidedType.Create x.Context ty) - | _ -> None - - /// Detect a provided type-as expression - let (|ProvidedTypeAsExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.Coerce(arg, ty) -> Some (ProvidedExpr.Create x.Context arg, ProvidedType.Create x.Context ty) - | _ -> None - - /// Detect a provided new-tuple expression - let (|ProvidedNewTupleExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.NewTuple(args) -> Some (ProvidedExpr.CreateArray x.Context (Array.ofList args)) - | _ -> None - - /// Detect a provided tuple-get expression - let (|ProvidedTupleGetExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.TupleGet(arg, n) -> Some (ProvidedExpr.Create x.Context arg, n) - | _ -> None - - /// Detect a provided new-array expression - let (|ProvidedNewArrayExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.NewArray(ty, args) -> Some (ProvidedType.Create x.Context ty, ProvidedExpr.CreateArray x.Context (Array.ofList args)) - | _ -> None - - /// Detect a provided sequential expression - let (|ProvidedSequentialExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.Sequential(e1, e2) -> Some (ProvidedExpr.Create x.Context e1, ProvidedExpr.Create x.Context e2) - | _ -> None - - /// Detect a provided lambda expression - let (|ProvidedLambdaExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.Lambda(v, body) -> Some (ProvidedVar.Create x.Context v, ProvidedExpr.Create x.Context body) - | _ -> None - - /// Detect a provided try/finally expression - let (|ProvidedTryFinallyExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.TryFinally(b1, b2) -> Some (ProvidedExpr.Create x.Context b1, ProvidedExpr.Create x.Context b2) - | _ -> None - - /// Detect a provided try/with expression - let (|ProvidedTryWithExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.TryWith(b, v1, e1, v2, e2) -> Some (ProvidedExpr.Create x.Context b, ProvidedVar.Create x.Context v1, ProvidedExpr.Create x.Context e1, ProvidedVar.Create x.Context v2, ProvidedExpr.Create x.Context e2) - | _ -> None - -#if PROVIDED_ADDRESS_OF - let (|ProvidedAddressOfExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.AddressOf(e) -> Some (ProvidedExpr.Create x.Context e) - | _ -> None -#endif - - /// Detect a provided type-test expression - let (|ProvidedTypeTestExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.TypeTest(e, ty) -> Some (ProvidedExpr.Create x.Context e, ProvidedType.Create x.Context ty) - | _ -> None - - /// Detect a provided 'let' expression - let (|ProvidedLetExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.Let(v, e, b) -> Some (ProvidedVar.Create x.Context v, ProvidedExpr.Create x.Context e, ProvidedExpr.Create x.Context b) - | _ -> None - - - /// Detect a provided expression which is a for-loop over integers - let (|ProvidedForIntegerRangeLoopExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.ForIntegerRangeLoop (v, e1, e2, e3) -> - Some (ProvidedVar.Create x.Context v, - ProvidedExpr.Create x.Context e1, - ProvidedExpr.Create x.Context e2, - ProvidedExpr.Create x.Context e3) - | _ -> None - - /// Detect a provided 'set variable' expression - let (|ProvidedVarSetExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.VarSet(v, e) -> Some (ProvidedVar.Create x.Context v, ProvidedExpr.Create x.Context e) - | _ -> None - - /// Detect a provided 'IfThenElse' expression - let (|ProvidedIfThenElseExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.IfThenElse(g, t, e) -> Some (ProvidedExpr.Create x.Context g, ProvidedExpr.Create x.Context t, ProvidedExpr.Create x.Context e) - | _ -> None - - /// Detect a provided 'Var' expression - let (|ProvidedVarExpr|_|) (x: ProvidedExpr) = - match x.Handle with - | Quotations.Patterns.Var v -> Some (ProvidedVar.Create x.Context v) - | _ -> None - /// Get the provided invoker expression for a particular use of a method. let GetInvokerExpression (provider: ITypeProvider, methodBase: ProvidedMethodBase, paramExprs: ProvidedVar[]) = - provider.GetInvokerExpression(methodBase.Handle, [| for p in paramExprs -> Quotations.Expr.Var(p.Handle) |]) |> ProvidedExpr.Create methodBase.Context + provider.GetInvokerExpression(methodBase.Handle, [| for p in paramExprs -> Quotations.Expr.Var (p.Handle) |]) |> ProvidedExpr.Create methodBase.Context /// Compute the Name or FullName property of a provided type, reporting appropriate errors let CheckAndComputeProvidedNameProperty(m, st: Tainted, proj, propertyString) = @@ -862,16 +739,16 @@ module internal ExtensionTyping = let newError = tpe.MapText((fun msg -> FSComp.SR.etProvidedTypeWithNameException(propertyString, msg)), st.TypeProviderDesignation, m) raise newError if String.IsNullOrEmpty name then - raise (TypeProviderError(FSComp.SR.etProvidedTypeWithNullOrEmptyName(propertyString), st.TypeProviderDesignation, m)) + raise (TypeProviderError(FSComp.SR.etProvidedTypeWithNullOrEmptyName propertyString, st.TypeProviderDesignation, m)) name /// Verify that this type provider has supported attributes let ValidateAttributesOfProvidedType (m, st: Tainted) = let fullName = CheckAndComputeProvidedNameProperty(m, st, (fun st -> st.FullName), "FullName") if TryTypeMember(st, fullName, "IsGenericType", m, false, fun st->st.IsGenericType) |> unmarshal then - errorR(Error(FSComp.SR.etMustNotBeGeneric(fullName), m)) + errorR(Error(FSComp.SR.etMustNotBeGeneric fullName, m)) if TryTypeMember(st, fullName, "IsArray", m, false, fun st->st.IsArray) |> unmarshal then - errorR(Error(FSComp.SR.etMustNotBeAnArray(fullName), m)) + errorR(Error(FSComp.SR.etMustNotBeAnArray fullName, m)) TryTypeMemberNonNull(st, fullName, "GetInterfaces", m, [||], fun st -> st.GetInterfaces()) |> ignore @@ -885,7 +762,7 @@ module internal ExtensionTyping = let rec declaringTypes (st: Tainted) accu = match TryTypeMember(st, name, "DeclaringType", m, null, fun st -> st.DeclaringType) with | Tainted.Null -> accu - | dt -> declaringTypes dt (CheckAndComputeProvidedNameProperty(m, dt, (fun dt -> dt.Name), "Name")::accu) + | dt -> declaringTypes dt (CheckAndComputeProvidedNameProperty(m, dt, (fun dt -> dt.Name), "Name") :: accu) let path = [| match namespaceName with | null -> () @@ -905,16 +782,16 @@ module internal ExtensionTyping = let namespaceName = TryTypeMember(st, name, "Namespace", m, FSComp.SR.invalidNamespaceForProvidedType(), fun st -> st.Namespace) |> unmarshal let fullName = TryTypeMemberNonNull(st, name, "FullName", m, FSComp.SR.invalidFullNameForProvidedType(), fun st -> st.FullName) |> unmarshal ValidateExpectedName m expectedPath expectedName st - // Must be able to call (GetMethods|GetEvents|GetPropeties|GetNestedTypes|GetConstructors)(bindingFlags). + // Must be able to call (GetMethods|GetEvents|GetProperties|GetNestedTypes|GetConstructors)(bindingFlags). let usedMembers : Tainted[] = // These are the members the compiler will actually use - [| for x in TryTypeMemberArray(st, fullName, "GetMethods", m, fun st -> st.GetMethods()) -> x.Coerce(m) - for x in TryTypeMemberArray(st, fullName, "GetEvents", m, fun st -> st.GetEvents()) -> x.Coerce(m) - for x in TryTypeMemberArray(st, fullName, "GetFields", m, fun st -> st.GetFields()) -> x.Coerce(m) - for x in TryTypeMemberArray(st, fullName, "GetProperties", m, fun st -> st.GetProperties()) -> x.Coerce(m) + [| for x in TryTypeMemberArray(st, fullName, "GetMethods", m, fun st -> st.GetMethods()) -> x.Coerce m + for x in TryTypeMemberArray(st, fullName, "GetEvents", m, fun st -> st.GetEvents()) -> x.Coerce m + for x in TryTypeMemberArray(st, fullName, "GetFields", m, fun st -> st.GetFields()) -> x.Coerce m + for x in TryTypeMemberArray(st, fullName, "GetProperties", m, fun st -> st.GetProperties()) -> x.Coerce m // These will be validated on-demand - //for x in TryTypeMemberArray(st, fullName, "GetNestedTypes", m, fun st -> st.GetNestedTypes(bindingFlags)) -> x.Coerce() - for x in TryTypeMemberArray(st, fullName, "GetConstructors", m, fun st -> st.GetConstructors()) -> x.Coerce(m) |] + //for x in TryTypeMemberArray(st, fullName, "GetNestedTypes", m, fun st -> st.GetNestedTypes bindingFlags) -> x.Coerce() + for x in TryTypeMemberArray(st, fullName, "GetConstructors", m, fun st -> st.GetConstructors()) -> x.Coerce m |] fullName, namespaceName, usedMembers // We scrutinize namespaces for invalid characters on open, but this provides better diagnostics @@ -926,11 +803,11 @@ module internal ExtensionTyping = // This needs to be a *shallow* exploration. Otherwise, as in Freebase sample the entire database could be explored. for mi in usedMembers do match mi with - | Tainted.Null -> errorR(Error(FSComp.SR.etNullMember(fullName), m)) + | Tainted.Null -> errorR(Error(FSComp.SR.etNullMember fullName, m)) | _ -> let memberName = TryMemberMember(mi, fullName, "Name", "Name", m, "invalid provided type member name", fun mi -> mi.Name) |> unmarshal - if String.IsNullOrEmpty(memberName) then - errorR(Error(FSComp.SR.etNullOrEmptyMemberName(fullName), m)) + if String.IsNullOrEmpty memberName then + errorR(Error(FSComp.SR.etNullOrEmptyMemberName fullName, m)) else let miDeclaringType = TryMemberMember(mi, fullName, memberName, "DeclaringType", m, ProvidedType.CreateNoContext(typeof), fun mi -> mi.DeclaringType) match miDeclaringType with @@ -940,8 +817,11 @@ module internal ExtensionTyping = errorR(Error(FSComp.SR.etNullMemberDeclaringType(fullName, memberName), m)) | _ -> let miDeclaringTypeFullName = - TryMemberMember(miDeclaringType, fullName, memberName, "FullName", m, "invalid declaring type full name", fun miDeclaringType -> miDeclaringType.FullName) + TryMemberMember (miDeclaringType, fullName, memberName, "FullName", m, + "invalid declaring type full name", + fun miDeclaringType -> miDeclaringType.FullName) |> unmarshal + if not (ProvidedType.TaintedEquals (st, miDeclaringType)) then errorR(Error(FSComp.SR.etNullMemberDeclaringTypeDifferentFromProvidedType(fullName, memberName, miDeclaringTypeFullName), m)) @@ -1015,7 +895,7 @@ module internal ExtensionTyping = | -1 -> () | n -> errorR(Error(FSComp.SR.etIllegalCharactersInTypeName(string expectedName.[n], expectedName), m)) - let staticParameters = st.PApplyWithProvider((fun (st, provider) -> st.GetStaticParameters(provider)), range=m) + let staticParameters = st.PApplyWithProvider((fun (st, provider) -> st.GetStaticParameters provider), range=m) if staticParameters.PUntaint((fun a -> a.Length), m) = 0 then ValidateProvidedTypeAfterStaticInstantiation(m, st, expectedPath, expectedName) @@ -1095,7 +975,7 @@ module internal ExtensionTyping = else let mangledName = let nm = methBeforeArgs.PUntaint((fun x -> x.Name), m) - let staticParams = methBeforeArgs.PApplyWithProvider((fun (mb, resolver) -> mb.GetStaticParametersForMethod(resolver)), range=m) + let staticParams = methBeforeArgs.PApplyWithProvider((fun (mb, resolver) -> mb.GetStaticParametersForMethod resolver), range=m) let mangledName = ComputeMangledNameForApplyStaticParameters(nm, staticArgs, staticParams, m) mangledName @@ -1122,7 +1002,7 @@ module internal ExtensionTyping = // Otherwise, use the full path of the erased type, including mangled arguments let nm = typeBeforeArguments.PUntaint((fun x -> x.Name), m) let enc, _ = ILPathToProvidedType (typeBeforeArguments, m) - let staticParams = typeBeforeArguments.PApplyWithProvider((fun (mb, resolver) -> mb.GetStaticParameters(resolver)), range=m) + let staticParams = typeBeforeArguments.PApplyWithProvider((fun (mb, resolver) -> mb.GetStaticParameters resolver), range=m) let mangledName = ComputeMangledNameForApplyStaticParameters(nm, staticArgs, staticParams, m) enc @ [ mangledName ] @@ -1145,7 +1025,7 @@ module internal ExtensionTyping = try PrettyNaming.demangleProvidedTypeName typeLogicalName with PrettyNaming.InvalidMangledStaticArg piece -> - error(Error(FSComp.SR.etProvidedTypeReferenceInvalidText(piece), range0)) + error(Error(FSComp.SR.etProvidedTypeReferenceInvalidText piece, range0)) let argSpecsTable = dict argNamesAndValues let typeBeforeArguments = ResolveProvidedType(resolver, range0, moduleOrNamespace, typeName) @@ -1155,7 +1035,9 @@ module internal ExtensionTyping = | _ -> // Take the static arguments (as strings, taken from the text in the reference we're relinking), // and convert them to objects of the appropriate type, based on the expected kind. - let staticParameters = typeBeforeArguments.PApplyWithProvider((fun (typeBeforeArguments, resolver) -> typeBeforeArguments.GetStaticParameters(resolver)), range=range0) + let staticParameters = + typeBeforeArguments.PApplyWithProvider((fun (typeBeforeArguments, resolver) -> + typeBeforeArguments.GetStaticParameters resolver),range=range0) let staticParameters = staticParameters.PApplyArray(id, "", m) @@ -1163,14 +1045,13 @@ module internal ExtensionTyping = staticParameters |> Array.map (fun sp -> let typeBeforeArgumentsName = typeBeforeArguments.PUntaint ((fun st -> st.Name), m) let spName = sp.PUntaint ((fun sp -> sp.Name), m) - match argSpecsTable.TryGetValue(spName) with + match argSpecsTable.TryGetValue spName with | true, arg -> /// Find the name of the representation type for the static parameter let spReprTypeName = sp.PUntaint((fun sp -> - let pt = sp.ParameterType - let ut = pt.RawSystemType - let uet = if pt.IsEnum then ut.GetEnumUnderlyingType() else ut + let pt = sp.ParameterType + let uet = if pt.IsEnum then pt.GetEnumUnderlyingType() else pt uet.FullName), m) match spReprTypeName with @@ -1196,7 +1077,7 @@ module internal ExtensionTyping = | null -> error (Error(FSComp.SR.etStaticParameterRequiresAValue (spName, typeBeforeArgumentsName, typeBeforeArgumentsName, spName), range0)) | v -> v else - error(Error(FSComp.SR.etProvidedTypeReferenceMissingArgument(spName), range0))) + error(Error(FSComp.SR.etProvidedTypeReferenceMissingArgument spName, range0))) match TryApplyProvidedType(typeBeforeArguments, None, staticArgs, range0) with diff --git a/src/fcs-fable/src/fsharp/ExtensionTyping.fsi b/src/fcs-fable/src/fsharp/ExtensionTyping.fsi index d4b58be8cb..b672b0481d 100755 --- a/src/fcs-fable/src/fsharp/ExtensionTyping.fsi +++ b/src/fcs-fable/src/fsharp/ExtensionTyping.fsi @@ -54,6 +54,7 @@ module internal ExtensionTyping = * isInteractive: bool * systemRuntimeContainsType : (string -> bool) * systemRuntimeAssemblyVersion : System.Version + * compilerToolsPath : string list * range -> Tainted list /// Given an extension type resolver, supply a human-readable name suitable for error messages. @@ -119,7 +120,9 @@ module internal ExtensionTyping = member IsEnum : bool member IsInterface : bool member IsClass : bool + member IsMeasure: bool member IsSealed : bool + member IsAbstract : bool member IsPublic : bool member IsNestedPublic : bool member GenericParameterPosition : int @@ -128,6 +131,11 @@ module internal ExtensionTyping = member GetArrayRank : unit -> int member RawSystemType : System.Type member GetEnumUnderlyingType : unit -> ProvidedType + member MakePointerType: unit -> ProvidedType + member MakeByRefType: unit -> ProvidedType + member MakeArrayType: unit -> ProvidedType + member MakeArrayType: rank: int -> ProvidedType + member MakeGenericType: args: ProvidedType[] -> ProvidedType static member Void : ProvidedType static member CreateNoContext : Type -> ProvidedType member TryGetILTypeRef : unit -> ILTypeRef option @@ -181,9 +189,7 @@ module internal ExtensionTyping = ProvidedMethodInfo = inherit ProvidedMethodBase member ReturnType : ProvidedType -#if !FX_NO_REFLECTION_METADATA_TOKENS member MetadataToken : int -#endif and [] ProvidedParameterInfo = @@ -236,15 +242,41 @@ module internal ExtensionTyping = and [] ProvidedConstructorInfo = inherit ProvidedMethodBase + + type ProvidedExprType = + | ProvidedNewArrayExpr of ProvidedType * ProvidedExpr[] +#if PROVIDED_ADDRESS_OF + | ProvidedAddressOfExpr of ProvidedExpr +#endif + | ProvidedNewObjectExpr of ProvidedConstructorInfo * ProvidedExpr[] + | ProvidedWhileLoopExpr of ProvidedExpr * ProvidedExpr + | ProvidedNewDelegateExpr of ProvidedType * ProvidedVar[] * ProvidedExpr + | ProvidedForIntegerRangeLoopExpr of ProvidedVar * ProvidedExpr * ProvidedExpr * ProvidedExpr + | ProvidedSequentialExpr of ProvidedExpr * ProvidedExpr + | ProvidedTryWithExpr of ProvidedExpr * ProvidedVar * ProvidedExpr * ProvidedVar * ProvidedExpr + | ProvidedTryFinallyExpr of ProvidedExpr * ProvidedExpr + | ProvidedLambdaExpr of ProvidedVar * ProvidedExpr + | ProvidedCallExpr of ProvidedExpr option * ProvidedMethodInfo * ProvidedExpr[] + | ProvidedConstantExpr of obj * ProvidedType + | ProvidedDefaultExpr of ProvidedType + | ProvidedNewTupleExpr of ProvidedExpr[] + | ProvidedTupleGetExpr of ProvidedExpr * int + | ProvidedTypeAsExpr of ProvidedExpr * ProvidedType + | ProvidedTypeTestExpr of ProvidedExpr * ProvidedType + | ProvidedLetExpr of ProvidedVar * ProvidedExpr * ProvidedExpr + | ProvidedVarSetExpr of ProvidedVar * ProvidedExpr + | ProvidedIfThenElseExpr of ProvidedExpr * ProvidedExpr * ProvidedExpr + | ProvidedVarExpr of ProvidedVar - [] - type ProvidedExpr = + and [] + ProvidedExpr = member Type : ProvidedType /// Convert the expression to a string for diagnostics member UnderlyingExpressionString : string + member GetExprType : unit -> ProvidedExprType option - [] - type ProvidedVar = + and [] + ProvidedVar = member Type : ProvidedType member Name : string member IsMutable : bool @@ -252,70 +284,6 @@ module internal ExtensionTyping = override Equals : obj -> bool override GetHashCode : unit -> int - /// Detect a provided new-array expression - val (|ProvidedNewArrayExpr|_|) : ProvidedExpr -> (ProvidedType * ProvidedExpr[]) option - -#if PROVIDED_ADDRESS_OF - val (|ProvidedAddressOfExpr|_|) : ProvidedExpr -> ProvidedExpr option -#endif - - /// Detect a provided new-object expression - val (|ProvidedNewObjectExpr|_|) : ProvidedExpr -> (ProvidedConstructorInfo * ProvidedExpr[]) option - - /// Detect a provided while-loop expression - val (|ProvidedWhileLoopExpr|_|) : ProvidedExpr -> (ProvidedExpr * ProvidedExpr) option - - /// Detect a provided new-delegate expression - val (|ProvidedNewDelegateExpr|_|) : ProvidedExpr -> (ProvidedType * ProvidedVar[] * ProvidedExpr) option - - /// Detect a provided expression which is a for-loop over integers - val (|ProvidedForIntegerRangeLoopExpr|_|) : ProvidedExpr -> (ProvidedVar * ProvidedExpr * ProvidedExpr * ProvidedExpr) option - - /// Detect a provided sequential expression - val (|ProvidedSequentialExpr|_|) : ProvidedExpr -> (ProvidedExpr * ProvidedExpr) option - - /// Detect a provided try/with expression - val (|ProvidedTryWithExpr|_|) : ProvidedExpr -> (ProvidedExpr * ProvidedVar * ProvidedExpr * ProvidedVar * ProvidedExpr) option - - /// Detect a provided try/finally expression - val (|ProvidedTryFinallyExpr|_|) : ProvidedExpr -> (ProvidedExpr * ProvidedExpr) option - - /// Detect a provided lambda expression - val (|ProvidedLambdaExpr|_|) : ProvidedExpr -> (ProvidedVar * ProvidedExpr) option - - /// Detect a provided call expression - val (|ProvidedCallExpr|_|) : ProvidedExpr -> (ProvidedExpr option * ProvidedMethodInfo * ProvidedExpr[]) option - - /// Detect a provided constant expression - val (|ProvidedConstantExpr|_|) : ProvidedExpr -> (obj * ProvidedType) option - - /// Detect a provided default-value expression - val (|ProvidedDefaultExpr|_|) : ProvidedExpr -> ProvidedType option - - /// Detect a provided new-tuple expression - val (|ProvidedNewTupleExpr|_|) : ProvidedExpr -> ProvidedExpr[] option - - /// Detect a provided tuple-get expression - val (|ProvidedTupleGetExpr|_|) : ProvidedExpr -> (ProvidedExpr * int) option - - /// Detect a provided type-as expression - val (|ProvidedTypeAsExpr|_|) : ProvidedExpr -> (ProvidedExpr * ProvidedType) option - - /// Detect a provided type-test expression - val (|ProvidedTypeTestExpr|_|) : ProvidedExpr -> (ProvidedExpr * ProvidedType) option - - /// Detect a provided 'let' expression - val (|ProvidedLetExpr|_|) : ProvidedExpr -> (ProvidedVar * ProvidedExpr * ProvidedExpr) option - - /// Detect a provided 'set variable' expression - val (|ProvidedVarSetExpr|_|) : ProvidedExpr -> (ProvidedVar * ProvidedExpr) option - - /// Detect a provided 'IfThenElse' expression - val (|ProvidedIfThenElseExpr|_|) : ProvidedExpr -> (ProvidedExpr * ProvidedExpr * ProvidedExpr) option - - /// Detect a provided 'Var' expression - val (|ProvidedVarExpr|_|) : ProvidedExpr -> ProvidedVar option - /// Get the provided expression for a particular use of a method. val GetInvokerExpression : ITypeProvider * ProvidedMethodBase * ProvidedVar[] -> ProvidedExpr diff --git a/src/fcs-fable/src/fsharp/FSComp.txt b/src/fcs-fable/src/fsharp/FSComp.txt old mode 100755 new mode 100644 index ae91c46ed3..bbcd42bf9f --- a/src/fcs-fable/src/fsharp/FSComp.txt +++ b/src/fcs-fable/src/fsharp/FSComp.txt @@ -1,9 +1,10 @@ -# ----------------------------------------------------------------------------- -# use a completely new error number and add new messages at the end of the file -# ----------------------------------------------------------------------------- +# ------------------------------------------------------------------------------- +# use a completely new error number and keep messages in their surrounding groups +# ------------------------------------------------------------------------------- undefinedNameNamespace,"The namespace '%s' is not defined." undefinedNameNamespaceOrModule,"The namespace or module '%s' is not defined." undefinedNameFieldConstructorOrMember,"The field, constructor or member '%s' is not defined." +undefinedNameFieldConstructorOrMemberWhenTypeIsKnown,"The type '%s' does not define the field, constructor or member '%s'." undefinedNameValueConstructorNamespaceOrType,"The value, constructor, namespace or type '%s' is not defined." undefinedNameValueOfConstructor,"The value or constructor '%s' is not defined." undefinedNameValueNamespaceTypeOrModule,"The value, namespace, type or module '%s' is not defined." @@ -43,7 +44,6 @@ buildProductNameCommunity,"F# Compiler for F# %s" 212,buildInvalidFilename,"'%s' is not a valid filename" 213,buildInvalidAssemblyName,"'%s' is not a valid assembly name" 214,buildInvalidPrivacy,"Unrecognized privacy setting '%s' for managed resource, valid options are 'public' and 'private'" -215,buildMultipleReferencesNotAllowed,"Multiple references to '%s.dll' are not permitted" 218,buildCannotReadAssembly,"Unable to read assembly '%s'" 220,buildAssemblyResolutionFailed,"Assembly resolution failure at or near this location" 221,buildImplicitModuleIsNotLegalIdentifier,"The declarations in this file will be placed in an implicit module '%s' based on the file name '%s'. However this is not a valid F# identifier, so the contents will not be accessible from other files. Consider renaming the file or adding a 'module' or 'namespace' declaration at the top of the file." @@ -73,6 +73,7 @@ buildProductNameCommunity,"F# Compiler for F# %s" pickleErrorReadingWritingMetadata,"Error reading/writing metadata for the F# compiled DLL '%s'. Was the DLL compiled with an earlier version of the F# compiler? (error: '%s')." 245,tastTypeOrModuleNotConcrete,"The type/module '%s' is not a concrete module or type" tastTypeHasAssemblyCodeRepresentation,"The type '%s' has an inline assembly code representation" +246,optsUnrecognizedLanguageVersion,"Unrecognized value '%s' for --langversion use --langversion:? for complete list" 247,tastNamespaceAndModuleWithSameNameInAssembly,"A namespace and a module named '%s' both occur in two parts of this assembly" 248,tastTwoModulesWithSameNameInAssembly,"Two modules named '%s' occur in two parts of this assembly" 249,tastDuplicateTypeDefinitionInAssembly,"Two type definitions named '%s' occur in namespace '%s' in two parts of this assembly" @@ -193,6 +194,10 @@ ExceptionDefsNotCompatibleFieldOrderDiffers,"The exception definitions are not c 364,typrelNamedArgumentHasBeenAssignedMoreThenOnce,"A named argument has been assigned more than one value" 365,typrelNoImplementationGiven,"No implementation was given for '%s'" 366,typrelNoImplementationGivenWithSuggestion,"No implementation was given for '%s'. Note that all interface members must be implemented and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'." +365,typrelNoImplementationGivenSeveral,"No implementation was given for those members: %s" +366,typrelNoImplementationGivenSeveralWithSuggestion,"No implementation was given for those members: %sNote that all interface members must be implemented and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'." +365,typrelNoImplementationGivenSeveralTruncated,"No implementation was given for those members (some results omitted): %s" +366,typrelNoImplementationGivenSeveralTruncatedWithSuggestion,"No implementation was given for those members (some results omitted): %sNote that all interface members must be implemented and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'." 367,typrelMemberDoesNotHaveCorrectNumberOfArguments,"The member '%s' does not have the correct number of arguments. The required signature is '%s'." 368,typrelMemberDoesNotHaveCorrectNumberOfTypeParameters,"The member '%s' does not have the correct number of method type parameters. The required signature is '%s'." 369,typrelMemberDoesNotHaveCorrectKindsOfGenericParameters,"The member '%s' does not have the correct kinds of generic parameters. The required signature is '%s'." @@ -357,9 +362,16 @@ csCtorHasNoArgumentOrReturnProperty,"The object constructor '%s' has no argument 508,csNoMemberTakesTheseArguments3,"No %s member or object constructor named '%s' takes %d arguments. The named argument '%s' doesn't correspond to any argument or settable return property for any overload." 509,csMethodNotFound,"Method or object constructor '%s' not found" csNoOverloadsFound,"No overloads match for method '%s'." +csNoOverloadsFoundArgumentsPrefixSingular,"Known type of argument: %s" +csNoOverloadsFoundArgumentsPrefixPlural,"Known types of arguments: %s" +csNoOverloadsFoundTypeParametersPrefixSingular,"Known type parameter: %s" +csNoOverloadsFoundTypeParametersPrefixPlural,"Known type parameters: %s" +csNoOverloadsFoundReturnType,"Known return type: %s" csMethodIsOverloaded,"A unique overload for method '%s' could not be determined based on type information prior to this program point. A type annotation may be needed." -csCandidates,"Candidates: %s" -csSeeAvailableOverloads,"The available overloads are shown below." +csCandidates,"Candidates:\n%s" +csAvailableOverloads,"Available overloads:\n%s" +csOverloadCandidateNamedArgumentTypeMismatch,"Argument '%s' doesn't match" +csOverloadCandidateIndexedArgumentTypeMismatch,"Argument at index %d doesn't match" 512,parsDoCannotHaveVisibilityDeclarations,"Accessibility modifiers are not permitted on 'do' bindings, but '%s' was given." 513,parsEofInHashIf,"End of file in #if section begun at or after here" 514,parsEofInString,"End of file in string begun at or before here" @@ -416,6 +428,7 @@ parsAttributesMustComeBeforeVal,"Attributes should be placed before 'val'" 568,parsAllEnumFieldsRequireValues,"All enum fields must be given values" 569,parsInlineAssemblyCannotHaveVisibilityDeclarations,"Accessibility modifiers are not permitted on inline assembly code types" 571,parsUnexpectedIdentifier,"Unexpected identifier: '%s'" +10,parsUnexpectedSymbolDot,"Unexpected symbol '.' in member definition. Expected 'with', '=' or other token." 572,parsUnionCasesCannotHaveVisibilityDeclarations,"Accessibility modifiers are not permitted on union cases. Use 'type U = internal ...' or 'type U = private ...' to give an accessibility to the whole representation." 573,parsEnumFieldsCannotHaveVisibilityDeclarations,"Accessibility modifiers are not permitted on enumeration fields" parsConsiderUsingSeparateRecordType,"Consider using a separate record type instead" @@ -840,6 +853,7 @@ optsNoOpt,"Only include optimization information essential for implementing inli optsNoInterface,"Don't add a resource to the generated assembly containing F#-specific metadata" optsSig,"Print the inferred interface of the assembly to a file" optsReference,"Reference an assembly (Short form: -r)" +optsCompilerTool,"Reference an assembly or directory containing a design time tool (Short form: -t)" optsWin32res,"Specify a Win32 resource file (.res)" optsWin32manifest,"Specify a Win32 manifest file" optsNowin32manifest,"Do not include the default Win32 manifest" @@ -856,6 +870,7 @@ optsDebug,"Specify debugging type: full, portable, embedded, pdbonly. ('%s' is t optsOptimize,"Enable optimizations (Short form: -O)" optsTailcalls,"Enable or disable tailcalls" optsDeterministic,"Produce a deterministic assembly (including module version GUID and timestamp)" +optsPathMap,"Maps physical paths to source path names output by the compiler" optsCrossoptimize,"Enable or disable cross-module optimizations" optsWarnaserrorPM,"Report all warnings as errors" optsWarnaserror,"Report specific warnings as errors" @@ -873,6 +888,7 @@ optsUtf8output,"Output messages in UTF-8 encoding" optsFullpaths,"Output messages with fully qualified paths" optsLib,"Specify a directory for the include path which is used to resolve source files and assemblies (Short form: -I)" optsBaseaddress,"Base address for the library to be built" +optsChecksumAlgorithm,"Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default)" optsNoframework,"Do not reference the default CLI assemblies by default" optsStandalone,"Statically link the F# library and all referenced DLLs that depend on it into the assembly being generated" optsStaticlink,"Statically link the given assembly and all referenced DLLs that depend on this assembly. Use an assembly name e.g. mylib, not a DLL name." @@ -895,6 +911,7 @@ optsHelpBannerLanguage,"- LANGUAGE -" optsHelpBannerErrsAndWarns,"- ERRORS AND WARNINGS -" 1063,optsUnknownArgumentToTheTestSwitch,"Unknown --test argument: '%s'" 1064,optsUnknownPlatform,"Unrecognized platform '%s', valid values are 'x86', 'x64', 'Itanium', 'anycpu32bitpreferred', and 'anycpu'" +1065,optsUnknownChecksumAlgorithm,"Algorithm '%s' is not supported" optsInternalNoDescription,"The command-line option '%s' is for test purposes only" optsDCLONoDescription,"The command-line option '%s' has been deprecated" optsDCLODeprecatedSuggestAlternative,"The command-line option '%s' has been deprecated. Use '%s' instead." @@ -1004,7 +1021,7 @@ lexUnexpectedChar,"Unexpected character '%s'" 1153,lexInvalidFloat,"Invalid floating point number" 1154,lexOusideDecimal,"This number is outside the allowable range for decimal literals" 1155,lexOusideThirtyTwoBitFloat,"This number is outside the allowable range for 32-bit floats" -1156,lexInvalidNumericLiteral,"This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0b0001 (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger)." +1156,lexInvalidNumericLiteral,"This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger)." 1157,lexInvalidByteLiteral,"This is not a valid byte literal" 1158,lexInvalidCharLiteral,"This is not a valid character literal" 1159,lexThisUnicodeOnlyInStringLiterals,"This Unicode encoding is only valid in string literals" @@ -1078,7 +1095,6 @@ lexIndentOffForML,"Consider using a file with extension '.ml' or '.mli' instead" 1219,tcUnionCaseNameConflictsWithGeneratedType,"The union case named '%s' conflicts with the generated type '%s'" 1220,chkNoReflectedDefinitionOnStructMember,"ReflectedDefinitionAttribute may not be applied to an instance member on a struct type, because the instance member takes an implicit 'this' byref parameter" 1221,tcDllImportNotAllowed,"DLLImport bindings must be static members in a class or function definitions in a module" -1222,buildExplicitCoreLibRequiresNoFramework,"When mscorlib.dll or FSharp.Core.dll is explicitly referenced the %s option must also be passed" 1223,buildExpectedSigdataFile,"FSharp.Core.sigdata not found alongside FSharp.Core. File expected in %s. Consider upgrading to a more recent version of FSharp.Core, where this file is no longer be required." 1225,buildExpectedFileAlongSideFSharpCore,"File '%s' not found alongside FSharp.Core. File expected in %s. Consider upgrading to a more recent version of FSharp.Core, where this file is no longer be required." 1227,buildUnexpectedFileNameCharacter,"Filename '%s' contains invalid character '%s'" @@ -1136,7 +1152,9 @@ fscTooManyErrors,"Exiting - too many errors" 2023,fscResxSourceFileDeprecated,"Passing a .resx file (%s) as a source file to the compiler is deprecated. Use resgen.exe to transform the .resx file into a .resources file to pass as a --resource option. If you are using MSBuild, this can be done via an item in the .fsproj project file." 2024,fscStaticLinkingNoProfileMismatches,"Static linking may not be used on an assembly referencing mscorlib (e.g. a .NET Framework assembly) when generating an assembly that references System.Runtime (e.g. a .NET Core or Portable assembly)." 2025,fscAssemblyWildcardAndDeterminism,"An %s specified version '%s', but this value is a wildcard, and you have requested a deterministic build, these are in conflict." -2026,fscDeterministicDebugRequiresPortablePdb,"Determinstic builds only support portable PDBs (--debug:portable or --debug:embedded)" +2026,fscDeterministicDebugRequiresPortablePdb,"Deterministic builds only support portable PDBs (--debug:portable or --debug:embedded)" +2027,fscPathMapDebugRequiresPortablePdb,"--pathmap can only be used with portable PDBs (--debug:portable or --debug:embedded)" +2028,optsInvalidPathMapFormat,"Invalid path map. Mappings must be comma separated and of the format 'path=sourcePath'" 3000,etIllegalCharactersInNamespaceName,"Character '%s' is not allowed in provided namespace name '%s'" 3001,etNullOrEmptyMemberName,"The provided type '%s' returned a member with a null or empty member name" 3002,etNullMember,"The provided type '%s' returned a null member" @@ -1342,8 +1360,13 @@ tcGlobalsSystemTypeNotFound,"The system type '%s' was required but no referenced 3213,typrelMemberHasMultiplePossibleDispatchSlots,"The member '%s' matches multiple overloads of the same method.\nPlease restrict it to one of the following:%s." 3214,methodIsNotStatic,"Method or object constructor '%s' is not static" 3215,parsUnexpectedSymbolEqualsInsteadOfIn,"Unexpected symbol '=' in expression. Did you intend to use 'for x in y .. z do' instead?" +3216,packageManagerUnknown,"Package manager key '%s' was not registered in %s. Currently registered: %s" +3217,packageManagerError,"%s" tcAnonRecdCcuMismatch,"Two anonymous record types are from different assemblies '%s' and '%s'" -tcAnonRecdFieldNameMismatch,"Two anonymous record types have mismatched sets of field names '%s' and '%s'" +tcAnonRecdFieldNameMismatch,"This anonymous record does not exactly match the expected shape. Add the missing fields %s and remove the extra fields %s." +tcAnonRecdFieldNameSubset,"This anonymous record does not have enough fields. Add the missing fields %s." +tcAnonRecdFieldNameSuperset,"This anonymous record has too many fields. Remove the extra fields %s." +tcAnonRecdFieldNameDifferent,"This is the wrong anonymous record. It should have the fields %s." keywordDescriptionAbstract,"Indicates a method that either has no implementation in the type in which it is declared or that is virtual and has a default implementation." keyworkDescriptionAnd,"Used in mutually recursive bindings, in property declarations, and with multiple constraints on generic parameters." keywordDescriptionAs,"Used to give the current class object an object name. Also used to give a name to a whole pattern within a pattern match." @@ -1452,5 +1475,37 @@ notAFunctionButMaybeDeclaration,"This value is not a function and cannot be appl 3243,parsInvalidAnonRecdExpr,"Invalid anonymous record expression" 3244,parsInvalidAnonRecdType,"Invalid anonymous record type" 3245,tcCopyAndUpdateNeedsRecordType,"The input to a copy-and-update expression that creates an anonymous record must be either an anonymous record or a record" +3246,tcAugmentationsCannotHaveAttributes,"Attributes cannot be applied to type extensions." +3247,couldNotLoadDependencyManagerExtension,"The dependency manager extension %s could not be loaded. Message: %s" +3250,expressionHasNoName,"Expression does not have a name." +3251,chkNoFirstClassNameOf,"Using the 'nameof' operator as a first-class function value is not permitted." 3300,chkInvalidFunctionParameterType,"The parameter '%s' has an invalid type '%s'. This is not permitted by the rules of Common IL." 3301,chkInvalidFunctionReturnType,"The function or method has an invalid return type '%s'. This is not permitted by the rules of Common IL." +3302,packageManagementRequiresVFive,"The package management feature requires language version 5.0 use /langversion:preview" +3303,fromEndSlicingRequiresVFive,"From the end slicing with requires language version 5.0, use /langversion:preview." +3343,tcRequireMergeSourcesOrBindN,"The 'let! ... and! ...' construct may only be used if the computation expression builder defines either a '%s' method or appropriate 'MergeSource' and 'Bind' methods" +3344,tcAndBangNotSupported,"This feature is not supported in this version of F#. You may need to add /langversion:preview to use this feature." +3345,tcInvalidUseBangBindingNoAndBangs,"use! may not be combined with and!" +3350,chkFeatureNotLanguageSupported,"Feature '%s' is not available in F# %s. Please use language version %s or greater." +3351,chkFeatureNotRuntimeSupported,"Feature '%s' is not supported by target runtime." +3352,typrelInterfaceMemberNoMostSpecificImplementation,"Interface member '%s' does not have a most specific implementation." +useSdkRefs,"Use reference assemblies for .NET framework references when available (Enabled by default)." +fSharpBannerVersion,"%s for F# %s" +optsLangVersion,"Display the allowed values for language version, specify language version such as 'latest' or 'preview'" +optsSupportedLangVersions,"Supported language versions:" +nativeResourceFormatError,"Stream does not begin with a null resource and is not in '.RES' format." +nativeResourceHeaderMalformed,"Resource header beginning at offset %s is malformed." +formatDashItem," - %s" +featureSingleUnderscorePattern,"single underscore pattern" +featureWildCardInForLoop,"wild card in for loop" +featureRelaxWhitespace,"whitespace relexation" +featureNameOf,"nameof" +featureImplicitYield,"implicit yield" +featureOpenStaticClasses,"open static classes" +featureDotlessFloat32Literal,"dotless float32 literal" +featurePackageManagement,"package management" +featureFromEndSlicing,"from-end slicing" +featureFixedIndexSlice3d4d,"fixed-index slice 3d/4d" +featureAndBang,"applicative computation expressions" +featureNullableOptionalInterop,"nullable optional interop" +featureDefaultInterfaceMemberConsumption,"default interface member consumption" diff --git a/src/fcs-fable/src/fsharp/FSInteractiveSettings.txt b/src/fcs-fable/src/fsharp/FSInteractiveSettings.txt old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/fsharp/FSStrings.resx b/src/fcs-fable/src/fsharp/FSStrings.resx old mode 100755 new mode 100644 index 05cd75cc66..e755b590b4 --- a/src/fcs-fable/src/fsharp/FSStrings.resx +++ b/src/fcs-fable/src/fsharp/FSStrings.resx @@ -159,12 +159,6 @@ Discriminated union cases and exception labels must be uppercase identifiers - - Possible overload: '{0}'. {1}. - - - \n\nPossible best overload: '{0}'. - This function takes too many arguments, or is used in a context where a function is not expected @@ -327,6 +321,9 @@ symbol '..' + + symbol '..^' + quote symbol @@ -564,6 +561,9 @@ keyword 'and' + ! + keyword 'and!' + keyword 'as' diff --git a/src/fcs-fable/src/fsharp/FSharp.Compiler.nuget/Directory.Build.props b/src/fcs-fable/src/fsharp/FSharp.Compiler.nuget/Directory.Build.props deleted file mode 100644 index 8093275dba..0000000000 --- a/src/fcs-fable/src/fsharp/FSharp.Compiler.nuget/Directory.Build.props +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - netcoreapp2.1 - Microsoft.FSharp.Compiler.nuspec - - - diff --git a/src/fcs-fable/src/fsharp/FSharp.Compiler.nuget/Directory.Build.targets b/src/fcs-fable/src/fsharp/FSharp.Compiler.nuget/Directory.Build.targets deleted file mode 100644 index 2721c93a90..0000000000 --- a/src/fcs-fable/src/fsharp/FSharp.Compiler.nuget/Directory.Build.targets +++ /dev/null @@ -1,18 +0,0 @@ - - - - -rtm-$(NuGetPackageVersionSuffix) - $(FSPackageVersion)$(PreReleaseSuffix) - - - - - - - - - - - - - diff --git a/src/fcs-fable/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.Prerelease.csproj b/src/fcs-fable/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.Prerelease.csproj deleted file mode 100644 index 692e5aba1b..0000000000 --- a/src/fcs-fable/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.Prerelease.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Microsoft.FSharp.Compiler - true - - - diff --git a/src/fcs-fable/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.csproj b/src/fcs-fable/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.csproj deleted file mode 100644 index abb19e418f..0000000000 --- a/src/fcs-fable/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Microsoft.FSharp.Compiler - false - - - diff --git a/src/fcs-fable/src/fsharp/FSharp.Compiler.nuget/Testing.FSharp.Compiler.csproj b/src/fcs-fable/src/fsharp/FSharp.Compiler.nuget/Testing.FSharp.Compiler.csproj deleted file mode 100644 index aaee9c7394..0000000000 --- a/src/fcs-fable/src/fsharp/FSharp.Compiler.nuget/Testing.FSharp.Compiler.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Testing.FSharp.Compiler - true - - - diff --git a/src/fcs-fable/src/fsharp/FindUnsolved.fs b/src/fcs-fable/src/fsharp/FindUnsolved.fs old mode 100755 new mode 100644 index 280a623460..a5cf703516 --- a/src/fcs-fable/src/fsharp/FindUnsolved.fs +++ b/src/fcs-fable/src/fsharp/FindUnsolved.fs @@ -1,14 +1,14 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. - /// Find unsolved, uninstantiated type variables module internal FSharp.Compiler.FindUnsolved open FSharp.Compiler open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals open FSharp.Compiler.TypeRelations @@ -21,6 +21,8 @@ type cenv = denv: DisplayEnv mutable unsolved: Typars } + override x.ToString() = "" + /// Walk types, collecting type variables let accTy cenv _env ty = let normalizedTy = tryNormalizeMeasureInType cenv.g ty @@ -48,7 +50,7 @@ let rec accExpr (cenv:cenv) (env:env) expr = | Expr.Val (_v, _vFlags, _m) -> () - | Expr.Quote(ast, _, _, _m, ty) -> + | Expr.Quote (ast, _, _, _m, ty) -> accExpr cenv env ast accTy cenv env ty @@ -68,27 +70,27 @@ let rec accExpr (cenv:cenv) (env:env) expr = | Expr.Op (c, tyargs, args, m) -> accOp cenv env (c, tyargs, args, m) - | Expr.App(f, fty, tyargs, argsl, _m) -> + | Expr.App (f, fty, tyargs, argsl, _m) -> accTy cenv env fty accTypeInst cenv env tyargs accExpr cenv env f accExprs cenv env argsl - | Expr.Lambda(_, _ctorThisValOpt, _baseValOpt, argvs, _body, m, rty) -> + | Expr.Lambda (_, _ctorThisValOpt, _baseValOpt, argvs, _body, m, rty) -> let topValInfo = ValReprInfo ([], [argvs |> List.map (fun _ -> ValReprInfo.unnamedTopArg1)], ValReprInfo.unnamedRetVal) let ty = mkMultiLambdaTy m argvs rty accLambdas cenv env topValInfo expr ty - | Expr.TyLambda(_, tps, _body, _m, rty) -> + | Expr.TyLambda (_, tps, _body, _m, rty) -> let topValInfo = ValReprInfo (ValReprInfo.InferTyparInfo tps, [], ValReprInfo.unnamedRetVal) accTy cenv env rty let ty = mkForallTyIfNeeded tps rty accLambdas cenv env topValInfo expr ty - | Expr.TyChoose(_tps, e1, _m) -> + | Expr.TyChoose (_tps, e1, _m) -> accExpr cenv env e1 - | Expr.Match(_, _exprm, dtree, targets, m, ty) -> + | Expr.Match (_, _exprm, dtree, targets, m, ty) -> accTy cenv env ty accDTree cenv env dtree accTargets cenv env m ty targets @@ -133,7 +135,7 @@ and accOp cenv env (op, tyargs, args, _m) = accTypeInst cenv env enclTypeArgs accTypeInst cenv env methTypeArgs accTypeInst cenv env tys - | TOp.TraitCall(TTrait(tys, _nm, _, argtys, rty, _sln)) -> + | TOp.TraitCall (TTrait(tys, _nm, _, argtys, rty, _sln)) -> argtys |> accTypeInst cenv env rty |> Option.iter (accTy cenv env) tys |> List.iter (accTy cenv env) @@ -144,7 +146,7 @@ and accOp cenv env (op, tyargs, args, _m) = and accLambdas cenv env topValInfo e ety = match e with - | Expr.TyChoose(_tps, e1, _m) -> accLambdas cenv env topValInfo e1 ety + | Expr.TyChoose (_tps, e1, _m) -> accLambdas cenv env topValInfo e1 ety | Expr.Lambda _ | Expr.TyLambda _ -> let _tps, ctorThisValOpt, baseValOpt, vsl, body, bodyty = destTopLambda cenv.g cenv.amap topValInfo (e, ety) @@ -186,6 +188,7 @@ and accDiscrim cenv env d = | DecisionTreeTest.ActivePatternCase (exp, tys, _, _, _) -> accExpr cenv env exp accTypeInst cenv env tys + | DecisionTreeTest.Error _ -> () and accAttrib cenv env (Attrib(_, _k, args, props, _, _, _m)) = args |> List.iter (fun (AttribExpr(expr1, expr2)) -> diff --git a/src/fcs-fable/src/fsharp/FindUnsolved.fsi b/src/fcs-fable/src/fsharp/FindUnsolved.fsi new file mode 100644 index 0000000000..48d3dc3a43 --- /dev/null +++ b/src/fcs-fable/src/fsharp/FindUnsolved.fsi @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + + +module internal FSharp.Compiler.FindUnsolved + +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.Import + +/// Find all unsolved inference variables after type inference for an entire file +val UnsolvedTyparsOfModuleDef: g: TcGlobals -> amap: ImportMap -> denv: DisplayEnv -> mdef : ModuleOrNamespaceExpr * extraAttribs: Attrib list -> Typar list diff --git a/src/fcs-fable/src/fsharp/IlxGen.fs b/src/fcs-fable/src/fsharp/IlxGen.fs old mode 100755 new mode 100644 index 6b7bda2370..9209eb68fb --- a/src/fcs-fable/src/fsharp/IlxGen.fs +++ b/src/fcs-fable/src/fsharp/IlxGen.fs @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -//-------------------------------------------------------------------------- -// The ILX generator. -//-------------------------------------------------------------------------- - +/// The ILX generator. module internal FSharp.Compiler.IlxGen open System.IO @@ -13,6 +10,7 @@ open System.Collections.Generic open Internal.Utilities open Internal.Utilities.Collections +open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal @@ -20,22 +18,25 @@ open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Extensions.ILX open FSharp.Compiler.AbstractIL.Extensions.ILX.Types open FSharp.Compiler.AbstractIL.Internal.BinaryConstants - -open FSharp.Compiler open FSharp.Compiler.AttributeChecking -open FSharp.Compiler.Ast +open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Infos open FSharp.Compiler.Import open FSharp.Compiler.Layout open FSharp.Compiler.Lib +open FSharp.Compiler.LowerCallsAndSeqs open FSharp.Compiler.PrettyNaming open FSharp.Compiler.Range -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.Tastops.DebugPrint +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.TypedTreeOps.DebugPrint open FSharp.Compiler.TcGlobals open FSharp.Compiler.TypeRelations +open FSharp.Compiler.XmlDoc let IsNonErasedTypar (tp: Typar) = not tp.IsErased @@ -79,7 +80,7 @@ let ChooseParamNames fieldNamesAndTypes = fieldNamesAndTypes |> List.map (fun (ilPropName, ilFieldName, ilPropType) -> let lowerPropName = String.uncapitalize ilPropName - let ilParamName = if takenFieldNames.Contains(lowerPropName) then ilPropName else lowerPropName + let ilParamName = if takenFieldNames.Contains lowerPropName then ilPropName else lowerPropName ilParamName, ilFieldName, ilPropType) /// Approximation for purposes of optimization and giving a warning when compiling definition-only files as EXEs @@ -101,22 +102,17 @@ let ChooseFreeVarNames takenNames ts = let ts, _names = List.mapFold chooseName names tns ts -/// +++GLOBAL STATE: a name generator used by IlxGen for static fields, some generated arguments and other things. -/// REVIEW: this will mean the hosted compiler service is not deterministic. We should at least create a new one -/// of these for each compilation. -let ilxgenGlobalNng = NiceNameGenerator () - /// We can't tailcall to methods taking byrefs. This helper helps search for them let IsILTypeByref = function ILType.Byref _ -> true | _ -> false let mainMethName = CompilerGeneratedName "main" /// Used to query custom attributes when emitting COM interop code. -type AttributeDecoder (namedArgs) = +type AttributeDecoder(namedArgs) = let nameMap = namedArgs |> List.map (fun (AttribNamedArg(s, _, _, c)) -> s, c) |> NameMap.ofList - let findConst x = match NameMap.tryFind x nameMap with | Some(AttribExpr(_, Expr.Const(c, _, _))) -> Some c | _ -> None - let findAppTr x = match NameMap.tryFind x nameMap with | Some(AttribExpr(_, Expr.App(_, _, [TType_app(tr, _)], _, _))) -> Some tr | _ -> None + let findConst x = match NameMap.tryFind x nameMap with | Some(AttribExpr(_, Expr.Const (c, _, _))) -> Some c | _ -> None + let findAppTr x = match NameMap.tryFind x nameMap with | Some(AttribExpr(_, Expr.App (_, _, [TType_app(tr, _)], _, _))) -> Some tr | _ -> None member __.FindInt16 x dflt = match findConst x with | Some(Const.Int16 x) -> x | _ -> dflt @@ -126,7 +122,7 @@ type AttributeDecoder (namedArgs) = member __.FindString x dflt = match findConst x with | Some(Const.String x) -> x | _ -> dflt - member __.FindTypeName x dflt = match findAppTr x with | Some(tr) -> tr.DisplayName | _ -> dflt + member __.FindTypeName x dflt = match findAppTr x with | Some tr -> tr.DisplayName | _ -> dflt //-------------------------------------------------------------------------- // Statistics @@ -152,9 +148,9 @@ let NewCounter nm = let CountClosure = NewCounter "closures" -let CountMethodDef = NewCounter "IL method defintitions corresponding to values" +let CountMethodDef = NewCounter "IL method definitions corresponding to values" -let CountStaticFieldDef = NewCounter "IL field defintitions corresponding to values" +let CountStaticFieldDef = NewCounter "IL field definitions corresponding to values" let CountCallFuncInstructions = NewCounter "callfunc instructions (indirect calls)" @@ -197,7 +193,7 @@ type IlxGenOptions = emitConstantArraysUsingStaticDataBlobs: bool /// If this is set, then the last module becomes the "main" module and its toplevel bindings are executed at startup - mainMethodInfo: Tast.Attribs option + mainMethodInfo: Attribs option /// Indicates if local optimizations are on localOptimizationsAreOn: bool @@ -234,7 +230,7 @@ type cenv = amap: ImportMap /// A callback for TcVal in the typechecker. Used to generalize values when finding witnesses. - /// It is unfortunate this is needed but it is until we supply witnesses through the compiation. + /// It is unfortunate this is needed but it is until we supply witnesses through the compilation. TcVal: ConstraintSolver.TcValF /// The TAST for the assembly being emitted @@ -254,13 +250,22 @@ type cenv = /// Used to apply forced inlining optimizations to witnesses generated late during codegen mutable optimizeDuringCodeGen: (Expr -> Expr) + + /// What depth are we at when generating an expression? + mutable exprRecursionDepth: int + + /// Delayed Method Generation - prevents stack overflows when we need to generate methods that are split into many methods by the optimizer. + delayedGenMethods: Queue unit> } + override x.ToString() = "" + let mkTypeOfExpr cenv m ilty = - mkAsmExpr ([ mkNormalCall (mspec_Type_GetTypeFromHandle cenv.g) ], [], - [mkAsmExpr ([ I_ldtoken (ILToken.ILType ilty) ], [], [], [cenv.g.system_RuntimeTypeHandle_ty], m)], - [cenv.g.system_Type_ty], m) + let g = cenv.g + mkAsmExpr ([ mkNormalCall (mspec_Type_GetTypeFromHandle g) ], [], + [mkAsmExpr ([ I_ldtoken (ILToken.ILType ilty) ], [], [], [g.system_RuntimeTypeHandle_ty], m)], + [g.system_Type_ty], m) let mkGetNameExpr cenv (ilt: ILType) m = mkAsmExpr ([I_ldstr ilt.BasicQualifiedName], [], [], [cenv.g.string_ty], m) @@ -328,7 +333,7 @@ let NestedTypeRefForCompLoc cloc n = | [] -> let tyname = mkTopName cloc.Namespace n mkILTyRef(cloc.Scope, tyname) - | h::t -> mkILNestedTyRef(cloc.Scope, mkTopName cloc.Namespace h :: t, n) + | h :: t -> mkILNestedTyRef(cloc.Scope, mkTopName cloc.Namespace h :: t, n) let CleanUpGeneratedTypeName (nm: string) = if nm.IndexOfAny IllegalCharactersInTypeAndNamespaceNames = -1 then @@ -397,7 +402,7 @@ type TypeReprEnv(reprs: Map, count: int) = uint16 666 /// Add an additional type parameter to the environment. If the parameter is a units-of-measure parameter - /// then it is ignored, since it doesn't corespond to a .NET type parameter. + /// then it is ignored, since it doesn't correspond to a .NET type parameter. member tyenv.AddOne (tp: Typar) = if IsNonErasedTypar tp then TypeReprEnv(reprs.Add (tp.Stamp, uint16 count), count + 1) @@ -585,7 +590,7 @@ and ComputeUnionHasHelpers g (tcref: TyconRef) = elif tyconRefEq g tcref g.option_tcr_canon then SpecialFSharpOptionHelpers else match TryFindFSharpAttribute g g.attrib_DefaultAugmentationAttribute tcref.Attribs with - | Some(Attrib(_, _, [ AttribBoolArg (b) ], _, _, _, _)) -> + | Some(Attrib(_, _, [ AttribBoolArg b ], _, _, _, _)) -> if b then AllHelpers else NoHelpers | Some (Attrib(_, _, _, _, _, _, m)) -> errorR(Error(FSComp.SR.ilDefaultAugmentationAttributeCouldNotBeDecoded(), m)) @@ -652,11 +657,14 @@ and GenTypePermitVoidAux amap m tyenv ty = GenTypeAux amap m tyenv VoidOK PtrTyp // - For interactive code, we always place fields in their type/module with an accurate name let GenFieldSpecForStaticField (isInteractive, g, ilContainerTy, vspec: Val, nm, m, cloc, ilTy) = if isInteractive || HasFSharpAttribute g g.attrib_LiteralAttribute vspec.Attribs then - let fieldName = vspec.CompiledName + let fieldName = vspec.CompiledName g.CompilerGlobalState let fieldName = if isInteractive then CompilerGeneratedName fieldName else fieldName mkILFieldSpecInTy (ilContainerTy, fieldName, ilTy) else - let fieldName = ilxgenGlobalNng.FreshCompilerGeneratedName (nm, m) + let fieldName = + // Ensure that we have an g.CompilerGlobalState + assert(g.CompilerGlobalState |> Option.isSome) + g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName (nm, m) let ilFieldContainerTy = mkILTyForCompLoc (CompLocForInitClass cloc) mkILFieldSpecInTy (ilFieldContainerTy, fieldName, ilTy) @@ -770,33 +778,78 @@ and NamedLocalIlxClosureInfo = | NamedLocalIlxClosureInfoGenerator of (IlxGenEnv -> IlxClosureInfo) | NamedLocalIlxClosureInfoGenerated of IlxClosureInfo + override __.ToString() = "" + /// Indicates the overall representation decisions for all the elements of a namespace of module and ModuleStorage = - { Vals: Lazy> - SubModules: Lazy> } + { + Vals: Lazy> + + SubModules: Lazy> + } + + override __.ToString() = "" /// Indicate whether a call to the value can be implemented as /// a branch. At the moment these are only used for generating branch calls back to /// the entry label of the method currently being generated when a direct tailcall is /// made in the method itself. and BranchCallItem = + | BranchCallClosure of ArityInfo + | BranchCallMethod of // Argument counts for compiled form of F# method or value ArityInfo * // Arg infos for compiled form of F# method or value (TType * ArgReprInfo) list list * // Typars for F# method or value - Tast.Typars * + Typars * // Typars for F# method or value int * // num obj args int + + override __.ToString() = "" /// Represents a place we can branch to and Mark = | Mark of ILCodeLabel - member x.CodeLabel = (let (Mark(lab)) = x in lab) + member x.CodeLabel = (let (Mark lab) = x in lab) + +//-------------------------------------------------------------------------- +// We normally generate in the context of a "what to do next" continuation +//-------------------------------------------------------------------------- + +and sequel = + | EndFilter + + /// Exit a 'handler' block + /// The integer says which local to save result in + | LeaveHandler of (bool (* finally? *) * int * Mark) + + /// Branch to the given mark + | Br of Mark + | CmpThenBrOrContinue of Pops * ILInstr list + + /// Continue and leave the value on the IL computation stack + | Continue + + /// The value then do something else + | DiscardThen of sequel + + /// Return from the method + | Return + + /// End a scope of local variables. Used at end of 'let' and 'let rec' blocks to get tail recursive setting + /// of end-of-scope marks + | EndLocalScope of sequel * Mark + + /// Return from a method whose return type is void + | ReturnVoid + +and Pushes = ILType list +and Pops = int /// The overall environment at a particular point in an expression tree. and IlxGenEnv = @@ -831,8 +884,20 @@ and IlxGenEnv = /// Are we under the scope of a try, catch or finally? If so we can't tailcall. SEH = structured exception handling withinSEH: bool + + /// Are we inside of a recursive let binding, while loop, or a for loop? + isInLoop: bool } + override __.ToString() = "" + +let discard = DiscardThen Continue +let discardAndReturnVoid = DiscardThen ReturnVoid + +let SetIsInLoop isInLoop eenv = + if eenv.isInLoop = isInLoop then eenv + else { eenv with isInLoop = isInLoop } + let ReplaceTyenv tyenv (eenv: IlxGenEnv) = {eenv with tyenv = tyenv } let EnvForTypars tps eenv = {eenv with tyenv = TypeReprEnv.ForTypars tps } @@ -889,16 +954,16 @@ let AddStorageForLocalVals g vals eenv = List.foldBack (fun (v, s) acc -> AddSto // Lookup eenv //-------------------------------------------------------------------------- -let StorageForVal m v eenv = +let StorageForVal g m v eenv = let v = try eenv.valsInScope.[v] with :? KeyNotFoundException -> assert false - errorR(Error(FSComp.SR.ilUndefinedValue(showL(valAtBindL v)), m)) + errorR(Error(FSComp.SR.ilUndefinedValue(showL(valAtBindL g v)), m)) notlazy (Arg 668(* random value for post-hoc diagnostic analysis on generated tree *) ) v.Force() -let StorageForValRef m (v: ValRef) eenv = StorageForVal m v.Deref eenv +let StorageForValRef g m (v: ValRef) eenv = StorageForVal g m v.Deref eenv let IsValRefIsDllImport g (vref: ValRef) = vref.Attribs |> HasFSharpAttributeOpt g g.attrib_DllImportAttribute @@ -934,12 +999,15 @@ let GetMethodSpecForMemberVal amap g (memberInfo: ValMemberInfo) (vref: ValRef) else match flatArgInfos with | [] -> error(InternalError("This instance method '" + vref.LogicalName + "' has no arguments", m)) - | (h, _):: t -> h, t + | (h, _) :: t -> h, t let thisTy = if isByrefTy g thisTy then destByrefTy g thisTy else thisTy let thisArgTys = argsOfAppTy g thisTy if numParentTypars <> thisArgTys.Length then - let msg = sprintf "CodeGen check: type checking did not quantify the correct number of type variables for this method, #parentTypars = %d, #mtps = %d, #thisArgTys = %d" numParentTypars mtps.Length thisArgTys.Length + let msg = + sprintf + "CodeGen check: type checking did not quantify the correct number of type variables for this method, #parentTypars = %d, #mtps = %d, #thisArgTys = %d" + numParentTypars mtps.Length thisArgTys.Length warning(InternalError(msg, m)) else List.iter2 @@ -953,15 +1021,15 @@ let GetMethodSpecForMemberVal amap g (memberInfo: ValMemberInfo) (vref: ValRef) let isSlotSig = memberInfo.MemberFlags.IsDispatchSlot || memberInfo.MemberFlags.IsOverrideOrExplicitImpl let ilMethodArgTys = GenParamTypes amap m tyenvUnderTypars isSlotSig methodArgTys let ilMethodInst = GenTypeArgs amap m tyenvUnderTypars (List.map mkTyparTy mtps) - let mspec = mkILInstanceMethSpecInTy (ilTy, vref.CompiledName, ilMethodArgTys, ilActualRetTy, ilMethodInst) - + let mspec = mkILInstanceMethSpecInTy (ilTy, vref.CompiledName g.CompilerGlobalState, ilMethodArgTys, ilActualRetTy, ilMethodInst) + mspec, ctps, mtps, paramInfos, retInfo, methodArgTys else let methodArgTys, paramInfos = List.unzip flatArgInfos let ilMethodArgTys = GenParamTypes amap m tyenvUnderTypars false methodArgTys let ilMethodInst = GenTypeArgs amap m tyenvUnderTypars (List.map mkTyparTy mtps) - let mspec = mkILStaticMethSpecInTy (ilTy, vref.CompiledName, ilMethodArgTys, ilActualRetTy, ilMethodInst) - + let mspec = mkILStaticMethSpecInTy (ilTy, vref.CompiledName g.CompilerGlobalState , ilMethodArgTys, ilActualRetTy, ilMethodInst) + mspec, ctps, mtps, paramInfos, retInfo, methodArgTys /// Determine how a top-level value is represented, when representing as a field, by computing an ILFieldSpec @@ -984,8 +1052,8 @@ let ComputeFieldSpecForVal(optIntraAssemblyInfo: IlxGenIntraAssemblyInfo option, /// Compute the representation information for an F#-declared value (not a member nor a function). /// Mutable and literal static fields must have stable names and live in the "public" location -let ComputeStorageForFSharpValue amap g cloc optIntraAssemblyInfo optShadowLocal isInteractive returnTy (vref: ValRef) m = - let nm = vref.CompiledName +let ComputeStorageForFSharpValue amap (g:TcGlobals) cloc optIntraAssemblyInfo optShadowLocal isInteractive returnTy (vref: ValRef) m = + let nm = vref.CompiledName g.CompilerGlobalState let vspec = vref.Deref let ilTy = GenType amap m TypeReprEnv.Empty returnTy (* TypeReprEnv.Empty ok: not a field in a generic class *) let ilTyForProperty = mkILTyForCompLoc cloc @@ -1002,11 +1070,11 @@ let ComputeStorageForFSharpMember amap g topValInfo memberInfo (vref: ValRef) m let mspec, _, _, paramInfos, retInfo, methodArgTys = GetMethodSpecForMemberVal amap g memberInfo vref Method (topValInfo, vref, mspec, m, paramInfos, methodArgTys, retInfo) -/// Compute the representation information for an F#-declared function in a module or an F#-decalared extension member. +/// Compute the representation information for an F#-declared function in a module or an F#-declared extension member. /// Note, there is considerable overlap with ComputeStorageForFSharpMember/GetMethodSpecForMemberVal and these could be /// rationalized. -let ComputeStorageForFSharpFunctionOrFSharpExtensionMember amap g cloc topValInfo (vref: ValRef) m = - let nm = vref.CompiledName +let ComputeStorageForFSharpFunctionOrFSharpExtensionMember amap (g:TcGlobals) cloc topValInfo (vref: ValRef) m = + let nm = vref.CompiledName g.CompilerGlobalState let (tps, curriedArgInfos, returnTy, retInfo) = GetTopValTypeInCompiledForm g topValInfo vref.Type m let tyenvUnderTypars = TypeReprEnv.ForTypars tps let (methodArgTys, paramInfos) = curriedArgInfos |> List.concat |> List.unzip @@ -1029,7 +1097,7 @@ let IsFSharpValCompiledAsMethod g (v: Val) = | _ -> true /// Determine how a top level value is represented, when it is being represented -/// as a method. This depends on its type and other representation inforrmation. +/// as a method. This depends on its type and other representation information. /// If it's a function or is polymorphic, then it gets represented as a /// method (possibly and instance method). Otherwise it gets represented as a /// static field and property. @@ -1044,7 +1112,7 @@ let ComputeStorageForTopVal (amap, g, optIntraAssemblyInfo: IlxGenIntraAssemblyI | Some a -> a let m = vref.Range - let nm = vref.CompiledName + let nm = vref.CompiledName g.CompilerGlobalState if vref.Deref.IsCompiledAsStaticPropertyWithoutField then let nm = "get_"+nm @@ -1081,7 +1149,7 @@ let ComputeStorageForNonLocalTopVal amap g cloc modref (v: Val) = | None -> error(InternalError("ComputeStorageForNonLocalTopVal, expected an arity for " + v.LogicalName, v.Range)) | Some _ -> ComputeStorageForTopVal (amap, g, None, false, NoShadowLocal, mkNestedValRef modref v, cloc) -/// Determine how all the F#-decalred top level values, functions and members are represented, for an external module or namespace. +/// Determine how all the F#-declared top level values, functions and members are represented, for an external module or namespace. let rec AddStorageForNonLocalModuleOrNamespaceRef amap g cloc acc (modref: ModuleOrNamespaceRef) (modul: ModuleOrNamespace) = let acc = (acc, modul.ModuleOrNamespaceType.ModuleAndNamespaceDefinitions) ||> List.fold (fun acc smodul -> @@ -1146,7 +1214,7 @@ and AddBindingsForModuleDef allocVal cloc eenv x = eenv | TMAbstract(ModuleOrNamespaceExprWithSig(mtyp, _, _)) -> AddBindingsForLocalModuleType allocVal cloc eenv mtyp - | TMDefs(mdefs) -> + | TMDefs mdefs -> AddBindingsForModuleDefs allocVal cloc eenv mdefs /// Record how constructs are represented, for a module or namespace. @@ -1173,7 +1241,7 @@ and AddBindingsForModuleTopVals _g allocVal _cloc eenv vs = let AddIncrementalLocalAssemblyFragmentToIlxGenEnv (amap: ImportMap, isIncrementalFragment, g, ccu, fragName, intraAssemblyInfo, eenv, typedImplFiles) = let cloc = CompLocForFragment fragName ccu let allocVal = ComputeAndAddStorageForLocalTopVal (amap, g, intraAssemblyInfo, true, NoShadowLocal) - (eenv, typedImplFiles) ||> List.fold (fun eenv (TImplFile(qname, _, mexpr, _, _, _)) -> + (eenv, typedImplFiles) ||> List.fold (fun eenv (TImplFile (qname, _, mexpr, _, _, _)) -> let cloc = { cloc with TopImplQualifiedName = qname.Text } if isIncrementalFragment then match mexpr with @@ -1185,7 +1253,7 @@ let AddIncrementalLocalAssemblyFragmentToIlxGenEnv (amap: ImportMap, isIncrement // Generate debugging marks //-------------------------------------------------------------------------- -/// Generate IL debuging information. +/// Generate IL debugging information. let GenILSourceMarker (g: TcGlobals) (m: range) = ILSourceMarker.Create(document=g.memoize_file m.FileIndex, line=m.StartLine, @@ -1194,7 +1262,7 @@ let GenILSourceMarker (g: TcGlobals) (m: range) = endLine= m.EndLine, endColumn=m.EndColumn+1) -/// Optionally generate IL debuging information. +/// Optionally generate IL debugging information. let GenPossibleILSourceMarker cenv m = if cenv.opts.generateDebugSymbols then Some (GenILSourceMarker cenv.g m ) @@ -1238,7 +1306,7 @@ type PropKey = PropKey of string * ILTypes * ILThisConvention let AddPropertyDefToHash (m: range) (ht: Dictionary) (pdef: ILPropertyDef) = let nm = PropKey(pdef.Name, pdef.Args, pdef.CallingConv) - match ht.TryGetValue(nm) with + match ht.TryGetValue nm with | true, (idx, pd) -> ht.[nm] <- (idx, MergePropertyPair m pd pdef) | _ -> @@ -1270,11 +1338,11 @@ type TypeDefBuilder(tdef: ILTypeDef, tdefDiscards) = events = mkILEvents (tdef.Events.AsList @ ResizeArray.toList gevents), nestedTypes = mkILTypeDefs (tdef.NestedTypes.AsList @ gnested.Close())) - member b.AddEventDef(edef) = gevents.Add edef + member b.AddEventDef edef = gevents.Add edef - member b.AddFieldDef(ilFieldDef) = gfields.Add ilFieldDef + member b.AddFieldDef ilFieldDef = gfields.Add ilFieldDef - member b.AddMethodDef(ilMethodDef) = + member b.AddMethodDef ilMethodDef = let discard = match tdefDiscards with | Some (mdefDiscard, _) -> mdefDiscard ilMethodDef @@ -1322,11 +1390,11 @@ and TypeDefsBuilder() = || not (Array.isEmpty tdef.Methods.AsArray) then yield tdef ] - member b.FindTypeDefBuilder(nm) = + member b.FindTypeDefBuilder nm = try tdefs.[nm] |> snd |> fst with :? KeyNotFoundException -> failwith ("FindTypeDefBuilder: " + nm + " not found") - member b.FindNestedTypeDefsBuilder(path) = + member b.FindNestedTypeDefsBuilder path = List.fold (fun (acc: TypeDefsBuilder) x -> acc.FindTypeDefBuilder(x).NestedTypeDefs) b path member b.FindNestedTypeDefBuilder(tref: ILTypeRef) = @@ -1342,10 +1410,12 @@ type AnonTypeGenerationTable() = /// Assembly generation buffers type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbuf = + let g = cenv.g // The Abstract IL table of types let gtdefs= new TypeDefsBuilder() + // The definitions of top level values, as quotations. - let mutable reflectedDefinitions: Dictionary = Dictionary(HashIdentity.Reference) + let mutable reflectedDefinitions: Dictionary = Dictionary(HashIdentity.Reference) let mutable extraBindingsToGenerate = [] // A memoization table for generating value types for big constant arrays @@ -1353,7 +1423,7 @@ type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbu new MemoizationTable<(CompileLocation * int), ILTypeSpec> ((fun (cloc, size) -> let name = CompilerGeneratedName ("T" + string(newUnique()) + "_" + string size + "Bytes") // Type names ending ...$T_37Bytes - let vtdef = mkRawDataValueTypeDef cenv.g.iltyp_ValueType (name, size, 0us) + let vtdef = mkRawDataValueTypeDef g.iltyp_ValueType (name, size, 0us) let vtref = NestedTypeRefForCompLoc cloc vtdef.Name let vtspec = mkILTySpec(vtref, []) let vtdef = vtdef.WithAccess(ComputeTypeAccess vtref true) @@ -1363,93 +1433,102 @@ type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbu let generateAnonType genToStringMethod (isStruct, ilTypeRef, nms) = - let flds = [ for (i, nm) in Array.indexed nms -> (nm, nm + "@", ILType.TypeVar (uint16 i)) ] + let propTys = [ for (i, nm) in Array.indexed nms -> nm, ILType.TypeVar (uint16 i) ] + // Note that this alternative below would give the same names as C#, but the generated // comparison/equality doesn't know about these names. //let flds = [ for (i, nm) in Array.indexed nms -> (nm, "<" + nm + ">" + "i__Field", ILType.TypeVar (uint16 i)) ] + let ilCtorRef = mkILMethRef(ilTypeRef, ILCallingConv.Instance, ".ctor", 0, List.map snd propTys, ILType.Void) - let ilGenericParams = - [ for nm in nms -> - { Name = sprintf "<%s>j__TPar" nm - Constraints = [] - Variance=NonVariant - CustomAttrsStored = storeILCustomAttrs emptyILCustomAttrs - HasReferenceTypeConstraint=false - HasNotNullableValueTypeConstraint=false - HasDefaultConstructorConstraint= false - MetadataIndex = NoMetadataIdx } ] + let ilMethodRefs = + [| for (propName, propTy) in propTys -> + mkILMethRef (ilTypeRef, ILCallingConv.Instance, "get_" + propName, 0, [], propTy) |] - let ilTy = mkILFormalNamedTy (if isStruct then ILBoxity.AsValue else ILBoxity.AsObject) ilTypeRef ilGenericParams + let ilTy = mkILNamedTy (if isStruct then ILBoxity.AsValue else ILBoxity.AsObject) ilTypeRef (List.map snd propTys) - // Generate the IL fields - let ilFieldDefs = - mkILFields - [ for (_, fldName, fldTy) in flds -> - let fdef = mkILInstanceField (fldName, fldTy, None, ILMemberAccess.Private) - fdef.With(customAttrs = mkILCustomAttrs [ cenv.g.DebuggerBrowsableNeverAttribute ]) ] + if ilTypeRef.Scope.IsLocalRef then + + let flds = [ for (i, nm) in Array.indexed nms -> (nm, nm + "@", ILType.TypeVar (uint16 i)) ] + + let ilGenericParams = + [ for nm in nms -> + { Name = sprintf "<%s>j__TPar" nm + Constraints = [] + Variance=NonVariant + CustomAttrsStored = storeILCustomAttrs emptyILCustomAttrs + HasReferenceTypeConstraint=false + HasNotNullableValueTypeConstraint=false + HasDefaultConstructorConstraint= false + MetadataIndex = NoMetadataIdx } ] + + let ilTy = mkILFormalNamedTy (if isStruct then ILBoxity.AsValue else ILBoxity.AsObject) ilTypeRef ilGenericParams + + // Generate the IL fields + let ilFieldDefs = + mkILFields + [ for (_, fldName, fldTy) in flds -> + let fdef = mkILInstanceField (fldName, fldTy, None, ILMemberAccess.Private) + fdef.With(customAttrs = mkILCustomAttrs [ g.DebuggerBrowsableNeverAttribute ]) ] - // Generate property definitions for the fields compiled as properties - let ilProperties = - mkILProperties - [ for (i, (propName, _fldName, fldTy)) in List.indexed flds -> - ILPropertyDef.Create(name=propName, - attributes=PropertyAttributes.None, - setMethod=None, - getMethod=Some(mkILMethRef(ilTypeRef, ILCallingConv.Instance, "get_" + propName, 0, [], fldTy )), - callingConv=ILCallingConv.Instance.ThisConv, - propertyType=fldTy, - init= None, - args=[], - customAttrs=mkILCustomAttrs [ mkCompilationMappingAttrWithSeqNum cenv.g (int SourceConstructFlags.Field) i ]) ] + // Generate property definitions for the fields compiled as properties + let ilProperties = + mkILProperties + [ for (i, (propName, _fldName, fldTy)) in List.indexed flds -> + ILPropertyDef.Create(name=propName, + attributes=PropertyAttributes.None, + setMethod=None, + getMethod=Some(mkILMethRef(ilTypeRef, ILCallingConv.Instance, "get_" + propName, 0, [], fldTy )), + callingConv=ILCallingConv.Instance.ThisConv, + propertyType=fldTy, + init= None, + args=[], + customAttrs=mkILCustomAttrs [ mkCompilationMappingAttrWithSeqNum g (int SourceConstructFlags.Field) i ]) ] - let ilMethods = - [ for (propName, fldName, fldTy) in flds -> - mkLdfldMethodDef ("get_" + propName, ILMemberAccess.Public, false, ilTy, fldName, fldTy) - yield! genToStringMethod ilTy ] + let ilMethods = + [ for (propName, fldName, fldTy) in flds -> + mkLdfldMethodDef ("get_" + propName, ILMemberAccess.Public, false, ilTy, fldName, fldTy) + yield! genToStringMethod ilTy ] - let ilBaseTy = (if isStruct then cenv.g.iltyp_ValueType else cenv.g.ilg.typ_Object) + let ilBaseTy = (if isStruct then g.iltyp_ValueType else g.ilg.typ_Object) - let ilCtorDef = mkILSimpleStorageCtorWithParamNames(None, (if isStruct then None else Some ilBaseTy.TypeSpec), ilTy, [], flds, ILMemberAccess.Public) - let ilCtorRef = mkRefToILMethod(ilTypeRef, ilCtorDef) - let ilMethodRefs = [| for mdef in ilMethods -> mkRefToILMethod(ilTypeRef, mdef) |] - - if ilTypeRef.Scope.IsLocalRef then + let ilCtorDef = mkILSimpleStorageCtorWithParamNames(None, (if isStruct then None else Some ilBaseTy.TypeSpec), ilTy, [], flds, ILMemberAccess.Public) // Create a tycon that looks exactly like a record definition, to help drive the generation of equality/comparison code let m = range0 let tps = [ for nm in nms -> let stp = Typar(mkSynId m ("T"+nm), TyparStaticReq.NoStaticReq, true) - NewTypar (TyparKind.Type, TyparRigidity.WarnIfNotRigid, stp, false, TyparDynamicReq.Yes, [], true, true) ] + Construct.NewTypar (TyparKind.Type, TyparRigidity.WarnIfNotRigid, stp, false, TyparDynamicReq.Yes, [], true, true) ] let tycon = - let lmtyp = MaybeLazy.Strict (NewEmptyModuleOrNamespaceType ModuleOrType) + let lmtyp = MaybeLazy.Strict (Construct.NewEmptyModuleOrNamespaceType ModuleOrType) let cpath = CompPath(ilTypeRef.Scope, []) - NewTycon(Some cpath, ilTypeRef.Name, m, taccessPublic, taccessPublic, TyparKind.Type, LazyWithContext.NotLazy tps, XmlDoc.Empty, false, false, false, lmtyp) + Construct.NewTycon(Some cpath, ilTypeRef.Name, m, taccessPublic, taccessPublic, TyparKind.Type, LazyWithContext.NotLazy tps, XmlDoc.Empty, false, false, false, lmtyp) if isStruct then - tycon.SetIsStructRecordOrUnion(true) + tycon.SetIsStructRecordOrUnion true tycon.entity_tycon_repr <- - TRecdRepr (MakeRecdFieldsTable + TRecdRepr + (Construct.MakeRecdFieldsTable [ for (tp, (propName, _fldName, _fldTy)) in (List.zip tps flds) -> - NewRecdField false None (mkSynId m propName) false (mkTyparTy tp) true false [] [] XmlDoc.Empty taccessPublic false ]) + Construct.NewRecdField false None (mkSynId m propName) false (mkTyparTy tp) true false [] [] XmlDoc.Empty taccessPublic false ]) let tcref = mkLocalTyconRef tycon let _, typ = generalizeTyconRef tcref let tcaug = tcref.TypeContents tcaug.tcaug_interfaces <- - [ (cenv.g.mk_IStructuralComparable_ty, true, m) - (cenv.g.mk_IComparable_ty, true, m) - (mkAppTy cenv.g.system_GenericIComparable_tcref [typ], true, m) - (cenv.g.mk_IStructuralEquatable_ty, true, m) - (mkAppTy cenv.g.system_GenericIEquatable_tcref [typ], true, m) ] + [ (g.mk_IStructuralComparable_ty, true, m) + (g.mk_IComparable_ty, true, m) + (mkAppTy g.system_GenericIComparable_tcref [typ], true, m) + (g.mk_IStructuralEquatable_ty, true, m) + (mkAppTy g.system_GenericIEquatable_tcref [typ], true, m) ] - let vspec1, vspec2 = AugmentWithHashCompare.MakeValsForEqualsAugmentation cenv.g tcref - let evspec1, evspec2, evspec3 = AugmentWithHashCompare.MakeValsForEqualityWithComparerAugmentation cenv.g tcref - let cvspec1, cvspec2 = AugmentWithHashCompare.MakeValsForCompareAugmentation cenv.g tcref - let cvspec3 = AugmentWithHashCompare.MakeValsForCompareWithComparerAugmentation cenv.g tcref + let vspec1, vspec2 = AugmentWithHashCompare.MakeValsForEqualsAugmentation g tcref + let evspec1, evspec2, evspec3 = AugmentWithHashCompare.MakeValsForEqualityWithComparerAugmentation g tcref + let cvspec1, cvspec2 = AugmentWithHashCompare.MakeValsForCompareAugmentation g tcref + let cvspec3 = AugmentWithHashCompare.MakeValsForCompareWithComparerAugmentation g tcref tcaug.SetCompare (mkLocalValRef cvspec1, mkLocalValRef cvspec2) tcaug.SetCompareWith (mkLocalValRef cvspec3) @@ -1458,7 +1537,7 @@ type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbu // Build the ILTypeDef. We don't rely on the normal record generation process because we want very specific field names - let ilTypeDefAttribs = mkILCustomAttrs [ cenv.g.CompilerGeneratedAttribute; mkCompilationMappingAttr cenv.g (int SourceConstructFlags.RecordType) ] + let ilTypeDefAttribs = mkILCustomAttrs [ g.CompilerGeneratedAttribute; mkCompilationMappingAttr g (int SourceConstructFlags.RecordType) ] let ilInterfaceTys = [ for (ity, _, _) in tcaug.tcaug_interfaces -> GenType cenv.amap m (TypeReprEnv.ForTypars tps) ity ] @@ -1473,10 +1552,10 @@ type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbu mgbuf.AddTypeDef(ilTypeRef, ilTypeDef, false, true, None) let extraBindings = - [ yield! AugmentWithHashCompare.MakeBindingsForCompareAugmentation cenv.g tycon - yield! AugmentWithHashCompare.MakeBindingsForCompareWithComparerAugmentation cenv.g tycon - yield! AugmentWithHashCompare.MakeBindingsForEqualityWithComparerAugmentation cenv.g tycon - yield! AugmentWithHashCompare.MakeBindingsForEqualsAugmentation cenv.g tycon ] + [ yield! AugmentWithHashCompare.MakeBindingsForCompareAugmentation g tycon + yield! AugmentWithHashCompare.MakeBindingsForCompareWithComparerAugmentation g tycon + yield! AugmentWithHashCompare.MakeBindingsForEqualityWithComparerAugmentation g tycon + yield! AugmentWithHashCompare.MakeBindingsForEqualsAugmentation g tycon ] let optimizedExtraBindings = extraBindings |> List.map (fun (TBind(a, b, c)) -> TBind(a, cenv.optimizeDuringCodeGen b, c)) @@ -1489,71 +1568,68 @@ type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbu /// static init fields on script modules. let mutable scriptInitFspecs: (ILFieldSpec * range) list = [] - member mgbuf.AddScriptInitFieldSpec(fieldSpec, range) = + member __.AddScriptInitFieldSpec (fieldSpec, range) = scriptInitFspecs <- (fieldSpec, range) :: scriptInitFspecs /// This initializes the script in #load and fsc command-line order causing their - /// sideeffects to be executed. - member mgbuf.AddInitializeScriptsInOrderToEntryPoint() = + /// side effects to be executed. + member mgbuf.AddInitializeScriptsInOrderToEntryPoint () = // Get the entry point and initialized any scripts in order. match explicitEntryPointInfo with | Some tref -> - let IntializeCompiledScript(fspec, m) = + let InitializeCompiledScript(fspec, m) = mgbuf.AddExplicitInitToSpecificMethodDef((fun (md: ILMethodDef) -> md.IsEntryPoint), tref, fspec, GenPossibleILSourceMarker cenv m, [], []) - scriptInitFspecs |> List.iter IntializeCompiledScript + scriptInitFspecs |> List.iter InitializeCompiledScript | None -> () - member mgbuf.GenerateRawDataValueType(cloc, size) = + member __.GenerateRawDataValueType (cloc, size) = // Byte array literals require a ValueType of size the required number of bytes. // With fsi.exe, S.R.Emit TypeBuilder CreateType has restrictions when a ValueType VT is nested inside a type T, and T has a field of type VT. // To avoid this situation, these ValueTypes are generated under the private implementation rather than in the current cloc. [was bug 1532]. let cloc = CompLocForPrivateImplementationDetails cloc rawDataValueTypeGenerator.Apply((cloc, size)) - member mgbuf.GenerateAnonType(genToStringMethod, anonInfo: AnonRecdTypeInfo) = + member __.GenerateAnonType (genToStringMethod, anonInfo: AnonRecdTypeInfo) = let isStruct = evalAnonInfoIsStruct anonInfo let key = anonInfo.Stamp - match anonTypeTable.Table.TryGetValue key with - | true, res -> res - | _ -> + if not (anonTypeTable.Table.ContainsKey key) then let info = generateAnonType genToStringMethod (isStruct, anonInfo.ILTypeRef, anonInfo.SortedNames) anonTypeTable.Table.[key] <- info - info - member mgbuf.LookupAnonType(anonInfo: AnonRecdTypeInfo) = + member __.LookupAnonType (anonInfo: AnonRecdTypeInfo) = match anonTypeTable.Table.TryGetValue anonInfo.Stamp with | true, res -> res | _ -> failwithf "the anonymous record %A has not been generated in the pre-phase of generating this module" anonInfo.ILTypeRef - member mgbuf.GrabExtraBindingsToGenerate() = + member __.GrabExtraBindingsToGenerate () = let result = extraBindingsToGenerate extraBindingsToGenerate <- [] result - member mgbuf.AddTypeDef(tref: ILTypeRef, tdef, eliminateIfEmpty, addAtEnd, tdefDiscards) = + member __.AddTypeDef (tref: ILTypeRef, tdef, eliminateIfEmpty, addAtEnd, tdefDiscards) = gtdefs.FindNestedTypeDefsBuilder(tref.Enclosing).AddTypeDef(tdef, eliminateIfEmpty, addAtEnd, tdefDiscards) - member mgbuf.GetCurrentFields(tref: ILTypeRef) = + member __.GetCurrentFields (tref: ILTypeRef) = gtdefs.FindNestedTypeDefBuilder(tref).GetCurrentFields() - member mgbuf.AddReflectedDefinition(vspec: Tast.Val, expr) = + member __.AddReflectedDefinition (vspec: Val, expr) = // preserve order by storing index of item let n = reflectedDefinitions.Count - reflectedDefinitions.Add(vspec, (vspec.CompiledName, n, expr)) + reflectedDefinitions.Add(vspec, (vspec.CompiledName cenv.g.CompilerGlobalState, n, expr)) - member mgbuf.ReplaceNameOfReflectedDefinition(vspec, newName) = + member __.ReplaceNameOfReflectedDefinition (vspec, newName) = match reflectedDefinitions.TryGetValue vspec with | true, (name, n, expr) when name <> newName -> reflectedDefinitions.[vspec] <- (newName, n, expr) | _ -> () - member mgbuf.AddMethodDef(tref: ILTypeRef, ilMethodDef) = + member __.AddMethodDef (tref: ILTypeRef, ilMethodDef) = gtdefs.FindNestedTypeDefBuilder(tref).AddMethodDef(ilMethodDef) if ilMethodDef.IsEntryPoint then - explicitEntryPointInfo <- Some(tref) + explicitEntryPointInfo <- Some tref - member mgbuf.AddExplicitInitToSpecificMethodDef(cond, tref, fspec, sourceOpt, feefee, seqpt) = - // Authoring a .cctor with effects forces the cctor for the 'initialization' module by doing a dummy store & load of a field - // Doing both a store and load keeps FxCop happier because it thinks the field is useful + member __.AddExplicitInitToSpecificMethodDef (cond, tref, fspec, sourceOpt, feefee, seqpt) = + // Authoring a .cctor with effects forces the cctor for the 'initialization' module by doing a dummy store & load of a field + // Doing both a store and load keeps FxCop happier because it thinks the field is useful let instrs = [ yield! (if condition "NO_ADD_FEEFEE_TO_CCTORS" then [] elif condition "ADD_SEQPT_TO_CCTORS" then seqpt else feefee) // mark start of hidden code yield mkLdcInt32 0 @@ -1562,30 +1638,29 @@ type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbu yield AI_pop] gtdefs.FindNestedTypeDefBuilder(tref).PrependInstructionsToSpecificMethodDef(cond, instrs, sourceOpt) - member mgbuf.AddEventDef(tref, edef) = + member __.AddEventDef (tref, edef) = gtdefs.FindNestedTypeDefBuilder(tref).AddEventDef(edef) - member mgbuf.AddFieldDef(tref, ilFieldDef) = + member __.AddFieldDef (tref, ilFieldDef) = gtdefs.FindNestedTypeDefBuilder(tref).AddFieldDef(ilFieldDef) - member mgbuf.AddOrMergePropertyDef(tref, pdef, m) = + member __.AddOrMergePropertyDef (tref, pdef, m) = gtdefs.FindNestedTypeDefBuilder(tref).AddOrMergePropertyDef(pdef, m) - member mgbuf.Close() = + member __.Close() = // old implementation adds new element to the head of list so result was accumulated in reversed order let orderedReflectedDefinitions = [for (KeyValue(vspec, (name, n, expr))) in reflectedDefinitions -> n, ((name, vspec), expr)] |> List.sortBy (fst >> (~-)) // invert the result to get 'order-by-descending' behavior (items in list are 0..* so we don't need to worry about int.MinValue) |> List.map snd gtdefs.Close(), orderedReflectedDefinitions - member mgbuf.cenv = cenv - member mgbuf.GetExplicitEntryPointInfo() = explicitEntryPointInfo + member __.cenv = cenv + + member __.GetExplicitEntryPointInfo() = explicitEntryPointInfo /// Record the types of the things on the evaluation stack. /// Used for the few times we have to flush the IL evaluation stack and to compute maxStack. -type Pushes = ILType list -type Pops = int let pop (i: int) : Pops = i let Push tys: Pushes = tys let Push0 = Push [] @@ -1604,6 +1679,7 @@ type CodeGenBuffer(m: range, methodName, alreadyUsedArgs: int) = + let g = mgbuf.cenv.g let locals = new ResizeArray<((string * (Mark * Mark)) list * ILType * bool)>(10) let codebuf = new ResizeArray(200) let exnSpecs = new ResizeArray(10) @@ -1613,7 +1689,7 @@ type CodeGenBuffer(m: range, let mutable stack: ILType list = [] let mutable nstack = 0 let mutable maxStack = 0 - let mutable hasSequencePoints = false + let mutable hasDebugPoints = false let mutable anyDocument = None // we collect an arbitrary document in order to emit the header FeeFee if needed let codeLabelToPC: Dictionary = new Dictionary<_, _>(10) @@ -1621,7 +1697,7 @@ type CodeGenBuffer(m: range, let rec lab2pc n lbl = if n = System.Int32.MaxValue then error(InternalError("recursive label graph", m)) - match codeLabelToCodeLabel.TryGetValue(lbl) with + match codeLabelToCodeLabel.TryGetValue lbl with | true, l -> lab2pc (n + 1) l | _ -> codeLabelToPC.[lbl] @@ -1629,9 +1705,9 @@ type CodeGenBuffer(m: range, // Add a nop to make way for the first sequence point. do if mgbuf.cenv.opts.generateDebugSymbols then - let doc = mgbuf.cenv.g.memoize_file m.FileIndex + let doc = g.memoize_file m.FileIndex let i = FeeFeeInstr mgbuf.cenv doc - codebuf.Add(i) // for the FeeFee or a better sequence point + codebuf.Add i // for the FeeFee or a better sequence point member cgbuf.DoPushes (pushes: Pushes) = for ty in pushes do @@ -1670,7 +1746,7 @@ type CodeGenBuffer(m: range, cgbuf.DoPushes pushes is |> List.iter codebuf.Add - member cgbuf.GetLastSequencePoint() = + member cgbuf.GetLastDebugPoint() = lastSeqPoint member private cgbuf.EnsureNopBetweenDebugPoints() = @@ -1683,11 +1759,11 @@ type CodeGenBuffer(m: range, codebuf.Add(AI_nop) - member cgbuf.EmitSeqPoint(src) = + member cgbuf.EmitSeqPoint src = if mgbuf.cenv.opts.generateDebugSymbols then - let attr = GenILSourceMarker mgbuf.cenv.g src + let attr = GenILSourceMarker g src let i = I_seqpoint attr - hasSequencePoints <- true + hasDebugPoints <- true // Replace the FeeFee seqpoint at the entry with a better sequence point if codebuf.Count = 1 then @@ -1696,7 +1772,7 @@ type CodeGenBuffer(m: range, else cgbuf.EnsureNopBetweenDebugPoints() - codebuf.Add(i) + codebuf.Add i // Save the last sequence point away so we can make a decision graph look consistent (i.e. reassert the sequence point at each target) lastSeqPoint <- Some src @@ -1705,18 +1781,18 @@ type CodeGenBuffer(m: range, // Emit FeeFee breakpoints for hidden code, see https://blogs.msdn.microsoft.com/jmstall/2005/06/19/line-hidden-and-0xfeefee-sequence-points/ member cgbuf.EmitStartOfHiddenCode() = if mgbuf.cenv.opts.generateDebugSymbols then - let doc = mgbuf.cenv.g.memoize_file m.FileIndex + let doc = g.memoize_file m.FileIndex let i = FeeFeeInstr mgbuf.cenv doc - hasSequencePoints <- true + hasDebugPoints <- true // don't emit just after another FeeFee match codebuf.[codebuf.Count-1] with | I_seqpoint sm when sm.Line = FeeFee mgbuf.cenv -> () | _ -> cgbuf.EnsureNopBetweenDebugPoints() - codebuf.Add(i) + codebuf.Add i - member cgbuf.EmitExceptionClause(clause) = + member cgbuf.EmitExceptionClause clause = exnSpecs.Add clause member cgbuf.GenerateDelayMark(_nm) = @@ -1725,7 +1801,7 @@ type CodeGenBuffer(m: range, member cgbuf.SetCodeLabelToCodeLabel(lab1, lab2) = #if DEBUG - if codeLabelToCodeLabel.ContainsKey(lab1) then + if codeLabelToCodeLabel.ContainsKey lab1 then let msg = sprintf "two values given for label %s, methodName = %s, m = %s" (formatCodeLabel lab1) methodName (stringOfRange m) System.Diagnostics.Debug.Assert(false, msg) warning(InternalError(msg, m)) @@ -1734,7 +1810,7 @@ type CodeGenBuffer(m: range, member cgbuf.SetCodeLabelToPC(lab, pc) = #if DEBUG - if codeLabelToPC.ContainsKey(lab) then + if codeLabelToPC.ContainsKey lab then let msg = sprintf "two values given for label %s, methodName = %s, m = %s" (formatCodeLabel lab) methodName (stringOfRange m) System.Diagnostics.Debug.Assert(false, msg) warning(InternalError(msg, m)) @@ -1747,13 +1823,13 @@ type CodeGenBuffer(m: range, member cgbuf.SetMarkToHere (Mark lab) = cgbuf.SetCodeLabelToPC(lab, codebuf.Count) - member cgbuf.SetStack(s) = + member cgbuf.SetStack s = stack <- s nstack <- s.Length - member cgbuf.Mark(s) = - let res = cgbuf.GenerateDelayMark(s) - cgbuf.SetMarkToHere(res) + member cgbuf.Mark s = + let res = cgbuf.GenerateDelayMark s + cgbuf.SetMarkToHere res res member cgbuf.mgbuf = mgbuf @@ -1783,7 +1859,7 @@ type CodeGenBuffer(m: range, instrs |> Array.mapi (fun idx i2 -> if idx = 0 && (match i2 with AI_nop -> true | _ -> false) && anyDocument.IsSome then // This special dummy sequence point says skip the start of the method - hasSequencePoints <- true + hasDebugPoints <- true FeeFeeInstr mgbuf.cenv anyDocument.Value else i2) @@ -1794,19 +1870,18 @@ type CodeGenBuffer(m: range, for kvp in codeLabelToCodeLabel do dict.Add(kvp.Key, lab2pc 0 kvp.Key) dict - (ResizeArray.toList locals, maxStack, codeLabels, instrs, ResizeArray.toList exnSpecs, hasSequencePoints) + (ResizeArray.toList locals, maxStack, codeLabels, instrs, ResizeArray.toList exnSpecs, hasDebugPoints) module CG = let EmitInstr (cgbuf: CodeGenBuffer) pops pushes i = cgbuf.EmitInstr(pops, pushes, i) let EmitInstrs (cgbuf: CodeGenBuffer) pops pushes is = cgbuf.EmitInstrs(pops, pushes, is) - let EmitSeqPoint (cgbuf: CodeGenBuffer) src = cgbuf.EmitSeqPoint(src) - let GenerateDelayMark (cgbuf: CodeGenBuffer) nm = cgbuf.GenerateDelayMark(nm) + let EmitSeqPoint (cgbuf: CodeGenBuffer) src = cgbuf.EmitSeqPoint src + let GenerateDelayMark (cgbuf: CodeGenBuffer) nm = cgbuf.GenerateDelayMark nm let SetMark (cgbuf: CodeGenBuffer) m1 m2 = cgbuf.SetMark(m1, m2) - let SetMarkToHere (cgbuf: CodeGenBuffer) m1 = cgbuf.SetMarkToHere(m1) - let SetStack (cgbuf: CodeGenBuffer) s = cgbuf.SetStack(s) - let GenerateMark (cgbuf: CodeGenBuffer) s = cgbuf.Mark(s) + let SetMarkToHere (cgbuf: CodeGenBuffer) m1 = cgbuf.SetMarkToHere m1 + let SetStack (cgbuf: CodeGenBuffer) s = cgbuf.SetStack s + let GenerateMark (cgbuf: CodeGenBuffer) s = cgbuf.Mark s -open CG //-------------------------------------------------------------------------- @@ -1817,24 +1892,25 @@ let GenString cenv cgbuf s = CG.EmitInstrs cgbuf (pop 0) (Push [cenv.g.ilg.typ_String]) [ I_ldstr s ] let GenConstArray cenv (cgbuf: CodeGenBuffer) eenv ilElementType (data:'a[]) (write: ByteBuffer -> 'a -> unit) = + let g = cenv.g let buf = ByteBuffer.Create data.Length data |> Array.iter (write buf) let bytes = buf.Close() let ilArrayType = mkILArr1DTy ilElementType if data.Length = 0 then - CG.EmitInstrs cgbuf (pop 0) (Push [ilArrayType]) [ mkLdcInt32 (0); I_newarr (ILArrayShape.SingleDimensional, ilElementType); ] + CG.EmitInstrs cgbuf (pop 0) (Push [ilArrayType]) [ mkLdcInt32 0; I_newarr (ILArrayShape.SingleDimensional, ilElementType); ] else let vtspec = cgbuf.mgbuf.GenerateRawDataValueType(eenv.cloc, bytes.Length) let ilFieldName = CompilerGeneratedName ("field" + string(newUnique())) let fty = ILType.Value vtspec let ilFieldDef = mkILStaticField (ilFieldName, fty, None, Some bytes, ILMemberAccess.Assembly) - let ilFieldDef = ilFieldDef.With(customAttrs = mkILCustomAttrs [ cenv.g.DebuggerBrowsableNeverAttribute ]) + let ilFieldDef = ilFieldDef.With(customAttrs = mkILCustomAttrs [ g.DebuggerBrowsableNeverAttribute ]) let fspec = mkILFieldSpecInTy (mkILTyForCompLoc eenv.cloc, ilFieldName, fty) CountStaticFieldDef() cgbuf.mgbuf.AddFieldDef(fspec.DeclaringTypeRef, ilFieldDef) CG.EmitInstrs cgbuf (pop 0) - (Push [ ilArrayType; ilArrayType; cenv.g.iltyp_RuntimeFieldHandle ]) + (Push [ ilArrayType; ilArrayType; g.iltyp_RuntimeFieldHandle ]) [ mkLdcInt32 data.Length I_newarr (ILArrayShape.SingleDimensional, ilElementType) AI_dup @@ -1842,36 +1918,7 @@ let GenConstArray cenv (cgbuf: CodeGenBuffer) eenv ilElementType (data:'a[]) (wr CG.EmitInstrs cgbuf (pop 2) Push0 - [ mkNormalCall (mkInitializeArrayMethSpec cenv.g) ] - - -//-------------------------------------------------------------------------- -// We normally generate in the context of a "what to do next" continuation -//-------------------------------------------------------------------------- - -type sequel = - | EndFilter - /// Exit a 'handler' block - /// The integer says which local to save result in - | LeaveHandler of (bool (* finally? *) * int * Mark) - /// Branch to the given mark - | Br of Mark - | CmpThenBrOrContinue of Pops * ILInstr list - /// Continue and leave the value on the IL computation stack - | Continue - /// The value then do something else - | DiscardThen of sequel - /// Return from the method - | Return - /// End a scope of local variables. Used at end of 'let' and 'let rec' blocks to get tail recursive setting - /// of end-of-scope marks - | EndLocalScope of sequel * Mark - /// Return from a method whose return type is void - | ReturnVoid - -let discard = DiscardThen Continue -let discardAndReturnVoid = DiscardThen ReturnVoid - + [ mkNormalCall (mkInitializeArrayMethSpec g) ] //------------------------------------------------------------------------- // This is the main code generation routine. It is used to generate @@ -1888,7 +1935,7 @@ let CodeGenThen cenv mgbuf (entryPointInfo, methodName, eenv, alreadyUsedArgs, c liveLocals=IntMap.empty() innerVals = innerVals} - let locals, maxStack, lab2pc, code, exnSpecs, hasSequencePoints = cgbuf.Close() + let locals, maxStack, lab2pc, code, exnSpecs, hasDebugPoints = cgbuf.Close() let localDebugSpecs: ILLocalDebugInfo list = locals @@ -1920,18 +1967,18 @@ let CodeGenThen cenv mgbuf (entryPointInfo, methodName, eenv, alreadyUsedArgs, c code, exnSpecs, localDebugSpecs, - hasSequencePoints) + hasDebugPoints) let CodeGenMethod cenv mgbuf (entryPointInfo, methodName, eenv, alreadyUsedArgs, codeGenFunction, m) = - let locals, maxStack, lab2pc, instrs, exns, localDebugSpecs, hasSequencePoints = + let locals, maxStack, lab2pc, instrs, exns, localDebugSpecs, hasDebugPoints = CodeGenThen cenv mgbuf (entryPointInfo, methodName, eenv, alreadyUsedArgs, codeGenFunction, m) let code = IL.buildILCode methodName lab2pc instrs exns localDebugSpecs // Attach a source range to the method. Only do this is it has some sequence points, because .NET 2.0/3.5 // ILDASM has issues if you emit symbols with a source range but without any sequence points - let sourceRange = if hasSequencePoints then GenPossibleILSourceMarker cenv m else None + let sourceRange = if hasDebugPoints then GenPossibleILSourceMarker cenv m else None // The old union erasure phase increased maxstack by 2 since the code pushes some items, we do the same here let maxStack = maxStack + 2 @@ -1961,7 +2008,7 @@ let compileSequenceExpressions = true // try (System.Environment.GetEnvironmentV // Sequence Point Logic //------------------------------------------------------------------------- -type EmitSequencePointState = +type EmitDebugPointState = /// Indicates that we need a sequence point at first opportunity. Used on entrance to a method /// and whenever we drop into an expression within the stepping control structure. | SPAlways @@ -1976,33 +2023,33 @@ let BindingEmitsNoCode g (b: Binding) = IsFSharpValCompiledAsMethod g b.Var /// For example, if the r.h.s is a lambda then no sequence point is emitted. /// /// Returns (isSticky, sequencePointForBind, sequencePointGenerationFlagForRhsOfBind) -let ComputeSequencePointInfoForBinding g (TBind(_, e, spBind) as bind) = +let ComputeDebugPointForBinding g (TBind(_, e, spBind) as bind) = if BindingEmitsNoCode g bind then false, None, SPSuppress else match spBind, stripExpr e with - | NoSequencePointAtInvisibleBinding, _ -> false, None, SPSuppress - | NoSequencePointAtStickyBinding, _ -> true, None, SPSuppress - | NoSequencePointAtDoBinding, _ -> false, None, SPAlways - | NoSequencePointAtLetBinding, _ -> false, None, SPSuppress + | NoDebugPointAtInvisibleBinding, _ -> false, None, SPSuppress + | NoDebugPointAtStickyBinding, _ -> true, None, SPSuppress + | NoDebugPointAtDoBinding, _ -> false, None, SPAlways + | NoDebugPointAtLetBinding, _ -> false, None, SPSuppress // Don't emit sequence points for lambdas. // SEQUENCE POINT REVIEW: don't emit for lazy either, nor any builder expressions, nor interface-implementing object expressions | _, (Expr.Lambda _ | Expr.TyLambda _) -> false, None, SPSuppress - | SequencePointAtBinding m, _ -> false, Some m, SPSuppress + | DebugPointAtBinding m, _ -> false, Some m, SPSuppress /// Determines if a sequence will be emitted when we generate the code for a binding. /// -/// False for Lambdas, BindingEmitsNoCode, NoSequencePointAtStickyBinding, NoSequencePointAtInvisibleBinding, and NoSequencePointAtLetBinding. -/// True for SequencePointAtBinding, NoSequencePointAtDoBinding. -let BindingEmitsSequencePoint g bind = - match ComputeSequencePointInfoForBinding g bind with +/// False for Lambdas, BindingEmitsNoCode, NoDebugPointAtStickyBinding, NoDebugPointAtInvisibleBinding, and NoDebugPointAtLetBinding. +/// True for DebugPointAtBinding, NoDebugPointAtDoBinding. +let BindingEmitsDebugPoint g bind = + match ComputeDebugPointForBinding g bind with | _, None, SPSuppress -> false | _ -> true let BindingIsInvisible (TBind(_, _, spBind)) = match spBind with - | NoSequencePointAtInvisibleBinding _ -> true + | NoDebugPointAtInvisibleBinding _ -> true | _ -> false /// Determines if the code generated for a binding is to be marked as hidden, e.g. the 'newobj' for a local function definition. @@ -2014,27 +2061,27 @@ let BindingEmitsHiddenCode (TBind(_, e, spBind)) = /// Determines if generating the code for a compound expression will emit a sequence point as the first instruction /// through the processing of the constituent parts. Used to prevent the generation of sequence points for /// compound expressions. -let rec FirstEmittedCodeWillBeSequencePoint g sp expr = +let rec FirstEmittedCodeWillBeDebugPoint g sp expr = match sp with | SPAlways -> match stripExpr expr with | Expr.Let (bind, body, _, _) -> - BindingEmitsSequencePoint g bind || - FirstEmittedCodeWillBeSequencePoint g sp bind.Expr || - (BindingEmitsNoCode g bind && FirstEmittedCodeWillBeSequencePoint g sp body) - | Expr.LetRec(binds, body, _, _) -> - binds |> List.exists (BindingEmitsSequencePoint g) || - (binds |> List.forall (BindingEmitsNoCode g) && FirstEmittedCodeWillBeSequencePoint g sp body) + BindingEmitsDebugPoint g bind || + FirstEmittedCodeWillBeDebugPoint g sp bind.Expr || + (BindingEmitsNoCode g bind && FirstEmittedCodeWillBeDebugPoint g sp body) + | Expr.LetRec (binds, body, _, _) -> + binds |> List.exists (BindingEmitsDebugPoint g) || + (binds |> List.forall (BindingEmitsNoCode g) && FirstEmittedCodeWillBeDebugPoint g sp body) | Expr.Sequential (_, _, NormalSeq, spSeq, _) -> match spSeq with - | SequencePointsAtSeq -> true - | SuppressSequencePointOnExprOfSequential -> true - | SuppressSequencePointOnStmtOfSequential -> false - | Expr.Match (SequencePointAtBinding _, _, _, _, _, _) -> true - | Expr.Op((TOp.TryCatch (SequencePointAtTry _, _) - | TOp.TryFinally (SequencePointAtTry _, _) - | TOp.For (SequencePointAtForLoop _, _) - | TOp.While (SequencePointAtWhileLoop _, _)), _, _, _) -> true + | DebugPointAtSequential.Both -> true + | DebugPointAtSequential.StmtOnly -> true + | DebugPointAtSequential.ExprOnly -> false + | Expr.Match (DebugPointAtBinding _, _, _, _, _, _) -> true + | Expr.Op ((TOp.TryCatch (DebugPointAtTry.Yes _, _) + | TOp.TryFinally (DebugPointAtTry.Yes _, _) + | TOp.For (DebugPointAtFor.Yes _, _) + | TOp.While (DebugPointAtWhile.Yes _, _)), _, _, _) -> true | _ -> false | SPSuppress -> @@ -2042,9 +2089,9 @@ let rec FirstEmittedCodeWillBeSequencePoint g sp expr = /// Suppress sequence points for some compound expressions - though not all - even if "SPAlways" is set. /// -/// Note this is only used when FirstEmittedCodeWillBeSequencePoint is false. -let EmitSequencePointForWholeExpr g sp expr = - assert (not (FirstEmittedCodeWillBeSequencePoint g sp expr)) +/// Note this is only used when FirstEmittedCodeWillBeDebugPoint is false. +let EmitDebugPointForWholeExpr g sp expr = + assert (not (FirstEmittedCodeWillBeDebugPoint g sp expr)) match sp with | SPAlways -> match stripExpr expr with @@ -2052,8 +2099,8 @@ let EmitSequencePointForWholeExpr g sp expr = // In some cases, we emit sequence points for the 'whole' of a 'let' expression. // Specifically, when // + SPAlways (i.e. a sequence point is required as soon as meaningful) - // + binding is NoSequencePointAtStickyBinding, or NoSequencePointAtLetBinding. - // + not FirstEmittedCodeWillBeSequencePoint + // + binding is NoDebugPointAtStickyBinding, or NoDebugPointAtLetBinding. + // + not FirstEmittedCodeWillBeDebugPoint // For example if we start with // let someCode () = f x // and by inlining 'f' the expression becomes @@ -2062,35 +2109,35 @@ let EmitSequencePointForWholeExpr g sp expr = // _before_ the evaluation of 'x'. This will only happen for sticky 'let' introduced by inlining and other code generation // steps. We do _not_ do this for 'invisible' let which can be skipped. | Expr.Let (bind, _, _, _) when BindingIsInvisible bind -> false - | Expr.LetRec(binds, _, _, _) when binds |> List.forall BindingIsInvisible -> false + | Expr.LetRec (binds, _, _, _) when binds |> List.forall BindingIsInvisible -> false // If the binding is a lambda then we don't emit a sequence point. | Expr.Let (bind, _, _, _) when BindingEmitsHiddenCode bind -> false - | Expr.LetRec(binds, _, _, _) when binds |> List.forall BindingEmitsHiddenCode -> false + | Expr.LetRec (binds, _, _, _) when binds |> List.forall BindingEmitsHiddenCode -> false // If the binding is represented by a top-level generated constant value then we don't emit a sequence point. | Expr.Let (bind, _, _, _) when BindingEmitsNoCode g bind -> false - | Expr.LetRec(binds, _, _, _) when binds |> List.forall (BindingEmitsNoCode g) -> false + | Expr.LetRec (binds, _, _, _) when binds |> List.forall (BindingEmitsNoCode g) -> false // Suppress sequence points for the whole 'a;b' and do it at 'a' instead. | Expr.Sequential _ -> false // Suppress sequence points at labels and gotos, it makes no sense to emit sequence points at these. We emit FeeFee instead - | Expr.Op(TOp.Label _, _, _, _) -> false - | Expr.Op(TOp.Goto _, _, _, _) -> false + | Expr.Op (TOp.Label _, _, _, _) -> false + | Expr.Op (TOp.Goto _, _, _, _) -> false // We always suppress at the whole 'match'/'try'/... expression because we do it at the individual parts. // // These cases need documenting. For example, a typical 'match' gets compiled to // let tmp = expr // generates a sequence point, BEFORE tmp is evaluated - // match tmp with // a match marked with NoSequencePointAtInvisibleLetBinding + // match tmp with // a match marked with NoDebugPointAtInvisibleLetBinding // So since the 'let tmp = expr' has a sequence point, then no sequence point is needed for the 'match'. But the processing // of the 'let' requests SPAlways for the body. | Expr.Match _ -> false - | Expr.Op(TOp.TryCatch _, _, _, _) -> false - | Expr.Op(TOp.TryFinally _, _, _, _) -> false - | Expr.Op(TOp.For _, _, _, _) -> false - | Expr.Op(TOp.While _, _, _, _) -> false + | Expr.Op (TOp.TryCatch _, _, _, _) -> false + | Expr.Op (TOp.TryFinally _, _, _, _) -> false + | Expr.Op (TOp.For _, _, _, _) -> false + | Expr.Op (TOp.While _, _, _, _) -> false | _ -> true | SPSuppress -> false @@ -2101,210 +2148,241 @@ let EmitSequencePointForWholeExpr g sp expr = /// let f () = a /// body let EmitHiddenCodeMarkerForWholeExpr g sp expr = - assert (not (FirstEmittedCodeWillBeSequencePoint g sp expr)) - assert (not (EmitSequencePointForWholeExpr g sp expr)) + assert (not (FirstEmittedCodeWillBeDebugPoint g sp expr)) + assert (not (EmitDebugPointForWholeExpr g sp expr)) match sp with | SPAlways -> match stripExpr expr with | Expr.Let (bind, _, _, _) when BindingEmitsHiddenCode bind -> true - | Expr.LetRec(binds, _, _, _) when binds |> List.exists BindingEmitsHiddenCode -> true + | Expr.LetRec (binds, _, _, _) when binds |> List.exists BindingEmitsHiddenCode -> true | _ -> false | SPSuppress -> false /// Some expressions must emit some preparation code, then emit the actual code. -let rec RangeOfSequencePointForWholeExpr g expr = +let rec RangeOfDebugPointForWholeExpr g expr = match stripExpr expr with | Expr.Let (bind, body, _, _) -> - match ComputeSequencePointInfoForBinding g bind with + match ComputeDebugPointForBinding g bind with // For sticky bindings, prefer the range of the overall expression. | true, _, _ -> expr.Range - | _, None, SPSuppress -> RangeOfSequencePointForWholeExpr g body + | _, None, SPSuppress -> RangeOfDebugPointForWholeExpr g body | _, Some m, _ -> m - | _, None, SPAlways -> RangeOfSequencePointForWholeExpr g bind.Expr - | Expr.LetRec(_, body, _, _) -> RangeOfSequencePointForWholeExpr g body - | Expr.Sequential (expr1, _, NormalSeq, _, _) -> RangeOfSequencePointForWholeExpr g expr1 + | _, None, SPAlways -> RangeOfDebugPointForWholeExpr g bind.Expr + | Expr.LetRec (_, body, _, _) -> RangeOfDebugPointForWholeExpr g body + | Expr.Sequential (expr1, _, NormalSeq, _, _) -> RangeOfDebugPointForWholeExpr g expr1 | _ -> expr.Range /// Used to avoid emitting multiple sequence points in decision tree generation -let DoesGenExprStartWithSequencePoint g sp expr = - FirstEmittedCodeWillBeSequencePoint g sp expr || - EmitSequencePointForWholeExpr g sp expr +let DoesGenExprStartWithDebugPoint g sp expr = + FirstEmittedCodeWillBeDebugPoint g sp expr || + EmitDebugPointForWholeExpr g sp expr + +let ProcessDebugPointForExpr (cenv: cenv) (cgbuf: CodeGenBuffer) sp expr = + let g = cenv.g + if not (FirstEmittedCodeWillBeDebugPoint g sp expr) then + if EmitDebugPointForWholeExpr g sp expr then + CG.EmitSeqPoint cgbuf (RangeOfDebugPointForWholeExpr g expr) + elif EmitHiddenCodeMarkerForWholeExpr g sp expr then + cgbuf.EmitStartOfHiddenCode() //------------------------------------------------------------------------- // Generate expressions //------------------------------------------------------------------------- -let rec GenExpr (cenv: cenv) (cgbuf: CodeGenBuffer) eenv sp expr sequel = +let rec GenExpr cenv cgbuf eenv sp (expr: Expr) sequel = + cenv.exprRecursionDepth <- cenv.exprRecursionDepth + 1 - let expr = stripExpr expr + if cenv.exprRecursionDepth > 1 then +#if !FABLE_COMPILER + StackGuard.EnsureSufficientExecutionStack cenv.exprRecursionDepth +#endif + GenExprAux cenv cgbuf eenv sp expr sequel + else + GenExprWithStackGuard cenv cgbuf eenv sp expr sequel + + cenv.exprRecursionDepth <- cenv.exprRecursionDepth - 1 + + if cenv.exprRecursionDepth = 0 then + ProcessDelayedGenMethods cenv + +and ProcessDelayedGenMethods cenv = + while cenv.delayedGenMethods.Count > 0 do + let gen = cenv.delayedGenMethods.Dequeue () + gen cenv + +and GenExprWithStackGuard cenv cgbuf eenv sp expr sequel = + assert (cenv.exprRecursionDepth = 1) + try + GenExprAux cenv cgbuf eenv sp expr sequel + assert (cenv.exprRecursionDepth = 1) + with + | :? System.InsufficientExecutionStackException -> + error(InternalError(sprintf "Expression is too large and/or complex to emit. Method name: '%s'. Recursive depth: %i." cgbuf.MethodName cenv.exprRecursionDepth, expr.Range)) + +/// Process the debug point and check for alternative ways to generate this expression. +/// Returns 'true' if the expression was processed by alternative means. +and GenExprPreSteps (cenv: cenv) (cgbuf: CodeGenBuffer) eenv sp expr sequel = + let g = cenv.g + + ProcessDebugPointForExpr cenv cgbuf sp expr + + match (if compileSequenceExpressions then ConvertSequenceExprToObject g cenv.amap expr else None) with + | Some info -> + GenSequenceExpr cenv cgbuf eenv info sequel + true + | None -> + false - if not (FirstEmittedCodeWillBeSequencePoint cenv.g sp expr) then - if EmitSequencePointForWholeExpr cenv.g sp expr then - CG.EmitSeqPoint cgbuf (RangeOfSequencePointForWholeExpr cenv.g expr) - elif EmitHiddenCodeMarkerForWholeExpr cenv.g sp expr then - cgbuf.EmitStartOfHiddenCode() +and GenExprAux (cenv: cenv) (cgbuf: CodeGenBuffer) eenv sp expr sequel = + let g = cenv.g + let expr = stripExpr expr - match (if compileSequenceExpressions then LowerCallsAndSeqs.LowerSeqExpr cenv.g cenv.amap expr else None) with - | Some info -> - GenSequenceExpr cenv cgbuf eenv info sequel - | None -> + // Process the debug point and see if there's a replacement technique to process this expression + if GenExprPreSteps cenv cgbuf eenv sp expr sequel then () else - match expr with - | Expr.Const(c, m, ty) -> - GenConstant cenv cgbuf eenv (c, m, ty) sequel - | Expr.Match (spBind, exprm, tree, targets, m, ty) -> - GenMatch cenv cgbuf eenv (spBind, exprm, tree, targets, m, ty) sequel - | Expr.Sequential(e1, e2, dir, spSeq, m) -> - GenSequential cenv cgbuf eenv sp (e1, e2, dir, spSeq, m) sequel - | Expr.LetRec (binds, body, m, _) -> - GenLetRec cenv cgbuf eenv (binds, body, m) sequel - | Expr.Let (bind, body, _, _) -> - // This case implemented here to get a guaranteed tailcall - // Make sure we generate the sequence point outside the scope of the variable - let startScope, endScope as scopeMarks = StartDelayedLocalScope "let" cgbuf - let eenv = AllocStorageForBind cenv cgbuf scopeMarks eenv bind - let spBind = GenSequencePointForBind cenv cgbuf bind - GenBindingAfterSequencePoint cenv cgbuf eenv spBind bind (Some startScope) - - // Work out if we need a sequence point for the body. For any "user" binding then the body gets SPAlways. - // For invisible compiler-generated bindings we just use "sp", unless its body is another invisible binding - // For sticky bindings arising from inlining we suppress any immediate sequence point in the body - let spBody = - match bind.SequencePointInfo with - | SequencePointAtBinding _ - | NoSequencePointAtLetBinding - | NoSequencePointAtDoBinding -> SPAlways - | NoSequencePointAtInvisibleBinding -> sp - | NoSequencePointAtStickyBinding -> SPSuppress - - // Generate the body - GenExpr cenv cgbuf eenv spBody body (EndLocalScope(sequel, endScope)) - - | Expr.Lambda _ | Expr.TyLambda _ -> - GenLambda cenv cgbuf eenv false None expr sequel - | Expr.App(Expr.Val(vref, _, m) as v, _, tyargs, [], _) when - List.forall (isMeasureTy cenv.g) tyargs && - ( - // inline only values that are stored in local variables - match StorageForValRef m vref eenv with - | ValStorage.Local _ -> true - | _ -> false - ) -> - // application of local type functions with type parameters = measure types and body = local value - inine the body - GenExpr cenv cgbuf eenv sp v sequel - | Expr.App(f,fty, tyargs, args, m) -> - GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel - | Expr.Val(v, _, m) -> - GenGetVal cenv cgbuf eenv (v, m) sequel - - // Most generation of linear expressions is implemented routinely using tailcalls and the correct sequels. - // This is because the element of expansion happens to be the final thing generated in most cases. However - // for large lists we have to process the linearity separately - | LinearOpExpr _ -> - GenLinearExpr cenv cgbuf eenv expr sequel id |> ignore - - | Expr.Op(op, tyargs, args, m) -> - match op, args, tyargs with - | TOp.ExnConstr(c), _, _ -> - GenAllocExn cenv cgbuf eenv (c, args, m) sequel - | TOp.UnionCase(c), _, _ -> - GenAllocUnionCase cenv cgbuf eenv (c, tyargs, args, m) sequel - | TOp.Recd(isCtor, tycon), _, _ -> - GenAllocRecd cenv cgbuf eenv isCtor (tycon, tyargs, args, m) sequel - | TOp.AnonRecd(anonInfo), _, _ -> - GenAllocAnonRecd cenv cgbuf eenv (anonInfo, tyargs, args, m) sequel - | TOp.AnonRecdGet (anonInfo, n), [e], _ -> - GenGetAnonRecdField cenv cgbuf eenv (anonInfo, e, tyargs, n, m) sequel - | TOp.TupleFieldGet (tupInfo, n), [e], _ -> - GenGetTupleField cenv cgbuf eenv (tupInfo, e, tyargs, n, m) sequel - | TOp.ExnFieldGet(ecref, n), [e], _ -> - GenGetExnField cenv cgbuf eenv (e, ecref, n, m) sequel - | TOp.UnionCaseFieldGet(ucref, n), [e], _ -> - GenGetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel - | TOp.UnionCaseFieldGetAddr(ucref, n, _readonly), [e], _ -> - GenGetUnionCaseFieldAddr cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel - | TOp.UnionCaseTagGet ucref, [e], _ -> - GenGetUnionCaseTag cenv cgbuf eenv (e, ucref, tyargs, m) sequel - | TOp.UnionCaseProof ucref, [e], _ -> - GenUnionCaseProof cenv cgbuf eenv (e, ucref, tyargs, m) sequel - | TOp.ExnFieldSet(ecref, n), [e;e2], _ -> - GenSetExnField cenv cgbuf eenv (e, ecref, n, e2, m) sequel - | TOp.UnionCaseFieldSet(ucref, n), [e;e2], _ -> - GenSetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, e2, m) sequel - | TOp.ValFieldGet f, [e], _ -> - GenGetRecdField cenv cgbuf eenv (e, f, tyargs, m) sequel - | TOp.ValFieldGet f, [], _ -> - GenGetStaticField cenv cgbuf eenv (f, tyargs, m) sequel - | TOp.ValFieldGetAddr (f, _readonly), [e], _ -> - GenGetRecdFieldAddr cenv cgbuf eenv (e, f, tyargs, m) sequel - | TOp.ValFieldGetAddr (f, _readonly), [], _ -> - GenGetStaticFieldAddr cenv cgbuf eenv (f, tyargs, m) sequel - | TOp.ValFieldSet f, [e1;e2], _ -> - GenSetRecdField cenv cgbuf eenv (e1, f, tyargs, e2, m) sequel - | TOp.ValFieldSet f, [e2], _ -> - GenSetStaticField cenv cgbuf eenv (f, tyargs, e2, m) sequel - | TOp.Tuple tupInfo, _, _ -> - GenAllocTuple cenv cgbuf eenv (tupInfo, args, tyargs, m) sequel - | TOp.ILAsm(code, returnTys), _, _ -> - GenAsmCode cenv cgbuf eenv (code, tyargs, args, returnTys, m) sequel - | TOp.While (sp, _), [Expr.Lambda(_, _, _, [_], e1, _, _);Expr.Lambda(_, _, _, [_], e2, _, _)], [] -> - GenWhileLoop cenv cgbuf eenv (sp, e1, e2, m) sequel - | TOp.For(spStart, dir), [Expr.Lambda(_, _, _, [_], e1, _, _);Expr.Lambda(_, _, _, [_], e2, _, _);Expr.Lambda(_, _, _, [v], e3, _, _)], [] -> - GenForLoop cenv cgbuf eenv (spStart, v, e1, dir, e2, e3, m) sequel - | TOp.TryFinally(spTry, spFinally), [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [_], e2, _, _)], [resty] -> - GenTryFinally cenv cgbuf eenv (e1, e2, m, resty, spTry, spFinally) sequel - | TOp.TryCatch(spTry, spWith), [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [vf], ef, _, _);Expr.Lambda(_, _, _, [vh], eh, _, _)], [resty] -> - GenTryCatch cenv cgbuf eenv (e1, vf, ef, vh, eh, m, resty, spTry, spWith) sequel - | TOp.ILCall(virt, _, valu, newobj, valUseFlags, _, isDllImport, ilMethRef, enclArgTys, methArgTys, returnTys), args, [] -> - GenILCall cenv cgbuf eenv (virt, valu, newobj, valUseFlags, isDllImport, ilMethRef, enclArgTys, methArgTys, args, returnTys, m) sequel - | TOp.RefAddrGet _readonly, [e], [ty] -> GenGetAddrOfRefCellField cenv cgbuf eenv (e, ty, m) sequel - | TOp.Coerce, [e], [tgty;srcty] -> GenCoerce cenv cgbuf eenv (e, tgty, m, srcty) sequel - | TOp.Reraise, [], [rtnty] -> GenReraise cenv cgbuf eenv (rtnty, m) sequel - | TOp.TraitCall(ss), args, [] -> GenTraitCall cenv cgbuf eenv (ss, args, m) expr sequel - | TOp.LValueOp(LSet, v), [e], [] -> GenSetVal cenv cgbuf eenv (v, e, m) sequel - | TOp.LValueOp(LByrefGet, v), [], [] -> GenGetByref cenv cgbuf eenv (v, m) sequel - | TOp.LValueOp(LByrefSet, v), [e], [] -> GenSetByref cenv cgbuf eenv (v, e, m) sequel - | TOp.LValueOp(LAddrOf _, v), [], [] -> GenGetValAddr cenv cgbuf eenv (v, m) sequel - | TOp.Array, elems, [elemTy] -> GenNewArray cenv cgbuf eenv (elems, elemTy, m) sequel - | TOp.Bytes bytes, [], [] -> - if cenv.opts.emitConstantArraysUsingStaticDataBlobs then - GenConstArray cenv cgbuf eenv cenv.g.ilg.typ_Byte bytes (fun buf b -> buf.EmitByte b) - GenSequel cenv eenv.cloc cgbuf sequel - else - GenNewArraySimple cenv cgbuf eenv (List.ofArray (Array.map (mkByte cenv.g m) bytes), cenv.g.byte_ty, m) sequel - | TOp.UInt16s arr, [], [] -> - if cenv.opts.emitConstantArraysUsingStaticDataBlobs then - GenConstArray cenv cgbuf eenv cenv.g.ilg.typ_UInt16 arr (fun buf b -> buf.EmitUInt16 b) - GenSequel cenv eenv.cloc cgbuf sequel - else - GenNewArraySimple cenv cgbuf eenv (List.ofArray (Array.map (mkUInt16 cenv.g m) arr), cenv.g.uint16_ty, m) sequel - | TOp.Goto(label), _, _ -> - if cgbuf.mgbuf.cenv.opts.generateDebugSymbols then - cgbuf.EmitStartOfHiddenCode() - CG.EmitInstr cgbuf (pop 0) Push0 AI_nop - CG.EmitInstr cgbuf (pop 0) Push0 (I_br label) - // NOTE: discard sequel - | TOp.Return, [e], _ -> - GenExpr cenv cgbuf eenv SPSuppress e Return - // NOTE: discard sequel - | TOp.Return, [], _ -> - GenSequel cenv eenv.cloc cgbuf ReturnVoid - // NOTE: discard sequel - | TOp.Label(label), _, _ -> - cgbuf.SetMarkToHere (Mark label) - GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel - | _ -> error(InternalError("Unexpected operator node expression", expr.Range)) - | Expr.StaticOptimization(constraints, e2, e3, m) -> - GenStaticOptimization cenv cgbuf eenv (constraints, e2, e3, m) sequel - | Expr.Obj(_, ty, _, _, [meth], [], m) when isDelegateTy cenv.g ty -> - GenDelegateExpr cenv cgbuf eenv expr (meth, m) sequel - | Expr.Obj(_, ty, basev, basecall, overrides, interfaceImpls, m) -> - GenObjectExpr cenv cgbuf eenv expr (ty, basev, basecall, overrides, interfaceImpls, m) sequel - - | Expr.Quote(ast, conv, _, m, ty) -> GenQuotation cenv cgbuf eenv (ast, conv, m, ty) sequel - | Expr.Link _ -> failwith "Unexpected reclink" - | Expr.TyChoose (_, _, m) -> error(InternalError("Unexpected Expr.TyChoose", m)) + match expr with + // Most generation of linear expressions is implemented routinely using tailcalls and the correct sequels. + // This is because the element of expansion happens to be the final thing generated in most cases. However + // for large lists we have to process the linearity separately + | Expr.Sequential _ + | Expr.Let _ + | LinearOpExpr _ + | Expr.Match _ -> + GenLinearExpr cenv cgbuf eenv sp expr sequel false id |> ignore + + | Expr.Const (c, m, ty) -> + GenConstant cenv cgbuf eenv (c, m, ty) sequel + + | Expr.LetRec (binds, body, m, _) -> + GenLetRec cenv cgbuf eenv (binds, body, m) sequel + + | Expr.Lambda _ | Expr.TyLambda _ -> + GenLambda cenv cgbuf eenv false [] expr sequel + + | Expr.App (Expr.Val (vref, _, m) as v, _, tyargs, [], _) when + List.forall (isMeasureTy g) tyargs && + ( + // inline only values that are stored in local variables + match StorageForValRef g m vref eenv with + | ValStorage.Local _ -> true + | _ -> false + ) -> + // application of local type functions with type parameters = measure types and body = local value - inline the body + GenExpr cenv cgbuf eenv sp v sequel + + | Expr.App (f,fty, tyargs, args, m) -> + GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel + + | Expr.Val (v, _, m) -> + GenGetVal cenv cgbuf eenv (v, m) sequel + + | Expr.Op (op, tyargs, args, m) -> + match op, args, tyargs with + | TOp.ExnConstr c, _, _ -> + GenAllocExn cenv cgbuf eenv (c, args, m) sequel + | TOp.UnionCase c, _, _ -> + GenAllocUnionCase cenv cgbuf eenv (c, tyargs, args, m) sequel + | TOp.Recd (isCtor, tycon), _, _ -> + GenAllocRecd cenv cgbuf eenv isCtor (tycon, tyargs, args, m) sequel + | TOp.AnonRecd anonInfo, _, _ -> + GenAllocAnonRecd cenv cgbuf eenv (anonInfo, tyargs, args, m) sequel + | TOp.AnonRecdGet (anonInfo, n), [e], _ -> + GenGetAnonRecdField cenv cgbuf eenv (anonInfo, e, tyargs, n, m) sequel + | TOp.TupleFieldGet (tupInfo, n), [e], _ -> + GenGetTupleField cenv cgbuf eenv (tupInfo, e, tyargs, n, m) sequel + | TOp.ExnFieldGet (ecref, n), [e], _ -> + GenGetExnField cenv cgbuf eenv (e, ecref, n, m) sequel + | TOp.UnionCaseFieldGet (ucref, n), [e], _ -> + GenGetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel + | TOp.UnionCaseFieldGetAddr (ucref, n, _readonly), [e], _ -> + GenGetUnionCaseFieldAddr cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel + | TOp.UnionCaseTagGet ucref, [e], _ -> + GenGetUnionCaseTag cenv cgbuf eenv (e, ucref, tyargs, m) sequel + | TOp.UnionCaseProof ucref, [e], _ -> + GenUnionCaseProof cenv cgbuf eenv (e, ucref, tyargs, m) sequel + | TOp.ExnFieldSet (ecref, n), [e;e2], _ -> + GenSetExnField cenv cgbuf eenv (e, ecref, n, e2, m) sequel + | TOp.UnionCaseFieldSet (ucref, n), [e;e2], _ -> + GenSetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, e2, m) sequel + | TOp.ValFieldGet f, [e], _ -> + GenGetRecdField cenv cgbuf eenv (e, f, tyargs, m) sequel + | TOp.ValFieldGet f, [], _ -> + GenGetStaticField cenv cgbuf eenv (f, tyargs, m) sequel + | TOp.ValFieldGetAddr (f, _readonly), [e], _ -> + GenGetRecdFieldAddr cenv cgbuf eenv (e, f, tyargs, m) sequel + | TOp.ValFieldGetAddr (f, _readonly), [], _ -> + GenGetStaticFieldAddr cenv cgbuf eenv (f, tyargs, m) sequel + | TOp.ValFieldSet f, [e1;e2], _ -> + GenSetRecdField cenv cgbuf eenv (e1, f, tyargs, e2, m) sequel + | TOp.ValFieldSet f, [e2], _ -> + GenSetStaticField cenv cgbuf eenv (f, tyargs, e2, m) sequel + | TOp.Tuple tupInfo, _, _ -> + GenAllocTuple cenv cgbuf eenv (tupInfo, args, tyargs, m) sequel + | TOp.ILAsm (code, returnTys), _, _ -> + GenAsmCode cenv cgbuf eenv (code, tyargs, args, returnTys, m) sequel + | TOp.While (sp, _), [Expr.Lambda (_, _, _, [_], e1, _, _);Expr.Lambda (_, _, _, [_], e2, _, _)], [] -> + GenWhileLoop cenv cgbuf eenv (sp, e1, e2, m) sequel + | TOp.For (spStart, dir), [Expr.Lambda (_, _, _, [_], e1, _, _);Expr.Lambda (_, _, _, [_], e2, _, _);Expr.Lambda (_, _, _, [v], e3, _, _)], [] -> + GenForLoop cenv cgbuf eenv (spStart, v, e1, dir, e2, e3, m) sequel + | TOp.TryFinally (spTry, spFinally), [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [_], e2, _, _)], [resty] -> + GenTryFinally cenv cgbuf eenv (e1, e2, m, resty, spTry, spFinally) sequel + | TOp.TryCatch (spTry, spWith), [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [vf], ef, _, _);Expr.Lambda (_, _, _, [vh], eh, _, _)], [resty] -> + GenTryCatch cenv cgbuf eenv (e1, vf, ef, vh, eh, m, resty, spTry, spWith) sequel + | TOp.ILCall (virt, _, valu, newobj, valUseFlags, _, isDllImport, ilMethRef, enclArgTys, methArgTys, returnTys), args, [] -> + GenILCall cenv cgbuf eenv (virt, valu, newobj, valUseFlags, isDllImport, ilMethRef, enclArgTys, methArgTys, args, returnTys, m) sequel + | TOp.RefAddrGet _readonly, [e], [ty] -> GenGetAddrOfRefCellField cenv cgbuf eenv (e, ty, m) sequel + | TOp.Coerce, [e], [tgty;srcty] -> GenCoerce cenv cgbuf eenv (e, tgty, m, srcty) sequel + | TOp.Reraise, [], [rtnty] -> GenReraise cenv cgbuf eenv (rtnty, m) sequel + | TOp.TraitCall ss, args, [] -> GenTraitCall cenv cgbuf eenv (ss, args, m) expr sequel + | TOp.LValueOp (LSet, v), [e], [] -> GenSetVal cenv cgbuf eenv (v, e, m) sequel + | TOp.LValueOp (LByrefGet, v), [], [] -> GenGetByref cenv cgbuf eenv (v, m) sequel + | TOp.LValueOp (LByrefSet, v), [e], [] -> GenSetByref cenv cgbuf eenv (v, e, m) sequel + | TOp.LValueOp (LAddrOf _, v), [], [] -> GenGetValAddr cenv cgbuf eenv (v, m) sequel + | TOp.Array, elems, [elemTy] -> GenNewArray cenv cgbuf eenv (elems, elemTy, m) sequel + | TOp.Bytes bytes, [], [] -> + if cenv.opts.emitConstantArraysUsingStaticDataBlobs then + GenConstArray cenv cgbuf eenv g.ilg.typ_Byte bytes (fun buf b -> buf.EmitByte b) + GenSequel cenv eenv.cloc cgbuf sequel + else + GenNewArraySimple cenv cgbuf eenv (List.ofArray (Array.map (mkByte g m) bytes), g.byte_ty, m) sequel + | TOp.UInt16s arr, [], [] -> + if cenv.opts.emitConstantArraysUsingStaticDataBlobs then + GenConstArray cenv cgbuf eenv g.ilg.typ_UInt16 arr (fun buf b -> buf.EmitUInt16 b) + GenSequel cenv eenv.cloc cgbuf sequel + else + GenNewArraySimple cenv cgbuf eenv (List.ofArray (Array.map (mkUInt16 g m) arr), g.uint16_ty, m) sequel + | TOp.Goto label, _, _ -> + if cgbuf.mgbuf.cenv.opts.generateDebugSymbols then + cgbuf.EmitStartOfHiddenCode() + CG.EmitInstr cgbuf (pop 0) Push0 AI_nop + CG.EmitInstr cgbuf (pop 0) Push0 (I_br label) + // NOTE: discard sequel + | TOp.Return, [e], _ -> + GenExpr cenv cgbuf eenv SPSuppress e Return + // NOTE: discard sequel + | TOp.Return, [], _ -> + GenSequel cenv eenv.cloc cgbuf ReturnVoid + // NOTE: discard sequel + | TOp.Label label, _, _ -> + cgbuf.SetMarkToHere (Mark label) + GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel + | _ -> error(InternalError("Unexpected operator node expression", expr.Range)) + + | Expr.StaticOptimization (constraints, e2, e3, m) -> + GenStaticOptimization cenv cgbuf eenv (constraints, e2, e3, m) sequel + + | Expr.Obj (_, ty, _, _, [meth], [], m) when isDelegateTy g ty -> + GenDelegateExpr cenv cgbuf eenv expr (meth, m) sequel + + | Expr.Obj (_, ty, basev, basecall, overrides, interfaceImpls, m) -> + GenObjectExpr cenv cgbuf eenv expr (ty, basev, basecall, overrides, interfaceImpls, m) sequel + + | Expr.Quote (ast, conv, _, m, ty) -> GenQuotation cenv cgbuf eenv (ast, conv, m, ty) sequel + + | Expr.Link _ -> failwith "Unexpected reclink" + + | Expr.TyChoose (_, _, m) -> error(InternalError("Unexpected Expr.TyChoose", m)) and GenExprs cenv cgbuf eenv es = List.iter (fun e -> GenExpr cenv cgbuf eenv SPSuppress e Continue) es @@ -2314,9 +2392,7 @@ and CodeGenMethodForExpr cenv mgbuf (spReq, entryPointInfo, methodName, eenv, al CodeGenMethod cenv mgbuf (entryPointInfo, methodName, eenv, alreadyUsedArgs, (fun cgbuf eenv -> GenExpr cenv cgbuf eenv spReq expr0 sequel0), expr0.Range) - code - - + code //-------------------------------------------------------------------------- // Generate sequels @@ -2325,7 +2401,7 @@ and CodeGenMethodForExpr cenv mgbuf (spReq, entryPointInfo, methodName, eenv, al (* does the sequel discard its result, and if so what does it do next? *) and sequelAfterDiscard sequel = match sequel with - | DiscardThen sequel -> Some(sequel) + | DiscardThen sequel -> Some sequel | EndLocalScope(sq, mark) -> sequelAfterDiscard sq |> Option.map (fun sq -> EndLocalScope(sq, mark)) | _ -> None @@ -2397,37 +2473,41 @@ and GenSequel cenv cloc cgbuf sequel = //-------------------------------------------------------------------------- and GenConstant cenv cgbuf eenv (c, m, ty) sequel = + let g = cenv.g let ilTy = GenType cenv.amap m eenv.tyenv ty // Check if we need to generate the value at all match sequelAfterDiscard sequel with | None -> - match TryEliminateDesugaredConstants cenv.g m c with + match TryEliminateDesugaredConstants g m c with | Some e -> GenExpr cenv cgbuf eenv SPSuppress e Continue | None -> - match c with - | Const.Bool b -> CG.EmitInstr cgbuf (pop 0) (Push [cenv.g.ilg.typ_Bool]) (mkLdcInt32 (if b then 1 else 0)) - | Const.SByte i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdcInt32 (int32 i)) - | Const.Int16 i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdcInt32 (int32 i)) - | Const.Int32 i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdcInt32 i) - | Const.Int64 i -> - // see https://github.com/Microsoft/visualfsharp/pull/3620 + let emitInt64Constant i = + // see https://github.com/dotnet/fsharp/pull/3620 + // and https://github.com/dotnet/fsharp/issue/8683 + // and https://github.com/dotnet/roslyn/blob/98f12bb/src/Compilers/Core/Portable/CodeGen/ILBuilderEmit.cs#L679 if i >= int64 System.Int32.MinValue && i <= int64 System.Int32.MaxValue then CG.EmitInstrs cgbuf (pop 0) (Push [ilTy]) [ mkLdcInt32 (int32 i); AI_conv DT_I8 ] elif i >= int64 System.UInt32.MinValue && i <= int64 System.UInt32.MaxValue then CG.EmitInstrs cgbuf (pop 0) (Push [ilTy]) [ mkLdcInt32 (int32 i); AI_conv DT_U8 ] else CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (iLdcInt64 i) + match c with + | Const.Bool b -> CG.EmitInstr cgbuf (pop 0) (Push [g.ilg.typ_Bool]) (mkLdcInt32 (if b then 1 else 0)) + | Const.SByte i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdcInt32 (int32 i)) + | Const.Int16 i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdcInt32 (int32 i)) + | Const.Int32 i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdcInt32 i) + | Const.Int64 i -> emitInt64Constant i | Const.IntPtr i -> CG.EmitInstrs cgbuf (pop 0) (Push [ilTy]) [iLdcInt64 i; AI_conv DT_I ] | Const.Byte i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdcInt32 (int32 i)) | Const.UInt16 i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdcInt32 (int32 i)) | Const.UInt32 i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdcInt32 (int32 i)) - | Const.UInt64 i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (iLdcInt64 (int64 i)) + | Const.UInt64 i -> emitInt64Constant (int64 i) | Const.UIntPtr i -> CG.EmitInstrs cgbuf (pop 0) (Push [ilTy]) [iLdcInt64 (int64 i); AI_conv DT_U ] | Const.Double f -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (AI_ldc (DT_R8, ILConst.R8 f)) | Const.Single f -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (AI_ldc (DT_R4, ILConst.R4 f)) - | Const.Char(c) -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) ( mkLdcInt32 (int c)) - | Const.String(s) -> GenString cenv cgbuf s + | Const.Char c -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) ( mkLdcInt32 (int c)) + | Const.String s -> GenString cenv cgbuf s | Const.Unit -> GenUnit cenv eenv m cgbuf | Const.Zero -> GenDefaultValue cenv cgbuf eenv (ty, m) | Const.Decimal _ -> failwith "unreachable" @@ -2449,7 +2529,7 @@ and GenUnit cenv eenv m cgbuf = and GenUnitThenSequel cenv eenv m cloc cgbuf sequel = match sequelAfterDiscard sequel with - | Some(sq) -> GenSequel cenv cloc cgbuf sq + | Some sq -> GenSequel cenv cloc cgbuf sq | None -> GenUnit cenv eenv m cgbuf; GenSequel cenv cloc cgbuf sequel @@ -2482,7 +2562,7 @@ and GenGetTupleField cenv cgbuf eenv (tupInfo, e, tys, n, m) sequel = let ty = GenNamedTyApp cenv.amap m eenv.tyenv tcr' tys mkGetTupleItemN g m n ty tupInfo e tys.[n] else - let tysA, tysB = List.splitAfter (goodTupleFields) tys + let tysA, tysB = List.splitAfter goodTupleFields tys let tyB = mkCompiledTupleTy g tupInfo tysB let tys' = tysA@[tyB] let tcr' = mkCompiledTupleTyconRef g tupInfo (List.length tys') @@ -2515,16 +2595,128 @@ and GenAllocUnionCase cenv cgbuf eenv (c,tyargs,args,m) sequel = GenAllocUnionCaseCore cenv cgbuf eenv (c,tyargs,args.Length,m) GenSequel cenv eenv.cloc cgbuf sequel -and GenLinearExpr cenv cgbuf eenv expr sequel (contf: FakeUnit -> FakeUnit) = +and GenLinearExpr cenv cgbuf eenv sp expr sequel preSteps (contf: FakeUnit -> FakeUnit) = + let expr = stripExpr expr match expr with - | LinearOpExpr (TOp.UnionCase c, tyargs, argsFront, argLast, m) -> + | Expr.Sequential (e1, e2, specialSeqFlag, spSeq, _) -> + // Process the debug point and see if there's a replacement technique to process this expression + if preSteps && GenExprPreSteps cenv cgbuf eenv sp expr sequel then contf Fake else + + // Compiler generated sequential executions result in suppressions of sequence points on both + // left and right of the sequence + let spAction, spExpr = + (match spSeq with + | DebugPointAtSequential.Both -> SPAlways, SPAlways + | DebugPointAtSequential.StmtOnly -> SPSuppress, sp + | DebugPointAtSequential.ExprOnly -> sp, SPSuppress) + match specialSeqFlag with + | NormalSeq -> + GenExpr cenv cgbuf eenv spAction e1 discard + GenLinearExpr cenv cgbuf eenv spExpr e2 sequel true contf + | ThenDoSeq -> + GenExpr cenv cgbuf eenv spExpr e1 Continue + GenExpr cenv cgbuf eenv spAction e2 discard + GenSequel cenv eenv.cloc cgbuf sequel + contf Fake + + | Expr.Let (bind, body, _, _) -> + // Process the debug point and see if there's a replacement technique to process this expression + if preSteps && GenExprPreSteps cenv cgbuf eenv sp expr sequel then contf Fake else + + // This case implemented here to get a guaranteed tailcall + // Make sure we generate the sequence point outside the scope of the variable + let startScope, endScope as scopeMarks = StartDelayedLocalScope "let" cgbuf + let eenv = AllocStorageForBind cenv cgbuf scopeMarks eenv bind + let spBind = GenDebugPointForBind cenv cgbuf bind + GenBindingAfterDebugPoint cenv cgbuf eenv spBind bind (Some startScope) + + // Work out if we need a sequence point for the body. For any "user" binding then the body gets SPAlways. + // For invisible compiler-generated bindings we just use "sp", unless its body is another invisible binding + // For sticky bindings arising from inlining we suppress any immediate sequence point in the body + let spBody = + match bind.DebugPoint with + | DebugPointAtBinding _ + | NoDebugPointAtLetBinding + | NoDebugPointAtDoBinding -> SPAlways + | NoDebugPointAtInvisibleBinding -> sp + | NoDebugPointAtStickyBinding -> SPSuppress + + // Generate the body + GenLinearExpr cenv cgbuf eenv spBody body (EndLocalScope(sequel, endScope)) true contf + + | Expr.Match (spBind, _exprm, tree, targets, m, ty) -> + // Process the debug point and see if there's a replacement technique to process this expression + if preSteps && GenExprPreSteps cenv cgbuf eenv sp expr sequel then contf Fake else + + match spBind with + | DebugPointAtBinding m -> CG.EmitSeqPoint cgbuf m + | NoDebugPointAtDoBinding + | NoDebugPointAtLetBinding + | NoDebugPointAtInvisibleBinding + | NoDebugPointAtStickyBinding -> () + + // The target of branch needs a sequence point. + // If we don't give it one it will get entirely the wrong sequence point depending on earlier codegen + // Note we're not interested in having pattern matching and decision trees reveal their inner working. + // Hence at each branch target we 'reassert' the overall sequence point that was active as we came into the match. + // + // NOTE: sadly this causes multiple sequence points to appear for the "initial" location of an if/then/else or match. + let activeSP = cgbuf.GetLastDebugPoint() + let repeatSP() = + match activeSP with + | None -> () + | Some src -> + if activeSP <> cgbuf.GetLastDebugPoint() then + CG.EmitSeqPoint cgbuf src + + // First try the common cases where we don't need a join point. + match tree with + | TDSuccess _ -> + failwith "internal error: matches that immediately succeed should have been normalized using mkAndSimplifyMatch" + + | _ -> + // Create a join point + let stackAtTargets = cgbuf.GetCurrentStack() // the stack at the target of each clause + let (sequelOnBranches, afterJoin, stackAfterJoin, sequelAfterJoin) = GenJoinPoint cenv cgbuf "match" eenv ty m sequel + + // Stack: "stackAtTargets" is "stack prior to any match-testing" and also "stack at the start of each branch-RHS". + // match-testing (dtrees) should not contribute to the stack. + // Each branch-RHS (targets) may contribute to the stack, leaving it in the "stackAfterJoin" state, for the join point. + // Since code is branching and joining, the cgbuf stack is maintained manually. + GenDecisionTreeAndTargets cenv cgbuf stackAtTargets eenv tree targets repeatSP sequelOnBranches (contf << (fun Fake -> + CG.SetMarkToHere cgbuf afterJoin + + //assert(cgbuf.GetCurrentStack() = stackAfterJoin) // REVIEW: Since gen_dtree* now sets stack, stack should be stackAfterJoin at this point... + CG.SetStack cgbuf stackAfterJoin + // If any values are left on the stack after the join then we're certainly going to do something with them + // For example, we may be about to execute a 'stloc' for + // + // let y2 = if System.DateTime.Now.Year < 2000 then 1 else 2 + // + // or a 'stelem' for + // + // arr.[0] <- if System.DateTime.Now.Year > 2000 then 1 else 2 + // + // In both cases, any instructions that come after this point will be falsely associated with the last branch of the control + // prior to the join point. This is base, e.g. see FSharp 1.0 bug 5155 + if not (isNil stackAfterJoin) then + cgbuf.EmitStartOfHiddenCode() + + GenSequel cenv eenv.cloc cgbuf sequelAfterJoin + Fake)) + + | LinearOpExpr (TOp.UnionCase c, tyargs, argsFront, argLast, m) -> + // Process the debug point and see if there's a replacement technique to process this expression + if preSteps && GenExprPreSteps cenv cgbuf eenv sp expr sequel then contf Fake else + GenExprs cenv cgbuf eenv argsFront - GenLinearExpr cenv cgbuf eenv argLast Continue (contf << (fun (Fake) -> + GenLinearExpr cenv cgbuf eenv SPSuppress argLast Continue true (contf << (fun Fake -> GenAllocUnionCaseCore cenv cgbuf eenv (c, tyargs, argsFront.Length + 1, m) GenSequel cenv eenv.cloc cgbuf sequel Fake)) + | _ -> - GenExpr cenv cgbuf eenv SPSuppress expr sequel + GenExpr cenv cgbuf eenv sp expr sequel contf Fake and GenAllocRecd cenv cgbuf eenv ctorInfo (tcref,argtys,args,m) sequel = @@ -2555,7 +2747,7 @@ and GenAllocRecd cenv cgbuf eenv ctorInfo (tcref,argtys,args,m) sequel = GenSequel cenv eenv.cloc cgbuf sequel and GenAllocAnonRecd cenv cgbuf eenv (anonInfo: AnonRecdTypeInfo, tyargs, args, m) sequel = - let anonCtor, _anonMethods, anonType = cgbuf.mgbuf.LookupAnonType(anonInfo) + let anonCtor, _anonMethods, anonType = cgbuf.mgbuf.LookupAnonType anonInfo let boxity = anonType.Boxity GenExprs cenv cgbuf eenv args let ilTypeArgs = GenTypeArgs cenv.amap m eenv.tyenv tyargs @@ -2564,7 +2756,7 @@ and GenAllocAnonRecd cenv cgbuf eenv (anonInfo: AnonRecdTypeInfo, tyargs, args, GenSequel cenv eenv.cloc cgbuf sequel and GenGetAnonRecdField cenv cgbuf eenv (anonInfo: AnonRecdTypeInfo, e, tyargs, n, m) sequel = - let _anonCtor, anonMethods, anonType = cgbuf.mgbuf.LookupAnonType(anonInfo) + let _anonCtor, anonMethods, anonType = cgbuf.mgbuf.LookupAnonType anonInfo let boxity = anonType.Boxity let ilTypeArgs = GenTypeArgs cenv.amap m eenv.tyenv tyargs let anonMethod = anonMethods.[n] @@ -2598,72 +2790,71 @@ and GenNewArray cenv cgbuf eenv (elems: Expr list, elemTy, m) sequel = let elems' = Array.ofList elems let test, write = match elems'.[0] with - | Expr.Const(Const.Bool _, _, _) -> + | Expr.Const (Const.Bool _, _, _) -> (function Const.Bool _ -> true | _ -> false), (fun (buf: ByteBuffer) -> function Const.Bool b -> buf.EmitBoolAsByte b | _ -> failwith "unreachable") - | Expr.Const(Const.Char _, _, _) -> + | Expr.Const (Const.Char _, _, _) -> (function Const.Char _ -> true | _ -> false), (fun buf -> function Const.Char b -> buf.EmitInt32AsUInt16 (int b) | _ -> failwith "unreachable") - | Expr.Const(Const.Byte _, _, _) -> + | Expr.Const (Const.Byte _, _, _) -> (function Const.Byte _ -> true | _ -> false), (fun buf -> function Const.Byte b -> buf.EmitByte b | _ -> failwith "unreachable") - | Expr.Const(Const.UInt16 _, _, _) -> + | Expr.Const (Const.UInt16 _, _, _) -> (function Const.UInt16 _ -> true | _ -> false), (fun buf -> function Const.UInt16 b -> buf.EmitUInt16 b | _ -> failwith "unreachable") - | Expr.Const(Const.UInt32 _, _, _) -> + | Expr.Const (Const.UInt32 _, _, _) -> (function Const.UInt32 _ -> true | _ -> false), (fun buf -> function Const.UInt32 b -> buf.EmitInt32 (int32 b) | _ -> failwith "unreachable") - | Expr.Const(Const.UInt64 _, _, _) -> + | Expr.Const (Const.UInt64 _, _, _) -> (function Const.UInt64 _ -> true | _ -> false), (fun buf -> function Const.UInt64 b -> buf.EmitInt64 (int64 b) | _ -> failwith "unreachable") - | Expr.Const(Const.SByte _, _, _) -> + | Expr.Const (Const.SByte _, _, _) -> (function Const.SByte _ -> true | _ -> false), (fun buf -> function Const.SByte b -> buf.EmitByte (byte b) | _ -> failwith "unreachable") - | Expr.Const(Const.Int16 _, _, _) -> + | Expr.Const (Const.Int16 _, _, _) -> (function Const.Int16 _ -> true | _ -> false), (fun buf -> function Const.Int16 b -> buf.EmitUInt16 (uint16 b) | _ -> failwith "unreachable") - | Expr.Const(Const.Int32 _, _, _) -> + | Expr.Const (Const.Int32 _, _, _) -> (function Const.Int32 _ -> true | _ -> false), (fun buf -> function Const.Int32 b -> buf.EmitInt32 b | _ -> failwith "unreachable") - | Expr.Const(Const.Int64 _, _, _) -> + | Expr.Const (Const.Int64 _, _, _) -> (function Const.Int64 _ -> true | _ -> false), (fun buf -> function Const.Int64 b -> buf.EmitInt64 b | _ -> failwith "unreachable") | _ -> (function _ -> false), (fun _ _ -> failwith "unreachable") - if elems' |> Array.forall (function Expr.Const(c, _, _) -> test c | _ -> false) then + if elems' |> Array.forall (function Expr.Const (c, _, _) -> test c | _ -> false) then let ilElemTy = GenType cenv.amap m eenv.tyenv elemTy - GenConstArray cenv cgbuf eenv ilElemTy elems' (fun buf -> function Expr.Const(c, _, _) -> write buf c | _ -> failwith "unreachable") + GenConstArray cenv cgbuf eenv ilElemTy elems' (fun buf -> function Expr.Const (c, _, _) -> write buf c | _ -> failwith "unreachable") GenSequel cenv eenv.cloc cgbuf sequel else GenNewArraySimple cenv cgbuf eenv (elems, elemTy, m) sequel and GenCoerce cenv cgbuf eenv (e, tgty, m, srcty) sequel = - // Is this an upcast? - if TypeRelations.TypeDefinitelySubsumesTypeNoCoercion 0 cenv.g cenv.amap m tgty srcty && - // Do an extra check - should not be needed - TypeRelations.TypeFeasiblySubsumesType 0 cenv.g cenv.amap m tgty TypeRelations.NoCoerce srcty then - begin - if (isInterfaceTy cenv.g tgty) then ( - GenExpr cenv cgbuf eenv SPSuppress e Continue - let ilToTy = GenType cenv.amap m eenv.tyenv tgty - // Section "III.1.8.1.3 Merging stack states" of ECMA-335 implies that no unboxing - // is required, but we still push the coerce'd type on to the code gen buffer. - CG.EmitInstrs cgbuf (pop 1) (Push [ilToTy]) [] - GenSequel cenv eenv.cloc cgbuf sequel - ) else ( - GenExpr cenv cgbuf eenv SPSuppress e sequel - ) - end - else - GenExpr cenv cgbuf eenv SPSuppress e Continue - if not (isObjTy cenv.g srcty) then - let ilFromTy = GenType cenv.amap m eenv.tyenv srcty - CG.EmitInstrs cgbuf (pop 1) (Push [cenv.g.ilg.typ_Object]) [ I_box ilFromTy ] - if not (isObjTy cenv.g tgty) then - let ilToTy = GenType cenv.amap m eenv.tyenv tgty - CG.EmitInstrs cgbuf (pop 1) (Push [ilToTy]) [ I_unbox_any ilToTy ] - GenSequel cenv eenv.cloc cgbuf sequel + let g = cenv.g + // Is this an upcast? + if TypeRelations.TypeDefinitelySubsumesTypeNoCoercion 0 g cenv.amap m tgty srcty && + // Do an extra check - should not be needed + TypeRelations.TypeFeasiblySubsumesType 0 g cenv.amap m tgty TypeRelations.NoCoerce srcty + then + if isInterfaceTy g tgty then + GenExpr cenv cgbuf eenv SPSuppress e Continue + let ilToTy = GenType cenv.amap m eenv.tyenv tgty + // Section "III.1.8.1.3 Merging stack states" of ECMA-335 implies that no unboxing + // is required, but we still push the coerced type on to the code gen buffer. + CG.EmitInstrs cgbuf (pop 1) (Push [ilToTy]) [] + GenSequel cenv eenv.cloc cgbuf sequel + else + GenExpr cenv cgbuf eenv SPSuppress e sequel + else + GenExpr cenv cgbuf eenv SPSuppress e Continue + if not (isObjTy g srcty) then + let ilFromTy = GenType cenv.amap m eenv.tyenv srcty + CG.EmitInstrs cgbuf (pop 1) (Push [g.ilg.typ_Object]) [ I_box ilFromTy ] + if not (isObjTy g tgty) then + let ilToTy = GenType cenv.amap m eenv.tyenv tgty + CG.EmitInstrs cgbuf (pop 1) (Push [ilToTy]) [ I_unbox_any ilToTy ] + GenSequel cenv eenv.cloc cgbuf sequel and GenReraise cenv cgbuf eenv (rtnty, m) sequel = let ilReturnTy = GenType cenv.amap m eenv.tyenv rtnty @@ -2702,56 +2893,61 @@ and GenSetExnField cenv cgbuf eenv (e, ecref, fieldNum, e2, m) sequel = and UnionCodeGen (cgbuf: CodeGenBuffer) = { new EraseUnions.ICodeGen with - member __.CodeLabel(m) = m.CodeLabel + member __.CodeLabel m = m.CodeLabel member __.GenerateDelayMark() = CG.GenerateDelayMark cgbuf "unionCodeGenMark" - member __.GenLocal(ilty) = cgbuf.AllocLocal([], ilty, false) |> uint16 - member __.SetMarkToHere(m) = CG.SetMarkToHere cgbuf m + member __.GenLocal ilty = cgbuf.AllocLocal([], ilty, false) |> uint16 + member __.SetMarkToHere m = CG.SetMarkToHere cgbuf m member __.MkInvalidCastExnNewobj () = mkInvalidCastExnNewobj cgbuf.mgbuf.cenv.g member __.EmitInstr x = CG.EmitInstr cgbuf (pop 0) (Push []) x member __.EmitInstrs xs = CG.EmitInstrs cgbuf (pop 0) (Push []) xs } and GenUnionCaseProof cenv cgbuf eenv (e, ucref, tyargs, m) sequel = + let g = cenv.g GenExpr cenv cgbuf eenv SPSuppress e Continue let cuspec, idx = GenUnionCaseSpec cenv.amap m eenv.tyenv ucref tyargs let fty = EraseUnions.GetILTypeForAlternative cuspec idx - let avoidHelpers = entityRefInThisAssembly cenv.g.compilingFslib ucref.TyconRef - EraseUnions.emitCastData cenv.g.ilg (UnionCodeGen cgbuf) (false, avoidHelpers, cuspec, idx) + let avoidHelpers = entityRefInThisAssembly g.compilingFslib ucref.TyconRef + EraseUnions.emitCastData g.ilg (UnionCodeGen cgbuf) (false, avoidHelpers, cuspec, idx) CG.EmitInstrs cgbuf (pop 1) (Push [fty]) [ ] // push/pop to match the line above GenSequel cenv eenv.cloc cgbuf sequel and GenGetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel = - assert (ucref.Tycon.IsStructOrEnumTycon || isProvenUnionCaseTy (tyOfExpr cenv.g e)) + let g = cenv.g + assert (ucref.Tycon.IsStructOrEnumTycon || isProvenUnionCaseTy (tyOfExpr g e)) GenExpr cenv cgbuf eenv SPSuppress e Continue let cuspec, idx = GenUnionCaseSpec cenv.amap m eenv.tyenv ucref tyargs let fty = actualTypOfIlxUnionField cuspec idx n - let avoidHelpers = entityRefInThisAssembly cenv.g.compilingFslib ucref.TyconRef + let avoidHelpers = entityRefInThisAssembly g.compilingFslib ucref.TyconRef CG.EmitInstrs cgbuf (pop 1) (Push [fty]) (EraseUnions.mkLdData (avoidHelpers, cuspec, idx, n)) GenSequel cenv eenv.cloc cgbuf sequel and GenGetUnionCaseFieldAddr cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel = - assert (ucref.Tycon.IsStructOrEnumTycon || isProvenUnionCaseTy (tyOfExpr cenv.g e)) + let g = cenv.g + assert (ucref.Tycon.IsStructOrEnumTycon || isProvenUnionCaseTy (tyOfExpr g e)) GenExpr cenv cgbuf eenv SPSuppress e Continue let cuspec, idx = GenUnionCaseSpec cenv.amap m eenv.tyenv ucref tyargs let fty = actualTypOfIlxUnionField cuspec idx n - let avoidHelpers = entityRefInThisAssembly cenv.g.compilingFslib ucref.TyconRef + let avoidHelpers = entityRefInThisAssembly g.compilingFslib ucref.TyconRef CG.EmitInstrs cgbuf (pop 1) (Push [ILType.Byref fty]) (EraseUnions.mkLdDataAddr (avoidHelpers, cuspec, idx, n)) GenSequel cenv eenv.cloc cgbuf sequel and GenGetUnionCaseTag cenv cgbuf eenv (e, tcref, tyargs, m) sequel = + let g = cenv.g GenExpr cenv cgbuf eenv SPSuppress e Continue let cuspec = GenUnionSpec cenv.amap m eenv.tyenv tcref tyargs - let avoidHelpers = entityRefInThisAssembly cenv.g.compilingFslib tcref - EraseUnions.emitLdDataTag cenv.g.ilg (UnionCodeGen cgbuf) (avoidHelpers, cuspec) - CG.EmitInstrs cgbuf (pop 1) (Push [cenv.g.ilg.typ_Int32]) [ ] // push/pop to match the line above + let avoidHelpers = entityRefInThisAssembly g.compilingFslib tcref + EraseUnions.emitLdDataTag g.ilg (UnionCodeGen cgbuf) (avoidHelpers, cuspec) + CG.EmitInstrs cgbuf (pop 1) (Push [g.ilg.typ_Int32]) [ ] // push/pop to match the line above GenSequel cenv eenv.cloc cgbuf sequel and GenSetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, e2, m) sequel = + let g = cenv.g GenExpr cenv cgbuf eenv SPSuppress e Continue let cuspec, idx = GenUnionCaseSpec cenv.amap m eenv.tyenv ucref tyargs - let avoidHelpers = entityRefInThisAssembly cenv.g.compilingFslib ucref.TyconRef - EraseUnions.emitCastData cenv.g.ilg (UnionCodeGen cgbuf) (false, avoidHelpers, cuspec, idx) + let avoidHelpers = entityRefInThisAssembly g.compilingFslib ucref.TyconRef + EraseUnions.emitCastData g.ilg (UnionCodeGen cgbuf) (false, avoidHelpers, cuspec, idx) CG.EmitInstrs cgbuf (pop 1) (Push [cuspec.DeclaringType]) [ ] // push/pop to match the line above GenExpr cenv cgbuf eenv SPSuppress e2 Continue CG.EmitInstrs cgbuf (pop 2) Push0 (EraseUnions.mkStData (cuspec, idx, n)) @@ -2820,15 +3016,16 @@ and GenFieldStore isStatic cenv cgbuf eenv (rfref: RecdFieldRef, tyargs, m) sequ /// Generate arguments to a call, unless the argument is the single lone "unit" value /// to a method or value compiled as a method taking no arguments and GenUntupledArgsDiscardingLoneUnit cenv cgbuf eenv m numObjArgs curriedArgInfos args = + let g = cenv.g match curriedArgInfos, args with // Type.M() // new C() | [[]], [arg] when numObjArgs = 0 -> - assert isUnitTy cenv.g (tyOfExpr cenv.g arg) + assert isUnitTy g (tyOfExpr g arg) GenExpr cenv cgbuf eenv SPSuppress arg discard // obj.M() | [[_];[]], [arg1;arg2] when numObjArgs = 1 -> - assert isUnitTy cenv.g (tyOfExpr cenv.g arg2) + assert isUnitTy g (tyOfExpr g arg2) GenExpr cenv cgbuf eenv SPSuppress arg1 Continue GenExpr cenv cgbuf eenv SPSuppress arg2 discard | _ -> @@ -2837,6 +3034,7 @@ and GenUntupledArgsDiscardingLoneUnit cenv cgbuf eenv m numObjArgs curriedArgInf /// Codegen arguments and GenUntupledArgExpr cenv cgbuf eenv m argInfos expr sequel = + let g = cenv.g let numRequiredExprs = List.length argInfos assert (numRequiredExprs >= 1) if numRequiredExprs = 1 then @@ -2847,13 +3045,13 @@ and GenUntupledArgExpr cenv cgbuf eenv m argInfos expr sequel = es |> List.iter (fun x -> GenExpr cenv cgbuf eenv SPSuppress x Continue) GenSequel cenv eenv.cloc cgbuf sequel else - let ty = tyOfExpr cenv.g expr + let ty = tyOfExpr g expr let locv, loce = mkCompGenLocal m "arg" ty let bind = mkCompGenBind locv expr LocalScope "untuple" cgbuf (fun scopeMarks -> let eenvinner = AllocStorageForBind cenv cgbuf scopeMarks eenv bind GenBinding cenv cgbuf eenvinner bind - let tys = destRefTupleTy cenv.g ty + let tys = destRefTupleTy g ty assert (tys.Length = numRequiredExprs) // TODO - tupInfoRef argInfos |> List.iteri (fun i _ -> GenGetTupleField cenv cgbuf eenvinner (tupInfoRef (* TODO *), loce, tys, i, m) Continue) @@ -2866,17 +3064,18 @@ and GenUntupledArgExpr cenv cgbuf eenv m argInfos expr sequel = //-------------------------------------------------------------------------- and GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel = + let g = cenv.g match (f, tyargs, args) with (* Look for tailcall to turn into branch *) - | (Expr.Val(v, _, _), _, _) when - match ListAssoc.tryFind cenv.g.valRefEq v eenv.innerVals with + | (Expr.Val (v, _, _), _, _) when + match ListAssoc.tryFind g.valRefEq v eenv.innerVals with | Some (kind, _) -> (not v.IsConstructor && (* when branch-calling methods we must have the right type parameters *) (match kind with | BranchCallClosure _ -> true | BranchCallMethod (_, _, tps, _, _) -> - (List.lengthsEqAndForall2 (fun ty tp -> typeEquiv cenv.g ty (mkTyparTy tp)) tyargs tps)) && + (List.lengthsEqAndForall2 (fun ty tp -> typeEquiv g ty (mkTyparTy tp)) tyargs tps)) && (* must be exact #args, ignoring tupling - we untuple if needed below *) (let arityInfo = match kind with @@ -2888,7 +3087,7 @@ and GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel = (match sequelIgnoringEndScopesAndDiscard sequel with Return | ReturnVoid -> true | _ -> false)) | None -> false -> - let (kind, mark) = ListAssoc.find cenv.g.valRefEq v eenv.innerVals // already checked above in when guard + let (kind, mark) = ListAssoc.find g.valRefEq v eenv.innerVals // already checked above in when guard let ntmargs = match kind with | BranchCallClosure arityInfo -> @@ -2917,42 +3116,42 @@ and GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel = // PhysicalEquality becomes cheap reference equality once // a nominal type is known. We can't replace it for variable types since // a "ceq" instruction can't be applied to variable type values. - | (Expr.Val(v, _, _), [ty], [arg1;arg2]) when - (valRefEq cenv.g v cenv.g.reference_equality_inner_vref) - && isAppTy cenv.g ty -> + | (Expr.Val (v, _, _), [ty], [arg1;arg2]) when + (valRefEq g v g.reference_equality_inner_vref) + && isAppTy g ty -> GenExpr cenv cgbuf eenv SPSuppress arg1 Continue GenExpr cenv cgbuf eenv SPSuppress arg2 Continue - CG.EmitInstr cgbuf (pop 2) (Push [cenv.g.ilg.typ_Bool]) AI_ceq + CG.EmitInstr cgbuf (pop 2) (Push [g.ilg.typ_Bool]) AI_ceq GenSequel cenv eenv.cloc cgbuf sequel // Emit "methodhandleof" calls as ldtoken instructions // // The token for the "GenericMethodDefinition" is loaded - | Expr.Val(v, _, m), _, [arg] when valRefEq cenv.g v cenv.g.methodhandleof_vref -> - let (|OptionalCoerce|) = function Expr.Op(TOp.Coerce _, _, [arg], _) -> arg | x -> x - let (|OptionalTyapp|) = function Expr.App(f, _, [_], [], _) -> f | x -> x + | Expr.Val (v, _, m), _, [arg] when valRefEq g v g.methodhandleof_vref -> + let (|OptionalCoerce|) = function Expr.Op (TOp.Coerce _, _, [arg], _) -> arg | x -> x + let (|OptionalTyapp|) = function Expr.App (f, _, [_], [], _) -> f | x -> x match arg with // Generate ldtoken instruction for "methodhandleof(fun (a, b, c) -> f(a, b, c))" // where f is an F# function value or F# method - | Expr.Lambda(_, _, _, _, Expr.App(OptionalCoerce(OptionalTyapp(Expr.Val(vref, _, _))), _, _, _, _), _, _) -> + | Expr.Lambda (_, _, _, _, Expr.App (OptionalCoerce(OptionalTyapp(Expr.Val (vref, _, _))), _, _, _, _), _, _) -> - let storage = StorageForValRef m vref eenv + let storage = StorageForValRef g m vref eenv match storage with | Method (_, _, mspec, _, _, _, _) -> - CG.EmitInstr cgbuf (pop 0) (Push [cenv.g.iltyp_RuntimeMethodHandle]) (I_ldtoken (ILToken.ILMethod mspec)) + CG.EmitInstr cgbuf (pop 0) (Push [g.iltyp_RuntimeMethodHandle]) (I_ldtoken (ILToken.ILMethod mspec)) | _ -> errorR(Error(FSComp.SR.ilxgenUnexpectedArgumentToMethodHandleOfDuringCodegen(), m)) // Generate ldtoken instruction for "methodhandleof(fun (a, b, c) -> obj.M(a, b, c))" // where M is an IL method. - | Expr.Lambda(_, _, _, _, Expr.Op(TOp.ILCall(_, _, valu, _, _, _, _, ilMethRef, actualTypeInst, actualMethInst, _), _, _, _), _, _) -> + | Expr.Lambda (_, _, _, _, Expr.Op (TOp.ILCall (_, _, valu, _, _, _, _, ilMethRef, actualTypeInst, actualMethInst, _), _, _, _), _, _) -> let boxity = (if valu then AsValue else AsObject) let mkFormalParams gparams = gparams |> DropErasedTyargs |> List.mapi (fun n _gf -> mkILTyvarTy (uint16 n)) let ilGenericMethodSpec = IL.mkILMethSpec (ilMethRef, boxity, mkFormalParams actualTypeInst, mkFormalParams actualMethInst) let i = I_ldtoken (ILToken.ILMethod ilGenericMethodSpec) - CG.EmitInstr cgbuf (pop 0) (Push [cenv.g.iltyp_RuntimeMethodHandle]) i + CG.EmitInstr cgbuf (pop 0) (Push [g.iltyp_RuntimeMethodHandle]) i | _ -> System.Diagnostics.Debug.Assert(false, sprintf "Break for invalid methodhandleof argument expression") @@ -2962,32 +3161,32 @@ and GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel = GenSequel cenv eenv.cloc cgbuf sequel // Optimize calls to top methods when given "enough" arguments. - | Expr.Val(vref, valUseFlags, _), _, _ + | Expr.Val (vref, valUseFlags, _), _, _ when - (let storage = StorageForValRef m vref eenv + (let storage = StorageForValRef g m vref eenv match storage with | Method (topValInfo, vref, _, _, _, _, _) -> - (let tps, argtys, _, _ = GetTopValTypeInFSharpForm cenv.g topValInfo vref.Type m + (let tps, argtys, _, _ = GetTopValTypeInFSharpForm g topValInfo vref.Type m tps.Length = tyargs.Length && argtys.Length <= args.Length) | _ -> false) -> - let storage = StorageForValRef m vref eenv + let storage = StorageForValRef g m vref eenv match storage with | Method (topValInfo, vref, mspec, _, _, _, _) -> let nowArgs, laterArgs = - let _, curriedArgInfos, _, _ = GetTopValTypeInFSharpForm cenv.g topValInfo vref.Type m + let _, curriedArgInfos, _, _ = GetTopValTypeInFSharpForm g topValInfo vref.Type m List.splitAt curriedArgInfos.Length args - let actualRetTy = applyTys cenv.g vref.Type (tyargs, nowArgs) - let _, curriedArgInfos, returnTy, _ = GetTopValTypeInCompiledForm cenv.g topValInfo vref.Type m + let actualRetTy = applyTys g vref.Type (tyargs, nowArgs) + let _, curriedArgInfos, returnTy, _ = GetTopValTypeInCompiledForm g topValInfo vref.Type m let ilTyArgs = GenTypeArgs cenv.amap m eenv.tyenv tyargs // For instance method calls chop off some type arguments, which are already // carried by the class. Also work out if it's a virtual call. - let _, virtualCall, newobj, isSuperInit, isSelfInit, _, _, _ = GetMemberCallInfo cenv.g (vref, valUseFlags) in + let _, virtualCall, newobj, isSuperInit, isSelfInit, _, _, _ = GetMemberCallInfo g (vref, valUseFlags) in // numEnclILTypeArgs will include unit-of-measure args, unfortunately. For now, just cut-and-paste code from GetMemberCallInfo // @REVIEW: refactor this @@ -3016,7 +3215,7 @@ and GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel = let isTailCall = if isNil laterArgs && not isSelfInit then - let isDllImport = IsValRefIsDllImport cenv.g vref + let isDllImport = IsValRefIsDllImport g vref let hasByrefArg = mspec.FormalArgTypes |> List.exists (function ILType.Byref _ -> true | _ -> false) let makesNoCriticalTailcalls = vref.MakesNoCriticalTailcalls CanTailcall((boxity=AsValue), ccallInfo, eenv.withinSEH, hasByrefArg, mustGenerateUnitAfterCall, isDllImport, isSelfInit, makesNoCriticalTailcalls, sequel) @@ -3046,9 +3245,12 @@ and GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel = let whereSaved, eenv = (eenv, laterArgs) ||> List.mapFold (fun eenv laterArg -> // Only save arguments that have effects - if Optimizer.ExprHasEffect cenv.g laterArg then - let ilTy = laterArg |> tyOfExpr cenv.g |> GenType cenv.amap m eenv.tyenv - let locName = ilxgenGlobalNng.FreshCompilerGeneratedName ("arg", m), ilTy, false + if Optimizer.ExprHasEffect g laterArg then + let ilTy = laterArg |> tyOfExpr g |> GenType cenv.amap m eenv.tyenv + let locName = + // Ensure that we have an g.CompilerGlobalState + assert(g.CompilerGlobalState |> Option.isSome) + g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName ("arg", m), ilTy, false let loc, _realloc, eenv = AllocLocal cenv cgbuf eenv true locName scopeMarks GenExpr cenv cgbuf eenv SPSuppress laterArg Continue EmitSetLocal cgbuf loc @@ -3085,7 +3287,7 @@ and GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel = // However, we know the type instantiation for the value. // In this case we can often generate a type-specific local expression for the value. // This reduces the number of dynamic type applications. - | (Expr.Val(vref, _, _), _, _) -> + | (Expr.Val (vref, _, _), _, _) -> GenGetValRefAndSequel cenv cgbuf eenv m vref (Some (tyargs, args, m, sequel)) | _ -> @@ -3110,7 +3312,7 @@ and CanTailcall (hasStructObjArg, ccallInfo, withinSEH, hasByrefArg, mustGenerat else Normalcall and GenNamedLocalTyFuncCall cenv (cgbuf: CodeGenBuffer) eenv ty cloinfo tyargs m = - + let g = cenv.g let ilContractClassTyargs = cloinfo.localTypeFuncContractFreeTypars |> List.map mkTyparTy @@ -3128,7 +3330,7 @@ and GenNamedLocalTyFuncCall cenv (cgbuf: CodeGenBuffer) eenv ty cloinfo tyargs m // Local TyFunc are represented as a $contract type. they currently get stored in a value of type object // Recover result (value or reference types) via unbox_any. CG.EmitInstrs cgbuf (pop 1) (Push [ilContractTy]) [I_unbox_any ilContractTy] - let actualRetTy = applyTys cenv.g ty (tyargs, []) + let actualRetTy = applyTys g ty (tyargs, []) let ilDirectInvokeMethSpec = mkILInstanceMethSpecInTy(ilContractTy, "DirectInvoke", [], ilContractFormalRetTy, ilTyArgs) let ilActualRetTy = GenType cenv.amap m eenv.tyenv actualRetTy @@ -3146,13 +3348,14 @@ and GenArgsAndIndirectCall cenv cgbuf eenv (functy, tyargs, args, m) sequel = /// Generate an indirect call, converting to an ILX callfunc instruction and GenIndirectCall cenv cgbuf eenv (functy, tyargs, args, m) sequel = + let g = cenv.g // Fold in the new types into the environment as we generate the formal types. let ilxClosureApps = // keep only non-erased type arguments when computing indirect call let tyargs = DropErasedTyargs tyargs - let typars, formalFuncTy = tryDestForallTy cenv.g functy + let typars, formalFuncTy = tryDestForallTy g functy let feenv = eenv.tyenv.Add typars @@ -3160,7 +3363,7 @@ and GenIndirectCall cenv cgbuf eenv (functy, tyargs, args, m) sequel = let formalRetTy, appBuilder = List.fold (fun (formalFuncTy, sofar) _ -> - let dty, rty = destFunTy cenv.g formalFuncTy + let dty, rty = destFunTy g formalFuncTy (rty, (fun acc -> sofar (Apps_app(GenType cenv.amap m feenv dty, acc))))) (formalFuncTy, id) args @@ -3169,7 +3372,7 @@ and GenIndirectCall cenv cgbuf eenv (functy, tyargs, args, m) sequel = List.foldBack (fun tyarg acc -> Apps_tyapp(GenType cenv.amap m eenv.tyenv tyarg, acc)) tyargs (appBuilder ilxRetApps) - let actualRetTy = applyTys cenv.g functy (tyargs, args) + let actualRetTy = applyTys g functy (tyargs, args) let ilActualRetTy = GenType cenv.amap m eenv.tyenv actualRetTy // Check if any byrefs are involved to make sure we don't tailcall @@ -3185,7 +3388,7 @@ and GenIndirectCall cenv cgbuf eenv (functy, tyargs, args, m) sequel = CountCallFuncInstructions() // Generate the code code an ILX callfunc operation - let instrs = EraseClosures.mkCallFunc cenv.g.ilxPubCloEnv (fun ty -> cgbuf.AllocLocal([], ty, false) |> uint16) eenv.tyenv.Count isTailCall ilxClosureApps + let instrs = EraseClosures.mkCallFunc g.ilxPubCloEnv (fun ty -> cgbuf.AllocLocal([], ty, false) |> uint16) eenv.tyenv.Count isTailCall ilxClosureApps CG.EmitInstrs cgbuf (pop (1+args.Length)) (Push [ilActualRetTy]) instrs // Done compiling indirect call... @@ -3198,9 +3401,9 @@ and GenIndirectCall cenv cgbuf eenv (functy, tyargs, args, m) sequel = and GenTry cenv cgbuf eenv scopeMarks (e1, m, resty, spTry) = let sp = match spTry with - | SequencePointAtTry m -> CG.EmitSeqPoint cgbuf m; SPAlways - | SequencePointInBodyOfTry -> SPAlways - | NoSequencePointAtTry -> SPSuppress + | DebugPointAtTry.Yes m -> CG.EmitSeqPoint cgbuf m; SPAlways + | DebugPointAtTry.Body -> SPAlways + | DebugPointAtTry.No -> SPSuppress let stack, eenvinner = EmitSaveStack cenv cgbuf eenv m scopeMarks let startTryMark = CG.GenerateMark cgbuf "startTryMark" @@ -3210,11 +3413,13 @@ and GenTry cenv cgbuf eenv scopeMarks (e1, m, resty, spTry) = let ilResultTy = GenType cenv.amap m eenvinner.tyenv resty let whereToSave, _realloc, eenvinner = - AllocLocal cenv cgbuf eenvinner true (ilxgenGlobalNng.FreshCompilerGeneratedName ("tryres", m), ilResultTy, false) (startTryMark, endTryMark) + // Ensure that we have an g.CompilerGlobalState + assert(cenv.g.CompilerGlobalState |> Option.isSome) + AllocLocal cenv cgbuf eenvinner true (cenv.g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName ("tryres", m), ilResultTy, false) (startTryMark, endTryMark) - // Generate the body of the try. In the normal case (SequencePointAtTry) we generate a sequence point + // Generate the body of the try. In the normal case (DebugPointAtTry.Yes) we generate a sequence point // both on the 'try' keyword and on the start of the expression in the 'try'. For inlined code and - // compiler generated 'try' blocks (i.e. NoSequencePointAtTry, used for the try/finally implicit + // compiler generated 'try' blocks (i.e. DebugPointAtTry.No, used for the try/finally implicit // in a 'use' or 'foreach'), we suppress the sequence point GenExpr cenv cgbuf eenvinner sp e1 (LeaveHandler (false, whereToSave, afterHandler)) CG.SetMarkToHere cgbuf endTryMark @@ -3222,6 +3427,8 @@ and GenTry cenv cgbuf eenv scopeMarks (e1, m, resty, spTry) = whereToSave, eenvinner, stack, tryMarks, afterHandler, ilResultTy and GenTryCatch cenv cgbuf eenv (e1, vf: Val, ef, vh: Val, eh, m, resty, spTry, spWith) sequel = + let g = cenv.g + // Save the stack - gross because IL flushes the stack at the exn. handler // note: eenvinner notes spill vars are live LocalScope "trystack" cgbuf (fun scopeMarks -> @@ -3233,69 +3440,67 @@ and GenTryCatch cenv cgbuf eenv (e1, vf: Val, ef, vh: Val, eh, m, resty, spTry, if cenv.opts.generateFilterBlocks then let startOfFilter = CG.GenerateMark cgbuf "startOfFilter" let afterFilter = CG.GenerateDelayMark cgbuf "afterFilter" - let (sequelOnBranches, afterJoin, stackAfterJoin, sequelAfterJoin) = GenJoinPoint cenv cgbuf "filter" eenv cenv.g.int_ty m EndFilter - begin - // We emit the sequence point for the 'with' keyword span on the start of the filter - // block. However the targets of the filter block pattern matching should not get any - // sequence points (they will be 'true'/'false' values indicating if the exception has been - // caught or not). - // - // The targets of the handler block DO get sequence points. Thus the expected behaviour - // for a try/with with a complex pattern is that we hit the "with" before the filter is run - // and then jump to the handler for the successful catch (or continue with exception handling - // if the filter fails) - match spWith with - | SequencePointAtWith m -> CG.EmitSeqPoint cgbuf m - | NoSequencePointAtWith -> () - - - CG.SetStack cgbuf [cenv.g.ilg.typ_Object] - let _, eenvinner = AllocLocalVal cenv cgbuf vf eenvinner None (startOfFilter, afterFilter) - CG.EmitInstr cgbuf (pop 1) (Push [cenv.g.iltyp_Exception]) (I_castclass cenv.g.iltyp_Exception) - - GenStoreVal cgbuf eenvinner vf.Range vf - - // Why SPSuppress? Because we do not emit a sequence point at the start of the List.filter - we've already put one on - // the 'with' keyword above - GenExpr cenv cgbuf eenvinner SPSuppress ef sequelOnBranches - CG.SetMarkToHere cgbuf afterJoin - CG.SetStack cgbuf stackAfterJoin - GenSequel cenv eenv.cloc cgbuf sequelAfterJoin - end + let (sequelOnBranches, afterJoin, stackAfterJoin, sequelAfterJoin) = GenJoinPoint cenv cgbuf "filter" eenv g.int_ty m EndFilter + // We emit the sequence point for the 'with' keyword span on the start of the filter + // block. However the targets of the filter block pattern matching should not get any + // sequence points (they will be 'true'/'false' values indicating if the exception has been + // caught or not). + // + // The targets of the handler block DO get sequence points. Thus the expected behaviour + // for a try/with with a complex pattern is that we hit the "with" before the filter is run + // and then jump to the handler for the successful catch (or continue with exception handling + // if the filter fails) + match spWith with + | DebugPointAtWith.Yes m -> CG.EmitSeqPoint cgbuf m + | DebugPointAtWith.No -> () + + + CG.SetStack cgbuf [g.ilg.typ_Object] + let _, eenvinner = AllocLocalVal cenv cgbuf vf eenvinner None (startOfFilter, afterFilter) + CG.EmitInstr cgbuf (pop 1) (Push [g.iltyp_Exception]) (I_castclass g.iltyp_Exception) + + GenStoreVal cenv cgbuf eenvinner vf.Range vf + + // Why SPSuppress? Because we do not emit a sequence point at the start of the List.filter - we've already put one on + // the 'with' keyword above + GenExpr cenv cgbuf eenvinner SPSuppress ef sequelOnBranches + CG.SetMarkToHere cgbuf afterJoin + CG.SetStack cgbuf stackAfterJoin + GenSequel cenv eenv.cloc cgbuf sequelAfterJoin let endOfFilter = CG.GenerateMark cgbuf "endOfFilter" let filterMarks = (startOfFilter.CodeLabel, endOfFilter.CodeLabel) CG.SetMarkToHere cgbuf afterFilter let startOfHandler = CG.GenerateMark cgbuf "startOfHandler" - begin - CG.SetStack cgbuf [cenv.g.ilg.typ_Object] - let _, eenvinner = AllocLocalVal cenv cgbuf vh eenvinner None (startOfHandler, afterHandler) - CG.EmitInstr cgbuf (pop 1) (Push [cenv.g.iltyp_Exception]) (I_castclass cenv.g.iltyp_Exception) - GenStoreVal cgbuf eenvinner vh.Range vh - - GenExpr cenv cgbuf eenvinner SPAlways eh (LeaveHandler (false, whereToSave, afterHandler)) - end + + CG.SetStack cgbuf [g.ilg.typ_Object] + let _, eenvinner = AllocLocalVal cenv cgbuf vh eenvinner None (startOfHandler, afterHandler) + CG.EmitInstr cgbuf (pop 1) (Push [g.iltyp_Exception]) (I_castclass g.iltyp_Exception) + GenStoreVal cenv cgbuf eenvinner vh.Range vh + + GenExpr cenv cgbuf eenvinner SPAlways eh (LeaveHandler (false, whereToSave, afterHandler)) + let endOfHandler = CG.GenerateMark cgbuf "endOfHandler" let handlerMarks = (startOfHandler.CodeLabel, endOfHandler.CodeLabel) ILExceptionClause.FilterCatch(filterMarks, handlerMarks) else let startOfHandler = CG.GenerateMark cgbuf "startOfHandler" - begin - match spWith with - | SequencePointAtWith m -> CG.EmitSeqPoint cgbuf m - | NoSequencePointAtWith -> () + + match spWith with + | DebugPointAtWith.Yes m -> CG.EmitSeqPoint cgbuf m + | DebugPointAtWith.No -> () - CG.SetStack cgbuf [cenv.g.ilg.typ_Object] - let _, eenvinner = AllocLocalVal cenv cgbuf vh eenvinner None (startOfHandler, afterHandler) - CG.EmitInstr cgbuf (pop 1) (Push [cenv.g.iltyp_Exception]) (I_castclass cenv.g.iltyp_Exception) + CG.SetStack cgbuf [g.ilg.typ_Object] + let _, eenvinner = AllocLocalVal cenv cgbuf vh eenvinner None (startOfHandler, afterHandler) + CG.EmitInstr cgbuf (pop 1) (Push [g.iltyp_Exception]) (I_castclass g.iltyp_Exception) - GenStoreVal cgbuf eenvinner m vh + GenStoreVal cenv cgbuf eenvinner m vh - GenExpr cenv cgbuf eenvinner SPAlways eh (LeaveHandler (false, whereToSave, afterHandler)) - end + GenExpr cenv cgbuf eenvinner SPAlways eh (LeaveHandler (false, whereToSave, afterHandler)) + let endOfHandler = CG.GenerateMark cgbuf "endOfHandler" let handlerMarks = (startOfHandler.CodeLabel, endOfHandler.CodeLabel) - ILExceptionClause.TypeCatch(cenv.g.ilg.typ_Object, handlerMarks) + ILExceptionClause.TypeCatch(g.ilg.typ_Object, handlerMarks) cgbuf.EmitExceptionClause { Clause = seh @@ -3327,14 +3532,14 @@ and GenTryFinally cenv cgbuf eenv (bodyExpr, handlerExpr, m, resty, spTry, spFin let sp = match spFinally with - | SequencePointAtFinally m -> CG.EmitSeqPoint cgbuf m; SPAlways - | NoSequencePointAtFinally -> SPSuppress + | DebugPointAtFinally.Yes m -> CG.EmitSeqPoint cgbuf m; SPAlways + | DebugPointAtFinally.No -> SPSuppress GenExpr cenv cgbuf eenvinner sp handlerExpr (LeaveHandler (true, whereToSave, afterHandler)) let endOfHandler = CG.GenerateMark cgbuf "endOfHandler" let handlerMarks = (startOfHandler.CodeLabel, endOfHandler.CodeLabel) cgbuf.EmitExceptionClause - { Clause = ILExceptionClause.Finally(handlerMarks) + { Clause = ILExceptionClause.Finally handlerMarks Range = tryMarks } CG.SetMarkToHere cgbuf afterHandler @@ -3352,6 +3557,9 @@ and GenTryFinally cenv cgbuf eenv (bodyExpr, handlerExpr, m, resty, spTry, spFin //-------------------------------------------------------------------------- and GenForLoop cenv cgbuf eenv (spFor, v, e1, dir, e2, loopBody, m) sequel = + let eenv = SetIsInLoop true eenv + let g = cenv.g + // The JIT/NGen eliminate array-bounds checks for C# loops of form: // for(int i=0; i < (#ldlen arr#); i++) { ... arr[i] ... } // Here @@ -3370,22 +3578,26 @@ and GenForLoop cenv cgbuf eenv (spFor, v, e1, dir, e2, loopBody, m) sequel = let finishIdx, eenvinner = if isFSharpStyle then - let v, _realloc, eenvinner = AllocLocal cenv cgbuf eenvinner true (ilxgenGlobalNng.FreshCompilerGeneratedName ("endLoop", m), cenv.g.ilg.typ_Int32, false) (start, finish) + // Ensure that we have an g.CompilerGlobalState + assert(g.CompilerGlobalState |> Option.isSome) + let vName = g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName ("endLoop", m) + let v, _realloc, eenvinner = AllocLocal cenv cgbuf eenvinner true (vName, g.ilg.typ_Int32, false) (start, finish) v, eenvinner else -1, eenvinner - let _, eenvinner = AllocLocalVal cenv cgbuf v eenvinner None (start, finish) (* note: eenvStack noted stack spill vars are live *) + let _, eenvinner = AllocLocalVal cenv cgbuf v eenvinner None (start, finish) + match spFor with - | SequencePointAtForLoop(spStart) -> CG.EmitSeqPoint cgbuf spStart - | NoSequencePointAtForLoop -> () + | DebugPointAtFor.Yes spStart -> CG.EmitSeqPoint cgbuf spStart + | DebugPointAtFor.No -> () GenExpr cenv cgbuf eenv SPSuppress e1 Continue - GenStoreVal cgbuf eenvinner m v + GenStoreVal cenv cgbuf eenvinner m v if isFSharpStyle then GenExpr cenv cgbuf eenvinner SPSuppress e2 Continue EmitSetLocal cgbuf finishIdx - EmitGetLocal cgbuf cenv.g.ilg.typ_Int32 finishIdx + EmitGetLocal cgbuf g.ilg.typ_Int32 finishIdx GenGetLocalVal cenv cgbuf eenvinner e2.Range v None CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp ((if isUp then BI_blt else BI_bgt), finish.CodeLabel)) @@ -3399,9 +3611,9 @@ and GenForLoop cenv cgbuf eenv (spFor, v, e1, dir, e2, loopBody, m) sequel = // v++ or v-- GenGetLocalVal cenv cgbuf eenvinner e2.Range v None - CG.EmitInstr cgbuf (pop 0) (Push [cenv.g.ilg.typ_Int32]) (mkLdcInt32 1) + CG.EmitInstr cgbuf (pop 0) (Push [g.ilg.typ_Int32]) (mkLdcInt32 1) CG.EmitInstr cgbuf (pop 1) Push0 (if isUp then AI_add else AI_sub) - GenStoreVal cgbuf eenvinner m v + GenStoreVal cenv cgbuf eenvinner m v // .text CG.SetMarkToHere cgbuf test @@ -3410,8 +3622,8 @@ and GenForLoop cenv cgbuf eenv (spFor, v, e1, dir, e2, loopBody, m) sequel = // FSharpForLoopDown: if v <> e2 - 1 then goto .inner // CSharpStyle: if v < e2 then goto .inner match spFor with - | SequencePointAtForLoop(spStart) -> CG.EmitSeqPoint cgbuf spStart - | NoSequencePointAtForLoop -> () //CG.EmitSeqPoint cgbuf e2.Range + | DebugPointAtFor.Yes spStart -> CG.EmitSeqPoint cgbuf spStart + | DebugPointAtFor.No -> () //CG.EmitSeqPoint cgbuf e2.Range GenGetLocalVal cenv cgbuf eenvinner e2.Range v None @@ -3419,8 +3631,8 @@ and GenForLoop cenv cgbuf eenv (spFor, v, e1, dir, e2, loopBody, m) sequel = let e2Sequel = (CmpThenBrOrContinue (pop 2, [ I_brcmp(cmp, inner.CodeLabel) ])) if isFSharpStyle then - EmitGetLocal cgbuf cenv.g.ilg.typ_Int32 finishIdx - CG.EmitInstr cgbuf (pop 0) (Push [cenv.g.ilg.typ_Int32]) (mkLdcInt32 1) + EmitGetLocal cgbuf g.ilg.typ_Int32 finishIdx + CG.EmitInstr cgbuf (pop 0) (Push [g.ilg.typ_Int32]) (mkLdcInt32 1) CG.EmitInstr cgbuf (pop 1) Push0 (if isUp then AI_add else AI_sub) GenSequel cenv eenv.cloc cgbuf e2Sequel else @@ -3438,12 +3650,13 @@ and GenForLoop cenv cgbuf eenv (spFor, v, e1, dir, e2, loopBody, m) sequel = //-------------------------------------------------------------------------- and GenWhileLoop cenv cgbuf eenv (spWhile, e1, e2, m) sequel = + let eenv = SetIsInLoop true eenv let finish = CG.GenerateDelayMark cgbuf "while_finish" let startTest = CG.GenerateMark cgbuf "startTest" match spWhile with - | SequencePointAtWhileLoop(spStart) -> CG.EmitSeqPoint cgbuf spStart - | NoSequencePointAtWhileLoop -> () + | DebugPointAtWhile.Yes spStart -> CG.EmitSeqPoint cgbuf spStart + | DebugPointAtWhile.No -> () // SEQUENCE POINTS: Emit a sequence point to cover all of 'while e do' GenExpr cenv cgbuf eenv SPSuppress e1 (CmpThenBrOrContinue (pop 1, [ I_brcmp(BI_brfalse, finish.CodeLabel) ])) @@ -3454,28 +3667,6 @@ and GenWhileLoop cenv cgbuf eenv (spWhile, e1, e2, m) sequel = // SEQUENCE POINTS: Emit a sequence point to cover 'done' if present GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel -//-------------------------------------------------------------------------- -// Generate seq -//-------------------------------------------------------------------------- - -and GenSequential cenv cgbuf eenv spIn (e1, e2, specialSeqFlag, spSeq, _m) sequel = - - // Compiler generated sequential executions result in suppressions of sequence points on both - // left and right of the sequence - let spAction, spExpr = - (match spSeq with - | SequencePointsAtSeq -> SPAlways, SPAlways - | SuppressSequencePointOnExprOfSequential -> SPSuppress, spIn - | SuppressSequencePointOnStmtOfSequential -> spIn, SPSuppress) - match specialSeqFlag with - | NormalSeq -> - GenExpr cenv cgbuf eenv spAction e1 discard - GenExpr cenv cgbuf eenv spExpr e2 sequel - | ThenDoSeq -> - GenExpr cenv cgbuf eenv spExpr e1 Continue - GenExpr cenv cgbuf eenv spAction e2 discard - GenSequel cenv eenv.cloc cgbuf sequel - //-------------------------------------------------------------------------- // Generate IL assembly code. // Polymorphic IL/ILX instructions may be instantiated when polymorphic code is inlined. @@ -3484,6 +3675,7 @@ and GenSequential cenv cgbuf eenv spIn (e1, e2, specialSeqFlag, spSeq, _m) seque //-------------------------------------------------------------------------- and GenAsmCode cenv cgbuf eenv (il, tyargs, args, returnTys, m) sequel = + let g = cenv.g let ilTyArgs = GenTypesPermitVoid cenv.amap m eenv.tyenv tyargs let ilReturnTys = GenTypesPermitVoid cenv.amap m eenv.tyenv returnTys let ilAfterInst = @@ -3501,28 +3693,28 @@ and GenAsmCode cenv cgbuf eenv (il, tyargs, args, returnTys, m) sequel = let tspec = ty.TypeSpec mkILTy ty.Boxity (mkILTySpec(tspec.TypeRef, ilTyArgs)) } match i, ilTyArgs with - | I_unbox_any (ILType.TypeVar _), [tyarg] -> I_unbox_any (tyarg) - | I_box (ILType.TypeVar _), [tyarg] -> I_box (tyarg) - | I_isinst (ILType.TypeVar _), [tyarg] -> I_isinst (tyarg) - | I_castclass (ILType.TypeVar _), [tyarg] -> I_castclass (tyarg) + | I_unbox_any (ILType.TypeVar _), [tyarg] -> I_unbox_any tyarg + | I_box (ILType.TypeVar _), [tyarg] -> I_box tyarg + | I_isinst (ILType.TypeVar _), [tyarg] -> I_isinst tyarg + | I_castclass (ILType.TypeVar _), [tyarg] -> I_castclass tyarg | I_newarr (shape, ILType.TypeVar _), [tyarg] -> I_newarr (shape, tyarg) | I_ldelem_any (shape, ILType.TypeVar _), [tyarg] -> I_ldelem_any (shape, tyarg) | I_ldelema (ro, _, shape, ILType.TypeVar _), [tyarg] -> I_ldelema (ro, false, shape, tyarg) | I_stelem_any (shape, ILType.TypeVar _), [tyarg] -> I_stelem_any (shape, tyarg) | I_ldobj (a, b, ILType.TypeVar _), [tyarg] -> I_ldobj (a, b, tyarg) | I_stobj (a, b, ILType.TypeVar _), [tyarg] -> I_stobj (a, b, tyarg) - | I_ldtoken (ILToken.ILType (ILType.TypeVar _)), [tyarg] -> I_ldtoken (ILToken.ILType (tyarg)) - | I_sizeof (ILType.TypeVar _), [tyarg] -> I_sizeof (tyarg) + | I_ldtoken (ILToken.ILType (ILType.TypeVar _)), [tyarg] -> I_ldtoken (ILToken.ILType tyarg) + | I_sizeof (ILType.TypeVar _), [tyarg] -> I_sizeof tyarg // currently unused, added for forward compat, see https://visualfsharp.codeplex.com/SourceControl/network/forks/jackpappas/fsharpcontrib/contribution/7134 - | I_cpobj (ILType.TypeVar _), [tyarg] -> I_cpobj (tyarg) - | I_initobj (ILType.TypeVar _), [tyarg] -> I_initobj (tyarg) + | I_cpobj (ILType.TypeVar _), [tyarg] -> I_cpobj tyarg + | I_initobj (ILType.TypeVar _), [tyarg] -> I_initobj tyarg | I_ldfld (al, vol, fspec), _ -> I_ldfld (al, vol, modFieldSpec fspec) - | I_ldflda (fspec), _ -> I_ldflda (modFieldSpec fspec) + | I_ldflda fspec, _ -> I_ldflda (modFieldSpec fspec) | I_stfld (al, vol, fspec), _ -> I_stfld (al, vol, modFieldSpec fspec) | I_stsfld (vol, fspec), _ -> I_stsfld (vol, modFieldSpec fspec) | I_ldsfld (vol, fspec), _ -> I_ldsfld (vol, modFieldSpec fspec) - | I_ldsflda (fspec), _ -> I_ldsflda (modFieldSpec fspec) - | EI_ilzero(ILType.TypeVar _), [tyarg] -> EI_ilzero(tyarg) + | I_ldsflda fspec, _ -> I_ldsflda (modFieldSpec fspec) + | EI_ilzero(ILType.TypeVar _), [tyarg] -> EI_ilzero tyarg | AI_nop, _ -> i // These are embedded in the IL for a an initonly ldfld, i.e. // here's the relevant comment from tc.fs @@ -3544,7 +3736,7 @@ and GenAsmCode cenv cgbuf eenv (il, tyargs, args, returnTys, m) sequel = // This is the instruction sequence for "not" // For these we can just generate the argument and change the test (from a brfalse to a brtrue and vice versa) | ([ AI_ceq ], - [arg1; Expr.Const((Const.Bool false | Const.SByte 0y| Const.Int16 0s | Const.Int32 0 | Const.Int64 0L | Const.Byte 0uy| Const.UInt16 0us | Const.UInt32 0u | Const.UInt64 0UL), _, _) ], + [arg1; Expr.Const ((Const.Bool false | Const.SByte 0y| Const.Int16 0s | Const.Int32 0 | Const.Int64 0L | Const.Byte 0uy| Const.UInt16 0us | Const.UInt32 0u | Const.UInt64 0UL), _, _) ], CmpThenBrOrContinue(1, [I_brcmp (((BI_brfalse | BI_brtrue) as bi), label1) ]), _) -> @@ -3591,7 +3783,6 @@ and GenAsmCode cenv cgbuf eenv (il, tyargs, args, returnTys, m) sequel = GenSequel cenv eenv.cloc cgbuf sequel | _ -> // float or float32 or float<_> or float32<_> - let g = cenv.g in let anyfpType ty = typeEquivAux EraseMeasures g g.float_ty ty || typeEquivAux EraseMeasures g g.float32_ty ty // Otherwise generate the arguments, and see if we can use a I_brcmp rather than a comparison followed by an I_brfalse/I_brtrue @@ -3638,47 +3829,47 @@ and GenAsmCode cenv cgbuf eenv (il, tyargs, args, returnTys, m) sequel = //-------------------------------------------------------------------------- and GenQuotation cenv cgbuf eenv (ast, conv, m, ety) sequel = - + let g = cenv.g let referencedTypeDefs, spliceTypes, spliceArgExprs, astSpec = match !conv with | Some res -> res | None -> try - let qscope = QuotationTranslator.QuotationGenerationScope.Create (cenv.g, cenv.amap, cenv.viewCcu, QuotationTranslator.IsReflectedDefinition.No) - let astSpec = QuotationTranslator.ConvExprPublic qscope QuotationTranslator.QuotationTranslationEnv.Empty ast - let referencedTypeDefs, spliceTypes, spliceArgExprs = qscope.Close() - referencedTypeDefs, List.map fst spliceTypes, List.map fst spliceArgExprs, astSpec + let qscope = QuotationTranslator.QuotationGenerationScope.Create (g, cenv.amap, cenv.viewCcu, QuotationTranslator.IsReflectedDefinition.No) + let astSpec = QuotationTranslator.ConvExprPublic qscope ast + let referencedTypeDefs, typeSplices, exprSplices = qscope.Close() + referencedTypeDefs, List.map fst typeSplices, List.map fst exprSplices, astSpec with - QuotationTranslator.InvalidQuotedTerm e -> error(e) + QuotationTranslator.InvalidQuotedTerm e -> error e let astSerializedBytes = QuotationPickler.pickle astSpec let someTypeInModuleExpr = mkTypeOfExpr cenv m eenv.someTypeInThisAssembly - let rawTy = mkRawQuotedExprTy cenv.g + let rawTy = mkRawQuotedExprTy g let spliceTypeExprs = List.map (GenType cenv.amap m eenv.tyenv >> (mkTypeOfExpr cenv m)) spliceTypes - let bytesExpr = Expr.Op(TOp.Bytes(astSerializedBytes), [], [], m) + let bytesExpr = Expr.Op (TOp.Bytes astSerializedBytes, [], [], m) let deserializeExpr = - match QuotationTranslator.QuotationGenerationScope.ComputeQuotationFormat cenv.g with + match QuotationTranslator.QuotationGenerationScope.ComputeQuotationFormat g with | QuotationTranslator.QuotationSerializationFormat.FSharp_40_Plus -> let referencedTypeDefExprs = List.map (mkILNonGenericBoxedTy >> mkTypeOfExpr cenv m) referencedTypeDefs - let referencedTypeDefsExpr = mkArray (cenv.g.system_Type_ty, referencedTypeDefExprs, m) - let spliceTypesExpr = mkArray (cenv.g.system_Type_ty, spliceTypeExprs, m) + let referencedTypeDefsExpr = mkArray (g.system_Type_ty, referencedTypeDefExprs, m) + let spliceTypesExpr = mkArray (g.system_Type_ty, spliceTypeExprs, m) let spliceArgsExpr = mkArray (rawTy, spliceArgExprs, m) - mkCallDeserializeQuotationFSharp40Plus cenv.g m someTypeInModuleExpr referencedTypeDefsExpr spliceTypesExpr spliceArgsExpr bytesExpr + mkCallDeserializeQuotationFSharp40Plus g m someTypeInModuleExpr referencedTypeDefsExpr spliceTypesExpr spliceArgsExpr bytesExpr | QuotationTranslator.QuotationSerializationFormat.FSharp_20_Plus -> - let mkList ty els = List.foldBack (mkCons cenv.g ty) els (mkNil cenv.g m ty) - let spliceTypesExpr = mkList cenv.g.system_Type_ty spliceTypeExprs + let mkList ty els = List.foldBack (mkCons g ty) els (mkNil g m ty) + let spliceTypesExpr = mkList g.system_Type_ty spliceTypeExprs let spliceArgsExpr = mkList rawTy spliceArgExprs - mkCallDeserializeQuotationFSharp20Plus cenv.g m someTypeInModuleExpr spliceTypesExpr spliceArgsExpr bytesExpr + mkCallDeserializeQuotationFSharp20Plus g m someTypeInModuleExpr spliceTypesExpr spliceArgsExpr bytesExpr let afterCastExpr = // Detect a typed quotation and insert the cast if needed. The cast should not fail but does // unfortunately involve a "typeOf" computation over a quotation tree. - if tyconRefEq cenv.g (tcrefOfAppTy cenv.g ety) cenv.g.expr_tcr then - mkCallCastQuotation cenv.g m (List.head (argsOfAppTy cenv.g ety)) deserializeExpr + if tyconRefEq g (tcrefOfAppTy g ety) g.expr_tcr then + mkCallCastQuotation g m (List.head (argsOfAppTy g ety)) deserializeExpr else deserializeExpr GenExpr cenv cgbuf eenv SPSuppress afterCastExpr sequel @@ -3732,18 +3923,20 @@ and CommitCallSequel cenv eenv m cloc cgbuf mustGenerateUnitAfterCall sequel = and MakeNotSupportedExnExpr cenv eenv (argExpr, m) = - let ety = mkAppTy (cenv.g.FindSysTyconRef ["System"] "NotSupportedException") [] + let g = cenv.g + let ety = mkAppTy (g.FindSysTyconRef ["System"] "NotSupportedException") [] let ilty = GenType cenv.amap m eenv.tyenv ety - let mref = mkILCtorMethSpecForTy(ilty, [cenv.g.ilg.typ_String]).MethodRef - Expr.Op(TOp.ILCall(false, false, false, true, NormalValUse, false, false, mref, [], [], [ety]), [], [argExpr], m) + let mref = mkILCtorMethSpecForTy(ilty, [g.ilg.typ_String]).MethodRef + Expr.Op (TOp.ILCall (false, false, false, true, NormalValUse, false, false, mref, [], [], [ety]), [], [argExpr], m) and GenTraitCall cenv cgbuf eenv (traitInfo, argExprs, m) expr sequel = - let minfoOpt = CommitOperationResult (ConstraintSolver.CodegenWitnessThatTypeSupportsTraitConstraint cenv.TcVal cenv.g cenv.amap m traitInfo argExprs) + let g = cenv.g + let minfoOpt = CommitOperationResult (ConstraintSolver.CodegenWitnessThatTypeSupportsTraitConstraint cenv.TcVal g cenv.amap m traitInfo argExprs) match minfoOpt with | None -> - let exnArg = mkString cenv.g m (FSComp.SR.ilDynamicInvocationNotSupported(traitInfo.MemberName)) + let exnArg = mkString g m (FSComp.SR.ilDynamicInvocationNotSupported(traitInfo.MemberName)) let exnExpr = MakeNotSupportedExnExpr cenv eenv (exnArg, m) - let replacementExpr = mkThrow m (tyOfExpr cenv.g expr) exnExpr + let replacementExpr = mkThrow m (tyOfExpr g expr) exnExpr GenExpr cenv cgbuf eenv SPSuppress replacementExpr sequel | Some expr -> let expr = cenv.optimizeDuringCodeGen expr @@ -3762,7 +3955,7 @@ and GenGetAddrOfRefCellField cenv cgbuf eenv (e, ty, m) sequel = and GenGetValAddr cenv cgbuf eenv (v: ValRef, m) sequel = let vspec = v.Deref let ilTy = GenTypeOfVal cenv eenv vspec - let storage = StorageForValRef m v eenv + let storage = StorageForValRef cenv.g m v eenv match storage with | Local (idx, _, None) -> @@ -3799,31 +3992,35 @@ and GenSetByref cenv cgbuf eenv (v: ValRef, e, m) sequel = GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel and GenDefaultValue cenv cgbuf eenv (ty, m) = + let g = cenv.g let ilTy = GenType cenv.amap m eenv.tyenv ty - if isRefTy cenv.g ty then + if isRefTy g ty then CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) AI_ldnull else - match tryDestAppTy cenv.g ty with - | ValueSome tcref when (tyconRefEq cenv.g cenv.g.system_SByte_tcref tcref || - tyconRefEq cenv.g cenv.g.system_Int16_tcref tcref || - tyconRefEq cenv.g cenv.g.system_Int32_tcref tcref || - tyconRefEq cenv.g cenv.g.system_Bool_tcref tcref || - tyconRefEq cenv.g cenv.g.system_Byte_tcref tcref || - tyconRefEq cenv.g cenv.g.system_Char_tcref tcref || - tyconRefEq cenv.g cenv.g.system_UInt16_tcref tcref || - tyconRefEq cenv.g cenv.g.system_UInt32_tcref tcref) -> + match tryTcrefOfAppTy g ty with + | ValueSome tcref when (tyconRefEq g g.system_SByte_tcref tcref || + tyconRefEq g g.system_Int16_tcref tcref || + tyconRefEq g g.system_Int32_tcref tcref || + tyconRefEq g g.system_Bool_tcref tcref || + tyconRefEq g g.system_Byte_tcref tcref || + tyconRefEq g g.system_Char_tcref tcref || + tyconRefEq g g.system_UInt16_tcref tcref || + tyconRefEq g g.system_UInt32_tcref tcref) -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) iLdcZero - | ValueSome tcref when (tyconRefEq cenv.g cenv.g.system_Int64_tcref tcref || - tyconRefEq cenv.g cenv.g.system_UInt64_tcref tcref) -> + | ValueSome tcref when (tyconRefEq g g.system_Int64_tcref tcref || + tyconRefEq g g.system_UInt64_tcref tcref) -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (iLdcInt64 0L) - | ValueSome tcref when (tyconRefEq cenv.g cenv.g.system_Single_tcref tcref) -> + | ValueSome tcref when (tyconRefEq g g.system_Single_tcref tcref) -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (iLdcSingle 0.0f) - | ValueSome tcref when (tyconRefEq cenv.g cenv.g.system_Double_tcref tcref) -> + | ValueSome tcref when (tyconRefEq g g.system_Double_tcref tcref) -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (iLdcDouble 0.0) | _ -> let ilTy = GenType cenv.amap m eenv.tyenv ty LocalScope "ilzero" cgbuf (fun scopeMarks -> - let locIdx, realloc, _ = AllocLocal cenv cgbuf eenv true (ilxgenGlobalNng.FreshCompilerGeneratedName ("default", m), ilTy, false) scopeMarks + let locIdx, realloc, _ = + // Ensure that we have an g.CompilerGlobalState + assert(g.CompilerGlobalState |> Option.isSome) + AllocLocal cenv cgbuf eenv true (g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName ("default", m), ilTy, false) scopeMarks // "initobj" (Generated by EmitInitLocal) doesn't work on byref types // But ilzero(&ty) only gets generated in the built-in get-address function so // we can just rely on zeroinit of all IL locals. @@ -3839,9 +4036,10 @@ and GenDefaultValue cenv cgbuf eenv (ty, m) = //-------------------------------------------------------------------------- and GenGenericParam cenv eenv (tp: Typar) = + let g = cenv.g let subTypeConstraints = tp.Constraints - |> List.choose (function | TyparConstraint.CoercesTo(ty, _) -> Some(ty) | _ -> None) + |> List.choose (function | TyparConstraint.CoercesTo(ty, _) -> Some ty | _ -> None) |> List.map (GenTypeAux cenv.amap tp.Range eenv.tyenv VoidNotOK PtrTypesNotOK) let refTypeConstraint = @@ -3862,7 +4060,7 @@ and GenGenericParam cenv eenv (tp: Typar) = | None -> tp.Name | Some nm -> nm // Some special rules apply when compiling Fsharp.Core.dll to avoid a proliferation of [] attributes on type parameters - if cenv.g.compilingFslib then + if g.compilingFslib then match nm with | "U" -> "TResult" | "U1" -> "TResult1" @@ -3927,7 +4125,8 @@ and GenFormalSlotsig m cenv eenv (TSlotSig(_, ty, ctps, mtps, paraml, returnTy)) | None -> ilRet ilTy, ilParams, ilRet -and instSlotParam inst (TSlotParam(nm, ty, inFlag, fl2, fl3, attrs)) = TSlotParam(nm, instType inst ty, inFlag, fl2, fl3, attrs) +and instSlotParam inst (TSlotParam(nm, ty, inFlag, fl2, fl3, attrs)) = + TSlotParam(nm, instType inst ty, inFlag, fl2, fl3, attrs) and GenActualSlotsig m cenv eenv (TSlotSig(_, ty, ctps, mtps, ilSlotParams, ilSlotRetTy)) methTyparsOfOverridingMethod (methodParams: Val list) = let ilSlotParams = List.concat ilSlotParams @@ -3944,8 +4143,10 @@ and GenActualSlotsig m cenv eenv (TSlotSig(_, ty, ctps, mtps, ilSlotParams, ilSl let iLRet = mkILReturn ilRetTy ilParams, iLRet -and GenNameOfOverridingMethod cenv (useMethodImpl, (TSlotSig(nameOfOverridenMethod, enclTypOfOverridenMethod, _, _, _, _))) = - if useMethodImpl then qualifiedMangledNameOfTyconRef (tcrefOfAppTy cenv.g enclTypOfOverridenMethod) nameOfOverridenMethod else nameOfOverridenMethod +and GenNameOfOverridingMethod cenv (useMethodImpl, slotsig) = + let (TSlotSig(nameOfOverridenMethod, enclTypOfOverridenMethod, _, _, _, _)) = slotsig + if useMethodImpl then qualifiedMangledNameOfTyconRef (tcrefOfAppTy cenv.g enclTypOfOverridenMethod) nameOfOverridenMethod + else nameOfOverridenMethod and GenMethodImpl cenv eenv (useMethodImpl, (TSlotSig(nameOfOverridenMethod, _, _, _, _, _) as slotsig)) m = let ilOverrideTy, ilOverrideParams, ilOverrideRet = GenFormalSlotsig m cenv eenv slotsig @@ -3978,27 +4179,28 @@ and fixupMethodImplFlags (mdef: ILMethodDef) = mdef.WithAccess(ILMemberAccess.Private).WithHideBySig().WithFinal(true).WithNewSlot and GenObjectMethod cenv eenvinner (cgbuf: CodeGenBuffer) useMethodImpl tmethod = + let g = cenv.g // Check if we're compiling the property as a .NET event - let (TObjExprMethod(slotsig, attribs, methTyparsOfOverridingMethod, methodParams, methodBodyExpr, m)) = tmethod + let (TObjExprMethod(slotsig, attribs, methTyparsOfOverridingMethod, methodParams, moveNextExpr, m)) = tmethod let (TSlotSig(nameOfOverridenMethod, _, _, _, _, _)) = slotsig - if CompileAsEvent cenv.g attribs then + if CompileAsEvent g attribs then [] else let eenvUnderTypars = AddTyparsToEnv methTyparsOfOverridingMethod eenvinner let methodParams = List.concat methodParams - let methodParamsNonSelf = match methodParams with [] -> [] | _::t -> t // drop the 'this' arg when computing better argument names for IL parameters + let methodParamsNonSelf = match methodParams with [] -> [] | _ :: t -> t // drop the 'this' arg when computing better argument names for IL parameters let ilParamsOfOverridingMethod, ilReturnOfOverridingMethod = GenActualSlotsig m cenv eenvUnderTypars slotsig methTyparsOfOverridingMethod methodParamsNonSelf let ilAttribs = GenAttrs cenv eenvinner attribs // Args are stored starting at #1 - let eenvForMeth = AddStorageForLocalVals cenv.g (methodParams |> List.mapi (fun i v -> (v, Arg i))) eenvUnderTypars + let eenvForMeth = AddStorageForLocalVals g (methodParams |> List.mapi (fun i v -> (v, Arg i))) eenvUnderTypars let sequel = (if slotSigHasVoidReturnTy slotsig then discardAndReturnVoid else Return) - let ilMethodBody = CodeGenMethodForExpr cenv cgbuf.mgbuf (SPAlways, [], nameOfOverridenMethod, eenvForMeth, 0, methodBodyExpr, sequel) + let ilMethodBody = CodeGenMethodForExpr cenv cgbuf.mgbuf (SPAlways, [], nameOfOverridenMethod, eenvForMeth, 0, moveNextExpr, sequel) - let nameOfOverridingMethod, methodImplGenerator = GenMethodImpl cenv eenvinner (useMethodImpl, slotsig) methodBodyExpr.Range + let nameOfOverridingMethod, methodImplGenerator = GenMethodImpl cenv eenvinner (useMethodImpl, slotsig) moveNextExpr.Range let mdef = mkILGenericVirtualMethod @@ -4015,7 +4217,8 @@ and GenObjectMethod cenv eenvinner (cgbuf: CodeGenBuffer) useMethodImpl tmethod [(useMethodImpl, methodImplGenerator, methTyparsOfOverridingMethod), mdef] and GenObjectExpr cenv cgbuf eenvouter expr (baseType, baseValOpt, basecall, overrides, interfaceImpls, m) sequel = - let cloinfo, _, eenvinner = GetIlxClosureInfo cenv m false None eenvouter expr + let g = cenv.g + let cloinfo, _, eenvinner = GetIlxClosureInfo cenv m false [] eenvouter expr let cloAttribs = cloinfo.cloAttribs let cloFreeVars = cloinfo.cloFreeVars @@ -4041,7 +4244,7 @@ and GenObjectExpr cenv cgbuf eenvouter expr (baseType, baseValOpt, basecall, ove let mimpls, mdefs = [ for ov in overrides do - yield! genMethodAndOptionalMethodImpl ov (isInterfaceTy cenv.g baseType) + yield! genMethodAndOptionalMethodImpl ov (isInterfaceTy g baseType) for (_, tmethods) in interfaceImpls do for tmethod in tmethods do yield! genMethodAndOptionalMethodImpl tmethod true ] @@ -4052,15 +4255,15 @@ and GenObjectExpr cenv cgbuf eenvouter expr (baseType, baseValOpt, basecall, ove let interfaceTys = interfaceImpls |> List.map (fst >> GenType cenv.amap m eenvinner.tyenv) let attrs = GenAttrs cenv eenvinner cloAttribs - let super = (if isInterfaceTy cenv.g baseType then cenv.g.ilg.typ_Object else ilCloRetTy) - let interfaceTys = interfaceTys @ (if isInterfaceTy cenv.g baseType then [ilCloRetTy] else []) + let super = (if isInterfaceTy g baseType then g.ilg.typ_Object else ilCloRetTy) + let interfaceTys = interfaceTys @ (if isInterfaceTy g baseType then [ilCloRetTy] else []) let cloTypeDefs = GenClosureTypeDefs cenv (ilCloTypeRef, ilCloGenericFormals, attrs, ilCloFreeVars, ilCloLambdas, ilCtorBody, mdefs, mimpls, super, interfaceTys) for cloTypeDef in cloTypeDefs do cgbuf.mgbuf.AddTypeDef(ilCloTypeRef, cloTypeDef, false, false, None) CountClosure() GenGetLocalVals cenv cgbuf eenvouter m cloFreeVars - CG.EmitInstr cgbuf (pop ilCloFreeVars.Length) (Push [ EraseClosures.mkTyOfLambdas cenv.g.ilxPubCloEnv ilCloLambdas]) (I_newobj (ilxCloSpec.Constructor, None)) + CG.EmitInstr cgbuf (pop ilCloFreeVars.Length) (Push [ EraseClosures.mkTyOfLambdas g.ilxPubCloEnv ilCloLambdas]) (I_newobj (ilxCloSpec.Constructor, None)) GenSequel cenv eenvouter.cloc cgbuf sequel and GenSequenceExpr @@ -4069,24 +4272,25 @@ and GenSequenceExpr eenvouter (nextEnumeratorValRef: ValRef, pcvref: ValRef, currvref: ValRef, stateVars, generateNextExpr, closeExpr, checkCloseExpr: Expr, seqElemTy, m) sequel = + let g = cenv.g let stateVars = [ pcvref; currvref ] @ stateVars let stateVarsSet = stateVars |> List.map (fun vref -> vref.Deref) |> Zset.ofList valOrder // pretend that the state variables are bound let eenvouter = - eenvouter |> AddStorageForLocalVals cenv.g (stateVars |> List.map (fun v -> v.Deref, Local(0, false, None))) + eenvouter |> AddStorageForLocalVals g (stateVars |> List.map (fun v -> v.Deref, Local(0, false, None))) // Get the free variables. Make a lambda to pretend that the 'nextEnumeratorValRef' is bound (it is an argument to GenerateNext) let (cloAttribs, _, _, cloFreeTyvars, cloFreeVars, ilCloTypeRef: ILTypeRef, ilCloFreeVars, eenvinner) = - GetIlxClosureFreeVars cenv m None eenvouter [] (mkLambda m nextEnumeratorValRef.Deref (generateNextExpr, cenv.g.int32_ty)) + GetIlxClosureFreeVars cenv m [] eenvouter [] (mkLambda m nextEnumeratorValRef.Deref (generateNextExpr, g.int32_ty)) let ilCloSeqElemTy = GenType cenv.amap m eenvinner.tyenv seqElemTy - let cloRetTy = mkSeqTy cenv.g seqElemTy + let cloRetTy = mkSeqTy g seqElemTy let ilCloRetTyInner = GenType cenv.amap m eenvinner.tyenv cloRetTy let ilCloRetTyOuter = GenType cenv.amap m eenvouter.tyenv cloRetTy - let ilCloEnumeratorTy = GenType cenv.amap m eenvinner.tyenv (mkIEnumeratorTy cenv.g seqElemTy) - let ilCloEnumerableTy = GenType cenv.amap m eenvinner.tyenv (mkSeqTy cenv.g seqElemTy) - let ilCloBaseTy = GenType cenv.amap m eenvinner.tyenv (mkAppTy cenv.g.seq_base_tcr [seqElemTy]) + let ilCloEnumeratorTy = GenType cenv.amap m eenvinner.tyenv (mkIEnumeratorTy g seqElemTy) + let ilCloEnumerableTy = GenType cenv.amap m eenvinner.tyenv (mkSeqTy g seqElemTy) + let ilCloBaseTy = GenType cenv.amap m eenvinner.tyenv (mkAppTy g.seq_base_tcr [seqElemTy]) let ilCloGenericParams = GenGenericParams cenv eenvinner cloFreeTyvars // Create a new closure class with a single "MoveNext" method that implements the iterator. @@ -4111,7 +4315,7 @@ and GenSequenceExpr GenSequel cenv eenv.cloc cgbuf Return), m) mkILNonGenericVirtualMethod("GetFreshEnumerator", ILMemberAccess.Public, [], mkILReturn ilCloEnumeratorTy, MethodBody.IL mbody) - |> AddNonUserCompilerGeneratedAttribs cenv.g + |> AddNonUserCompilerGeneratedAttribs g let closeMethod = // Note: We suppress the first sequence point in the body of this method since it is the initial state machine jump @@ -4123,28 +4327,29 @@ and GenSequenceExpr // Note: We suppress the first sequence point in the body of this method since it is the initial state machine jump let spReq = SPSuppress let ilCode = CodeGenMethodForExpr cenv cgbuf.mgbuf (spReq, [], "get_CheckClose", eenvinner, 1, checkCloseExpr, Return) - mkILNonGenericVirtualMethod("get_CheckClose", ILMemberAccess.Public, [], mkILReturn cenv.g.ilg.typ_Bool, MethodBody.IL ilCode) + mkILNonGenericVirtualMethod("get_CheckClose", ILMemberAccess.Public, [], mkILReturn g.ilg.typ_Bool, MethodBody.IL ilCode) let generateNextMethod = // Note: We suppress the first sequence point in the body of this method since it is the initial state machine jump let spReq = SPSuppress // the 'next enumerator' byref arg is at arg position 1 - let eenvinner = eenvinner |> AddStorageForLocalVals cenv.g [ (nextEnumeratorValRef.Deref, Arg 1) ] + let eenvinner = eenvinner |> AddStorageForLocalVals g [ (nextEnumeratorValRef.Deref, Arg 1) ] let ilParams = [mkILParamNamed("next", ILType.Byref ilCloEnumerableTy)] - let ilReturn = mkILReturn cenv.g.ilg.typ_Int32 + let ilReturn = mkILReturn g.ilg.typ_Int32 let ilCode = MethodBody.IL (CodeGenMethodForExpr cenv cgbuf.mgbuf (spReq, [], "GenerateNext", eenvinner, 2, generateNextExpr, Return)) mkILNonGenericVirtualMethod("GenerateNext", ILMemberAccess.Public, ilParams, ilReturn, ilCode) let lastGeneratedMethod = let ilCode = CodeGenMethodForExpr cenv cgbuf.mgbuf (SPSuppress, [], "get_LastGenerated", eenvinner, 1, exprForValRef m currvref, Return) mkILNonGenericVirtualMethod("get_LastGenerated", ILMemberAccess.Public, [], mkILReturn ilCloSeqElemTy, MethodBody.IL ilCode) - |> AddNonUserCompilerGeneratedAttribs cenv.g + |> AddNonUserCompilerGeneratedAttribs g let ilCtorBody = mkILSimpleStorageCtor(None, Some ilCloBaseTy.TypeSpec, ilCloTyInner, [], [], ILMemberAccess.Assembly).MethodBody let attrs = GenAttrs cenv eenvinner cloAttribs - let cloTypeDefs = GenClosureTypeDefs cenv (ilCloTypeRef, ilCloGenericParams, attrs, ilCloFreeVars, ilCloLambdas, ilCtorBody, [generateNextMethod;closeMethod;checkCloseMethod;lastGeneratedMethod;getFreshMethod], [], ilCloBaseTy, []) + let cloMethods = [generateNextMethod; closeMethod; checkCloseMethod; lastGeneratedMethod; getFreshMethod] + let cloTypeDefs = GenClosureTypeDefs cenv (ilCloTypeRef, ilCloGenericParams, attrs, ilCloFreeVars, ilCloLambdas, ilCtorBody, cloMethods, [], ilCloBaseTy, []) for cloTypeDef in cloTypeDefs do cgbuf.mgbuf.AddTypeDef(ilCloTypeRef, cloTypeDef, false, false, None) @@ -4165,7 +4370,7 @@ and GenSequenceExpr /// Generate the class for a closure type definition and GenClosureTypeDefs cenv (tref: ILTypeRef, ilGenParams, attrs, ilCloFreeVars, ilCloLambdas, ilCtorBody, mdefs, mimpls, ext, ilIntfTys) = - + let g = cenv.g let cloInfo = { cloFreeVars=ilCloFreeVars cloStructure=ilCloLambdas @@ -4176,7 +4381,7 @@ and GenClosureTypeDefs cenv (tref: ILTypeRef, ilGenParams, attrs, ilCloFreeVars, layout = ILTypeDefLayout.Auto, attributes = enum 0, genericParams = ilGenParams, - customAttrs = mkILCustomAttrs(attrs @ [mkCompilationMappingAttr cenv.g (int SourceConstructFlags.Closure) ]), + customAttrs = mkILCustomAttrs(attrs @ [mkCompilationMappingAttr g (int SourceConstructFlags.Closure) ]), fields = emptyILFields, events= emptyILEvents, properties = emptyILProperties, @@ -4194,7 +4399,7 @@ and GenClosureTypeDefs cenv (tref: ILTypeRef, ilGenParams, attrs, ilCloFreeVars, .WithEncoding(ILDefaultPInvokeEncoding.Auto) .WithInitSemantics(ILTypeInit.BeforeField) - let tdefs = EraseClosures.convIlxClosureDef cenv.g.ilxPubCloEnv tref.Enclosing tdef cloInfo + let tdefs = EraseClosures.convIlxClosureDef g.ilxPubCloEnv tref.Enclosing tdef cloInfo tdefs and GenGenericParams cenv eenv tps = @@ -4204,17 +4409,15 @@ and GenGenericArgs m (tyenv: TypeReprEnv) tps = tps |> DropErasedTypars |> List.map (fun c -> (mkILTyvarTy tyenv.[c, m])) /// Generate the closure class for a function -and GenLambdaClosure cenv (cgbuf: CodeGenBuffer) eenv isLocalTypeFunc selfv expr = +and GenLambdaClosure cenv (cgbuf: CodeGenBuffer) eenv isLocalTypeFunc thisVars expr = + let g = cenv.g match expr with | Expr.Lambda (_, _, _, _, _, m, _) - | Expr.TyLambda(_, _, _, m, _) -> + | Expr.TyLambda (_, _, _, m, _) -> - let cloinfo, body, eenvinner = GetIlxClosureInfo cenv m isLocalTypeFunc selfv eenv expr + let cloinfo, body, eenvinner = GetIlxClosureInfo cenv m isLocalTypeFunc thisVars eenv expr - let entryPointInfo = - match selfv with - | Some v -> [(v, BranchCallClosure (cloinfo.cloArityInfo))] - | _ -> [] + let entryPointInfo = thisVars |> List.map (fun v -> (v, BranchCallClosure (cloinfo.cloArityInfo))) let ilCloBody = CodeGenMethodForExpr cenv cgbuf.mgbuf (SPAlways, entryPointInfo, cloinfo.cloName, eenvinner, 1, body, Return) let ilCloTypeRef = cloinfo.cloSpec.TypeRef @@ -4225,7 +4428,7 @@ and GenLambdaClosure cenv (cgbuf: CodeGenBuffer) eenv isLocalTypeFunc selfv expr let (ilContractGenericParams, ilContractMethTyargs, ilContractTySpec: ILTypeSpec, ilContractFormalRetTy) = GenNamedLocalTypeFuncContractInfo cenv eenv m cloinfo let ilContractTypeRef = ilContractTySpec.TypeRef let ilContractTy = mkILFormalBoxedTy ilContractTypeRef ilContractGenericParams - let ilContractCtor = mkILNonGenericEmptyCtor None cenv.g.ilg.typ_Object + let ilContractCtor = mkILNonGenericEmptyCtor None g.ilg.typ_Object let ilContractMeths = [ilContractCtor; mkILGenericVirtualMethod("DirectInvoke", ILMemberAccess.Assembly, ilContractMethTyargs, [], mkILReturn ilContractFormalRetTy, MethodBody.Abstract) ] let ilContractTypeDef = @@ -4233,7 +4436,7 @@ and GenLambdaClosure cenv (cgbuf: CodeGenBuffer) eenv isLocalTypeFunc selfv expr layout = ILTypeDefLayout.Auto, attributes = enum 0, genericParams = ilContractGenericParams, - customAttrs = mkILCustomAttrs [mkCompilationMappingAttr cenv.g (int SourceConstructFlags.Closure) ], + customAttrs = mkILCustomAttrs [mkCompilationMappingAttr g (int SourceConstructFlags.Closure) ], fields = emptyILFields, events= emptyILEvents, properties = emptyILProperties, @@ -4241,7 +4444,7 @@ and GenLambdaClosure cenv (cgbuf: CodeGenBuffer) eenv isLocalTypeFunc selfv expr methodImpls= emptyILMethodImpls, nestedTypes=emptyILTypeDefs, implements = [], - extends= Some cenv.g.ilg.typ_Object, + extends= Some g.ilg.typ_Object, securityDecls= emptyILSecurityDecls) // the contract type is an abstract type and not sealed @@ -4256,14 +4459,14 @@ and GenLambdaClosure cenv (cgbuf: CodeGenBuffer) eenv isLocalTypeFunc selfv expr .WithEncoding(ILDefaultPInvokeEncoding.Auto) cgbuf.mgbuf.AddTypeDef(ilContractTypeRef, ilContractTypeDef, false, false, None) - + let ilCtorBody = mkILMethodBody (true, [], 8, nonBranchingInstrsToCode (mkCallBaseConstructor(ilContractTy, [])), None ) let cloMethods = [ mkILGenericVirtualMethod("DirectInvoke", ILMemberAccess.Assembly, cloinfo.localTypeFuncDirectILGenericParams, [], mkILReturn (cloinfo.cloILFormalRetTy), MethodBody.IL ilCloBody) ] let cloTypeDefs = GenClosureTypeDefs cenv (ilCloTypeRef, cloinfo.cloILGenericParams, [], cloinfo.cloILFreeVars, cloinfo.ilCloLambdas, ilCtorBody, cloMethods, [], ilContractTy, []) cloTypeDefs - + else - GenClosureTypeDefs cenv (ilCloTypeRef, cloinfo.cloILGenericParams, [], cloinfo.cloILFreeVars, cloinfo.ilCloLambdas, ilCloBody, [], [], cenv.g.ilg.typ_Object, []) + GenClosureTypeDefs cenv (ilCloTypeRef, cloinfo.cloILGenericParams, [], cloinfo.cloILFreeVars, cloinfo.ilCloLambdas, ilCloBody, [], [], g.ilg.typ_Object, []) CountClosure() for cloTypeDef in cloTypeDefs do cgbuf.mgbuf.AddTypeDef(ilCloTypeRef, cloTypeDef, false, false, None) @@ -4272,14 +4475,15 @@ and GenLambdaClosure cenv (cgbuf: CodeGenBuffer) eenv isLocalTypeFunc selfv expr | _ -> failwith "GenLambda: not a lambda" and GenLambdaVal cenv (cgbuf: CodeGenBuffer) eenv (cloinfo, m) = + let g = cenv.g GenGetLocalVals cenv cgbuf eenv m cloinfo.cloFreeVars CG.EmitInstr cgbuf (pop cloinfo.cloILFreeVars.Length) - (Push [EraseClosures.mkTyOfLambdas cenv.g.ilxPubCloEnv cloinfo.ilCloLambdas]) + (Push [EraseClosures.mkTyOfLambdas g.ilxPubCloEnv cloinfo.ilCloLambdas]) (I_newobj (cloinfo.cloSpec.Constructor, None)) -and GenLambda cenv cgbuf eenv isLocalTypeFunc selfv expr sequel = - let cloinfo, m = GenLambdaClosure cenv cgbuf eenv isLocalTypeFunc selfv expr +and GenLambda cenv cgbuf eenv isLocalTypeFunc thisVars expr sequel = + let cloinfo, m = GenLambdaClosure cenv cgbuf eenv isLocalTypeFunc thisVars expr GenLambdaVal cenv cgbuf eenv (cloinfo, m) GenSequel cenv eenv.cloc cgbuf sequel @@ -4287,22 +4491,24 @@ and GenTypeOfVal cenv eenv (v: Val) = GenType cenv.amap v.Range eenv.tyenv v.Type and GenFreevar cenv m eenvouter tyenvinner (fv: Val) = - match StorageForVal m fv eenvouter with + let g = cenv.g + match StorageForVal cenv.g m fv eenvouter with // Local type functions - | Local(_, _, Some _) | Env(_, _, _, Some _) -> cenv.g.ilg.typ_Object + | Local(_, _, Some _) | Env(_, _, _, Some _) -> g.ilg.typ_Object #if DEBUG // Check for things that should never make it into the free variable set. Only do this in debug for performance reasons | (StaticField _ | StaticProperty _ | Method _ | Null) -> error(InternalError("GenFreevar: compiler error: unexpected unrealized value", fv.Range)) #endif | _ -> GenType cenv.amap m tyenvinner fv.Type -and GetIlxClosureFreeVars cenv m selfv eenvouter takenNames expr = +and GetIlxClosureFreeVars cenv m (thisVars: ValRef list) eenvouter takenNames expr = + let g = cenv.g // Choose a base name for the closure let basename = let boundv = eenvouter.letBoundVars |> List.tryFind (fun v -> not v.IsCompilerGenerated) match boundv with - | Some v -> v.CompiledName + | Some v -> v.CompiledName cenv.g.CompilerGlobalState | None -> "clo" // Get a unique stamp for the closure. This must be stable for things that can be part of a let rec. @@ -4310,7 +4516,7 @@ and GetIlxClosureFreeVars cenv m selfv eenvouter takenNames expr = match expr with | Expr.Obj (uniq, _, _, _, _, _, _) | Expr.Lambda (uniq, _, _, _, _, _, _) - | Expr.TyLambda(uniq, _, _, _, _) -> uniq + | Expr.TyLambda (uniq, _, _, _, _) -> uniq | _ -> newUnique() // Choose a name for the closure @@ -4318,7 +4524,10 @@ and GetIlxClosureFreeVars cenv m selfv eenvouter takenNames expr = // FSharp 1.0 bug 3404: System.Reflection doesn't like '.' and '`' in type names let basenameSafeForUseAsTypename = CleanUpGeneratedTypeName basename let suffixmark = expr.Range - let cloName = globalStableNameGenerator.GetUniqueCompilerGeneratedName(basenameSafeForUseAsTypename, suffixmark, uniq) + let cloName = + // Ensure that we have an g.CompilerGlobalState + assert(g.CompilerGlobalState |> Option.isSome) + g.CompilerGlobalState.Value.StableNameGenerator.GetUniqueCompilerGeneratedName(basenameSafeForUseAsTypename, suffixmark, uniq) NestedTypeRefForCompLoc eenvouter.cloc cloName // Collect the free variables of the closure @@ -4331,12 +4540,10 @@ and GetIlxClosureFreeVars cenv m selfv eenvouter takenNames expr = cloFreeVarResults.FreeLocals |> Zset.elements |> List.filter (fun fv -> - match StorageForVal m fv eenvouter with - | (StaticField _ | StaticProperty _ | Method _ | Null) -> false - | _ -> - match selfv with - | Some v -> not (valRefEq cenv.g (mkLocalValRef fv) v) - | _ -> true) + (thisVars |> List.forall (fun v -> not (valRefEq g (mkLocalValRef fv) v))) && + (match StorageForVal cenv.g m fv eenvouter with + | (StaticField _ | StaticProperty _ | Method _ | Null) -> false + | _ -> true)) // The general shape is: // {LAM . expr }[free-typars]: overall-type[contract-typars] @@ -4348,7 +4555,7 @@ and GetIlxClosureFreeVars cenv m selfv eenvouter takenNames expr = // bake our own function base contracts for local type functions // // -- "internal" ones, which get used internally in the implementation - let cloContractFreeTyvarSet = (freeInType CollectTypars (tyOfExpr cenv.g expr)).FreeTypars + let cloContractFreeTyvarSet = (freeInType CollectTypars (tyOfExpr g expr)).FreeTypars let cloInternalFreeTyvars = Zset.diff cloFreeVarResults.FreeTyvars.FreeTypars cloContractFreeTyvarSet |> Zset.elements let cloContractFreeTyvars = cloContractFreeTyvarSet |> Zset.elements @@ -4366,7 +4573,7 @@ and GetIlxClosureFreeVars cenv m selfv eenvouter takenNames expr = // If generating a named closure, add the closure itself as a var, available via "arg0" . // The latter doesn't apply for the delegate implementation of closures. // Build the environment that is active inside the closure itself - let eenvinner = eenvinner |> AddStorageForLocalVals cenv.g (match selfv with | Some v -> [(v.Deref, Arg 0)] | _ -> []) + let eenvinner = eenvinner |> AddStorageForLocalVals g (thisVars |> List.map (fun v -> (v.Deref, Arg 0))) let ilCloFreeVars = let ilCloFreeVarNames = ChooseFreeVarNames takenNames (List.map nameOfVal cloFreeVars) @@ -4376,7 +4583,7 @@ and GetIlxClosureFreeVars cenv m selfv eenvouter takenNames expr = let ilCloFreeVarStorage = (cloFreeVars, ilCloFreeVars) ||> List.mapi2 (fun i v fv -> let localCloInfo = - match StorageForVal m v eenvouter with + match StorageForVal g m v eenvouter with | Local(_, _, localCloInfo) | Env(_, _, _, localCloInfo) -> localCloInfo | _ -> None @@ -4384,17 +4591,18 @@ and GetIlxClosureFreeVars cenv m selfv eenvouter takenNames expr = (v, Env(ilCloTyInner, i, ilField, localCloInfo))) - let eenvinner = eenvinner |> AddStorageForLocalVals cenv.g ilCloFreeVarStorage + let eenvinner = eenvinner |> AddStorageForLocalVals g ilCloFreeVarStorage // Return a various results (cloAttribs, cloInternalFreeTyvars, cloContractFreeTyvars, cloFreeTyvars, cloFreeVars, ilCloTypeRef, Array.ofList ilCloFreeVars, eenvinner) -and GetIlxClosureInfo cenv m isLocalTypeFunc selfv eenvouter expr = +and GetIlxClosureInfo cenv m isLocalTypeFunc thisVars eenvouter expr = + let g = cenv.g let returnTy = match expr with - | Expr.Lambda (_, _, _, _, _, _, returnTy) | Expr.TyLambda(_, _, _, _, returnTy) -> returnTy - | Expr.Obj(_, ty, _, _, _, _, _) -> ty + | Expr.Lambda (_, _, _, _, _, _, returnTy) | Expr.TyLambda (_, _, _, _, returnTy) -> returnTy + | Expr.Obj (_, ty, _, _, _, _, _) -> ty | _ -> failwith "GetIlxClosureInfo: not a lambda expression" // Determine the structure of the closure. We do this before analyzing free variables to @@ -4402,21 +4610,22 @@ and GetIlxClosureInfo cenv m isLocalTypeFunc selfv eenvouter expr = let tvsl, vs, body, returnTy = let rec getCallStructure tvacc vacc (e, ety) = match e with - | Expr.TyLambda(_, tvs, body, _m, bty) -> + | Expr.TyLambda (_, tvs, body, _m, bty) -> getCallStructure ((DropErasedTypars tvs) :: tvacc) vacc (body, bty) | Expr.Lambda (_, _, _, vs, body, _, bty) when not isLocalTypeFunc -> // Transform a lambda taking untupled arguments into one // taking only a single tupled argument if necessary. REVIEW: do this earlier - let tupledv, body = MultiLambdaToTupledLambda cenv.g vs body + let tupledv, body = MultiLambdaToTupledLambda g vs body getCallStructure tvacc (tupledv :: vacc) (body, bty) | _ -> (List.rev tvacc, List.rev vacc, e, ety) getCallStructure [] [] (expr, returnTy) - let takenNames = vs |> List.map (fun v -> v.CompiledName) + let takenNames = vs |> List.map (fun v -> v.CompiledName g.CompilerGlobalState) // Get the free variables and the information about the closure, add the free variables to the environment - let (cloAttribs, cloInternalFreeTyvars, cloContractFreeTyvars, _, cloFreeVars, ilCloTypeRef, ilCloFreeVars, eenvinner) = GetIlxClosureFreeVars cenv m selfv eenvouter takenNames expr + let (cloAttribs, cloInternalFreeTyvars, cloContractFreeTyvars, _, cloFreeVars, ilCloTypeRef, ilCloFreeVars, eenvinner) = + GetIlxClosureFreeVars cenv m thisVars eenvouter takenNames expr // Put the type and value arguments into the environment let rec getClosureArgs eenv ntmargs tvsl (vs: Val list) = @@ -4427,9 +4636,9 @@ and GetIlxClosureInfo cenv m isLocalTypeFunc selfv eenvouter expr = let lambdas = (tvs, l) ||> List.foldBack (fun tv sofar -> Lambdas_forall(GenGenericParam cenv eenv tv, sofar)) lambdas, eenv | [], v :: rest -> - let nm = v.CompiledName + let nm = v.CompiledName g.CompilerGlobalState let l, eenv = - let eenv = AddStorageForVal cenv.g (v, notlazy (Arg ntmargs)) eenv + let eenv = AddStorageForVal g (v, notlazy (Arg ntmargs)) eenv getClosureArgs eenv (ntmargs+1) [] rest let lambdas = Lambdas_lambda (mkILParamNamed(nm, GenTypeOfVal cenv eenv v), l) lambdas, eenv @@ -4495,7 +4704,7 @@ and GetIlxClosureInfo cenv m isLocalTypeFunc selfv eenvouter expr = if isLocalTypeFunc then let rec strip lambdas acc = match lambdas with - | Lambdas_forall(gp, r) -> strip r (gp::acc) + | Lambdas_forall(gp, r) -> strip r (gp :: acc) | Lambdas_return returnTy -> List.rev acc, returnTy, lambdas | _ -> failwith "AdjustNamedLocalTypeFuncIlxClosureInfo: local functions can currently only be type functions" strip ilCloLambdas [] @@ -4527,7 +4736,7 @@ and GetIlxClosureInfo cenv m isLocalTypeFunc selfv eenvouter expr = and IsNamedLocalTypeFuncVal g (v: Val) expr = not v.IsCompiledAsTopLevel && - IsGenericValWithGenericContraints g v && + IsGenericValWithGenericConstraints g v && (match stripExpr expr with Expr.TyLambda _ -> true | _ -> false) /// Generate the information relevant to the contract portion of a named local type function @@ -4538,7 +4747,7 @@ and GenNamedLocalTypeFuncContractInfo cenv eenv m cloinfo = let ilContractGenericParams = GenGenericParams cenv eenv cloinfo.localTypeFuncContractFreeTypars let tvs, contractRetTy = match cloinfo.cloExpr with - | Expr.TyLambda(_, tvs, _, _, bty) -> tvs, bty + | Expr.TyLambda (_, tvs, _, _, bty) -> tvs, bty | e -> [], tyOfExpr cenv.g e let eenvForContract = AddTyparsToEnv tvs eenvForContract let ilContractMethTyargs = GenGenericParams cenv eenvForContract tvs @@ -4548,6 +4757,8 @@ and GenNamedLocalTypeFuncContractInfo cenv eenv m cloinfo = /// Generate a new delegate construction including a closure class if necessary. This is a lot like generating function closures /// and object expression closures, and most of the code is shared. and GenDelegateExpr cenv cgbuf eenvouter expr (TObjExprMethod((TSlotSig(_, delegateTy, _, _, _, _) as slotsig), _attribs, methTyparsOfOverridingMethod, tmvs, body, _), m) sequel = + let g = cenv.g + // Get the instantiation of the delegate type let ilCtxtDelTy = GenType cenv.amap m eenvouter.tyenv delegateTy let tmvs = List.concat tmvs @@ -4555,8 +4766,8 @@ and GenDelegateExpr cenv cgbuf eenvouter expr (TObjExprMethod((TSlotSig(_, deleg // Yuck. TLBIMP.EXE generated APIs use UIntPtr for the delegate ctor. let useUIntPtrForDelegateCtor = try - if isILAppTy cenv.g delegateTy then - let tcref = tcrefOfAppTy cenv.g delegateTy + if isILAppTy g delegateTy then + let tcref = tcrefOfAppTy g delegateTy let tdef = tcref.ILTyconRawMetadata match tdef.Methods.FindByName ".ctor" with | [ctorMDef] -> @@ -4571,7 +4782,8 @@ and GenDelegateExpr cenv cgbuf eenvouter expr (TObjExprMethod((TSlotSig(_, deleg // Work out the free type variables for the morphing thunk let takenNames = List.map nameOfVal tmvs - let (cloAttribs, _, _, cloFreeTyvars, cloFreeVars, ilDelegeeTypeRef, ilCloFreeVars, eenvinner) = GetIlxClosureFreeVars cenv m None eenvouter takenNames expr + let (cloAttribs, _, _, cloFreeTyvars, cloFreeVars, ilDelegeeTypeRef, ilCloFreeVars, eenvinner) = + GetIlxClosureFreeVars cenv m [] eenvouter takenNames expr let ilDelegeeGenericParams = GenGenericParams cenv eenvinner cloFreeTyvars let ilDelegeeGenericActualsInner = mkILFormalGenericArgs 0 ilDelegeeGenericParams @@ -4582,13 +4794,13 @@ and GenDelegateExpr cenv cgbuf eenvouter expr (TObjExprMethod((TSlotSig(_, deleg let envForDelegeeUnderTypars = AddTyparsToEnv methTyparsOfOverridingMethod eenvinner let numthis = 1 - let tmvs, body = BindUnitVars cenv.g (tmvs, List.replicate (List.concat slotsig.FormalParams).Length ValReprInfo.unnamedTopArg1, body) + let tmvs, body = BindUnitVars g (tmvs, List.replicate (List.concat slotsig.FormalParams).Length ValReprInfo.unnamedTopArg1, body) // The slot sig contains a formal instantiation. When creating delegates we're only // interested in the actual instantiation since we don't have to emit a method impl. let ilDelegeeParams, ilDelegeeRet = GenActualSlotsig m cenv envForDelegeeUnderTypars slotsig methTyparsOfOverridingMethod tmvs - let envForDelegeeMeth = AddStorageForLocalVals cenv.g (List.mapi (fun i v -> (v, Arg (i+numthis))) tmvs) envForDelegeeUnderTypars + let envForDelegeeMeth = AddStorageForLocalVals g (List.mapi (fun i v -> (v, Arg (i+numthis))) tmvs) envForDelegeeUnderTypars let ilMethodBody = CodeGenMethodForExpr cenv cgbuf.mgbuf (SPAlways, [], delegeeMethName, envForDelegeeMeth, 1, body, (if slotSigHasVoidReturnTy slotsig then discardAndReturnVoid else Return)) let delegeeInvokeMeth = mkILNonGenericInstanceMethod @@ -4596,12 +4808,12 @@ and GenDelegateExpr cenv cgbuf eenvouter expr (TObjExprMethod((TSlotSig(_, deleg ilDelegeeParams, ilDelegeeRet, MethodBody.IL ilMethodBody) - let delegeeCtorMeth = mkILSimpleStorageCtor(None, Some cenv.g.ilg.typ_Object.TypeSpec, ilDelegeeTyInner, [], [], ILMemberAccess.Assembly) + let delegeeCtorMeth = mkILSimpleStorageCtor(None, Some g.ilg.typ_Object.TypeSpec, ilDelegeeTyInner, [], [], ILMemberAccess.Assembly) let ilCtorBody = delegeeCtorMeth.MethodBody let ilCloLambdas = Lambdas_return ilCtxtDelTy let ilAttribs = GenAttrs cenv eenvinner cloAttribs - let cloTypeDefs = GenClosureTypeDefs cenv (ilDelegeeTypeRef, ilDelegeeGenericParams, ilAttribs, ilCloFreeVars, ilCloLambdas, ilCtorBody, [delegeeInvokeMeth], [], cenv.g.ilg.typ_Object, []) + let cloTypeDefs = GenClosureTypeDefs cenv (ilDelegeeTypeRef, ilDelegeeGenericParams, ilAttribs, ilCloFreeVars, ilCloLambdas, ilCtorBody, [delegeeInvokeMeth], [], g.ilg.typ_Object, []) for cloTypeDef in cloTypeDefs do cgbuf.mgbuf.AddTypeDef(ilDelegeeTypeRef, cloTypeDef, false, false, None) CountClosure() @@ -4609,12 +4821,12 @@ and GenDelegateExpr cenv cgbuf eenvouter expr (TObjExprMethod((TSlotSig(_, deleg let ctxtGenericArgsForDelegee = GenGenericArgs m eenvouter.tyenv cloFreeTyvars let ilxCloSpec = IlxClosureSpec.Create(IlxClosureRef(ilDelegeeTypeRef, ilCloLambdas, ilCloFreeVars), ctxtGenericArgsForDelegee) GenGetLocalVals cenv cgbuf eenvouter m cloFreeVars - CG.EmitInstr cgbuf (pop ilCloFreeVars.Length) (Push [EraseClosures.mkTyOfLambdas cenv.g.ilxPubCloEnv ilCloLambdas]) (I_newobj (ilxCloSpec.Constructor, None)) + CG.EmitInstr cgbuf (pop ilCloFreeVars.Length) (Push [EraseClosures.mkTyOfLambdas g.ilxPubCloEnv ilCloLambdas]) (I_newobj (ilxCloSpec.Constructor, None)) let ilDelegeeTyOuter = mkILBoxedTy ilDelegeeTypeRef ctxtGenericArgsForDelegee let ilDelegeeInvokeMethOuter = mkILNonGenericInstanceMethSpecInTy (ilDelegeeTyOuter, "Invoke", typesOfILParams ilDelegeeParams, ilDelegeeRet.Type) - let ilDelegeeCtorMethOuter = mkCtorMethSpecForDelegate cenv.g.ilg (ilCtxtDelTy, useUIntPtrForDelegateCtor) - CG.EmitInstr cgbuf (pop 0) (Push [cenv.g.ilg.typ_IntPtr]) (I_ldftn ilDelegeeInvokeMethOuter) + let ilDelegeeCtorMethOuter = mkCtorMethSpecForDelegate g.ilg (ilCtxtDelTy, useUIntPtrForDelegateCtor) + CG.EmitInstr cgbuf (pop 0) (Push [g.ilg.typ_IntPtr]) (I_ldftn ilDelegeeInvokeMethOuter) CG.EmitInstr cgbuf (pop 2) (Push [ilCtxtDelTy]) (I_newobj(ilDelegeeCtorMethOuter, None)) GenSequel cenv eenvouter.cloc cgbuf sequel @@ -4667,69 +4879,28 @@ and GenJoinPoint cenv cgbuf pos eenv ty m sequel = let afterJoin = CG.GenerateDelayMark cgbuf (pos + "_join") // go to the join point Br afterJoin, afterJoin, stackAfterJoin, sequel - -and GenMatch cenv cgbuf eenv (spBind, _exprm, tree, targets, m, ty) sequel = - - match spBind with - | SequencePointAtBinding m -> CG.EmitSeqPoint cgbuf m - | NoSequencePointAtDoBinding - | NoSequencePointAtLetBinding - | NoSequencePointAtInvisibleBinding - | NoSequencePointAtStickyBinding -> () - - // The target of branch needs a sequence point. - // If we don't give it one it will get entirely the wrong sequence point depending on earlier codegen - // Note we're not interested in having pattern matching and decision trees reveal their inner working. - // Hence at each branch target we 'reassert' the overall sequence point that was active as we came into the match. - // - // NOTE: sadly this causes multiple sequence points to appear for the "initial" location of an if/then/else or match. - let activeSP = cgbuf.GetLastSequencePoint() - let repeatSP() = - match activeSP with - | None -> () - | Some src -> - if activeSP <> cgbuf.GetLastSequencePoint() then - CG.EmitSeqPoint cgbuf src - - // First try the common cases where we don't need a join point. - match tree with - | TDSuccess _ -> - failwith "internal error: matches that immediately succeed should have been normalized using mkAndSimplifyMatch" - - | _ -> - // Create a join point - let stackAtTargets = cgbuf.GetCurrentStack() // the stack at the target of each clause - let (sequelOnBranches, afterJoin, stackAfterJoin, sequelAfterJoin) = GenJoinPoint cenv cgbuf "match" eenv ty m sequel - - // Stack: "stackAtTargets" is "stack prior to any match-testing" and also "stack at the start of each branch-RHS". - // match-testing (dtrees) should not contribute to the stack. - // Each branch-RHS (targets) may contribute to the stack, leaving it in the "stackAfterJoin" state, for the join point. - // Since code is branching and joining, the cgbuf stack is maintained manually. - GenDecisionTreeAndTargets cenv cgbuf stackAtTargets eenv tree targets repeatSP sequelOnBranches - CG.SetMarkToHere cgbuf afterJoin - - //assert(cgbuf.GetCurrentStack() = stackAfterJoin) // REVIEW: Since gen_dtree* now sets stack, stack should be stackAfterJoin at this point... - CG.SetStack cgbuf stackAfterJoin - // If any values are left on the stack after the join then we're certainly going to do something with them - // For example, we may be about to execute a 'stloc' for - // - // let y2 = if System.DateTime.Now.Year < 2000 then 1 else 2 - // - // or a 'stelem' for - // - // arr.[0] <- if System.DateTime.Now.Year > 2000 then 1 else 2 - // - // In both cases, any instructions that come after this point will be falsely associated with the last branch of the control - // prior to the join point. This is base, e.g. see FSharp 1.0 bug 5155 - if not (isNil stackAfterJoin) then - cgbuf.EmitStartOfHiddenCode() - - GenSequel cenv eenv.cloc cgbuf sequelAfterJoin // Accumulate the decision graph as we go -and GenDecisionTreeAndTargets cenv cgbuf stackAtTargets eenv tree targets repeatSP sequel = - let targetInfos = GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv tree targets repeatSP (IntMap.empty()) sequel - GenPostponedDecisionTreeTargets cenv cgbuf stackAtTargets targetInfos sequel +and GenDecisionTreeAndTargets cenv cgbuf stackAtTargets eenv tree targets repeatSP sequel contf = + GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv tree targets repeatSP (IntMap.empty()) sequel (fun targetInfos -> + let sortedTargetInfos = + targetInfos + |> Seq.sortBy (fun (KeyValue(targetIdx, _)) -> targetIdx) + |> List.ofSeq + GenPostponedDecisionTreeTargets cenv cgbuf sortedTargetInfos stackAtTargets sequel contf + ) + +and GenPostponedDecisionTreeTargets cenv cgbuf targetInfos stackAtTargets sequel contf = + match targetInfos with + | [] -> contf Fake + | (KeyValue(_, (targetInfo, isTargetPostponed))) :: rest -> + if isTargetPostponed then + let eenvAtTarget, spExprAtTarget, exprAtTarget, sequelAtTarget = GenDecisionTreeTarget cenv cgbuf stackAtTargets targetInfo sequel + GenLinearExpr cenv cgbuf eenvAtTarget spExprAtTarget exprAtTarget sequelAtTarget true (fun Fake -> + GenPostponedDecisionTreeTargets cenv cgbuf rest stackAtTargets sequel contf + ) + else + GenPostponedDecisionTreeTargets cenv cgbuf rest stackAtTargets sequel contf and TryFindTargetInfo targetInfos n = match IntMap.tryFind n targetInfos with @@ -4740,26 +4911,31 @@ and TryFindTargetInfo targetInfos n = /// /// When inplabOpt is "Some inplab", we are assuming an existing branch to "inplab" and can optionally /// set inplab to point to another location if no codegen is required. -and GenDecisionTreeAndTargetsInner cenv cgbuf inplabOpt stackAtTargets eenv tree targets repeatSP targetInfos sequel = +and GenDecisionTreeAndTargetsInner cenv cgbuf inplabOpt stackAtTargets eenv tree targets repeatSP targetInfos sequel (contf: Zmap<_,_> -> FakeUnit) = CG.SetStack cgbuf stackAtTargets // Set the expected initial stack. match tree with | TDBind(bind, rest) -> match inplabOpt with Some inplab -> CG.SetMarkToHere cgbuf inplab | None -> () let startScope, endScope as scopeMarks = StartDelayedLocalScope "dtreeBind" cgbuf let eenv = AllocStorageForBind cenv cgbuf scopeMarks eenv bind - let sp = GenSequencePointForBind cenv cgbuf bind - GenBindingAfterSequencePoint cenv cgbuf eenv sp bind (Some startScope) + let sp = GenDebugPointForBind cenv cgbuf bind + GenBindingAfterDebugPoint cenv cgbuf eenv sp bind (Some startScope) // We don't get the scope marks quite right for dtree-bound variables. This is because // we effectively lose an EndLocalScope for all dtrees that go to the same target // So we just pretend that the variable goes out of scope here. CG.SetMarkToHere cgbuf endScope - GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv rest targets repeatSP targetInfos sequel + GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv rest targets repeatSP targetInfos sequel contf - | TDSuccess (es, targetIdx) -> - GenDecisionTreeSuccess cenv cgbuf inplabOpt stackAtTargets eenv es targetIdx targets repeatSP targetInfos sequel + | TDSuccess(es, targetIdx) -> + let targetInfos, genTargetInfoOpt = GenDecisionTreeSuccess cenv cgbuf inplabOpt stackAtTargets eenv es targetIdx targets repeatSP targetInfos sequel + match genTargetInfoOpt with + | Some (eenvAtTarget, spExprAtTarget, exprAtTarget, sequelAtTarget) -> + GenLinearExpr cenv cgbuf eenvAtTarget spExprAtTarget exprAtTarget sequelAtTarget true (fun Fake -> contf targetInfos) + | _ -> + contf targetInfos | TDSwitch(e, cases, dflt, m) -> - GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases dflt m targets repeatSP targetInfos sequel + GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases dflt m targets repeatSP targetInfos sequel contf and GetTarget (targets:_[]) n = if n >= targets.Length then failwith "GetTarget: target not found in decision tree" @@ -4780,14 +4956,19 @@ and GenDecisionTreeSuccess cenv cgbuf inplabOpt stackAtTargets eenv es targetIdx else match inplabOpt with None -> () | Some inplab -> CG.SetMarkToHere cgbuf inplab repeatSP() - // It would be better not to emit any expressions here, and instead push these assignments into the postponed target - // However not all targets are currently postponed (we only postpone in debug code), pending further testing of the performance - // impact of postponing. - (vs, es) ||> List.iter2 (GenBindingRhs cenv cgbuf eenv SPSuppress) - vs |> List.rev |> List.iter (fun v -> GenStoreVal cgbuf eenvAtTarget v.Range v) + + (vs, es) ||> List.iter2 (fun v e -> + + // Emit the expression + GenBindingRhs cenv cgbuf eenv SPSuppress v e) + + vs |> List.rev |> List.iter (fun v -> + // Store the results + GenStoreVal cenv cgbuf eenvAtTarget v.Range v) + CG.EmitInstr cgbuf (pop 0) Push0 (I_br targetMarkAfterBinds.CodeLabel) - targetInfos + targetInfos, None | None -> @@ -4800,26 +4981,19 @@ and GenDecisionTreeSuccess cenv cgbuf inplabOpt stackAtTargets eenv es targetIdx let targetInfo = (targetMarkBeforeBinds, targetMarkAfterBinds, eenvAtTarget, successExpr, spTarget, repeatSP, vs, binds, startScope, endScope) // In debug mode push all decision tree targets to after the switching - let isTargetPostponed = - if cenv.opts.localOptimizationsAreOn then - GenDecisionTreeTarget cenv cgbuf stackAtTargets targetIdx targetInfo sequel - false + let isTargetPostponed, genTargetInfoOpt = + if cenv.opts.localOptimizationsAreOn then + false, Some(GenDecisionTreeTarget cenv cgbuf stackAtTargets targetInfo sequel) else CG.EmitInstr cgbuf (pop 0) Push0 (I_br targetMarkBeforeBinds.CodeLabel) - true + true, None let targetInfos = IntMap.add targetIdx (targetInfo, isTargetPostponed) targetInfos - targetInfos - -and GenPostponedDecisionTreeTargets cenv cgbuf stackAtTargets targetInfos sequel = - let targetInfos = targetInfos |> Seq.sortBy (fun (KeyValue(targetIdx, _)) -> targetIdx) - for (KeyValue(targetIdx, (targetInfo, isTargetPostponed))) in targetInfos do - if isTargetPostponed then - GenDecisionTreeTarget cenv cgbuf stackAtTargets targetIdx targetInfo sequel + targetInfos, genTargetInfoOpt -and GenDecisionTreeTarget cenv cgbuf stackAtTargets _targetIdx (targetMarkBeforeBinds, targetMarkAfterBinds, eenvAtTarget, successExpr, spTarget, repeatSP, vs, binds, startScope, endScope) sequel = +and GenDecisionTreeTarget cenv cgbuf stackAtTargets (targetMarkBeforeBinds, targetMarkAfterBinds, eenvAtTarget, successExpr, spTarget, repeatSP, vs, binds, startScope, endScope) sequel = CG.SetMarkToHere cgbuf targetMarkBeforeBinds - let spExpr = (match spTarget with SequencePointAtTarget -> SPAlways | SuppressSequencePointAtTarget _ -> SPSuppress) + let spExpr = (match spTarget with DebugPointForTarget.Yes -> SPAlways | DebugPointForTarget.No _ -> SPSuppress) // Repeat the sequence point to make sure each target branch has some sequence point (instead of inheriting // a random sequence point from the previously generated IL code from the previous block. See comment on @@ -4827,21 +5001,21 @@ and GenDecisionTreeTarget cenv cgbuf stackAtTargets _targetIdx (targetMarkBefore // // Only repeat the sequence point if we really have to, i.e. if the target expression doesn't start with a // sequence point anyway - if isNil vs && DoesGenExprStartWithSequencePoint cenv.g spExpr successExpr then + if isNil vs && DoesGenExprStartWithDebugPoint cenv.g spExpr successExpr then () else match spTarget with - | SequencePointAtTarget -> repeatSP() - | SuppressSequencePointAtTarget -> cgbuf.EmitStartOfHiddenCode() + | DebugPointForTarget.Yes -> repeatSP() + | DebugPointForTarget.No -> cgbuf.EmitStartOfHiddenCode() CG.SetMarkToHere cgbuf startScope GenBindings cenv cgbuf eenvAtTarget binds CG.SetMarkToHere cgbuf targetMarkAfterBinds CG.SetStack cgbuf stackAtTargets - GenExpr cenv cgbuf eenvAtTarget spExpr successExpr (EndLocalScope(sequel, endScope)) + (eenvAtTarget, spExpr, successExpr, (EndLocalScope(sequel, endScope))) - -and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defaultTargetOpt switchm targets repeatSP targetInfos sequel = +and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defaultTargetOpt switchm targets repeatSP targetInfos sequel contf = + let g = cenv.g let m = e.Range match inplabOpt with None -> () | Some inplab -> CG.SetMarkToHere cgbuf inplab @@ -4850,12 +5024,12 @@ and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defau // optimize a test against a boolean value, i.e. the all-important if-then-else | TCase(DecisionTreeTest.Const(Const.Bool b), successTree) :: _ -> let failureTree = (match defaultTargetOpt with None -> cases.Tail.Head.CaseTree | Some d -> d) - GenDecisionTreeTest cenv eenv.cloc cgbuf stackAtTargets e None eenv (if b then successTree else failureTree) (if b then failureTree else successTree) targets repeatSP targetInfos sequel + GenDecisionTreeTest cenv eenv.cloc cgbuf stackAtTargets e None eenv (if b then successTree else failureTree) (if b then failureTree else successTree) targets repeatSP targetInfos sequel contf // // Remove a single test for a union case . Union case tests are always exa //| [ TCase(DecisionTreeTest.UnionCase _, successTree) ] when (defaultTargetOpt.IsNone) -> // GenDecisionTreeAndTargetsInner cenv cgbuf inplabOpt stackAtTargets eenv successTree targets repeatSP targetInfos sequel - // //GenDecisionTree cenv eenv.cloc cgbuf stackAtTargets e (Some (pop 1, Push [cenv.g.ilg.typ_Bool], Choice1Of2 (avoidHelpers, cuspec, idx))) eenv successTree failureTree targets repeatSP targetInfos sequel + // //GenDecisionTree cenv eenv.cloc cgbuf stackAtTargets e (Some (pop 1, Push [g.ilg.typ_Bool], Choice1Of2 (avoidHelpers, cuspec, idx))) eenv successTree failureTree targets repeatSP targetInfos sequel // Optimize a single test for a union case to an "isdata" test - much // more efficient code, and this case occurs in the generated equality testers where perf is important @@ -4866,8 +5040,8 @@ and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defau | Some tg -> tg let cuspec = GenUnionSpec cenv.amap m eenv.tyenv c.TyconRef tyargs let idx = c.Index - let avoidHelpers = entityRefInThisAssembly cenv.g.compilingFslib c.TyconRef - GenDecisionTreeTest cenv eenv.cloc cgbuf stackAtTargets e (Some (pop 1, Push [cenv.g.ilg.typ_Bool], Choice1Of2 (avoidHelpers, cuspec, idx))) eenv successTree failureTree targets repeatSP targetInfos sequel + let avoidHelpers = entityRefInThisAssembly g.compilingFslib c.TyconRef + GenDecisionTreeTest cenv eenv.cloc cgbuf stackAtTargets e (Some (pop 1, Push [g.ilg.typ_Bool], Choice1Of2 (avoidHelpers, cuspec, idx))) eenv successTree failureTree targets repeatSP targetInfos sequel contf | _ -> let caseLabels = List.map (fun _ -> CG.GenerateDelayMark cgbuf "switch_case") cases @@ -4887,18 +5061,18 @@ and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defau BI_brfalse | DecisionTreeTest.IsNull -> GenExpr cenv cgbuf eenv SPSuppress e Continue - let srcTy = tyOfExpr cenv.g e - if isTyparTy cenv.g srcTy then + let srcTy = tyOfExpr g e + if isTyparTy g srcTy then let ilFromTy = GenType cenv.amap m eenv.tyenv srcTy - CG.EmitInstr cgbuf (pop 1) (Push [cenv.g.ilg.typ_Object]) (I_box ilFromTy) + CG.EmitInstr cgbuf (pop 1) (Push [g.ilg.typ_Object]) (I_box ilFromTy) BI_brfalse | DecisionTreeTest.IsInst (_srcty, tgty) -> - let e = mkCallTypeTest cenv.g m tgty e + let e = mkCallTypeTest g m tgty e GenExpr cenv cgbuf eenv SPSuppress e Continue BI_brtrue | _ -> failwith "internal error: GenDecisionTreeSwitch" CG.EmitInstr cgbuf (pop 1) Push0 (I_brcmp (bi, (List.head caseLabels).CodeLabel)) - GenDecisionTreeCases cenv cgbuf stackAtTargets eenv targets repeatSP targetInfos defaultTargetOpt caseLabels cases sequel + GenDecisionTreeCases cenv cgbuf stackAtTargets eenv defaultTargetOpt targets repeatSP targetInfos sequel caseLabels cases contf | DecisionTreeTest.ActivePatternCase _ -> error(InternalError("internal error in codegen: DecisionTreeTest.ActivePatternCase", switchm)) | DecisionTreeTest.UnionCase (hdc, tyargs) -> @@ -4911,10 +5085,10 @@ and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defau | TCase(DecisionTreeTest.UnionCase (c, _), _) -> (c.Index, label.CodeLabel) | _ -> failwith "error: mixed constructor/const test?") - let avoidHelpers = entityRefInThisAssembly cenv.g.compilingFslib hdc.TyconRef - EraseUnions.emitDataSwitch cenv.g.ilg (UnionCodeGen cgbuf) (avoidHelpers, cuspec, dests) + let avoidHelpers = entityRefInThisAssembly g.compilingFslib hdc.TyconRef + EraseUnions.emitDataSwitch g.ilg (UnionCodeGen cgbuf) (avoidHelpers, cuspec, dests) CG.EmitInstrs cgbuf (pop 1) Push0 [ ] // push/pop to match the line above - GenDecisionTreeCases cenv cgbuf stackAtTargets eenv targets repeatSP targetInfos defaultTargetOpt caseLabels cases sequel + GenDecisionTreeCases cenv cgbuf stackAtTargets eenv defaultTargetOpt targets repeatSP targetInfos sequel caseLabels cases contf | DecisionTreeTest.Const c -> GenExpr cenv cgbuf eenv SPSuppress e Continue @@ -4952,32 +5126,36 @@ and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defau if mx - mn = (List.length dests - 1) then let destinationLabels = dests |> List.sortBy fst |> List.map snd if mn <> 0 then - CG.EmitInstrs cgbuf (pop 0) (Push [cenv.g.ilg.typ_Int32]) [ mkLdcInt32 mn] + CG.EmitInstrs cgbuf (pop 0) (Push [g.ilg.typ_Int32]) [ mkLdcInt32 mn] CG.EmitInstrs cgbuf (pop 1) Push0 [ AI_sub ] CG.EmitInstr cgbuf (pop 1) Push0 (I_switch destinationLabels) else error(InternalError("non-dense integer matches not implemented in codegen - these should have been removed by the pattern match compiler", switchm)) - GenDecisionTreeCases cenv cgbuf stackAtTargets eenv targets repeatSP targetInfos defaultTargetOpt caseLabels cases sequel + GenDecisionTreeCases cenv cgbuf stackAtTargets eenv defaultTargetOpt targets repeatSP targetInfos sequel caseLabels cases contf | _ -> error(InternalError("these matches should never be needed", switchm)) + | DecisionTreeTest.Error m -> error(InternalError("Trying to compile error recovery branch", m)) -and GenDecisionTreeCases cenv cgbuf stackAtTargets eenv targets repeatSP targetInfos defaultTargetOpt caseLabels cases sequel = - assert(cgbuf.GetCurrentStack() = stackAtTargets) // cgbuf stack should be unchanged over tests. [bug://1750]. - - let targetInfos = - match defaultTargetOpt with - | Some defaultTarget -> GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv defaultTarget targets repeatSP targetInfos sequel - | None -> targetInfos +and GenDecisionTreeCases cenv cgbuf stackAtTargets eenv defaultTargetOpt targets repeatSP targetInfos sequel caseLabels cases (contf: Zmap<_,_> -> FakeUnit) = - let targetInfos = - (targetInfos, caseLabels, cases) |||> List.fold2 (fun targetInfos caseLabel (TCase(_, caseTree)) -> - GenDecisionTreeAndTargetsInner cenv cgbuf (Some caseLabel) stackAtTargets eenv caseTree targets repeatSP targetInfos sequel) - targetInfos + match defaultTargetOpt with + | Some defaultTarget -> + GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv defaultTarget targets repeatSP targetInfos sequel (fun targetInfos -> + GenDecisionTreeCases cenv cgbuf stackAtTargets eenv None targets repeatSP targetInfos sequel caseLabels cases contf + ) + | None -> + match caseLabels, cases with + | caseLabel :: caseLabelsTail, (TCase(_, caseTree)) :: casesTail -> + GenDecisionTreeAndTargetsInner cenv cgbuf (Some caseLabel) stackAtTargets eenv caseTree targets repeatSP targetInfos sequel (fun targetInfos -> + GenDecisionTreeCases cenv cgbuf stackAtTargets eenv None targets repeatSP targetInfos sequel caseLabelsTail casesTail contf + ) + | _ -> + contf targetInfos // Used for the peephole optimization below -and (|BoolExpr|_|) = function Expr.Const(Const.Bool b1, _, _) -> Some(b1) | _ -> None - -and GenDecisionTreeTest cenv cloc cgbuf stackAtTargets e tester eenv successTree failureTree targets repeatSP targetInfos sequel = +and (|BoolExpr|_|) = function Expr.Const (Const.Bool b1, _, _) -> Some b1 | _ -> None +and GenDecisionTreeTest cenv cloc cgbuf stackAtTargets e tester eenv successTree failureTree targets repeatSP targetInfos sequel contf = + let g = cenv.g match successTree, failureTree with // Peephole: if generating a boolean value or its negation then just leave it on the stack @@ -4986,24 +5164,24 @@ and GenDecisionTreeTest cenv cloc cgbuf stackAtTargets e tester eenv successTree TDSuccess(es2, n2) when isNil es1 && isNil es2 && (match GetTarget targets n1, GetTarget targets n2 with - | TTarget(_, BoolExpr(b1), _), TTarget(_, BoolExpr(b2), _) -> b1 = not b2 + | TTarget(_, BoolExpr b1, _), TTarget(_, BoolExpr b2, _) -> b1 = not b2 | _ -> false) -> match GetTarget targets n1, GetTarget targets n2 with - | TTarget(_, BoolExpr(b1), _), _ -> + | TTarget(_, BoolExpr b1, _), _ -> GenExpr cenv cgbuf eenv SPSuppress e Continue match tester with | Some (pops, pushes, i) -> match i with - | Choice1Of2 (avoidHelpers, cuspec, idx) -> CG.EmitInstrs cgbuf pops pushes (EraseUnions.mkIsData cenv.g.ilg (avoidHelpers, cuspec, idx)) + | Choice1Of2 (avoidHelpers, cuspec, idx) -> CG.EmitInstrs cgbuf pops pushes (EraseUnions.mkIsData g.ilg (avoidHelpers, cuspec, idx)) | Choice2Of2 i -> CG.EmitInstr cgbuf pops pushes i | _ -> () if not b1 then - CG.EmitInstrs cgbuf (pop 0) (Push [cenv.g.ilg.typ_Bool]) [mkLdcInt32 (0) ] + CG.EmitInstrs cgbuf (pop 0) (Push [g.ilg.typ_Bool]) [mkLdcInt32 0 ] CG.EmitInstrs cgbuf (pop 1) Push0 [AI_ceq] GenSequel cenv cloc cgbuf sequel - targetInfos + contf targetInfos | _ -> failwith "internal error: GenDecisionTreeTest during bool elim" @@ -5016,18 +5194,18 @@ and GenDecisionTreeTest cenv cloc cgbuf stackAtTargets e tester eenv successTree // Turn 'isdata' tests that branch into EI_brisdata tests | Some (_, _, Choice1Of2 (avoidHelpers, cuspec, idx)) -> - GenExpr cenv cgbuf eenv SPSuppress e (CmpThenBrOrContinue(pop 1, EraseUnions.mkBrIsData cenv.g.ilg false (avoidHelpers, cuspec, idx, failure.CodeLabel))) + GenExpr cenv cgbuf eenv SPSuppress e (CmpThenBrOrContinue(pop 1, EraseUnions.mkBrIsData g.ilg false (avoidHelpers, cuspec, idx, failure.CodeLabel))) | Some (pops, pushes, i) -> GenExpr cenv cgbuf eenv SPSuppress e Continue match i with - | Choice1Of2 (avoidHelpers, cuspec, idx) -> CG.EmitInstrs cgbuf pops pushes (EraseUnions.mkIsData cenv.g.ilg (avoidHelpers, cuspec, idx)) + | Choice1Of2 (avoidHelpers, cuspec, idx) -> CG.EmitInstrs cgbuf pops pushes (EraseUnions.mkIsData g.ilg (avoidHelpers, cuspec, idx)) | Choice2Of2 i -> CG.EmitInstr cgbuf pops pushes i CG.EmitInstr cgbuf (pop 1) Push0 (I_brcmp (BI_brfalse, failure.CodeLabel)) - let targetInfos = GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv successTree targets repeatSP targetInfos sequel - - GenDecisionTreeAndTargetsInner cenv cgbuf (Some failure) stackAtTargets eenv failureTree targets repeatSP targetInfos sequel + GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv successTree targets repeatSP targetInfos sequel (fun targetInfos -> + GenDecisionTreeAndTargetsInner cenv cgbuf (Some failure) stackAtTargets eenv failureTree targets repeatSP targetInfos sequel contf + ) /// Generate fixups for letrec bindings and GenLetRecFixup cenv cgbuf eenv (ilxCloSpec: IlxClosureSpec, e, ilField: ILFieldSpec, e2, _m) = @@ -5038,10 +5216,11 @@ and GenLetRecFixup cenv cgbuf eenv (ilxCloSpec: IlxClosureSpec, e, ilField: ILFi /// Generate letrec bindings and GenLetRecBindings cenv (cgbuf: CodeGenBuffer) eenv (allBinds: Bindings, m) = + let eenv = SetIsInLoop true eenv // Fix up recursion for non-toplevel recursive bindings let bindsPossiblyRequiringFixup = allBinds |> List.filter (fun b -> - match (StorageForVal m b.Var eenv) with + match (StorageForVal cenv.g m b.Var eenv) with | StaticProperty _ | Method _ // Note: Recursive data stored in static fields may require fixups e.g. let x = C(x) @@ -5049,15 +5228,15 @@ and GenLetRecBindings cenv (cgbuf: CodeGenBuffer) eenv (allBinds: Bindings, m) = | Null -> false | _ -> true) - let computeFixupsForOneRecursiveVar boundv forwardReferenceSet fixups selfv access set e = + let computeFixupsForOneRecursiveVar boundv forwardReferenceSet fixups thisVars access set e = match e with | Expr.Lambda _ | Expr.TyLambda _ | Expr.Obj _ -> - let isLocalTypeFunc = Option.isSome selfv && (IsNamedLocalTypeFuncVal cenv.g (Option.get selfv) e) - let selfv = (match e with Expr.Obj _ -> None | _ when isLocalTypeFunc -> None | _ -> Option.map mkLocalValRef selfv) - let clo, _, eenvclo = GetIlxClosureInfo cenv m isLocalTypeFunc selfv {eenv with letBoundVars=(mkLocalValRef boundv)::eenv.letBoundVars} e + let isLocalTypeFunc = Option.isSome thisVars && (IsNamedLocalTypeFuncVal cenv.g (Option.get thisVars) e) + let thisVars = (match e with Expr.Obj _ -> [] | _ when isLocalTypeFunc -> [] | _ -> Option.map mkLocalValRef thisVars |> Option.toList) + let clo, _, eenvclo = GetIlxClosureInfo cenv m isLocalTypeFunc thisVars {eenv with letBoundVars=(mkLocalValRef boundv) :: eenv.letBoundVars} e clo.cloFreeVars |> List.iter (fun fv -> if Zset.contains fv forwardReferenceSet then - match StorageForVal m fv eenvclo with + match StorageForVal cenv.g m fv eenvclo with | Env (_, _, ilField, _) -> fixups := (boundv, fv, (fun () -> GenLetRecFixup cenv cgbuf eenv (clo.cloSpec, access, ilField, exprForVal m fv, m))) :: !fixups | _ -> error (InternalError("GenLetRec: " + fv.LogicalName + " was not in the environment", m)) ) @@ -5102,14 +5281,14 @@ and GenLetRec cenv cgbuf eenv (binds, body, m) sequel = // Generate simple bindings //------------------------------------------------------------------------- -and GenSequencePointForBind cenv cgbuf bind = - let _, pt, sp = ComputeSequencePointInfoForBinding cenv.g bind +and GenDebugPointForBind cenv cgbuf bind = + let _, pt, sp = ComputeDebugPointForBinding cenv.g bind pt |> Option.iter (CG.EmitSeqPoint cgbuf) sp and GenBinding cenv cgbuf eenv bind = - let sp = GenSequencePointForBind cenv cgbuf bind - GenBindingAfterSequencePoint cenv cgbuf eenv sp bind None + let sp = GenDebugPointForBind cenv cgbuf bind + GenBindingAfterDebugPoint cenv cgbuf eenv sp bind None and ComputeMemberAccessRestrictedBySig eenv vspec = let isHidden = @@ -5125,7 +5304,8 @@ and ComputeMethodAccessRestrictedBySig eenv vspec = vspec.IsIncrClassGeneratedMember // compiler generated members for class function 'let' bindings get assembly visibility ComputeMemberAccess isHidden -and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec, rhsExpr, _)) startScopeMarkOpt = +and GenBindingAfterDebugPoint cenv cgbuf eenv sp (TBind(vspec, rhsExpr, _)) startScopeMarkOpt = + let g = cenv.g // Record the closed reflection definition if publishing // There is no real reason we're doing this so late in the day @@ -5147,7 +5327,7 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec, rhsExpr, _)) s let m = vspec.Range - match StorageForVal m vspec eenv with + match StorageForVal cenv.g m vspec eenv with | Null -> GenExpr cenv cgbuf eenv SPSuppress rhsExpr discard @@ -5155,16 +5335,23 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec, rhsExpr, _)) s // The initialization code for static 'let' and 'do' bindings gets compiled into the initialization .cctor for the whole file | _ when vspec.IsClassConstructor && isNil vspec.TopValDeclaringEntity.TyparsNoRange -> - let tps, _, _, _, cctorBody, _ = IteratedAdjustArityOfLambda cenv.g cenv.amap vspec.ValReprInfo.Value rhsExpr + let tps, _, _, _, cctorBody, _ = IteratedAdjustArityOfLambda g cenv.amap vspec.ValReprInfo.Value rhsExpr let eenv = EnvForTypars tps eenv CommitStartScope cgbuf startScopeMarkOpt GenExpr cenv cgbuf eenv SPSuppress cctorBody discard | Method (topValInfo, _, mspec, _, paramInfos, methodArgTys, retInfo) -> - let tps, ctorThisValOpt, baseValOpt, vsl, body', bodyty = IteratedAdjustArityOfLambda cenv.g cenv.amap topValInfo rhsExpr + let tps, ctorThisValOpt, baseValOpt, vsl, body', bodyty = IteratedAdjustArityOfLambda g cenv.amap topValInfo rhsExpr let methodVars = List.concat vsl CommitStartScope cgbuf startScopeMarkOpt - GenMethodForBinding cenv cgbuf eenv (vspec, mspec, access, paramInfos, retInfo) (topValInfo, ctorThisValOpt, baseValOpt, tps, methodVars, methodArgTys, body', bodyty) + + let ilxMethInfoArgs = + (vspec, mspec, access, paramInfos, retInfo, topValInfo, ctorThisValOpt, baseValOpt, tps, methodVars, methodArgTys, body', bodyty) + // if we have any expression recursion depth, we should delay the generation of a method to prevent stack overflows + if cenv.exprRecursionDepth > 0 then + DelayGenMethodForBinding cenv cgbuf.mgbuf eenv ilxMethInfoArgs + else + GenMethodForBinding cenv cgbuf.mgbuf eenv ilxMethInfoArgs | StaticProperty (ilGetterMethSpec, optShadowLocal) -> @@ -5185,7 +5372,7 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec, rhsExpr, _)) s let ilMethodDef = let ilMethodBody = MethodBody.IL(CodeGenMethodForExpr cenv cgbuf.mgbuf (SPSuppress, [], ilGetterMethSpec.Name, eenv, 0, rhsExpr, Return)) (mkILStaticMethod ([], ilGetterMethSpec.Name, access, [], mkILReturn ilTy, ilMethodBody)).WithSpecialName - |> AddNonUserCompilerGeneratedAttribs cenv.g + |> AddNonUserCompilerGeneratedAttribs g CountMethodDef() cgbuf.mgbuf.AddMethodDef(ilGetterMethSpec.MethodRef.DeclaringTypeRef, ilMethodDef) @@ -5226,7 +5413,7 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec, rhsExpr, _)) s else GenAttrs cenv eenv vspec.Attribs // literals have no property, so preserve all the attributes on the field itself - let ilFieldDef = ilFieldDef.With(customAttrs = mkILCustomAttrs (ilAttribs @ [ cenv.g.DebuggerBrowsableNeverAttribute ])) + let ilFieldDef = ilFieldDef.With(customAttrs = mkILCustomAttrs (ilAttribs @ [ g.DebuggerBrowsableNeverAttribute ])) [ (fspec.DeclaringTypeRef, ilFieldDef) ] @@ -5251,7 +5438,7 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec, rhsExpr, _)) s propertyType=fty, init=None, args = [], - customAttrs=mkILCustomAttrs (ilAttribs @ [mkCompilationMappingAttr cenv.g (int SourceConstructFlags.Value)])) + customAttrs=mkILCustomAttrs (ilAttribs @ [mkCompilationMappingAttr g (int SourceConstructFlags.Value)])) cgbuf.mgbuf.AddOrMergePropertyDef(ilTypeRefForProperty, ilPropDef, m) let getterMethod = @@ -5276,15 +5463,15 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec, rhsExpr, _)) s GenSetStorage m cgbuf storage | _ -> - let storage = StorageForVal m vspec eenv + let storage = StorageForVal cenv.g m vspec eenv match storage, rhsExpr with - // locals are zero-init, no need to initialize them - | Local (_, realloc, _), Expr.Const(Const.Zero, _, _) when not realloc -> + // locals are zero-init, no need to initialize them, except if you are in a loop and the local is mutable. + | Local (_, realloc, _), Expr.Const (Const.Zero, _, _) when not realloc && not (eenv.isInLoop && vspec.IsMutable) -> CommitStartScope cgbuf startScopeMarkOpt | _ -> GenBindingRhs cenv cgbuf eenv SPSuppress vspec rhsExpr CommitStartScope cgbuf startScopeMarkOpt - GenStoreVal cgbuf eenv vspec.Range vspec + GenStoreVal cenv cgbuf eenv vspec.Range vspec //------------------------------------------------------------------------- // Generate method bindings @@ -5292,6 +5479,7 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec, rhsExpr, _)) s /// Generate encoding P/Invoke and COM marshalling information and GenMarshal cenv attribs = + let g = cenv.g let otherAttribs = // For IlReflect backend, we rely on Reflection.Emit API to emit the pseudo-custom attributes // correctly, so we do not filter them out. @@ -5299,9 +5487,9 @@ and GenMarshal cenv attribs = match cenv.opts.ilxBackend with | IlReflectBackend -> attribs | IlWriteBackend -> - attribs |> List.filter (IsMatchingFSharpAttributeOpt cenv.g cenv.g.attrib_MarshalAsAttribute >> not) + attribs |> List.filter (IsMatchingFSharpAttributeOpt g g.attrib_MarshalAsAttribute >> not) - match TryFindFSharpAttributeOpt cenv.g cenv.g.attrib_MarshalAsAttribute attribs with + match TryFindFSharpAttributeOpt g g.attrib_MarshalAsAttribute attribs with | Some (Attrib(_, _, [ AttribInt32Arg unmanagedType ], namedArgs, _, _, m)) -> let decoder = AttributeDecoder namedArgs let rec decodeUnmanagedType unmanagedType = @@ -5380,7 +5568,7 @@ and GenMarshal cenv attribs = // the argument is a System.Type obj, but it's written to MD as a UTF8 string match decoder.FindTypeName "SafeArrayUserDefinedSubType" "" with | "" -> None - | res -> if (safeArraySubType = ILNativeVariant.IDispatch) || (safeArraySubType = ILNativeVariant.IUnknown) then Some(res) else None + | res -> if (safeArraySubType = ILNativeVariant.IDispatch) || (safeArraySubType = ILNativeVariant.IUnknown) then Some res else None ILNativeType.SafeArray(safeArraySubType, safeArrayUserDefinedSubType) | 0x1E -> ILNativeType.FixedArray (decoder.FindInt32 "SizeConst" 0x0) | 0x1F -> ILNativeType.Int @@ -5419,26 +5607,28 @@ and GenMarshal cenv attribs = /// Generate special attributes on an IL parameter and GenParamAttribs cenv paramTy attribs = - let inFlag = HasFSharpAttribute cenv.g cenv.g.attrib_InAttribute attribs || isInByrefTy cenv.g paramTy - let outFlag = HasFSharpAttribute cenv.g cenv.g.attrib_OutAttribute attribs || isOutByrefTy cenv.g paramTy - let optionalFlag = HasFSharpAttributeOpt cenv.g cenv.g.attrib_OptionalAttribute attribs + let g = cenv.g + let inFlag = HasFSharpAttribute g g.attrib_InAttribute attribs || isInByrefTy g paramTy + let outFlag = HasFSharpAttribute g g.attrib_OutAttribute attribs || isOutByrefTy g paramTy + let optionalFlag = HasFSharpAttributeOpt g g.attrib_OptionalAttribute attribs - let defaultValue = TryFindFSharpAttributeOpt cenv.g cenv.g.attrib_DefaultParameterValueAttribute attribs + let defaultValue = TryFindFSharpAttributeOpt g g.attrib_DefaultParameterValueAttribute attribs |> Option.bind OptionalArgInfo.FieldInitForDefaultParameterValueAttrib // Return the filtered attributes. Do not generate In, Out, Optional or DefaultParameterValue attributes // as custom attributes in the code - they are implicit from the IL bits for these let attribs = attribs - |> List.filter (IsMatchingFSharpAttribute cenv.g cenv.g.attrib_InAttribute >> not) - |> List.filter (IsMatchingFSharpAttribute cenv.g cenv.g.attrib_OutAttribute >> not) - |> List.filter (IsMatchingFSharpAttributeOpt cenv.g cenv.g.attrib_OptionalAttribute >> not) - |> List.filter (IsMatchingFSharpAttributeOpt cenv.g cenv.g.attrib_DefaultParameterValueAttribute >> not) + |> List.filter (IsMatchingFSharpAttribute g g.attrib_InAttribute >> not) + |> List.filter (IsMatchingFSharpAttribute g g.attrib_OutAttribute >> not) + |> List.filter (IsMatchingFSharpAttributeOpt g g.attrib_OptionalAttribute >> not) + |> List.filter (IsMatchingFSharpAttributeOpt g g.attrib_DefaultParameterValueAttribute >> not) let Marshal, attribs = GenMarshal cenv attribs inFlag, outFlag, optionalFlag, defaultValue, Marshal, attribs /// Generate IL parameters and GenParams cenv eenv (mspec: ILMethodSpec) (attribs: ArgReprInfo list) methodArgTys (implValsOpt: Val list option) = + let g = cenv.g let ilArgTys = mspec.FormalArgTypes let argInfosAndTypes = if List.length attribs = List.length ilArgTys then List.zip ilArgTys attribs @@ -5446,7 +5636,7 @@ and GenParams cenv eenv (mspec: ILMethodSpec) (attribs: ArgReprInfo list) method let argInfosAndTypes = match implValsOpt with - | Some(implVals) when (implVals.Length = ilArgTys.Length) -> + | Some implVals when (implVals.Length = ilArgTys.Length) -> List.map2 (fun x y -> x, Some y) argInfosAndTypes implVals | _ -> List.map (fun x -> x, None) argInfosAndTypes @@ -5454,7 +5644,7 @@ and GenParams cenv eenv (mspec: ILMethodSpec) (attribs: ArgReprInfo list) method (Set.empty, List.zip methodArgTys argInfosAndTypes) ||> List.mapFold (fun takenNames (methodArgTy, ((ilArgTy, topArgInfo), implValOpt)) -> let inFlag, outFlag, optionalFlag, defaultParamValue, Marshal, attribs = GenParamAttribs cenv methodArgTy topArgInfo.Attribs - + let idOpt = (match topArgInfo.Name with | Some v -> Some v | None -> match implValOpt with @@ -5464,16 +5654,21 @@ and GenParams cenv eenv (mspec: ILMethodSpec) (attribs: ArgReprInfo list) method let nmOpt, takenNames = match idOpt with | Some id -> - let nm = if takenNames.Contains(id.idText) then globalNng.FreshCompilerGeneratedName (id.idText, id.idRange) else id.idText - Some nm, takenNames.Add(nm) + let nm = + if takenNames.Contains(id.idText) then + // Ensure that we have an g.CompilerGlobalState + assert(g.CompilerGlobalState |> Option.isSome) + g.CompilerGlobalState.Value.NiceNameGenerator.FreshCompilerGeneratedName (id.idText, id.idRange) + else + id.idText + Some nm, takenNames.Add nm | None -> None, takenNames - let ilAttribs = GenAttrs cenv eenv attribs - + let ilAttribs = - match GenReadOnlyAttributeIfNecessary cenv.g methodArgTy with + match GenReadOnlyAttributeIfNecessary g methodArgTy with | Some attr -> ilAttribs @ [attr] | None -> ilAttribs @@ -5531,31 +5726,32 @@ and GenEventForProperty cenv eenvForMeth (mspec: ILMethodSpec) (v: Val) ilAttrsT customAttrs = mkILCustomAttrs ilAttrsThatGoOnPrimaryItem) and ComputeFlagFixupsForMemberBinding cenv (v: Val, memberInfo: ValMemberInfo) = + let g = cenv.g if isNil memberInfo.ImplementedSlotSigs then [fixupVirtualSlotFlags] else memberInfo.ImplementedSlotSigs |> List.map (fun slotsig -> let oty = slotsig.ImplementedType - let otcref = tcrefOfAppTy cenv.g oty + let otcref = tcrefOfAppTy g oty let tcref = v.MemberApparentEntity let useMethodImpl = // REVIEW: it would be good to get rid of this special casing of Compare and GetHashCode during code generation - isInterfaceTy cenv.g oty && + isInterfaceTy g oty && (let isCompare = Option.isSome tcref.GeneratedCompareToValues && - (typeEquiv cenv.g oty cenv.g.mk_IComparable_ty || - tyconRefEq cenv.g cenv.g.system_GenericIComparable_tcref otcref) + (typeEquiv g oty g.mk_IComparable_ty || + tyconRefEq g g.system_GenericIComparable_tcref otcref) not isCompare) && (let isGenericEquals = - Option.isSome tcref.GeneratedHashAndEqualsWithComparerValues && tyconRefEq cenv.g cenv.g.system_GenericIEquatable_tcref otcref + Option.isSome tcref.GeneratedHashAndEqualsWithComparerValues && tyconRefEq g g.system_GenericIEquatable_tcref otcref not isGenericEquals) && (let isStructural = - (Option.isSome tcref.GeneratedCompareToWithComparerValues && typeEquiv cenv.g oty cenv.g.mk_IStructuralComparable_ty) || - (Option.isSome tcref.GeneratedHashAndEqualsWithComparerValues && typeEquiv cenv.g oty cenv.g.mk_IStructuralEquatable_ty) + (Option.isSome tcref.GeneratedCompareToWithComparerValues && typeEquiv g oty g.mk_IStructuralComparable_ty) || + (Option.isSome tcref.GeneratedHashAndEqualsWithComparerValues && typeEquiv g oty g.mk_IStructuralEquatable_ty) not isStructural) @@ -5567,13 +5763,14 @@ and ComputeFlagFixupsForMemberBinding cenv (v: Val, memberInfo: ValMemberInfo) = fixupVirtualSlotFlags >> renameMethodDef nameOfOverridingMethod) and ComputeMethodImplAttribs cenv (_v: Val) attrs = + let g = cenv.g let implflags = - match TryFindFSharpAttribute cenv.g cenv.g.attrib_MethodImplAttribute attrs with + match TryFindFSharpAttribute g g.attrib_MethodImplAttribute attrs with | Some (Attrib(_, _, [ AttribInt32Arg flags ], _, _, _, _)) -> flags | _ -> 0x0 let hasPreserveSigAttr = - match TryFindFSharpAttributeOpt cenv.g cenv.g.attrib_PreserveSigAttribute attrs with + match TryFindFSharpAttributeOpt g g.attrib_PreserveSigAttribute attrs with | Some _ -> true | _ -> false @@ -5584,8 +5781,8 @@ and ComputeMethodImplAttribs cenv (_v: Val) attrs = // (See ECMA 335, Partition II, section 23.1.11 - Flags for methods [MethodImplAttributes]) let attrs = attrs - |> List.filter (IsMatchingFSharpAttribute cenv.g cenv.g.attrib_MethodImplAttribute >> not) - |> List.filter (IsMatchingFSharpAttributeOpt cenv.g cenv.g.attrib_PreserveSigAttribute >> not) + |> List.filter (IsMatchingFSharpAttribute g g.attrib_MethodImplAttribute >> not) + |> List.filter (IsMatchingFSharpAttributeOpt g g.attrib_PreserveSigAttribute >> not) let hasPreserveSigImplFlag = ((implflags &&& 0x80) <> 0x0) || hasPreserveSigAttr let hasSynchronizedImplFlag = (implflags &&& 0x20) <> 0x0 @@ -5593,23 +5790,23 @@ and ComputeMethodImplAttribs cenv (_v: Val) attrs = let hasAggressiveInliningImplFlag = (implflags &&& 0x0100) <> 0x0 hasPreserveSigImplFlag, hasSynchronizedImplFlag, hasNoInliningImplFlag, hasAggressiveInliningImplFlag, attrs -and GenMethodForBinding - cenv cgbuf eenv - (v: Val, mspec, access, paramInfos, retInfo) - (topValInfo, ctorThisValOpt, baseValOpt, tps, methodVars, methodArgTys, body, returnTy) = +and DelayGenMethodForBinding cenv mgbuf eenv ilxMethInfoArgs = + cenv.delayedGenMethods.Enqueue (fun cenv -> GenMethodForBinding cenv mgbuf eenv ilxMethInfoArgs) +and GenMethodForBinding cenv mgbuf eenv (v, mspec, access, paramInfos, retInfo, topValInfo, ctorThisValOpt, baseValOpt, tps, methodVars, methodArgTys, body, returnTy) = + let g = cenv.g let m = v.Range let selfMethodVars, nonSelfMethodVars, compileAsInstance = match v.MemberInfo with - | Some _ when ValSpecIsCompiledAsInstance cenv.g v -> + | Some _ when ValSpecIsCompiledAsInstance g v -> match methodVars with | [] -> error(InternalError("Internal error: empty argument list for instance method", v.Range)) - | h::t -> [h], t, true + | h :: t -> [h], t, true | _ -> [], methodVars, false - let nonUnitNonSelfMethodVars, body = BindUnitVars cenv.g (nonSelfMethodVars, paramInfos, body) + let nonUnitNonSelfMethodVars, body = BindUnitVars g (nonSelfMethodVars, paramInfos, body) let nonUnitMethodVars = selfMethodVars@nonUnitNonSelfMethodVars - let cmtps, curriedArgInfos, _, _ = GetTopValTypeInCompiledForm cenv.g topValInfo v.Type v.Range + let cmtps, curriedArgInfos, _, _ = GetTopValTypeInCompiledForm g topValInfo v.Type v.Range let eenv = bindBaseOrThisVarOpt cenv eenv ctorThisValOpt let eenv = bindBaseOrThisVarOpt cenv eenv baseValOpt @@ -5624,23 +5821,23 @@ and GenMethodForBinding let eenvForMeth = let eenvForMeth = eenvUnderMethLambdaTypars let numImplicitArgs = if isCtor then 1 else 0 - let eenvForMeth = AddStorageForLocalVals cenv.g (List.mapi (fun i v -> (v, Arg (numImplicitArgs+i))) nonUnitMethodVars) eenvForMeth + let eenvForMeth = AddStorageForLocalVals g (List.mapi (fun i v -> (v, Arg (numImplicitArgs+i))) nonUnitMethodVars) eenvForMeth eenvForMeth let tailCallInfo = [(mkLocalValRef v, BranchCallMethod (topValInfo.AritiesOfArgs, curriedArgInfos, tps, nonUnitMethodVars.Length, v.NumObjArgs))] // Discard the result on a 'void' return type. For a constructor just return 'void' let sequel = - if isUnitTy cenv.g returnTy then discardAndReturnVoid + if isUnitTy g returnTy then discardAndReturnVoid elif isCtor then ReturnVoid else Return // Now generate the code. let hasPreserveSigNamedArg, ilMethodBody, hasDllImport = - match TryFindFSharpAttributeOpt cenv.g cenv.g.attrib_DllImportAttribute v.Attribs with - | Some (Attrib(_, _, [ AttribStringArg(dll) ], namedArgs, _, _, m)) -> + match TryFindFSharpAttributeOpt g g.attrib_DllImportAttribute v.Attribs with + | Some (Attrib(_, _, [ AttribStringArg dll ], namedArgs, _, _, m)) -> if not (isNil tps) then error(Error(FSComp.SR.ilSignatureForExternalFunctionContainsTypeParameters(), m)) - let hasPreserveSigNamedArg, mbody = GenPInvokeMethod (v.CompiledName, dll, namedArgs) + let hasPreserveSigNamedArg, mbody = GenPInvokeMethod (v.CompiledName g.CompilerGlobalState, dll, namedArgs) hasPreserveSigNamedArg, mbody, true | Some (Attrib(_, _, _, _, _, _, m)) -> @@ -5650,14 +5847,14 @@ and GenMethodForBinding // Replace the body of ValInline.PseudoVal "must inline" methods with a 'throw' // However still generate the code for reflection etc. let bodyExpr = - if HasFSharpAttribute cenv.g cenv.g.attrib_NoDynamicInvocationAttribute v.Attribs then - let exnArg = mkString cenv.g m (FSComp.SR.ilDynamicInvocationNotSupported(v.CompiledName)) + if HasFSharpAttribute g g.attrib_NoDynamicInvocationAttribute v.Attribs then + let exnArg = mkString g m (FSComp.SR.ilDynamicInvocationNotSupported(v.CompiledName g.CompilerGlobalState)) let exnExpr = MakeNotSupportedExnExpr cenv eenv (exnArg, m) mkThrow m returnTy exnExpr else body - let ilCode = CodeGenMethodForExpr cenv cgbuf.mgbuf (SPAlways, tailCallInfo, mspec.Name, eenvForMeth, 0, bodyExpr, sequel) + let ilCode = CodeGenMethodForExpr cenv mgbuf (SPAlways, tailCallInfo, mspec.Name, eenvForMeth, 0, bodyExpr, sequel) // This is the main code generation for most methods false, MethodBody.IL ilCode, false @@ -5665,42 +5862,42 @@ and GenMethodForBinding // Do not generate DllImport attributes into the code - they are implicit from the P/Invoke let attrs = v.Attribs - |> List.filter (IsMatchingFSharpAttributeOpt cenv.g cenv.g.attrib_DllImportAttribute >> not) - |> List.filter (IsMatchingFSharpAttribute cenv.g cenv.g.attrib_CompiledNameAttribute >> not) + |> List.filter (IsMatchingFSharpAttributeOpt g g.attrib_DllImportAttribute >> not) + |> List.filter (IsMatchingFSharpAttribute g g.attrib_CompiledNameAttribute >> not) let attrsAppliedToGetterOrSetter, attrs = List.partition (fun (Attrib(_, _, _, _, isAppliedToGetterOrSetter, _, _)) -> isAppliedToGetterOrSetter) attrs let sourceNameAttribs, compiledName = - match v.Attribs |> List.tryFind (IsMatchingFSharpAttribute cenv.g cenv.g.attrib_CompiledNameAttribute) with - | Some (Attrib(_, _, [ AttribStringArg(b) ], _, _, _, _)) -> [ mkCompilationSourceNameAttr cenv.g v.LogicalName ], Some b + match v.Attribs |> List.tryFind (IsMatchingFSharpAttribute g g.attrib_CompiledNameAttribute) with + | Some (Attrib(_, _, [ AttribStringArg b ], _, _, _, _)) -> [ mkCompilationSourceNameAttr g v.LogicalName ], Some b | _ -> [], None // check if the hasPreserveSigNamedArg and hasSynchronizedImplFlag implementation flags have been specified let hasPreserveSigImplFlag, hasSynchronizedImplFlag, hasNoInliningFlag, hasAggressiveInliningImplFlag, attrs = ComputeMethodImplAttribs cenv v attrs - let securityAttributes, attrs = attrs |> List.partition (fun a -> IsSecurityAttribute cenv.g cenv.amap cenv.casApplied a m) + let securityAttributes, attrs = attrs |> List.partition (fun a -> IsSecurityAttribute g cenv.amap cenv.casApplied a m) let permissionSets = CreatePermissionSets cenv eenv securityAttributes let secDecls = if List.isEmpty securityAttributes then emptyILSecurityDecls else mkILSecurityDecls permissionSets // Do not push the attributes to the method for events and properties - let ilAttrsCompilerGenerated = if v.IsCompilerGenerated then [ cenv.g.CompilerGeneratedAttribute ] else [] + let ilAttrsCompilerGenerated = if v.IsCompilerGenerated then [ g.CompilerGeneratedAttribute ] else [] let ilAttrsThatGoOnPrimaryItem = [ yield! GenAttrs cenv eenv attrs yield! GenCompilationArgumentCountsAttr cenv v ] let ilTypars = GenGenericParams cenv eenvUnderMethLambdaTypars tps - let ilParams = GenParams cenv eenv mspec paramInfos methodArgTys (Some(nonUnitNonSelfMethodVars)) + let ilParams = GenParams cenv eenv mspec paramInfos methodArgTys (Some nonUnitNonSelfMethodVars) let ilReturn = GenReturnInfo cenv eenv mspec.FormalReturnType retInfo let methName = mspec.Name let tref = mspec.MethodRef.DeclaringTypeRef let EmitTheMethodDef (mdef: ILMethodDef) = // Does the function have an explicit [] attribute? - let isExplicitEntryPoint = HasFSharpAttribute cenv.g cenv.g.attrib_EntryPointAttribute attrs + let isExplicitEntryPoint = HasFSharpAttribute g g.attrib_EntryPointAttribute attrs let mdef = mdef @@ -5723,15 +5920,15 @@ and GenMethodForBinding else mdef CountMethodDef() - cgbuf.mgbuf.AddMethodDef(tref, mdef) + mgbuf.AddMethodDef(tref, mdef) match v.MemberInfo with // don't generate unimplemented abstracts - | Some(memberInfo) when memberInfo.MemberFlags.IsDispatchSlot && not memberInfo.IsImplemented -> + | Some memberInfo when memberInfo.MemberFlags.IsDispatchSlot && not memberInfo.IsImplemented -> // skipping unimplemented abstract method () - | Some(memberInfo) when not v.IsExtensionMember -> + | Some memberInfo when not v.IsExtensionMember -> let ilMethTypars = ilTypars |> List.drop mspec.DeclaringType.GenericArgs.Length if memberInfo.MemberFlags.MemberKind = MemberKind.Constructor then @@ -5750,20 +5947,20 @@ and GenMethodForBinding else let mdef = if not compileAsInstance then - mkILStaticMethod (ilMethTypars, v.CompiledName, access, ilParams, ilReturn, ilMethodBody) + mkILStaticMethod (ilMethTypars, v.CompiledName g.CompilerGlobalState, access, ilParams, ilReturn, ilMethodBody) elif (memberInfo.MemberFlags.IsDispatchSlot && memberInfo.IsImplemented) || memberInfo.MemberFlags.IsOverrideOrExplicitImpl then let flagFixups = ComputeFlagFixupsForMemberBinding cenv (v, memberInfo) - let mdef = mkILGenericVirtualMethod (v.CompiledName, ILMemberAccess.Public, ilMethTypars, ilParams, ilReturn, ilMethodBody) + let mdef = mkILGenericVirtualMethod (v.CompiledName g.CompilerGlobalState, ILMemberAccess.Public, ilMethTypars, ilParams, ilReturn, ilMethodBody) let mdef = List.fold (fun mdef f -> f mdef) mdef flagFixups // fixup can potentially change name of reflected definition that was already recorded - patch it if necessary - cgbuf.mgbuf.ReplaceNameOfReflectedDefinition(v, mdef.Name) + mgbuf.ReplaceNameOfReflectedDefinition(v, mdef.Name) mdef else - mkILGenericNonVirtualMethod (v.CompiledName, access, ilMethTypars, ilParams, ilReturn, ilMethodBody) + mkILGenericNonVirtualMethod (v.CompiledName g.CompilerGlobalState, access, ilMethTypars, ilParams, ilReturn, ilMethodBody) let isAbstract = memberInfo.MemberFlags.IsDispatchSlot && @@ -5782,22 +5979,22 @@ and GenMethodForBinding error(InternalError("A property may not be more generic than the enclosing type - constrain the polymorphism in the expression", v.Range)) // Check if we're compiling the property as a .NET event - if CompileAsEvent cenv.g v.Attribs then + if CompileAsEvent g v.Attribs then // Emit the pseudo-property as an event, but not if its a private method impl if mdef.Access <> ILMemberAccess.Private then let edef = GenEventForProperty cenv eenvForMeth mspec v ilAttrsThatGoOnPrimaryItem m returnTy - cgbuf.mgbuf.AddEventDef(tref, edef) + mgbuf.AddEventDef(tref, edef) // The method def is dropped on the floor here else // Emit the property, but not if its a private method impl if mdef.Access <> ILMemberAccess.Private then - let vtyp = ReturnTypeOfPropertyVal cenv.g v + let vtyp = ReturnTypeOfPropertyVal g v let ilPropTy = GenType cenv.amap m eenvUnderMethTypeTypars.tyenv vtyp - let ilArgTys = v |> ArgInfosOfPropertyVal cenv.g |> List.map fst |> GenTypes cenv.amap m eenvUnderMethTypeTypars.tyenv + let ilArgTys = v |> ArgInfosOfPropertyVal g |> List.map fst |> GenTypes cenv.amap m eenvUnderMethTypeTypars.tyenv let ilPropDef = GenPropertyForMethodDef compileAsInstance tref mdef v memberInfo ilArgTys ilPropTy (mkILCustomAttrs ilAttrsThatGoOnPrimaryItem) compiledName - cgbuf.mgbuf.AddOrMergePropertyDef(tref, ilPropDef, m) + mgbuf.AddOrMergePropertyDef(tref, ilPropDef, m) // Add the special name flag for all properties let mdef = mdef.WithSpecialName.With(customAttrs= mkILCustomAttrs ((GenAttrs cenv eenv attrsAppliedToGetterOrSetter) @ sourceNameAttribs @ ilAttrsCompilerGenerated)) @@ -5857,7 +6054,7 @@ and GenBindings cenv cgbuf eenv binds = List.iter (GenBinding cenv cgbuf eenv) b //------------------------------------------------------------------------- and GenSetVal cenv cgbuf eenv (vref, e, m) sequel = - let storage = StorageForValRef m vref eenv + let storage = StorageForValRef cenv.g m vref eenv match storage with | Env (ilCloTy, _, _, _) -> CG.EmitInstr cgbuf (pop 0) (Push [ilCloTy]) mkLdarg0 @@ -5869,39 +6066,40 @@ and GenSetVal cenv cgbuf eenv (vref, e, m) sequel = and GenGetValRefAndSequel cenv cgbuf eenv m (v: ValRef) fetchSequel = let ty = v.Type - GenGetStorageAndSequel cenv cgbuf eenv m (ty, GenType cenv.amap m eenv.tyenv ty) (StorageForValRef m v eenv) fetchSequel + GenGetStorageAndSequel cenv cgbuf eenv m (ty, GenType cenv.amap m eenv.tyenv ty) (StorageForValRef cenv.g m v eenv) fetchSequel and GenGetVal cenv cgbuf eenv (v: ValRef, m) sequel = GenGetValRefAndSequel cenv cgbuf eenv m v None GenSequel cenv eenv.cloc cgbuf sequel and GenBindingRhs cenv cgbuf eenv sp (vspec: Val) e = + let g = cenv.g match e with | Expr.TyLambda _ | Expr.Lambda _ -> - let isLocalTypeFunc = IsNamedLocalTypeFuncVal cenv.g vspec e + let isLocalTypeFunc = IsNamedLocalTypeFuncVal g vspec e match e with - | Expr.TyLambda(_, tyargs, body, _, ttype) when + | Expr.TyLambda (_, tyargs, body, _, ttype) when ( tyargs |> List.forall (fun tp -> tp.IsErased) && - (match StorageForVal vspec.Range vspec eenv with Local _ -> true | _ -> false) && + (match StorageForVal g vspec.Range vspec eenv with Local _ -> true | _ -> false) && (isLocalTypeFunc || (match ttype with - TType_var(typar) -> match typar.Solution with Some(TType_app(t, _))-> t.IsStructOrEnumTycon | _ -> false + TType_var typar -> match typar.Solution with Some(TType_app(t, _))-> t.IsStructOrEnumTycon | _ -> false | _ -> false)) ) -> // type lambda with erased type arguments that is stored as local variable (not method or property)- inline body GenExpr cenv cgbuf eenv sp body Continue | _ -> - let selfv = if isLocalTypeFunc then None else Some (mkLocalValRef vspec) - GenLambda cenv cgbuf eenv isLocalTypeFunc selfv e Continue + let thisVars = if isLocalTypeFunc then [] else [ mkLocalValRef vspec ] + GenLambda cenv cgbuf eenv isLocalTypeFunc thisVars e Continue | _ -> GenExpr cenv cgbuf eenv sp e Continue and CommitStartScope cgbuf startScopeMarkOpt = match startScopeMarkOpt with | None -> () - | Some ss -> cgbuf.SetMarkToHere(ss) + | Some ss -> cgbuf.SetMarkToHere ss and EmitInitLocal cgbuf ty idx = CG.EmitInstrs cgbuf (pop 0) Push0 [I_ldloca (uint16 idx); (I_initobj ty) ] @@ -5953,6 +6151,7 @@ and CommitGetStorageSequel cenv cgbuf eenv m ty localCloInfo storeSequel = GenArgsAndIndirectCall cenv cgbuf eenv (ty, tyargs, args, m) sequel and GenGetStorageAndSequel cenv cgbuf eenv m (ty, ilTy) storage storeSequel = + let g = cenv.g match storage with | Local (idx, _, localCloInfo) -> EmitGetLocal cgbuf ilTy idx @@ -5978,16 +6177,16 @@ and GenGetStorageAndSequel cenv cgbuf eenv m (ty, ilTy) storage storeSequel = // First build a lambda expression for the saturated use of the toplevel value... // REVIEW: we should NOT be doing this in the backend... - let expr, exprty = AdjustValForExpectedArity cenv.g m vref NormalValUse topValInfo + let expr, exprty = AdjustValForExpectedArity g m vref NormalValUse topValInfo // Then reduce out any arguments (i.e. apply the sequel immediately if we can...) match storeSequel with | None -> - GenLambda cenv cgbuf eenv false None expr Continue + GenLambda cenv cgbuf eenv false [] expr Continue | Some (tyargs', args, m, sequel) -> let specializedExpr = if isNil args && isNil tyargs' then failwith ("non-lambda at use of method " + mspec.Name) - MakeApplicationAndBetaReduce cenv.g (expr, exprty, [tyargs'], args, m) + MakeApplicationAndBetaReduce g (expr, exprty, [tyargs'], args, m) GenExpr cenv cgbuf eenv SPSuppress specializedExpr sequel | Null -> @@ -6007,13 +6206,13 @@ and GenGetLocalVals cenv cgbuf eenvouter m fvs = List.iter (fun v -> GenGetLocalVal cenv cgbuf eenvouter m v None) fvs and GenGetLocalVal cenv cgbuf eenv m (vspec: Val) fetchSequel = - GenGetStorageAndSequel cenv cgbuf eenv m (vspec.Type, GenTypeOfVal cenv eenv vspec) (StorageForVal m vspec eenv) fetchSequel + GenGetStorageAndSequel cenv cgbuf eenv m (vspec.Type, GenTypeOfVal cenv eenv vspec) (StorageForVal cenv.g m vspec eenv) fetchSequel and GenGetLocalVRef cenv cgbuf eenv m (vref: ValRef) fetchSequel = - GenGetStorageAndSequel cenv cgbuf eenv m (vref.Type, GenTypeOfVal cenv eenv vref.Deref) (StorageForValRef m vref eenv) fetchSequel + GenGetStorageAndSequel cenv cgbuf eenv m (vref.Type, GenTypeOfVal cenv eenv vref.Deref) (StorageForValRef cenv.g m vref eenv) fetchSequel -and GenStoreVal cgbuf eenv m (vspec: Val) = - GenSetStorage vspec.Range cgbuf (StorageForVal m vspec eenv) +and GenStoreVal cenv cgbuf eenv m (vspec: Val) = + GenSetStorage vspec.Range cgbuf (StorageForVal cenv.g m vspec eenv) /// Allocate IL locals and AllocLocal cenv cgbuf eenv compgen (v, ty, isFixed) (scopeMarks: Mark * Mark) = @@ -6029,27 +6228,28 @@ and AllocLocal cenv cgbuf eenv compgen (v, ty, isFixed) (scopeMarks: Mark * Mark /// Decide storage for local value and if necessary allocate an ILLocal for it and AllocLocalVal cenv cgbuf v eenv repr scopeMarks = + let g = cenv.g let repr, eenv = let ty = v.Type - if isUnitTy cenv.g ty && not v.IsMutable then Null, eenv + if isUnitTy g ty && not v.IsMutable then Null, eenv else match repr with - | Some r when IsNamedLocalTypeFuncVal cenv.g v r -> + | Some r when IsNamedLocalTypeFuncVal g v r -> // known, named, non-escaping type functions let cloinfoGenerate eenv = let eenvinner = {eenv with - letBoundVars=(mkLocalValRef v)::eenv.letBoundVars} - let cloinfo, _, _ = GetIlxClosureInfo cenv v.Range true None eenvinner (Option.get repr) + letBoundVars=(mkLocalValRef v) :: eenv.letBoundVars} + let cloinfo, _, _ = GetIlxClosureInfo cenv v.Range true [] eenvinner (Option.get repr) cloinfo - let idx, realloc, eenv = AllocLocal cenv cgbuf eenv v.IsCompilerGenerated (v.CompiledName, cenv.g.ilg.typ_Object, false) scopeMarks + let idx, realloc, eenv = AllocLocal cenv cgbuf eenv v.IsCompilerGenerated (v.CompiledName g.CompilerGlobalState, g.ilg.typ_Object, false) scopeMarks Local (idx, realloc, Some(ref (NamedLocalIlxClosureInfoGenerator cloinfoGenerate))), eenv | _ -> // normal local - let idx, realloc, eenv = AllocLocal cenv cgbuf eenv v.IsCompilerGenerated (v.CompiledName, GenTypeOfVal cenv eenv v, v.IsFixed) scopeMarks + let idx, realloc, eenv = AllocLocal cenv cgbuf eenv v.IsCompilerGenerated (v.CompiledName g.CompilerGlobalState, GenTypeOfVal cenv eenv v, v.IsFixed) scopeMarks Local (idx, realloc, None), eenv - let eenv = AddStorageForVal cenv.g (v, notlazy repr) eenv + let eenv = AddStorageForVal g (v, notlazy repr) eenv Some repr, eenv and AllocStorageForBind cenv cgbuf scopeMarks eenv bind = @@ -6084,6 +6284,7 @@ and AllocValForBind cenv cgbuf (scopeMarks: Mark * Mark) eenv (TBind(v, repr, _) and AllocTopValWithinExpr cenv cgbuf cloc scopeMarks v eenv = + let g = cenv.g // decide whether to use a shadow local or not let useShadowLocal = cenv.opts.generateDebugSymbols && @@ -6091,7 +6292,7 @@ and AllocTopValWithinExpr cenv cgbuf cloc scopeMarks v eenv = not v.IsCompilerGenerated && not v.IsMutable && // Don't use shadow locals for things like functions which are not compiled as static values/properties - IsCompiledAsStaticProperty cenv.g v + IsCompiledAsStaticProperty g v let optShadowLocal, eenv = if useShadowLocal then @@ -6099,13 +6300,10 @@ and AllocTopValWithinExpr cenv cgbuf cloc scopeMarks v eenv = match storageOpt with | None -> NoShadowLocal, eenv | Some storage -> ShadowLocal storage, eenv - else NoShadowLocal, eenv - ComputeAndAddStorageForLocalTopVal (cenv.amap, cenv.g, cenv.intraAssemblyInfo, cenv.opts.isInteractive, optShadowLocal) cloc v eenv - - + ComputeAndAddStorageForLocalTopVal (cenv.amap, g, cenv.intraAssemblyInfo, cenv.opts.isInteractive, optShadowLocal) cloc v eenv //-------------------------------------------------------------------------- // Generate stack save/restore and assertions - pulled into letrec by alloc* @@ -6118,7 +6316,10 @@ and EmitSaveStack cenv cgbuf eenv m scopeMarks = let savedStack = (cgbuf.GetCurrentStack()) let savedStackLocals, eenvinner = (eenv, savedStack) ||> List.mapFold (fun eenv ty -> - let idx, _realloc, eenv = AllocLocal cenv cgbuf eenv true (ilxgenGlobalNng.FreshCompilerGeneratedName ("spill", m), ty, false) scopeMarks + let idx, _realloc, eenv = + // Ensure that we have an g.CompilerGlobalState + assert(cenv.g.CompilerGlobalState |> Option.isSome) + AllocLocal cenv cgbuf eenv true (cenv.g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName ("spill", m), ty, false) scopeMarks idx, eenv) List.iter (EmitSetLocal cgbuf) savedStackLocals cgbuf.AssertEmptyStack() @@ -6134,15 +6335,15 @@ and EmitRestoreStack cgbuf (savedStack, savedStackLocals) = //------------------------------------------------------------------------- and GenAttribArg amap g eenv x (ilArgTy: ILType) = + let exprL expr = exprL g expr match x, ilArgTy with - // Detect 'null' used for an array argument - | Expr.Const(Const.Zero, _, _), ILType.Array _ -> + | Expr.Const (Const.Zero, _, _), ILType.Array _ -> ILAttribElem.Null // Detect standard constants - | Expr.Const(c, m, _), _ -> + | Expr.Const (c, m, _), _ -> let tynm = ilArgTy.TypeSpec.Name let isobj = (tynm = "System.Object") @@ -6173,7 +6374,7 @@ and GenAttribArg amap g eenv x (ilArgTy: ILType) = | _ -> error (InternalError ( "The type '" + tynm + "' may not be used as a custom attribute value", m)) // Detect '[| ... |]' nodes - | Expr.Op(TOp.Array, [elemTy], args, m), _ -> + | Expr.Op (TOp.Array, [elemTy], args, m), _ -> let ilElemTy = GenType amap m eenv.tyenv elemTy ILAttribElem.Array (ilElemTy, List.map (fun arg -> GenAttribArg amap g eenv arg ilElemTy) args) @@ -6186,7 +6387,7 @@ and GenAttribArg amap g eenv x (ilArgTy: ILType) = ILAttribElem.TypeRef (Some (GenType amap x.Range eenv.tyenv ty).TypeRef) // Ignore upcasts - | Expr.Op(TOp.Coerce, _, [arg2], _), _ -> + | Expr.Op (TOp.Coerce, _, [arg2], _), _ -> GenAttribArg amap g eenv arg2 ilArgTy // Detect explicit enum values @@ -6224,38 +6425,41 @@ and GenAttr amap g eenv (Attrib(_, k, args, props, _, _, _)) = (s, ilTy, fld, cval)) let mspec = match k with - | ILAttrib(mref) -> mkILMethSpec(mref, AsObject, [], []) - | FSAttrib(vref) -> + | ILAttrib mref -> mkILMethSpec(mref, AsObject, [], []) + | FSAttrib vref -> assert(vref.IsMember) let mspec, _, _, _, _, _ = GetMethodSpecForMemberVal amap g (Option.get vref.MemberInfo) vref mspec let ilArgs = List.map2 (fun (AttribExpr(_, vexpr)) ty -> GenAttribArg amap g eenv vexpr ty) args mspec.FormalArgTypes mkILCustomAttribMethRef g.ilg (mspec, ilArgs, props) -and GenAttrs cenv eenv attrs = List.map (GenAttr cenv.amap cenv.g eenv) attrs +and GenAttrs cenv eenv attrs = + List.map (GenAttr cenv.amap cenv.g eenv) attrs and GenCompilationArgumentCountsAttr cenv (v: Val) = + let g = cenv.g [ match v.ValReprInfo with - | Some(tvi) when v.IsMemberOrModuleBinding -> - let arities = if ValSpecIsCompiledAsInstance cenv.g v then List.tail tvi.AritiesOfArgs else tvi.AritiesOfArgs + | Some tvi when v.IsMemberOrModuleBinding -> + let arities = if ValSpecIsCompiledAsInstance g v then List.tail tvi.AritiesOfArgs else tvi.AritiesOfArgs if arities.Length > 1 then - yield mkCompilationArgumentCountsAttr cenv.g arities + yield mkCompilationArgumentCountsAttr g arities | _ -> () ] // Create a permission set for a list of security attributes and CreatePermissionSets cenv eenv (securityAttributes: Attrib list) = + let g = cenv.g [for ((Attrib(tcref, _, actions, _, _, _, _)) as attr) in securityAttributes do let action = match actions with | [AttribInt32Arg act] -> act | _ -> failwith "internal error: unrecognized security action" let secaction = (List.assoc action (Lazy.force ILSecurityActionRevMap)) let tref = tcref.CompiledRepresentationForNamedType - let ilattr = GenAttr cenv.amap cenv.g eenv attr + let ilattr = GenAttr cenv.amap g eenv attr let _, ilNamedArgs = - match TryDecodeILAttribute cenv.g tref (mkILCustomAttrs [ilattr]) with + match TryDecodeILAttribute g tref (mkILCustomAttrs [ilattr]) with | Some(ae, na) -> ae, na | _ -> [], [] let setArgs = ilNamedArgs |> List.map (fun (n, ilt, _, ilae) -> (n, ilt, ilae)) - yield IL.mkPermissionSet cenv.g.ilg (secaction, [(tref, setArgs)])] + yield IL.mkPermissionSet g.ilg (secaction, [(tref, setArgs)])] //-------------------------------------------------------------------------- // Generate the set of modules for an assembly, and the declarations in each module @@ -6263,9 +6467,10 @@ and CreatePermissionSets cenv eenv (securityAttributes: Attrib list) = /// Generate a static class at the given cloc and GenTypeDefForCompLoc (cenv, eenv, mgbuf: AssemblyBuilder, cloc, hidden, attribs, initTrigger, eliminateIfEmpty, addAtEnd) = + let g = cenv.g let tref = TypeRefForCompLoc cloc let tdef = - mkILSimpleClass cenv.g.ilg + mkILSimpleClass g.ilg (tref.Name, ComputeTypeAccess tref hidden, emptyILMethods, @@ -6277,7 +6482,7 @@ and GenTypeDefForCompLoc (cenv, eenv, mgbuf: AssemblyBuilder, cloc, hidden, attr (GenAttrs cenv eenv attribs @ (if List.contains tref.Name [TypeNameForImplicitMainMethod cloc; TypeNameForInitClass cloc; TypeNameForPrivateImplementationDetails cloc] then [ ] - else [mkCompilationMappingAttr cenv.g (int SourceConstructFlags.Module)])), + else [mkCompilationMappingAttr g (int SourceConstructFlags.Module)])), initTrigger) let tdef = tdef.WithSealed(true).WithAbstract(true) mgbuf.AddTypeDef(tref, tdef, eliminateIfEmpty, addAtEnd, None) @@ -6316,10 +6521,10 @@ and GenModuleDef cenv (cgbuf: CodeGenBuffer) qname lazyInitInfo eenv x = | TMDefDo(e, _) -> GenExpr cenv cgbuf eenv SPAlways e discard - | TMAbstract(mexpr) -> + | TMAbstract mexpr -> GenModuleExpr cenv cgbuf qname lazyInitInfo eenv mexpr - | TMDefs(mdefs) -> + | TMDefs mdefs -> GenModuleDefs cenv cgbuf qname lazyInitInfo eenv mdefs @@ -6361,13 +6566,13 @@ and GenModuleBinding cenv (cgbuf: CodeGenBuffer) (qname: QualifiedNameOfFile) la /// Generate the namespace fragments in a single file -and GenTopImpl cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (TImplFile(qname, _, mexpr, hasExplicitEntryPoint, isScript, anonRecdTypes), optimizeDuringCodeGen) = - +and GenTopImpl cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (TImplFile (qname, _, mexpr, hasExplicitEntryPoint, isScript, anonRecdTypes), optimizeDuringCodeGen) = + let g = cenv.g let m = qname.Range // Generate all the anonymous record types mentioned anywhere in this module for anonInfo in anonRecdTypes.Values do - mgbuf.GenerateAnonType((fun ilThisTy -> GenToStringMethod cenv eenv ilThisTy m), anonInfo) |> ignore + mgbuf.GenerateAnonType((fun ilThisTy -> GenToStringMethod cenv eenv ilThisTy m), anonInfo) let eenv = {eenv with cloc = { eenv.cloc with TopImplQualifiedName = qname.Text } } @@ -6435,56 +6640,47 @@ and GenTopImpl cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (TImplFile(qname, else [], [] - begin - - match mainInfoOpt with - - // Final file in .EXE - | Some mainInfo -> - - // Generate an explicit main method. If necessary, make a class constructor as - // well for the bindings earlier in the file containing the entrypoint. - match mgbuf.GetExplicitEntryPointInfo() with - - // Final file, explicit entry point: place the code in a .cctor, and add code to main that forces the .cctor (if topCode has initialization effect). - | Some tref -> - if doesSomething then - lazyInitInfo.Add (fun fspec feefee seqpt -> - // This adds the explicit init of the .cctor to the explicit entrypoint main method - mgbuf.AddExplicitInitToSpecificMethodDef((fun md -> md.IsEntryPoint), tref, fspec, GenPossibleILSourceMarker cenv m, feefee, seqpt)) - - let cctorMethDef = mkILClassCtor (MethodBody.IL topCode) - mgbuf.AddMethodDef(initClassTy.TypeRef, cctorMethDef) - - // Final file, implicit entry point. We generate no .cctor. - // void main@() { - // - // } - | None -> - - let ilAttrs = mkILCustomAttrs (GenAttrs cenv eenv mainInfo) - if not cenv.opts.isInteractive && not doesSomething then - let errorM = m.EndRange - warning (Error(FSComp.SR.ilMainModuleEmpty(), errorM)) - - // generate main@ - let ilMainMethodDef = - let mdef = mkILNonGenericStaticMethod(mainMethName, ILMemberAccess.Public, [], mkILReturn ILType.Void, MethodBody.IL topCode) - mdef.With(isEntryPoint= true, customAttrs = ilAttrs) - - mgbuf.AddMethodDef(initClassTy.TypeRef, ilMainMethodDef) - - // Library file: generate an optional .cctor if topCode has initialization effect - | None -> + match mainInfoOpt with + // Final file in .EXE + | Some mainInfo -> + // Generate an explicit main method. If necessary, make a class constructor as + // well for the bindings earlier in the file containing the entry point. + match mgbuf.GetExplicitEntryPointInfo() with + // Final file, explicit entry point: place the code in a .cctor, and add code to main that forces the .cctor (if topCode has initialization effect). + | Some tref -> if doesSomething then + lazyInitInfo.Add (fun fspec feefee seqpt -> + // This adds the explicit init of the .cctor to the explicit entry point main method + mgbuf.AddExplicitInitToSpecificMethodDef((fun md -> md.IsEntryPoint), tref, fspec, GenPossibleILSourceMarker cenv m, feefee, seqpt)) - // Add the cctor let cctorMethDef = mkILClassCtor (MethodBody.IL topCode) mgbuf.AddMethodDef(initClassTy.TypeRef, cctorMethDef) + // Final file, implicit entry point. We generate no .cctor. + // void main@() { + // + // } + | None -> + let ilAttrs = mkILCustomAttrs (GenAttrs cenv eenv mainInfo) + if not cenv.opts.isInteractive && not doesSomething then + let errorM = m.EndRange + warning (Error(FSComp.SR.ilMainModuleEmpty(), errorM)) + + // generate main@ + let ilMainMethodDef = + let mdef = mkILNonGenericStaticMethod(mainMethName, ILMemberAccess.Public, [], mkILReturn ILType.Void, MethodBody.IL topCode) + mdef.With(isEntryPoint= true, customAttrs = ilAttrs) + + mgbuf.AddMethodDef(initClassTy.TypeRef, ilMainMethodDef) - end + + // Library file: generate an optional .cctor if topCode has initialization effect + | None -> + if doesSomething then + // Add the cctor + let cctorMethDef = mkILClassCtor (MethodBody.IL topCode) + mgbuf.AddMethodDef(initClassTy.TypeRef, cctorMethDef) // Commit the directed initializations if doesSomething then @@ -6493,9 +6689,9 @@ and GenTopImpl cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (TImplFile(qname, // There is no need to do this for a final file with an implicit entry point. For an explicit entry point in lazyInitInfo. let initFieldName = CompilerGeneratedName "init" let ilFieldDef = - mkILStaticField (initFieldName, cenv.g.ilg.typ_Int32, None, None, ComputeMemberAccess true) - |> cenv.g.AddFieldNeverAttrs - |> cenv.g.AddFieldGeneratedAttrs + mkILStaticField (initFieldName, g.ilg.typ_Int32, None, None, ComputeMemberAccess true) + |> g.AddFieldNeverAttrs + |> g.AddFieldGeneratedAttrs let fspec = mkILFieldSpecInTy (initClassTy, initFieldName, cenv. g.ilg.typ_Int32) CountStaticFieldDef() @@ -6505,14 +6701,14 @@ and GenTopImpl cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (TImplFile(qname, // of references to the cctor for nested modules etc. lazyInitInfo |> Seq.iter (fun f -> f fspec feefee seqpt) - if isScript && not(isFinalFile) then + if isScript && not isFinalFile then mgbuf.AddScriptInitFieldSpec(fspec, m) // Compute the ilxgenEnv after the generation of the module, i.e. the residue need to generate anything that // uses the constructs exported from this module. // We add the module type all over again. Note no shadow locals for static fields needed here since they are only relevant to the main/.cctor let eenvafter = - let allocVal = ComputeAndAddStorageForLocalTopVal (cenv.amap, cenv.g, cenv.intraAssemblyInfo, cenv.opts.isInteractive, NoShadowLocal) + let allocVal = ComputeAndAddStorageForLocalTopVal (cenv.amap, g, cenv.intraAssemblyInfo, cenv.opts.isInteractive, NoShadowLocal) AddBindingsForLocalModuleType allocVal clocCcu eenv mexpr.Type eenvafter @@ -6525,12 +6721,13 @@ and GenForceWholeFileInitializationAsPartOfCCtor cenv (mgbuf: AssemblyBuilder) ( /// Generate an Equals method. and GenEqualsOverrideCallingIComparable cenv (tcref: TyconRef, ilThisTy, _ilThatTy) = - let mspec = mkILNonGenericInstanceMethSpecInTy (cenv.g.iltyp_IComparable, "CompareTo", [cenv.g.ilg.typ_Object], cenv.g.ilg.typ_Int32) + let g = cenv.g + let mspec = mkILNonGenericInstanceMethSpecInTy (g.iltyp_IComparable, "CompareTo", [g.ilg.typ_Object], g.ilg.typ_Int32) mkILNonGenericVirtualMethod ("Equals", ILMemberAccess.Public, - [mkILParamNamed ("obj", cenv.g.ilg.typ_Object)], - mkILReturn cenv.g.ilg.typ_Bool, + [mkILParamNamed ("obj", g.ilg.typ_Object)], + mkILReturn g.ilg.typ_Bool, mkMethodBody(true, [], 2, nonBranchingInstrsToCode [ yield mkLdarg0 @@ -6539,10 +6736,10 @@ and GenEqualsOverrideCallingIComparable cenv (tcref: TyconRef, ilThisTy, _ilThat yield I_callconstraint ( Normalcall, ilThisTy, mspec, None) else yield I_callvirt ( Normalcall, mspec, None) - yield mkLdcInt32 (0) + yield mkLdcInt32 0 yield AI_ceq ], None)) - |> AddNonUserCompilerGeneratedAttribs cenv.g + |> AddNonUserCompilerGeneratedAttribs g and GenFieldInit m c = match c with @@ -6551,6 +6748,7 @@ and GenFieldInit m c = and GenAbstractBinding cenv eenv tref (vref: ValRef) = assert(vref.IsMember) + let g = cenv.g let m = vref.Range let memberInfo = Option.get vref.MemberInfo let attribs = vref.Attribs @@ -6560,21 +6758,25 @@ and GenAbstractBinding cenv eenv tref (vref: ValRef) = [ yield! GenAttrs cenv eenv attribs yield! GenCompilationArgumentCountsAttr cenv vref.Deref ] - let mspec, ctps, mtps, argInfos, retInfo, methodArgTys = GetMethodSpecForMemberVal cenv.amap cenv.g memberInfo vref + let mspec, ctps, mtps, argInfos, retInfo, methodArgTys = GetMethodSpecForMemberVal cenv.amap g memberInfo vref let eenvForMeth = EnvForTypars (ctps@mtps) eenv let ilMethTypars = GenGenericParams cenv eenvForMeth mtps let ilReturn = GenReturnInfo cenv eenvForMeth mspec.FormalReturnType retInfo let ilParams = GenParams cenv eenvForMeth mspec argInfos methodArgTys None - let compileAsInstance = ValRefIsCompiledAsInstanceMember cenv.g vref - let mdef = mkILGenericVirtualMethod (vref.CompiledName, ILMemberAccess.Public, ilMethTypars, ilParams, ilReturn, MethodBody.Abstract) + let compileAsInstance = ValRefIsCompiledAsInstanceMember g vref + let mdef = mkILGenericVirtualMethod (vref.CompiledName g.CompilerGlobalState, ILMemberAccess.Public, ilMethTypars, ilParams, ilReturn, MethodBody.Abstract) let mdef = fixupVirtualSlotFlags mdef let mdef = if mdef.IsVirtual then mdef.WithFinal(memberInfo.MemberFlags.IsFinal).WithAbstract(memberInfo.MemberFlags.IsDispatchSlot) else mdef - let mdef = mdef.WithPreserveSig(hasPreserveSigImplFlag).WithSynchronized(hasSynchronizedImplFlag).WithNoInlining(hasNoInliningFlag).WithAggressiveInlining(hasAggressiveInliningImplFlag) + let mdef = + mdef.WithPreserveSig(hasPreserveSigImplFlag) + .WithSynchronized(hasSynchronizedImplFlag) + .WithNoInlining(hasNoInliningFlag) + .WithAggressiveInlining(hasAggressiveInliningImplFlag) match memberInfo.MemberFlags.MemberKind with | MemberKind.ClassConstructor @@ -6585,15 +6787,15 @@ and GenAbstractBinding cenv eenv tref (vref: ValRef) = | MemberKind.PropertyGetSet -> error(Error(FSComp.SR.ilUnexpectedGetSetAnnotation(), m)) | MemberKind.PropertySet | MemberKind.PropertyGet -> let v = vref.Deref - let vtyp = ReturnTypeOfPropertyVal cenv.g v - if CompileAsEvent cenv.g attribs then + let vtyp = ReturnTypeOfPropertyVal g v + if CompileAsEvent g attribs then let edef = GenEventForProperty cenv eenvForMeth mspec v ilAttrs m vtyp [], [], [edef] else let ilPropDef = let ilPropTy = GenType cenv.amap m eenvForMeth.tyenv vtyp - let ilArgTys = v |> ArgInfosOfPropertyVal cenv.g |> List.map fst |> GenTypes cenv.amap m eenvForMeth.tyenv + let ilArgTys = v |> ArgInfosOfPropertyVal g |> List.map fst |> GenTypes cenv.amap m eenvForMeth.tyenv GenPropertyForMethodDef compileAsInstance tref mdef v memberInfo ilArgTys ilPropTy (mkILCustomAttrs ilAttrs) None let mdef = mdef.WithSpecialName [mdef], [ilPropDef], [] @@ -6603,27 +6805,28 @@ and GenAbstractBinding cenv eenv tref (vref: ValRef) = /// Generate a ToString method that calls 'sprintf "%A"' and GenToStringMethod cenv eenv ilThisTy m = - [ match (eenv.valsInScope.TryFind cenv.g.sprintf_vref.Deref, - eenv.valsInScope.TryFind cenv.g.new_format_vref.Deref) with + let g = cenv.g + [ match (eenv.valsInScope.TryFind g.sprintf_vref.Deref, + eenv.valsInScope.TryFind g.new_format_vref.Deref) with | Some(Lazy(Method(_, _, sprintfMethSpec, _, _, _, _))), Some(Lazy(Method(_, _, newFormatMethSpec, _, _, _, _))) -> // The type returned by the 'sprintf' call - let funcTy = EraseClosures.mkILFuncTy cenv.g.ilxPubCloEnv ilThisTy cenv.g.ilg.typ_String + let funcTy = EraseClosures.mkILFuncTy g.ilxPubCloEnv ilThisTy g.ilg.typ_String // Give the instantiation of the printf format object, i.e. a Format`5 object compatible with StringFormat let newFormatMethSpec = mkILMethSpec(newFormatMethSpec.MethodRef, AsObject, [// 'T -> string' funcTy // rest follow from 'StringFormat' GenUnitTy cenv eenv m - cenv.g.ilg.typ_String - cenv.g.ilg.typ_String + g.ilg.typ_String + g.ilg.typ_String ilThisTy], []) // Instantiate with our own type let sprintfMethSpec = mkILMethSpec(sprintfMethSpec.MethodRef, AsObject, [], [funcTy]) // Here's the body of the method. Call printf, then invoke the function it returns - let callInstrs = EraseClosures.mkCallFunc cenv.g.ilxPubCloEnv (fun _ -> 0us) eenv.tyenv.Count Normalcall (Apps_app(ilThisTy, Apps_done cenv.g.ilg.typ_String)) + let callInstrs = EraseClosures.mkCallFunc g.ilxPubCloEnv (fun _ -> 0us) eenv.tyenv.Count Normalcall (Apps_app(ilThisTy, Apps_done g.ilg.typ_String)) let mdef = mkILNonGenericVirtualMethod ("ToString", ILMemberAccess.Public, [], - mkILReturn cenv.g.ilg.typ_String, + mkILReturn g.ilg.typ_String, mkMethodBody (true, [], 2, nonBranchingInstrsToCode ([ // load the hardwired format string yield I_ldstr "%+A" @@ -6637,11 +6840,12 @@ and GenToStringMethod cenv eenv ilThisTy m = yield mkNormalLdobj ilThisTy ] @ callInstrs), None)) - let mdef = mdef.With(customAttrs = mkILCustomAttrs [ cenv.g.CompilerGeneratedAttribute ]) + let mdef = mdef.With(customAttrs = mkILCustomAttrs [ g.CompilerGeneratedAttribute ]) yield mdef | _ -> () ] and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = + let g = cenv.g let tcref = mkLocalTyconRef tycon if tycon.IsTypeAbbrev then () else match tycon.TypeReprInfo with @@ -6677,8 +6881,8 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = (if Option.isNone tycon.GeneratedCompareToValues && Option.isNone tycon.GeneratedHashAndEqualsValues && - tycon.HasInterface cenv.g cenv.g.mk_IComparable_ty && - not (tycon.HasOverride cenv.g "Equals" [cenv.g.obj_ty]) && + tycon.HasInterface g g.mk_IComparable_ty && + not (tycon.HasOverride g "Equals" [g.obj_ty]) && not tycon.IsFSharpInterfaceTycon then [ GenEqualsOverrideCallingIComparable cenv (tcref, ilThisTy, ilThisTy) ] @@ -6707,17 +6911,17 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = [ for vref in tycon.MembersOfFSharpTyconByName |> NameMultiMap.range do assert(vref.IsMember) let memberInfo = vref.MemberInfo.Value - if memberInfo.MemberFlags.IsOverrideOrExplicitImpl && not (CompileAsEvent cenv.g vref.Attribs) then + if memberInfo.MemberFlags.IsOverrideOrExplicitImpl && not (CompileAsEvent g vref.Attribs) then for slotsig in memberInfo.ImplementedSlotSigs do - if isInterfaceTy cenv.g slotsig.ImplementedType then + if isInterfaceTy g slotsig.ImplementedType then match vref.ValReprInfo with | Some _ -> let memberParentTypars, memberMethodTypars = - match PartitionValRefTypars cenv.g vref with + match PartitionValRefTypars g vref with | Some(_, memberParentTypars, memberMethodTypars, _, _) -> memberParentTypars, memberMethodTypars | None -> [], [] @@ -6739,19 +6943,19 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = | None -> None | Some memberInfo -> match name, memberInfo.MemberFlags.MemberKind with - | ("Item" | "op_IndexedLookup"), (MemberKind.PropertyGet | MemberKind.PropertySet) when not (isNil (ArgInfosOfPropertyVal cenv.g vref.Deref)) -> - Some( mkILCustomAttribute cenv.g.ilg (cenv.g.FindSysILTypeRef "System.Reflection.DefaultMemberAttribute", [cenv.g.ilg.typ_String], [ILAttribElem.String(Some(name))], []) ) + | ("Item" | "op_IndexedLookup"), (MemberKind.PropertyGet | MemberKind.PropertySet) when not (isNil (ArgInfosOfPropertyVal g vref.Deref)) -> + Some( mkILCustomAttribute g.ilg (g.FindSysILTypeRef "System.Reflection.DefaultMemberAttribute", [g.ilg.typ_String], [ILAttribElem.String(Some name)], []) ) | _ -> None) |> Option.toList let tyconRepr = tycon.TypeReprInfo // DebugDisplayAttribute gets copied to the subtypes generated as part of DU compilation - let debugDisplayAttrs, normalAttrs = tycon.Attribs |> List.partition (IsMatchingFSharpAttribute cenv.g cenv.g.attrib_DebuggerDisplayAttribute) - let securityAttrs, normalAttrs = normalAttrs |> List.partition (fun a -> IsSecurityAttribute cenv.g cenv.amap cenv.casApplied a m) - let generateDebugDisplayAttribute = not cenv.g.compilingFslib && tycon.IsUnionTycon && isNil debugDisplayAttrs - let generateDebugProxies = (not (tyconRefEq cenv.g tcref cenv.g.unit_tcr_canon) && - not (HasFSharpAttribute cenv.g cenv.g.attrib_DebuggerTypeProxyAttribute tycon.Attribs)) + let debugDisplayAttrs, normalAttrs = tycon.Attribs |> List.partition (IsMatchingFSharpAttribute g g.attrib_DebuggerDisplayAttribute) + let securityAttrs, normalAttrs = normalAttrs |> List.partition (fun a -> IsSecurityAttribute g cenv.amap cenv.casApplied a m) + let generateDebugDisplayAttribute = not g.compilingFslib && tycon.IsUnionTycon && isNil debugDisplayAttrs + let generateDebugProxies = (not (tyconRefEq g tcref g.unit_tcr_canon) && + not (HasFSharpAttribute g g.attrib_DebuggerTypeProxyAttribute tycon.Attribs)) let permissionSets = CreatePermissionSets cenv eenv securityAttrs let secDecls = if List.isEmpty securityAttrs then emptyILSecurityDecls else mkILSecurityDecls permissionSets @@ -6759,13 +6963,13 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let ilDebugDisplayAttributes = [ yield! GenAttrs cenv eenv debugDisplayAttrs if generateDebugDisplayAttribute then - yield cenv.g.mkDebuggerDisplayAttribute ("{" + debugDisplayMethodName + "(),nq}") ] + yield g.mkDebuggerDisplayAttribute ("{" + debugDisplayMethodName + "(),nq}") ] let ilCustomAttrs = [ yield! defaultMemberAttrs yield! normalAttrs - |> List.filter (IsMatchingFSharpAttribute cenv.g cenv.g.attrib_StructLayoutAttribute >> not) + |> List.filter (IsMatchingFSharpAttribute g g.attrib_StructLayoutAttribute >> not) |> GenAttrs cenv eenv yield! ilDebugDisplayAttributes ] @@ -6794,7 +6998,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = isEmptyStruct && cenv.opts.workAroundReflectionEmitBugs && not tycon.TyparsNoRange.IsEmpty // Compute a bunch of useful things for each field - let isCLIMutable = (TryFindFSharpBoolAttribute cenv.g cenv.g.attrib_CLIMutableAttribute tycon.Attribs = Some true) + let isCLIMutable = (TryFindFSharpBoolAttribute g g.attrib_CLIMutableAttribute tycon.Attribs = Some true) let fieldSummaries = [ for fspec in tycon.AllFieldsArray do @@ -6821,8 +7025,8 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = [ for (useGenuineField, ilFieldName, isFSharpMutable, isStatic, _, ilPropType, isPropHidden, fspec) in fieldSummaries do let ilFieldOffset = - match TryFindFSharpAttribute cenv.g cenv.g.attrib_FieldOffsetAttribute fspec.FieldAttribs with - | Some (Attrib(_, _, [ AttribInt32Arg(fieldOffset) ], _, _, _, _)) -> + match TryFindFSharpAttribute g g.attrib_FieldOffsetAttribute fspec.FieldAttribs with + | Some (Attrib(_, _, [ AttribInt32Arg fieldOffset ], _, _, _, _)) -> Some fieldOffset | Some (Attrib(_, _, _, _, _, _, m)) -> errorR(Error(FSComp.SR.ilFieldOffsetAttributeCouldNotBeDecoded(), m)) @@ -6838,24 +7042,25 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = yield! fspec.FieldAttribs ] - let ilNotSerialized = HasFSharpAttributeOpt cenv.g cenv.g.attrib_NonSerializedAttribute attribs + let ilNotSerialized = HasFSharpAttributeOpt g g.attrib_NonSerializedAttribute attribs let fattribs = attribs // Do not generate FieldOffset as a true CLI custom attribute, since it is implied by other corresponding CLI metadata - |> List.filter (IsMatchingFSharpAttribute cenv.g cenv.g.attrib_FieldOffsetAttribute >> not) + |> List.filter (IsMatchingFSharpAttribute g g.attrib_FieldOffsetAttribute >> not) // Do not generate NonSerialized as a true CLI custom attribute, since it is implied by other corresponding CLI metadata - |> List.filter (IsMatchingFSharpAttributeOpt cenv.g cenv.g.attrib_NonSerializedAttribute >> not) + |> List.filter (IsMatchingFSharpAttributeOpt g g.attrib_NonSerializedAttribute >> not) let ilFieldMarshal, fattribs = GenMarshal cenv fattribs - // The IL field is hidden if the property/field is hidden OR we're using a property AND the field is not mutable (because we can take the address of a mutable field). + // The IL field is hidden if the property/field is hidden OR we're using a property + // AND the field is not mutable (because we can take the address of a mutable field). // Otherwise fields are always accessed via their property getters/setters let isFieldHidden = isPropHidden || (not useGenuineField && not isFSharpMutable) let extraAttribs = match tyconRepr with - | TRecdRepr _ when not useGenuineField -> [ cenv.g.DebuggerBrowsableNeverAttribute ] // hide fields in records in debug display + | TRecdRepr _ when not useGenuineField -> [ g.DebuggerBrowsableNeverAttribute ] // hide fields in records in debug display | _ -> [] // don't hide fields in classes in debug display let access = ComputeMemberAccess isFieldHidden @@ -6879,7 +7084,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = yield fdef if requiresExtraField then - yield mkILInstanceField("__dummy", cenv.g.ilg.typ_Int32, None, ILMemberAccess.Assembly) ] + yield mkILInstanceField("__dummy", g.ilg.typ_Int32, None, ILMemberAccess.Assembly) ] // Generate property definitions for the fields compiled as properties let ilPropertyDefsForFields = @@ -6888,7 +7093,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let ilCallingConv = if isStatic then ILCallingConv.Static else ILCallingConv.Instance let ilPropName = fspec.Name let ilHasSetter = isCLIMutable || isFSharpMutable - let ilFieldAttrs = GenAttrs cenv eenv propAttribs @ [mkCompilationMappingAttrWithSeqNum cenv.g (int SourceConstructFlags.Field) i] + let ilFieldAttrs = GenAttrs cenv eenv propAttribs @ [mkCompilationMappingAttrWithSeqNum g (int SourceConstructFlags.Field) i] yield ILPropertyDef.Create(name= ilPropName, attributes= PropertyAttributes.None, @@ -6932,26 +7137,26 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = if generateDebugDisplayAttribute then let (|Lazy|) (x: Lazy<_>) = x.Force() - match (eenv.valsInScope.TryFind cenv.g.sprintf_vref.Deref, - eenv.valsInScope.TryFind cenv.g.new_format_vref.Deref) with + match (eenv.valsInScope.TryFind g.sprintf_vref.Deref, + eenv.valsInScope.TryFind g.new_format_vref.Deref) with | Some(Lazy(Method(_, _, sprintfMethSpec, _, _, _, _))), Some(Lazy(Method(_, _, newFormatMethSpec, _, _, _, _))) -> // The type returned by the 'sprintf' call - let funcTy = EraseClosures.mkILFuncTy cenv.g.ilxPubCloEnv ilThisTy cenv.g.ilg.typ_String + let funcTy = EraseClosures.mkILFuncTy g.ilxPubCloEnv ilThisTy g.ilg.typ_String // Give the instantiation of the printf format object, i.e. a Format`5 object compatible with StringFormat let newFormatMethSpec = mkILMethSpec(newFormatMethSpec.MethodRef, AsObject, [// 'T -> string' funcTy // rest follow from 'StringFormat' GenUnitTy cenv eenv m - cenv.g.ilg.typ_String - cenv.g.ilg.typ_String - cenv.g.ilg.typ_String], []) + g.ilg.typ_String + g.ilg.typ_String + g.ilg.typ_String], []) // Instantiate with our own type let sprintfMethSpec = mkILMethSpec(sprintfMethSpec.MethodRef, AsObject, [], [funcTy]) // Here's the body of the method. Call printf, then invoke the function it returns - let callInstrs = EraseClosures.mkCallFunc cenv.g.ilxPubCloEnv (fun _ -> 0us) eenv.tyenv.Count Normalcall (Apps_app(ilThisTy, Apps_done cenv.g.ilg.typ_String)) + let callInstrs = EraseClosures.mkCallFunc g.ilxPubCloEnv (fun _ -> 0us) eenv.tyenv.Count Normalcall (Apps_app(ilThisTy, Apps_done g.ilg.typ_String)) let ilMethodDef = mkILNonGenericInstanceMethod (debugDisplayMethodName, ILMemberAccess.Assembly, [], - mkILReturn cenv.g.ilg.typ_Object, + mkILReturn g.ilg.typ_Object, mkMethodBody (true, [], 2, nonBranchingInstrsToCode @@ -6967,12 +7172,12 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = yield mkNormalLdobj ilThisTy ] @ callInstrs), None)) - yield ilMethodDef.WithSpecialName |> AddNonUserCompilerGeneratedAttribs cenv.g + yield ilMethodDef.WithSpecialName |> AddNonUserCompilerGeneratedAttribs g | None, _ -> //printfn "sprintf not found" () | _, None -> - //printfn "new formatnot found" + //printfn "new format not found" () | _ -> //printfn "neither found, or non-method" @@ -6995,17 +7200,17 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let isStructRecord = tycon.IsStructRecordOrUnionTycon // No type spec if the record is a value type - let spec = if isStructRecord then None else Some(cenv.g.ilg.typ_Object.TypeSpec) + let spec = if isStructRecord then None else Some(g.ilg.typ_Object.TypeSpec) let ilMethodDef = mkILSimpleStorageCtorWithParamNames(None, spec, ilThisTy, [], ChooseParamNames fieldNamesAndTypes, reprAccess) yield ilMethodDef // FSharp 1.0 bug 1988: Explicitly setting the ComVisible(true) attribute on an F# type causes an F# record to be emitted in a way that enables mutation for COM interop scenarios // FSharp 3.0 feature: adding CLIMutable to a record type causes emit of default constructor, and all fields get property setters // Records that are value types do not create a default constructor with CLIMutable or ComVisible - if not isStructRecord && (isCLIMutable || (TryFindFSharpBoolAttribute cenv.g cenv.g.attrib_ComVisibleAttribute tycon.Attribs = Some true)) then - yield mkILSimpleStorageCtor(None, Some cenv.g.ilg.typ_Object.TypeSpec, ilThisTy, [], [], reprAccess) + if not isStructRecord && (isCLIMutable || (TryFindFSharpBoolAttribute g g.attrib_ComVisibleAttribute tycon.Attribs = Some true)) then + yield mkILSimpleStorageCtor(None, Some g.ilg.typ_Object.TypeSpec, ilThisTy, [], [], reprAccess) - if not (tycon.HasMember cenv.g "ToString" []) then + if not (tycon.HasMember g "ToString" []) then yield! GenToStringMethod cenv eenv ilThisTy m | TFSharpObjectRepr r when tycon.IsFSharpDelegateTycon -> @@ -7018,13 +7223,13 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let (TSlotSig(nm, ty, ctps, mtps, paraml, returnTy)) = ss let paraml = match paraml with - | [[tsp]] when isUnitTy cenv.g tsp.Type -> [] (* suppress unit arg *) + | [[tsp]] when isUnitTy g tsp.Type -> [] (* suppress unit arg *) | paraml -> paraml GenActualSlotsig m cenv eenvinner (TSlotSig(nm, ty, ctps, mtps, paraml, returnTy)) [] [] - yield! mkILDelegateMethods reprAccess cenv.g.ilg (cenv.g.iltyp_AsyncCallback, cenv.g.iltyp_IAsyncResult) (p, r) + yield! mkILDelegateMethods reprAccess g.ilg (g.iltyp_AsyncCallback, g.iltyp_IAsyncResult) (p, r) | _ -> () - | TUnionRepr _ when not (tycon.HasMember cenv.g "ToString" []) -> + | TUnionRepr _ when not (tycon.HasMember g "ToString" []) -> yield! GenToStringMethod cenv eenv ilThisTy m | _ -> () ] @@ -7034,23 +7239,23 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let ilFields = mkILFields ilFieldDefs let tdef, tdefDiscards = - let isSerializable = (TryFindFSharpBoolAttribute cenv.g cenv.g.attrib_AutoSerializableAttribute tycon.Attribs <> Some(false)) + let isSerializable = (TryFindFSharpBoolAttribute g g.attrib_AutoSerializableAttribute tycon.Attribs <> Some false) match tycon.TypeReprInfo with | TILObjectRepr _ -> - let tdef = tycon.ILTyconRawMetadata.WithAccess(access) + let tdef = tycon.ILTyconRawMetadata.WithAccess access let tdef = tdef.With(customAttrs = mkILCustomAttrs ilCustomAttrs, genericParams = ilGenParams) tdef, None | TRecdRepr _ | TFSharpObjectRepr _ as tyconRepr -> - let super = superOfTycon cenv.g tycon + let super = superOfTycon g tycon let ilBaseTy = GenType cenv.amap m eenvinner.tyenv super // Build a basic type definition let isObjectType = (match tyconRepr with TFSharpObjectRepr _ -> true | _ -> false) let ilAttrs = ilCustomAttrs @ - [mkCompilationMappingAttr cenv.g + [mkCompilationMappingAttr g (int (if isObjectType then SourceConstructFlags.ObjectType elif hiddenRepr then SourceConstructFlags.RecordType ||| SourceConstructFlags.NonPublicRepresentation @@ -7078,14 +7283,18 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = typeDefTrigger) // Set some the extra entries in the definition - let isTheSealedAttribute = tyconRefEq cenv.g tcref cenv.g.attrib_SealedAttribute.TyconRef + let isTheSealedAttribute = tyconRefEq g tcref g.attrib_SealedAttribute.TyconRef - let tdef = tdef.WithSealed(isSealedTy cenv.g thisTy || isTheSealedAttribute).WithSerializable(isSerializable).WithAbstract(isAbstract).WithImport(isComInteropTy cenv.g thisTy) - let tdef = tdef.With(methodImpls=mkILMethodImpls methodImpls) + let tdef = + tdef.WithSealed(isSealedTy g thisTy || isTheSealedAttribute) + .WithSerializable(isSerializable) + .WithAbstract(isAbstract) + .WithImport(isComInteropTy g thisTy) + .With(methodImpls=mkILMethodImpls methodImpls) let tdLayout, tdEncoding = - match TryFindFSharpAttribute cenv.g cenv.g.attrib_StructLayoutAttribute tycon.Attribs with - | Some (Attrib(_, _, [ AttribInt32Arg(layoutKind) ], namedArgs, _, _, _)) -> + match TryFindFSharpAttribute g g.attrib_StructLayoutAttribute tycon.Attribs with + | Some (Attrib(_, _, [ AttribInt32Arg layoutKind ], namedArgs, _, _, _)) -> let decoder = AttributeDecoder namedArgs let ilPack = decoder.FindInt32 "Pack" 0x0 let ilSize = decoder.FindInt32 "Size" 0x0 @@ -7152,19 +7361,19 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = tycon.UnionCasesArray |> Array.mapi (fun i ucspec -> { altName=ucspec.CompiledName altFields=GenUnionCaseRef cenv.amap m eenvinner.tyenv i ucspec.RecdFieldsArray - altCustomAttrs= mkILCustomAttrs (GenAttrs cenv eenv ucspec.Attribs @ [mkCompilationMappingAttrWithSeqNum cenv.g (int SourceConstructFlags.UnionCase) i]) }) + altCustomAttrs= mkILCustomAttrs (GenAttrs cenv eenv ucspec.Attribs @ [mkCompilationMappingAttrWithSeqNum g (int SourceConstructFlags.UnionCase) i]) }) let cuinfo = { cudReprAccess=reprAccess - cudNullPermitted=IsUnionTypeWithNullAsTrueValue cenv.g tycon + cudNullPermitted=IsUnionTypeWithNullAsTrueValue g tycon cudHelpersAccess=reprAccess - cudHasHelpers=ComputeUnionHasHelpers cenv.g tcref + cudHasHelpers=ComputeUnionHasHelpers g tcref cudDebugProxies= generateDebugProxies cudDebugDisplayAttributes= ilDebugDisplayAttributes cudAlternatives= alternatives cudWhere = None} let layout = - if isStructTy cenv.g thisTy then + if isStructTy g thisTy then if (match ilTypeDefKind with ILTypeDefKind.ValueType -> true | _ -> false) then // Structs with no instance fields get size 1, pack 0 ILTypeDefLayout.Sequential { Size=Some 1; Pack=Some 0us } @@ -7175,7 +7384,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let cattrs = mkILCustomAttrs (ilCustomAttrs @ - [mkCompilationMappingAttr cenv.g + [mkCompilationMappingAttr g (int (if hiddenRepr then SourceConstructFlags.SumType ||| SourceConstructFlags.NonPublicRepresentation else SourceConstructFlags.SumType)) ]) @@ -7192,7 +7401,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = methodImpls= mkILMethodImpls methodImpls, nestedTypes=emptyILTypeDefs, implements = ilIntfTys, - extends= Some (if tycon.IsStructOrEnumTycon then cenv.g.iltyp_ValueType else cenv.g.ilg.typ_Object), + extends= Some (if tycon.IsStructOrEnumTycon then g.iltyp_ValueType else g.ilg.typ_Object), securityDecls= emptyILSecurityDecls) .WithLayout(layout) .WithSerializable(isSerializable) @@ -7201,7 +7410,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = .WithAccess(access) .WithInitSemantics(ILTypeInit.BeforeField) - let tdef2 = cenv.g.eraseClassUnionDef tref tdef cuinfo + let tdef2 = g.eraseClassUnionDef tref tdef cuinfo // Discard the user-supplied (i.e. prim-type.fs) implementations of the get_Empty, get_IsEmpty, get_Value and get_None and Some methods. // This is because we will replace their implementations by ones that load the unique @@ -7238,6 +7447,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = /// Generate the type for an F# exception declaration. and GenExnDef cenv mgbuf eenv m (exnc: Tycon) = + let g = cenv.g let exncref = mkLocalEntityRef exnc match exnc.ExceptionInfo with | TExnAbbrevRepr _ | TExnAsmRepr _ | TExnNone -> () @@ -7266,26 +7476,26 @@ and GenExnDef cenv mgbuf eenv m (exnc: Tycon) = propertyType = ilPropType, init = None, args = [], - customAttrs=mkILCustomAttrs (GenAttrs cenv eenv fld.PropertyAttribs @ [mkCompilationMappingAttrWithSeqNum cenv.g (int SourceConstructFlags.Field) i])) + customAttrs=mkILCustomAttrs (GenAttrs cenv eenv fld.PropertyAttribs @ [mkCompilationMappingAttrWithSeqNum g (int SourceConstructFlags.Field) i])) yield (ilMethodDef, ilFieldDef, ilPropDef, (ilPropName, ilFieldName, ilPropType)) ] |> List.unzip4 let ilCtorDef = - mkILSimpleStorageCtorWithParamNames(None, Some cenv.g.iltyp_Exception.TypeSpec, ilThisTy, [], ChooseParamNames fieldNamesAndTypes, reprAccess) + mkILSimpleStorageCtorWithParamNames(None, Some g.iltyp_Exception.TypeSpec, ilThisTy, [], ChooseParamNames fieldNamesAndTypes, reprAccess) // In compiled code, all exception types get a parameterless constructor for use with XML serialization // This does default-initialization of all fields let ilCtorDefNoArgs = if not (isNil fieldNamesAndTypes) then - [ mkILSimpleStorageCtor(None, Some cenv.g.iltyp_Exception.TypeSpec, ilThisTy, [], [], reprAccess) ] + [ mkILSimpleStorageCtor(None, Some g.iltyp_Exception.TypeSpec, ilThisTy, [], [], reprAccess) ] else [] let serializationRelatedMembers = // do not emit serialization related members if target framework lacks SerializationInfo or StreamingContext - match cenv.g.iltyp_SerializationInfo, cenv.g.iltyp_StreamingContext with + match g.iltyp_SerializationInfo, g.iltyp_StreamingContext with | Some serializationInfoType, Some streamingContextType -> - let ilCtorDefForSerialziation = + let ilCtorDefForSerialization = mkILCtor(ILMemberAccess.Family, [mkILParamNamed("info", serializationInfoType);mkILParamNamed("context", streamingContextType)], mkMethodBody @@ -7294,54 +7504,51 @@ and GenExnDef cenv mgbuf eenv m (exnc: Tycon) = [ mkLdarg0 mkLdarg 1us mkLdarg 2us - mkNormalCall (mkILCtorMethSpecForTy (cenv.g.iltyp_Exception, [serializationInfoType; streamingContextType])) ], + mkNormalCall (mkILCtorMethSpecForTy (g.iltyp_Exception, [serializationInfoType; streamingContextType])) ], None)) - -//#if BE_SECURITY_TRANSPARENT - [ilCtorDefForSerialziation] -//#else + + [ilCtorDefForSerialization] (* let getObjectDataMethodForSerialization = - let ilMethodDef = mkILNonGenericVirtualMethod ("GetObjectData", ILMemberAccess.Public, - [mkILParamNamed ("info", serializationInfoType);mkILParamNamed("context", cenv.g.iltyp_StreamingContext)], + [mkILParamNamed ("info", serializationInfoType);mkILParamNamed("context", g.iltyp_StreamingContext)], mkILReturn ILType.Void, (let code = nonBranchingInstrsToCode [ mkLdarg0 mkLdarg 1us mkLdarg 2us - mkNormalCall (mkILNonGenericInstanceMethSpecInTy (cenv.g.iltyp_Exception, "GetObjectData", [serializationInfoType; cenv.g.iltyp_StreamingContext], ILType.Void)) + mkNormalCall (mkILNonGenericInstanceMethSpecInTy (g.iltyp_Exception, "GetObjectData", [serializationInfoType; g.iltyp_StreamingContext], ILType.Void)) ] mkMethodBody(true, [], 8, code, None))) // Here we must encode: [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] // In ILDASM this is: .permissionset demand = {[mscorlib]System.Security.Permissions.SecurityPermissionAttribute = {property bool 'SerializationFormatter' = bool(true)}} - match cenv.g.tref_SecurityPermissionAttribute with + match g.tref_SecurityPermissionAttribute with | None -> ilMethodDef | Some securityPermissionAttributeType -> { ilMethodDef with - SecurityDecls=mkILSecurityDecls [ IL.mkPermissionSet cenv.g.ilg (ILSecurityAction.Demand, [(securityPermissionAttributeType, [("SerializationFormatter", cenv.g.ilg.typ_Bool, ILAttribElem.Bool(true))])])] + SecurityDecls=mkILSecurityDecls [ IL.mkPermissionSet g.ilg (ILSecurityAction.Demand, [(securityPermissionAttributeType, [("SerializationFormatter", g.ilg.typ_Bool, ILAttribElem.Bool true)])])] HasSecurity=true } - [ilCtorDefForSerialziation; getObjectDataMethodForSerialization] + [ilCtorDefForSerialization; getObjectDataMethodForSerialization] *) //#endif | _ -> [] let ilTypeName = tref.Name - + let interfaces = exnc.ImmediateInterfaceTypesOfFSharpTycon |> List.map (GenType cenv.amap m eenv.tyenv) let tdef = mkILGenericClass - (ilTypeName, access, [], cenv.g.iltyp_Exception, + (ilTypeName, access, [], g.iltyp_Exception, interfaces, mkILMethods ([ilCtorDef] @ ilCtorDefNoArgs @ serializationRelatedMembers @ ilMethodDefsForProperties), mkILFields ilFieldDefs, emptyILTypeDefs, mkILProperties ilPropertyDefs, emptyILEvents, - mkILCustomAttrs [mkCompilationMappingAttr cenv.g (int SourceConstructFlags.Exception)], + mkILCustomAttrs [mkCompilationMappingAttr g (int SourceConstructFlags.Exception)], ILTypeInit.BeforeField) let tdef = tdef.WithSerializable(true) mgbuf.AddTypeDef(tref, tdef, false, false, None) @@ -7349,29 +7556,27 @@ and GenExnDef cenv mgbuf eenv m (exnc: Tycon) = let CodegenAssembly cenv eenv mgbuf fileImpls = if not (isNil fileImpls) then - let a, b = List.frontAndBack fileImpls - let eenv = List.fold (GenTopImpl cenv mgbuf None) eenv a - let eenv = GenTopImpl cenv mgbuf cenv.opts.mainMethodInfo eenv b - - // Some constructs generate residue types and bindings. Generate these now. They don't result in any - // top-level initialization code. - begin - let extraBindings = mgbuf.GrabExtraBindingsToGenerate() - //printfn "#extraBindings = %d" extraBindings.Length - if extraBindings.Length > 0 then - let mexpr = TMDefs [ for b in extraBindings -> TMDefLet(b, range0) ] - let _emptyTopInstrs, _emptyTopCode = - CodeGenMethod cenv mgbuf ([], "unused", eenv, 0, (fun cgbuf eenv -> - let lazyInitInfo = ResizeArray() - let qname = QualifiedNameOfFile(mkSynId range0 "unused") - LocalScope "module" cgbuf (fun scopeMarks -> - let eenv = AddBindingsForModuleDef (fun cloc v -> AllocTopValWithinExpr cenv cgbuf cloc scopeMarks v) eenv.cloc eenv mexpr - GenModuleDef cenv cgbuf qname lazyInitInfo eenv mexpr)), range0) - //printfn "#_emptyTopInstrs = %d" _emptyTopInstrs.Length - () - end - - mgbuf.AddInitializeScriptsInOrderToEntryPoint() + let a, b = List.frontAndBack fileImpls + let eenv = List.fold (GenTopImpl cenv mgbuf None) eenv a + let eenv = GenTopImpl cenv mgbuf cenv.opts.mainMethodInfo eenv b + + // Some constructs generate residue types and bindings. Generate these now. They don't result in any + // top-level initialization code. + let extraBindings = mgbuf.GrabExtraBindingsToGenerate() + //printfn "#extraBindings = %d" extraBindings.Length + if extraBindings.Length > 0 then + let mexpr = TMDefs [ for b in extraBindings -> TMDefLet(b, range0) ] + let _emptyTopInstrs, _emptyTopCode = + CodeGenMethod cenv mgbuf ([], "unused", eenv, 0, (fun cgbuf eenv -> + let lazyInitInfo = ResizeArray() + let qname = QualifiedNameOfFile(mkSynId range0 "unused") + LocalScope "module" cgbuf (fun scopeMarks -> + let eenv = AddBindingsForModuleDef (fun cloc v -> AllocTopValWithinExpr cenv cgbuf cloc scopeMarks v) eenv.cloc eenv mexpr + GenModuleDef cenv cgbuf qname lazyInitInfo eenv mexpr)), range0) + //printfn "#_emptyTopInstrs = %d" _emptyTopInstrs.Length + () + + mgbuf.AddInitializeScriptsInOrderToEntryPoint() //------------------------------------------------------------------------- // When generating a module we just write into mutable @@ -7389,7 +7594,8 @@ let GetEmptyIlxGenEnv (ilg: ILGlobals) ccu = liveLocals=IntMap.empty() innerVals = [] sigToImplRemapInfo = [] (* "module remap info" *) - withinSEH = false } + withinSEH = false + isInLoop = false } type IlxGenResults = { ilTypeDefs: ILTypeDef list @@ -7403,6 +7609,7 @@ type IlxGenResults = let GenerateCode (cenv, anonTypeTable, eenv, TypedAssemblyAfterOptimization fileImpls, assemAttribs, moduleAttribs) = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.IlxGen + let g = cenv.g // Generate the implementations into the mgbuf let mgbuf = new AssemblyBuilder(cenv, anonTypeTable) @@ -7424,22 +7631,15 @@ let GenerateCode (cenv, anonTypeTable, eenv, TypedAssemblyAfterOptimization file match reflectedDefinitions with | [] -> [] | _ -> - let qscope = QuotationTranslator.QuotationGenerationScope.Create (cenv.g, cenv.amap, cenv.viewCcu, QuotationTranslator.IsReflectedDefinition.Yes) + let qscope = QuotationTranslator.QuotationGenerationScope.Create (g, cenv.amap, cenv.viewCcu, QuotationTranslator.IsReflectedDefinition.Yes) let defns = reflectedDefinitions |> List.choose (fun ((methName, v), e) -> try - let ety = tyOfExpr cenv.g e - let tps, taue, _ = - match e with - | Expr.TyLambda (_, tps, b, _, _) -> tps, b, applyForallTy cenv.g ety (List.map mkTyparTy tps) - | _ -> [], e, ety - let env = QuotationTranslator.QuotationTranslationEnv.Empty.BindTypars tps - let astExpr = QuotationTranslator.ConvExprPublic qscope env taue - let mbaseR = QuotationTranslator.ConvMethodBase qscope env (methName, v) + let mbaseR, astExpr = QuotationTranslator.ConvReflectedDefinition qscope methName v e Some(mbaseR, astExpr) with - | QuotationTranslator.InvalidQuotedTerm e -> warning(e); None) + | QuotationTranslator.InvalidQuotedTerm e -> warning e; None) let referencedTypeDefs, freeTypes, spliceArgExprs = qscope.Close() @@ -7456,7 +7656,7 @@ let GenerateCode (cenv, anonTypeTable, eenv, TypedAssemblyAfterOptimization file let ilNetModuleAttrs = GenAttrs cenv eenv moduleAttribs let casApplied = new Dictionary() - let securityAttrs, topAssemblyAttrs = assemAttribs |> List.partition (fun a -> IsSecurityAttribute cenv.g cenv.amap casApplied a rangeStartup) + let securityAttrs, topAssemblyAttrs = assemAttribs |> List.partition (fun a -> IsSecurityAttribute g cenv.amap casApplied a rangeStartup) // remove any security attributes from the top-level assembly attribute list let permissionSets = CreatePermissionSets cenv eenv securityAttrs @@ -7475,7 +7675,6 @@ let GenerateCode (cenv, anonTypeTable, eenv, TypedAssemblyAfterOptimization file //------------------------------------------------------------------------- open System -open System.Reflection /// The lookup* functions are the conversions available from ilreflect. type ExecutionContext = @@ -7499,8 +7698,8 @@ let defaultOf = /// Top-level val bindings are stored (for example) in static fields. /// In the FSI case, these fields are be created and initialised, so we can recover the object. /// IlxGen knows how v was stored, and then ilreflect knows how this storage was generated. -/// IlxGen converts (v: Tast.Val) to AbsIL datastructures. -/// Ilreflect converts from AbsIL datastructures to emitted Type, FieldInfo, MethodInfo etc. +/// IlxGen converts (v: Tast.Val) to AbsIL data structures. +/// Ilreflect converts from AbsIL data structures to emitted Type, FieldInfo, MethodInfo etc. let LookupGeneratedValue (amap: ImportMap) (ctxt: ExecutionContext) eenv (v: Val) = try // Convert the v.Type into a System.Type according to ilxgen and ilreflect. @@ -7508,7 +7707,7 @@ let LookupGeneratedValue (amap: ImportMap) (ctxt: ExecutionContext) eenv (v: Val let ilTy = GenType amap v.Range TypeReprEnv.Empty v.Type (* TypeReprEnv.Empty ok, not expecting typars *) ctxt.LookupType ilTy // Lookup the compiled v value (as an object). - match StorageForVal v.Range v eenv with + match StorageForVal amap.g v.Range v eenv with | StaticField (fspec, _, hasLiteralAttr, ilContainerTy, _, _, ilGetterMethRef, _, _) -> let obj = if hasLiteralAttr then @@ -7548,9 +7747,9 @@ let LookupGeneratedValue (amap: ImportMap) (ctxt: ExecutionContext) eenv (v: Val None // Invoke the set_Foo method for a declaration with a default/null value. Used to release storage in fsi.exe -let ClearGeneratedValue (ctxt: ExecutionContext) (_g: TcGlobals) eenv (v: Val) = +let ClearGeneratedValue (ctxt: ExecutionContext) (g: TcGlobals) eenv (v: Val) = try - match StorageForVal v.Range v eenv with + match StorageForVal g v.Range v eenv with | StaticField (fspec, _, hasLiteralAttr, _, _, _, _ilGetterMethRef, ilSetterMethRef, _) -> if not hasLiteralAttr && v.IsMutable then let staticTy = ctxt.LookupTypeRef ilSetterMethRef.DeclaringTypeRef @@ -7569,7 +7768,7 @@ let ClearGeneratedValue (ctxt: ExecutionContext) (_g: TcGlobals) eenv (v: Val) = #endif //!FABLE_COMPILER /// The published API from the ILX code generator -type IlxAssemblyGenerator(amap: ImportMap, tcGlobals: TcGlobals, tcVal: ConstraintSolver.TcValF, ccu: Tast.CcuThunk) = +type IlxAssemblyGenerator(amap: ImportMap, tcGlobals: TcGlobals, tcVal: ConstraintSolver.TcValF, ccu: CcuThunk) = // The incremental state held by the ILX code generator let mutable ilxGenEnv = GetEmptyIlxGenEnv tcGlobals.ilg ccu @@ -7597,7 +7796,9 @@ type IlxAssemblyGenerator(amap: ImportMap, tcGlobals: TcGlobals, tcVal: Constrai casApplied = casApplied intraAssemblyInfo = intraAssemblyInfo opts = codeGenOpts - optimizeDuringCodeGen = (fun x -> x) } + optimizeDuringCodeGen = (fun x -> x) + exprRecursionDepth = 0 + delayedGenMethods = Queue () } GenerateCode (cenv, anonTypeTable, ilxGenEnv, typedAssembly, assemAttribs, moduleAttribs) #if !FABLE_COMPILER @@ -7608,4 +7809,3 @@ type IlxAssemblyGenerator(amap: ImportMap, tcGlobals: TcGlobals, tcVal: Constrai member __.LookupGeneratedValue (ctxt, v) = LookupGeneratedValue amap ctxt ilxGenEnv v #endif //!FABLE_COMPILER - diff --git a/src/fcs-fable/src/fsharp/IlxGen.fsi b/src/fcs-fable/src/fsharp/IlxGen.fsi old mode 100755 new mode 100644 index 432f785eef..3b76c92e5d --- a/src/fcs-fable/src/fsharp/IlxGen.fsi +++ b/src/fcs-fable/src/fsharp/IlxGen.fsi @@ -7,7 +7,7 @@ open System.IO open System.Reflection open FSharp.Compiler open FSharp.Compiler.AbstractIL.IL -open FSharp.Compiler.Tast +open FSharp.Compiler.TypedTree open FSharp.Compiler.TcGlobals /// Indicates how the generated IL code is ultimately emitted @@ -17,91 +17,99 @@ type IlxGenBackend = [] type internal IlxGenOptions = - { fragName : string + { fragName: string /// Indicates if we are generating filter blocks - generateFilterBlocks : bool + generateFilterBlocks: bool /// Indicates if we should workaround old reflection emit bugs - workAroundReflectionEmitBugs : bool + workAroundReflectionEmitBugs: bool /// Indicates if static array data should be emitted using static blobs - emitConstantArraysUsingStaticDataBlobs : bool + emitConstantArraysUsingStaticDataBlobs: bool /// If this is set, then the last module becomes the "main" module - mainMethodInfo : Attribs option + mainMethodInfo: Attribs option /// Indicates if local optimizations are active - localOptimizationsAreOn : bool + localOptimizationsAreOn: bool /// Indicates if we are generating debug symbols or not - generateDebugSymbols : bool + generateDebugSymbols: bool /// A flag to help test emit of debug information - testFlagEmitFeeFeeAs100001 : bool + testFlagEmitFeeFeeAs100001: bool /// Indicates which backend we are generating code for - ilxBackend : IlxGenBackend + ilxBackend: IlxGenBackend /// Indicates the code is being generated in FSI.EXE and is executed immediately after code generation /// This includes all interactively compiled code, including #load, definitions, and expressions - isInteractive : bool + isInteractive: bool /// Indicates the code generated is an interactive 'it' expression. We generate a setter to allow clearing of the underlying /// storage, even though 'it' is not logically mutable - isInteractiveItExpr : bool + isInteractiveItExpr: bool /// Indicates that, whenever possible, use callvirt instead of call - alwaysCallVirt : bool } + alwaysCallVirt: bool + } /// The results of the ILX compilation of one fragment of an assembly type public IlxGenResults = - { /// The generated IL/ILX type definitions - ilTypeDefs : ILTypeDef list + { + /// The generated IL/ILX type definitions + ilTypeDefs: ILTypeDef list + /// The generated IL/ILX assembly attributes - ilAssemAttrs : ILAttribute list + ilAssemAttrs: ILAttribute list + /// The generated IL/ILX .NET module attributes - ilNetModuleAttrs : ILAttribute list + ilNetModuleAttrs: ILAttribute list + /// The attributes for the assembly in F# form - topAssemblyAttrs : Attribs + topAssemblyAttrs: Attribs + /// The security attributes to attach to the assembly - permissionSets : ILSecurityDecl list - /// The generated IL/ILX resources associated with F# quotations - quotationResourceInfo : (ILTypeRef list * byte[]) list } + permissionSets: ILSecurityDecl list + /// The generated IL/ILX resources associated with F# quotations + quotationResourceInfo: (ILTypeRef list * byte[]) list + } /// Used to support the compilation-inversion operations "ClearGeneratedValue" and "LookupGeneratedValue" type ExecutionContext = - { LookupFieldRef : (ILFieldRef -> FieldInfo) - LookupMethodRef : (ILMethodRef -> MethodInfo) - LookupTypeRef : (ILTypeRef -> Type) - LookupType : (ILType -> Type) } + { + LookupFieldRef: (ILFieldRef -> FieldInfo) + LookupMethodRef: (ILMethodRef -> MethodInfo) + LookupTypeRef: (ILTypeRef -> Type) + LookupType: (ILType -> Type) + } /// An incremental ILX code generator for a single assembly type public IlxAssemblyGenerator = /// Create an incremental ILX code generator for a single assembly - new : Import.ImportMap * TcGlobals * ConstraintSolver.TcValF * CcuThunk -> IlxAssemblyGenerator + new: Import.ImportMap * TcGlobals * ConstraintSolver.TcValF * CcuThunk -> IlxAssemblyGenerator /// Register a set of referenced assemblies with the ILX code generator - member AddExternalCcus : CcuThunk list -> unit + member AddExternalCcus: CcuThunk list -> unit /// Register a fragment of the current assembly with the ILX code generator. If 'isIncrementalFragment' is true then the input /// is assumed to be a fragment 'typed' into FSI.EXE, otherwise the input is assumed to be the result of a '#load' - member AddIncrementalLocalAssemblyFragment : isIncrementalFragment: bool * fragName:string * typedImplFiles: TypedImplFile list -> unit + member AddIncrementalLocalAssemblyFragment: isIncrementalFragment: bool * fragName:string * typedImplFiles: TypedImplFile list -> unit /// Generate ILX code for an assembly fragment - member GenerateCode : IlxGenOptions * TypedAssemblyAfterOptimization * Attribs * Attribs -> IlxGenResults + member GenerateCode: IlxGenOptions * TypedAssemblyAfterOptimization * Attribs * Attribs -> IlxGenResults #if !FABLE_COMPILER /// Invert the compilation of the given value and clear the storage of the value - member ClearGeneratedValue : ExecutionContext * Val -> unit + member ClearGeneratedValue: ExecutionContext * Val -> unit /// Invert the compilation of the given value and return its current dynamic value and its compiled System.Type - member LookupGeneratedValue : ExecutionContext * Val -> (obj * System.Type) option + member LookupGeneratedValue: ExecutionContext * Val -> (obj * System.Type) option #endif //!FABLE_COMPILER - -val ReportStatistics : TextWriter -> unit +val ReportStatistics: TextWriter -> unit /// Determine if an F#-declared value, method or function is compiled as a method. -val IsFSharpValCompiledAsMethod : TcGlobals -> Val -> bool +val IsFSharpValCompiledAsMethod: TcGlobals -> Val -> bool diff --git a/src/fcs-fable/src/fsharp/InfoReader.fs b/src/fcs-fable/src/fsharp/InfoReader.fs index 2a2bfd7ea6..222a255789 100644 --- a/src/fcs-fable/src/fsharp/InfoReader.fs +++ b/src/fcs-fable/src/fsharp/InfoReader.fs @@ -4,23 +4,26 @@ /// Select members from a type by name, searching the type hierarchy if needed module internal FSharp.Compiler.InfoReader +open System open System.Collections.Generic -open FSharp.Compiler.AbstractIL.IL -open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler +open FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AccessibilityLogic -open FSharp.Compiler.Ast open FSharp.Compiler.AttributeChecking open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Infos open FSharp.Compiler.Range -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals +open FSharp.Compiler.Features +open FSharp.Compiler.TypeRelations /// Use the given function to select some of the member values from the members of an F# type -let private SelectImmediateMemberVals g optFilter f (tcref: TyconRef) = +let SelectImmediateMemberVals g optFilter f (tcref: TyconRef) = let chooser (vref: ValRef) = match vref.MemberInfo with // The 'when' condition is a workaround for the fact that values providing @@ -79,7 +82,7 @@ let rec GetImmediateIntrinsicMethInfosOfTypeAux (optFilter, ad) g amap m origTy GetImmediateIntrinsicMethInfosOfTypeAux (optFilter, ad) g amap m origTy betterMetadataTy |> List.filter (fun minfo -> not minfo.IsInstance) else - match tryDestAppTy g metadataTy with + match tryTcrefOfAppTy g metadataTy with | ValueNone -> [] | ValueSome tcref -> SelectImmediateMemberVals g optFilter (TrySelectMemberVal g optFilter origTy None) tcref @@ -107,7 +110,7 @@ type PropertyCollector(g, amap, m, ty, optFilter, ad) = let props = new Dictionary(hashIdentity) let add pinfo = - match props.TryGetValue(pinfo), pinfo with + match props.TryGetValue pinfo, pinfo with | (true, FSProp (_, ty, Some vref1, _)), FSProp (_, _, _, Some vref2) | (true, FSProp (_, ty, _, Some vref2)), FSProp (_, _, Some vref1, _) -> let pinfo = FSProp (g, ty, Some vref1, Some vref2) @@ -167,7 +170,7 @@ let rec GetImmediateIntrinsicPropInfosOfTypeAux (optFilter, ad) g amap m origTy let betterMetadataTy = convertToTypeWithMetadataIfPossible g metadataTy GetImmediateIntrinsicPropInfosOfTypeAux (optFilter, ad) g amap m origTy betterMetadataTy else - match tryDestAppTy g metadataTy with + match tryTcrefOfAppTy g metadataTy with | ValueNone -> [] | ValueSome tcref -> let propCollector = new PropertyCollector(g, amap, m, origTy, optFilter, ad) @@ -186,13 +189,58 @@ let rec GetImmediateIntrinsicPropInfosOfType (optFilter, ad) g amap m ty = let IsIndexerType g amap ty = isArray1DTy g ty || isListTy g ty || - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref -> let _, entityTy = generalizeTyconRef tcref let props = GetImmediateIntrinsicPropInfosOfType (None, AccessibleFromSomeFSharpCode) g amap range0 entityTy props |> List.exists (fun x -> x.PropertyName = "Item") | ValueNone -> false +/// Get the items that are considered the most specific in the hierarchy out of the given items by type. +/// REVIEW: Note complexity O(N^2) +let GetMostSpecificItemsByType g amap f xs = + [ for x in xs do + match f x with + | None -> () + | Some (xTy, m) -> + let isEqual = + xs + |> List.forall (fun y -> + match f y with + | None -> true + | Some (yTy, _) -> + if typeEquiv g xTy yTy then true + else not (TypeFeasiblySubsumesType 0 g amap m xTy CanCoerce yTy)) + if isEqual then + yield x ] + +/// Finds the most specific methods from a method collection by a given method's signature. +let GetMostSpecificMethodInfosByMethInfoSig g amap m (ty, minfo) minfos = + minfos + |> GetMostSpecificItemsByType g amap (fun (ty2, minfo2) -> + let isEqual = + typeEquiv g ty ty2 && + MethInfosEquivByPartialSig EraseNone true g amap m minfo minfo2 + if isEqual then + Some(minfo2.ApparentEnclosingType, m) + else + None) + +/// From the given method sets, filter each set down to the most specific ones. +let FilterMostSpecificMethInfoSets g amap m (minfoSets: NameMultiMap<_>) : NameMultiMap<_> = + minfoSets + |> Map.map (fun _ minfos -> + ([], minfos) + ||> List.fold (fun minfoSpecifics (ty, minfo) -> + let alreadySeen = + minfoSpecifics + |> List.exists (fun (tySpecific, minfoSpecific) -> + typeEquiv g ty tySpecific && + MethInfosEquivByPartialSig EraseNone true g amap m minfo minfoSpecific) + if alreadySeen then + minfoSpecifics + else + GetMostSpecificMethodInfosByMethInfoSig g amap m (ty, minfo) minfos @ minfoSpecifics)) /// Sets of methods up the hierarchy, ignoring duplicates by name and sig. /// Used to collect sets of virtual methods, protected methods, protected @@ -206,7 +254,7 @@ type HierarchyItem = /// An InfoReader is an object to help us read and cache infos. /// We create one of these for each file we typecheck. -type InfoReader(g: TcGlobals, amap: Import.ImportMap) = +type InfoReader(g: TcGlobals, amap: Import.ImportMap) as this = /// Get the declared IL fields of a type, not including inherited fields let GetImmediateIntrinsicILFieldsOfType (optFilter, ad) m ty = @@ -266,7 +314,7 @@ type InfoReader(g: TcGlobals, amap: Import.ImportMap) = /// Get the F#-declared record fields or class 'val' fields of a type let GetImmediateIntrinsicRecdOrClassFieldsOfType (optFilter, _ad) _m ty = - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueNone -> [] | ValueSome tcref -> // Note;secret fields are not allowed in lookups here, as we're only looking @@ -299,10 +347,10 @@ type InfoReader(g: TcGlobals, amap: Import.ImportMap) = let GetIntrinsicRecdOrClassFieldInfosUncached ((optFilter, ad), m, ty) = FoldPrimaryHierarchyOfType (fun ty acc -> GetImmediateIntrinsicRecdOrClassFieldsOfType (optFilter, ad) m ty @ acc) g amap m AllowMultiIntfInstantiations.Yes ty [] - let GetEntireTypeHierachyUncached (allowMultiIntfInst, m, ty) = + let GetEntireTypeHierarchyUncached (allowMultiIntfInst, m, ty) = FoldEntireHierarchyOfType (fun ty acc -> ty :: acc) g amap m allowMultiIntfInst ty [] - let GetPrimaryTypeHierachyUncached (allowMultiIntfInst, m, ty) = + let GetPrimaryTypeHierarchyUncached (allowMultiIntfInst, m, ty) = FoldPrimaryHierarchyOfType (fun ty acc -> ty :: acc) g amap m allowMultiIntfInst ty [] /// The primitive reader for the named items up a hierarchy @@ -316,9 +364,9 @@ type InfoReader(g: TcGlobals, amap: Import.ImportMap) = let einfos = ComputeImmediateIntrinsicEventsOfType (optFilter, ad) m ty let rfinfos = GetImmediateIntrinsicRecdOrClassFieldsOfType (optFilter, ad) m ty match acc with - | Some(MethodItem(inheritedMethSets)) when not (isNil minfos) -> Some(MethodItem (minfos::inheritedMethSets)) + | Some(MethodItem(inheritedMethSets)) when not (isNil minfos) -> Some(MethodItem (minfos :: inheritedMethSets)) | _ when not (isNil minfos) -> Some(MethodItem ([minfos])) - | Some(PropertyItem(inheritedPropSets)) when not (isNil pinfos) -> Some(PropertyItem(pinfos::inheritedPropSets)) + | Some(PropertyItem(inheritedPropSets)) when not (isNil pinfos) -> Some(PropertyItem(pinfos :: inheritedPropSets)) | _ when not (isNil pinfos) -> Some(PropertyItem([pinfos])) | _ when not (isNil finfos) -> Some(ILFieldItem(finfos)) | _ when not (isNil einfos) -> Some(EventItem(einfos)) @@ -332,6 +380,60 @@ type InfoReader(g: TcGlobals, amap: Import.ImportMap) = ty None + let GetImmediateIntrinsicOverrideMethodSetsOfType optFilter m (interfaceTys: TType list) ty acc = + match tryAppTy g ty with + | ValueSome (tcref, _) when tcref.IsILTycon && tcref.ILTyconRawMetadata.IsInterface -> + let mimpls = tcref.ILTyconRawMetadata.MethodImpls.AsList + let mdefs = tcref.ILTyconRawMetadata.Methods + + // MethodImpls contains a list of methods that override. + // OverrideBy is the method that does the overriding. + // Overrides is the method being overriden. + (acc, mimpls) + ||> List.fold (fun acc ilMethImpl -> + let overridesName = ilMethImpl.Overrides.MethodRef.Name + let overrideBy = ilMethImpl.OverrideBy + let canAccumulate = + match optFilter with + | None -> true + | Some name when name = overridesName -> true + | _ -> false + if canAccumulate then + match mdefs.TryFindInstanceByNameAndCallingSignature (overrideBy.Name, overrideBy.MethodRef.CallingSignature) with + | Some mdef -> + let overridesILTy = ilMethImpl.Overrides.DeclaringType + let overridesTyFullName = overridesILTy.TypeRef.FullName + let overridesTyOpt = + interfaceTys + |> List.tryPick (fun ty -> + match tryTcrefOfAppTy g ty with + | ValueSome tcref when tcref.IsILTycon && tcref.ILTyconRawMetadata.Name = overridesTyFullName -> + generalizedTyconRef tcref + |> Some + | _ -> + None) + match overridesTyOpt with + | Some overridesTy -> + NameMultiMap.add overridesName (overridesTy, MethInfo.CreateILMeth(amap, m, ty, mdef)) acc + | _ -> + acc + | _ -> + acc + else + acc) + | _ -> acc + + /// Visiting each type in the hierarchy and accumulate most specific methods that are the OverrideBy target from types. + let GetIntrinsicMostSpecificOverrideMethodSetsUncached ((optFilter, _ad, allowMultiIntfInst), m, ty) : NameMultiMap<_> = + let interfaceTys = + FoldPrimaryHierarchyOfType (fun ty acc -> + if isInterfaceTy g ty then ty :: acc + else acc) g amap m allowMultiIntfInst ty [] + + (NameMultiMap.Empty, interfaceTys) + ||> List.fold (fun acc ty -> GetImmediateIntrinsicOverrideMethodSetsOfType optFilter m interfaceTys ty acc) + |> FilterMostSpecificMethInfoSets g amap m + /// Make a cache for function 'f' keyed by type (plus some additional 'flags') that only /// caches computations for monomorphic types. @@ -360,7 +462,6 @@ type InfoReader(g: TcGlobals, amap: Import.ImportMap) = (match stripTyEqns g ty with | TType_app(tcref, []) -> hash tcref.LogicalName | _ -> 0) }) - let hashFlags0 = { new System.Collections.Generic.IEqualityComparer<_> with @@ -384,9 +485,23 @@ type InfoReader(g: TcGlobals, amap: Import.ImportMap) = let ilFieldInfoCache = MakeInfoCache GetIntrinsicILFieldInfosUncached hashFlags1 let eventInfoCache = MakeInfoCache GetIntrinsicEventInfosUncached hashFlags1 let namedItemsCache = MakeInfoCache GetIntrinsicNamedItemsUncached hashFlags2 + let mostSpecificOverrideMethodInfoCache = MakeInfoCache GetIntrinsicMostSpecificOverrideMethodSetsUncached hashFlags0 + + let entireTypeHierarchyCache = MakeInfoCache GetEntireTypeHierarchyUncached HashIdentity.Structural + let primaryTypeHierarchyCache = MakeInfoCache GetPrimaryTypeHierarchyUncached HashIdentity.Structural - let entireTypeHierarchyCache = MakeInfoCache GetEntireTypeHierachyUncached HashIdentity.Structural - let primaryTypeHierarchyCache = MakeInfoCache GetPrimaryTypeHierachyUncached HashIdentity.Structural + // Runtime feature support + + let isRuntimeFeatureSupported (infoReader: InfoReader) runtimeFeature = + match g.System_Runtime_CompilerServices_RuntimeFeature_ty with + | Some runtimeFeatureTy -> + infoReader.GetILFieldInfosOfType (None, AccessorDomain.AccessibleFromEverywhere, range0, runtimeFeatureTy) + |> List.exists (fun (ilFieldInfo: ILFieldInfo) -> ilFieldInfo.FieldName = runtimeFeature) + | _ -> + false + + let isRuntimeFeatureDefaultImplementationsOfInterfacesSupported = + lazy isRuntimeFeatureSupported this "DefaultImplementationsOfInterfaces" member x.g = g member x.amap = amap @@ -421,7 +536,7 @@ type InfoReader(g: TcGlobals, amap: Import.ImportMap) = | flds -> // multiple fields with the same name can come from different classes, // so filter them by the given type name - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueNone -> ValueNone | ValueSome tcref -> match flds |> List.filter (fun rfinfo -> tyconRefEq g tcref rfinfo.TyconRef) with @@ -433,14 +548,35 @@ type InfoReader(g: TcGlobals, amap: Import.ImportMap) = member x.TryFindNamedItemOfType (nm, ad, m, ty) = namedItemsCache.Apply(((nm, ad), m, ty)) + /// Read the raw method sets of a type that are the most specific overrides. Cache the result for monomorphic types + member x.GetIntrinsicMostSpecificOverrideMethodSetsOfType (optFilter, ad, allowMultiIntfInst, m, ty) = + mostSpecificOverrideMethodInfoCache.Apply(((optFilter, ad, allowMultiIntfInst), m, ty)) + /// Get the super-types of a type, including interface types. - member x.GetEntireTypeHierachy (allowMultiIntfInst, m, ty) = + member x.GetEntireTypeHierarchy (allowMultiIntfInst, m, ty) = entireTypeHierarchyCache.Apply((allowMultiIntfInst, m, ty)) /// Get the super-types of a type, excluding interface types. - member x.GetPrimaryTypeHierachy (allowMultiIntfInst, m, ty) = + member x.GetPrimaryTypeHierarchy (allowMultiIntfInst, m, ty) = primaryTypeHierarchyCache.Apply((allowMultiIntfInst, m, ty)) + /// Check if the given language feature is supported by the runtime. + member x.IsLanguageFeatureRuntimeSupported langFeature = + match langFeature with + // Both default and static interface method consumption features are tied to the runtime support of DIMs. + | LanguageFeature.DefaultInterfaceMemberConsumption -> isRuntimeFeatureDefaultImplementationsOfInterfacesSupported.Value + | _ -> true + +let private tryLanguageFeatureRuntimeErrorAux (infoReader: InfoReader) langFeature m error = + if not (infoReader.IsLanguageFeatureRuntimeSupported langFeature) then + let featureStr = infoReader.g.langVersion.GetFeatureString langFeature + error (Error(FSComp.SR.chkFeatureNotRuntimeSupported featureStr, m)) + +let tryLanguageFeatureRuntimeError infoReader langFeature m = + tryLanguageFeatureRuntimeErrorAux infoReader langFeature m error + +let tryLanguageFeatureRuntimeErrorRecover infoReader langFeature m = + tryLanguageFeatureRuntimeErrorAux infoReader langFeature m errorR /// Get the declared constructors of any F# type let rec GetIntrinsicConstructorInfosOfTypeAux (infoReader: InfoReader) m origTy metadataTy = @@ -467,7 +603,7 @@ let rec GetIntrinsicConstructorInfosOfTypeAux (infoReader: InfoReader) m origTy let betterMetadataTy = convertToTypeWithMetadataIfPossible g metadataTy GetIntrinsicConstructorInfosOfTypeAux infoReader m origTy betterMetadataTy else - match tryDestAppTy g metadataTy with + match tryTcrefOfAppTy g metadataTy with | ValueNone -> [] | ValueSome tcref -> tcref.MembersOfFSharpTyconByName @@ -509,7 +645,7 @@ type private IndexedList<'T>(itemLists: 'T list list, itemsByName: NameMultiMap< member x.ItemsWithName(nm) = NameMultiMap.find nm itemsByName /// Add new items, extracting the names using the given function. - member x.AddItems(items, nmf) = IndexedList<'T>(items::itemLists, List.foldBack (fun x acc -> NameMultiMap.add (nmf x) x acc) items itemsByName ) + member x.AddItems(items, nmf) = IndexedList<'T>(items :: itemLists, List.foldBack (fun x acc -> NameMultiMap.add (nmf x) x acc) items itemsByName ) /// Get an empty set of items static member Empty = IndexedList<'T>([], NameMultiMap.empty) @@ -662,22 +798,22 @@ let ExcludeHiddenOfPropInfos g amap m pinfos = |> List.concat /// Get the sets of intrinsic methods in the hierarchy (not including extension methods) -let GetIntrinsicMethInfoSetsOfType (infoReader: InfoReader) (optFilter, ad, allowMultiIntfInst) findFlag m ty = +let GetIntrinsicMethInfoSetsOfType (infoReader:InfoReader) optFilter ad allowMultiIntfInst findFlag m ty = infoReader.GetRawIntrinsicMethodSetsOfType(optFilter, ad, allowMultiIntfInst, m, ty) |> FilterOverridesOfMethInfos findFlag infoReader.g infoReader.amap m /// Get the sets intrinsic properties in the hierarchy (not including extension properties) -let GetIntrinsicPropInfoSetsOfType (infoReader: InfoReader) (optFilter, ad, allowMultiIntfInst) findFlag m ty = +let GetIntrinsicPropInfoSetsOfType (infoReader:InfoReader) optFilter ad allowMultiIntfInst findFlag m ty = infoReader.GetRawIntrinsicPropertySetsOfType(optFilter, ad, allowMultiIntfInst, m, ty) |> FilterOverridesOfPropInfos findFlag infoReader.g infoReader.amap m /// Get the flattened list of intrinsic methods in the hierarchy -let GetIntrinsicMethInfosOfType infoReader (optFilter, ad, allowMultiIntfInst) findFlag m ty = - GetIntrinsicMethInfoSetsOfType infoReader (optFilter, ad, allowMultiIntfInst) findFlag m ty |> List.concat +let GetIntrinsicMethInfosOfType infoReader optFilter ad allowMultiIntfInst findFlag m ty = + GetIntrinsicMethInfoSetsOfType infoReader optFilter ad allowMultiIntfInst findFlag m ty |> List.concat /// Get the flattened list of intrinsic properties in the hierarchy -let GetIntrinsicPropInfosOfType infoReader (optFilter, ad, allowMultiIntfInst) findFlag m ty = - GetIntrinsicPropInfoSetsOfType infoReader (optFilter, ad, allowMultiIntfInst) findFlag m ty |> List.concat +let GetIntrinsicPropInfosOfType infoReader optFilter ad allowMultiIntfInst findFlag m ty = + GetIntrinsicPropInfoSetsOfType infoReader optFilter ad allowMultiIntfInst findFlag m ty |> List.concat /// Perform type-directed name resolution of a particular named member in an F# type let TryFindIntrinsicNamedItemOfType (infoReader: InfoReader) (nm, ad) findFlag m ty = @@ -695,12 +831,16 @@ let TryFindIntrinsicNamedItemOfType (infoReader: InfoReader) (nm, ad) findFlag m /// -- getting the Dispose method when resolving the 'use' construct /// -- getting the various methods used to desugar the computation expression syntax let TryFindIntrinsicMethInfo infoReader m ad nm ty = - GetIntrinsicMethInfosOfType infoReader (Some nm, ad, AllowMultiIntfInstantiations.Yes) IgnoreOverrides m ty + GetIntrinsicMethInfosOfType infoReader (Some nm) ad AllowMultiIntfInstantiations.Yes IgnoreOverrides m ty /// Try to find a particular named property on a type. Only used to ensure that local 'let' definitions and property names /// are distinct, a somewhat adhoc check in tc.fs. let TryFindPropInfo infoReader m ad nm ty = - GetIntrinsicPropInfosOfType infoReader (Some nm, ad, AllowMultiIntfInstantiations.Yes) IgnoreOverrides m ty + GetIntrinsicPropInfosOfType infoReader (Some nm) ad AllowMultiIntfInstantiations.Yes IgnoreOverrides m ty + +/// Get a set of most specific override methods. +let GetIntrinisicMostSpecificOverrideMethInfoSetsOfType (infoReader: InfoReader) m ty = + infoReader.GetIntrinsicMostSpecificOverrideMethodSetsOfType (None, AccessibleFromSomewhere, AllowMultiIntfInstantiations.Yes, m, ty) //------------------------------------------------------------------------- // Helpers related to delegates and events - these use method searching hence are in this file @@ -717,7 +857,7 @@ let GetSigOfFunctionForDelegate (infoReader: InfoReader) delty m ad = let g = infoReader.g let amap = infoReader.amap let invokeMethInfo = - match GetIntrinsicMethInfosOfType infoReader (Some "Invoke", ad, AllowMultiIntfInstantiations.Yes) IgnoreOverrides m delty with + match GetIntrinsicMethInfosOfType infoReader (Some "Invoke") ad AllowMultiIntfInstantiations.Yes IgnoreOverrides m delty with | [h] -> h | [] -> error(Error(FSComp.SR.noInvokeMethodsFound (), m)) | h :: _ -> warning(InternalError(FSComp.SR.moreThanOneInvokeMethodFound (), m)); h diff --git a/src/fcs-fable/src/fsharp/InnerLambdasToTopLevelFuncs.fs b/src/fcs-fable/src/fsharp/InnerLambdasToTopLevelFuncs.fs old mode 100755 new mode 100644 index 53fa7baa3a..b21f0d2279 --- a/src/fcs-fable/src/fsharp/InnerLambdasToTopLevelFuncs.fs +++ b/src/fcs-fable/src/fsharp/InnerLambdasToTopLevelFuncs.fs @@ -6,15 +6,18 @@ open FSharp.Compiler open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Diagnostics -open FSharp.Compiler.Ast +open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.Tastops.DebugPrint -open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Layout open FSharp.Compiler.Detuple.GlobalUsageAnalysis +open FSharp.Compiler.Layout open FSharp.Compiler.Lib +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.TypedTreeOps.DebugPrint +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.XmlDoc let verboseTLR = false @@ -29,7 +32,7 @@ module Zmap = try Zmap.find k mp with e -> dprintf "Zmap.force: %s %s\n" str (soK k) - PreserveStackTrace(e) + PreserveStackTrace e raise e //------------------------------------------------------------------------- @@ -45,7 +48,7 @@ let fringeTR tr = let rec collect tr acc = match tr with | TreeNode subts -> List.foldBack collect subts acc - | LeafNode x -> x::acc + | LeafNode x -> x :: acc collect tr [] @@ -81,7 +84,7 @@ let isDelayedRepr (f: Val) e = // REVIEW: these should just be replaced by direct calls to mkLocal, mkCompGenLocal etc. // REVIEW: However these set an arity whereas the others don't let mkLocalNameTypeArity compgen m name ty topValInfo = - NewVal(name, m, None, ty, Immutable, compgen, topValInfo, taccessPublic, ValNotInRecScope, None, NormalVal, [], ValInline.Optional, XmlDoc.Empty, false, false, false, false, false, false, None, ParentNone) + Construct.NewVal(name, m, None, ty, Immutable, compgen, topValInfo, taccessPublic, ValNotInRecScope, None, NormalVal, [], ValInline.Optional, XmlDoc.Empty, false, false, false, false, false, false, None, ParentNone) //------------------------------------------------------------------------- // definitions: TLR, arity, arity-met, arity-short @@ -438,7 +441,7 @@ module Pass2_DetermineReqdItems = else {state with revDeclist = fclass :: state.revDeclist - stack = (let env = ReqdItemsForDefn.Initial reqdTypars0 m in (fclass, reqdVals0, env)::state.stack) } + stack = (let env = ReqdItemsForDefn.Initial reqdTypars0 m in (fclass, reqdVals0, env) :: state.stack) } /// POP & SAVE = end collecting for fclass and store let SaveFrame (fclass: BindingGroupSharingSameReqdItems) state = @@ -448,7 +451,7 @@ module Pass2_DetermineReqdItems = else match state.stack with | [] -> internalError "trl: popFrame has empty stack" - | (fclass, _reqdVals0, env)::stack -> (* ASSERT: same fclass *) + | (fclass, _reqdVals0, env) :: stack -> (* ASSERT: same fclass *) {state with stack = stack reqdItemsMap = Zmap.add fclass env state.reqdItemsMap @@ -743,7 +746,7 @@ let FlatEnvPacks g fclassM topValS declist (reqdItemsMap: Zmap List.tryFind (IsGenericValWithGenericContraints g) with + match vals |> List.tryFind (IsGenericValWithGenericConstraints g) with | None -> () | Some v -> raise (AbortTLR v.Range) @@ -762,7 +765,7 @@ let FlatEnvPacks g fclassM topValS declist (reqdItemsMap: Zmap List.map (fun (subv, subaenv) -> mkBind NoSequencePointAtInvisibleBinding subaenv (aenvExprFor subv)) + vaenvs |> List.map (fun (subv, subaenv) -> mkBind NoDebugPointAtInvisibleBinding subaenv (aenvExprFor subv)) List.map unpackCarrier (Zmap.toList cmap) @ List.collect unpackSubenv env.ReqdSubEnvs @@ -771,6 +774,8 @@ let FlatEnvPacks g fclassM topValS declist (reqdItemsMap: Zmap Option.isSome) + g.CompilerGlobalState.Value.NiceNameGenerator.FreshCompilerGeneratedName(name, m) let fHat = mkLocalNameTypeArity f.IsCompilerGenerated m fHatName fHatTy (Some fHatArity) fHat @@ -1120,25 +1129,25 @@ module Pass4_RewriteAssembly = // ilobj - has implicit lambda exprs and recursive/base references | Expr.Obj (_, ty, basev, basecall, overrides, iimpls, m) -> - let basecall, z = TransExpr penv z basecall - let overrides, z = List.mapFold (TransMethod penv) z overrides - let (iimpls:(TType*ObjExprMethod list)list), (z: RewriteState) = - List.mapFold (fun z (tType, objExprs) -> + let basecall, z = TransExpr penv z basecall + let overrides, z = List.mapFold (TransMethod penv) z overrides + let iimpls, z = + (z, iimpls) ||> List.mapFold (fun z (tType, objExprs) -> let objExprs', z' = List.mapFold (TransMethod penv) z objExprs - (tType, objExprs'), z') z iimpls - let expr = Expr.Obj(newUnique(), ty, basev, basecall, overrides, iimpls, m) + (tType, objExprs'), z') + let expr = Expr.Obj (newUnique(), ty, basev, basecall, overrides, iimpls, m) let pds, z = ExtractPreDecs z MakePreDecs m pds expr, z (* if TopLevel, lift preDecs over the ilobj expr *) // lambda, tlambda - explicit lambda terms - | Expr.Lambda(_, ctorThisValOpt, baseValOpt, argvs, body, m, rty) -> + | Expr.Lambda (_, ctorThisValOpt, baseValOpt, argvs, body, m, rty) -> let z = EnterInner z let body, z = TransExpr penv z body let z = ExitInner z let pds, z = ExtractPreDecs z MakePreDecs m pds (rebuildLambda m ctorThisValOpt baseValOpt argvs (body, rty)), z - | Expr.TyLambda(_, argtyvs, body, m, rty) -> + | Expr.TyLambda (_, argtyvs, body, m, rty) -> let z = EnterInner z let body, z = TransExpr penv z body let z = ExitInner z @@ -1147,7 +1156,7 @@ module Pass4_RewriteAssembly = /// Lifting TLR out over constructs (disabled) /// Lift minimally to ensure the defn is not lifted up and over defns on which it depends (disabled) - | Expr.Match(spBind, exprm, dtree, targets, m, ty) -> + | Expr.Match (spBind, exprm, dtree, targets, m, ty) -> let targets = Array.toList targets let dtree, z = TransDecisionTree penv z dtree let targets, z = List.mapFold (TransDecisionTreeTarget penv) z targets @@ -1161,19 +1170,19 @@ module Pass4_RewriteAssembly = | Expr.Quote (a,{contents=Some(typeDefs,argTypes,argExprs,data)},isFromQueryExpression,m,ty) -> let argExprs,z = List.mapFold (TransExpr penv) z argExprs - Expr.Quote(a,{contents=Some(typeDefs,argTypes,argExprs,data)},isFromQueryExpression,m,ty),z + Expr.Quote (a,{contents=Some(typeDefs,argTypes,argExprs,data)},isFromQueryExpression,m,ty),z | Expr.Quote (a,{contents=None},isFromQueryExpression,m,ty) -> - Expr.Quote(a,{contents=None},isFromQueryExpression,m,ty),z + Expr.Quote (a,{contents=None},isFromQueryExpression,m,ty),z | Expr.Op (c,tyargs,args,m) -> let args,z = List.mapFold (TransExpr penv) z args - Expr.Op(c,tyargs,args,m),z + Expr.Op (c,tyargs,args,m),z | Expr.StaticOptimization (constraints,e2,e3,m) -> let e2,z = TransExpr penv z e2 let e3,z = TransExpr penv z e3 - Expr.StaticOptimization(constraints,e2,e3,m),z + Expr.StaticOptimization (constraints,e2,e3,m),z | Expr.TyChoose (_,_,m) -> error(Error(FSComp.SR.tlrUnexpectedTExpr(),m)) @@ -1185,7 +1194,7 @@ module Pass4_RewriteAssembly = | Expr.Sequential (e1, e2, dir, spSeq, m) -> let e1, z = TransExpr penv z e1 TransLinearExpr penv z e2 (contf << (fun (e2, z) -> - Expr.Sequential(e1, e2, dir, spSeq, m), z)) + Expr.Sequential (e1, e2, dir, spSeq, m), z)) // letrec - pass_recbinds does the work | Expr.LetRec (binds, e, m, _) -> @@ -1204,7 +1213,7 @@ module Pass4_RewriteAssembly = // tailcall TransLinearExpr penv z e (contf << (fun (e, z) -> let e = mkLetsFromBindings m rebinds e - MakePreDecs m pds (Expr.LetRec (binds, e, m, NewFreeVarsCache())), z)) + MakePreDecs m pds (Expr.LetRec (binds, e, m, Construct.NewFreeVarsCache())), z)) // let - can consider the mu-let bindings as mu-letrec bindings - so like as above | Expr.Let (bind, e, m, _) -> @@ -1295,12 +1304,12 @@ module Pass4_RewriteAssembly = | TMDefDo(e, m) -> let _bind, z = TransExpr penv z e TMDefDo(e, m), z - | TMDefs(defs) -> + | TMDefs defs -> let defs, z = TransModuleDefs penv z defs - TMDefs(defs), z - | TMAbstract(mexpr) -> + TMDefs defs, z + | TMAbstract mexpr -> let mexpr, z = TransModuleExpr penv z mexpr - TMAbstract(mexpr), z + TMAbstract mexpr, z and TransModuleBindings penv z binds = List.mapFold (TransModuleBinding penv) z binds and TransModuleBinding penv z x = match x with @@ -1311,9 +1320,9 @@ module Pass4_RewriteAssembly = let rhs, z = TransModuleDef penv z rhs ModuleOrNamespaceBinding.Module(nm, rhs), z - let TransImplFile penv z (TImplFile(fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes)) = + let TransImplFile penv z (TImplFile (fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes)) = let moduleExpr, z = TransModuleExpr penv z moduleExpr - (TImplFile(fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes)), z + (TImplFile (fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes)), z //------------------------------------------------------------------------- // pass5: copyExpr diff --git a/src/fcs-fable/src/fsharp/InnerLambdasToTopLevelFuncs.fsi b/src/fcs-fable/src/fsharp/InnerLambdasToTopLevelFuncs.fsi old mode 100755 new mode 100644 index 5a25c27ac5..897952add3 --- a/src/fcs-fable/src/fsharp/InnerLambdasToTopLevelFuncs.fsi +++ b/src/fcs-fable/src/fsharp/InnerLambdasToTopLevelFuncs.fsi @@ -2,7 +2,7 @@ module internal FSharp.Compiler.InnerLambdasToTopLevelFuncs -open FSharp.Compiler +open FSharp.Compiler.TypedTree open FSharp.Compiler.TcGlobals -val MakeTLRDecisions : Tast.CcuThunk -> TcGlobals -> Tast.TypedImplFile -> Tast.TypedImplFile +val MakeTLRDecisions : CcuThunk -> TcGlobals -> TypedImplFile -> TypedImplFile diff --git a/src/fcs-fable/src/fsharp/InternalCollections.fs b/src/fcs-fable/src/fsharp/InternalCollections.fs index 8713eef00f..6ffb9f0680 100755 --- a/src/fcs-fable/src/fsharp/InternalCollections.fs +++ b/src/fcs-fable/src/fsharp/InternalCollections.fs @@ -2,7 +2,6 @@ namespace Internal.Utilities.Collections open System -open System.Collections.Generic [] type internal ValueStrength<'T when 'T : not struct> = @@ -39,7 +38,7 @@ type internal AgedLookup<'Token, 'Key, 'Value when 'Value : not struct>(keepStro // This function returns true if two keys are the same according to the predicate // function passed in. | []->None - | (similarKey,value)::t-> + | (similarKey,value) :: t-> if areSimilar(key,similarKey) then Some(similarKey,value) else Lookup key t Lookup key data @@ -84,18 +83,18 @@ type internal AgedLookup<'Token, 'Key, 'Value when 'Value : not struct>(keepStro | true, value -> yield key, value ] #endif - let AssignWithStrength(tok,newdata,discard1) = - let actualLength = List.length newdata + let AssignWithStrength(tok,newData,discard1) = + let actualLength = List.length newData let tossThreshold = max 0 (actualLength - keepMax) // Delete everything less than this threshold - let weakThreshhold = max 0 (actualLength - keepStrongly) // Weaken everything less than this threshold + let weakThreshold = max 0 (actualLength - keepStrongly) // Weaken everything less than this threshold - let newdata = newdata|> List.mapi( fun n kv -> n,kv ) // Place the index. - let newdata,discard2 = newdata |> List.partition (fun (n:int,v) -> n >= tossThreshold || requiredToKeep (snd v)) - let newdata = - newdata + let newData = newData|> List.mapi( fun n kv -> n,kv ) // Place the index. + let newData,discard2 = newData |> List.partition (fun (n:int,v) -> n >= tossThreshold || requiredToKeep (snd v)) + let newData = + newData |> List.map( fun (n:int,(k,v)) -> let handle = - if n(keepStro Strong(v) k,handle ) ignore tok // Updating refs requires tok - refs <- newdata + refs <- newData discard1 |> List.iter (snd >> strongDiscard) discard2 |> List.iter (snd >> snd >> strongDiscard) @@ -117,14 +116,14 @@ type internal AgedLookup<'Token, 'Key, 'Value when 'Value : not struct>(keepStro member al.TryGetKeyValue(tok, key) = let data = FilterAndHold(tok) - let result,newdata = TryGetKeyValueImpl(data,key) - AssignWithStrength(tok,newdata,[]) + let result,newData = TryGetKeyValueImpl(data,key) + AssignWithStrength(tok,newData,[]) result member al.TryGet(tok, key) = let data = FilterAndHold(tok) - let result,newdata = TryGetKeyValueImpl(data,key) - AssignWithStrength(tok,newdata,[]) + let result,newData = TryGetKeyValueImpl(data,key) + AssignWithStrength(tok,newData,[]) match result with | Some(_,value) -> Some(value) | None -> None @@ -137,8 +136,8 @@ type internal AgedLookup<'Token, 'Key, 'Value when 'Value : not struct>(keepStro member al.Remove(tok, key) = let data = FilterAndHold(tok) - let newdata,discard = RemoveImpl (data,key) - AssignWithStrength(tok,newdata,discard) + let newData,discard = RemoveImpl (data,key) + AssignWithStrength(tok,newData,discard) member al.Clear(tok) = let discards = FilterAndHold(tok) diff --git a/src/fcs-fable/src/fsharp/LanguageFeatures.fs b/src/fcs-fable/src/fsharp/LanguageFeatures.fs new file mode 100644 index 0000000000..05572cfb9e --- /dev/null +++ b/src/fcs-fable/src/fsharp/LanguageFeatures.fs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +/// Coordinating compiler operations - configuration, loading initial context, reporting errors etc. +module internal FSharp.Compiler.Features + +open System + +//------------------------------------------------------------------------------------------------------------------ +// Language version command line switch +//------------------------------------------------------------------------------------------------------------------ +// Add your features to this List - in code use languageVersion.SupportsFeature(LanguageFeatures.yourFeature) +// a return value of false means your feature is not supported by the user's language selection +// All new language features added from now on must be protected by this. +// Note: +// * The fslang design process will require a decision about feature name and whether it is required. +// * When a feature is assigned a release language, we will scrub the code of feature references and apply +// the Release Language version. + +[] +type LanguageFeature = + | SingleUnderscorePattern + | WildCardInForLoop + | RelaxWhitespace + | NameOf + | ImplicitYield + | OpenStaticClasses + | DotlessFloat32Literal + | PackageManagement + | FromEndSlicing + | FixedIndexSlice3d4d + | AndBang + | NullableOptionalInterop + | DefaultInterfaceMemberConsumption + +/// LanguageVersion management +type LanguageVersion (specifiedVersionAsString) = + + // When we increment language versions here preview is higher than current RTM version + static let languageVersion46 = 4.6m + static let languageVersion47 = 4.7m + static let languageVersion50 = 5.0m + static let previewVersion = 9999m // Language version when preview specified + static let defaultVersion = languageVersion47 // Language version when default specified + static let latestVersion = defaultVersion // Language version when latest specified + static let latestMajorVersion = languageVersion47 // Language version when latestmajor specified + + static let validOptions = [| "preview"; "default"; "latest"; "latestmajor" |] + static let languageVersions = set [| languageVersion46; languageVersion47 (*; languageVersion50 *) |] + + static let features = + dict [ + // F# 4.7 + LanguageFeature.SingleUnderscorePattern, languageVersion47 + LanguageFeature.WildCardInForLoop, languageVersion47 + LanguageFeature.RelaxWhitespace, languageVersion47 + LanguageFeature.ImplicitYield, languageVersion47 + + // F# 5.0 + LanguageFeature.FixedIndexSlice3d4d, languageVersion50 + LanguageFeature.FromEndSlicing, languageVersion50 + LanguageFeature.DotlessFloat32Literal, languageVersion50 + + // F# preview + LanguageFeature.NameOf, previewVersion + LanguageFeature.OpenStaticClasses, previewVersion + LanguageFeature.PackageManagement, previewVersion + LanguageFeature.AndBang, previewVersion + LanguageFeature.NullableOptionalInterop, previewVersion + LanguageFeature.DefaultInterfaceMemberConsumption, previewVersion + ] + + let specified = + match specifiedVersionAsString with + | "?" -> 0m + | "preview" -> previewVersion + | "default" -> defaultVersion + | "latest" -> latestVersion + | "latestmajor" -> latestMajorVersion + | "4.6" -> languageVersion46 + | "4.7" -> languageVersion47 +(* | "5.0" -> languageVersion50 *) + | _ -> 0m + + let versionToString v = + if v = previewVersion then "'preview'" + else string v + + let specifiedString = versionToString specified + + /// Check if this feature is supported by the selected langversion + member _.SupportsFeature featureId = + match features.TryGetValue featureId with + | true, v -> v <= specified + | false, _ -> false + + /// Has preview been explicitly specified + member _.IsPreviewEnabled = + specified = previewVersion + + /// Does the languageVersion support this version string + member _.ContainsVersion version = + match version with + | "?" | "preview" | "default" | "latest" | "latestmajor" -> true + | _ -> languageVersions.Contains specified + + /// Get a list of valid strings for help text + member _.ValidOptions = validOptions + + /// Get a list of valid versions for help text + member _.ValidVersions = + [| + for v in languageVersions |> Seq.sort -> + sprintf "%M%s" v (if v = defaultVersion then " (Default)" else "") + |] + + /// Get the specified LanguageVersion + member _.SpecifiedVersion = specified + + /// Get the specified LanguageVersion as a string + member _.SpecifiedVersionString = specifiedString + + /// Get a string name for the given feature. + member _.GetFeatureString feature = + match feature with + | LanguageFeature.SingleUnderscorePattern -> FSComp.SR.featureSingleUnderscorePattern() + | LanguageFeature.WildCardInForLoop -> FSComp.SR.featureWildCardInForLoop() + | LanguageFeature.RelaxWhitespace -> FSComp.SR.featureRelaxWhitespace() + | LanguageFeature.NameOf -> FSComp.SR.featureNameOf() + | LanguageFeature.ImplicitYield -> FSComp.SR.featureImplicitYield() + | LanguageFeature.OpenStaticClasses -> FSComp.SR.featureOpenStaticClasses() + | LanguageFeature.DotlessFloat32Literal -> FSComp.SR.featureDotlessFloat32Literal() + | LanguageFeature.PackageManagement -> FSComp.SR.featurePackageManagement() + | LanguageFeature.FromEndSlicing -> FSComp.SR.featureFromEndSlicing() + | LanguageFeature.FixedIndexSlice3d4d -> FSComp.SR.featureFixedIndexSlice3d4d() + | LanguageFeature.AndBang -> FSComp.SR.featureAndBang() + | LanguageFeature.NullableOptionalInterop -> FSComp.SR.featureNullableOptionalInterop() + | LanguageFeature.DefaultInterfaceMemberConsumption -> FSComp.SR.featureDefaultInterfaceMemberConsumption() + + /// Get a version string associated with the given feature. + member _.GetFeatureVersionString feature = + match features.TryGetValue feature with + | true, v -> versionToString v + | _ -> invalidArg "feature" "Internal error: Unable to find feature." diff --git a/src/fcs-fable/src/fsharp/LanguageFeatures.fsi b/src/fcs-fable/src/fsharp/LanguageFeatures.fsi new file mode 100644 index 0000000000..fd367388bd --- /dev/null +++ b/src/fcs-fable/src/fsharp/LanguageFeatures.fsi @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +/// Coordinating compiler operations - configuration, loading initial context, reporting errors etc. +module internal FSharp.Compiler.Features + +/// LanguageFeature enumeration +[] +type LanguageFeature = + | SingleUnderscorePattern + | WildCardInForLoop + | RelaxWhitespace + | NameOf + | ImplicitYield + | OpenStaticClasses + | DotlessFloat32Literal + | PackageManagement + | FromEndSlicing + | FixedIndexSlice3d4d + | AndBang + | NullableOptionalInterop + | DefaultInterfaceMemberConsumption + +/// LanguageVersion management +type LanguageVersion = + + /// Create a LanguageVersion management object + new: string -> LanguageVersion + + /// Get the list of valid versions + member ContainsVersion: string -> bool + + /// Has preview been explicitly specified + member IsPreviewEnabled: bool + + /// Does the selected LanguageVersion support the specified feature + member SupportsFeature: LanguageFeature -> bool + + /// Get the list of valid versions + member ValidVersions: string array + + /// Get the list of valid options + member ValidOptions: string array + + /// Get the specified LanguageVersion + member SpecifiedVersion: decimal + + /// Get the specified LanguageVersion as a string + member SpecifiedVersionString: string + + /// Get a string name for the given feature. + member GetFeatureString: feature: LanguageFeature -> string + + /// Get a version string associated with the given feature. + member GetFeatureVersionString: feature: LanguageFeature -> string diff --git a/src/fcs-fable/src/fsharp/LegacyHostedCompilerForTesting.fs b/src/fcs-fable/src/fsharp/LegacyHostedCompilerForTesting.fs index c13af60671..d1c536999f 100644 --- a/src/fcs-fable/src/fsharp/LegacyHostedCompilerForTesting.fs +++ b/src/fcs-fable/src/fsharp/LegacyHostedCompilerForTesting.fs @@ -61,20 +61,20 @@ type internal InProcCompiler(legacyReferenceResolver) = let ctok = AssumeCompilationThreadWithoutEvidence () let loggerProvider = InProcErrorLoggerProvider() - let exitCode = ref 0 + let mutable exitCode = 0 let exiter = { new Exiter with - member this.Exit n = exitCode := n; raise StopProcessing } + member this.Exit n = exitCode <- n; raise StopProcessing } try typecheckAndCompile(ctok, argv, legacyReferenceResolver, false, ReduceMemoryFlag.Yes, CopyFSharpCoreFlag.Yes, exiter, loggerProvider.Provider, None, None) with | StopProcessing -> () | ReportedError _ | WrappedError(ReportedError _,_) -> - exitCode := 1 + exitCode <- 1 () let output : CompilationOutput = { Warnings = loggerProvider.CapturedWarnings; Errors = loggerProvider.CapturedErrors } - !exitCode = 0, output + exitCode = 0, output /// in-proc version of fsc.exe type internal FscCompiler(legacyReferenceResolver) = diff --git a/src/fcs-fable/src/fsharp/MSBuildReferenceResolver.fs b/src/fcs-fable/src/fsharp/LegacyMSBuildReferenceResolver.fs similarity index 98% rename from src/fcs-fable/src/fsharp/MSBuildReferenceResolver.fs rename to src/fcs-fable/src/fsharp/LegacyMSBuildReferenceResolver.fs index 1a49c6a0fc..c0f2596c39 100644 --- a/src/fcs-fable/src/fsharp/MSBuildReferenceResolver.fs +++ b/src/fcs-fable/src/fsharp/LegacyMSBuildReferenceResolver.fs @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -module internal FSharp.Compiler.MSBuildReferenceResolver +module LegacyMSBuildReferenceResolver open System open System.IO @@ -16,6 +16,7 @@ module internal FSharp.Compiler.MSBuildReferenceResolver open Microsoft.Build.Tasks open Microsoft.Build.Utilities open Microsoft.Build.Framework + open FSharp.Compiler // Reflection wrapper for properties type System.Object with @@ -254,12 +255,12 @@ module internal FSharp.Compiler.MSBuildReferenceResolver "Software\Microsoft\.NetFramework", "AssemblyFoldersEx" , "" if Array.isEmpty references then [| |] else - let backgroundException = ref false + let mutable backgroundException = false let protect f = - if not !backgroundException then + if not backgroundException then try f() - with _ -> backgroundException := true + with _ -> backgroundException <- true let engine = { new IBuildEngine with @@ -343,7 +344,7 @@ module internal FSharp.Compiler.MSBuildReferenceResolver #if ENABLE_MONO_SUPPORT // The properties TargetedRuntimeVersion and CopyLocalDependenciesWhenParentReferenceInGac // are not available on Mono. So we only set them if available (to avoid a compile-time dependency). - if not FSharp.Compiler.AbstractIL.IL.runningOnMono then + if not FSharp.Compiler.AbstractIL.Internal.Utils.runningOnMono then typeof.InvokeMember("TargetedRuntimeVersion",(BindingFlags.Instance ||| BindingFlags.SetProperty ||| BindingFlags.Public),null,rar,[| box targetedRuntimeVersionValue |]) |> ignore typeof.InvokeMember("CopyLocalDependenciesWhenParentReferenceInGac",(BindingFlags.Instance ||| BindingFlags.SetProperty ||| BindingFlags.Public),null,rar,[| box true |]) |> ignore #else @@ -367,7 +368,7 @@ module internal FSharp.Compiler.MSBuildReferenceResolver resolvedFiles - let Resolver = + let getResolver () = { new ReferenceResolver.Resolver with member __.HighestInstalledNetFrameworkVersion() = HighestInstalledRefAssembliesOrDotNETFramework() member __.DotNetFrameworkReferenceAssembliesRootDirectory = DotNetFrameworkReferenceAssembliesRootDirectory diff --git a/src/fcs-fable/src/fsharp/LegacyMSBuildReferenceResolver.fsi b/src/fcs-fable/src/fsharp/LegacyMSBuildReferenceResolver.fsi new file mode 100644 index 0000000000..1b4aa72858 --- /dev/null +++ b/src/fcs-fable/src/fsharp/LegacyMSBuildReferenceResolver.fsi @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. +module LegacyMSBuildReferenceResolver + +open FSharp.Compiler + +val getResolver: unit -> ReferenceResolver.Resolver \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/LexFilter.fs b/src/fcs-fable/src/fsharp/LexFilter.fs index 157b5bba3e..d4e7608a7c 100755 --- a/src/fcs-fable/src/fsharp/LexFilter.fs +++ b/src/fcs-fable/src/fsharp/LexFilter.fs @@ -1,20 +1,19 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. /// LexFilter - process the token stream prior to parsing. -/// Implements the offside rule and a copule of other lexical transformations. +/// Implements the offside rule and a couple of other lexical transformations. module internal FSharp.Compiler.LexFilter open Internal.Utilities.Text.Lexing open FSharp.Compiler -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Diagnostics -open FSharp.Compiler.Ast open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Parser +open FSharp.Compiler.Features open FSharp.Compiler.Lexhelp - +open FSharp.Compiler.ParseHelpers +open FSharp.Compiler.Parser +open FSharp.Compiler.SyntaxTree let debug = false let stringOfPos (p: Position) = sprintf "(%d:%d)" p.OriginalLine p.Column @@ -196,7 +195,7 @@ let rec isIfBlockContinuator token = | END | RPAREN -> true // The following arise during reprocessing of the inserted tokens, e.g. when we hit a DONE | ORIGHT_BLOCK_END | OBLOCKEND | ODECLEND -> true - | ODUMMY(token) -> isIfBlockContinuator(token) + | ODUMMY token -> isIfBlockContinuator token | _ -> false /// Determine the token that may align with the 'try' of a 'try/catch' or 'try/finally' without closing @@ -209,14 +208,14 @@ let rec isTryBlockContinuator token = | FINALLY | WITH -> true // The following arise during reprocessing of the inserted tokens when we hit a DONE | ORIGHT_BLOCK_END | OBLOCKEND | ODECLEND -> true - | ODUMMY(token) -> isTryBlockContinuator(token) + | ODUMMY token -> isTryBlockContinuator token | _ -> false let rec isThenBlockContinuator token = match token with // The following arise during reprocessing of the inserted tokens when we hit a DONE | ORIGHT_BLOCK_END | OBLOCKEND | ODECLEND -> true - | ODUMMY(token) -> isThenBlockContinuator(token) + | ODUMMY token -> isThenBlockContinuator token | _ -> false let rec isDoContinuator token = @@ -228,7 +227,7 @@ let rec isDoContinuator token = // done *) | DONE -> true | ORIGHT_BLOCK_END | OBLOCKEND | ODECLEND -> true // The following arise during reprocessing of the inserted tokens when we hit a DONE - | ODUMMY(token) -> isDoContinuator(token) + | ODUMMY token -> isDoContinuator token | _ -> false let rec isInterfaceContinuator token = @@ -239,7 +238,7 @@ let rec isInterfaceContinuator token = // end | END -> true | ORIGHT_BLOCK_END | OBLOCKEND | ODECLEND -> true // The following arise during reprocessing of the inserted tokens when we hit a DONE - | ODUMMY(token) -> isInterfaceContinuator(token) + | ODUMMY token -> isInterfaceContinuator token | _ -> false let rec isNamespaceContinuator token = @@ -250,7 +249,7 @@ let rec isNamespaceContinuator token = // namespace <-- here // .... | Parser.EOF _ | NAMESPACE -> false - | ODUMMY(token) -> isNamespaceContinuator token + | ODUMMY token -> isNamespaceContinuator token | _ -> true // anything else is a namespace continuator let rec isTypeContinuator token = @@ -276,7 +275,7 @@ let rec isTypeContinuator token = // The following arise during reprocessing of the inserted tokens when we hit a DONE | ORIGHT_BLOCK_END | OBLOCKEND | ODECLEND -> true - | ODUMMY(token) -> isTypeContinuator(token) + | ODUMMY token -> isTypeContinuator token | _ -> false let rec isForLoopContinuator token = @@ -287,7 +286,7 @@ let rec isForLoopContinuator token = // done | DONE -> true | ORIGHT_BLOCK_END | OBLOCKEND | ODECLEND -> true// The following arise during reprocessing of the inserted tokens when we hit a DONE - | ODUMMY(token) -> isForLoopContinuator(token) + | ODUMMY token -> isForLoopContinuator token | _ -> false let rec isWhileBlockContinuator token = @@ -298,7 +297,7 @@ let rec isWhileBlockContinuator token = // done | DONE -> true | ORIGHT_BLOCK_END | OBLOCKEND | ODECLEND -> true // The following arise during reprocessing of the inserted tokens when we hit a DONE - | ODUMMY(token) -> isWhileBlockContinuator(token) + | ODUMMY token -> isWhileBlockContinuator token | _ -> false let rec isLetContinuator token = @@ -308,7 +307,7 @@ let rec isLetContinuator token = // and ... | AND -> true | ORIGHT_BLOCK_END | OBLOCKEND | ODECLEND -> true // The following arise during reprocessing of the inserted tokens when we hit a DONE - | ODUMMY(token) -> isLetContinuator(token) + | ODUMMY token -> isLetContinuator token | _ -> false let rec isTypeSeqBlockElementContinuator token = @@ -321,7 +320,7 @@ let rec isTypeSeqBlockElementContinuator token = // member x.M2 | BAR -> true | OBLOCKBEGIN | ORIGHT_BLOCK_END | OBLOCKEND | ODECLEND -> true // The following arise during reprocessing of the inserted tokens when we hit a DONE - | ODUMMY(token) -> isTypeSeqBlockElementContinuator token + | ODUMMY token -> isTypeSeqBlockElementContinuator token | _ -> false // Work out when a token doesn't terminate a single item in a sequence definition @@ -345,7 +344,7 @@ let rec isSeqBlockElementContinuator token = // The following arise during reprocessing of the inserted tokens when we hit a DONE | ORIGHT_BLOCK_END | OBLOCKEND | ODECLEND -> true - | ODUMMY(token) -> isSeqBlockElementContinuator token + | ODUMMY token -> isSeqBlockElementContinuator token | _ -> false let rec isWithAugmentBlockContinuator token = @@ -356,7 +355,7 @@ let rec isWithAugmentBlockContinuator token = // member ... // end | END -> true - | ODUMMY(token) -> isWithAugmentBlockContinuator(token) + | ODUMMY token -> isWithAugmentBlockContinuator token | _ -> false let isLongIdentifier token = (match token with IDENT _ | DOT -> true | _ -> false) @@ -401,39 +400,72 @@ type LexbufState(startPos: Position, member x.EndPos = endPos member x.PastEOF = pastEOF -[] -type PositionTuple = - val X: Position - val Y: Position - new (x: Position, y: Position) = { X = x; Y = y } - /// Used to save the state related to a token +/// Treat as though this is read-only. [] type TokenTup = - val Token : token - val LexbufState : LexbufState - val LastTokenPos: PositionTuple + // This is mutable for performance reasons. + val mutable Token : token + val mutable LexbufState : LexbufState + val mutable LastTokenPos: Position new (token, state, lastTokenPos) = { Token=token; LexbufState=state;LastTokenPos=lastTokenPos } /// Returns starting position of the token member x.StartPos = x.LexbufState.StartPos /// Returns end position of the token member x.EndPos = x.LexbufState.EndPos - + +type TokenTupPool() = + + /// Arbitrary. + /// When parsing the compiler's source files, the pool didn't come close to reaching this limit. + /// Therefore, this seems like a reasonable limit to handle 99% of cases. + [] + let maxSize = 100 + +#if FABLE_COMPILER + let stack = Internal.Utilities.Text.Parsing.Stack<_>(maxSize) + do for i = 1 to maxSize do + stack.Push(TokenTup(Unchecked.defaultof<_>, Unchecked.defaultof<_>, Unchecked.defaultof<_>)) +#else + let stack = System.Collections.Generic.Stack(Array.init maxSize (fun _ -> TokenTup(Unchecked.defaultof<_>, Unchecked.defaultof<_>, Unchecked.defaultof<_>))) +#endif + + member _.Rent() = + if stack.Count = 0 then + assert false + TokenTup(Unchecked.defaultof<_>, Unchecked.defaultof<_>, Unchecked.defaultof<_>) + else + stack.Pop() + + member _.Return(x: TokenTup) = + x.Token <- Unchecked.defaultof<_> + x.LexbufState <- Unchecked.defaultof<_> + x.LastTokenPos <- Unchecked.defaultof<_> + if stack.Count >= maxSize then + assert false + else + stack.Push x + /// Returns a token 'tok' with the same position as this token - member x.UseLocation(tok) = + member pool.UseLocation(x: TokenTup, tok) = let tokState = x.LexbufState - TokenTup(tok, LexbufState(tokState.StartPos, tokState.EndPos, false), x.LastTokenPos) + let tokTup = pool.Rent() + tokTup.Token <- tok + tokTup.LexbufState <- LexbufState(tokState.StartPos, tokState.EndPos, false) + tokTup.LastTokenPos <- x.LastTokenPos + tokTup /// Returns a token 'tok' with the same position as this token, except that /// it is shifted by specified number of characters from the left and from the right /// Note: positive value means shift to the right in both cases - member x.UseShiftedLocation(tok, shiftLeft, shiftRight) = - let tokState = x.LexbufState - TokenTup(tok, LexbufState(tokState.StartPos.ShiftColumnBy(shiftLeft), - tokState.EndPos.ShiftColumnBy(shiftRight), false), x.LastTokenPos) - - + member pool.UseShiftedLocation(x: TokenTup, tok, shiftLeft, shiftRight) = + let tokState = x.LexbufState + let tokTup = pool.Rent() + tokTup.Token <- tok + tokTup.LexbufState <- LexbufState(tokState.StartPos.ShiftColumnBy shiftLeft, tokState.EndPos.ShiftColumnBy shiftRight, false) + tokTup.LastTokenPos <- x.LastTokenPos + tokTup //---------------------------------------------------------------------------- // Utilities for the tokenizer that are needed in other places @@ -472,20 +504,20 @@ let (|TyparsCloseOp|_|) (txt: string) = | ('!' :: '=' :: _) | ('<' :: _) | ('>' :: _) - | ('$' :: _) -> Some (INFIX_COMPARE_OP(s)) - | ('&' :: _) -> Some (INFIX_AMP_OP(s)) - | ('|' :: _) -> Some (INFIX_BAR_OP(s)) + | ('$' :: _) -> Some (INFIX_COMPARE_OP s) + | ('&' :: _) -> Some (INFIX_AMP_OP s) + | ('|' :: _) -> Some (INFIX_BAR_OP s) | ('!' :: _) | ('?' :: _) - | ('~' :: _) -> Some (PREFIX_OP(s)) + | ('~' :: _) -> Some (PREFIX_OP s) | ('@' :: _) - | ('^' :: _) -> Some (INFIX_AT_HAT_OP(s)) + | ('^' :: _) -> Some (INFIX_AT_HAT_OP s) | ('+' :: _) - | ('-' :: _) -> Some (PLUS_MINUS_OP(s)) - | ('*' :: '*' :: _) -> Some (INFIX_STAR_STAR_OP(s)) + | ('-' :: _) -> Some (PLUS_MINUS_OP s) + | ('*' :: '*' :: _) -> Some (INFIX_STAR_STAR_OP s) | ('*' :: _) | ('/' :: _) - | ('%' :: _) -> Some (INFIX_STAR_DIV_MOD_OP(s)) + | ('%' :: _) -> Some (INFIX_STAR_DIV_MOD_OP s) | _ -> None Some([| for _c in angles do yield GREATER |], afterOp) @@ -543,6 +575,12 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | Parser.EOF _ -> tokenTup.LexbufState.StartPos.ColumnMinusOne | _ -> tokenTup.LexbufState.StartPos + //---------------------------------------------------------------------------- + // TokenTup pool + //-------------------------------------------------------------------------- + + let pool = TokenTupPool() + //---------------------------------------------------------------------------- // Part II. The state of the new lex stream object. //-------------------------------------------------------------------------- @@ -554,7 +592,6 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, let runWrappedLexerInConsistentLexbufState() = let state = if haveLexbufState then savedLexbufState else getLexbufState() setLexbufState state - let lastTokenStart = state.StartPos let lastTokenEnd = state.EndPos let token = lexer lexbuf // Now we've got the token, remember the lexbuf state, associating it with the token @@ -562,7 +599,12 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, let tokenLexbufState = getLexbufState() savedLexbufState <- tokenLexbufState haveLexbufState <- true - TokenTup(token, tokenLexbufState, PositionTuple(lastTokenStart, lastTokenEnd)) + + let tokenTup = pool.Rent() + tokenTup.Token <- token + tokenTup.LexbufState <- tokenLexbufState + tokenTup.LastTokenPos <- lastTokenEnd + tokenTup //---------------------------------------------------------------------------- // Fetch a raw token, either from the old lexer or from our delayedStack @@ -634,15 +676,15 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, //-------------------------------------------------------------------------- let pushCtxt tokenTup (newCtxt: Context) = - let rec unindentationLimit strict stack = + let rec undentationLimit strict stack = match newCtxt, stack with | _, [] -> PositionWithColumn(newCtxt.StartPos, -1) // ignore Vanilla because a SeqBlock is always coming - | _, (CtxtVanilla _ :: rest) -> unindentationLimit strict rest + | _, (CtxtVanilla _ :: rest) -> undentationLimit strict rest - | _, (CtxtSeqBlock _ :: rest) when not strict -> unindentationLimit strict rest - | _, (CtxtParen _ :: rest) when not strict -> unindentationLimit strict rest + | _, (CtxtSeqBlock _ :: rest) when not strict -> undentationLimit strict rest + | _, (CtxtParen _ :: rest) when not strict -> undentationLimit strict rest // 'begin match' limited by minimum of two // '(match' limited by minimum of two @@ -662,7 +704,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // Otherwise 'function ...' places no limit until we hit a CtxtLetDecl etc... (Recursive) | (CtxtMatchClauses _), (CtxtFunction _ :: rest) - -> unindentationLimit false rest + -> undentationLimit false rest // 'try ... with' limited by 'try' | _, (CtxtMatchClauses _ :: (CtxtTry _ as limitCtxt) :: _rest) @@ -670,7 +712,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // 'fun ->' places no limit until we hit a CtxtLetDecl etc... (Recursive) | _, (CtxtFun _ :: rest) - -> unindentationLimit false rest + -> undentationLimit false rest // 'f ...{' places no limit until we hit a CtxtLetDecl etc... // 'f ...[' places no limit until we hit a CtxtLetDecl etc... @@ -678,7 +720,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | _, (CtxtParen ((LBRACE | LBRACK | LBRACK_BAR), _) :: CtxtSeqBlock _ :: rest) | _, (CtxtParen ((LBRACE | LBRACK | LBRACK_BAR), _) :: CtxtVanilla _ :: CtxtSeqBlock _ :: rest) | _, (CtxtSeqBlock _ :: CtxtParen((LBRACE | LBRACK | LBRACK_BAR), _) :: CtxtVanilla _ :: CtxtSeqBlock _ :: rest) - -> unindentationLimit false rest + -> undentationLimit false rest // MAJOR PERMITTED UNDENTATION This is allowing: // if x then y else @@ -700,7 +742,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | CtxtWithAsAugment _, ((CtxtInterfaceHead _ | CtxtMemberHead _ | CtxtException _ | CtxtTypeDefns _) as limitCtxt :: _rest) -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol) - // Permit unindentation via parentheses (or begin/end) following a 'then', 'else' or 'do': + // Permit undentation via parentheses (or begin/end) following a 'then', 'else' or 'do': // if nr > 0 then ( // nr <- nr - 1 // acc <- d @@ -723,7 +765,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // end | _, ((CtxtWithAsAugment _ | CtxtThen _ | CtxtElse _ | CtxtDo _ ) :: rest) - -> unindentationLimit false rest + -> undentationLimit false rest // '... (function ->' places no limit until we hit a CtxtLetDecl etc.... (Recursive) @@ -741,7 +783,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // 0 // | 2 -> ... <---- not allowed | _, (CtxtFunction _ :: rest) - -> unindentationLimit false rest + -> undentationLimit false rest // 'module ... : sig' limited by 'module' // 'module ... : struct' limited by 'module' @@ -768,8 +810,17 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // 'type C = class ... ' limited by 'type' // 'type C = interface ... ' limited by 'type' // 'type C = struct ... ' limited by 'type' - | _, (CtxtParen ((CLASS | STRUCT | INTERFACE), _) :: CtxtSeqBlock _ :: (CtxtTypeDefns _ as limitCtxt) :: _) - -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol + 1) + | _, (CtxtParen ((CLASS | STRUCT | INTERFACE), _) :: CtxtSeqBlock _ :: (CtxtTypeDefns _ as limitCtxt) :: _) + -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol + 1) + + // 'type C(' limited by 'type' + | _, (CtxtSeqBlock _ :: CtxtParen(LPAREN, _) :: (CtxtTypeDefns _ as limitCtxt) :: _ ) + // 'static member C(' limited by 'static', likewise others + | _, (CtxtSeqBlock _ :: CtxtParen(LPAREN, _) :: (CtxtMemberHead _ as limitCtxt) :: _ ) + // 'static member P with get() = ' limited by 'static', likewise others + | _, (CtxtWithAsLet _ :: (CtxtMemberHead _ as limitCtxt) :: _ ) + when lexbuf.SupportsFeature LanguageFeature.RelaxWhitespace + -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol + 1) // REVIEW: document these | _, (CtxtSeqBlock _ :: CtxtParen((BEGIN | LPAREN | LBRACK | LBRACK_BAR), _) :: CtxtVanilla _ :: (CtxtSeqBlock _ as limitCtxt) :: _) @@ -784,6 +835,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // else expr | (CtxtIf _ | CtxtElse _ | CtxtThen _), (CtxtIf _ as limitCtxt) :: _rest -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol) + // Permitted inner-construct precise block alignment: // while ... // do expr @@ -805,7 +857,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // always already pushed a SeqBlock at this position. | CtxtVanilla _ -> () | _ -> - let p1 = unindentationLimit true offsideStack + let p1 = undentationLimit true offsideStack let c2 = newCtxt.StartCol if c2 < p1.Column then warn tokenTup @@ -866,11 +918,11 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | INFIX_COMPARE_OP " let tokenEndPos = tokenTup.LexbufState.EndPos if isAdjacent tokenTup lookaheadTokenTup then - let stack = ref [] + let mutable stack = [] let rec scanAhead nParen = let lookaheadTokenTup = popNextTokenTup() let lookaheadToken = lookaheadTokenTup.Token - stack := (lookaheadTokenTup, true) :: !stack + stack <- (lookaheadTokenTup, true) :: stack let lookaheadTokenStartPos = startPosOfTokenTup lookaheadTokenTup match lookaheadToken with | Parser.EOF _ | SEMICOLON_SEMICOLON -> false @@ -886,21 +938,21 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, let hasAfterOp = (match lookaheadToken with GREATER _ -> false | _ -> true) if nParen > 0 then // Don't smash the token if there is an after op and we're in a nested paren - stack := (lookaheadTokenTup, not hasAfterOp) :: (!stack).Tail + stack <- (lookaheadTokenTup, not hasAfterOp) :: stack.Tail scanAhead nParen else // On successful parse of a set of type parameters, look for an adjacent (, e.g. // M(args) // and insert a HIGH_PRECEDENCE_PAREN_APP - if not hasAfterOp && (match nextTokenIsAdjacentLParenOrLBrack lookaheadTokenTup with Some(LPAREN) -> true | _ -> false) then + if not hasAfterOp && (match nextTokenIsAdjacentLParenOrLBrack lookaheadTokenTup with Some LPAREN -> true | _ -> false) then let dotTokenTup = peekNextTokenTup() - stack := (dotTokenTup.UseLocation(HIGH_PRECEDENCE_PAREN_APP), false) :: !stack + stack <- (pool.UseLocation(dotTokenTup, HIGH_PRECEDENCE_PAREN_APP), false) :: stack true | INFIX_COMPARE_OP (TyparsCloseOp(greaters, afterOp)) -> let nParen = nParen - greaters.Length if nParen > 0 then // Don't smash the token if there is an after op and we're in a nested paren - stack := (lookaheadTokenTup, not afterOp.IsSome) :: (!stack).Tail + stack <- (lookaheadTokenTup, not afterOp.IsSome) :: stack.Tail scanAhead nParen else // On successful parse of a set of type parameters, look for an adjacent (, e.g. @@ -908,7 +960,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // and insert a HIGH_PRECEDENCE_PAREN_APP if afterOp.IsNone && (match nextTokenIsAdjacentLParenOrLBrack lookaheadTokenTup with Some LPAREN -> true | _ -> false) then let dotTokenTup = peekNextTokenTup() - stack := (dotTokenTup.UseLocation(HIGH_PRECEDENCE_PAREN_APP), false) :: !stack + stack <- (pool.UseLocation(dotTokenTup, HIGH_PRECEDENCE_PAREN_APP), false) :: stack true | (LPAREN | LESS _ | LBRACK | LBRACK_LESS | INFIX_COMPARE_OP " scanAhead (nParen+1) @@ -959,26 +1011,31 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, let res = scanAhead 0 // Put the tokens back on and smash them up if needed - !stack |> List.iter (fun (tokenTup, smash) -> + stack |> List.iter (fun (tokenTup, smash) -> if smash then match tokenTup.Token with | INFIX_COMPARE_OP " - delayToken (tokenTup.UseShiftedLocation(INFIX_STAR_DIV_MOD_OP "/", 1, 0)) - delayToken (tokenTup.UseShiftedLocation(LESS res, 0, -1)) + delayToken (pool.UseShiftedLocation(tokenTup, INFIX_STAR_DIV_MOD_OP "/", 1, 0)) + delayToken (pool.UseShiftedLocation(tokenTup, LESS res, 0, -1)) + pool.Return tokenTup | GREATER_BAR_RBRACK -> - delayToken (tokenTup.UseShiftedLocation(BAR_RBRACK, 1, 0)) - delayToken (tokenTup.UseShiftedLocation(GREATER res, 0, -2)) + delayToken (pool.UseShiftedLocation(tokenTup, BAR_RBRACK, 1, 0)) + delayToken (pool.UseShiftedLocation(tokenTup, GREATER res, 0, -2)) + pool.Return tokenTup | GREATER_RBRACK -> - delayToken (tokenTup.UseShiftedLocation(RBRACK, 1, 0)) - delayToken (tokenTup.UseShiftedLocation(GREATER res, 0, -1)) + delayToken (pool.UseShiftedLocation(tokenTup, RBRACK, 1, 0)) + delayToken (pool.UseShiftedLocation(tokenTup, GREATER res, 0, -1)) + pool.Return tokenTup | GREATER _ -> - delayToken (tokenTup.UseLocation(GREATER res)) + delayToken (pool.UseLocation(tokenTup, GREATER res)) + pool.Return tokenTup | (INFIX_COMPARE_OP (TyparsCloseOp(greaters, afterOp) as opstr)) -> match afterOp with | None -> () - | Some tok -> delayToken (tokenTup.UseShiftedLocation(tok, greaters.Length, 0)) + | Some tok -> delayToken (pool.UseShiftedLocation(tokenTup, tok, greaters.Length, 0)) for i = greaters.Length - 1 downto 0 do - delayToken (tokenTup.UseShiftedLocation(greaters.[i] res, i, -opstr.Length + i + 1)) + delayToken (pool.UseShiftedLocation(tokenTup, greaters.[i] res, i, -opstr.Length + i + 1)) + pool.Return tokenTup | _ -> delayToken tokenTup else delayToken tokenTup) @@ -992,11 +1049,11 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, //-------------------------------------------------------------------------- let returnToken (tokenLexbufState: LexbufState) tok = - setLexbufState(tokenLexbufState) - prevWasAtomicEnd <- isAtomicExprEndToken(tok) + setLexbufState tokenLexbufState + prevWasAtomicEnd <- isAtomicExprEndToken tok tok - let rec suffixExists p l = match l with [] -> false | _::t -> p t || suffixExists p t + let rec suffixExists p l = match l with [] -> false | _ :: t -> p t || suffixExists p t let tokenBalancesHeadContext token stack = match token, stack with @@ -1044,8 +1101,8 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, let rec hwTokenFetch (useBlockRule) = let tokenTup = popNextTokenTup() - let tokenReplaced = rulesForBothSoftWhiteAndHardWhite(tokenTup) - if tokenReplaced then hwTokenFetch(useBlockRule) else + let tokenReplaced = rulesForBothSoftWhiteAndHardWhite tokenTup + if tokenReplaced then hwTokenFetch useBlockRule else let tokenStartPos = (startPosOfTokenTup tokenTup) let token = tokenTup.Token @@ -1093,11 +1150,11 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, let reprocess() = delayToken tokenTup - hwTokenFetch(useBlockRule) + hwTokenFetch useBlockRule let reprocessWithoutBlockRule() = delayToken tokenTup - hwTokenFetch(false) + hwTokenFetch false let insertTokenFromPrevPosToCurrentPos tok = delayToken tokenTup @@ -1105,7 +1162,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // span of inserted token lasts from the col + 1 of the prev token // to the beginning of current token let lastTokenPos = - let pos = tokenTup.LastTokenPos.Y + let pos = tokenTup.LastTokenPos pos.ShiftColumnBy 1 returnToken (lexbufStateForInsertedDummyTokens (lastTokenPos, tokenTup.LexbufState.StartPos)) tok @@ -1202,7 +1259,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, if not compilingFsLib then // ... <<< code with unmatched ( or [ or { or [| >>> ... "type" ... // We want a TYPE or MODULE keyword to close any currently-open "expression" contexts, as though there were close delimiters in the file, so: - let rec nextOuterMostInterestingContextIsNamespaceOrModule(offsideStack) = + let rec nextOuterMostInterestingContextIsNamespaceOrModule offsideStack = match offsideStack with // next outermost is namespace or module | _ :: (CtxtNamespaceBody _ | CtxtModuleBody _) :: _ -> true @@ -1213,7 +1270,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | _ :: [] -> true // anything else is a non-namespace/module | _ -> false - while not offsideStack.IsEmpty && (not(nextOuterMostInterestingContextIsNamespaceOrModule(offsideStack))) && + while not offsideStack.IsEmpty && (not(nextOuterMostInterestingContextIsNamespaceOrModule offsideStack)) && (match offsideStack.Head with // open-parens of sorts | CtxtParen((LPAREN|LBRACK|LBRACE|LBRACE_BAR|LBRACK_BAR), _) -> true @@ -1231,7 +1288,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, popCtxt() effectsToDo <- (fun() -> if debug then dprintf "--> because %s is coming, inserting OBLOCKEND\n" keywordName - delayTokenNoProcessing (tokenTup.UseLocation(OBLOCKEND))) :: effectsToDo + delayTokenNoProcessing (pool.UseLocation(tokenTup, OBLOCKEND))) :: effectsToDo | CtxtSeqBlock(_, _, NoAddBlockEnd) -> if debug then dprintf "--> because %s is coming, popping CtxtSeqBlock\n" keywordName popCtxt() @@ -1239,22 +1296,26 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, popCtxt() effectsToDo <- (fun() -> if debug then dprintf "--> because %s is coming, inserting ORIGHT_BLOCK_END\n" keywordName - delayTokenNoProcessing (tokenTup.UseLocation(ORIGHT_BLOCK_END))) :: effectsToDo + delayTokenNoProcessing (pool.UseLocation(tokenTup, ORIGHT_BLOCK_END))) :: effectsToDo | CtxtVanilla _ -> if debug then dprintf "--> because %s is coming, popping CtxtVanilla\n" keywordName popCtxt() | _ -> failwith "impossible, the while loop guard just above prevents this" - // See bugs 91609/92107/245850; we turn ...TYPE... into ...TYPE_COMING_SOON(x6), TYPE_IS_HERE... to help the parser recover when it sees "type" in a parenthesized expression. + // See bugs 91609/92107/245850; we turn ...TYPE... into ...TYPE_COMING_SOON x6, TYPE_IS_HERE... to help the parser recover when it sees "type" in a parenthesized expression. // And we do the same thing for MODULE. // Why _six_ TYPE_COMING_SOON? It's rather arbitrary, this means we can recover from up to six unmatched parens before failing. The unit tests (with 91609 in the name) demonstrate this. // Don't "delayToken tokenTup", we are replacing it, so consume it. if debug then dprintf "inserting 6 copies of %+A before %+A\n" comingSoon isHere - delayTokenNoProcessing (tokenTup.UseLocation(isHere)) + delayTokenNoProcessing (pool.UseLocation(tokenTup, isHere)) for i in 1..6 do - delayTokenNoProcessing (tokenTup.UseLocation(comingSoon)) + delayTokenNoProcessing (pool.UseLocation(tokenTup, comingSoon)) for e in List.rev effectsToDo do e() // push any END tokens after pushing the TYPE_IS_HERE and TYPE_COMING_SOON stuff, so that they come before those in the token stream + let returnToken tokenLexbufState token = + pool.Return tokenTup + returnToken tokenLexbufState token + match token, offsideStack with // inserted faux tokens need no other processing | _ when tokensThatNeedNoProcessingCount > 0 -> @@ -1275,7 +1336,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // reset on ';;' rule. A ';;' terminates ALL entries | SEMICOLON_SEMICOLON, [] -> if debug then dprintf ";; scheduling a reset\n" - delayToken(tokenTup.UseLocation(ORESET)) + delayToken(pool.UseLocation(tokenTup, ORESET)) returnToken tokenLexbufState SEMICOLON_SEMICOLON | ORESET, [] -> @@ -1283,7 +1344,8 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // NOTE: The parser thread of F# Interactive will often be blocked on this call, e.g. after an entry has been // processed and we're waiting for the first token of the next entry. peekInitial() |> ignore - hwTokenFetch(true) + pool.Return tokenTup + hwTokenFetch true | IN, stack when detectJoinInCtxt stack -> @@ -1296,7 +1358,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, if tokenStartCol < offsidePos.Column then warn tokenTup (FSComp.SR.lexfltIncorrentIndentationOfIn()) popCtxt() // Make sure we queue a dummy token at this position to check if any other pop rules apply - delayToken(tokenTup.UseLocation(ODUMMY(token))) + delayToken(pool.UseLocation(tokenTup, ODUMMY token)) returnToken tokenLexbufState (if blockLet then ODECLEND else token) // Balancing rule. Encountering a 'done' balances with a 'do'. i.e. even a non-offside 'done' closes a 'do' @@ -1305,8 +1367,9 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, if debug then dprintf "DONE at %a terminates CtxtDo(offsidePos=%a)\n" outputPos tokenStartPos outputPos offsidePos popCtxt() // reprocess as the DONE may close a DO context - delayToken(tokenTup.UseLocation(ODECLEND)) - hwTokenFetch(useBlockRule) + delayToken(pool.UseLocation(tokenTup, ODECLEND)) + pool.Return tokenTup + hwTokenFetch useBlockRule // Balancing rule. Encountering a ')' or '}' balances with a '(' or '{', even if not offside | ((END | RPAREN | RBRACE | BAR_RBRACE | RBRACK | BAR_RBRACK | RQUOTE _ | GREATER true) as t2), (CtxtParen (t1, _) :: _) @@ -1314,15 +1377,15 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, if debug then dprintf "RPAREN/RBRACE/BAR_RBRACE/RBRACK/BAR_RBRACK/RQUOTE/END at %a terminates CtxtParen()\n" outputPos tokenStartPos popCtxt() // Queue a dummy token at this position to check if any closing rules apply - delayToken(tokenTup.UseLocation(ODUMMY(token))) + delayToken(pool.UseLocation(tokenTup, ODUMMY token)) returnToken tokenLexbufState token // Balancing rule. Encountering a 'end' can balance with a 'with' but only when not offside - | END, (CtxtWithAsAugment(offsidePos) :: _) + | END, (CtxtWithAsAugment offsidePos :: _) when not (tokenStartCol + 1 <= offsidePos.Column) -> if debug then dprintf "END at %a terminates CtxtWithAsAugment()\n" outputPos tokenStartPos popCtxt() - delayToken(tokenTup.UseLocation(ODUMMY(token))) // make sure we queue a dummy token at this position to check if any closing rules apply + delayToken(pool.UseLocation(tokenTup, ODUMMY token)) // make sure we queue a dummy token at this position to check if any closing rules apply returnToken tokenLexbufState OEND // Transition rule. CtxtNamespaceHead ~~~> CtxtSeqBlock @@ -1346,7 +1409,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, delayToken tokenTup pushCtxt tokenTup (CtxtNamespaceBody namespaceTokenPos) pushCtxtSeqBlockAt (tokenTup, true, AddBlockEnd) - hwTokenFetch(false) + hwTokenFetch false // Transition rule. CtxtModuleHead ~~~> push CtxtModuleBody; push CtxtSeqBlock // Applied when a ':' or '=' token is seen @@ -1381,7 +1444,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, delayToken tokenTup pushCtxt tokenTup (CtxtModuleBody (moduleTokenPos, true)) pushCtxtSeqBlockAt (tokenTup, true, AddBlockEnd) - hwTokenFetch(false) + hwTokenFetch false // Offside rule for SeqBlock. // f x @@ -1576,13 +1639,13 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, reprocess() // Pop CtxtMemberBody when offside. Insert an ODECLEND to indicate the end of the member - | _, ((CtxtMemberBody(offsidePos)) :: _) when isSemiSemi || tokenStartCol <= offsidePos.Column -> + | _, ((CtxtMemberBody offsidePos) :: _) when isSemiSemi || tokenStartCol <= offsidePos.Column -> if debug then dprintf "token at column %d is offside from MEMBER/OVERRIDE head with offsidePos %a!\n" tokenStartCol outputPos offsidePos popCtxt() insertToken ODECLEND // Pop CtxtMemberHead when offside - | _, ((CtxtMemberHead(offsidePos)) :: _) when isSemiSemi || tokenStartCol <= offsidePos.Column -> + | _, ((CtxtMemberHead offsidePos) :: _) when isSemiSemi || tokenStartCol <= offsidePos.Column -> if debug then dprintf "token at column %d is offside from MEMBER/OVERRIDE head with offsidePos %a!\n" tokenStartCol outputPos offsidePos popCtxt() reprocess() @@ -1599,7 +1662,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, popCtxt() insertToken OEND - | _, (CtxtWithAsAugment(offsidePos) :: _) + | _, (CtxtWithAsAugment offsidePos :: _) when isSemiSemi || (if isWithAugmentBlockContinuator token then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> if debug then dprintf "offside from CtxtWithAsAugment, isWithAugmentBlockContinuator = %b\n" (isWithAugmentBlockContinuator token) popCtxt() @@ -1694,7 +1757,8 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, insertComingSoonTokens("MODULE", MODULE_COMING_SOON, MODULE_IS_HERE) if debug then dprintf "MODULE: entering CtxtModuleHead, awaiting EQUALS to go to CtxtSeqBlock (%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtModuleHead (tokenStartPos, token)) - hwTokenFetch(useBlockRule) + pool.Return tokenTup + hwTokenFetch useBlockRule // exception ... ~~~> CtxtException | EXCEPTION, (_ :: _) -> @@ -1705,24 +1769,24 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // let ... ~~~> CtxtLetDecl // -- this rule only applies to // - 'static let' - | LET(isUse), (ctxt :: _) when (match ctxt with CtxtMemberHead _ -> true | _ -> false) -> + | LET isUse, (ctxt :: _) when (match ctxt with CtxtMemberHead _ -> true | _ -> false) -> if debug then dprintf "LET: entering CtxtLetDecl(), awaiting EQUALS to go to CtxtSeqBlock (%a)\n" outputPos tokenStartPos let startPos = match ctxt with CtxtMemberHead startPos -> startPos | _ -> tokenStartPos popCtxt() // get rid of the CtxtMemberHead pushCtxt tokenTup (CtxtLetDecl(true, startPos)) - returnToken tokenLexbufState (OLET(isUse)) + returnToken tokenLexbufState (OLET isUse) // let ... ~~~> CtxtLetDecl // -- this rule only applies to // - 'let' 'right-on' a SeqBlock line // - 'let' in a CtxtMatchClauses, which is a parse error, but we need to treat as OLET to get various O...END tokens to enable parser to recover - | LET(isUse), (ctxt :: _) -> + | LET isUse, (ctxt :: _) -> let blockLet = match ctxt with | CtxtSeqBlock _ -> true | CtxtMatchClauses _ -> true | _ -> false if debug then dprintf "LET: entering CtxtLetDecl(blockLet=%b), awaiting EQUALS to go to CtxtSeqBlock (%a)\n" blockLet outputPos tokenStartPos pushCtxt tokenTup (CtxtLetDecl(blockLet, tokenStartPos)) - returnToken tokenLexbufState (if blockLet then OLET(isUse) else token) + returnToken tokenLexbufState (if blockLet then OLET isUse else token) // let! ... ~~~> CtxtLetDecl | BINDER b, (ctxt :: _) -> @@ -1731,6 +1795,13 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, pushCtxt tokenTup (CtxtLetDecl(blockLet, tokenStartPos)) returnToken tokenLexbufState (if blockLet then OBINDER b else token) + // and! ... ~~~> CtxtLetDecl + | AND_BANG isUse, (ctxt :: _) -> + let blockLet = match ctxt with CtxtSeqBlock _ -> true | _ -> false + if debug then dprintf "AND!: entering CtxtLetDecl(blockLet=%b), awaiting EQUALS to go to CtxtSeqBlock (%a)\n" blockLet outputPos tokenStartPos + pushCtxt tokenTup (CtxtLetDecl(blockLet,tokenStartPos)) + returnToken tokenLexbufState (if blockLet then OAND_BANG isUse else token) + | (VAL | STATIC | ABSTRACT | MEMBER | OVERRIDE | DEFAULT), ctxtStack when thereIsACtxtMemberBodyOnTheStackAndWeShouldPopStackForUpcomingMember ctxtStack -> if debug then dprintf "STATIC/MEMBER/OVERRIDE/DEFAULT: already inside CtxtMemberBody, popping all that context before starting next member...\n" // save this token, we'll consume it again later... @@ -1742,12 +1813,12 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | Some tok -> popCtxt() if debug then dprintf "--> inserting %+A\n" tok - delayTokenNoProcessing (tokenTup.UseLocation(tok)) + delayTokenNoProcessing (pool.UseLocation(tokenTup, tok)) // for the rest, we silently pop them | _ -> popCtxt() popCtxt() // pop CtxtMemberBody if debug then dprintf "...STATIC/MEMBER/OVERRIDE/DEFAULT: finished popping all that context\n" - hwTokenFetch(useBlockRule) + hwTokenFetch useBlockRule // static member ... ~~~> CtxtMemberHead // static ... ~~~> CtxtMemberHead @@ -1757,19 +1828,19 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // val ... ~~~> CtxtMemberHead | (VAL | STATIC | ABSTRACT | MEMBER | OVERRIDE | DEFAULT), (ctxt :: _) when (match ctxt with CtxtMemberHead _ -> false | _ -> true) -> if debug then dprintf "STATIC/MEMBER/OVERRIDE/DEFAULT: entering CtxtMemberHead, awaiting EQUALS to go to CtxtSeqBlock (%a)\n" outputPos tokenStartPos - pushCtxt tokenTup (CtxtMemberHead(tokenStartPos)) + pushCtxt tokenTup (CtxtMemberHead tokenStartPos) returnToken tokenLexbufState token // public new... ~~~> CtxtMemberHead | (PUBLIC | PRIVATE | INTERNAL), (_ctxt :: _) when (match peekNextToken() with NEW -> true | _ -> false) -> if debug then dprintf "PUBLIC/PRIVATE/INTERNAL NEW: entering CtxtMemberHead, awaiting EQUALS to go to CtxtSeqBlock (%a)\n" outputPos tokenStartPos - pushCtxt tokenTup (CtxtMemberHead(tokenStartPos)) + pushCtxt tokenTup (CtxtMemberHead tokenStartPos) returnToken tokenLexbufState token // new( ~~~> CtxtMemberHead, if not already there because of 'public' | NEW, ctxt :: _ when (match peekNextToken() with LPAREN -> true | _ -> false) && (match ctxt with CtxtMemberHead _ -> false | _ -> true) -> if debug then dprintf "NEW: entering CtxtMemberHead, awaiting EQUALS to go to CtxtSeqBlock (%a)\n" outputPos tokenStartPos - pushCtxt tokenTup (CtxtMemberHead(tokenStartPos)) + pushCtxt tokenTup (CtxtMemberHead tokenStartPos) returnToken tokenLexbufState token // 'let ... = ' ~~~> CtxtSeqBlock @@ -1821,7 +1892,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // 'static member ... =' ~~~> CtxtMemberBody, CtxtSeqBlock // 'default ... =' ~~~> CtxtMemberBody, CtxtSeqBlock // 'override ... =' ~~~> CtxtMemberBody, CtxtSeqBlock - | EQUALS, ((CtxtMemberHead(offsidePos)) :: _) -> + | EQUALS, ((CtxtMemberHead offsidePos) :: _) -> if debug then dprintf "CtxtMemberHead: EQUALS, pushing CtxtSeqBlock\n" replaceCtxt tokenTup (CtxtMemberBody (offsidePos)) pushCtxtSeqBlock(true, AddBlockEnd) @@ -1919,7 +1990,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // as well as: // member x.PublicGetSetProperty // with inline get() = "Ralf" - // and [] set(v) = () + // and [] set v = () // | PUBLIC | PRIVATE | INTERNAL | INLINE -> @@ -1945,7 +2016,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // So we're careful to set the offside column to be the minimum required *) limCtxt.StartPos if debug then dprintf "WITH, pushing CtxtWithAsLet, tokenStartPos = %a, lookaheadTokenStartPos = %a\n" outputPos tokenStartPos outputPos lookaheadTokenStartPos - pushCtxt tokenTup (CtxtWithAsLet(offsidePos)) + pushCtxt tokenTup (CtxtWithAsLet offsidePos) // Detect 'with' bindings of the form // @@ -1974,7 +2045,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // with [] get() = "Ralf" if (match lookaheadTokenTup.Token with LBRACK_LESS -> true | _ -> false) && (lookaheadTokenStartPos.OriginalLine = tokenTup.StartPos.OriginalLine) then let offsidePos = tokenStartPos - pushCtxt tokenTup (CtxtWithAsLet(offsidePos)) + pushCtxt tokenTup (CtxtWithAsLet offsidePos) returnToken tokenLexbufState OWITH else // In these situations @@ -1995,14 +2066,14 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // The limit is "interface"/"exception"/"type" let offsidePos = limCtxt.StartPos - pushCtxt tokenTup (CtxtWithAsAugment(offsidePos)) + pushCtxt tokenTup (CtxtWithAsAugment offsidePos) pushCtxtSeqBlock(true, AddBlockEnd) returnToken tokenLexbufState token | WITH, stack -> if debug then dprintf "WITH\n" if debug then dprintf "WITH --> NO MATCH, pushing CtxtWithAsAugment (type augmentation), stack = %A" stack - pushCtxt tokenTup (CtxtWithAsAugment(tokenStartPos)) + pushCtxt tokenTup (CtxtWithAsAugment tokenStartPos) pushCtxtSeqBlock(true, AddBlockEnd) returnToken tokenLexbufState token @@ -2010,13 +2081,13 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, let lookaheadTokenTup = peekNextTokenTup() let lookaheadTokenStartPos = startPosOfTokenTup lookaheadTokenTup let leadingBar = match (peekNextToken()) with BAR -> true | _ -> false - pushCtxt tokenTup (CtxtFunction(tokenStartPos)) + pushCtxt tokenTup (CtxtFunction tokenStartPos) pushCtxt lookaheadTokenTup (CtxtMatchClauses(leadingBar, lookaheadTokenStartPos)) returnToken tokenLexbufState OFUNCTION | THEN, _ -> if debug then dprintf "THEN, replacing THEN with OTHEN, pushing CtxtSeqBlock;CtxtThen(%a)\n" outputPos tokenStartPos - pushCtxt tokenTup (CtxtThen(tokenStartPos)) + pushCtxt tokenTup (CtxtThen tokenStartPos) pushCtxtSeqBlock(true, AddBlockEnd) returnToken tokenLexbufState OTHEN @@ -2030,14 +2101,14 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // if e1 then e2 // else if e3 then e4 // else if e5 then e6 - let _ = popNextTokenTup() + popNextTokenTup() |> pool.Return if debug then dprintf "ELSE IF: replacing ELSE IF with ELIF, pushing CtxtIf, CtxtVanilla(%a)\n" outputPos tokenStartPos - pushCtxt tokenTup (CtxtIf(tokenStartPos)) + pushCtxt tokenTup (CtxtIf tokenStartPos) returnToken tokenLexbufState ELIF | _ -> if debug then dprintf "ELSE: replacing ELSE with OELSE, pushing CtxtSeqBlock, CtxtElse(%a)\n" outputPos lookaheadTokenStartPos - pushCtxt tokenTup (CtxtElse(tokenStartPos)) + pushCtxt tokenTup (CtxtElse tokenStartPos) pushCtxtSeqBlock(true, AddBlockEnd) returnToken tokenLexbufState OELSE @@ -2085,7 +2156,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // type C = interface .... with | _ -> if debug then dprintf "INTERFACE, pushing CtxtInterfaceHead, tokenStartPos = %a, lookaheadTokenStartPos = %a\n" outputPos tokenStartPos outputPos lookaheadTokenStartPos - pushCtxt tokenTup (CtxtInterfaceHead(tokenStartPos)) + pushCtxt tokenTup (CtxtInterfaceHead tokenStartPos) returnToken tokenLexbufState OINTERFACE_MEMBER | CLASS, _ -> @@ -2097,8 +2168,9 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | TYPE, _ -> insertComingSoonTokens("TYPE", TYPE_COMING_SOON, TYPE_IS_HERE) if debug then dprintf "TYPE, pushing CtxtTypeDefns(%a)\n" outputPos tokenStartPos - pushCtxt tokenTup (CtxtTypeDefns(tokenStartPos)) - hwTokenFetch(useBlockRule) + pushCtxt tokenTup (CtxtTypeDefns tokenStartPos) + pool.Return tokenTup + hwTokenFetch useBlockRule | TRY, _ -> if debug then dprintf "Try, pushing CtxtTry(%a)\n" outputPos tokenStartPos @@ -2116,6 +2188,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | ODUMMY(_), _ -> if debug then dprintf "skipping dummy token as no offside rules apply\n" + pool.Return tokenTup hwTokenFetch (useBlockRule) // Ordinary tokens start a vanilla block @@ -2135,35 +2208,47 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, if debug then dprintf "inserting HIGH_PRECEDENCE_PAREN_APP at dotTokenPos = %a\n" outputPos (startPosOfTokenTup dotTokenTup) let hpa = match nextTokenIsAdjacentLParenOrLBrack tokenTup with - | Some(LPAREN) -> HIGH_PRECEDENCE_PAREN_APP - | Some(LBRACK) -> HIGH_PRECEDENCE_BRACK_APP + | Some LPAREN -> HIGH_PRECEDENCE_PAREN_APP + | Some LBRACK -> HIGH_PRECEDENCE_BRACK_APP | _ -> failwith "unreachable" - delayToken(dotTokenTup.UseLocation(hpa)) - delayToken(tokenTup) + delayToken(pool.UseLocation(dotTokenTup, hpa)) + delayToken tokenTup true // Insert HIGH_PRECEDENCE_TYAPP if needed | (DELEGATE | IDENT _ | IEEE64 _ | IEEE32 _ | DECIMAL _ | INT8 _ | INT16 _ | INT32 _ | INT64 _ | NATIVEINT _ | UINT8 _ | UINT16 _ | UINT32 _ | UINT64 _ | BIGNUM _) when peekAdjacentTypars false tokenTup -> let lessTokenTup = popNextTokenTup() - delayToken (lessTokenTup.UseLocation(match lessTokenTup.Token with LESS _ -> LESS true | _ -> failwith "unreachable")) + delayToken (pool.UseLocation(lessTokenTup, match lessTokenTup.Token with LESS _ -> LESS true | _ -> failwith "unreachable")) if debug then dprintf "softwhite inserting HIGH_PRECEDENCE_TYAPP at dotTokenPos = %a\n" outputPos (startPosOfTokenTup lessTokenTup) - delayToken (lessTokenTup.UseLocation(HIGH_PRECEDENCE_TYAPP)) + delayToken (pool.UseLocation(lessTokenTup, HIGH_PRECEDENCE_TYAPP)) delayToken (tokenTup) + pool.Return lessTokenTup + true + + // ..^1 will get parsed as DOT_DOT_HAT 1 while 1..^2 will get parsed as 1 DOT_DOT HAT 2 + // because of processing rule underneath this. + | (DOT_DOT_HAT) -> + let hatPos = new LexbufState(tokenTup.EndPos.ShiftColumnBy(-1), tokenTup.EndPos, false) + delayToken(let rented = pool.Rent() in rented.Token <- INFIX_AT_HAT_OP("^"); rented.LexbufState <- hatPos; rented.LastTokenPos <- tokenTup.LastTokenPos; rented) + delayToken(pool.UseShiftedLocation(tokenTup, DOT_DOT, 0, -1)) + pool.Return tokenTup true // Split this token to allow "1..2" for range specification | INT32_DOT_DOT (i, v) -> - let dotdotPos = new LexbufState(tokenTup.EndPos.ShiftColumnBy(-2), tokenTup.EndPos, false) - delayToken(new TokenTup(DOT_DOT, dotdotPos, tokenTup.LastTokenPos)) - delayToken(tokenTup.UseShiftedLocation(INT32(i, v), 0, -2)) + let dotDotPos = new LexbufState(tokenTup.EndPos.ShiftColumnBy(-2), tokenTup.EndPos, false) + delayToken(let rented = pool.Rent() in rented.Token <- DOT_DOT; rented.LexbufState <- dotDotPos; rented.LastTokenPos <- tokenTup.LastTokenPos; rented) + delayToken(pool.UseShiftedLocation(tokenTup, INT32(i, v), 0, -2)) + pool.Return tokenTup true // Split @>. and @@>. into two | RQUOTE_DOT (s, raw) -> let dotPos = new LexbufState(tokenTup.EndPos.ShiftColumnBy(-1), tokenTup.EndPos, false) - delayToken(new TokenTup(DOT, dotPos, tokenTup.LastTokenPos)) - delayToken(tokenTup.UseShiftedLocation(RQUOTE(s, raw), 0, -1)) + delayToken(let rented = pool.Rent() in rented.Token <- DOT; rented.LexbufState <- dotPos; rented.LastTokenPos <- tokenTup.LastTokenPos; rented) + delayToken(pool.UseShiftedLocation(tokenTup, RQUOTE(s, raw), 0, -1)) + pool.Return tokenTup true | MINUS | PLUS_MINUS_OP _ | PERCENT_OP _ | AMP | AMP_AMP @@ -2172,7 +2257,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | PERCENT_OP s -> (s = "%") || (s = "%%") | _ -> true) && nextTokenIsAdjacent tokenTup && - not (prevWasAtomicEnd && (tokenTup.LastTokenPos.Y = startPosOfTokenTup tokenTup))) -> + not (prevWasAtomicEnd && (tokenTup.LastTokenPos = startPosOfTokenTup tokenTup))) -> let plus = match tokenTup.Token with @@ -2184,8 +2269,17 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | MINUS -> true | _ -> false let nextTokenTup = popNextTokenTup() + /// Merge the location of the prefix token and the literal - let delayMergedToken tok = delayToken(new TokenTup(tok, new LexbufState(tokenTup.LexbufState.StartPos, nextTokenTup.LexbufState.EndPos, nextTokenTup.LexbufState.PastEOF), tokenTup.LastTokenPos)) + let delayMergedToken tok = + let rented = pool.Rent() + rented.Token <- tok + rented.LexbufState <- new LexbufState(tokenTup.LexbufState.StartPos, nextTokenTup.LexbufState.EndPos, nextTokenTup.LexbufState.PastEOF) + rented.LastTokenPos <- tokenTup.LastTokenPos + delayToken(rented) + pool.Return nextTokenTup + pool.Return tokenTup + let noMerge() = let tokenName = match tokenTup.Token with @@ -2197,7 +2291,8 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | _ -> failwith "unreachable" let token = ADJACENT_PREFIX_OP tokenName delayToken nextTokenTup - delayToken (tokenTup.UseLocation(token)) + delayToken (pool.UseLocation(tokenTup, token)) + pool.Return tokenTup if plusOrMinus then match nextTokenTup.Token with @@ -2206,10 +2301,10 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | INT32(v, bad) -> delayMergedToken(INT32((if plus then v else -v), (plus && bad))) // note: '-' makes a 'bad' max int 'good'. '+' does not | INT32_DOT_DOT(v, bad) -> delayMergedToken(INT32_DOT_DOT((if plus then v else -v), (plus && bad))) // note: '-' makes a 'bad' max int 'good'. '+' does not | INT64(v, bad) -> delayMergedToken(INT64((if plus then v else -v), (plus && bad))) // note: '-' makes a 'bad' max int 'good'. '+' does not - | NATIVEINT(v) -> delayMergedToken(NATIVEINT(if plus then v else -v)) - | IEEE32(v) -> delayMergedToken(IEEE32(if plus then v else -v)) - | IEEE64(v) -> delayMergedToken(IEEE64(if plus then v else -v)) - | DECIMAL(v) -> delayMergedToken(DECIMAL(if plus then v else System.Decimal.op_UnaryNegation v)) + | NATIVEINT v -> delayMergedToken(NATIVEINT(if plus then v else -v)) + | IEEE32 v -> delayMergedToken(IEEE32(if plus then v else -v)) + | IEEE64 v -> delayMergedToken(IEEE64(if plus then v else -v)) + | DECIMAL v -> delayMergedToken(DECIMAL(if plus then v else System.Decimal.op_UnaryNegation v)) | BIGNUM(v, s) -> delayMergedToken(BIGNUM((if plus then v else "-" + v), s)) | _ -> noMerge() else @@ -2223,14 +2318,18 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, and pushCtxtSeqBlockAt(p: TokenTup, addBlockBegin, addBlockEnd) = if addBlockBegin then if debug then dprintf "--> insert OBLOCKBEGIN \n" - delayToken(p.UseLocation(OBLOCKBEGIN)) + delayToken(pool.UseLocation(p, OBLOCKBEGIN)) pushCtxt p (CtxtSeqBlock(FirstInSeqBlock, startPosOfTokenTup p, addBlockEnd)) let rec swTokenFetch() = let tokenTup = popNextTokenTup() - let tokenReplaced = rulesForBothSoftWhiteAndHardWhite(tokenTup) + let tokenReplaced = rulesForBothSoftWhiteAndHardWhite tokenTup if tokenReplaced then swTokenFetch() - else returnToken tokenTup.LexbufState tokenTup.Token + else + let lexbufState = tokenTup.LexbufState + let tok = tokenTup.Token + pool.Return tokenTup + returnToken lexbufState tok //---------------------------------------------------------------------------- // Part VI. Publish the new lexer function. @@ -2243,7 +2342,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, () if lightSyntaxStatus.Status - then hwTokenFetch(true) + then hwTokenFetch true else swTokenFetch() @@ -2271,9 +2370,9 @@ type LexFilter (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, lex let insertComingSoonTokens comingSoon isHere = if debug then dprintf "inserting 6 copies of %+A before %+A\n" comingSoon isHere - delayToken(isHere) + delayToken isHere for i in 1..6 do - delayToken(comingSoon) + delayToken comingSoon member __.LexBuffer = inner.LexBuffer member __.Lexer _ = diff --git a/src/fcs-fable/src/fsharp/Logger.fsi b/src/fcs-fable/src/fsharp/Logger.fsi index cb84dde5f5..a3c041e1d0 100644 --- a/src/fcs-fable/src/fsharp/Logger.fsi +++ b/src/fcs-fable/src/fsharp/Logger.fsi @@ -4,9 +4,7 @@ namespace FSharp.Compiler open System -// FIXME: We cannot make this internal yet until F# gets a compiler switch to make cases public when the type itself is internal. -// https://github.com/Microsoft/visualfsharp/issues/4821 -type (* internal *) LogCompilerFunctionId = +type internal LogCompilerFunctionId = | Service_ParseAndCheckFileInProject = 1 | Service_CheckOneFile = 2 | Service_IncrementalBuildersCache_BuildingNewCache = 3 diff --git a/src/fcs-fable/src/fsharp/LowerCallsAndSeqs.fs b/src/fcs-fable/src/fsharp/LowerCallsAndSeqs.fs old mode 100755 new mode 100644 index 087d49f39b..b4dac49c0a --- a/src/fcs-fable/src/fsharp/LowerCallsAndSeqs.fs +++ b/src/fcs-fable/src/fsharp/LowerCallsAndSeqs.fs @@ -6,17 +6,16 @@ open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library - open FSharp.Compiler.AccessibilityLogic -open FSharp.Compiler.Ast -open FSharp.Compiler.Infos open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.Lib -open FSharp.Compiler.TcGlobals open FSharp.Compiler.InfoReader +open FSharp.Compiler.Infos +open FSharp.Compiler.Lib open FSharp.Compiler.MethodCalls +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps //---------------------------------------------------------------------------- // Eta-expansion of calls to top-level-methods @@ -24,13 +23,13 @@ open FSharp.Compiler.MethodCalls let InterceptExpr g cont expr = match expr with - | Expr.Val(vref, flags, m) -> + | Expr.Val (vref, flags, m) -> match vref.ValReprInfo with | Some arity -> Some (fst (AdjustValForExpectedArity g m vref flags arity)) | None -> None // App (Val v, tys, args) - | Expr.App((Expr.Val (vref, flags, _) as f0), f0ty, tyargsl, argsl, m) -> + | Expr.App ((Expr.Val (vref, flags, _) as f0), f0ty, tyargsl, argsl, m) -> // Only transform if necessary, i.e. there are not enough arguments match vref.ValReprInfo with | Some(topValInfo) -> @@ -43,7 +42,7 @@ let InterceptExpr g cont expr = Some (MakeApplicationAndBetaReduce g (f0, f0ty, [tyargsl], argsl, m)) | None -> None - | Expr.App(f0, f0ty, tyargsl, argsl, m) -> + | Expr.App (f0, f0ty, tyargsl, argsl, m) -> Some (MakeApplicationAndBetaReduce g (f0, f0ty, [tyargsl], argsl, m) ) | _ -> None @@ -58,17 +57,12 @@ let LowerImplFile g assembly = PostTransform= (fun _ -> None) IsUnderQuotations=false } assembly - //---------------------------------------------------------------------------- -// State machine compilation for sequence expressions +// General helpers let mkLambdaNoType g m uv e = mkLambda m uv (e, tyOfExpr g e) -let mkUnitDelayLambda (g: TcGlobals) m e = - let uv, _ue = mkCompGenLocal m "unitVar" g.unit_ty - mkLambdaNoType g m uv e - let callNonOverloadedMethod g amap m methName ty args = match TryFindIntrinsicMethInfo (InfoReader(g, amap)) m AccessibleFromSomeFSharpCode methName ty with | [] -> error(InternalError("No method called '"+methName+"' was found", m)) @@ -79,26 +73,49 @@ let callNonOverloadedMethod g amap m methName ty args = | _ -> error(InternalError("The method called '"+methName+"' resolved to a non-IL type", m)) +//---------------------------------------------------------------------------- +// State machine compilation for sequence expressions type LoweredSeqFirstPhaseResult = - { /// The code to run in the second phase, to rebuild the expressions, once all code labels and their mapping to program counters have been determined - /// 'nextVar' is the argument variable for the GenerateNext method that represents the byref argument that holds the "goto" destination for a tailcalling sequence expression + { + /// The second phase of the transformation. This rebuilds the 'generate', 'dispose' and 'checkDispose' expressions for the + /// state machine. It is run after all code labels and their mapping to program counters have been determined + /// after the first phase. + /// + /// The arguments to phase2 are as follows: + /// 'pc' is the state machine variable allocated to hold the "program counter" for the state machine + /// 'current' is the state machine variable allocated to hold the "current" value being yielded from the enumeration + /// 'nextVar' is the argument variable for the GenerateNext method that represents the byref argument + /// that holds the "goto" destination for a tailcalling sequence expression + /// 'pcMap' is the mapping from code labels to values for 'pc' + /// + /// The phase2 function returns the core of the generate, dispose and checkDispose implementations. phase2 : ((* pc: *) ValRef * (* current: *) ValRef * (* nextVar: *) ValRef * Map -> Expr * Expr * Expr) /// The labels allocated for one portion of the sequence expression - labels : int list + entryPoints : int list - /// any actual work done in Close + /// Indicates if any actual work is done in dispose, i.e. is there a 'try-finally' (or 'use') in the computation. significantClose : bool /// The state variables allocated for one portion of the sequence expression (i.e. the local let-bound variables which become state variables) stateVars: ValRef list /// The vars captured by the non-synchronous path - capturedVars: FreeVars } + asyncVars: FreeVars + } let isVarFreeInExpr v e = Zset.contains v (freeInExpr CollectTyparsAndLocals e).FreeLocals +let (|Seq|_|) g expr = + match expr with + // use 'seq { ... }' as an indicator + | ValApp g g.seq_vref ([elemTy], [e], _m) -> Some (e, elemTy) + | _ -> None + +let IsPossibleSequenceExpr g expr = + match expr with Seq g _ -> true | _ -> false + /// Analyze a TAST expression to detect the elaborated form of a sequence expression. /// Then compile it to a state machine represented as a TAST containing goto, return and label nodes. /// The returned state machine will also contain references to state variables (from internal 'let' bindings), @@ -109,46 +126,39 @@ let isVarFreeInExpr v e = Zset.contains v (freeInExpr CollectTyparsAndLocals e). /// The analysis is done in two phases. The first phase determines the state variables and state labels (as Abstract IL code labels). /// We then allocate an integer pc for each state label and proceed with the second phase, which builds two related state machine /// expressions: one for 'MoveNext' and one for 'Dispose'. -let LowerSeqExpr g amap overallExpr = +let ConvertSequenceExprToObject g amap overallExpr = /// Detect a 'yield x' within a 'seq { ... }' let (|SeqYield|_|) expr = match expr with - | Expr.App(Expr.Val (vref, _, _), _f0ty, _tyargsl, [arg], m) when valRefEq g vref g.seq_singleton_vref -> - Some (arg, m) - | _ -> - None + | ValApp g g.seq_singleton_vref (_, [arg], m) -> Some (arg, m) + | _ -> None /// Detect a 'expr; expr' within a 'seq { ... }' let (|SeqAppend|_|) expr = match expr with - | Expr.App(Expr.Val (vref, _, _), _f0ty, _tyargsl, [arg1;arg2], m) when valRefEq g vref g.seq_append_vref -> - Some (arg1, arg2, m) - | _ -> - None + | ValApp g g.seq_append_vref (_, [arg1; arg2], m) -> Some (arg1, arg2, m) + | _ -> None /// Detect a 'while gd do expr' within a 'seq { ... }' let (|SeqWhile|_|) expr = match expr with - | Expr.App(Expr.Val (vref, _, _), _f0ty, _tyargsl, [Expr.Lambda(_, _, _, [dummyv], gd, _, _);arg2], m) - when valRefEq g vref g.seq_generated_vref && - not (isVarFreeInExpr dummyv gd) -> + | ValApp g g.seq_generated_vref (_, [Expr.Lambda (_, _, _, [dummyv], gd, _, _);arg2], m) + when not (isVarFreeInExpr dummyv gd) -> Some (gd, arg2, m) | _ -> None let (|SeqTryFinally|_|) expr = match expr with - | Expr.App(Expr.Val (vref, _, _), _f0ty, _tyargsl, [arg1;Expr.Lambda(_, _, _, [dummyv], compensation, _, _)], m) - when valRefEq g vref g.seq_finally_vref && - not (isVarFreeInExpr dummyv compensation) -> + | ValApp g g.seq_finally_vref (_, [arg1;Expr.Lambda (_, _, _, [dummyv], compensation, _, _)], m) + when not (isVarFreeInExpr dummyv compensation) -> Some (arg1, compensation, m) | _ -> None let (|SeqUsing|_|) expr = match expr with - | Expr.App(Expr.Val (vref, _, _), _f0ty, [_;_;elemTy], [resource;Expr.Lambda(_, _, _, [v], body, _, _)], m) - when valRefEq g vref g.seq_using_vref -> + | ValApp g g.seq_using_vref ([_;_;elemTy], [resource;Expr.Lambda (_, _, _, [v], body, _, _)], m) -> Some (resource, v, body, elemTy, m) | _ -> None @@ -156,31 +166,30 @@ let LowerSeqExpr g amap overallExpr = let (|SeqFor|_|) expr = match expr with // Nested for loops are represented by calls to Seq.collect - | Expr.App(Expr.Val (vref, _, _), _f0ty, [_inpElemTy;_enumty2;genElemTy], [Expr.Lambda(_, _, _, [v], body, _, _); inp], m) when valRefEq g vref g.seq_collect_vref -> + | ValApp g g.seq_collect_vref ([_inpElemTy;_enumty2;genElemTy], [Expr.Lambda (_, _, _, [v], body, _, _); inp], m) -> Some (inp, v, body, genElemTy, m) // "for x in e -> e2" is converted to a call to Seq.map by the F# type checker. This could be removed, except it is also visible in F# quotations. - | Expr.App(Expr.Val (vref, _, _), _f0ty, [_inpElemTy;genElemTy], [Expr.Lambda(_, _, _, [v], body, _, _); inp], m) when valRefEq g vref g.seq_map_vref -> + | ValApp g g.seq_map_vref ([_inpElemTy;genElemTy], [Expr.Lambda (_, _, _, [v], body, _, _); inp], m) -> Some (inp, v, mkCallSeqSingleton g body.Range genElemTy body, genElemTy, m) | _ -> None let (|SeqDelay|_|) expr = match expr with - | Expr.App(Expr.Val (vref, _, _), _f0ty, [elemTy], [Expr.Lambda(_, _, _, [v], e, _, _)], _m) when valRefEq g vref g.seq_delay_vref && not (isVarFreeInExpr v e) -> Some (e, elemTy) + | ValApp g g.seq_delay_vref ([elemTy], [Expr.Lambda (_, _, _, [v], e, _, _)], _m) + when not (isVarFreeInExpr v e) -> + Some (e, elemTy) | _ -> None let (|SeqEmpty|_|) expr = match expr with - | Expr.App(Expr.Val (vref, _, _), _f0ty, _tyargsl, [], m) when valRefEq g vref g.seq_empty_vref -> Some (m) - | _ -> None - - let (|Seq|_|) expr = - match expr with - // use 'seq { ... }' as an indicator - | Expr.App(Expr.Val (vref, _, _), _f0ty, [elemTy], [e], _m) when valRefEq g vref g.seq_vref -> Some (e, elemTy) + | ValApp g g.seq_empty_vref (_, [], m) -> Some (m) | _ -> None + /// Implement a decision to represent a 'let' binding as a non-escaping local variable (rather than a state machine variable) let RepresentBindingAsLocal (bind: Binding) res2 m = - // printfn "found letrec state variable %s" bind.Var.DisplayName + if verbose then + printfn "LowerSeq: found local variable %s" bind.Var.DisplayName + { res2 with phase2 = (fun ctxt -> let generate2, dispose2, checkDispose2 = res2.phase2 ctxt @@ -190,13 +199,16 @@ let LowerSeqExpr g amap overallExpr = generate, dispose, checkDispose) stateVars = res2.stateVars } + /// Implement a decision to represent a 'let' binding as a state machine variable let RepresentBindingAsStateMachineLocal (bind: Binding) res2 m = - // printfn "found letrec state variable %s" bind.Var.DisplayName + if verbose then + printfn "LowerSeq: found state variable %s" bind.Var.DisplayName + let (TBind(v, e, sp)) = bind let sp, spm = match sp with - | SequencePointAtBinding m -> SequencePointsAtSeq, m - | _ -> SuppressSequencePointOnExprOfSequential, e.Range + | DebugPointAtBinding m -> DebugPointAtSequential.Both, m + | _ -> DebugPointAtSequential.StmtOnly, e.Range let vref = mkLocalValRef v { res2 with phase2 = (fun ctxt -> @@ -211,10 +223,12 @@ let LowerSeqExpr g amap overallExpr = let dispose = dispose2 let checkDispose = checkDispose2 generate, dispose, checkDispose) - stateVars = vref::res2.stateVars } + stateVars = vref :: res2.stateVars } let RepresentBindingsAsLifted mkBinds res2 = - // printfn "found top level let " + if verbose then + printfn "found top level let " + { res2 with phase2 = (fun ctxt -> let generate2, dispose2, checkDispose2 = res2.phase2 ctxt @@ -223,7 +237,7 @@ let LowerSeqExpr g amap overallExpr = let checkDispose = checkDispose2 generate, dispose, checkDispose) } - let rec Lower + let rec ConvertSeqExprCode isWholeExpr isTailCall // is this sequence in tailcall position? noDisposeContinuationLabel // represents the label for the code where there is effectively nothing to do to dispose the iterator for the current state @@ -238,48 +252,46 @@ let LowerSeqExpr g amap overallExpr = //return true //NEXT: let label = IL.generateCodeLabel() - Some { phase2 = (fun (pcv, currv, _nextv, pcMap) -> + Some { phase2 = (fun (pcVar, currVar, _nextv, pcMap) -> let generate = mkCompGenSequential m - (mkValSet m pcv (mkInt32 g m pcMap.[label])) - (mkSequential SequencePointsAtSeq m - (mkValSet m currv e) + (mkValSet m pcVar (mkInt32 g m pcMap.[label])) + (mkSequential DebugPointAtSequential.Both m + (mkValSet m currVar e) (mkCompGenSequential m - (Expr.Op(TOp.Return, [], [mkOne g m], m)) - (Expr.Op(TOp.Label label, [], [], m)))) + (Expr.Op (TOp.Return, [], [mkOne g m], m)) + (Expr.Op (TOp.Label label, [], [], m)))) let dispose = - mkCompGenSequential m - (Expr.Op(TOp.Label label, [], [], m)) - (Expr.Op(TOp.Goto currentDisposeContinuationLabel, [], [], m)) + mkLabelled m label + (Expr.Op (TOp.Goto currentDisposeContinuationLabel, [], [], m)) let checkDispose = - mkCompGenSequential m - (Expr.Op(TOp.Label label, [], [], m)) - (Expr.Op(TOp.Return, [], [mkBool g m (not (noDisposeContinuationLabel = currentDisposeContinuationLabel))], m)) + mkLabelled m label + (Expr.Op (TOp.Return, [], [mkBool g m (not (noDisposeContinuationLabel = currentDisposeContinuationLabel))], m)) generate, dispose, checkDispose) - labels=[label] + entryPoints=[label] stateVars=[] significantClose = false - capturedVars = emptyFreeVars + asyncVars = emptyFreeVars } | SeqDelay(delayedExpr, _elemTy) -> // printfn "found Seq.delay" // note, using 'isWholeExpr' here prevents 'seq { yield! e }' and 'seq { 0 .. 1000 }' from being compiled - Lower isWholeExpr isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel delayedExpr + ConvertSeqExprCode isWholeExpr isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel delayedExpr | SeqAppend(e1, e2, m) -> // printfn "found Seq.append" - let res1 = Lower false false noDisposeContinuationLabel currentDisposeContinuationLabel e1 - let res2 = Lower false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel e2 + let res1 = ConvertSeqExprCode false false noDisposeContinuationLabel currentDisposeContinuationLabel e1 + let res2 = ConvertSeqExprCode false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel e2 match res1, res2 with | Some res1, Some res2 -> - let capturedVars = - if res1.labels.IsEmpty then - res2.capturedVars + let asyncVars = + if res1.entryPoints.IsEmpty then + res2.asyncVars else // All of 'e2' is needed after resuming at any of the labels - unionFreeVars res1.capturedVars (freeInExpr CollectLocals e2) + unionFreeVars res1.asyncVars (freeInExpr CollectLocals e2) Some { phase2 = (fun ctxt -> let generate1, dispose1, checkDispose1 = res1.phase2 ctxt @@ -290,45 +302,45 @@ let LowerSeqExpr g amap overallExpr = let dispose = mkCompGenSequential m dispose2 dispose1 let checkDispose = mkCompGenSequential m checkDispose2 checkDispose1 generate, dispose, checkDispose) - labels= res1.labels @ res2.labels + entryPoints= res1.entryPoints @ res2.entryPoints stateVars = res1.stateVars @ res2.stateVars significantClose = res1.significantClose || res2.significantClose - capturedVars = capturedVars } + asyncVars = asyncVars } | _ -> None | SeqWhile(guardExpr, bodyExpr, m) -> // printfn "found Seq.while" - let resBody = Lower false false noDisposeContinuationLabel currentDisposeContinuationLabel bodyExpr + let resBody = ConvertSeqExprCode false false noDisposeContinuationLabel currentDisposeContinuationLabel bodyExpr match resBody with | Some res2 -> - let capturedVars = - if res2.labels.IsEmpty then - res2.capturedVars // the whole loopis synchronous, no labels + let asyncVars = + if res2.entryPoints.IsEmpty then + res2.asyncVars // the whole loop is synchronous, no labels else freeInExpr CollectLocals expr // everything is needed on subsequent iterations Some { phase2 = (fun ctxt -> let generate2, dispose2, checkDispose2 = res2.phase2 ctxt - let generate = mkWhile g (SequencePointAtWhileLoop guardExpr.Range, NoSpecialWhileLoopMarker, guardExpr, generate2, m) + let generate = mkWhile g (DebugPointAtWhile.Yes guardExpr.Range, NoSpecialWhileLoopMarker, guardExpr, generate2, m) let dispose = dispose2 let checkDispose = checkDispose2 generate, dispose, checkDispose) - labels = res2.labels + entryPoints = res2.entryPoints stateVars = res2.stateVars significantClose = res2.significantClose - capturedVars = capturedVars } + asyncVars = asyncVars } | _ -> None | SeqUsing(resource, v, body, elemTy, m) -> // printfn "found Seq.using" let reduction = - mkLet (SequencePointAtBinding body.Range) m v resource + mkLet (DebugPointAtBinding body.Range) m v resource (mkCallSeqFinally g m elemTy body (mkUnitDelayLambda g m (mkCallDispose g m v.Type (exprForVal m v)))) - Lower false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel reduction + ConvertSeqExprCode false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel reduction | SeqFor(inp, v, body, genElemTy, m) -> // printfn "found Seq.for" @@ -345,16 +357,16 @@ let LowerSeqExpr g amap overallExpr = (mkCallSeqGenerated g m genElemTy (mkUnitDelayLambda g m (callNonOverloadedMethod g amap m "MoveNext" inpEnumTy [enume])) (mkInvisibleLet m v (callNonOverloadedMethod g amap m "get_Current" inpEnumTy [enume]) (mkCoerceIfNeeded g (mkSeqTy g genElemTy) (tyOfExpr g body) body)))) - Lower false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel reduction + ConvertSeqExprCode false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel reduction | SeqTryFinally(e1, compensation, m) -> // printfn "found Seq.try/finally" let innerDisposeContinuationLabel = IL.generateCodeLabel() - let resBody = Lower false false noDisposeContinuationLabel innerDisposeContinuationLabel e1 + let resBody = ConvertSeqExprCode false false noDisposeContinuationLabel innerDisposeContinuationLabel e1 match resBody with | Some res1 -> - let capturedVars = unionFreeVars res1.capturedVars (freeInExpr CollectLocals compensation) - Some { phase2 = (fun ((pcv, _currv, _, pcMap) as ctxt) -> + let asyncVars = unionFreeVars res1.asyncVars (freeInExpr CollectLocals compensation) + Some { phase2 = (fun ((pcVar, _currv, _, pcMap) as ctxt) -> let generate1, dispose1, checkDispose1 = res1.phase2 ctxt let generate = // copy the compensation expression - one copy for the success continuation and one for the exception @@ -362,38 +374,35 @@ let LowerSeqExpr g amap overallExpr = mkCompGenSequential m // set the PC to the inner finally, so that if an exception happens we run the right finally (mkCompGenSequential m - (mkValSet m pcv (mkInt32 g m pcMap.[innerDisposeContinuationLabel])) + (mkValSet m pcVar (mkInt32 g m pcMap.[innerDisposeContinuationLabel])) generate1 ) // set the PC past the try/finally before trying to run it, to make sure we only run it once - (mkCompGenSequential m - (Expr.Op(TOp.Label innerDisposeContinuationLabel, [], [], m)) + (mkLabelled m innerDisposeContinuationLabel (mkCompGenSequential m - (mkValSet m pcv (mkInt32 g m pcMap.[currentDisposeContinuationLabel])) + (mkValSet m pcVar (mkInt32 g m pcMap.[currentDisposeContinuationLabel])) compensation)) let dispose = // generate inner try/finallys, then outer try/finallys mkCompGenSequential m dispose1 // set the PC past the try/finally before trying to run it, to make sure we only run it once - (mkCompGenSequential m - (Expr.Op(TOp.Label innerDisposeContinuationLabel, [], [], m)) + (mkLabelled m innerDisposeContinuationLabel (mkCompGenSequential m - (mkValSet m pcv (mkInt32 g m pcMap.[currentDisposeContinuationLabel])) + (mkValSet m pcVar (mkInt32 g m pcMap.[currentDisposeContinuationLabel])) (mkCompGenSequential m compensation - (Expr.Op(TOp.Goto currentDisposeContinuationLabel, [], [], m))))) + (Expr.Op (TOp.Goto currentDisposeContinuationLabel, [], [], m))))) let checkDispose = mkCompGenSequential m checkDispose1 - (mkCompGenSequential m - (Expr.Op(TOp.Label innerDisposeContinuationLabel, [], [], m)) - (Expr.Op(TOp.Return, [], [mkTrue g m (* yes, we must dispose!!! *) ], m))) + (mkLabelled m innerDisposeContinuationLabel + (Expr.Op (TOp.Return, [], [mkTrue g m (* yes, we must dispose!!! *) ], m))) generate, dispose, checkDispose) - labels = innerDisposeContinuationLabel :: res1.labels + entryPoints = innerDisposeContinuationLabel :: res1.entryPoints stateVars = res1.stateVars significantClose = true - capturedVars = capturedVars } + asyncVars = asyncVars } | _ -> None @@ -401,37 +410,37 @@ let LowerSeqExpr g amap overallExpr = // printfn "found Seq.empty" Some { phase2 = (fun _ -> let generate = mkUnit g m - let dispose = Expr.Op(TOp.Goto currentDisposeContinuationLabel, [], [], m) - let checkDispose = Expr.Op(TOp.Goto currentDisposeContinuationLabel, [], [], m) + let dispose = Expr.Op (TOp.Goto currentDisposeContinuationLabel, [], [], m) + let checkDispose = Expr.Op (TOp.Goto currentDisposeContinuationLabel, [], [], m) generate, dispose, checkDispose) - labels = [] + entryPoints = [] stateVars = [] significantClose = false - capturedVars = emptyFreeVars } + asyncVars = emptyFreeVars } - | Expr.Sequential(x1, x2, NormalSeq, ty, m) -> - match Lower false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel x2 with + | Expr.Sequential (x1, x2, NormalSeq, ty, m) -> + match ConvertSeqExprCode false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel x2 with | Some res2-> // printfn "found sequential execution" Some { res2 with phase2 = (fun ctxt -> let generate2, dispose2, checkDispose2 = res2.phase2 ctxt - let generate = Expr.Sequential(x1, generate2, NormalSeq, ty, m) + let generate = Expr.Sequential (x1, generate2, NormalSeq, ty, m) let dispose = dispose2 let checkDispose = checkDispose2 generate, dispose, checkDispose) } | None -> None - | Expr.Let(bind, bodyExpr, m, _) + | Expr.Let (bind, bodyExpr, m, _) // Restriction: compilation of sequence expressions containing non-toplevel constrained generic functions is not supported - when bind.Var.IsCompiledAsTopLevel || not (IsGenericValWithGenericContraints g bind.Var) -> + when bind.Var.IsCompiledAsTopLevel || not (IsGenericValWithGenericConstraints g bind.Var) -> - let resBody = Lower false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel bodyExpr + let resBody = ConvertSeqExprCode false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel bodyExpr match resBody with | Some res2 -> if bind.Var.IsCompiledAsTopLevel then Some (RepresentBindingsAsLifted (mkLetBind m bind) res2) - elif not (res2.capturedVars.FreeLocals.Contains(bind.Var)) then + elif not (res2.asyncVars.FreeLocals.Contains(bind.Var)) then // printfn "found state variable %s" bind.Var.DisplayName Some (RepresentBindingAsLocal bind res2 m) else @@ -441,7 +450,7 @@ let LowerSeqExpr g amap overallExpr = None (* - | Expr.LetRec(binds, e2, m, _) + | Expr.LetRec (binds, e2, m, _) when // Restriction: only limited forms of "let rec" in sequence expressions can be handled by assignment to state local values (let recvars = valsOfBinds binds |> List.map (fun v -> (v, 0)) |> ValMap.OfList @@ -449,17 +458,17 @@ let LowerSeqExpr g amap overallExpr = // Rule 1 - IsCompiledAsTopLevel require no state local value bind.Var.IsCompiledAsTopLevel || // Rule 2 - funky constrained local funcs not allowed - not (IsGenericValWithGenericContraints g bind.Var)) && + not (IsGenericValWithGenericConstraints g bind.Var)) && binds |> List.count (fun bind -> // Rule 3 - Recursive non-lambda and repack values are allowed match stripExpr bind.Expr with | Expr.Lambda _ | Expr.TyLambda _ -> false // "let v = otherv" bindings get produced for environment packing by InnerLambdasToTopLevelFuncs.fs, we can accept and compiler these ok - | Expr.Val(v, _, _) when not (recvars.ContainsVal v.Deref) -> false + | Expr.Val (v, _, _) when not (recvars.ContainsVal v.Deref) -> false | _ -> true) <= 1) -> - match Lower false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel e2 with + match ConvertSeqExprCode false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel e2 with | Some res2 -> let topLevelBinds, nonTopLevelBinds = binds |> List.partition (fun bind -> bind.Var.IsCompiledAsTopLevel) // Represent the closure-capturing values as state machine locals. They may still be recursively-referential @@ -470,22 +479,29 @@ let LowerSeqExpr g amap overallExpr = | None -> None *) + // LIMITATION: non-trivial pattern matches involving or-patterns or active patterns where bindings can't be + // transferred to the r.h.s. are not yet compiled. + // + // TODO: remove this limitation | Expr.Match (spBind, exprm, pt, targets, m, ty) when targets |> Array.forall (fun (TTarget(vs, _e, _spTarget)) -> isNil vs) -> // lower all the targets. abandon if any fail to lower - let tglArray = targets |> Array.map (fun (TTarget(_vs, targetExpr, _spTarget)) -> Lower false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel targetExpr) - // LIMITATION: non-trivial pattern matches involving or-patterns or active patterns where bindings can't be - // transferred to the r.h.s. are not yet compiled. + // lower all the targets. abandon if any fail to lower + let tglArray = targets |> Array.map (fun (TTarget(_vs, targetExpr, _spTarget)) -> ConvertSeqExprCode false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel targetExpr) if tglArray |> Array.forall Option.isSome then let tglArray = Array.map Option.get tglArray let tgl = Array.toList tglArray - let labs = tgl |> List.collect (fun res -> res.labels) - let (capturedVars, _) = + let labs = tgl |> List.collect (fun res -> res.entryPoints) + + let (asyncVars, _) = ((emptyFreeVars, false), Array.zip targets tglArray) ||> Array.fold (fun (fvs, seenLabel) ((TTarget(_vs, e, _spTarget)), res) -> if seenLabel then unionFreeVars fvs (freeInExpr CollectLocals e), true - else res.capturedVars, not res.labels.IsEmpty) + else res.asyncVars, not res.entryPoints.IsEmpty) + let stateVars = tgl |> List.collect (fun res -> res.stateVars) + let significantClose = tgl |> List.exists (fun res -> res.significantClose) + Some { phase2 = (fun ctxt -> let gtgs, disposals, checkDisposes = (Array.toList targets, tgl) @@ -498,10 +514,10 @@ let LowerSeqExpr g amap overallExpr = let dispose = if isNil disposals then mkUnit g m else List.reduce (mkCompGenSequential m) disposals let checkDispose = if isNil checkDisposes then mkFalse g m else List.reduce (mkCompGenSequential m) checkDisposes generate, dispose, checkDispose) - labels=labs + entryPoints=labs stateVars = stateVars significantClose = significantClose - capturedVars = capturedVars } + asyncVars = asyncVars } else None @@ -512,12 +528,12 @@ let LowerSeqExpr g amap overallExpr = // Note, however, this leads to a loss of tailcalls: the case not // handled correctly yet is sequence expressions that use yield! in the last position // This can give rise to infinite iterator chains when implemented by the naive expansion to - // �for x in e yield e�. For example consider this: + // 'for x in e yield e'. For example consider this: // // let rec rwalk x = { yield x // yield! rwalk (x + rand()) } // - // This is the moral equivalent of a tailcall optimization. These also don�t compile well + // This is the moral equivalent of a tailcall optimization. These also don't compile well // in the C# compilation model | arbitrarySeqExpr -> @@ -540,170 +556,217 @@ let LowerSeqExpr g amap overallExpr = //return 2 //NEXT: let label = IL.generateCodeLabel() - Some { phase2 = (fun (pcv, _currv, nextv, pcMap) -> + Some { phase2 = (fun (pcVar, _currv, nextVar, pcMap) -> let generate = mkCompGenSequential m - (mkValSet m pcv (mkInt32 g m pcMap.[label])) - (mkSequential SequencePointsAtSeq m - (mkAddrSet m nextv arbitrarySeqExpr) + (mkValSet m pcVar (mkInt32 g m pcMap.[label])) + (mkSequential DebugPointAtSequential.Both m + (mkAddrSet m nextVar arbitrarySeqExpr) (mkCompGenSequential m - (Expr.Op(TOp.Return, [], [mkTwo g m], m)) - (Expr.Op(TOp.Label label, [], [], m)))) + (Expr.Op (TOp.Return, [], [mkTwo g m], m)) + (Expr.Op (TOp.Label label, [], [], m)))) let dispose = - mkCompGenSequential m - (Expr.Op(TOp.Label label, [], [], m)) - (Expr.Op(TOp.Goto currentDisposeContinuationLabel, [], [], m)) + mkLabelled m label + (Expr.Op (TOp.Goto currentDisposeContinuationLabel, [], [], m)) let checkDispose = - mkCompGenSequential m - (Expr.Op(TOp.Label label, [], [], m)) - (Expr.Op(TOp.Return, [], [mkFalse g m], m)) + mkLabelled m label + (Expr.Op (TOp.Return, [], [mkFalse g m], m)) generate, dispose, checkDispose) - labels=[label] + entryPoints=[label] stateVars=[] significantClose = false - capturedVars = emptyFreeVars } + asyncVars = emptyFreeVars } else let v, ve = mkCompGenLocal m "v" inpElemTy - Lower false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel (mkCallSeqCollect g m inpElemTy inpElemTy (mkLambdaNoType g m v (mkCallSeqSingleton g m inpElemTy ve)) arbitrarySeqExpr) + ConvertSeqExprCode false isTailCall noDisposeContinuationLabel currentDisposeContinuationLabel (mkCallSeqCollect g m inpElemTy inpElemTy (mkLambdaNoType g m v (mkCallSeqSingleton g m inpElemTy ve)) arbitrarySeqExpr) match overallExpr with - | Seq(e, ty) -> + | Seq g (e, ty) -> // printfn "found seq { ... } or Seq.delay (fun () -> ...) in FSharp.Core.dll" let m = e.Range let initLabel = IL.generateCodeLabel() let noDisposeContinuationLabel = IL.generateCodeLabel() - match Lower true true noDisposeContinuationLabel noDisposeContinuationLabel e with + + // Perform phase1 + match ConvertSeqExprCode true true noDisposeContinuationLabel noDisposeContinuationLabel e with | Some res -> - let labs = res.labels + + // After phase1, create the variables for the state machine and work out a program counter for each label. + let labs = res.entryPoints let stateVars = res.stateVars // printfn "successfully lowered, found %d state variables and %d labels!" stateVars.Length labs.Length - let pcv, pce = mkMutableCompGenLocal m "pc" g.int32_ty - let currv, _curre = mkMutableCompGenLocal m "current" ty - let nextv, _nexte = mkMutableCompGenLocal m "next" (mkByrefTy g (mkSeqTy g ty)) - let nextvref = mkLocalValRef nextv - let pcvref = mkLocalValRef pcv - let currvref = mkLocalValRef currv + let pcVar, pcExpr = mkMutableCompGenLocal m "pc" g.int32_ty + let currVar, _currExpr = mkMutableCompGenLocal m "current" ty + let nextVar, _nextExpr = mkMutableCompGenLocal m "next" (mkByrefTy g (mkSeqTy g ty)) + let nextVarRef = mkLocalValRef nextVar + let pcVarRef = mkLocalValRef pcVar + let currVarRef = mkLocalValRef currVar let pcs = labs |> List.mapi (fun i _ -> i + 1) let pcDone = labs.Length + 1 let pcInit = 0 let pc2lab = Map.ofList ((pcInit, initLabel) :: (pcDone, noDisposeContinuationLabel) :: List.zip pcs labs) let lab2pc = Map.ofList ((initLabel, pcInit) :: (noDisposeContinuationLabel, pcDone) :: List.zip labs pcs) - let stateMachineExpr, disposalExpr, checkDisposeExpr = res.phase2 (pcvref, currvref, nextvref, lab2pc) - // Add on the final 'return false' to indicate the iteration is complete - let stateMachineExpr = + + // Execute phase2, building the core of the the GenerateNext, Dispose and CheckDispose methods + let generateExprCore, disposalExprCore, checkDisposeExprCore = + res.phase2 (pcVarRef, currVarRef, nextVarRef, lab2pc) + + // Add on the final label and cleanup to the GenerateNext method + // generateExpr; + // pc <- PC_DONE + // noDispose: + // current <- null + // return 0 + let generateExprWithCleanup = mkCompGenSequential m - stateMachineExpr + generateExprCore (mkCompGenSequential m // set the pc to "finished" - (mkValSet m pcvref (mkInt32 g m pcDone)) - (mkCompGenSequential m - (Expr.Op(TOp.Label noDisposeContinuationLabel, [], [], m)) + (mkValSet m pcVarRef (mkInt32 g m pcDone)) + (mkLabelled m noDisposeContinuationLabel (mkCompGenSequential m // zero out the current value to free up its memory - (mkValSet m currvref (mkDefault (m, currvref.Type))) - (Expr.Op(TOp.Return, [], [mkZero g m], m))))) - let checkDisposeExpr = + (mkValSet m currVarRef (mkDefault (m, currVarRef.Type))) + (Expr.Op (TOp.Return, [], [mkZero g m], m))))) + + // Add on the final label to the 'CheckDispose' method + // checkDisposeExprCore + // noDispose: + // return false + let checkDisposeExprWithCleanup = mkCompGenSequential m - checkDisposeExpr - (mkCompGenSequential m - (Expr.Op(TOp.Label noDisposeContinuationLabel, [], [], m)) - (Expr.Op(TOp.Return, [], [mkFalse g m], m))) + checkDisposeExprCore + (mkLabelled m noDisposeContinuationLabel + (Expr.Op (TOp.Return, [], [mkFalse g m], m))) + // A utility to add a jump table to the three generated methods let addJumpTable isDisposal expr = - let mbuilder = new MatchBuilder(NoSequencePointAtInvisibleBinding, m ) - let mkGotoLabelTarget lab = mbuilder.AddResultTarget(Expr.Op(TOp.Goto lab, [], [], m), SuppressSequencePointAtTarget) + let mbuilder = new MatchBuilder(NoDebugPointAtInvisibleBinding, m ) + let mkGotoLabelTarget lab = mbuilder.AddResultTarget(Expr.Op (TOp.Goto lab, [], [], m), DebugPointForTarget.No) let dtree = - TDSwitch(pce, + TDSwitch(pcExpr, [ - // no disposal action for the initial state (pc = 0) + // Add an empty disposal action for the initial state (pc = 0) if isDisposal then yield mkCase(DecisionTreeTest.Const(Const.Int32 pcInit), mkGotoLabelTarget noDisposeContinuationLabel) + + // Yield one target for each PC, where the action of the target is to goto the appropriate label for pc in pcs do yield mkCase(DecisionTreeTest.Const(Const.Int32 pc), mkGotoLabelTarget pc2lab.[pc]) + + // Yield one target for the 'done' program counter, where the action of the target is to continuation label yield mkCase(DecisionTreeTest.Const(Const.Int32 pcDone), mkGotoLabelTarget noDisposeContinuationLabel) ], Some(mkGotoLabelTarget pc2lab.[pcInit]), m) let table = mbuilder.Close(dtree, m, g.int_ty) - mkCompGenSequential m table (mkCompGenSequential m (Expr.Op(TOp.Label initLabel, [], [], m)) expr) - - let handleExeceptionsInDispose disposalExpr = - // let mutable exn : exn = null - // while(this.pc <> END_STATE) do - // try - // ``disposalExpr'' - // with e -> exn <- e - // if exn <> null then raise exn + mkCompGenSequential m table (mkLabelled m initLabel expr) + + // A utility to handle the cases where exceptions are raised by the disposal logic. + // We wrap the disposal state machine in a loop that repeatedly drives the disposal logic of the + // state machine through each disposal state, then re-raise the last exception raised. + // + // let mutable exn : exn = null + // while(this.pc <> END_STATE) do + // try + // ``disposalExpr`` + // with e -> exn <- e + // if exn <> null then raise exn + let handleExceptionsInDispose disposalExpr = let exnV, exnE = mkMutableCompGenLocal m "exn" g.exn_ty let exnVref = mkLocalValRef exnV let startLabel = IL.generateCodeLabel() - let doneLabel = IL.generateCodeLabel () + let doneDisposeLabel = IL.generateCodeLabel () // try ``disposalExpr'' with e -> exn <- e let eV, eE = mkLocal m "e" g.exn_ty let efV, _ = mkLocal m "ef" g.exn_ty - let assignToExn = Expr.Op(TOp.LValueOp(LValueOperation.LSet, exnVref), [], [eE], m) + + // exn <- e + let assignToExn = Expr.Op (TOp.LValueOp (LValueOperation.LSet, exnVref), [], [eE], m) + + // try + // ``disposalExpr`` + // with e -> exn <- e let exceptionCatcher = mkTryWith g (disposalExpr, - efV, Expr.Const((Const.Bool true), m, g.bool_ty), + efV, Expr.Const ((Const.Bool true), m, g.bool_ty), eV, assignToExn, m, g.unit_ty, - NoSequencePointAtTry, NoSequencePointAtWith) - - - // while(this.pc != END_STATE) + DebugPointAtTry.No, DebugPointAtWith.No) + + // Make the loop + // + // startLabel: + // match this.pc with + // | PC_DONE -> goto DONE_DISPOSE + // | _ -> () + // try + // ``disposalExpr`` + // with e -> + // exn <- e + // goto startLabel + // DONE_DISPOSE: let whileLoop = - let mbuilder = new MatchBuilder(NoSequencePointAtInvisibleBinding, m) - let addResultTarget e = mbuilder.AddResultTarget(e, SuppressSequencePointAtTarget) + let mbuilder = new MatchBuilder(NoDebugPointAtInvisibleBinding, m) + let addResultTarget e = mbuilder.AddResultTarget(e, DebugPointForTarget.No) let dtree = - TDSwitch(pce, - [ mkCase((DecisionTreeTest.Const(Const.Int32 pcDone)), addResultTarget (Expr.Op(TOp.Goto doneLabel, [], [], m)) ) ], + TDSwitch(pcExpr, + [ mkCase((DecisionTreeTest.Const(Const.Int32 pcDone)), addResultTarget (Expr.Op (TOp.Goto doneDisposeLabel, [], [], m)) ) ], Some (addResultTarget (mkUnit g m)), m) let pcIsEndStateComparison = mbuilder.Close(dtree, m, g.unit_ty) - mkCompGenSequential m - (Expr.Op((TOp.Label startLabel), [], [], m)) + mkLabelled m startLabel (mkCompGenSequential m pcIsEndStateComparison (mkCompGenSequential m exceptionCatcher (mkCompGenSequential m - (Expr.Op((TOp.Goto startLabel), [], [], m)) - (Expr.Op((TOp.Label doneLabel), [], [], m)) + (Expr.Op ((TOp.Goto startLabel), [], [], m)) + (Expr.Op ((TOp.Label doneDisposeLabel), [], [], m)) ) ) ) // if exn != null then raise exn let doRaise = - mkNonNullCond g m g.unit_ty exnE (mkThrow m g.unit_ty exnE) (Expr.Const(Const.Unit, m, g.unit_ty)) + mkNonNullCond g m g.unit_ty exnE (mkThrow m g.unit_ty exnE) (Expr.Const (Const.Unit, m, g.unit_ty)) + // let mutable exn = null + // --loop-- + // if exn != null then raise exn mkLet - NoSequencePointAtLetBinding m exnV (Expr.Const(Const.Zero, m, g.exn_ty)) + NoDebugPointAtLetBinding m exnV (Expr.Const (Const.Zero, m, g.exn_ty)) (mkCompGenSequential m whileLoop doRaise) - let stateMachineExprWithJumpTable = addJumpTable false stateMachineExpr - let disposalExpr = + // Add the jump table to the GenerateNext method + let generateExprWithJumpTable = + addJumpTable false generateExprWithCleanup + + // Add the jump table to the Dispose method + let disposalExprWithJumpTable = if res.significantClose then let disposalExpr = mkCompGenSequential m - disposalExpr - (mkCompGenSequential m - (Expr.Op(TOp.Label noDisposeContinuationLabel, [], [], m)) + disposalExprCore + (mkLabelled m noDisposeContinuationLabel (mkCompGenSequential m // set the pc to "finished" - (mkValSet m pcvref (mkInt32 g m pcDone)) + (mkValSet m pcVarRef (mkInt32 g m pcDone)) // zero out the current value to free up its memory - (mkValSet m currvref (mkDefault (m, currvref.Type))))) + (mkValSet m currVarRef (mkDefault (m, currVarRef.Type))))) disposalExpr |> addJumpTable true - |> handleExeceptionsInDispose + |> handleExceptionsInDispose else - (mkValSet m pcvref (mkInt32 g m pcDone)) + mkValSet m pcVarRef (mkInt32 g m pcDone) + + // Add the jump table to the CheckDispose method + let checkDisposeExprWithJumpTable = + addJumpTable true checkDisposeExprWithCleanup - let checkDisposeExprWithJumpTable = addJumpTable true checkDisposeExpr - // all done, no return the results - Some (nextvref, pcvref, currvref, stateVars, stateMachineExprWithJumpTable, disposalExpr, checkDisposeExprWithJumpTable, ty, m) + // all done, now return the results + Some (nextVarRef, pcVarRef, currVarRef, stateVars, generateExprWithJumpTable, disposalExprWithJumpTable, checkDisposeExprWithJumpTable, ty, m) | None -> // printfn "FAILED: no compilation found! %s" (stringOfRange m) diff --git a/src/fcs-fable/src/fsharp/LowerCallsAndSeqs.fsi b/src/fcs-fable/src/fsharp/LowerCallsAndSeqs.fsi new file mode 100644 index 0000000000..16989637e2 --- /dev/null +++ b/src/fcs-fable/src/fsharp/LowerCallsAndSeqs.fsi @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +module internal FSharp.Compiler.LowerCallsAndSeqs + +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.Import +open FSharp.Compiler.Range + +/// An "expr -> expr" pass that eta-expands under-applied values of +/// known arity to lambda expressions and beta-var-reduces to bind +/// any known arguments. The results are later optimized by the peephole +/// optimizer in opt.fs +val LowerImplFile: g: TcGlobals -> assembly: TypedImplFile -> TypedImplFile + +/// Analyze a TAST expression to detect the elaborated form of a sequence expression. +/// Then compile it to a state machine represented as a TAST containing goto, return and label nodes. +/// The returned state machine will also contain references to state variables (from internal 'let' bindings), +/// a program counter (pc) that records the current state, and a current generated value (current). +/// All these variables are then represented as fields in a hosting closure object along with any additional +/// free variables of the sequence expression. +val ConvertSequenceExprToObject: g: TcGlobals -> amap: ImportMap -> overallExpr: Expr -> (ValRef * ValRef * ValRef * ValRef list * Expr * Expr * Expr * TType * range) option + +val IsPossibleSequenceExpr: g: TcGlobals -> overallExpr: Expr -> bool diff --git a/src/fcs-fable/src/fsharp/MethodCalls.fs b/src/fcs-fable/src/fsharp/MethodCalls.fs index cbd17ea1d2..4c6b5f5790 100644 --- a/src/fcs-fable/src/fsharp/MethodCalls.fs +++ b/src/fcs-fable/src/fsharp/MethodCalls.fs @@ -3,29 +3,34 @@ /// Logic associated with resolving method calls. module internal FSharp.Compiler.MethodCalls +open Internal.Utilities + open FSharp.Compiler open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.Range -open FSharp.Compiler.Ast +open FSharp.Compiler.AccessibilityLogic +open FSharp.Compiler.AttributeChecking open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Lib +open FSharp.Compiler.Features +open FSharp.Compiler.InfoReader open FSharp.Compiler.Infos -open FSharp.Compiler.AccessibilityLogic +open FSharp.Compiler.Lib open FSharp.Compiler.NameResolution -open FSharp.Compiler.InfoReader -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.Tastops.DebugPrint +open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.TypedTreeOps.DebugPrint open FSharp.Compiler.TypeRelations -open FSharp.Compiler.AttributeChecking #if !NO_EXTENSIONTYPING open FSharp.Compiler.ExtensionTyping #endif - //------------------------------------------------------------------------- // Sets of methods involved in overload resolution and trait constraint // satisfaction. @@ -41,13 +46,17 @@ open FSharp.Compiler.ExtensionTyping /// expression, e.g. a lambda expression may be converted to a delegate as /// an adhoc conversion. /// -/// The bool indicates if named using a '?' +/// The bool indicates if named using a '?', making the caller argument explicit-optional type CallerArg<'T> = /// CallerArg(ty, range, isOpt, exprInfo) - | CallerArg of TType * range * bool * 'T - member x.Type = (let (CallerArg(ty, _, _, _)) = x in ty) + | CallerArg of ty: TType * range: range * isOpt: bool * exprInfo: 'T + + member x.CallerArgumentType = (let (CallerArg(ty, _, _, _)) = x in ty) + member x.Range = (let (CallerArg(_, m, _, _)) = x in m) - member x.IsOptional = (let (CallerArg(_, _, isOpt, _)) = x in isOpt) + + member x.IsExplicitOptional = (let (CallerArg(_, _, isOpt, _)) = x in isOpt) + member x.Expr = (let (CallerArg(_, _, _, expr)) = x in expr) /// Represents the information about an argument in the method being called @@ -76,12 +85,16 @@ let GetCalledArg (pos, isParamArray, optArgInfo, callerInfo, isInArg, isOutArg, /// Represents a match between a caller argument and a called argument, arising from either /// a named argument or an unnamed argument. type AssignedCalledArg<'T> = + { /// The identifier for a named argument, if any NamedArgIdOpt : Ident option + /// The called argument in the method CalledArg: CalledArg + /// The argument on the caller side CallerArg: CallerArg<'T> } + member x.Position = x.CalledArg.Position /// Represents the possibilities for a named-setter argument (a property, field, or a record field setter) @@ -95,14 +108,119 @@ type AssignedItemSetter<'T> = AssignedItemSetter of Ident * AssignedItemSetterTa type CallerNamedArg<'T> = | CallerNamedArg of Ident * CallerArg<'T> + member x.Ident = (let (CallerNamedArg(id, _)) = x in id) + member x.Name = x.Ident.idText + member x.CallerArg = (let (CallerNamedArg(_, a)) = x in a) +/// Represents the list of unnamed / named arguments at method call site +/// remark: The usage of list list is due to tupling and currying of arguments, +/// stemming from SynValInfo in the AST. +[] +type CallerArgs<'T> = + { + Unnamed: CallerArg<'T> list list + Named: CallerNamedArg<'T> list list + } + static member Empty : CallerArgs<'T> = { Unnamed = []; Named = [] } + member x.CallerArgCounts = (List.length x.Unnamed, List.length x.Named) + member x.CurriedCallerArgs = List.zip x.Unnamed x.Named + member x.ArgumentNamesAndTypes = + [ (x.Unnamed |> List.map (List.map (fun i -> None, i.CallerArgumentType))) |> List.concat + (x.Named |> List.map (List.map (fun i -> Some i.Name, i.CallerArg.CallerArgumentType))) |> List.concat ] + |> List.concat //------------------------------------------------------------------------- // Callsite conversions //------------------------------------------------------------------------- +// If the called method argument is a delegate type, and the caller is known to be a function type, then the caller may provide a function +// If the called method argument is an Expression type, and the caller is known to be a function type, then the caller may provide a T +// If the called method argument is an [] Quotations.Expr, and the caller is not known to be a quoted expression type, then the caller may provide a T +let AdjustCalledArgTypeForLinqExpressionsAndAutoQuote (infoReader: InfoReader) callerArgTy (calledArg: CalledArg) m = + let g = infoReader.g + let calledArgTy = calledArg.CalledArgumentType + + let adjustDelegateTy calledTy = + let (SigOfFunctionForDelegate(_, delArgTys, _, fty)) = GetSigOfFunctionForDelegate infoReader calledTy m AccessibleFromSomewhere + let delArgTys = if isNil delArgTys then [g.unit_ty] else delArgTys + if (fst (stripFunTy g callerArgTy)).Length = delArgTys.Length then + fty + else + calledArgTy + + if isDelegateTy g calledArgTy && isFunTy g callerArgTy then + adjustDelegateTy calledArgTy + + elif isLinqExpressionTy g calledArgTy && isFunTy g callerArgTy then + let calledArgTyNoExpr = destLinqExpressionTy g calledArgTy + if isDelegateTy g calledArgTyNoExpr then + adjustDelegateTy calledArgTyNoExpr + else + calledArgTy + + elif calledArg.ReflArgInfo.AutoQuote && isQuotedExprTy g calledArgTy && not (isQuotedExprTy g callerArgTy) then + destQuotedExprTy g calledArgTy + + else calledArgTy + +/// Adjust the called argument type to take into account whether the caller's argument is CSharpMethod(?arg=Some(3)) or CSharpMethod(arg=1) +let AdjustCalledArgTypeForOptionals (g: TcGlobals) enforceNullableOptionalsKnownTypes (calledArg: CalledArg) calledArgTy (callerArg: CallerArg<_>) = + + if callerArg.IsExplicitOptional then + match calledArg.OptArgInfo with + // CSharpMethod(?x = arg), optional C#-style argument, may have nullable type + | CallerSide _ -> + if g.langVersion.SupportsFeature LanguageFeature.NullableOptionalInterop then + if isNullableTy g calledArgTy then + mkOptionTy g (destNullableTy g calledArgTy) + else + mkOptionTy g calledArgTy + else + calledArgTy + + // FSharpMethod(?x = arg), optional F#-style argument + | CalleeSide -> + // In this case, the called argument will already have option type + calledArgTy + + | NotOptional -> + // This condition represents an error but the error is raised in later processing + calledArgTy + else + match calledArg.OptArgInfo with + | NotOptional -> + calledArgTy + + // CSharpMethod(x = arg), optional C#-style argument, may have type Nullable. + // The arg should have type ty. However for backwards compat, we also allow arg to have type Nullable + | CallerSide _ -> + if isNullableTy g calledArgTy && g.langVersion.SupportsFeature LanguageFeature.NullableOptionalInterop then + // If inference has worked out it's a nullable then use this + if isNullableTy g callerArg.CallerArgumentType then + calledArgTy + // If inference has worked out it's a struct (e.g. an int) then use this + elif isStructTy g callerArg.CallerArgumentType then + destNullableTy g calledArgTy + // If neither and we are at the end of overload resolution then use the Nullable + elif enforceNullableOptionalsKnownTypes then + calledArgTy + // If at the beginning of inference then use a type variable + else + let compgenId = mkSynId range0 unassignedTyparName + let NewInferenceType () = mkTyparTy (Construct.NewTypar (TyparKind.Type, TyparRigidity.Flexible, Typar(compgenId, NoStaticReq, true), false, TyparDynamicReq.No, [], false, false)) + NewInferenceType() + else + calledArgTy + + // FSharpMethod(x = arg), optional F#-style argument, should have option type + | CalleeSide -> + if isOptionTy g calledArgTy then + destOptionTy g calledArgTy + else + calledArgTy + // F# supports three adhoc conversions at method callsites (note C# supports more, though ones // such as implicit conversions interact badly with type inference). // @@ -122,12 +240,12 @@ type CallerNamedArg<'T> = // The function AdjustCalledArgType detects this and refuses to apply the default byref-to-ref transformation. // // The function AdjustCalledArgType also adjusts for optional arguments. -let AdjustCalledArgType (infoReader: InfoReader) isConstraint (calledArg: CalledArg) (callerArg: CallerArg<_>) = +let AdjustCalledArgType (infoReader: InfoReader) isConstraint enforceNullableOptionalsKnownTypes (calledArg: CalledArg) (callerArg: CallerArg<_>) = let g = infoReader.g + let m = callerArg.Range // #424218 - when overload resolution is part of constraint solving - do not perform type-directed conversions let calledArgTy = calledArg.CalledArgumentType - let callerArgTy = callerArg.Type - let m = callerArg.Range + let callerArgTy = callerArg.CallerArgumentType if isConstraint then calledArgTy else @@ -151,41 +269,9 @@ let AdjustCalledArgType (infoReader: InfoReader) isConstraint (calledArg: Called mkRefCellTy g (destByrefTy g calledArgTy) else - // If the called method argument is a delegate type, then the caller may provide a function - let calledArgTy = - let adjustDelegateTy calledTy = - let (SigOfFunctionForDelegate(_, delArgTys, _, fty)) = GetSigOfFunctionForDelegate infoReader calledTy m AccessibleFromSomewhere - let delArgTys = if isNil delArgTys then [g.unit_ty] else delArgTys - if (fst (stripFunTy g callerArgTy)).Length = delArgTys.Length - then fty - else calledArgTy - - if isDelegateTy g calledArgTy && isFunTy g callerArgTy then - adjustDelegateTy calledArgTy - - elif isLinqExpressionTy g calledArgTy && isFunTy g callerArgTy then - let origArgTy = calledArgTy - let calledArgTy = destLinqExpressionTy g calledArgTy - if isDelegateTy g calledArgTy then - adjustDelegateTy calledArgTy - else - // BUG 435170: called arg is Expr<'t> where 't is not delegate - such conversion is not legal -> return original type - origArgTy - - elif calledArg.ReflArgInfo.AutoQuote && isQuotedExprTy g calledArgTy && not (isQuotedExprTy g callerArgTy) then - destQuotedExprTy g calledArgTy - - else calledArgTy - - // Adjust the called argument type to take into account whether the caller's argument is M(?arg=Some(3)) or M(arg=1) - // If the called method argument is optional with type Option, then the caller may provide a T, unless their argument is propagating-optional (i.e. isOptCallerArg) - let calledArgTy = - match calledArg.OptArgInfo with - | NotOptional -> calledArgTy - | CalleeSide when not callerArg.IsOptional && isOptionTy g calledArgTy -> destOptionTy g calledArgTy - | CalleeSide | CallerSide _ -> calledArgTy - calledArgTy - + let calledArgTy2 = AdjustCalledArgTypeForLinqExpressionsAndAutoQuote infoReader callerArgTy calledArg m + let calledArgTy3 = AdjustCalledArgTypeForOptionals g enforceNullableOptionalsKnownTypes calledArg calledArgTy2 callerArg + calledArgTy3 //------------------------------------------------------------------------- // CalledMeth @@ -194,18 +280,24 @@ let AdjustCalledArgType (infoReader: InfoReader) isConstraint (calledArg: Called type CalledMethArgSet<'T> = { /// The called arguments corresponding to "unnamed" arguments UnnamedCalledArgs : CalledArg list + /// Any unnamed caller arguments not otherwise assigned UnnamedCallerArgs : CallerArg<'T> list + /// The called "ParamArray" argument, if any ParamArrayCalledArgOpt : CalledArg option + /// Any unnamed caller arguments assigned to a "param array" argument ParamArrayCallerArgs : CallerArg<'T> list + /// Named args AssignedNamedArgs: AssignedCalledArg<'T> list } + member x.NumUnnamedCallerArgs = x.UnnamedCallerArgs.Length + member x.NumAssignedNamedArgs = x.AssignedNamedArgs.Length - member x.NumUnnamedCalledArgs = x.UnnamedCalledArgs.Length + member x.NumUnnamedCalledArgs = x.UnnamedCalledArgs.Length let MakeCalledArgs amap m (minfo: MethInfo) minst = // Mark up the arguments with their position, so we can sort them back into order later @@ -229,18 +321,31 @@ type CalledMeth<'T> (infoReader: InfoReader, nameEnv: NameResolutionEnv option, isCheckingAttributeCall, - freshenMethInfo, // a function to help generate fresh type variables the property setters methods in generic classes + /// a function to help generate fresh type variables the property setters methods in generic classes + freshenMethInfo, + /// range m, - ad, // the access domain of the place where the call is taking place - minfo: MethInfo, // the method we're attempting to call - calledTyArgs, // the 'called type arguments', i.e. the fresh generic instantiation of the method we're attempting to call - callerTyArgs: TType list, // the 'caller type arguments', i.e. user-given generic instantiation of the method we're attempting to call - pinfoOpt: PropInfo option, // the property related to the method we're attempting to call, if any - callerObjArgTys: TType list, // the types of the actual object argument, if any - curriedCallerArgs: (CallerArg<'T> list * CallerNamedArg<'T> list) list, // the data about any arguments supplied by the caller - allowParamArgs: bool, // do we allow the use of a param args method in its "expanded" form? - allowOutAndOptArgs: bool, // do we allow the use of the transformation that converts out arguments as tuple returns? - tyargsOpt : TType option) // method parameters + /// the access domain of the place where the call is taking place + ad, + /// the method we're attempting to call + minfo: MethInfo, + /// the 'called type arguments', i.e. the fresh generic instantiation of the method we're attempting to call + calledTyArgs, + /// the 'caller type arguments', i.e. user-given generic instantiation of the method we're attempting to call + // todo: consider CallerTypeArgs record + callerTyArgs: TType list, + /// the property related to the method we're attempting to call, if any + pinfoOpt: PropInfo option, + /// the types of the actual object argument, if any + callerObjArgTys: TType list, + /// the 'caller method arguments', i.e. a list of user-given parameter expressions, split between unnamed and named arguments + callerArgs: CallerArgs<'T>, + /// do we allow the use of a param args method in its "expanded" form? + allowParamArgs: bool, + /// do we allow the use of the transformation that converts out arguments as tuple returns? + allowOutAndOptArgs: bool, + /// method parameters + tyargsOpt : TType option) = let g = infoReader.g let methodRetTy = minfo.GetFSharpReturnTy(infoReader.amap, m, calledTyArgs) @@ -249,7 +354,7 @@ type CalledMeth<'T> do assert (fullCurriedCalledArgs.Length = fullCurriedCalledArgs.Length) let argSetInfos = - (curriedCallerArgs, fullCurriedCalledArgs) ||> List.map2 (fun (unnamedCallerArgs, namedCallerArgs) fullCalledArgs -> + (callerArgs.CurriedCallerArgs, fullCurriedCalledArgs) ||> List.map2 (fun (unnamedCallerArgs, namedCallerArgs) fullCalledArgs -> // Find the arguments not given by name let unnamedCalledArgs = fullCalledArgs |> List.filter (fun calledArg -> @@ -317,7 +422,7 @@ type CalledMeth<'T> let returnedObjTy = if minfo.IsConstructor then minfo.ApparentEnclosingType else methodRetTy unassignedNamedItems |> List.splitChoose (fun (CallerNamedArg(id, e) as arg) -> let nm = id.idText - let pinfos = GetIntrinsicPropInfoSetsOfType infoReader (Some(nm), ad, AllowMultiIntfInstantiations.Yes) IgnoreOverrides id.idRange returnedObjTy + let pinfos = GetIntrinsicPropInfoSetsOfType infoReader (Some nm) ad AllowMultiIntfInstantiations.Yes IgnoreOverrides id.idRange returnedObjTy let pinfos = pinfos |> ExcludeHiddenOfPropInfos g infoReader.amap m match pinfos with | [pinfo] when pinfo.HasSetter && not pinfo.IsIndexer -> @@ -327,7 +432,7 @@ type CalledMeth<'T> | _ -> let epinfos = match nameEnv with - | Some(ne) -> ExtensionPropInfosOfTypeInScope infoReader ne (Some(nm), ad) m returnedObjTy + | Some ne -> ExtensionPropInfosOfTypeInScope ResultCollectionSettings.AllResults infoReader ne (Some nm) ad m returnedObjTy | _ -> [] match epinfos with | [pinfo] when pinfo.HasSetter && not pinfo.IsIndexer -> @@ -337,8 +442,8 @@ type CalledMeth<'T> | _ -> freshenMethInfo m pminfo let pminst = match tyargsOpt with - | Some(TType.TType_app(_, types)) -> types - | _ -> pminst + | Some(TType.TType_app(_, types)) -> types + | _ -> pminst Choice1Of2(AssignedItemSetter(id, AssignedPropSetter(pinfo, pminfo, pminst), e)) | _ -> match infoReader.GetILFieldInfosOfType(Some(nm), ad, m, returnedObjTy) with @@ -377,6 +482,8 @@ type CalledMeth<'T> /// the instantiation of the method we're attempting to call member x.CalledTyArgs = calledTyArgs + member x.AllCalledArgs = fullCurriedCalledArgs + /// the instantiation of the method we're attempting to call member x.CalledTyparInst = let tps = minfo.FormalMethodTypars @@ -438,7 +545,8 @@ type CalledMeth<'T> member x.ParamArrayCallerArgs = x.ArgSets |> List.tryPick (fun argSet -> if Option.isSome argSet.ParamArrayCalledArgOpt then Some argSet.ParamArrayCallerArgs else None ) - member x.ParamArrayElementType = + member x.GetParamArrayElementType() = + // turned as a method to avoid assert in variable inspector assert (x.UsesParamArrayConversion) x.ParamArrayCalledArgOpt.Value.CalledArgumentType |> destArrayTy x.amap.g @@ -491,6 +599,8 @@ type CalledMeth<'T> member x.TotalNumAssignedNamedArgs = x.ArgSets |> List.sumBy (fun x -> x.NumAssignedNamedArgs) + override x.ToString() = "call to " + minfo.ToString() + let NamesOfCalledArgs (calledArgs: CalledArg list) = calledArgs |> List.choose (fun x -> x.NameOpt) @@ -507,29 +617,36 @@ type ArgumentAnalysis = let InferLambdaArgsForLambdaPropagation origRhsExpr = let rec loop e = match e with - | SynExpr.Lambda(_, _, _, rest, _) -> 1 + loop rest + | SynExpr.Lambda (_, _, _, rest, _) -> 1 + loop rest | SynExpr.MatchLambda _ -> 1 | _ -> 0 loop origRhsExpr let ExamineArgumentForLambdaPropagation (infoReader: InfoReader) (arg: AssignedCalledArg) = let g = infoReader.g + // Find the explicit lambda arguments of the caller. Ignore parentheses. - let argExpr = match arg.CallerArg.Expr with SynExpr.Paren(x, _, _, _) -> x | x -> x + let argExpr = match arg.CallerArg.Expr with SynExpr.Paren (x, _, _, _) -> x | x -> x let countOfCallerLambdaArg = InferLambdaArgsForLambdaPropagation argExpr + // Adjust for Expression<_>, Func<_, _>, ... - let adjustedCalledArgTy = AdjustCalledArgType infoReader false arg.CalledArg arg.CallerArg + let adjustedCalledArgTy = AdjustCalledArgType infoReader false false arg.CalledArg arg.CallerArg if countOfCallerLambdaArg > 0 then // Decompose the explicit function type of the target - let calledLambdaArgTys, _calledLambdaRetTy = Tastops.stripFunTy g adjustedCalledArgTy + let calledLambdaArgTys, _calledLambdaRetTy = stripFunTy g adjustedCalledArgTy if calledLambdaArgTys.Length >= countOfCallerLambdaArg then // success CallerLambdaHasArgTypes calledLambdaArgTys elif isDelegateTy g (if isLinqExpressionTy g adjustedCalledArgTy then destLinqExpressionTy g adjustedCalledArgTy else adjustedCalledArgTy) then - ArgDoesNotMatch // delegate arity mismatch + // delegate arity mismatch + ArgDoesNotMatch else - NoInfo // not a function type on the called side - no information - else CalledArgMatchesType(adjustedCalledArgTy) // not a lambda on the caller side - push information from caller to called + // not a function type on the called side - no information + NoInfo + else + // not a lambda on the caller side - push information from caller to called + CalledArgMatchesType(adjustedCalledArgTy) + let ExamineMethodForLambdaPropagation (x: CalledMeth) = let unnamedInfo = x.AssignedUnnamedArgs |> List.mapSquared (ExamineArgumentForLambdaPropagation x.infoReader) @@ -547,7 +664,7 @@ let ExamineMethodForLambdaPropagation (x: CalledMeth) = /// Is this a 'base' call (in the sense of C#) let IsBaseCall objArgs = match objArgs with - | [Expr.Val(v, _, _)] when v.BaseOrThisInfo = BaseVal -> true + | [Expr.Val (v, _, _)] when v.BaseOrThisInfo = BaseVal -> true | _ -> false /// Compute whether we insert a 'coerce' on the 'this' pointer for an object model call @@ -573,27 +690,43 @@ let ComputeConstrainedCallInfo g amap m (objArgs, minfo: MethInfo) = | _ -> None - /// Adjust the 'this' pointer before making a call /// Take the address of a struct, and coerce to an interface/base/constraint type if necessary let TakeObjAddrForMethodCall g amap (minfo: MethInfo) isMutable m objArgs f = let ccallInfo = ComputeConstrainedCallInfo g amap m (objArgs, minfo) let wrap, objArgs = + match objArgs with | [objArgExpr] -> + let hasCallInfo = ccallInfo.IsSome let mustTakeAddress = hasCallInfo || minfo.ObjArgNeedsAddress(amap, m) let objArgTy = tyOfExpr g objArgExpr - let wrap, objArgExpr', isReadOnly, _isWriteOnly = mkExprAddrOfExpr g mustTakeAddress hasCallInfo isMutable objArgExpr None m + + let isMutable = + match isMutable with + | DefinitelyMutates + | NeverMutates + | AddressOfOp -> isMutable + | PossiblyMutates -> + // Check to see if the method is read-only. Perf optimization. + // If there is an extension member whose first arg is an inref, we must return NeverMutates. + if mustTakeAddress && (minfo.IsReadOnly || minfo.IsReadOnlyExtensionMember (amap, m)) then + NeverMutates + else + isMutable + + let wrap, objArgExprAddr, isReadOnly, _isWriteOnly = + mkExprAddrOfExpr g mustTakeAddress hasCallInfo isMutable objArgExpr None m // Extension members and calls to class constraints may need a coercion for their object argument - let objArgExpr' = + let objArgExprCoerced = if not hasCallInfo && not (TypeDefinitelySubsumesTypeNoCoercion 0 g amap m minfo.ApparentEnclosingType objArgTy) then - mkCoerceExpr(objArgExpr', minfo.ApparentEnclosingType, m, objArgTy) + mkCoerceExpr(objArgExprAddr, minfo.ApparentEnclosingType, m, objArgTy) else - objArgExpr' + objArgExprAddr // Check to see if the extension member uses the extending type as a byref. // If so, make sure we don't allow readonly/immutable values to be passed byref from an extension member. @@ -605,7 +738,7 @@ let TakeObjAddrForMethodCall g amap (minfo: MethInfo) isMutable m objArgs f = errorR(Error(FSComp.SR.tcCannotCallExtensionMethodInrefToByref(minfo.DisplayName), m))) - wrap, [objArgExpr'] + wrap, [objArgExprCoerced] | _ -> id, objArgs @@ -616,11 +749,6 @@ let TakeObjAddrForMethodCall g amap (minfo: MethInfo) isMutable m objArgs f = // Build method calls. //------------------------------------------------------------------------- -//------------------------------------------------------------------------- -// Build calls -//------------------------------------------------------------------------- - - /// Build an expression node that is a call to a .NET method. let BuildILMethInfoCall g amap m isProp (minfo: ILMethInfo) valUseFlags minst direct args = let valu = isStructTy g minfo.ApparentEnclosingType @@ -635,14 +763,9 @@ let BuildILMethInfoCall g amap m isProp (minfo: ILMethInfo) valUseFlags minst di let exprTy = if ctor then minfo.ApparentEnclosingType else minfo.GetFSharpReturnTy(amap, m, minst) let retTy = if not ctor && ilMethRef.ReturnType = ILType.Void then [] else [exprTy] let isDllImport = minfo.IsDllImport g - Expr.Op(TOp.ILCall(useCallvirt, isProtected, valu, newobj, valUseFlags, isProp, isDllImport, ilMethRef, minfo.DeclaringTypeInst, minst, retTy), [], args, m), + Expr.Op (TOp.ILCall (useCallvirt, isProtected, valu, newobj, valUseFlags, isProp, isDllImport, ilMethRef, minfo.DeclaringTypeInst, minst, retTy), [], args, m), exprTy -/// Build a call to the System.Object constructor taking no arguments, -let BuildObjCtorCall (g: TcGlobals) m = - let ilMethRef = (mkILCtorMethSpecForTy(g.ilg.typ_Object, [])).MethodRef - Expr.Op(TOp.ILCall(false, false, false, false, CtorValUsedAsSuperInit, false, true, ilMethRef, [], [], [g.obj_ty]), [], [], m) - /// Build a call to an F# method. /// @@ -654,11 +777,12 @@ let BuildObjCtorCall (g: TcGlobals) m = let BuildFSharpMethodApp g m (vref: ValRef) vexp vexprty (args: Exprs) = let arities = (arityOfVal vref.Deref).AritiesOfArgs - let args3, (leftover, retTy) = + let args3, (leftover, retTy) = + let exprL expr = exprL g expr ((args, vexprty), arities) ||> List.mapFold (fun (args, fty) arity -> match arity, args with | (0|1), [] when typeEquiv g (domainOfFunTy g fty) g.unit_ty -> mkUnit g m, (args, rangeOfFunTy g fty) - | 0, (arg::argst) -> + | 0, (arg :: argst) -> let msg = Layout.showL (Layout.sepListL (Layout.rightL (Layout.TaggedTextOps.tagText ";")) (List.map exprL args)) warning(InternalError(sprintf "Unexpected zero arity, args = %s" msg, m)) arg, (argst, rangeOfFunTy g fty) @@ -691,15 +815,20 @@ let BuildFSharpMethodCall g m (ty, vref: ValRef) valUseFlags minst args = /// calls to the type-directed solutions to member constraints. let MakeMethInfoCall amap m minfo minst args = let valUseFlags = NormalValUse // correct unless if we allow wild trait constraints like "T has a ctor and can be used as a parent class" + match minfo with + | ILMeth(g, ilminfo, _) -> let direct = not minfo.IsVirtual let isProp = false // not necessarily correct, but this is only used post-creflect where this flag is irrelevant BuildILMethInfoCall g amap m isProp ilminfo valUseFlags minst direct args |> fst + | FSMeth(g, ty, vref, _) -> BuildFSharpMethodCall g m (ty, vref) valUseFlags minst args |> fst + | DefaultStructCtor(_, ty) -> mkDefault (m, ty) + #if !NO_EXTENSIONTYPING | ProvidedMeth(amap, mi, _, m) -> let isProp = false // not necessarily correct, but this is only used post-creflect where this flag is irrelevant @@ -710,7 +839,7 @@ let MakeMethInfoCall amap m minfo minst args = let actualMethInst = [] // GENERIC TYPE PROVIDERS: for generics, we would have something here let ilReturnTys = Option.toList (minfo.GetCompiledReturnTy(amap, m, [])) // GENERIC TYPE PROVIDERS: for generics, we would have more here // REVIEW: Should we allow protected calls? - Expr.Op(TOp.ILCall(false, false, valu, isConstructor, valUseFlags, isProp, false, ilMethodRef, actualTypeInst, actualMethInst, ilReturnTys), [], args, m) + Expr.Op (TOp.ILCall (false, false, valu, isConstructor, valUseFlags, isProp, false, ilMethodRef, actualTypeInst, actualMethInst, ilReturnTys), [], args, m) #endif @@ -725,10 +854,10 @@ let TryImportProvidedMethodBaseAsLibraryIntrinsic (amap: Import.ImportMap, m: ra match amap.g.knownIntrinsics.TryGetValue ((declaringEntity.LogicalName, methodName)) with | true, vref -> Some vref | _ -> - match amap.g.knownFSharpCoreModules.TryGetValue(declaringEntity.LogicalName) with + match amap.g.knownFSharpCoreModules.TryGetValue declaringEntity.LogicalName with | true, modRef -> modRef.ModuleOrNamespaceType.AllValsByLogicalName - |> Seq.tryPick (fun (KeyValue(_, v)) -> if v.CompiledName = methodName then Some (mkNestedValRef modRef v) else None) + |> Seq.tryPick (fun (KeyValue(_, v)) -> if (v.CompiledName amap.g.CompilerGlobalState) = methodName then Some (mkNestedValRef modRef v) else None) | _ -> None else None @@ -780,7 +909,7 @@ let BuildMethodCall tcVal g amap isMutable m isProp minfo valUseFlags minst objA if minfo.IsClassConstructor then error (InternalError (minfo.LogicalName + ": cannot call a class constructor", m)) let useCallvirt = not valu && not direct && minfo.IsVirtual - let isProtected = minfo.IsProtectedAccessiblity + let isProtected = minfo.IsProtectedAccessibility let exprTy = if isCtor then enclTy else minfo.GetFSharpReturnTy(amap, m, minst) match TryImportProvidedMethodBaseAsLibraryIntrinsic (amap, m, providedMeth) with | Some fsValRef -> @@ -801,7 +930,7 @@ let BuildMethodCall tcVal g amap isMutable m isProp minfo valUseFlags minst objA let actualMethInst = minst let retTy = if not isCtor && (ilMethRef.ReturnType = ILType.Void) then [] else [exprTy] let noTailCall = false - let expr = Expr.Op(TOp.ILCall(useCallvirt, isProtected, valu, isNewObj, valUseFlags, isProp, noTailCall, ilMethRef, actualTypeInst, actualMethInst, retTy), [], allArgs, m) + let expr = Expr.Op (TOp.ILCall (useCallvirt, isProtected, valu, isNewObj, valUseFlags, isProp, noTailCall, ilMethRef, actualTypeInst, actualMethInst, retTy), [], allArgs, m) expr, exprTy #endif @@ -825,9 +954,14 @@ let BuildMethodCall tcVal g amap isMutable m isProp minfo valUseFlags minst objA mkDefault (m, ty), ty) //------------------------------------------------------------------------- -// Build delegate constructions (lambdas/functions to delegates) +// Adjust caller arguments as part of building a method call //------------------------------------------------------------------------- +/// Build a call to the System.Object constructor taking no arguments, +let BuildObjCtorCall (g: TcGlobals) m = + let ilMethRef = (mkILCtorMethSpecForTy(g.ilg.typ_Object, [])).MethodRef + Expr.Op (TOp.ILCall (false, false, false, false, CtorValUsedAsSuperInit, false, true, ilMethRef, [], [], [g.obj_ty]), [], [], m) + /// Implements the elaborated form of adhoc conversions from functions to delegates at member callsites let BuildNewDelegateExpr (eventInfoOpt: EventInfo option, g, amap, delegateTy, invokeMethInfo: MethInfo, delArgTys, f, fty, m) = let slotsig = invokeMethInfo.GetSlotSig(amap, m) @@ -873,6 +1007,349 @@ let CoerceFromFSharpFuncToDelegate g amap infoReader ad callerArgTy m callerArgE let (SigOfFunctionForDelegate(invokeMethInfo, delArgTys, _, _)) = GetSigOfFunctionForDelegate infoReader delegateTy m ad BuildNewDelegateExpr (None, g, amap, delegateTy, invokeMethInfo, delArgTys, callerArgExpr, callerArgTy, m) +// Handle adhoc argument conversions +let AdjustCallerArgExprForCoercions (g: TcGlobals) amap infoReader ad isOutArg calledArgTy (reflArgInfo: ReflectedArgInfo) callerArgTy m callerArgExpr = + if isByrefTy g calledArgTy && isRefCellTy g callerArgTy then + None, Expr.Op (TOp.RefAddrGet false, [destRefCellTy g callerArgTy], [callerArgExpr], m) + +#if IMPLICIT_ADDRESS_OF + elif isInByrefTy g calledArgTy && not (isByrefTy g callerArgTy) then + let wrap, callerArgExprAddress, _readonly, _writeonly = mkExprAddrOfExpr g true false NeverMutates callerArgExpr None m + Some wrap, callerArgExprAddress +#endif + + elif isDelegateTy g calledArgTy && isFunTy g callerArgTy then + None, CoerceFromFSharpFuncToDelegate g amap infoReader ad callerArgTy m callerArgExpr calledArgTy + + elif isLinqExpressionTy g calledArgTy && isDelegateTy g (destLinqExpressionTy g calledArgTy) && isFunTy g callerArgTy then + let delegateTy = destLinqExpressionTy g calledArgTy + let expr = CoerceFromFSharpFuncToDelegate g amap infoReader ad callerArgTy m callerArgExpr delegateTy + None, mkCallQuoteToLinqLambdaExpression g m delegateTy (Expr.Quote (expr, ref None, false, m, mkQuotedExprTy g delegateTy)) + + // auto conversions to quotations (to match auto conversions to LINQ expressions) + elif reflArgInfo.AutoQuote && isQuotedExprTy g calledArgTy && not (isQuotedExprTy g callerArgTy) then + match reflArgInfo with + | ReflectedArgInfo.Quote true -> + None, mkCallLiftValueWithDefn g m calledArgTy callerArgExpr + | ReflectedArgInfo.Quote false -> + None, Expr.Quote (callerArgExpr, ref None, false, m, calledArgTy) + | ReflectedArgInfo.None -> failwith "unreachable" // unreachable due to reflArgInfo.AutoQuote condition + + // Note: out args do not need to be coerced + elif isOutArg then + None, callerArgExpr + + // Note: not all these casts are reported in quotations + else + None, mkCoerceIfNeeded g calledArgTy callerArgTy callerArgExpr + +/// Some of the code below must allocate temporary variables or bind other variables to particular values. +/// As usual we represent variable allocators by expr -> expr functions +/// which we then use to wrap the whole expression. These will either do nothing or pre-bind a variable. It doesn't +/// matter what order they are applied in as long as they are all composed together. +let emptyPreBinder (e: Expr) = e + +/// Get the expression that must be inserted on the caller side for a CallerSide optional arg, +/// i.e. one where there is no corresponding caller arg. +let rec GetDefaultExpressionForCallerSideOptionalArg tcFieldInit g (calledArg: CalledArg) currCalledArgTy currDfltVal eCallerMemberName mMethExpr = + match currDfltVal with + | MissingValue -> + // Add an I_nop if this is an initonly field to make sure we never recognize it as an lvalue. See mkExprAddrOfExpr. + emptyPreBinder, mkAsmExpr ([ mkNormalLdsfld (fspec_Missing_Value g); AI_nop ], [], [], [currCalledArgTy], mMethExpr) + + | DefaultValue -> + emptyPreBinder, mkDefault(mMethExpr, currCalledArgTy) + + | Constant fieldInit -> + match currCalledArgTy with + | NullableTy g inst when fieldInit <> ILFieldInit.Null -> + let nullableTy = mkILNonGenericBoxedTy(g.FindSysILTypeRef "System.Nullable`1") + let ctor = mkILCtorMethSpecForTy(nullableTy, [ILType.TypeVar 0us]).MethodRef + let ctorArgs = [Expr.Const (tcFieldInit mMethExpr fieldInit, mMethExpr, inst)] + emptyPreBinder, Expr.Op (TOp.ILCall (false, false, true, true, NormalValUse, false, false, ctor, [inst], [], [currCalledArgTy]), [], ctorArgs, mMethExpr) + | ByrefTy g inst -> + GetDefaultExpressionForCallerSideOptionalArg tcFieldInit g calledArg inst (PassByRef(inst, currDfltVal)) eCallerMemberName mMethExpr + | _ -> + match calledArg.CallerInfo, eCallerMemberName with + | CallerLineNumber, _ when typeEquiv g currCalledArgTy g.int_ty -> + emptyPreBinder, Expr.Const (Const.Int32(mMethExpr.StartLine), mMethExpr, currCalledArgTy) + | CallerFilePath, _ when typeEquiv g currCalledArgTy g.string_ty -> + let fileName = mMethExpr.FileName |> FileSystem.GetFullPathShim |> PathMap.apply g.pathMap + emptyPreBinder, Expr.Const (Const.String fileName, mMethExpr, currCalledArgTy) + | CallerMemberName, Some callerName when (typeEquiv g currCalledArgTy g.string_ty) -> + emptyPreBinder, Expr.Const (Const.String callerName, mMethExpr, currCalledArgTy) + | _ -> + emptyPreBinder, Expr.Const (tcFieldInit mMethExpr fieldInit, mMethExpr, currCalledArgTy) + + | WrapperForIDispatch -> + match g.TryFindSysILTypeRef "System.Runtime.InteropServices.DispatchWrapper" with + | None -> error(Error(FSComp.SR.fscSystemRuntimeInteropServicesIsRequired(), mMethExpr)) + | Some tref -> + let ty = mkILNonGenericBoxedTy tref + let mref = mkILCtorMethSpecForTy(ty, [g.ilg.typ_Object]).MethodRef + let expr = Expr.Op (TOp.ILCall (false, false, false, true, NormalValUse, false, false, mref, [], [], [g.obj_ty]), [], [mkDefault(mMethExpr, currCalledArgTy)], mMethExpr) + emptyPreBinder, expr + + | WrapperForIUnknown -> + match g.TryFindSysILTypeRef "System.Runtime.InteropServices.UnknownWrapper" with + | None -> error(Error(FSComp.SR.fscSystemRuntimeInteropServicesIsRequired(), mMethExpr)) + | Some tref -> + let ty = mkILNonGenericBoxedTy tref + let mref = mkILCtorMethSpecForTy(ty, [g.ilg.typ_Object]).MethodRef + let expr = Expr.Op (TOp.ILCall (false, false, false, true, NormalValUse, false, false, mref, [], [], [g.obj_ty]), [], [mkDefault(mMethExpr, currCalledArgTy)], mMethExpr) + emptyPreBinder, expr + + | PassByRef (ty, dfltVal2) -> + let v, _ = mkCompGenLocal mMethExpr "defaultByrefArg" ty + let wrapper2, rhs = GetDefaultExpressionForCallerSideOptionalArg tcFieldInit g calledArg currCalledArgTy dfltVal2 eCallerMemberName mMethExpr + (wrapper2 >> mkCompGenLet mMethExpr v rhs), mkValAddr mMethExpr false (mkLocalValRef v) + +/// Get the expression that must be inserted on the caller side for a CalleeSide optional arg where +/// no caller argument has been provided. Normally this is 'None', however CallerMemberName and friends +/// can be used with 'CalleeSide' optional arguments +let GetDefaultExpressionForCalleeSideOptionalArg g (calledArg: CalledArg) eCallerMemberName (mMethExpr: range) = + let calledArgTy = calledArg.CalledArgumentType + let calledNonOptTy = + if isOptionTy g calledArgTy then + destOptionTy g calledArgTy + else + calledArgTy // should be unreachable + + match calledArg.CallerInfo, eCallerMemberName with + | CallerLineNumber, _ when typeEquiv g calledNonOptTy g.int_ty -> + let lineExpr = Expr.Const(Const.Int32 mMethExpr.StartLine, mMethExpr, calledNonOptTy) + mkSome g calledNonOptTy lineExpr mMethExpr + | CallerFilePath, _ when typeEquiv g calledNonOptTy g.string_ty -> + let fileName = mMethExpr.FileName |> FileSystem.GetFullPathShim |> PathMap.apply g.pathMap + let filePathExpr = Expr.Const (Const.String(fileName), mMethExpr, calledNonOptTy) + mkSome g calledNonOptTy filePathExpr mMethExpr + | CallerMemberName, Some(callerName) when typeEquiv g calledNonOptTy g.string_ty -> + let memberNameExpr = Expr.Const (Const.String callerName, mMethExpr, calledNonOptTy) + mkSome g calledNonOptTy memberNameExpr mMethExpr + | _ -> + mkNone g calledNonOptTy mMethExpr + +/// Get the expression that must be inserted on the caller side for an optional arg where +/// no caller argument has been provided. +let GetDefaultExpressionForOptionalArg tcFieldInit g (calledArg: CalledArg) eCallerMemberName mItem (mMethExpr: range) = + let calledArgTy = calledArg.CalledArgumentType + let preBinder, expr = + match calledArg.OptArgInfo with + | NotOptional -> + error(InternalError("Unexpected NotOptional", mItem)) + + | CallerSide dfltVal -> + GetDefaultExpressionForCallerSideOptionalArg tcFieldInit g calledArg calledArgTy dfltVal eCallerMemberName mMethExpr + + | CalleeSide -> + emptyPreBinder, GetDefaultExpressionForCalleeSideOptionalArg g calledArg eCallerMemberName mMethExpr + + // Combine the variable allocators (if any) + let callerArg = CallerArg(calledArgTy, mMethExpr, false, expr) + preBinder, { NamedArgIdOpt = None; CalledArg = calledArg; CallerArg = callerArg } + +// Adjust all the optional arguments, filling in values for defaults, +let AdjustCallerArgForOptional tcFieldInit eCallerMemberName (infoReader: InfoReader) (assignedArg: AssignedCalledArg<_>) = + let g = infoReader.g + let amap = infoReader.amap + let callerArg = assignedArg.CallerArg + let (CallerArg(callerArgTy, m, isOptCallerArg, callerArgExpr)) = callerArg + let calledArg = assignedArg.CalledArg + match calledArg.OptArgInfo with + | NotOptional -> + if isOptCallerArg then errorR(Error(FSComp.SR.tcFormalArgumentIsNotOptional(), m)) + assignedArg + | _ -> + let callerArgExpr2 = + match calledArg.OptArgInfo with + | NotOptional -> failwith "unreachable" + + | CallerSide dfltVal -> + let calledArgTy = calledArg.CalledArgumentType + + if isOptCallerArg then + // CSharpMethod(?x=b) + if isOptionTy g callerArgTy then + if isNullableTy g calledArgTy then + // CSharpMethod(?x=b) when 'b' has optional type and 'x' has nullable type --> CSharpMethod(x=Option.toNullable b) + mkOptionToNullable g m (destOptionTy g callerArgTy) callerArgExpr + else + // CSharpMethod(?x=b) when 'b' has optional type and 'x' has non-nullable type --> CSharpMethod(x=Option.defaultValue DEFAULT v) + let _wrapper, defaultExpr = GetDefaultExpressionForCallerSideOptionalArg tcFieldInit g calledArg calledArgTy dfltVal eCallerMemberName m + let ty = destOptionTy g callerArgTy + mkOptionDefaultValue g m ty defaultExpr callerArgExpr + else + // This should be unreachable but the error will be reported elsewhere + callerArgExpr + else + if isNullableTy g calledArgTy then + // CSharpMethod(x=b) when 'x' has nullable type + if isNullableTy g callerArgTy then + // CSharpMethod(x=b) when both 'x' and 'b' have nullable type --> CSharpMethod(x=b) + callerArgExpr + else + // CSharpMethod(x=b) when 'x' has nullable type and 'b' does not --> CSharpMethod(x=Nullable(b)) + let calledNonOptTy = destNullableTy g calledArgTy + let minfo = GetIntrinsicConstructorInfosOfType infoReader m calledArgTy |> List.head + let callerArgExprCoerced = mkCoerceIfNeeded g calledNonOptTy callerArgTy callerArgExpr + MakeMethInfoCall amap m minfo [] [callerArgExprCoerced] + else + // CSharpMethod(x=b) --> CSharpMethod(?x=b) + callerArgExpr + + | CalleeSide -> + if isOptCallerArg then + // CSharpMethod(?x=b) --> CSharpMethod(?x=b) + callerArgExpr + else + // CSharpMethod(x=b) when CSharpMethod(A) --> CSharpMethod(?x=Some(b :> A)) + let calledArgTy = assignedArg.CalledArg.CalledArgumentType + if isOptionTy g calledArgTy then + let calledNonOptTy = destOptionTy g calledArgTy + let callerArgExprCoerced = mkCoerceIfNeeded g calledNonOptTy callerArgTy callerArgExpr + mkSome g calledNonOptTy callerArgExprCoerced m + else + assert false + callerArgExpr // defensive code - this case is unreachable + + let callerArg2 = CallerArg(tyOfExpr g callerArgExpr2, m, isOptCallerArg, callerArgExpr2) + { assignedArg with CallerArg=callerArg2 } + +// Handle CallerSide optional arguments. +// +// CallerSide optional arguments are largely for COM interop, e.g. to PIA assemblies for Word etc. +// As a result we follow the VB and C# behavior here. +// +// "1. If the parameter is statically typed as System.Object and does not have a value, then there are four cases: +// a. The parameter is marked with MarshalAs(IUnknown), MarshalAs(Interface), or MarshalAs(IDispatch). In this case we pass null. +// b. Else if the parameter is marked with IUnknownConstantAttribute. In this case we pass new System.Runtime.InteropServices.UnknownWrapper(null) +// c. Else if the parameter is marked with IDispatchConstantAttribute. In this case we pass new System.Runtime.InteropServices.DispatchWrapper(null) +// d. Else, we will pass Missing.Value. +// 2. Otherwise, if there is a value attribute, then emit the default value. +// 3. Otherwise, we emit default(T). +// 4. Finally, we apply conversions from the value to the parameter type. This is where the nullable conversions take place for VB. +// - VB allows you to mark ref parameters as optional. The semantics of this is that we create a temporary +// with type = type of parameter, load the optional value to it, and call the method. +// - VB also allows you to mark arrays with Nothing as the optional value. +// - VB also allows you to pass intrinsic values as optional values to parameters +// typed as Object. What we do in this case is we box the intrinsic value." +// +let AdjustCallerArgsForOptionals tcFieldInit eCallerMemberName (infoReader: InfoReader) (calledMeth: CalledMeth<_>) mItem mMethExpr = + let g = infoReader.g + + let assignedNamedArgs = calledMeth.ArgSets |> List.collect (fun argSet -> argSet.AssignedNamedArgs) + let unnamedCalledArgs = calledMeth.ArgSets |> List.collect (fun argSet -> argSet.UnnamedCalledArgs) + let unnamedCallerArgs = calledMeth.ArgSets |> List.collect (fun argSet -> argSet.UnnamedCallerArgs) + let unnamedArgs = + (unnamedCalledArgs, unnamedCallerArgs) ||> List.map2 (fun called caller -> + { NamedArgIdOpt = None; CalledArg=called; CallerArg=caller }) + + // Adjust all the optional arguments that require a default value to be inserted into the call, + // i.e. there is no corresponding caller arg. + let optArgs, optArgPreBinder = + (emptyPreBinder, calledMeth.UnnamedCalledOptArgs) ||> List.mapFold (fun preBinder calledArg -> + let preBinder2, arg = GetDefaultExpressionForOptionalArg tcFieldInit g calledArg eCallerMemberName mItem mMethExpr + arg, (preBinder >> preBinder2)) + + let adjustedNormalUnnamedArgs = List.map (AdjustCallerArgForOptional tcFieldInit eCallerMemberName infoReader) unnamedArgs + let adjustedAssignedNamedArgs = List.map (AdjustCallerArgForOptional tcFieldInit eCallerMemberName infoReader) assignedNamedArgs + + optArgs, optArgPreBinder, adjustedNormalUnnamedArgs, adjustedAssignedNamedArgs + +/// Adjust any 'out' arguments, passing in the address of a mutable local +let AdjustOutCallerArgs g (calledMeth: CalledMeth<_>) mMethExpr = + calledMeth.UnnamedCalledOutArgs |> List.map (fun calledArg -> + let calledArgTy = calledArg.CalledArgumentType + let outArgTy = destByrefTy g calledArgTy + let outv, outArgExpr = mkMutableCompGenLocal mMethExpr PrettyNaming.outArgCompilerGeneratedName outArgTy // mutable! + let expr = mkDefault (mMethExpr, outArgTy) + let callerArg = CallerArg (calledArgTy, mMethExpr, false, mkValAddr mMethExpr false (mkLocalValRef outv)) + let outArg = { NamedArgIdOpt=None;CalledArg=calledArg;CallerArg=callerArg } + outArg, outArgExpr, mkCompGenBind outv expr) + |> List.unzip3 + +/// Adjust any '[]' arguments, converting to an array +let AdjustParamArrayCallerArgs g amap infoReader ad (calledMeth: CalledMeth<_>) mMethExpr = + let argSets = calledMeth.ArgSets + + let paramArrayCallerArgs = argSets |> List.collect (fun argSet -> argSet.ParamArrayCallerArgs) + + match calledMeth.ParamArrayCalledArgOpt with + | None -> + [], [] + + | Some paramArrayCalledArg -> + let paramArrayCalledArgElementType = destArrayTy g paramArrayCalledArg.CalledArgumentType + + let paramArrayPreBinders, paramArrayExprs = + paramArrayCallerArgs + |> List.map (fun callerArg -> + let (CallerArg(callerArgTy, m, isOutArg, callerArgExpr)) = callerArg + AdjustCallerArgExprForCoercions g amap infoReader ad isOutArg paramArrayCalledArgElementType paramArrayCalledArg.ReflArgInfo callerArgTy m callerArgExpr) + |> List.unzip + + let paramArrayExpr = Expr.Op (TOp.Array, [paramArrayCalledArgElementType], paramArrayExprs, mMethExpr) + + let paramArrayCallerArg = + [ { NamedArgIdOpt = None + CalledArg=paramArrayCalledArg + CallerArg=CallerArg(paramArrayCalledArg.CalledArgumentType, mMethExpr, false, paramArrayExpr) } ] + + paramArrayPreBinders, paramArrayCallerArg + +/// Build the argument list for a method call. Adjust for param array, optional arguments, byref arguments and coercions. +/// For example, if you pass an F# reference cell to a byref then we must get the address of the +/// contents of the ref. Likewise lots of adjustments are made for optional arguments etc. +let AdjustCallerArgs tcFieldInit eCallerMemberName (infoReader: InfoReader) ad (calledMeth: CalledMeth<_>) objArgs lambdaVars mItem mMethExpr = + let g = infoReader.g + let amap = infoReader.amap + let calledMethInfo = calledMeth.Method + + // For unapplied 'e.M' we first evaluate 'e' outside the lambda, i.e. 'let v = e in (fun arg -> v.CSharpMethod(arg))' + let objArgPreBinder, objArgs = + match objArgs, lambdaVars with + | [objArg], Some _ -> + if calledMethInfo.IsExtensionMember && calledMethInfo.ObjArgNeedsAddress(amap, mMethExpr) then + error(Error(FSComp.SR.tcCannotPartiallyApplyExtensionMethodForByref(calledMethInfo.DisplayName), mMethExpr)) + let objArgTy = tyOfExpr g objArg + let v, ve = mkCompGenLocal mMethExpr "objectArg" objArgTy + (fun body -> mkCompGenLet mMethExpr v objArg body), [ve] + | _ -> + emptyPreBinder, objArgs + + // Handle param array and optional arguments + let paramArrayPreBinders, paramArrayArgs = + AdjustParamArrayCallerArgs g amap infoReader ad calledMeth mMethExpr + + let optArgs, optArgPreBinder, adjustedNormalUnnamedArgs, adjustedFinalAssignedNamedArgs = + AdjustCallerArgsForOptionals tcFieldInit eCallerMemberName infoReader calledMeth mItem mMethExpr + + let outArgs, outArgExprs, outArgTmpBinds = + AdjustOutCallerArgs g calledMeth mMethExpr + + let allArgs = + adjustedNormalUnnamedArgs @ + adjustedFinalAssignedNamedArgs @ + paramArrayArgs @ + optArgs @ + outArgs + + let allArgs = + allArgs |> List.sortBy (fun x -> x.Position) + + let allArgsPreBinders, allArgsCoerced = + allArgs + |> List.map (fun assignedArg -> + let isOutArg = assignedArg.CalledArg.IsOutArg + let reflArgInfo = assignedArg.CalledArg.ReflArgInfo + let calledArgTy = assignedArg.CalledArg.CalledArgumentType + let (CallerArg(callerArgTy, m, _, e)) = assignedArg.CallerArg + + AdjustCallerArgExprForCoercions g amap infoReader ad isOutArg calledArgTy reflArgInfo callerArgTy m e) + |> List.unzip + + objArgPreBinder, objArgs, allArgsPreBinders, allArgs, allArgsCoerced, optArgPreBinder, paramArrayPreBinders, outArgExprs, outArgTmpBinds + //------------------------------------------------------------------------- // Import provided expressions @@ -911,7 +1388,7 @@ module ProvidedMethodCalls = | _ when typeEquiv g normTy g.decimal_ty -> Const.Decimal(v :?> decimal) | _ when typeEquiv g normTy g.unit_ty -> Const.Unit | _ -> fail() - Expr.Const(c, m, ty) + Expr.Const (c, m, ty) with _ -> fail() ), range=m) @@ -931,13 +1408,13 @@ module ProvidedMethodCalls = elif st.PUntaint((fun st -> st.IsArray), m) then let et = st.PApply((fun st -> st.GetElementType()), m) let rank = st.PUntaint((fun st -> st.GetArrayRank()), m) - (loop et).PApply((fun st -> ProvidedType.CreateNoContext(if rank = 1 then st.RawSystemType.MakeArrayType() else st.RawSystemType.MakeArrayType(rank))), m) + (loop et).PApply((fun st -> if rank = 1 then st.MakeArrayType() else st.MakeArrayType(rank)), m) elif st.PUntaint((fun st -> st.IsByRef), m) then let et = st.PApply((fun st -> st.GetElementType()), m) - (loop et).PApply((fun st -> ProvidedType.CreateNoContext(st.RawSystemType.MakeByRefType())), m) + (loop et).PApply((fun st -> st.MakeByRefType()), m) elif st.PUntaint((fun st -> st.IsPointer), m) then let et = st.PApply((fun st -> st.GetElementType()), m) - (loop et).PApply((fun st -> ProvidedType.CreateNoContext(st.RawSystemType.MakePointerType())), m) + (loop et).PApply((fun st -> st.MakePointerType()), m) else let isGeneric = st.PUntaint((fun st -> st.IsGenericType), m) let headType = if isGeneric then st.PApply((fun st -> st.GetGenericTypeDefinition()), m) else st @@ -960,22 +1437,25 @@ module ProvidedMethodCalls = if tp.Kind = TyparKind.Type then yield genericArg |] - if genericArgs.Length = 0 then + if genericArgs.Length = 0 then headType else let erasedArgTys = genericArgs |> Array.map loop headType.PApply((fun st -> - let erasedArgTys = erasedArgTys |> Array.map (fun a -> a.PUntaintNoFailure (fun x -> x.RawSystemType)) - ProvidedType.CreateNoContext(st.RawSystemType.MakeGenericType erasedArgTys)), m) + let erasedArgTys = erasedArgTys |> Array.map (fun a -> a.PUntaintNoFailure(id)) + st.MakeGenericType erasedArgTys), m) else st loop inputType - let convertProvidedExpressionToExprAndWitness tcVal (thisArg: Expr option, - allArgs: Exprs, - paramVars: Tainted[], - g, amap, mut, isProp, isSuperInit, m, - expr: Tainted) = + let convertProvidedExpressionToExprAndWitness + tcVal + (thisArg: Expr option, + allArgs: Exprs, + paramVars: Tainted[], + g, amap, mut, isProp, isSuperInit, m, + expr: Tainted) = + let varConv = // note: using paramVars.Length as assumed initial size, but this might not // be the optimal value; this wasn't checked before obsoleting Dictionary.ofList @@ -988,125 +1468,101 @@ module ProvidedMethodCalls = match ea with | Tainted.Null -> error(Error(FSComp.SR.etNullProvidedExpression(ea.TypeProviderDesignation), m)) | _ -> - match ea.PApplyOption((function ProvidedTypeAsExpr x -> Some x | _ -> None), m) with - | Some info -> - let (expr, targetTy) = info.PApply2(id, m) + let exprType = ea.PApplyOption((fun x -> x.GetExprType()), m) + let exprType = match exprType with | Some exprType -> exprType | None -> fail() + match exprType.PUntaint(id, m) with + | ProvidedTypeAsExpr (expr, targetTy) -> + let (expr, targetTy) = exprType.PApply2((fun _ -> (expr, targetTy)), m) let srcExpr = exprToExpr expr let targetTy = Import.ImportProvidedType amap m (targetTy.PApply(id, m)) - let sourceTy = Import.ImportProvidedType amap m (expr.PApply((fun e -> e.Type), m)) + let sourceTy = Import.ImportProvidedType amap m (expr.PApply ((fun e -> e.Type), m)) let te = mkCoerceIfNeeded g targetTy sourceTy srcExpr None, (te, tyOfExpr g te) - | None -> - match ea.PApplyOption((function ProvidedTypeTestExpr x -> Some x | _ -> None), m) with - | Some info -> - let (expr, targetTy) = info.PApply2(id, m) + | ProvidedTypeTestExpr (expr, targetTy) -> + let (expr, targetTy) = exprType.PApply2((fun _ -> (expr, targetTy)), m) let srcExpr = exprToExpr expr let targetTy = Import.ImportProvidedType amap m (targetTy.PApply(id, m)) let te = mkCallTypeTest g m targetTy srcExpr None, (te, tyOfExpr g te) - | None -> - match ea.PApplyOption((function ProvidedIfThenElseExpr x -> Some x | _ -> None), m) with - | Some info -> - let test, thenBranch, elseBranch = info.PApply3(id, m) + | ProvidedIfThenElseExpr (test, thenBranch, elseBranch) -> + let test, thenBranch, elseBranch = exprType.PApply3((fun _ -> (test, thenBranch, elseBranch)), m) let testExpr = exprToExpr test let ifTrueExpr = exprToExpr thenBranch let ifFalseExpr = exprToExpr elseBranch - let te = mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m (tyOfExpr g ifTrueExpr) testExpr ifTrueExpr ifFalseExpr + let te = mkCond NoDebugPointAtStickyBinding DebugPointForTarget.No m (tyOfExpr g ifTrueExpr) testExpr ifTrueExpr ifFalseExpr None, (te, tyOfExpr g te) - | None -> - match ea.PApplyOption((function ProvidedVarExpr x -> Some x | _ -> None), m) with - | Some info -> - let _, vTe = varToExpr info + | ProvidedVarExpr providedVar -> + let _, vTe = varToExpr (exprType.PApply((fun _ -> providedVar), m)) None, (vTe, tyOfExpr g vTe) - | None -> - match ea.PApplyOption((function ProvidedConstantExpr x -> Some x | _ -> None), m) with - | Some info -> - let ce = convertConstExpr g amap m info + | ProvidedConstantExpr (obj, prType) -> + let ce = convertConstExpr g amap m (exprType.PApply((fun _ -> (obj, prType)), m)) None, (ce, tyOfExpr g ce) - | None -> - match ea.PApplyOption((function ProvidedNewTupleExpr x -> Some x | _ -> None), m) with - | Some info -> - let elems = info.PApplyArray(id, "GetInvokerExpresson", m) + | ProvidedNewTupleExpr info -> + let elems = exprType.PApplyArray((fun _ -> info), "GetInvokerExpression", m) let elemsT = elems |> Array.map exprToExpr |> Array.toList let exprT = mkRefTupledNoTypes g m elemsT None, (exprT, tyOfExpr g exprT) - | None -> - match ea.PApplyOption((function ProvidedNewArrayExpr x -> Some x | _ -> None), m) with - | Some info -> - let ty, elems = info.PApply2(id, m) + | ProvidedNewArrayExpr (ty, elems) -> + let ty, elems = exprType.PApply2((fun _ -> (ty, elems)), m) let tyT = Import.ImportProvidedType amap m ty - let elems = elems.PApplyArray(id, "GetInvokerExpresson", m) + let elems = elems.PApplyArray(id, "GetInvokerExpression", m) let elemsT = elems |> Array.map exprToExpr |> Array.toList - let exprT = Expr.Op(TOp.Array, [tyT], elemsT, m) + let exprT = Expr.Op (TOp.Array, [tyT], elemsT, m) None, (exprT, tyOfExpr g exprT) - | None -> - match ea.PApplyOption((function ProvidedTupleGetExpr x -> Some x | _ -> None), m) with - | Some info -> - let inp, n = info.PApply2(id, m) + | ProvidedTupleGetExpr (inp, n) -> + let inp, n = exprType.PApply2((fun _ -> (inp, n)), m) let inpT = inp |> exprToExpr // if type of expression is erased type then we need convert it to the underlying base type - let typeOfExpr = + let typeOfExpr = let t = tyOfExpr g inpT stripTyEqnsWrtErasure EraseMeasures g t let tupInfo, tysT = tryDestAnyTupleTy g typeOfExpr let exprT = mkTupleFieldGet g (tupInfo, inpT, tysT, n.PUntaint(id, m), m) None, (exprT, tyOfExpr g exprT) - | None -> - match ea.PApplyOption((function ProvidedLambdaExpr x -> Some x | _ -> None), m) with - | Some info -> - let v, b = info.PApply2(id, m) + | ProvidedLambdaExpr (v, b) -> + let v, b = exprType.PApply2((fun _ -> (v, b)), m) let vT = addVar v let bT = exprToExpr b removeVar v let exprT = mkLambda m vT (bT, tyOfExpr g bT) None, (exprT, tyOfExpr g exprT) - | None -> - match ea.PApplyOption((function ProvidedLetExpr x -> Some x | _ -> None), m) with - | Some info -> - let v, e, b = info.PApply3(id, m) + | ProvidedLetExpr (v, e, b) -> + let v, e, b = exprType.PApply3((fun _ -> (v, e, b)), m) let eT = exprToExpr e let vT = addVar v let bT = exprToExpr b removeVar v let exprT = mkCompGenLet m vT eT bT None, (exprT, tyOfExpr g exprT) - | None -> - match ea.PApplyOption((function ProvidedVarSetExpr x -> Some x | _ -> None), m) with - | Some info -> - let v, e = info.PApply2(id, m) + | ProvidedVarSetExpr (v, e) -> + let v, e = exprType.PApply2((fun _ -> (v, e)), m) let eT = exprToExpr e let vTopt, _ = varToExpr v match vTopt with | None -> fail() - | Some vT -> + | Some vT -> let exprT = mkValSet m (mkLocalValRef vT) eT None, (exprT, tyOfExpr g exprT) - | None -> - match ea.PApplyOption((function ProvidedWhileLoopExpr x -> Some x | _ -> None), m) with - | Some info -> - let guardExpr, bodyExpr = info.PApply2(id, m) + | ProvidedWhileLoopExpr (guardExpr, bodyExpr) -> + let guardExpr, bodyExpr = (exprType.PApply2((fun _ -> (guardExpr, bodyExpr)), m)) let guardExprT = exprToExpr guardExpr let bodyExprT = exprToExpr bodyExpr - let exprT = mkWhile g (SequencePointInfoForWhileLoop.NoSequencePointAtWhileLoop, SpecialWhileLoopMarker.NoSpecialWhileLoopMarker, guardExprT, bodyExprT, m) + let exprT = mkWhile g (DebugPointAtWhile.No, SpecialWhileLoopMarker.NoSpecialWhileLoopMarker, guardExprT, bodyExprT, m) None, (exprT, tyOfExpr g exprT) - | None -> - match ea.PApplyOption((function ProvidedForIntegerRangeLoopExpr x -> Some x | _ -> None), m) with - | Some info -> - let v, e1, e2, e3 = info.PApply4(id, m) + | ProvidedForIntegerRangeLoopExpr (v, e1, e2, e3) -> + let v, e1, e2, e3 = exprType.PApply4((fun _ -> (v, e1, e2, e3)), m) let e1T = exprToExpr e1 let e2T = exprToExpr e2 let vT = addVar v let e3T = exprToExpr e3 removeVar v - let exprT = mkFastForLoop g (SequencePointInfoForForLoop.NoSequencePointAtForLoop, m, vT, e1T, true, e2T, e3T) + let exprT = mkFastForLoop g (DebugPointAtFor.No, m, vT, e1T, true, e2T, e3T) None, (exprT, tyOfExpr g exprT) - | None -> - match ea.PApplyOption((function ProvidedNewDelegateExpr x -> Some x | _ -> None), m) with - | Some info -> - let delegateTy, boundVars, delegateBodyExpr = info.PApply3(id, m) + | ProvidedNewDelegateExpr (delegateTy, boundVars, delegateBodyExpr) -> + let delegateTy, boundVars, delegateBodyExpr = exprType.PApply3((fun _ -> (delegateTy, boundVars, delegateBodyExpr)), m) let delegateTyT = Import.ImportProvidedType amap m delegateTy - let vs = boundVars.PApplyArray(id, "GetInvokerExpresson", m) |> Array.toList + let vs = boundVars.PApplyArray(id, "GetInvokerExpression", m) |> Array.toList let vsT = List.map addVar vs let delegateBodyExprT = exprToExpr delegateBodyExpr List.iter removeVar vs @@ -1115,44 +1571,33 @@ module ProvidedMethodCalls = let infoReader = InfoReader(g, amap) let exprT = CoerceFromFSharpFuncToDelegate g amap infoReader AccessorDomain.AccessibleFromSomewhere lambdaExprTy m lambdaExpr delegateTyT None, (exprT, tyOfExpr g exprT) - | None -> #if PROVIDED_ADDRESS_OF - match ea.PApplyOption((function ProvidedAddressOfExpr x -> Some x | _ -> None), m) with - | Some e -> - let eT = exprToExpr e + | ProvidedAddressOfExpr e -> + let eT = exprToExpr (exprType.PApply((fun _ -> e), m)) let wrap,ce, _readonly, _writeonly = mkExprAddrOfExpr g true false DefinitelyMutates eT None m let ce = wrap ce None, (ce, tyOfExpr g ce) - | None -> #endif - match ea.PApplyOption((function ProvidedDefaultExpr x -> Some x | _ -> None), m) with - | Some pty -> - let ty = Import.ImportProvidedType amap m pty + | ProvidedDefaultExpr pty -> + let ty = Import.ImportProvidedType amap m (exprType.PApply((fun _ -> pty), m)) let ce = mkDefault (m, ty) None, (ce, tyOfExpr g ce) - | None -> - match ea.PApplyOption((function ProvidedCallExpr c -> Some c | _ -> None), m) with - | Some info -> - methodCallToExpr top ea info - | None -> - match ea.PApplyOption((function ProvidedSequentialExpr c -> Some c | _ -> None), m) with - | Some info -> - let e1, e2 = info.PApply2(id, m) + | ProvidedCallExpr (e1, e2, e3) -> + methodCallToExpr top ea (exprType.PApply((fun _ -> (e1, e2, e3)), m)) + | ProvidedSequentialExpr (e1, e2) -> + let e1, e2 = exprType.PApply2((fun _ -> (e1, e2)), m) let e1T = exprToExpr e1 let e2T = exprToExpr e2 let ce = mkCompGenSequential m e1T e2T None, (ce, tyOfExpr g ce) - | None -> - match ea.PApplyOption((function ProvidedTryFinallyExpr c -> Some c | _ -> None), m) with - | Some info -> - let e1, e2 = info.PApply2(id, m) + | ProvidedTryFinallyExpr (e1, e2) -> + let e1, e2 = exprType.PApply2((fun _ -> (e1, e2)), m) let e1T = exprToExpr e1 let e2T = exprToExpr e2 - let ce = mkTryFinally g (e1T, e2T, m, tyOfExpr g e1T, SequencePointInfoForTry.NoSequencePointAtTry, SequencePointInfoForFinally.NoSequencePointAtFinally) + let ce = mkTryFinally g (e1T, e2T, m, tyOfExpr g e1T, DebugPointAtTry.No, DebugPointAtFinally.No) None, (ce, tyOfExpr g ce) - | None -> - match ea.PApplyOption((function ProvidedTryWithExpr c -> Some c | _ -> None), m) with - | Some info -> + | ProvidedTryWithExpr (e1, e2, e3, e4, e5) -> + let info = exprType.PApply((fun _ -> (e1, e2, e3, e4, e5)), m) let bT = exprToExpr (info.PApply((fun (x, _, _, _, _) -> x), m)) let v1 = info.PApply((fun (_, x, _, _, _) -> x), m) let v1T = addVar v1 @@ -1162,21 +1607,17 @@ module ProvidedMethodCalls = let v2T = addVar v2 let e2T = exprToExpr (info.PApply((fun (_, _, _, _, x) -> x), m)) removeVar v2 - let ce = mkTryWith g (bT, v1T, e1T, v2T, e2T, m, tyOfExpr g bT, SequencePointInfoForTry.NoSequencePointAtTry, SequencePointInfoForWith.NoSequencePointAtWith) + let ce = mkTryWith g (bT, v1T, e1T, v2T, e2T, m, tyOfExpr g bT, DebugPointAtTry.No, DebugPointAtWith.No) None, (ce, tyOfExpr g ce) - | None -> - match ea.PApplyOption((function ProvidedNewObjectExpr c -> Some c | _ -> None), m) with - | Some info -> - None, ctorCallToExpr info - | None -> - fail() + | ProvidedNewObjectExpr (e1, e2) -> + None, ctorCallToExpr (exprType.PApply((fun _ -> (e1, e2)), m)) and ctorCallToExpr (ne: Tainted<_>) = let (ctor, args) = ne.PApply2(id, m) let targetMethInfo = ProvidedMeth(amap, ctor.PApply((fun ne -> upcast ne), m), None, m) let objArgs = [] - let arguments = [ for ea in args.PApplyArray(id, "GetInvokerExpresson", m) -> exprToExpr ea ] + let arguments = [ for ea in args.PApplyArray(id, "GetInvokerExpression", m) -> exprToExpr ea ] let callExpr = BuildMethodCall tcVal g amap Mutates.PossiblyMutates m false targetMethInfo isSuperInit [] objArgs arguments callExpr @@ -1201,7 +1642,7 @@ module ProvidedMethodCalls = | None -> [] | Some objExpr -> [exprToExpr objExpr] - let arguments = [ for ea in args.PApplyArray(id, "GetInvokerExpresson", m) -> exprToExpr ea ] + let arguments = [ for ea in args.PApplyArray(id, "GetInvokerExpression", m) -> exprToExpr ea ] let genericArguments = if meth.PUntaint((fun m -> m.IsGenericMethod), m) then meth.PApplyArray((fun m -> m.GetGenericArguments()), "GetGenericArguments", m) @@ -1219,7 +1660,7 @@ module ProvidedMethodCalls = // sub in the appropriate argument // REVIEW: "thisArg" pointer should be first, if present let vRaw = pe.PUntaint(id, m) - match varConv.TryGetValue(vRaw) with + match varConv.TryGetValue vRaw with | true, v -> v | _ -> let typeProviderDesignation = ExtensionTyping.DisplayNameOfTypeProvider (pe.TypeProvider, m) @@ -1276,13 +1717,22 @@ module ProvidedMethodCalls = raise( tpe.WithContext(typeName, methName) ) // loses original stack trace #endif - - let RecdFieldInstanceChecks g amap ad m (rfinfo: RecdFieldInfo) = if rfinfo.IsStatic then error (Error (FSComp.SR.tcStaticFieldUsedWhenInstanceFieldExpected(), m)) CheckRecdFieldInfoAttributes g rfinfo m |> CommitOperationResult CheckRecdFieldInfoAccessible amap m ad rfinfo +let ILFieldStaticChecks g amap infoReader ad m (finfo : ILFieldInfo) = + CheckILFieldInfoAccessible g amap m ad finfo + if not finfo.IsStatic then error (Error (FSComp.SR.tcFieldIsNotStatic(finfo.FieldName), m)) + + // Static IL interfaces fields are not supported in lower F# versions. + if isInterfaceTy g finfo.ApparentEnclosingType then + tryLanguageFeatureRuntimeErrorRecover infoReader LanguageFeature.DefaultInterfaceMemberConsumption m + tryLanguageFeatureErrorRecover g.langVersion LanguageFeature.DefaultInterfaceMemberConsumption m + + CheckILFieldAttributes g finfo m + let ILFieldInstanceChecks g amap ad m (finfo : ILFieldInfo) = if finfo.IsStatic then error (Error (FSComp.SR.tcStaticFieldUsedWhenInstanceFieldExpected(), m)) CheckILFieldInfoAccessible g amap m ad finfo @@ -1322,8 +1772,131 @@ let MethInfoChecks g amap isInstance tyargsOpt objArgs ad m (minfo: MethInfo) = CheckMethInfoAttributes g m tyargsOpt minfo |> CommitOperationResult -exception FieldNotMutable of DisplayEnv * Tast.RecdFieldRef * range +exception FieldNotMutable of DisplayEnv * RecdFieldRef * range let CheckRecdFieldMutation m denv (rfinfo: RecdFieldInfo) = - if not rfinfo.RecdField.IsMutable then error (FieldNotMutable(denv, rfinfo.RecdFieldRef, m)) + if not rfinfo.RecdField.IsMutable then + errorR (FieldNotMutable (denv, rfinfo.RecdFieldRef, m)) + +/// Generate a witness for the given (solved) constraint. Five possiblilities are taken +/// into account. +/// 1. The constraint is solved by a .NET-declared method or an F#-declared method +/// 2. The constraint is solved by an F# record field +/// 3. The constraint is solved by an F# anonymous record field +/// 4. The constraint is considered solved by a "built in" solution +/// 5. The constraint is solved by a closed expression given by a provided method from a type provider +/// +/// In each case an expression is returned where the method is applied to the given arguments, or the +/// field is dereferenced. +/// +/// None is returned in the cases where the trait has not been solved (e.g. is part of generic code) +/// or there is an unexpected mismatch of some kind. +let GenWitnessExpr amap g m (traitInfo: TraitConstraintInfo) argExprs = + + let sln = + match traitInfo.Solution with + | None -> Choice5Of5() + | Some sln -> + + // Given the solution information, reconstruct the MethInfo for the solution + match sln with + | ILMethSln(origTy, extOpt, mref, minst) -> + let metadataTy = convertToTypeWithMetadataIfPossible g origTy + let tcref = tcrefOfAppTy g metadataTy + let mdef = resolveILMethodRef tcref.ILTyconRawMetadata mref + let ilMethInfo = + match extOpt with + | None -> MethInfo.CreateILMeth(amap, m, origTy, mdef) + | Some ilActualTypeRef -> + let actualTyconRef = Import.ImportILTypeRef amap m ilActualTypeRef + MethInfo.CreateILExtensionMeth(amap, m, origTy, actualTyconRef, None, mdef) + Choice1Of5 (ilMethInfo, minst) + + | FSMethSln(ty, vref, minst) -> + Choice1Of5 (FSMeth(g, ty, vref, None), minst) + + | FSRecdFieldSln(tinst, rfref, isSetProp) -> + Choice2Of5 (tinst, rfref, isSetProp) + + | FSAnonRecdFieldSln(anonInfo, tinst, i) -> + Choice3Of5 (anonInfo, tinst, i) + + | BuiltInSln -> + Choice5Of5 () + + | ClosedExprSln expr -> + Choice4Of5 expr + match sln with + | Choice1Of5(minfo, methArgTys) -> + let argExprs = + // FIX for #421894 - typechecker assumes that coercion can be applied for the trait calls arguments but codegen doesn't emit coercion operations + // result - generation of non-verifiable code + // fix - apply coercion for the arguments (excluding 'receiver' argument in instance calls) + + // flatten list of argument types (looks like trait calls with curried arguments are not supported so we can just convert argument list in straightforward way) + let argTypes = + minfo.GetParamTypes(amap, m, methArgTys) + |> List.concat + // do not apply coercion to the 'receiver' argument + let receiverArgOpt, argExprs = + if minfo.IsInstance then + match argExprs with + | h :: t -> Some h, t + | argExprs -> None, argExprs + else None, argExprs + let convertedArgs = (argExprs, argTypes) ||> List.map2 (fun expr expectedTy -> mkCoerceIfNeeded g expectedTy (tyOfExpr g expr) expr) + match receiverArgOpt with + | Some r -> r :: convertedArgs + | None -> convertedArgs + + // Fix bug 1281: If we resolve to an instance method on a struct and we haven't yet taken + // the address of the object then go do that + if minfo.IsStruct && minfo.IsInstance && (match argExprs with [] -> false | h :: _ -> not (isByrefTy g (tyOfExpr g h))) then + let h, t = List.headAndTail argExprs + let wrap, h', _readonly, _writeonly = mkExprAddrOfExpr g true false PossiblyMutates h None m + Some (wrap (Expr.Op (TOp.TraitCall (traitInfo), [], (h' :: t), m))) + else + Some (MakeMethInfoCall amap m minfo methArgTys argExprs ) + + | Choice2Of5 (tinst, rfref, isSet) -> + match isSet, rfref.RecdField.IsStatic, argExprs.Length with + + // static setter + | true, true, 1 -> + Some (mkStaticRecdFieldSet (rfref, tinst, argExprs.[0], m)) + + // instance setter + | true, false, 2 -> + // If we resolve to an instance field on a struct and we haven't yet taken + // the address of the object then go do that + if rfref.Tycon.IsStructOrEnumTycon && not (isByrefTy g (tyOfExpr g argExprs.[0])) then + let h = List.head argExprs + let wrap, h', _readonly, _writeonly = mkExprAddrOfExpr g true false DefinitelyMutates h None m + Some (wrap (mkRecdFieldSetViaExprAddr (h', rfref, tinst, argExprs.[1], m))) + else + Some (mkRecdFieldSetViaExprAddr (argExprs.[0], rfref, tinst, argExprs.[1], m)) + + // static getter + | false, true, 0 -> + Some (mkStaticRecdFieldGet (rfref, tinst, m)) + + // instance getter + | false, false, 1 -> + if rfref.Tycon.IsStructOrEnumTycon && isByrefTy g (tyOfExpr g argExprs.[0]) then + Some (mkRecdFieldGetViaExprAddr (argExprs.[0], rfref, tinst, m)) + else + Some (mkRecdFieldGet g (argExprs.[0], rfref, tinst, m)) + | _ -> None + + | Choice3Of5 (anonInfo, tinst, i) -> + let tupInfo = anonInfo.TupInfo + if evalTupInfoIsStruct tupInfo && isByrefTy g (tyOfExpr g argExprs.[0]) then + Some (mkAnonRecdFieldGetViaExprAddr (anonInfo, argExprs.[0], tinst, i, m)) + else + Some (mkAnonRecdFieldGet g (anonInfo, argExprs.[0], tinst, i, m)) + | Choice4Of5 expr -> + Some (MakeApplicationAndBetaReduce g (expr, tyOfExpr g expr, [], argExprs, m)) + + | Choice5Of5 () -> + None diff --git a/src/fcs-fable/src/fsharp/MethodOverrides.fs b/src/fcs-fable/src/fsharp/MethodOverrides.fs index eda26ec3bd..629a5435d0 100644 --- a/src/fcs-fable/src/fsharp/MethodOverrides.fs +++ b/src/fcs-fable/src/fsharp/MethodOverrides.fs @@ -5,17 +5,20 @@ module internal FSharp.Compiler.MethodOverrides open FSharp.Compiler open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.Ast +open FSharp.Compiler.AccessibilityLogic open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.InfoReader open FSharp.Compiler.Lib open FSharp.Compiler.Infos -open FSharp.Compiler.AccessibilityLogic +open FSharp.Compiler.Features open FSharp.Compiler.NameResolution open FSharp.Compiler.Range -open FSharp.Compiler.InfoReader -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TypeRelations //------------------------------------------------------------------------- @@ -40,10 +43,34 @@ type OverrideInfo = member x.ReturnType = let (Override(_, _, _, _, _, b, _, _)) = x in b member x.IsCompilerGenerated = let (Override(_, _, _, _, _, _, _, b)) = x in b -// If the bool is true then the slot is optional, i.e. is an interface slot -// which does not _have_ to be implemented, because an inherited implementation -// is available. -type RequiredSlot = RequiredSlot of MethInfo * (* isOptional: *) bool +type RequiredSlot = + | RequiredSlot of MethInfo * isOptional: bool + | DefaultInterfaceImplementationSlot of MethInfo * isOptional: bool * possiblyNoMostSpecific: bool + + /// A slot which does not have to be implemented, because an inherited implementation is available. + member this.IsOptional = + match this with + | RequiredSlot(_, isOptional) + | DefaultInterfaceImplementationSlot(_, isOptional, _) -> isOptional + + /// A slot which has a default interface implementation. + /// A combination of this flag and the lack of IsOptional means the slot may have been reabstracted. + member this.HasDefaultInterfaceImplementation = + match this with + | DefaultInterfaceImplementationSlot _ -> true + | _ -> false + + /// A slot that *might* have ambiguity due to multiple inheritance; happens with default interface implementations. + member this.PossiblyNoMostSpecificImplementation = + match this with + | DefaultInterfaceImplementationSlot(_, _, possiblyNoMostSpecific) -> possiblyNoMostSpecific + | _ -> false + + /// Gets the method info. + member this.MethodInfo = + match this with + | RequiredSlot(methInfo, _) + | DefaultInterfaceImplementationSlot(methInfo, _, _) -> methInfo type SlotImplSet = SlotImplSet of RequiredSlot list * NameMultiMap * OverrideInfo list * PropInfo list @@ -134,7 +161,7 @@ module DispatchSlotChecking = // Drop 'this' match vsl with - | [thisv]::vs -> + | [thisv] :: vs -> // Check for empty variable list from a () arg let vs = if vs.Length = 1 && argInfos.IsEmpty then [] else vs let implKind = @@ -167,14 +194,18 @@ module DispatchSlotChecking = let IsTyparKindMatch (CompiledSig(_, _, fvmtps, _)) (Override(_, _, _, (mtps, _), _, _, _, _)) = List.lengthsEqAndForall2 (fun (tp1: Typar) (tp2: Typar) -> tp1.Kind = tp2.Kind) mtps fvmtps - /// Check if an override is a partial match for the requirements for a dispatch slot - let IsPartialMatch g (dispatchSlot: MethInfo) compiledSig (Override(_, _, _, (mtps, _), argTys, _retTy, _, _) as overrideBy) = - IsNameMatch dispatchSlot overrideBy && + /// Check if an override is a partial match for the requirements for a dispatch slot except for the name. + let IsSigPartialMatch g (dispatchSlot: MethInfo) compiledSig (Override(_, _, _, (mtps, _), argTys, _retTy, _, _) as overrideBy) = let (CompiledSig (vargtys, _, fvmtps, _)) = compiledSig mtps.Length = fvmtps.Length && IsTyparKindMatch compiledSig overrideBy && argTys.Length = vargtys.Length && - IsImplMatch g dispatchSlot overrideBy + IsImplMatch g dispatchSlot overrideBy + + /// Check if an override is a partial match for the requirements for a dispatch slot. + let IsPartialMatch g dispatchSlot compiledSig overrideBy = + IsNameMatch dispatchSlot overrideBy && + IsSigPartialMatch g dispatchSlot compiledSig overrideBy /// Compute the reverse of a type parameter renaming. let ReverseTyparRenaming g tinst = @@ -184,10 +215,10 @@ module DispatchSlotChecking = let ComposeTyparInsts inst1 inst2 = inst1 |> List.map (map2Of2 (instType inst2)) - /// Check if an override exactly matches the requirements for a dispatch slot - let IsExactMatch g amap m dispatchSlot (Override(_, _, _, (mtps, mtpinst), argTys, retTy, _, _) as overrideBy) = + /// Check if an override exactly matches the requirements for a dispatch slot except for the name. + let IsSigExactMatch g amap m dispatchSlot (Override(_, _, _, (mtps, mtpinst), argTys, retTy, _, _) as overrideBy) = let compiledSig = CompiledSigOfMeth g amap m dispatchSlot - IsPartialMatch g dispatchSlot compiledSig overrideBy && + IsSigPartialMatch g dispatchSlot compiledSig overrideBy && let (CompiledSig (vargtys, vrty, fvmtps, ttpinst)) = compiledSig // Compare the types. CompiledSigOfMeth, GetObjectExprOverrideInfo and GetTypeMemberOverrideInfo have already @@ -231,6 +262,11 @@ module DispatchSlotChecking = typarsAEquiv g aenv fvmtps mtps + /// Check if an override exactly matches the requirements for a dispatch slot. + let IsExactMatch g amap m dispatchSlot overrideBy = + IsNameMatch dispatchSlot overrideBy && + IsSigExactMatch g amap m dispatchSlot overrideBy + /// Check if an override implements a dispatch slot let OverrideImplementsDispatchSlot g amap m dispatchSlot availPriorOverride = IsExactMatch g amap m dispatchSlot availPriorOverride && @@ -243,48 +279,66 @@ module DispatchSlotChecking = |> NameMultiMap.find dispatchSlot.LogicalName |> List.exists (OverrideImplementsDispatchSlot g amap m dispatchSlot) - /// Check all dispatch slots are implemented by some override. - let CheckDispatchSlotsAreImplemented (denv, g, amap, m, + let CheckDispatchSlotsAreImplemented (denv, infoReader: InfoReader, m, nenv, sink: TcResultsSink, isOverallTyAbstract, reqdTy, dispatchSlots: RequiredSlot list, availPriorOverrides: OverrideInfo list, overrides: OverrideInfo list) = + let g = infoReader.g + let amap = infoReader.amap let isReqdTyInterface = isInterfaceTy g reqdTy let showMissingMethodsAndRaiseErrors = (isReqdTyInterface || not isOverallTyAbstract) - let res = ref true - let fail exn = (res := false ; if showMissingMethodsAndRaiseErrors then errorR exn) + let mutable res = true + let fail exn = + res <- false + if showMissingMethodsAndRaiseErrors then + errorR exn + // Index the availPriorOverrides and overrides by name let availPriorOverridesKeyed = availPriorOverrides |> NameMultiMap.initBy (fun ov -> ov.LogicalName) let overridesKeyed = overrides |> NameMultiMap.initBy (fun ov -> ov.LogicalName) - dispatchSlots |> List.iter (fun (RequiredSlot(dispatchSlot, isOptional)) -> - - match NameMultiMap.find dispatchSlot.LogicalName overridesKeyed - |> List.filter (OverrideImplementsDispatchSlot g amap m dispatchSlot) with + // we accumulate those to compose a more complete error message, see noimpl() bellow. + let missingOverloadImplementation = ResizeArray() + + for reqdSlot in dispatchSlots do + let dispatchSlot = reqdSlot.MethodInfo + + // Always try to raise a target runtime error if we have a DIM. + if reqdSlot.HasDefaultInterfaceImplementation then + tryLanguageFeatureRuntimeErrorRecover infoReader LanguageFeature.DefaultInterfaceMemberConsumption m + + let maybeResolvedSlot = + NameMultiMap.find dispatchSlot.LogicalName overridesKeyed + |> List.filter (OverrideImplementsDispatchSlot g amap m dispatchSlot) + + match maybeResolvedSlot with | [ovd] -> if not ovd.IsCompilerGenerated then - let item = Item.MethodGroup(ovd.LogicalName, [dispatchSlot], None) - CallNameResolutionSink sink (ovd.Range, nenv, item, item, dispatchSlot.FormalMethodTyparInst, ItemOccurence.Implemented, denv, AccessorDomain.AccessibleFromSomewhere) - sink |> ignore - () + let item = Item.MethodGroup(ovd.LogicalName, [dispatchSlot],None) + CallNameResolutionSink sink (ovd.Range, nenv, item, dispatchSlot.FormalMethodTyparInst, ItemOccurence.Implemented, AccessorDomain.AccessibleFromSomewhere) | [] -> - if not isOptional && + if not reqdSlot.IsOptional && // Check that no available prior override implements this dispatch slot not (DispatchSlotIsAlreadyImplemented g amap m availPriorOverridesKeyed dispatchSlot) then + // Always try to raise a language version error if we have a DIM that is not explicitly implemented. + if reqdSlot.HasDefaultInterfaceImplementation then + tryLanguageFeatureErrorRecover g.langVersion LanguageFeature.DefaultInterfaceMemberConsumption m + + if reqdSlot.PossiblyNoMostSpecificImplementation then + errorR(Error(FSComp.SR.typrelInterfaceMemberNoMostSpecificImplementation(NicePrint.stringOfMethInfo amap m denv dispatchSlot), m)) + // error reporting path let compiledSig = CompiledSigOfMeth g amap m dispatchSlot let noimpl() = - if isReqdTyInterface then - fail(Error(FSComp.SR.typrelNoImplementationGivenWithSuggestion(NicePrint.stringOfMethInfo amap m denv dispatchSlot), m)) - else - fail(Error(FSComp.SR.typrelNoImplementationGiven(NicePrint.stringOfMethInfo amap m denv dispatchSlot), m)) + missingOverloadImplementation.Add((isReqdTyInterface, lazy NicePrint.stringOfMethInfo amap m denv dispatchSlot)) match overrides |> List.filter (IsPartialMatch g dispatchSlot compiledSig) with | [] -> @@ -298,7 +352,7 @@ module DispatchSlotChecking = | [ Override(_, _, _, (mtps, _), argTys, _, _, _) as overrideBy ] -> let moreThanOnePossibleDispatchSlot = dispatchSlots - |> List.filter (fun (RequiredSlot(dispatchSlot, _)) -> IsNameMatch dispatchSlot overrideBy && IsImplMatch g dispatchSlot overrideBy) + |> List.filter (fun reqdSlot-> IsNameMatch reqdSlot.MethodInfo overrideBy && IsImplMatch g reqdSlot.MethodInfo overrideBy) |> isNilOrSingleton |> not @@ -307,7 +361,7 @@ module DispatchSlotChecking = if moreThanOnePossibleDispatchSlot then noimpl() - elif argTys.Length <> vargtys.Length then + elif argTys.Length <> vargtys.Length then fail(Error(FSComp.SR.typrelMemberDoesNotHaveCorrectNumberOfArguments(FormatOverride denv overrideBy, FormatMethInfoSig g amap m denv dispatchSlot), overrideBy.Range)) elif mtps.Length <> fvmtps.Length then fail(Error(FSComp.SR.typrelMemberDoesNotHaveCorrectNumberOfTypeParameters(FormatOverride denv overrideBy, FormatMethInfoSig g amap m denv dispatchSlot), overrideBy.Range)) @@ -319,16 +373,167 @@ module DispatchSlotChecking = errorR(Error(FSComp.SR.typrelOverloadNotFound(FormatMethInfoSig g amap m denv dispatchSlot, FormatMethInfoSig g amap m denv dispatchSlot), overrideBy.Range)) | [ overrideBy ] -> - if dispatchSlots |> List.exists (fun (RequiredSlot(dispatchSlot, _)) -> OverrideImplementsDispatchSlot g amap m dispatchSlot overrideBy) then + if dispatchSlots |> List.exists (fun reqdSlot -> OverrideImplementsDispatchSlot g amap m reqdSlot.MethodInfo overrideBy) then noimpl() else // Error will be reported below in CheckOverridesAreAllUsedOnce () - | _ -> fail(Error(FSComp.SR.typrelOverrideWasAmbiguous(FormatMethInfoSig g amap m denv dispatchSlot), m)) - | _ -> fail(Error(FSComp.SR.typrelMoreThenOneOverride(FormatMethInfoSig g amap m denv dispatchSlot), m))) - !res + | _ -> fail(Error(FSComp.SR.typrelMoreThenOneOverride(FormatMethInfoSig g amap m denv dispatchSlot), m)) + + if missingOverloadImplementation.Count > 0 then + // compose message listing missing override implementation + let maxDisplayedOverrides = 10 + let shouldTruncate = missingOverloadImplementation.Count > maxDisplayedOverrides + let messageWithInterfaceSuggestion = + // check any of the missing overrides has isReqdTyInterface flag set + // in which case we use the message "with suggestion" + missingOverloadImplementation + |> Seq.map fst + |> Seq.filter id + |> Seq.isEmpty + |> not + + if missingOverloadImplementation.Count = 1 then + // only one missing override, we have specific message for that + let signature = (snd missingOverloadImplementation.[0]).Value + if messageWithInterfaceSuggestion then + fail(Error(FSComp.SR.typrelNoImplementationGivenWithSuggestion(signature), m)) + else + fail(Error(FSComp.SR.typrelNoImplementationGiven(signature), m)) + else + let signatures = + (missingOverloadImplementation + |> Seq.truncate maxDisplayedOverrides + |> Seq.map snd + |> Seq.map (fun signature -> System.Environment.NewLine + "\t'" + signature.Value + "'") + |> String.concat "") + System.Environment.NewLine + + // we have specific message if the list is truncated + let messageFunction = + match shouldTruncate, messageWithInterfaceSuggestion with + | false, true -> FSComp.SR.typrelNoImplementationGivenSeveralWithSuggestion + | false, false -> FSComp.SR.typrelNoImplementationGivenSeveral + | true , true -> FSComp.SR.typrelNoImplementationGivenSeveralTruncatedWithSuggestion + | true , false -> FSComp.SR.typrelNoImplementationGivenSeveralTruncated + fail(Error(messageFunction(signatures), m)) + + res + + /// This is to find override methods that are at the most specific in the hierarchy of interface types. + let GetMostSpecificOverrideInterfaceMethodSets (infoReader: InfoReader) allReqdTys = + let g = infoReader.g + let amap = infoReader.amap + + let multipleSets = + allReqdTys + // Widdle down to the most specific interfaces. + |> GetMostSpecificItemsByType g amap (fun (ty, m) -> + if isInterfaceTy g ty then + Some(ty, m) + else + None) + + // Get the most specific method overrides for each interface type. + |> List.choose (fun (ty, m) -> + let mostSpecificOverrides = GetIntrinisicMostSpecificOverrideMethInfoSetsOfType infoReader m ty + if mostSpecificOverrides.IsEmpty then None + else Some mostSpecificOverrides) + + match multipleSets with + | [] -> NameMultiMap.Empty + | [set] -> set + | _ -> + multipleSets + // Merge method sets together. + |> List.reduce (fun final minfoSets -> + Map.fold (fun acc key minfos -> + match acc.TryGetValue key with + | true, minfos2 -> Map.add key (minfos @ minfos2) acc + | _ -> Map.add key minfos acc) final minfoSets) + + // Filter for most specifics when the sets have merged together. + |> FilterMostSpecificMethInfoSets g amap range0 + + /// Finds the override interface methods from the most specific overrides by the given method. + let GetMostSpecificOverrideInterfaceMethodsByMethod g amap m (mostSpecificOverrides: NameMultiMap) (minfo: MethInfo) = + let overrideBy = GetInheritedMemberOverrideInfo g amap m OverrideCanImplement.CanImplementAnyInterfaceSlot minfo + let minfoTy = generalizedTyconRef minfo.ApparentEnclosingTyconRef + NameMultiMap.find minfo.LogicalName mostSpecificOverrides + |> List.filter (fun (overridenTy, minfo2) -> + typeEquiv g overridenTy minfoTy && + IsSigExactMatch g amap m minfo2 overrideBy) + + /// Get a collection of slots for the given interface type. + let GetInterfaceDispatchSlots (infoReader: InfoReader) ad m availImpliedInterfaces mostSpecificOverrides interfaceTy = + let g = infoReader.g + let amap = infoReader.amap + + if isInterfaceTy g interfaceTy then + // Check if the interface has an inherited implementation + // If so, you do not have to implement all the methods - each + // specific method is "optionally" implemented. + let isInterfaceOptional = ListSet.contains (typeEquiv g) interfaceTy availImpliedInterfaces + [ for minfo in GetImmediateIntrinsicMethInfosOfType (None, ad) g amap m interfaceTy do + if minfo.IsNewSlot then + // If the interface itself is considered optional, then we are finished and do not need anymore context. + // Even if the method is actually not abstract. + if isInterfaceOptional then + yield RequiredSlot (minfo, true) + + // F# defined interface methods have no notion of optional/abstract or DIMs. + elif not minfo.IsILMethod then + yield RequiredSlot (minfo, false) + + // IL methods might have default implementations. + else + let isMethodOptional (minfo: MethInfo) = + // A DIM is considered *not* 'optional' if it is not language supported. + g.langVersion.SupportsFeature LanguageFeature.DefaultInterfaceMemberConsumption && + not minfo.IsAbstract + + match GetMostSpecificOverrideInterfaceMethodsByMethod g amap m mostSpecificOverrides minfo with + // No override. + | [] -> + if minfo.IsAbstract then + // Regular interface methods are never optional. + yield RequiredSlot (minfo, false) + else + yield DefaultInterfaceImplementationSlot (minfo, isMethodOptional minfo, false) + + // One override, one default implementation. + | [ (_, minfo2) ] -> + yield DefaultInterfaceImplementationSlot (minfo, isMethodOptional minfo2, false) + + // We found multiple override methods, means we might have ambiguity. + | _ -> + // If DIMs are not language supported, then do not consider a slot to have a specific implementation. + let possiblyNoMostSpecific = + g.langVersion.SupportsFeature LanguageFeature.DefaultInterfaceMemberConsumption + + yield DefaultInterfaceImplementationSlot (minfo, false, possiblyNoMostSpecific) ] + else + [] + + /// Get a collection of slots for the given class type. + let GetClassDispatchSlots (infoReader: InfoReader) ad m reqdTy = + [ if not (isInterfaceTy infoReader.g reqdTy) then + // In the normal case, the requirements for a class are precisely all the abstract slots up the whole hierarchy. + // So here we get and yield all of those. + for minfo in reqdTy |> GetIntrinsicMethInfosOfType infoReader None ad AllowMultiIntfInstantiations.Yes IgnoreOverrides m do + if minfo.IsDispatchSlot then + yield RequiredSlot(minfo, not minfo.IsAbstract) ] + + /// Get a collection of slots for the given type and implied types. + let GetDispatchSlotSet (infoReader: InfoReader) ad m availImpliedInterfaces mostSpecificOverrides reqdTy impliedTys = + let g = infoReader.g + + if isInterfaceTy g reqdTy then + [ for impliedTy in impliedTys do + yield (impliedTy, GetInterfaceDispatchSlots infoReader ad m availImpliedInterfaces mostSpecificOverrides impliedTy) ] + else + [ (reqdTy, GetClassDispatchSlots infoReader ad m reqdTy) ] /// Check all implementations implement some dispatch slot. let CheckOverridesAreAllUsedOnce(denv, g, amap, isObjExpr, reqdTy, @@ -340,7 +545,7 @@ module DispatchSlotChecking = if not overrideBy.IsFakeEventProperty then let m = overrideBy.Range let relevantVirts = NameMultiMap.find overrideBy.LogicalName dispatchSlotsKeyed - let relevantVirts = relevantVirts |> List.map (fun (RequiredSlot(dispatchSlot, _)) -> dispatchSlot) + let relevantVirts = relevantVirts |> List.map (fun reqdSlot -> reqdSlot.MethodInfo) match relevantVirts |> List.filter (fun dispatchSlot -> OverrideImplementsDispatchSlot g amap m dispatchSlot overrideBy) with | [] -> @@ -376,7 +581,7 @@ module DispatchSlotChecking = // dispatch slots are ordered from the derived classes to base // so we can check the topmost dispatch slot if it is final match dispatchSlots with - | meth::_ when meth.IsFinal -> errorR(Error(FSComp.SR.tcCannotOverrideSealedMethod((sprintf "%s::%s" (meth.ApparentEnclosingType.ToString()) (meth.LogicalName))), m)) + | meth :: _ when meth.IsFinal -> errorR(Error(FSComp.SR.tcCannotOverrideSealedMethod((sprintf "%s::%s" (meth.ApparentEnclosingType.ToString()) (meth.LogicalName))), m)) | _ -> () @@ -388,7 +593,7 @@ module DispatchSlotChecking = /// allReqdTys = {C;I2;I3} /// /// allReqdTys can include one class/record/union type. - let GetSlotImplSets (infoReader: InfoReader) denv isObjExpr allReqdTys = + let GetSlotImplSets (infoReader: InfoReader) denv ad isObjExpr allReqdTys = let g = infoReader.g let amap = infoReader.amap @@ -413,7 +618,7 @@ module DispatchSlotChecking = // For each implemented type, reduce its list of implied interfaces by subtracting out those implied // by another implemented interface type. // - // REVIEW: Note complexity O(ity*jty) + // REVIEW: Note complexity O(N^2) let reqdTyInfos = intfSets |> List.map (fun (i, reqdTy, impliedTys, m) -> let reduced = @@ -423,26 +628,17 @@ module DispatchSlotChecking = else acc ) (i, reqdTy, m, reduced)) - // Check that, for each implemented type, at least one implemented type is implied. This is enough to capture - // duplicates. - for (_i, reqdTy, m, impliedTys) in reqdTyInfos do - if isInterfaceTy g reqdTy && isNil impliedTys then - errorR(Error(FSComp.SR.typrelDuplicateInterface(), m)) - - // Check that no interface type is implied twice - // - // Note complexity O(reqdTy*reqdTy) - for (i, _reqdTy, reqdTyRange, impliedTys) in reqdTyInfos do - for (j, _, _, impliedTys2) in reqdTyInfos do - if i > j then - let overlap = ListSet.intersect (TypesFeasiblyEquiv 0 g amap reqdTyRange) impliedTys impliedTys2 - overlap |> List.iter (fun overlappingTy -> - if not (isNil (GetImmediateIntrinsicMethInfosOfType (None, AccessibleFromSomewhere) g amap reqdTyRange overlappingTy |> List.filter (fun minfo -> minfo.IsVirtual))) then - errorR(Error(FSComp.SR.typrelNeedExplicitImplementation(NicePrint.minimalStringOfType denv (List.head overlap)), reqdTyRange))) + // Find the full set of most derived interfaces, used roots to search for default interface implementations of interface methods. + let mostSpecificOverrides = GetMostSpecificOverrideInterfaceMethodSets infoReader allReqdTys // Get the SlotImplSet for each implemented type // This contains the list of required members and the list of available members - [ for (_, reqdTy, reqdTyRange, impliedTys) in reqdTyInfos do + [ for (i, reqdTy, reqdTyRange, impliedTys) in reqdTyInfos do + + // Check that, for each implemented type, at least one implemented type is implied. This is enough to capture + // duplicates. + if isInterfaceTy g reqdTy && isNil impliedTys then + errorR(Error(FSComp.SR.typrelDuplicateInterface(), reqdTyRange)) // Build a set of the implied interface types, for quicker lookup, by nominal type let isImpliedInterfaceTable = @@ -457,28 +653,7 @@ module DispatchSlotChecking = isImpliedInterfaceTable.ContainsKey (tcrefOfAppTy g ty) && impliedTys |> List.exists (TypesFeasiblyEquiv 0 g amap reqdTyRange ty) - //let isSlotImpl (minfo: MethInfo) = - // not minfo.IsAbstract && minfo.IsVirtual - - // Compute the abstract slots that require implementations - let dispatchSlots = - [ if isInterfaceTy g reqdTy then - for impliedTy in impliedTys do - // Check if the interface has an inherited implementation - // If so, you do not have to implement all the methods - each - // specific method is "optionally" implemented. - let isOptional = - ListSet.contains (typeEquiv g) impliedTy availImpliedInterfaces - for reqdSlot in GetImmediateIntrinsicMethInfosOfType (None, AccessibleFromSomewhere) g amap reqdTyRange impliedTy do - yield RequiredSlot(reqdSlot, isOptional) - else - - // In the normal case, the requirements for a class are precisely all the abstract slots up the whole hierarchy. - // So here we get and yield all of those. - for minfo in reqdTy |> GetIntrinsicMethInfosOfType infoReader (None, AccessibleFromSomewhere, AllowMultiIntfInstantiations.Yes) IgnoreOverrides reqdTyRange do - if minfo.IsDispatchSlot then - yield RequiredSlot(minfo, (*isOptional=*) not minfo.IsAbstract) ] - + let dispatchSlotSet = GetDispatchSlotSet infoReader ad reqdTyRange availImpliedInterfaces mostSpecificOverrides reqdTy impliedTys // Compute the methods that are available to implement abstract slots from the base class // @@ -493,16 +668,28 @@ module DispatchSlotChecking = match baseTyOpt with | None -> reqdTy | Some baseTy -> baseTy - [ // Get any class hierarchy methods on this type + [ // Get any class hierarchy methods or default interface methods on this type on this type // // NOTE: What we have below is an over-approximation that will get too many methods // and not always correctly relate them to the slots they implement. For example, // we may get an override from a base class and believe it implements a fresh, new abstract // slot in a subclass. - for minfos in infoReader.GetRawIntrinsicMethodSetsOfType(None, AccessibleFromSomewhere, AllowMultiIntfInstantiations.Yes, reqdTyRange, reqdTy) do + for minfos in infoReader.GetRawIntrinsicMethodSetsOfType(None, ad, AllowMultiIntfInstantiations.Yes, reqdTyRange, reqdTy) do for minfo in minfos do if not minfo.IsAbstract then yield GetInheritedMemberOverrideInfo g amap reqdTyRange CanImplementAnyClassHierarchySlot minfo ] + + /// Check that no interface type is implied twice + for (j, _, _, impliedTys2) in reqdTyInfos do + if i > j then + for (ty, dispatchSlots) in dispatchSlotSet do + if impliedTys2 |> List.exists (TypesFeasiblyEquiv 0 g amap reqdTyRange ty) then + if dispatchSlots + |> List.exists (fun reqdSlot -> + let minfo = reqdSlot.MethodInfo + // If the slot is optional, then we do not need an explicit implementation. + minfo.IsNewSlot && not reqdSlot.IsOptional) then + errorR(Error(FSComp.SR.typrelNeedExplicitImplementation(NicePrint.minimalStringOfType denv ty), reqdTyRange)) // We also collect up the properties. This is used for abstract slot inference when overriding properties let isRelevantRequiredProperty (x: PropInfo) = @@ -510,10 +697,11 @@ module DispatchSlotChecking = isImpliedInterfaceType x.ApparentEnclosingType let reqdProperties = - GetIntrinsicPropInfosOfType infoReader (None, AccessibleFromSomewhere, AllowMultiIntfInstantiations.Yes) IgnoreOverrides reqdTyRange reqdTy + GetIntrinsicPropInfosOfType infoReader None ad AllowMultiIntfInstantiations.Yes IgnoreOverrides reqdTyRange reqdTy |> List.filter isRelevantRequiredProperty - let dispatchSlotsKeyed = dispatchSlots |> NameMultiMap.initBy (fun (RequiredSlot(v, _)) -> v.LogicalName) + let dispatchSlots = dispatchSlotSet |> List.map snd |> List.concat + let dispatchSlotsKeyed = dispatchSlots |> NameMultiMap.initBy (fun reqdSlot -> reqdSlot.MethodInfo.LogicalName) yield SlotImplSet(dispatchSlots, dispatchSlotsKeyed, availPriorOverrides, reqdProperties) ] @@ -536,7 +724,7 @@ module DispatchSlotChecking = let allImmediateMembers = tycon.MembersOfFSharpTyconSorted @ tycon.AllGeneratedValues // Get all the members we have to implement, organized by each type we explicitly implement - let slotImplSets = GetSlotImplSets infoReader denv false allReqdTys + let slotImplSets = GetSlotImplSets infoReader denv AccessibleFromSomewhere false allReqdTys let allImpls = List.zip allReqdTys slotImplSets @@ -581,7 +769,7 @@ module DispatchSlotChecking = if isImplementation && not (isInterfaceTy g overallTy) then let overrides = allImmediateMembersThatMightImplementDispatchSlots |> List.map snd - let allCorrect = CheckDispatchSlotsAreImplemented (denv, g, amap, m, nenv, sink, tcaug.tcaug_abstract, reqdTy, dispatchSlots, availPriorOverrides, overrides) + let allCorrect = CheckDispatchSlotsAreImplemented (denv, infoReader, m, nenv, sink, tcaug.tcaug_abstract, reqdTy, dispatchSlots, availPriorOverrides, overrides) // Tell the user to mark the thing abstract if it was missing implementations if not allCorrect && not tcaug.tcaug_abstract && not (isInterfaceTy g reqdTy) then @@ -609,7 +797,8 @@ module DispatchSlotChecking = [ for ((reqdTy, m), (SlotImplSet(_dispatchSlots, dispatchSlotsKeyed, _, _))) in allImpls do let overrideByInfo = GetTypeMemberOverrideInfo g reqdTy overrideBy let overridenForThisSlotImplSet = - [ for (RequiredSlot(dispatchSlot, _)) in NameMultiMap.find overrideByInfo.LogicalName dispatchSlotsKeyed do + [ for reqdSlot in NameMultiMap.find overrideByInfo.LogicalName dispatchSlotsKeyed do + let dispatchSlot = reqdSlot.MethodInfo if OverrideImplementsDispatchSlot g amap m dispatchSlot overrideByInfo then if tyconRefEq g overrideByInfo.BoundingTyconRef dispatchSlot.DeclaringTyconRef then match dispatchSlot.ArbitraryValRef with @@ -633,13 +822,6 @@ module DispatchSlotChecking = overrideBy.MemberInfo.Value.ImplementedSlotSigs <- overriden) - - -//------------------------------------------------------------------------- -// "Type Completion" inference and a few other checks at the end of the inference scope -//------------------------------------------------------------------------- - - /// "Type Completion" inference and a few other checks at the end of the inference scope let FinalTypeDefinitionChecksAtEndOfInferenceScope (infoReader: InfoReader, nenv, sink, isImplementation, denv) (tycon: Tycon) = @@ -687,7 +869,6 @@ let FinalTypeDefinitionChecksAtEndOfInferenceScope (infoReader: InfoReader, nenv if hasExplicitObjectEqualsOverride && not hasExplicitObjectGetHashCode then warning(Error(FSComp.SR.typrelExplicitImplementationOfEquals(tycon.DisplayName), m)) - // remember these values to ensure we don't generate these methods during codegen tcaug.SetHasObjectGetHashCode hasExplicitObjectGetHashCode @@ -706,9 +887,9 @@ let GetAbstractMethInfosForSynMethodDecl(infoReader: InfoReader, ad, memberName: let minfos = match typToSearchForAbstractMembers with | _, Some(SlotImplSet(_, dispatchSlotsKeyed, _, _)) -> - NameMultiMap.find memberName.idText dispatchSlotsKeyed |> List.map (fun (RequiredSlot(dispatchSlot, _)) -> dispatchSlot) + NameMultiMap.find memberName.idText dispatchSlotsKeyed |> List.map (fun reqdSlot -> reqdSlot.MethodInfo) | ty, None -> - GetIntrinsicMethInfosOfType infoReader (Some(memberName.idText), ad, AllowMultiIntfInstantiations.Yes) IgnoreOverrides bindm ty + GetIntrinsicMethInfosOfType infoReader (Some memberName.idText) ad AllowMultiIntfInstantiations.Yes IgnoreOverrides bindm ty let dispatchSlots = minfos |> List.filter (fun minfo -> minfo.IsDispatchSlot) let topValSynArities = SynInfo.AritiesOfArgs valSynData let topValSynArities = if List.isEmpty topValSynArities then topValSynArities else topValSynArities.Tail @@ -723,7 +904,7 @@ let GetAbstractPropInfosForSynPropertyDecl(infoReader: InfoReader, ad, memberNam | _, Some(SlotImplSet(_, _, _, reqdProps)) -> reqdProps |> List.filter (fun pinfo -> pinfo.PropertyName = memberName.idText) | ty, None -> - GetIntrinsicPropInfosOfType infoReader (Some(memberName.idText), ad, AllowMultiIntfInstantiations.Yes) IgnoreOverrides bindm ty + GetIntrinsicPropInfosOfType infoReader (Some memberName.idText) ad AllowMultiIntfInstantiations.Yes IgnoreOverrides bindm ty let dispatchSlots = pinfos |> List.filter (fun pinfo -> pinfo.IsVirtualProperty) dispatchSlots diff --git a/src/fcs-fable/src/fsharp/NameResolution.fs b/src/fcs-fable/src/fsharp/NameResolution.fs index 114d0d8016..368b6c3fb0 100644 --- a/src/fcs-fable/src/fsharp/NameResolution.fs +++ b/src/fcs-fable/src/fsharp/NameResolution.fs @@ -4,26 +4,33 @@ /// Name environment and name resolution module internal FSharp.Compiler.NameResolution +open System.Collections.Generic + open Internal.Utilities + open FSharp.Compiler -open FSharp.Compiler.Range -open FSharp.Compiler.Ast -open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Lib open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Internal.Library.ResultOrException open FSharp.Compiler.AbstractIL.Diagnostics open FSharp.Compiler.AbstractIL.IL -open FSharp.Compiler.Infos open FSharp.Compiler.AccessibilityLogic open FSharp.Compiler.AttributeChecking +open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.InfoReader +open FSharp.Compiler.Infos +open FSharp.Compiler.Features +open FSharp.Compiler.Lib open FSharp.Compiler.PrettyNaming -open System.Collections.Generic +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.Text #if !NO_EXTENSIONTYPING open FSharp.Compiler.ExtensionTyping @@ -34,6 +41,7 @@ type NameResolver(g: TcGlobals, amap: Import.ImportMap, infoReader: InfoReader, instantiationGenerator: (range -> Typars -> TypeInst)) = + /// Used to transform typars into new inference typars // instantiationGenerator is a function to help us create the // type parameters by copying them from type parameter specifications read @@ -48,6 +56,7 @@ type NameResolver(g: TcGlobals, member nr.g = g member nr.amap = amap member nr.InfoReader = infoReader + member nr.languageSupportsNameOf = g.langVersion.SupportsFeature LanguageFeature.NameOf //------------------------------------------------------------------------- // Helpers for unionconstrs and recdfields @@ -77,7 +86,6 @@ let ActivePatternElemsOfValRef vref = | Some apinfo -> apinfo.ActiveTags |> List.mapi (fun i _ -> APElemRef(apinfo, vref, i)) | None -> [] - /// Try to make a reference to a value in a module. // // mkNestedValRef may fail if the assembly load set is @@ -124,10 +132,8 @@ let (|AbbrevOrAppTy|_|) (ty: TType) = type ArgumentContainer = /// The named argument is an argument of a method | Method of MethInfo - /// The named argument is a static parameter to a provided type or a parameter to an F# exception constructor + /// The named argument is a static parameter to a provided type. | Type of TyconRef - /// The named argument is a static parameter to a union case constructor - | UnionCase of UnionCaseInfo // Note: Active patterns are encoded like this: // let (|A|B|) x = if x < 0 then A else B // A and B are reported as results using 'Item.ActivePatternResult' @@ -141,7 +147,7 @@ type Item = | Value of ValRef /// Represents the resolution of a name to an F# union case. - | UnionCase of UnionCaseInfo * bool + | UnionCase of UnionCaseInfo * hasRequireQualifiedAccessAttr: bool /// Represents the resolution of a name to an F# active pattern result. | ActivePatternResult of ActivePatternInfo * TType * int * range @@ -152,9 +158,12 @@ type Item = /// Represents the resolution of a name to an F# exception definition. | ExnCase of TyconRef - /// Represents the resolution of a name to an F# record field. + /// Represents the resolution of a name to an F# record or exception field. | RecdField of RecdFieldInfo + /// Represents the resolution of a name to a union case field. + | UnionCaseField of UnionCaseInfo * fieldIndex: int + /// Represents the resolution of a name to a field of an anonymous record type. | AnonRecdField of AnonRecdTypeInfo * TTypes * int * range @@ -200,7 +209,7 @@ type Item = | TypeVar of string * Typar /// Represents the resolution of a name to a module or namespace - | ModuleOrNamespaces of Tast.ModuleOrNamespaceRef list + | ModuleOrNamespaces of ModuleOrNamespaceRef list /// Represents the resolution of a name to an operator | ImplicitOp of Ident * TraitConstraintSln option ref @@ -229,6 +238,7 @@ type Item = | Item.UnionCase(uinfo, _) -> DecompileOpName uinfo.UnionCase.DisplayName | Item.ExnCase tcref -> tcref.LogicalName | Item.RecdField rfinfo -> DecompileOpName rfinfo.RecdField.Name + | Item.UnionCaseField (uci, fieldIndex) -> uci.UnionCase.GetFieldByIndex(fieldIndex).Name | Item.AnonRecdField (anonInfo, _tys, i, _m) -> anonInfo.SortedNames.[i] | Item.NewDef id -> id.idText | Item.ILField finfo -> finfo.FieldName @@ -313,6 +323,7 @@ type FullyQualifiedFlag = | OpenQualified +type UnqualifiedItems = LayeredMap [] /// The environment of information used to resolve names @@ -320,8 +331,8 @@ type NameResolutionEnv = { /// Display environment information for output eDisplayEnv: DisplayEnv - /// Values and Data Tags available by unqualified name - eUnqualifiedItems: LayeredMap + /// Values, functions, methods and other items available by unqualified name + eUnqualifiedItems: UnqualifiedItems /// Data Tags and Active Pattern Tags available by unqualified name ePatItems: NameMap @@ -339,15 +350,15 @@ type NameResolutionEnv = /// open Collections <--- give a warning /// let v = new Collections.Generic.List() <--- give a warning" - eModulesAndNamespaces: NameMultiMap + eModulesAndNamespaces: NameMultiMap /// Fully qualified modules and namespaces. 'open' does not change this. - eFullyQualifiedModulesAndNamespaces: NameMultiMap + eFullyQualifiedModulesAndNamespaces: NameMultiMap /// RecdField labels in scope. RecdField labels are those where type are inferred /// by label rather than by known type annotation. /// Bools indicate if from a record, where no warning is given on indeterminate lookup - eFieldLabels: NameMultiMap + eFieldLabels: NameMultiMap /// Tycons indexed by the various names that may be used to access them, e.g. /// "List" --> multiple TyconRef's for the various tycons accessible by this name. @@ -416,6 +427,12 @@ type NameResolutionEnv = // Helpers to do with extension members //------------------------------------------------------------------------- +/// Indicates if we only need one result or all possible results from a resolution. +[] +type ResultCollectionSettings = + | AllResults + | AtMostOneResult + /// Allocate the next extension method priority. This is an incrementing sequence of integers /// during type checking. let NextExtensionMethodPriority() = uint64 (newStamp()) @@ -424,7 +441,7 @@ let NextExtensionMethodPriority() = uint64 (newStamp()) let private GetCSharpStyleIndexedExtensionMembersForTyconRef (amap: Import.ImportMap) m (tcrefOfStaticClass: TyconRef) = let g = amap.g // Type must be non-generic and have 'Extension' attribute - if isNil(tcrefOfStaticClass.Typars(m)) && TyconRefHasAttribute g m g.attrib_ExtensionAttribute tcrefOfStaticClass then + if isNil(tcrefOfStaticClass.Typars m) && TyconRefHasAttribute g m g.attrib_ExtensionAttribute tcrefOfStaticClass then let pri = NextExtensionMethodPriority() let ty = generalizedTyconRef tcrefOfStaticClass @@ -487,6 +504,130 @@ let private GetCSharpStyleIndexedExtensionMembersForTyconRef (amap: Import.Impor [] +/// Query the declared properties of a type (including inherited properties) +let IntrinsicPropInfosOfTypeInScope (infoReader: InfoReader) optFilter ad findFlag m ty = + let g = infoReader.g + let amap = infoReader.amap + let pinfos = GetIntrinsicPropInfoSetsOfType infoReader optFilter ad AllowMultiIntfInstantiations.Yes findFlag m ty + let pinfos = pinfos |> ExcludeHiddenOfPropInfos g amap m + pinfos + +/// Select from a list of extension properties +let SelectPropInfosFromExtMembers (infoReader: InfoReader) ad optFilter declaringTy m extMemInfos = + let g = infoReader.g + let amap = infoReader.amap + // NOTE: multiple "open"'s push multiple duplicate values into eIndexedExtensionMembers, hence use a set. + let seen = HashSet(ExtensionMember.Comparer g) + let propCollector = new PropertyCollector(g, amap, m, declaringTy, optFilter, ad) + for emem in extMemInfos do + if seen.Add emem then + match emem with + | FSExtMem (vref, _pri) -> + match vref.MemberInfo with + | None -> () + | Some membInfo -> propCollector.Collect(membInfo, vref) + | ILExtMem _ -> + // No extension properties coming from .NET + () + propCollector.Close() + +/// Query the available extension properties of a type (including extension properties for inherited types) +let ExtensionPropInfosOfTypeInScope collectionSettings (infoReader:InfoReader) (nenv: NameResolutionEnv) optFilter ad m ty = + let g = infoReader.g + + let extMemsDangling = SelectPropInfosFromExtMembers infoReader ad optFilter ty m nenv.eUnindexedExtensionMembers + + if collectionSettings = ResultCollectionSettings.AtMostOneResult && not (isNil extMemsDangling) then + extMemsDangling + else + let extMemsFromHierarchy = + infoReader.GetEntireTypeHierarchy(AllowMultiIntfInstantiations.Yes, m, ty) + |> List.collect (fun ty -> + match tryTcrefOfAppTy g ty with + | ValueSome tcref -> + let extMemInfos = nenv.eIndexedExtensionMembers.Find tcref + SelectPropInfosFromExtMembers infoReader ad optFilter ty m extMemInfos + | _ -> []) + + extMemsDangling @ extMemsFromHierarchy + +/// Get all the available properties of a type (both intrinsic and extension) +let AllPropInfosOfTypeInScope collectionSettings infoReader nenv optFilter ad findFlag m ty = + IntrinsicPropInfosOfTypeInScope infoReader optFilter ad findFlag m ty + @ ExtensionPropInfosOfTypeInScope collectionSettings infoReader nenv optFilter ad m ty + +/// Get the available methods of a type (both declared and inherited) +let IntrinsicMethInfosOfType (infoReader: InfoReader) optFilter ad allowMultiIntfInst findFlag m ty = + let g = infoReader.g + let amap = infoReader.amap + let minfos = GetIntrinsicMethInfoSetsOfType infoReader optFilter ad allowMultiIntfInst findFlag m ty + let minfos = minfos |> ExcludeHiddenOfMethInfos g amap m + minfos + +let TrySelectExtensionMethInfoOfILExtMem m amap apparentTy (actualParent, minfo, pri) = + match minfo with + | ILMeth(_,ilminfo,_) -> + MethInfo.CreateILExtensionMeth (amap, m, apparentTy, actualParent, Some pri, ilminfo.RawMetadata) |> Some + // F#-defined IL-style extension methods are not seen as extension methods in F# code + | FSMeth(g,_,vref,_) -> + FSMeth(g, apparentTy, vref, Some pri) |> Some +#if !NO_EXTENSIONTYPING + // // Provided extension methods are not yet supported + | ProvidedMeth(amap,providedMeth,_,m) -> + ProvidedMeth(amap, providedMeth, Some pri,m) |> Some +#endif + | DefaultStructCtor _ -> + None + +/// Select from a list of extension methods +let SelectMethInfosFromExtMembers (infoReader: InfoReader) optFilter apparentTy m extMemInfos = + let g = infoReader.g + // NOTE: multiple "open"'s push multiple duplicate values into eIndexedExtensionMembers + let seen = HashSet(ExtensionMember.Comparer g) + [ + for emem in extMemInfos do + if seen.Add emem then + match emem with + | FSExtMem (vref, pri) -> + match vref.MemberInfo with + | None -> () + | Some membInfo -> + match TrySelectMemberVal g optFilter apparentTy (Some pri) membInfo vref with + | Some m -> yield m + | _ -> () + | ILExtMem (actualParent, minfo, pri) when (match optFilter with None -> true | Some nm -> nm = minfo.LogicalName) -> + // Make a reference to the type containing the extension members + match TrySelectExtensionMethInfoOfILExtMem m infoReader.amap apparentTy (actualParent, minfo, pri) with + | Some minfo -> yield minfo + | None -> () + | _ -> () + ] + +/// Query the available extension properties of a methods (including extension methods for inherited types) +let ExtensionMethInfosOfTypeInScope (collectionSettings: ResultCollectionSettings) (infoReader: InfoReader) (nenv: NameResolutionEnv) optFilter m ty = + let extMemsDangling = SelectMethInfosFromExtMembers infoReader optFilter ty m nenv.eUnindexedExtensionMembers + if collectionSettings = ResultCollectionSettings.AtMostOneResult && not (isNil extMemsDangling) then + extMemsDangling + else + let extMemsFromHierarchy = + infoReader.GetEntireTypeHierarchy(AllowMultiIntfInstantiations.Yes, m, ty) + |> List.collect (fun ty -> + let g = infoReader.g + match tryTcrefOfAppTy g ty with + | ValueSome tcref -> + let extValRefs = nenv.eIndexedExtensionMembers.Find tcref + SelectMethInfosFromExtMembers infoReader optFilter ty m extValRefs + | _ -> []) + extMemsDangling @ extMemsFromHierarchy + +/// Get all the available methods of a type (both intrinsic and extension) +let AllMethInfosOfTypeInScope collectionSettings infoReader nenv optFilter ad findFlag m ty = + let intrinsic = IntrinsicMethInfosOfType infoReader optFilter ad AllowMultiIntfInstantiations.Yes findFlag m ty + if collectionSettings = ResultCollectionSettings.AtMostOneResult && not (isNil intrinsic) then + intrinsic + else + intrinsic @ ExtensionMethInfosOfTypeInScope collectionSettings infoReader nenv optFilter m ty + //------------------------------------------------------------------------- // Helpers to do with building environments //------------------------------------------------------------------------- @@ -503,7 +644,7 @@ type BulkAdd = Yes | No /// bulkAddMode: true when adding the values from the 'open' of a namespace /// or module, when we collapse the value table down to a dictionary. -let AddValRefsToItems (bulkAddMode: BulkAdd) (eUnqualifiedItems: LayeredMap<_, _>) (vrefs: ValRef[]) = +let AddValRefsToItems (bulkAddMode: BulkAdd) (eUnqualifiedItems: UnqualifiedItems) (vrefs: ValRef[]) = // Object model members are not added to the unqualified name resolution environment let vrefs = vrefs |> Array.filter (fun vref -> not vref.IsMember) @@ -525,11 +666,11 @@ let AddValRefToExtensionMembers pri (eIndexedExtensionMembers: TyconRefMultiMap< eIndexedExtensionMembers -/// This entrypoint is used to add some extra items to the environment for Visual Studio, e.g. static members +/// This entry point is used to add some extra items to the environment for Visual Studio, e.g. static members let AddFakeNamedValRefToNameEnv nm nenv vref = {nenv with eUnqualifiedItems = nenv.eUnqualifiedItems.Add (nm, Item.Value vref) } -/// This entrypoint is used to add some extra items to the environment for Visual Studio, e.g. record members +/// This entry point is used to add some extra items to the environment for Visual Studio, e.g. record members let AddFakeNameToNameEnv nm nenv item = {nenv with eUnqualifiedItems = nenv.eUnqualifiedItems.Add (nm, item) } @@ -588,7 +729,7 @@ let AddTyconsByDemangledNameAndArity (bulkAddMode: BulkAdd) (tcrefs: TyconRef[]) if tcrefs.Length = 0 then tab else let entries = tcrefs - |> Array.map (fun tcref -> KeyTyconByDemangledNameAndArity tcref.LogicalName tcref.TyparsNoRange tcref) + |> Array.map (fun tcref -> Construct.KeyTyconByDemangledNameAndArity tcref.LogicalName tcref.TyparsNoRange tcref) match bulkAddMode with | BulkAdd.Yes -> tab.AddAndMarkAsCollapsible entries @@ -599,7 +740,7 @@ let AddTyconByAccessNames bulkAddMode (tcrefs: TyconRef[]) (tab: LayeredMultiMap if tcrefs.Length = 0 then tab else let entries = tcrefs - |> Array.collect (fun tcref -> KeyTyconByAccessNames tcref.LogicalName tcref) + |> Array.collect (fun tcref -> Construct.KeyTyconByAccessNames tcref.LogicalName tcref) match bulkAddMode with | BulkAdd.Yes -> tab.AddAndMarkAsCollapsible entries @@ -615,7 +756,7 @@ let AddUnionCases1 (tab: Map<_, _>) (ucrefs: UnionCaseRef list) = acc.Add (ucref.CaseName, item)) /// Add a set of union cases to the corresponding sub-table of the environment -let AddUnionCases2 bulkAddMode (eUnqualifiedItems: LayeredMap<_, _>) (ucrefs: UnionCaseRef list) = +let AddUnionCases2 bulkAddMode (eUnqualifiedItems: UnqualifiedItems) (ucrefs: UnionCaseRef list) = match bulkAddMode with | BulkAdd.Yes -> let items = @@ -629,8 +770,46 @@ let AddUnionCases2 bulkAddMode (eUnqualifiedItems: LayeredMap<_, _>) (ucrefs: Un let item = Item.UnionCase(GeneralizeUnionCaseRef ucref, false) acc.Add (ucref.CaseName, item)) +let AddStaticContentOfTyconRefToNameEnv (g:TcGlobals) (amap: Import.ImportMap) ad m (nenv: NameResolutionEnv) (tcref:TyconRef) = + // If OpenStaticClasses is not enabled then don't do this + if amap.g.langVersion.SupportsFeature LanguageFeature.OpenStaticClasses then + let ty = generalizedTyconRef tcref + let infoReader = InfoReader(g,amap) + let items = + [| let methGroups = + AllMethInfosOfTypeInScope ResultCollectionSettings.AllResults infoReader nenv None ad PreferOverrides m ty + |> List.groupBy (fun m -> m.LogicalName) + + for (methName, methGroup) in methGroups do + let methGroup = methGroup |> List.filter (fun m -> not m.IsInstance && not m.IsClassConstructor) + if not methGroup.IsEmpty then + yield KeyValuePair(methName, Item.MethodGroup(methName, methGroup, None)) + + let propInfos = + AllPropInfosOfTypeInScope ResultCollectionSettings.AllResults infoReader nenv None ad PreferOverrides m ty + |> List.groupBy (fun m -> m.PropertyName) + + for (propName, propInfos) in propInfos do + let propInfos = propInfos |> List.filter (fun m -> m.IsStatic) + for propInfo in propInfos do + yield KeyValuePair(propName , Item.Property(propName,[propInfo])) + + let fields = + infoReader.GetILFieldInfosOfType(None, ad, m, ty) + |> List.groupBy (fun f -> f.FieldName) + + for (fieldName, fieldInfos) in fields do + let fieldInfos = fieldInfos |> List.filter (fun fi -> fi.IsStatic) + for fieldInfo in fieldInfos do + yield KeyValuePair(fieldName, Item.ILField(fieldInfo)) + |] + + { nenv with eUnqualifiedItems = nenv.eUnqualifiedItems.AddAndMarkAsCollapsible items } + else + nenv + /// Add any implied contents of a type definition to the environment. -let private AddPartsOfTyconRefToNameEnv bulkAddMode ownDefinition (g: TcGlobals) amap m nenv (tcref: TyconRef) = +let private AddPartsOfTyconRefToNameEnv bulkAddMode ownDefinition (g: TcGlobals) amap ad m nenv (tcref: TyconRef) = let isIL = tcref.IsILTycon let ucrefs = if isIL then [] else tcref.UnionCasesAsList |> List.map tcref.MakeNestedUnionCaseRef @@ -674,14 +853,18 @@ let private AddPartsOfTyconRefToNameEnv bulkAddMode ownDefinition (g: TcGlobals) if mayHaveConstruction then tab.LinearTryModifyThenLaterFlatten (tcref.DisplayName, (fun prev -> match prev with - | Some (Item.UnqualifiedType tcrefs) -> Item.UnqualifiedType (tcref::tcrefs) + | Some (Item.UnqualifiedType tcrefs) -> Item.UnqualifiedType (tcref :: tcrefs) | _ -> Item.UnqualifiedType [tcref])) else tab - if isILOrRequiredQualifiedAccess || List.isEmpty ucrefs then - tab - else - AddUnionCases2 bulkAddMode tab ucrefs + + let tab = + if isILOrRequiredQualifiedAccess || List.isEmpty ucrefs then + tab + else + AddUnionCases2 bulkAddMode tab ucrefs + + tab let ePatItems = if isILOrRequiredQualifiedAccess || List.isEmpty ucrefs then @@ -689,17 +872,26 @@ let private AddPartsOfTyconRefToNameEnv bulkAddMode ownDefinition (g: TcGlobals) else AddUnionCases1 nenv.ePatItems ucrefs - { nenv with - eFieldLabels = eFieldLabels - eUnqualifiedItems = eUnqualifiedItems - ePatItems = ePatItems - eIndexedExtensionMembers = eIndexedExtensionMembers - eUnindexedExtensionMembers = eUnindexedExtensionMembers } + let nenv = + { nenv with + eFieldLabels = eFieldLabels + eUnqualifiedItems = eUnqualifiedItems + ePatItems = ePatItems + eIndexedExtensionMembers = eIndexedExtensionMembers + eUnindexedExtensionMembers = eUnindexedExtensionMembers } + + let nenv = + if TryFindFSharpBoolAttribute g g.attrib_AutoOpenAttribute tcref.Attribs = Some true && isStaticClass g tcref then + AddStaticContentOfTyconRefToNameEnv g amap ad m nenv tcref + else + nenv + + nenv /// Add a set of type definitions to the name resolution environment -let AddTyconRefsToNameEnv bulkAddMode ownDefinition g amap m root nenv tcrefs = +let AddTyconRefsToNameEnv bulkAddMode ownDefinition g amap ad m root nenv tcrefs = if isNil tcrefs then nenv else - let env = List.fold (AddPartsOfTyconRefToNameEnv bulkAddMode ownDefinition g amap m) nenv tcrefs + let env = List.fold (AddPartsOfTyconRefToNameEnv bulkAddMode ownDefinition g amap ad m) nenv tcrefs // Add most of the contents of the tycons en-masse, then flatten the tables if we're opening a module or namespace let tcrefs = Array.ofList tcrefs { env with @@ -796,9 +988,9 @@ and AddModuleOrNamespaceContentsToNameEnv (g: TcGlobals) amap (ad: AccessorDomai mty.TypeAndExceptionDefinitions |> List.choose (fun tycon -> let tcref = modref.NestedTyconRef tycon - if IsEntityAccessible amap m ad tcref then Some(tcref) else None) + if IsEntityAccessible amap m ad tcref then Some tcref else None) - let nenv = (nenv, tcrefs) ||> AddTyconRefsToNameEnv BulkAdd.Yes false g amap m false + let nenv = (nenv, tcrefs) ||> AddTyconRefsToNameEnv BulkAdd.Yes false g amap ad m false let vrefs = mty.AllValsAndMembers.ToList() |> List.choose (fun x -> if IsAccessible ad x.Accessibility then TryMkValRefInModRef modref x else None) @@ -816,8 +1008,14 @@ and AddModuleOrNamespaceContentsToNameEnv (g: TcGlobals) amap (ad: AccessorDomai // open M1 // // The list contains [M1b; M1a] -and AddModulesAndNamespacesContentsToNameEnv g amap ad m root nenv modrefs = - (modrefs, nenv) ||> List.foldBack (fun modref acc -> AddModuleOrNamespaceContentsToNameEnv g amap ad m root acc modref) +and AddEntitiesContentsToNameEnv g amap ad m root nenv modrefs = + (modrefs, nenv) ||> List.foldBack (fun modref acc -> AddEntityContentsToNameEnv g amap ad m root acc modref) + +and AddEntityContentsToNameEnv g amap ad m root nenv (modref: EntityRef) = + if modref.IsModuleOrNamespace then + AddModuleOrNamespaceContentsToNameEnv g amap ad m root nenv modref + else + AddStaticContentOfTyconRefToNameEnv g amap ad m nenv modref /// Add a single modules or namespace to the name resolution environment let AddModuleOrNamespaceRefToNameEnv g amap m root ad nenv (modref: EntityRef) = @@ -897,10 +1095,8 @@ let AddResults res1 res2 = | Exception _, Result l -> Result l | Result x, Exception _ -> Result x // If we have error messages for the same symbol, then we can merge suggestions. - | Exception (UndefinedName(n1, f, id1, suggestions1)), Exception (UndefinedName(n2, _, id2, suggestions2)) when n1 = n2 && id1.idText = id2.idText && id1.idRange = id2.idRange -> - let suggestions = HashSet(suggestions1()) - suggestions.UnionWith(suggestions2()) - Exception(UndefinedName(n1, f, id1, fun () -> suggestions)) + | Exception (UndefinedName(n1, f, id1, suggestions1)), Exception (UndefinedName(n2, _, id2, suggestions2)) when n1 = n2 && id1.idText = id2.idText && Range.equals id1.idRange id2.idRange -> + Exception(UndefinedName(n1, f, id1, fun addToBuffer -> suggestions1 addToBuffer; suggestions2 addToBuffer)) // This prefers error messages coming from deeper failing long identifier paths | Exception (UndefinedName(n1, _, _, _) as e1), Exception (UndefinedName(n2, _, _, _) as e2) -> if n1 < n2 then Exception e2 else Exception e1 @@ -911,18 +1107,13 @@ let AddResults res1 res2 = let NoResultsOrUsefulErrors = Result [] -/// Indicates if we only need one result or all possible results from a resolution. -[] -type ResultCollectionSettings = -| AllResults -| AtMostOneResult - let rec CollectResults f = function | [] -> NoResultsOrUsefulErrors | [h] -> OneResult (f h) | h :: t -> AddResults (OneResult (f h)) (CollectResults f t) -let rec CollectAtMostOneResult f = function +let rec CollectAtMostOneResult f inputs = + match inputs with | [] -> NoResultsOrUsefulErrors | [h] -> OneResult (f h) | h :: t -> @@ -1098,7 +1289,7 @@ let AddEntityForProvidedType (amap: Import.ImportMap, modref: ModuleOrNamespaceR let importProvidedType t = Import.ImportProvidedType amap m t let isSuppressRelocate = amap.g.isInteractive || st.PUntaint((fun st -> st.IsSuppressRelocate), m) let tycon = Construct.NewProvidedTycon(resolutionEnvironment, st, importProvidedType, isSuppressRelocate, m) - modref.ModuleOrNamespaceType.AddProvidedTypeEntity(tycon) + modref.ModuleOrNamespaceType.AddProvidedTypeEntity tycon let tcref = modref.NestedTyconRef tycon System.Diagnostics.Debug.Assert(modref.TryDeref.IsSome) tcref @@ -1126,7 +1317,7 @@ let ResolveProvidedTypeNameInEntity (amap, m, typeName, modref: ModuleOrNamespac dprintfn "resolving name '%s' in TProvidedTypeExtensionPoint '%s'" typeName (sty.PUntaint((fun sty -> sty.FullName), m)) #endif - match sty.PApply((fun sty -> sty.GetNestedType(typeName)), m) with + match sty.PApply((fun sty -> sty.GetNestedType typeName), m) with | Tainted.Null -> //if staticResInfo.NumStaticArgs > 0 then // error(Error(FSComp.SR.etNestedProvidedTypesDoNotTakeStaticArgumentsOrGenericParameters(), m)) @@ -1172,7 +1363,7 @@ let MakeNestedType (ncenv: NameResolver) (tinst: TType list) m (tcrefNested: Tyc /// Get all the accessible nested types of an existing type. let GetNestedTypesOfType (ad, ncenv: NameResolver, optFilter, staticResInfo, checkForGenerated, m) ty = let g = ncenv.g - ncenv.InfoReader.GetPrimaryTypeHierachy(AllowMultiIntfInstantiations.Yes, m, ty) |> List.collect (fun ty -> + ncenv.InfoReader.GetPrimaryTypeHierarchy(AllowMultiIntfInstantiations.Yes, m, ty) |> List.collect (fun ty -> match ty with | AppTy g (tcref, tinst) -> let tycon = tcref.Deref @@ -1251,17 +1442,18 @@ type OpenDeclaration = IsOwnNamespace = isOwnNamespace } type FormatStringCheckContext = - { Source: string + { SourceText: ISourceText LineStartPositions: int[] } /// An abstract type for reporting the results of name resolution and type checking. type ITypecheckResultsSink = abstract NotifyEnvWithScope: range * NameResolutionEnv * AccessorDomain -> unit - abstract NotifyExprHasType: pos * TType * Tastops.DisplayEnv * NameResolutionEnv * AccessorDomain * range -> unit - abstract NotifyNameResolution: pos * Item * Item * TyparInst * ItemOccurence * Tastops.DisplayEnv * NameResolutionEnv * AccessorDomain * range * bool -> unit + abstract NotifyExprHasType: TType * NameResolutionEnv * AccessorDomain * range -> unit + abstract NotifyNameResolution: pos * item: Item * TyparInst * ItemOccurence * NameResolutionEnv * AccessorDomain * range * replace: bool -> unit + abstract NotifyMethodGroupNameResolution : pos * item: Item * itemMethodGroup: Item * TyparInst * ItemOccurence * NameResolutionEnv * AccessorDomain * range * replace: bool -> unit abstract NotifyFormatSpecifierLocation: range * int -> unit abstract NotifyOpenDeclaration: OpenDeclaration -> unit - abstract CurrentSource: string option + abstract CurrentSourceText: ISourceText option abstract FormatStringCheckContext: FormatStringCheckContext option let (|ValRefOfProp|_|) (pi: PropInfo) = pi.ArbitraryValRef @@ -1270,47 +1462,52 @@ let (|ValRefOfEvent|_|) (evt: EventInfo) = evt.ArbitraryValRef let rec (|RecordFieldUse|_|) (item: Item) = match item with - | Item.RecdField(RecdFieldInfo(_, RFRef(tcref, name))) -> Some (name, tcref) - | Item.SetterArg(_, RecordFieldUse(f)) -> Some(f) + | Item.RecdField(RecdFieldInfo(_, RecdFieldRef(tcref, name))) -> Some (name, tcref) + | Item.SetterArg(_, RecordFieldUse f) -> Some f + | _ -> None + +let (|UnionCaseFieldUse|_|) (item: Item) = + match item with + | Item.UnionCaseField (uci, fieldIndex) -> Some (fieldIndex, uci.UnionCaseRef) | _ -> None let rec (|ILFieldUse|_|) (item: Item) = match item with - | Item.ILField(finfo) -> Some(finfo) - | Item.SetterArg(_, ILFieldUse(f)) -> Some(f) + | Item.ILField finfo -> Some finfo + | Item.SetterArg(_, ILFieldUse f) -> Some f | _ -> None let rec (|PropertyUse|_|) (item: Item) = match item with - | Item.Property(_, pinfo::_) -> Some(pinfo) - | Item.SetterArg(_, PropertyUse(pinfo)) -> Some(pinfo) + | Item.Property(_, pinfo :: _) -> Some pinfo + | Item.SetterArg(_, PropertyUse pinfo) -> Some pinfo | _ -> None let rec (|FSharpPropertyUse|_|) (item: Item) = match item with - | Item.Property(_, [ValRefOfProp vref]) -> Some(vref) - | Item.SetterArg(_, FSharpPropertyUse(propDef)) -> Some(propDef) + | Item.Property(_, [ValRefOfProp vref]) -> Some vref + | Item.SetterArg(_, FSharpPropertyUse propDef) -> Some propDef | _ -> None let (|MethodUse|_|) (item: Item) = match item with - | Item.MethodGroup(_, [minfo], _) -> Some(minfo) + | Item.MethodGroup(_, [minfo], _) -> Some minfo | _ -> None let (|FSharpMethodUse|_|) (item: Item) = match item with - | Item.MethodGroup(_, [ValRefOfMeth vref], _) -> Some(vref) - | Item.Value(vref) when vref.IsMember -> Some(vref) + | Item.MethodGroup(_, [ValRefOfMeth vref], _) -> Some vref + | Item.Value vref when vref.IsMember -> Some vref | _ -> None let (|EntityUse|_|) (item: Item) = match item with - | Item.UnqualifiedType (tcref:: _) -> Some tcref - | Item.ExnCase(tcref) -> Some tcref + | Item.UnqualifiedType (tcref :: _) -> Some tcref + | Item.ExnCase tcref -> Some tcref | Item.Types(_, [AbbrevOrAppTy tcref]) | Item.DelegateCtor(AbbrevOrAppTy tcref) | Item.FakeInterfaceCtor(AbbrevOrAppTy tcref) -> Some tcref - | Item.CtorGroup(_, ctor::_) -> + | Item.CtorGroup(_, ctor :: _) -> match ctor.ApparentEnclosingType with | AbbrevOrAppTy tcref -> Some tcref | _ -> None @@ -1318,7 +1515,7 @@ let (|EntityUse|_|) (item: Item) = let (|EventUse|_|) (item: Item) = match item with - | Item.Event(einfo) -> Some einfo + | Item.Event einfo -> Some einfo | _ -> None let (|FSharpEventUse|_|) (item: Item) = @@ -1353,8 +1550,10 @@ let tyconRefDefnEq g (eref1: EntityRef) (eref2: EntityRef) = tyconRefEq g eref1 eref2 || // Signature items considered equal to implementation items - eref1.DefinitionRange <> Range.rangeStartup && eref1.DefinitionRange <> Range.range0 && eref1.DefinitionRange <> Range.rangeCmdArgs && - (eref1.DefinitionRange = eref2.DefinitionRange || eref1.SigRange = eref2.SigRange) && + not (Range.equals eref1.DefinitionRange Range.rangeStartup) && + not (Range.equals eref1.DefinitionRange Range.range0) && + not (Range.equals eref1.DefinitionRange Range.rangeCmdArgs) && + (Range.equals eref1.DefinitionRange eref2.DefinitionRange || Range.equals eref1.SigRange eref2.SigRange) && eref1.LogicalName = eref2.LogicalName let valRefDefnHash (_g: TcGlobals) (vref1: ValRef) = @@ -1364,8 +1563,10 @@ let valRefDefnEq g (vref1: ValRef) (vref2: ValRef) = valRefEq g vref1 vref2 || // Signature items considered equal to implementation items - vref1.DefinitionRange <> Range.rangeStartup && vref1.DefinitionRange <> Range.range0 && vref1.DefinitionRange <> Range.rangeCmdArgs && - (vref1.DefinitionRange = vref2.DefinitionRange || vref1.SigRange = vref2.SigRange) && + not (Range.equals vref1.DefinitionRange Range.rangeStartup) && + not (Range.equals vref1.DefinitionRange Range.range0) && + not (Range.equals vref1.DefinitionRange Range.rangeCmdArgs) && + (Range.equals vref1.DefinitionRange vref2.DefinitionRange || Range.equals vref1.SigRange vref2.SigRange) && vref1.LogicalName = vref2.LogicalName let unionCaseRefDefnEq g (uc1: UnionCaseRef) (uc2: UnionCaseRef) = @@ -1384,7 +1585,7 @@ let ItemsAreEffectivelyEqual g orig other = | TType_var tp1, TType_var tp2 -> not tp1.IsCompilerGenerated && not tp1.IsFromError && not tp2.IsCompilerGenerated && not tp2.IsFromError && - tp1.Range = tp2.Range + Range.equals tp1.Range tp2.Range | AbbrevOrAppTy tcref1, AbbrevOrAppTy tcref2 -> tyconRefDefnEq g tcref1 tcref2 | _ -> false) @@ -1393,7 +1594,7 @@ let ItemsAreEffectivelyEqual g orig other = valRefDefnEq g vref1 vref2 | ActivePatternCaseUse (range1, range1i, idx1), ActivePatternCaseUse (range2, range2i, idx2) -> - (idx1 = idx2) && (range1 = range2 || range1i = range2i) + (idx1 = idx2) && (Range.equals range1 range2 || Range.equals range1i range2i) | MethodUse minfo1, MethodUse minfo2 -> MethInfo.MethInfosUseIdenticalDefinitions minfo1 minfo2 || @@ -1402,7 +1603,7 @@ let ItemsAreEffectivelyEqual g orig other = | Some vref1, Some vref2 -> valRefDefnEq g vref1 vref2 | _ -> false - | PropertyUse(pinfo1), PropertyUse(pinfo2) -> + | PropertyUse pinfo1, PropertyUse pinfo2 -> PropInfo.PropInfosUseIdenticalDefinitions pinfo1 pinfo2 || // Allow for equality up to signature matching match pinfo1.ArbitraryValRef, pinfo2.ArbitraryValRef with @@ -1410,12 +1611,12 @@ let ItemsAreEffectivelyEqual g orig other = | _ -> false | Item.ArgName (id1, _, _), Item.ArgName (id2, _, _) -> - (id1.idText = id2.idText && id1.idRange = id2.idRange) + (id1.idText = id2.idText && Range.equals id1.idRange id2.idRange) | (Item.ArgName (id, _, _), ValUse vref) | (ValUse vref, Item.ArgName (id, _, _)) -> - ((id.idRange = vref.DefinitionRange || id.idRange = vref.SigRange) && id.idText = vref.DisplayName) + ((Range.equals id.idRange vref.DefinitionRange || Range.equals id.idRange vref.SigRange) && id.idText = vref.DisplayName) - | Item.AnonRecdField(anon1, _, i1, _), Item.AnonRecdField(anon2, _, i2, _) -> Tastops.anonInfoEquiv anon1 anon2 && i1 = i2 + | Item.AnonRecdField(anon1, _, i1, _), Item.AnonRecdField(anon2, _, i2, _) -> anonInfoEquiv anon1 anon2 && i1 = i2 | ILFieldUse f1, ILFieldUse f2 -> ILFieldInfo.ILFieldInfosUseIdenticalDefinitions f1 f2 @@ -1426,8 +1627,11 @@ let ItemsAreEffectivelyEqual g orig other = | RecordFieldUse(name1, tcref1), RecordFieldUse(name2, tcref2) -> name1 = name2 && tyconRefDefnEq g tcref1 tcref2 + | UnionCaseFieldUse(fieldIndex1, ucref1), UnionCaseFieldUse(fieldIndex2, ucref2) -> + unionCaseRefDefnEq g ucref1 ucref2 && fieldIndex1 = fieldIndex2 + | EventUse evt1, EventUse evt2 -> - EventInfo.EventInfosUseIdenticalDefintions evt1 evt2 || + EventInfo.EventInfosUseIdenticalDefinitions evt1 evt2 || // Allow for equality up to signature matching match evt1.ArbitraryValRef, evt2.ArbitraryValRef with | Some vref1, Some vref2 -> valRefDefnEq g vref1 vref2 @@ -1451,31 +1655,32 @@ let ItemsAreEffectivelyEqualHash (g: TcGlobals) orig = | ILFieldUse ilfinfo -> ilfinfo.ComputeHashCode() | UnionCaseUse ucase -> hash ucase.CaseName | RecordFieldUse (name, _) -> hash name + | UnionCaseFieldUse (fieldIndex, case) -> hash (case.CaseName, fieldIndex) | EventUse einfo -> einfo.ComputeHashCode() | Item.ModuleOrNamespaces (mref :: _) -> hash mref.DefinitionRange | _ -> 389329 [] -type CapturedNameResolution(p: pos, i: Item, tpinst, io: ItemOccurence, de: DisplayEnv, nre: NameResolutionEnv, ad: AccessorDomain, m: range) = - member this.Pos = p +type CapturedNameResolution(i: Item, tpinst, io: ItemOccurence, nre: NameResolutionEnv, ad: AccessorDomain, m: range) = + member this.Pos = m.End member this.Item = i member this.ItemWithInst = ({ Item = i; TyparInst = tpinst } : ItemWithInst) member this.ItemOccurence = io - member this.DisplayEnv = de + member this.DisplayEnv = nre.DisplayEnv member this.NameResolutionEnv = nre member this.AccessorDomain = ad member this.Range = m member this.DebugToString() = - sprintf "%A: %+A" (p.Line, p.Column) i + sprintf "%A: %+A" (this.Pos.Line, this.Pos.Column) i /// Represents container for all name resolutions that were met so far when typechecking some particular file type TcResolutions (capturedEnvs: ResizeArray, - capturedExprTypes: ResizeArray, + capturedExprTypes: ResizeArray, capturedNameResolutions: ResizeArray, capturedMethodGroupResolutions: ResizeArray) = - static let empty = TcResolutions(ResizeArray(0), ResizeArray(0), ResizeArray(0), ResizeArray(0)) + static let empty = TcResolutions(ResizeArray 0, ResizeArray 0, ResizeArray 0, ResizeArray 0) member this.CapturedEnvs = capturedEnvs member this.CapturedExpressionTypings = capturedExprTypes @@ -1506,7 +1711,7 @@ type TcSymbolUses(g, capturedNameResolutions: ResizeArray, ResizeArray(), Array.empty) + /// An accumulator for the results being emitted into the tcSink. -type TcResultsSinkImpl(g, ?source: string) = +type TcResultsSinkImpl(g, ?sourceText: ISourceText) = let capturedEnvs = ResizeArray<_>() let capturedExprTypings = ResizeArray<_>() - let capturedNameResolutions = ResizeArray<_>() + let capturedNameResolutions = ResizeArray() + let capturedMethodGroupResolutions = ResizeArray() + let capturedOpenDeclarations = ResizeArray() let capturedFormatSpecifierLocations = ResizeArray<_>() let capturedNameResolutionIdentifiers = @@ -1536,26 +1745,49 @@ type TcResultsSinkImpl(g, ?source: string) = new System.Collections.Generic.HashSet ( { new IEqualityComparer with member __.GetHashCode ((m, _)) = hash m - member __.Equals ((m1, item1), (m2, item2)) = m1 = m2 && ItemsAreEffectivelyEqual g item1 item2 } ) + member __.Equals ((m1, item1), (m2, item2)) = Range.equals m1 m2 && ItemsAreEffectivelyEqual g item1 item2 } ) - let capturedMethodGroupResolutions = ResizeArray<_>() - let capturedOpenDeclarations = ResizeArray() - let allowedRange (m: range) = not m.IsSynthetic + let allowedRange (m: range) = + not m.IsSynthetic + + let isAlreadyDone endPos item m = + // Desugaring some F# constructs (notably computation expressions with custom operators) + // results in duplication of textual variables. So we ensure we never record two name resolutions + // for the same identifier at the same location. + + match item with + | Item.ModuleOrNamespaces _ -> + not (capturedModulesAndNamespaces.Add (m, item)) + | _ -> + + let keyOpt = + match item with + | Item.Value vref -> Some (endPos, vref.DisplayName) + | Item.ArgName (id, _, _) -> Some (endPos, id.idText) + | _ -> None + + match keyOpt with + | Some key -> not (capturedNameResolutionIdentifiers.Add key) + | _ -> false + + let remove m = + capturedNameResolutions.RemoveAll(fun cnr -> Range.equals cnr.Range m) |> ignore + capturedMethodGroupResolutions.RemoveAll(fun cnr -> Range.equals cnr.Range m) |> ignore let formatStringCheckContext = lazy - source |> Option.map (fun source -> + sourceText |> Option.map (fun sourceText -> let positions = [| yield 0 - for i in 1..source.Length do - let c = source.[i-1] - if c = '\r' && i < source.Length && source.[i] = '\n' then () + for i in 1..sourceText.Length do + let c = sourceText.[i-1] + if c = '\r' && i < sourceText.Length && sourceText.[i] = '\n' then () elif c = '\r' then yield i elif c = '\n' then yield i - yield source.Length + yield sourceText.Length |] - { Source = source + { SourceText = sourceText LineStartPositions = positions }) member this.GetResolutions() = @@ -1567,59 +1799,40 @@ type TcResultsSinkImpl(g, ?source: string) = member this.GetOpenDeclarations() = capturedOpenDeclarations |> Seq.distinctBy (fun x -> x.Range, x.AppliedScope, x.IsOwnNamespace) |> Seq.toArray + member this.GetFormatSpecifierLocations() = + capturedFormatSpecifierLocations.ToArray() + interface ITypecheckResultsSink with member sink.NotifyEnvWithScope(m, nenv, ad) = if allowedRange m then capturedEnvs.Add((m, nenv, ad)) - member sink.NotifyExprHasType(endPos, ty, denv, nenv, ad, m) = + member sink.NotifyExprHasType(ty, nenv, ad, m) = if allowedRange m then - capturedExprTypings.Add((endPos, ty, denv, nenv, ad, m)) + capturedExprTypings.Add((ty, nenv, ad, m)) - member sink.NotifyNameResolution(endPos, item, itemMethodGroup, tpinst, occurenceType, denv, nenv, ad, m, replace) = - // Desugaring some F# constructs (notably computation expressions with custom operators) - // results in duplication of textual variables. So we ensure we never record two name resolutions - // for the same identifier at the same location. + member sink.NotifyNameResolution(endPos, item, tpinst, occurenceType, nenv, ad, m, replace) = if allowedRange m then - if replace then -#if FABLE_COMPILER // RemoveAll not supported - let r1 = capturedNameResolutions.FindAll(fun cnr -> cnr.Range <> m) - let r2 = capturedMethodGroupResolutions.FindAll(fun cnr -> cnr.Range <> m) - capturedNameResolutions.Clear() - capturedMethodGroupResolutions.Clear() - capturedNameResolutions.AddRange(r1) - capturedMethodGroupResolutions.AddRange(r2) -#else - capturedNameResolutions.RemoveAll(fun cnr -> cnr.Range = m) |> ignore - capturedMethodGroupResolutions.RemoveAll(fun cnr -> cnr.Range = m) |> ignore -#endif - else - let alreadyDone = - match item with - | Item.ModuleOrNamespaces _ -> - not (capturedModulesAndNamespaces.Add (m, item)) - | _ -> - let keyOpt = - match item with - | Item.Value vref -> Some (endPos, vref.DisplayName) - | Item.ArgName (id, _, _) -> Some (endPos, id.idText) - | _ -> None + if replace then + remove m + elif not (isAlreadyDone endPos item m) then + capturedNameResolutions.Add(CapturedNameResolution(item, tpinst, occurenceType, nenv, ad, m)) - match keyOpt with - | Some key -> not (capturedNameResolutionIdentifiers.Add key) - | _ -> false - - if not alreadyDone then - capturedNameResolutions.Add(CapturedNameResolution(endPos, item, tpinst, occurenceType, denv, nenv, ad, m)) - capturedMethodGroupResolutions.Add(CapturedNameResolution(endPos, itemMethodGroup, [], occurenceType, denv, nenv, ad, m)) + member sink.NotifyMethodGroupNameResolution(endPos, item, itemMethodGroup, tpinst, occurenceType, nenv, ad, m, replace) = + if allowedRange m then + if replace then + remove m + elif not (isAlreadyDone endPos item m) then + capturedNameResolutions.Add(CapturedNameResolution(item, tpinst, occurenceType, nenv, ad, m)) + capturedMethodGroupResolutions.Add(CapturedNameResolution(itemMethodGroup, [], occurenceType, nenv, ad, m)) member sink.NotifyFormatSpecifierLocation(m, numArgs) = capturedFormatSpecifierLocations.Add((m, numArgs)) - member sink.NotifyOpenDeclaration(openDeclaration) = - capturedOpenDeclarations.Add(openDeclaration) + member sink.NotifyOpenDeclaration openDeclaration = + capturedOpenDeclarations.Add openDeclaration - member sink.CurrentSource = source + member sink.CurrentSourceText = sourceText member sink.FormatStringCheckContext = formatStringCheckContext.Value @@ -1650,26 +1863,31 @@ let CallEnvSink (sink: TcResultsSink) (scopem, nenv, ad) = | Some sink -> sink.NotifyEnvWithScope(scopem, nenv, ad) /// Report a specific name resolution at a source range -let CallNameResolutionSink (sink: TcResultsSink) (m: range, nenv, item, itemMethodGroup, tpinst, occurenceType, denv, ad) = +let CallNameResolutionSink (sink: TcResultsSink) (m: range, nenv, item, tpinst, occurenceType, ad) = match sink.CurrentSink with | None -> () - | Some sink -> sink.NotifyNameResolution(m.End, item, itemMethodGroup, tpinst, occurenceType, denv, nenv, ad, m, false) + | Some sink -> sink.NotifyNameResolution(m.End, item, tpinst, occurenceType, nenv, ad, m, false) -let CallNameResolutionSinkReplacing (sink: TcResultsSink) (m: range, nenv, item, itemMethodGroup, tpinst, occurenceType, denv, ad) = +let CallMethodGroupNameResolutionSink (sink: TcResultsSink) (m: range, nenv, item, itemMethodGroup, tpinst, occurenceType, ad) = match sink.CurrentSink with | None -> () - | Some sink -> sink.NotifyNameResolution(m.End, item, itemMethodGroup, tpinst, occurenceType, denv, nenv, ad, m, true) + | Some sink -> sink.NotifyMethodGroupNameResolution(m.End, item, itemMethodGroup, tpinst, occurenceType, nenv, ad, m, false) + +let CallNameResolutionSinkReplacing (sink: TcResultsSink) (m: range, nenv, item, tpinst, occurenceType, ad) = + match sink.CurrentSink with + | None -> () + | Some sink -> sink.NotifyNameResolution(m.End, item, tpinst, occurenceType, nenv, ad, m, true) /// Report a specific expression typing at a source range -let CallExprHasTypeSink (sink: TcResultsSink) (m: range, nenv, ty, denv, ad) = +let CallExprHasTypeSink (sink: TcResultsSink) (m: range, nenv, ty, ad) = match sink.CurrentSink with | None -> () - | Some sink -> sink.NotifyExprHasType(m.End, ty, denv, nenv, ad, m) + | Some sink -> sink.NotifyExprHasType(ty, nenv, ad, m) let CallOpenDeclarationSink (sink: TcResultsSink) (openDeclaration: OpenDeclaration) = match sink.CurrentSink with | None -> () - | Some sink -> sink.NotifyOpenDeclaration(openDeclaration) + | Some sink -> sink.NotifyOpenDeclaration openDeclaration //------------------------------------------------------------------------- // Check inferability of type parameters in resolved items. @@ -1719,6 +1937,7 @@ let CheckAllTyparsInferrable amap m item = | Item.UnionCase _ | Item.ExnCase _ | Item.RecdField _ + | Item.UnionCaseField _ | Item.AnonRecdField _ | Item.NewDef _ | Item.ILField _ @@ -1753,15 +1972,15 @@ type ResolutionInfo = Item.ModuleOrNamespaces [eref] else Item.Types(eref.DisplayName, [FreshenTycon ncenv m eref]) - CallNameResolutionSink sink (m, nenv, item, item, emptyTyparInst, occ, nenv.eDisplayEnv, ad)) - warnings(typarChecker) + CallNameResolutionSink sink (m, nenv, item, emptyTyparInst, occ, ad)) + warnings typarChecker static member Empty = ResolutionInfo([], (fun _ -> ())) member x.AddEntity info = let (ResolutionInfo(entityPath, warnings)) = x - ResolutionInfo(info::entityPath, warnings) + ResolutionInfo(info :: entityPath, warnings) member x.AddWarning f = let (ResolutionInfo(entityPath, warnings)) = x @@ -1834,35 +2053,40 @@ let CheckForTypeLegitimacyAndMultipleGenericTypeAmbiguities //------------------------------------------------------------------------- /// Perform name resolution for an identifier which must resolve to be a namespace or module. -let rec ResolveLongIndentAsModuleOrNamespace sink atMostOne amap m first fullyQualified (nenv: NameResolutionEnv) ad (id: Ident) (rest: Ident list) isOpenDecl = +let rec ResolveLongIndentAsModuleOrNamespaceOrStaticClass sink (atMostOne: ResultCollectionSettings) (amap: Import.ImportMap) m allowStaticClasses first fullyQualified (nenv: NameResolutionEnv) ad (id:Ident) (rest: Ident list) isOpenDecl = + + // If the selected language version doesn't support open static classes then turn them off. + let allowStaticClasses = allowStaticClasses && amap.g.langVersion.SupportsFeature LanguageFeature.OpenStaticClasses if first && id.idText = MangledGlobalName then match rest with | [] -> error (Error(FSComp.SR.nrGlobalUsedOnlyAsFirstName(), id.idRange)) - | id2::rest2 -> - ResolveLongIndentAsModuleOrNamespace sink atMostOne amap m false FullyQualified nenv ad id2 rest2 isOpenDecl + | id2 :: rest2 -> + ResolveLongIndentAsModuleOrNamespaceOrStaticClass sink atMostOne amap m allowStaticClasses false FullyQualified nenv ad id2 rest2 isOpenDecl else let moduleOrNamespaces = nenv.ModulesAndNamespaces fullyQualified let namespaceNotFound = lazy( - let suggestModulesAndNamespaces() = - moduleOrNamespaces - |> Seq.collect (fun kv -> kv.Value) - |> Seq.filter (fun modref -> IsEntityAccessible amap m ad modref) - |> Seq.collect (fun e -> [e.DisplayName; e.DemangledModuleOrNamespaceName]) - |> HashSet + let suggestModulesAndNamespaces (addToBuffer: string -> unit) = + for kv in moduleOrNamespaces do + for modref in kv.Value do + if IsEntityAccessible amap m ad modref then + addToBuffer modref.DisplayName + addToBuffer modref.DemangledModuleOrNamespaceName UndefinedName(0, FSComp.SR.undefinedNameNamespaceOrModule, id, suggestModulesAndNamespaces)) + // Avoid generating the same error and name suggestion thunk twice It's not clear this is necessary + // since it's just saving an allocation. let mutable moduleNotFoundErrorCache = None let moduleNotFound (modref: ModuleOrNamespaceRef) (mty: ModuleOrNamespaceType) (id: Ident) depth = match moduleNotFoundErrorCache with - | Some (oldId, error) when oldId = id.idRange -> error + | Some (oldId, error) when Range.equals oldId id.idRange -> error | _ -> - let suggestNames() = - mty.ModulesAndNamespacesByDemangledName - |> Seq.filter (fun kv -> IsEntityAccessible amap m ad (modref.NestedTyconRef kv.Value)) - |> Seq.collect (fun e -> [e.Value.DisplayName; e.Value.DemangledModuleOrNamespaceName]) - |> HashSet + let suggestNames (addToBuffer: string -> unit) = + for kv in mty.ModulesAndNamespacesByDemangledName do + if IsEntityAccessible amap m ad (modref.NestedTyconRef kv.Value) then + addToBuffer kv.Value.DisplayName + addToBuffer kv.Value.DemangledModuleOrNamespaceName let error = raze (UndefinedName(depth, FSComp.SR.undefinedNameNamespace, id, suggestNames)) moduleNotFoundErrorCache <- Some(id.idRange, error) @@ -1871,41 +2095,75 @@ let rec ResolveLongIndentAsModuleOrNamespace sink atMostOne amap m first fullyQu let notifyNameResolution (modref: ModuleOrNamespaceRef) m = let item = Item.ModuleOrNamespaces [modref] let occurence = if isOpenDecl then ItemOccurence.Open else ItemOccurence.Use - CallNameResolutionSink sink (m, nenv, item, item, emptyTyparInst, occurence, nenv.DisplayEnv, ad) + CallNameResolutionSink sink (m, nenv, item, emptyTyparInst, occurence, ad) - match moduleOrNamespaces.TryGetValue id.idText with - | true, modrefs -> + let erefs = + let modrefs = + match moduleOrNamespaces.TryGetValue id.idText with + | true, modrefs -> modrefs + | _ -> [] + + let tcrefs = + if allowStaticClasses then + LookupTypeNameInEnvNoArity fullyQualified id.idText nenv |> List.filter (isStaticClass amap.g) + else [] + + modrefs @ tcrefs + + if not erefs.IsEmpty then /// Look through the sub-namespaces and/or modules - let rec look depth (modref: ModuleOrNamespaceRef) (mty: ModuleOrNamespaceType) (lid: Ident list) = + let rec look depth allowStaticClasses (modref: ModuleOrNamespaceRef) (lid: Ident list) = + let mty = modref.ModuleOrNamespaceType match lid with - | [] -> success (depth, modref, mty) - | id :: rest -> - match mty.ModulesAndNamespacesByDemangledName.TryGetValue id.idText with - | true, mspec -> - let subref = modref.NestedTyconRef mspec - if IsEntityAccessible amap m ad subref then - notifyNameResolution subref id.idRange - look (depth+1) subref mspec.ModuleOrNamespaceType rest - else - moduleNotFound modref mty id depth - | _ -> moduleNotFound modref mty id depth + | [] -> + success [ (depth, modref, mty) ] - - modrefs |> CollectResults2 atMostOne (fun modref -> - if IsEntityAccessible amap m ad modref then - notifyNameResolution modref id.idRange - look 1 modref modref.ModuleOrNamespaceType rest + | id :: rest -> + let especs = + let mspecs = + match mty.ModulesAndNamespacesByDemangledName.TryGetValue id.idText with + | true, res -> [res] + | _ -> [] + let tspecs = + if allowStaticClasses then + LookupTypeNameInEntityNoArity id.idRange id.idText mty + |> List.filter (modref.NestedTyconRef >> isStaticClass amap.g) + else [] + mspecs @ tspecs + + if not especs.IsEmpty then + especs + |> List.map (fun espec -> + let subref = modref.NestedTyconRef espec + if IsEntityAccessible amap m ad subref then + notifyNameResolution subref id.idRange + let allowStaticClasses = allowStaticClasses && (subref.IsModuleOrNamespace || isStaticClass amap.g subref) + look (depth+1) allowStaticClasses subref rest + else + moduleNotFound modref mty id depth) + |> List.reduce AddResults + else + moduleNotFound modref mty id depth + + erefs + |> List.map (fun eref -> + if IsEntityAccessible amap m ad eref then + notifyNameResolution eref id.idRange + let allowStaticClasses = allowStaticClasses && (eref.IsModuleOrNamespace || isStaticClass amap.g eref) + look 1 allowStaticClasses eref rest else raze (namespaceNotFound.Force())) - | _ -> raze (namespaceNotFound.Force()) - + |> List.reduce AddResults + else + raze (namespaceNotFound.Force()) -let ResolveLongIndentAsModuleOrNamespaceThen sink atMostOne amap m fullyQualified (nenv: NameResolutionEnv) ad id rest isOpenDecl f = - match ResolveLongIndentAsModuleOrNamespace sink ResultCollectionSettings.AllResults amap m true fullyQualified nenv ad id [] isOpenDecl with +// Note - 'rest' is annotated due to a bug currently in Unity (see: https://github.com/dotnet/fsharp/pull/7427) +let ResolveLongIndentAsModuleOrNamespaceThen sink atMostOne amap m fullyQualified (nenv: NameResolutionEnv) ad id (rest: Ident list) isOpenDecl f = + match ResolveLongIndentAsModuleOrNamespaceOrStaticClass sink ResultCollectionSettings.AllResults amap m false true fullyQualified nenv ad id [] isOpenDecl with | Result modrefs -> match rest with | [] -> error(Error(FSComp.SR.nrUnexpectedEmptyLongId(), id.idRange)) - | id2::rest2 -> + | id2 :: rest2 -> modrefs |> CollectResults2 atMostOne (fun (depth, modref, mty) -> let resInfo = ResolutionInfo.Empty.AddEntity(id.idRange, modref) @@ -1949,115 +2207,6 @@ let ResolveObjectConstructor (ncenv: NameResolver) edenv m ad ty = // Bind the "." notation (member lookup or lookup in a type) //------------------------------------------------------------------------- -/// Query the declared properties of a type (including inherited properties) -let IntrinsicPropInfosOfTypeInScope (infoReader: InfoReader) (optFilter, ad) findFlag m ty = - let g = infoReader.g - let amap = infoReader.amap - let pinfos = GetIntrinsicPropInfoSetsOfType infoReader (optFilter, ad, AllowMultiIntfInstantiations.Yes) findFlag m ty - let pinfos = pinfos |> ExcludeHiddenOfPropInfos g amap m - pinfos - -/// Select from a list of extension properties -let SelectPropInfosFromExtMembers (infoReader: InfoReader, ad, optFilter) declaringTy m extMemInfos = - let g = infoReader.g - let amap = infoReader.amap - // NOTE: multiple "open"'s push multiple duplicate values into eIndexedExtensionMembers, hence setify. - let seen = HashSet(ExtensionMember.Comparer g) - let propCollector = new PropertyCollector(g, amap, m, declaringTy, optFilter, ad) - for emem in extMemInfos do - if seen.Add emem then - match emem with - | FSExtMem (vref, _pri) -> - match vref.MemberInfo with - | None -> () - | Some membInfo -> propCollector.Collect(membInfo, vref) - | ILExtMem _ -> - // No extension properties coming from .NET - () - propCollector.Close() - -/// Query the available extension properties of a type (including extension properties for inherited types) -let ExtensionPropInfosOfTypeInScope (infoReader: InfoReader) (nenv: NameResolutionEnv) (optFilter, ad) m ty = - let g = infoReader.g - - let extMemsFromHierarchy = - infoReader.GetEntireTypeHierachy(AllowMultiIntfInstantiations.Yes, m, ty) |> List.collect (fun ty -> - if isAppTy g ty then - let tcref = tcrefOfAppTy g ty - let extMemInfos = nenv.eIndexedExtensionMembers.Find tcref - SelectPropInfosFromExtMembers (infoReader, ad, optFilter) ty m extMemInfos - else []) - - let extMemsDangling = SelectPropInfosFromExtMembers (infoReader, ad, optFilter) ty m nenv.eUnindexedExtensionMembers - extMemsDangling @ extMemsFromHierarchy - - -/// Get all the available properties of a type (both intrinsic and extension) -let AllPropInfosOfTypeInScope infoReader nenv (optFilter, ad) findFlag m ty = - IntrinsicPropInfosOfTypeInScope infoReader (optFilter, ad) findFlag m ty - @ ExtensionPropInfosOfTypeInScope infoReader nenv (optFilter, ad) m ty - -/// Get the available methods of a type (both declared and inherited) -let IntrinsicMethInfosOfType (infoReader: InfoReader) (optFilter, ad, allowMultiIntfInst) findFlag m ty = - let g = infoReader.g - let amap = infoReader.amap - let minfos = GetIntrinsicMethInfoSetsOfType infoReader (optFilter, ad, allowMultiIntfInst) findFlag m ty - let minfos = minfos |> ExcludeHiddenOfMethInfos g amap m - minfos - -/// Select from a list of extension methods -let SelectMethInfosFromExtMembers (infoReader: InfoReader) optFilter apparentTy m extMemInfos = - let g = infoReader.g - // NOTE: multiple "open"'s push multiple duplicate values into eIndexedExtensionMembers - let seen = HashSet(ExtensionMember.Comparer g) - [ - for emem in extMemInfos do - if seen.Add emem then - match emem with - | FSExtMem (vref, pri) -> - match vref.MemberInfo with - | None -> () - | Some membInfo -> - match TrySelectMemberVal g optFilter apparentTy (Some pri) membInfo vref with - | Some m -> yield m - | _ -> () - | ILExtMem (actualParent, minfo, pri) when (match optFilter with None -> true | Some nm -> nm = minfo.LogicalName) -> - // Make a reference to the type containing the extension members - match minfo with - | ILMeth(_, ilminfo, _) -> - yield (MethInfo.CreateILExtensionMeth (infoReader.amap, m, apparentTy, actualParent, Some pri, ilminfo.RawMetadata)) - // F#-defined IL-style extension methods are not seen as extension methods in F# code - | FSMeth(g, _, vref, _) -> - yield (FSMeth(g, apparentTy, vref, Some pri)) -#if !NO_EXTENSIONTYPING - // // Provided extension methods are not yet supported - | ProvidedMeth(amap, providedMeth, _, m) -> - yield (ProvidedMeth(amap, providedMeth, Some pri, m)) -#endif - | DefaultStructCtor _ -> - () - | _ -> () - ] - -/// Query the available extension properties of a methods (including extension methods for inherited types) -let ExtensionMethInfosOfTypeInScope (infoReader: InfoReader) (nenv: NameResolutionEnv) optFilter m ty = - let extMemsDangling = SelectMethInfosFromExtMembers infoReader optFilter ty m nenv.eUnindexedExtensionMembers - let extMemsFromHierarchy = - infoReader.GetEntireTypeHierachy(AllowMultiIntfInstantiations.Yes, m, ty) |> List.collect (fun ty -> - let g = infoReader.g - if isAppTy g ty then - let tcref = tcrefOfAppTy g ty - let extValRefs = nenv.eIndexedExtensionMembers.Find tcref - SelectMethInfosFromExtMembers infoReader optFilter ty m extValRefs - else []) - extMemsDangling @ extMemsFromHierarchy - -/// Get all the available methods of a type (both intrinsic and extension) -let AllMethInfosOfTypeInScope infoReader nenv (optFilter, ad) findFlag m ty = - IntrinsicMethInfosOfType infoReader (optFilter, ad, AllowMultiIntfInstantiations.Yes) findFlag m ty - @ ExtensionMethInfosOfTypeInScope infoReader nenv optFilter m ty - - /// Used to report an error condition where name resolution failed due to an indeterminate type exception IndeterminateType of range @@ -2103,7 +2252,7 @@ let CoreDisplayName(pinfo: PropInfo) = let DecodeFSharpEvent (pinfos: PropInfo list) ad g (ncenv: NameResolver) m = match pinfos with | [pinfo] when pinfo.IsFSharpEventProperty -> - let nm = CoreDisplayName(pinfo) + let nm = CoreDisplayName pinfo let minfos1 = GetImmediateIntrinsicMethInfosOfType (Some("add_"+nm), ad) g ncenv.amap m pinfo.ApparentEnclosingType let minfos2 = GetImmediateIntrinsicMethInfosOfType (Some("remove_"+nm), ad) g ncenv.amap m pinfo.ApparentEnclosingType match minfos1, minfos2 with @@ -2114,7 +2263,7 @@ let DecodeFSharpEvent (pinfos: PropInfo list) ad g (ncenv: NameResolver) m = // FOUND PROPERTY-AS-EVENT BUT DIDN'T FIND CORRESPONDING ADD/REMOVE METHODS Some(Item.Property (nm, pinfos)) | pinfo :: _ -> - let nm = CoreDisplayName(pinfo) + let nm = CoreDisplayName pinfo Some(Item.Property (nm, pinfos)) | _ -> None @@ -2161,7 +2310,7 @@ let rec ResolveLongIdentInTypePrim (ncenv: NameResolver) nenv lookupKind (resInf let pinfos = psets |> ExcludeHiddenOfPropInfos g ncenv.amap m // fold the available extension members into the overload resolution - let extensionPropInfos = ExtensionPropInfosOfTypeInScope ncenv.InfoReader nenv (optFilter, ad) m ty + let extensionPropInfos = ExtensionPropInfosOfTypeInScope ResultCollectionSettings.AllResults ncenv.InfoReader nenv optFilter ad m ty // make sure to keep the intrinsic pinfos before the extension pinfos in the list, // since later on this logic is used when giving preference to intrinsic definitions @@ -2173,23 +2322,23 @@ let rec ResolveLongIdentInTypePrim (ncenv: NameResolver) nenv lookupKind (resInf let minfos = msets |> ExcludeHiddenOfMethInfos g ncenv.amap m // fold the available extension members into the overload resolution - let extensionMethInfos = ExtensionMethInfosOfTypeInScope ncenv.InfoReader nenv optFilter m ty + let extensionMethInfos = ExtensionMethInfosOfTypeInScope ResultCollectionSettings.AllResults ncenv.InfoReader nenv optFilter m ty success [resInfo, Item.MakeMethGroup (nm, minfos@extensionMethInfos), rest] - | Some (ILFieldItem (finfo:: _)) when (match lookupKind with LookupKind.Expr | LookupKind.Pattern -> true | _ -> false) -> + | Some (ILFieldItem (finfo :: _)) when (match lookupKind with LookupKind.Expr | LookupKind.Pattern -> true | _ -> false) -> success [resInfo, Item.ILField finfo, rest] | Some (EventItem (einfo :: _)) when isLookUpExpr -> success [resInfo, Item.Event einfo, rest] - | Some (RecdFieldItem (rfinfo)) when (match lookupKind with LookupKind.Expr | LookupKind.RecdField | LookupKind.Pattern -> true | _ -> false) -> - success [resInfo, Item.RecdField(rfinfo), rest] + | Some (RecdFieldItem rfinfo) when (match lookupKind with LookupKind.Expr | LookupKind.RecdField | LookupKind.Pattern -> true | _ -> false) -> + success [resInfo, Item.RecdField rfinfo, rest] | _ -> - let pinfos = ExtensionPropInfosOfTypeInScope ncenv.InfoReader nenv (optFilter, ad) m ty + let pinfos = ExtensionPropInfosOfTypeInScope ResultCollectionSettings.AllResults ncenv.InfoReader nenv optFilter ad m ty if not (isNil pinfos) && isLookUpExpr then OneResult(success (resInfo, Item.Property (nm, pinfos), rest)) else - let minfos = ExtensionMethInfosOfTypeInScope ncenv.InfoReader nenv optFilter m ty + let minfos = ExtensionMethInfosOfTypeInScope ResultCollectionSettings.AllResults ncenv.InfoReader nenv optFilter m ty if not (isNil minfos) && isLookUpExpr then success [resInfo, Item.MakeMethGroup (nm, minfos), rest] @@ -2215,58 +2364,57 @@ let rec ResolveLongIdentInTypePrim (ncenv: NameResolver) nenv lookupKind (resInf |> MapResults (fun (resInfo, item) -> (resInfo, item, [])) | ResolveTypeNamesToTypeRefs -> OneSuccess (resInfo, Item.Types (nm, nestedTypes), rest) - | id2::rest2 -> + | id2 :: rest2 -> let nestedTypes = GetNestedTypesOfType (ad, ncenv, Some nm, TypeNameResolutionStaticArgsInfo.Indefinite, true, m) ty ResolveLongIdentInNestedTypes ncenv nenv lookupKind resInfo (depth+1) id m ad id2 rest2 findFlag typeNameResInfo nestedTypes match nestedSearchAccessible with | Result res when not (isNil res) -> nestedSearchAccessible | _ -> - let suggestMembers() = - let suggestions1 = - ExtensionPropInfosOfTypeInScope ncenv.InfoReader nenv (None, ad) m ty - |> List.map (fun p -> p.PropertyName) + let suggestMembers (addToBuffer: string -> unit) = + for p in ExtensionPropInfosOfTypeInScope ResultCollectionSettings.AllResults ncenv.InfoReader nenv None ad m ty do + addToBuffer p.PropertyName - let suggestions2 = - ExtensionMethInfosOfTypeInScope ncenv.InfoReader nenv None m ty - |> List.map (fun m -> m.DisplayName) + for m in ExtensionMethInfosOfTypeInScope ResultCollectionSettings.AllResults ncenv.InfoReader nenv None m ty do + addToBuffer m.DisplayName - let suggestions3 = - GetIntrinsicPropInfosOfType ncenv.InfoReader (None, ad, AllowMultiIntfInstantiations.No) findFlag m ty - |> List.map (fun p -> p.PropertyName) + for p in GetIntrinsicPropInfosOfType ncenv.InfoReader None ad AllowMultiIntfInstantiations.No findFlag m ty do + addToBuffer p.PropertyName - let suggestions4 = - GetIntrinsicMethInfosOfType ncenv.InfoReader (None, ad, AllowMultiIntfInstantiations.No) findFlag m ty - |> List.filter (fun m -> not m.IsClassConstructor && not m.IsConstructor) - |> List.map (fun m -> m.DisplayName) + for m in GetIntrinsicMethInfosOfType ncenv.InfoReader None ad AllowMultiIntfInstantiations.No findFlag m ty do + if not m.IsClassConstructor && not m.IsConstructor then + addToBuffer m.DisplayName - let suggestions5 = GetRecordLabelsForType g nenv ty + for l in GetRecordLabelsForType g nenv ty do + addToBuffer l - let suggestions6 = - match lookupKind with - | LookupKind.Expr | LookupKind.Pattern -> - if isAppTy g ty then - let tcref = tcrefOfAppTy g ty - tcref.UnionCasesArray - |> Array.map (fun uc -> uc.DisplayName) - else - [||] - | _ -> [||] + match lookupKind with + | LookupKind.Expr | LookupKind.Pattern -> + match tryTcrefOfAppTy g ty with + | ValueSome tcref -> + for uc in tcref.UnionCasesArray do + addToBuffer uc.DisplayName + | _ -> () + | _ -> () - [ yield! suggestions1 - yield! suggestions2 - yield! suggestions3 - yield! suggestions4 - yield! suggestions5 - yield! suggestions6 ] - |> HashSet + let errorTextF s = + if isAppTy g ty then + let tcref = tcrefOfAppTy g ty + FSComp.SR.undefinedNameFieldConstructorOrMemberWhenTypeIsKnown(tcref.DisplayNameWithStaticParametersAndTypars, s) + else + FSComp.SR.undefinedNameFieldConstructorOrMember(s) - raze (UndefinedName (depth, FSComp.SR.undefinedNameFieldConstructorOrMember, id, suggestMembers)) + raze (UndefinedName (depth, errorTextF, id, suggestMembers)) and ResolveLongIdentInNestedTypes (ncenv: NameResolver) nenv lookupKind resInfo depth id m ad (id2: Ident) (rest: Ident list) findFlag typeNameResInfo tys = tys |> CollectAtMostOneResult (fun ty -> - let resInfo = if isAppTy ncenv.g ty then resInfo.AddEntity(id.idRange, tcrefOfAppTy ncenv.g ty) else resInfo + let resInfo = + match tryTcrefOfAppTy ncenv.g ty with + | ValueSome tcref -> + resInfo.AddEntity(id.idRange, tcref) + | _ -> + resInfo ResolveLongIdentInTypePrim ncenv nenv lookupKind resInfo depth m ad id2 rest findFlag typeNameResInfo ty |> AtMostOneResult m) @@ -2333,7 +2481,7 @@ let rec ResolveExprLongIdentInModuleOrNamespace (ncenv: NameResolver) nenv (type let tcrefs = tcrefs |> List.map (fun tcref -> (resInfo, tcref)) match rest with - | id2::rest2 -> + | id2 :: rest2 -> let tcrefs = let typeNameResInfo = TypeNameResolutionInfo (ResolveTypeNamesToTypeRefs, TypeNameResolutionStaticArgsInfo.Indefinite) @@ -2360,7 +2508,7 @@ let rec ResolveExprLongIdentInModuleOrNamespace (ncenv: NameResolver) nenv (type // Something in a sub-namespace or sub-module let moduleSearch() = match rest with - | id2::rest2 -> + | id2 :: rest2 -> match mty.ModulesAndNamespacesByDemangledName.TryGetValue id.idText with | true, AccessibleEntityRef ncenv.amap m ad modref submodref -> let resInfo = resInfo.AddEntity(id.idRange, submodref) @@ -2373,43 +2521,28 @@ let rec ResolveExprLongIdentInModuleOrNamespace (ncenv: NameResolver) nenv (type match tyconSearch +++ moduleSearch +++ (fun _ -> unionSearch) with | Result [] -> - let suggestPossibleTypesAndNames() = - let types = - modref.ModuleOrNamespaceType.AllEntities - |> Seq.filter (fun e -> IsEntityAccessible ncenv.amap m ad (modref.NestedTyconRef e)) - |> Seq.map (fun e -> e.DisplayName) - - let submodules = - mty.ModulesAndNamespacesByDemangledName - |> Seq.filter (fun kv -> IsEntityAccessible ncenv.amap m ad (modref.NestedTyconRef kv.Value)) - |> Seq.map (fun e -> e.Value.DisplayName) - - let unions = - modref.ModuleOrNamespaceType.AllEntities - |> Seq.collect (fun tycon -> - let hasRequireQualifiedAccessAttribute = HasFSharpAttribute ncenv.g ncenv.g.attrib_RequireQualifiedAccessAttribute tycon.Attribs - if hasRequireQualifiedAccessAttribute then - [||] - else - tycon.UnionCasesArray) - |> Seq.map (fun uc -> uc.DisplayName) - - let vals = - modref.ModuleOrNamespaceType.AllValsByLogicalName - |> Seq.filter (fun e -> IsValAccessible ad (mkNestedValRef modref e.Value)) - |> Seq.map (fun e -> e.Value.DisplayName) - - let exns = - modref.ModuleOrNamespaceType.ExceptionDefinitionsByDemangledName - |> Seq.filter (fun e -> IsTyconReprAccessible ncenv.amap m ad (modref.NestedTyconRef e.Value)) - |> Seq.map (fun e -> e.Value.DisplayName) - - [ yield! types - yield! submodules - yield! unions - yield! vals - yield! exns ] - |> HashSet + let suggestPossibleTypesAndNames (addToBuffer: string -> unit) = + for e in modref.ModuleOrNamespaceType.AllEntities do + if IsEntityAccessible ncenv.amap m ad (modref.NestedTyconRef e) then + addToBuffer e.DisplayName + + if e.IsUnionTycon then + let hasRequireQualifiedAccessAttribute = HasFSharpAttribute ncenv.g ncenv.g.attrib_RequireQualifiedAccessAttribute e.Attribs + if not hasRequireQualifiedAccessAttribute then + for uc in e.UnionCasesArray do + addToBuffer uc.DisplayName + + for kv in mty.ModulesAndNamespacesByDemangledName do + if IsEntityAccessible ncenv.amap m ad (modref.NestedTyconRef kv.Value) then + addToBuffer kv.Value.DisplayName + + for e in modref.ModuleOrNamespaceType.AllValsByLogicalName do + if IsValAccessible ad (mkNestedValRef modref e.Value) then + addToBuffer e.Value.DisplayName + + for e in modref.ModuleOrNamespaceType.ExceptionDefinitionsByDemangledName do + if IsTyconReprAccessible ncenv.amap m ad (modref.NestedTyconRef e.Value) then + addToBuffer e.Value.DisplayName raze (UndefinedName(depth, FSComp.SR.undefinedNameValueConstructorNamespaceOrType, id, suggestPossibleTypesAndNames)) | results -> AtMostOneResult id.idRange results @@ -2434,17 +2567,26 @@ let ChooseTyconRefInExpr (ncenv: NameResolver, m, ad, nenv, id: Ident, typeNameR /// that may represent further actions, e.g. further lookups. let rec ResolveExprLongIdentPrim sink (ncenv: NameResolver) first fullyQualified m ad nenv (typeNameResInfo: TypeNameResolutionInfo) (id: Ident) (rest: Ident list) isOpenDecl = let resInfo = ResolutionInfo.Empty + let canSuggestThisItem (item:Item) = + // All items can be suggested except nameof when it comes from FSharp.Core.dll and the nameof feature is not enabled + match item with + | Item.Value v -> + let isNameOfOperator = valRefEq ncenv.g ncenv.g.nameof_vref v + if isNameOfOperator && not (ncenv.g.langVersion.SupportsFeature LanguageFeature.NameOf) then false + else true + | _ -> true + if first && id.idText = MangledGlobalName then match rest with | [] -> error (Error(FSComp.SR.nrGlobalUsedOnlyAsFirstName(), id.idRange)) | [next] -> ResolveExprLongIdentPrim sink ncenv false fullyQualified m ad nenv typeNameResInfo next [] isOpenDecl - | id2::rest2 -> + | id2 :: rest2 -> ResolveExprLongIdentPrim sink ncenv false FullyQualified m ad nenv typeNameResInfo id2 rest2 isOpenDecl else if isNil rest && fullyQualified <> FullyQualified then - let typeError = ref None + let mutable typeError = None // Single identifier. Lookup the unqualified names in the environment let envSearch = match nenv.eUnqualifiedItems.TryGetValue id.idText with @@ -2465,10 +2607,19 @@ let rec ResolveExprLongIdentPrim sink (ncenv: NameResolver) first fullyQualified let resInfo, item, rest = ForceRaise res ResolutionInfo.SendEntityPathToSink(sink, ncenv, nenv, ItemOccurence.Use, ad, resInfo, ResultTyparChecker(fun () -> CheckAllTyparsInferrable ncenv.amap m item)) Some(item, rest) - | Exception e -> typeError := Some e; None + | Exception e -> typeError <- Some e; None | true, res -> - Some (FreshenUnqualifiedItem ncenv m res, []) + let fresh = FreshenUnqualifiedItem ncenv m res + match fresh with + | Item.Value value -> + let isNameOfOperator = valRefEq ncenv.g ncenv.g.nameof_vref value + if isNameOfOperator && not (ncenv.languageSupportsNameOf) then + // Do not resolve `nameof` if the feature is unsupported, even if it is FSharp.Core + None + else + Some (fresh, []) + | _ -> Some (fresh, []) | _ -> None @@ -2494,44 +2645,30 @@ let rec ResolveExprLongIdentPrim sink (ncenv: NameResolver) first fullyQualified | Result _ as res -> ForceRaise res | _ -> let failingCase = - match !typeError with + match typeError with | Some e -> raze e | _ -> - let suggestNamesAndTypes() = - let suggestedNames = - nenv.eUnqualifiedItems - |> Seq.map (fun e -> e.Value.DisplayName) - - let suggestedTypes = - nenv.TyconsByDemangledNameAndArity fullyQualified - |> Seq.filter (fun e -> IsEntityAccessible ncenv.amap m ad e.Value) - |> Seq.map (fun e -> e.Value.DisplayName) - - let suggestedModulesAndNamespaces = - nenv.ModulesAndNamespaces fullyQualified - |> Seq.collect (fun kv -> kv.Value) - |> Seq.filter (fun modref -> IsEntityAccessible ncenv.amap m ad modref) - |> Seq.collect (fun e -> [e.DisplayName; e.DemangledModuleOrNamespaceName]) - - let unions = - // check if the user forgot to use qualified access - nenv.eTyconsByDemangledNameAndArity - |> Seq.choose (fun e -> - let hasRequireQualifiedAccessAttribute = HasFSharpAttribute ncenv.g ncenv.g.attrib_RequireQualifiedAccessAttribute e.Value.Attribs - if not hasRequireQualifiedAccessAttribute then - None - else - if e.Value.IsUnionTycon && e.Value.UnionCasesArray |> Array.exists (fun c -> c.DisplayName = id.idText) then - Some e.Value - else - None) - |> Seq.map (fun t -> t.DisplayName + "." + id.idText) - - [ yield! suggestedNames - yield! suggestedTypes - yield! suggestedModulesAndNamespaces - yield! unions ] - |> HashSet + 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 + addToBuffer modref.DemangledModuleOrNamespaceName + + // 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.DisplayName = id.idText) then + addToBuffer (e.Value.DisplayName + "." + id.idText) raze (UndefinedName(0, FSComp.SR.undefinedNameValueOfConstructor, id, suggestNamesAndTypes)) ForceRaise failingCase @@ -2570,7 +2707,7 @@ let rec ResolveExprLongIdentPrim sink (ncenv: NameResolver) first fullyQualified let tcrefs = LookupTypeNameInEnvNoArity fullyQualified id.idText nenv if isNil tcrefs then NoResultsOrUsefulErrors else match rest with - | id2::rest2 -> + | id2 :: rest2 -> let tcrefs = tcrefs |> List.map (fun tcref -> (resInfo, tcref)) let tcrefs = let typeNameResInfo = TypeNameResolutionInfo.ResolveToTypeRefs (TypeNameResolutionStaticArgsInfo.Indefinite) @@ -2598,29 +2735,26 @@ let rec ResolveExprLongIdentPrim sink (ncenv: NameResolver) first fullyQualified | _ -> let innerSearch = search +++ (moduleSearch AccessibleFromSomeFSharpCode) +++ (tyconSearch AccessibleFromSomeFSharpCode) - let suggestEverythingInScope() = - seq { yield! - nenv.ModulesAndNamespaces fullyQualified - |> Seq.collect (fun kv -> kv.Value) - |> Seq.filter (fun modref -> IsEntityAccessible ncenv.amap m ad modref) - |> Seq.collect (fun e -> [e.DisplayName; e.DemangledModuleOrNamespaceName]) + let suggestEverythingInScope (addToBuffer: string -> unit) = + for kv in nenv.ModulesAndNamespaces fullyQualified do + for modref in kv.Value do + if IsEntityAccessible ncenv.amap m ad modref then + addToBuffer modref.DisplayName + addToBuffer modref.DemangledModuleOrNamespaceName - yield! - nenv.TyconsByDemangledNameAndArity fullyQualified - |> Seq.filter (fun e -> IsEntityAccessible ncenv.amap m ad e.Value) - |> Seq.map (fun e -> e.Value.DisplayName) + for e in nenv.TyconsByDemangledNameAndArity fullyQualified do + if IsEntityAccessible ncenv.amap m ad e.Value then + addToBuffer e.Value.DisplayName - yield! - nenv.eUnqualifiedItems - |> Seq.map (fun e -> e.Value.DisplayName) - } |> HashSet + for e in nenv.eUnqualifiedItems do + if canSuggestThisItem e.Value then + addToBuffer e.Value.DisplayName match innerSearch with - | Exception (UndefinedName(0, _, id1, suggestionsF)) when id.idRange = id1.idRange -> - let mergeSuggestions() = - let res = suggestEverythingInScope() - res.UnionWith(suggestionsF()) - res + | Exception (UndefinedName(0, _, id1, suggestionsF)) when Range.equals id.idRange id1.idRange -> + let mergeSuggestions addToBuffer = + suggestionsF addToBuffer + suggestEverythingInScope addToBuffer let failingCase = raze (UndefinedName(0, FSComp.SR.undefinedNameValueNamespaceTypeOrModule, id, mergeSuggestions)) ForceRaise failingCase @@ -2636,7 +2770,7 @@ let rec ResolveExprLongIdentPrim sink (ncenv: NameResolver) first fullyQualified let ResolveExprLongIdent sink (ncenv: NameResolver) m ad nenv typeNameResInfo lid = match lid with | [] -> error (Error(FSComp.SR.nrInvalidExpression(textOfLid lid), m)) - | id::rest -> ResolveExprLongIdentPrim sink ncenv true OpenQualified m ad nenv typeNameResInfo id rest false + | id :: rest -> ResolveExprLongIdentPrim sink ncenv true OpenQualified m ad nenv typeNameResInfo id rest false //------------------------------------------------------------------------- // Resolve F#/IL "." syntax in patterns @@ -2672,7 +2806,7 @@ let rec ResolvePatternLongIdentInModuleOrNamespace (ncenv: NameResolver) nenv nu // Something in a type? e.g. a literal field let tyconSearch = match rest with - | id2::rest2 -> + | id2 :: rest2 -> let tcrefs = tcrefs.Force() ResolveLongIdentInTyconRefs ResultCollectionSettings.AtMostOneResult (ncenv: NameResolver) nenv LookupKind.Pattern (depth+1) m ad id2 rest2 numTyArgsOpt id.idRange tcrefs | _ -> @@ -2691,7 +2825,7 @@ let rec ResolvePatternLongIdentInModuleOrNamespace (ncenv: NameResolver) nenv nu // Something in a sub-namespace or sub-module or nested-type let moduleSearch() = match rest with - | id2::rest2 -> + | id2 :: rest2 -> match mty.ModulesAndNamespacesByDemangledName.TryGetValue id.idText with | true, AccessibleEntityRef ncenv.amap m ad modref submodref -> let resInfo = resInfo.AddEntity(id.idRange, submodref) @@ -2702,20 +2836,15 @@ let rec ResolvePatternLongIdentInModuleOrNamespace (ncenv: NameResolver) nenv nu match tyconSearch +++ ctorSearch +++ moduleSearch with | Result [] -> - let suggestPossibleTypes() = - let submodules = - mty.ModulesAndNamespacesByDemangledName - |> Seq.filter (fun kv -> IsEntityAccessible ncenv.amap m ad (modref.NestedTyconRef kv.Value)) - |> Seq.collect (fun e -> [e.Value.DisplayName; e.Value.DemangledModuleOrNamespaceName]) + let suggestPossibleTypes (addToBuffer: string -> unit) = + for kv in mty.ModulesAndNamespacesByDemangledName do + if IsEntityAccessible ncenv.amap m ad (modref.NestedTyconRef kv.Value) then + addToBuffer kv.Value.DisplayName + addToBuffer kv.Value.DemangledModuleOrNamespaceName - let suggestedTypes = - nenv.TyconsByDemangledNameAndArity FullyQualifiedFlag.OpenQualified - |> Seq.filter (fun e -> IsEntityAccessible ncenv.amap m ad e.Value) - |> Seq.map (fun e -> e.Value.DisplayName) - - [ yield! submodules - yield! suggestedTypes ] - |> HashSet + for e in nenv.TyconsByDemangledNameAndArity FullyQualifiedFlag.OpenQualified do + if IsEntityAccessible ncenv.amap m ad e.Value then + addToBuffer e.Value.DisplayName raze (UndefinedName(depth, FSComp.SR.undefinedNameConstructorModuleOrNamespace, id, suggestPossibleTypes)) | results -> AtMostOneResult id.idRange results @@ -2732,7 +2861,7 @@ let rec ResolvePatternLongIdentPrim sink (ncenv: NameResolver) fullyQualified wa match rest with | [] -> error (Error(FSComp.SR.nrGlobalUsedOnlyAsFirstName(), id.idRange)) - | id2::rest2 -> + | id2 :: rest2 -> ResolvePatternLongIdentPrim sink ncenv FullyQualified warnOnUpper newDef m ad nenv numTyArgsOpt id2 rest2 else // Single identifiers in patterns @@ -2748,7 +2877,7 @@ let rec ResolvePatternLongIdentPrim sink (ncenv: NameResolver) fullyQualified wa (warnOnUpper = WarnOnUpperCase) && id.idText.Length >= 3 && System.Char.ToLowerInvariant id.idText.[0] <> id.idText.[0] then - warning(UpperCaseIdentifierInPattern(m)) + warning(UpperCaseIdentifierInPattern m) Item.NewDef id // Long identifiers in patterns @@ -2786,7 +2915,7 @@ let rec ResolvePatternLongIdentPrim sink (ncenv: NameResolver) fullyQualified wa let ResolvePatternLongIdent sink (ncenv: NameResolver) warnOnUpper newDef m ad nenv numTyArgsOpt (lid: Ident list) = match lid with | [] -> error(Error(FSComp.SR.nrUnexpectedEmptyLongId(), m)) - | id::rest -> ResolvePatternLongIdentPrim sink ncenv OpenQualified warnOnUpper newDef m ad nenv numTyArgsOpt id rest + | id :: rest -> ResolvePatternLongIdentPrim sink ncenv OpenQualified warnOnUpper newDef m ad nenv numTyArgsOpt id rest //------------------------------------------------------------------------- // Resolve F#/IL "." syntax in types @@ -2800,8 +2929,10 @@ let ResolvePatternLongIdent sink (ncenv: NameResolver) warnOnUpper newDef m ad n // X.ListEnumerator // does not resolve // let ResolveNestedTypeThroughAbbreviation (ncenv: NameResolver) (tcref: TyconRef) m = - if tcref.IsTypeAbbrev && tcref.Typars(m).IsEmpty && isAppTy ncenv.g tcref.TypeAbbrev.Value && isNil (argsOfAppTy ncenv.g tcref.TypeAbbrev.Value) then - tcrefOfAppTy ncenv.g tcref.TypeAbbrev.Value + if tcref.IsTypeAbbrev && tcref.Typars(m).IsEmpty then + match tryAppTy ncenv.g tcref.TypeAbbrev.Value with + | ValueSome (abbrevTcref, []) -> abbrevTcref + | _ -> tcref else tcref @@ -2821,13 +2952,12 @@ let rec ResolveTypeLongIdentInTyconRefPrim (ncenv: NameResolver) (typeNameResInf match tcrefs with | tcref :: _ -> success tcref | [] -> - let suggestTypes() = - tcref.ModuleOrNamespaceType.TypesByDemangledNameAndArity id.idRange - |> Seq.map (fun e -> e.Value.DisplayName) - |> HashSet + let suggestTypes (addToBuffer: string -> unit) = + for e in tcref.ModuleOrNamespaceType.TypesByDemangledNameAndArity id.idRange do + addToBuffer e.Value.DisplayName raze (UndefinedName(depth, FSComp.SR.undefinedNameType, id, suggestTypes)) - | id2::rest2 -> + | id2 :: rest2 -> #if !NO_EXTENSIONTYPING // No dotting through type generators to get to a nested type! CheckForDirectReferenceToGeneratedType (tcref, PermitDirectReferenceToGeneratedType.No, m) @@ -2842,10 +2972,9 @@ let rec ResolveTypeLongIdentInTyconRefPrim (ncenv: NameResolver) (typeNameResInf match tcrefs with | _ :: _ -> tcrefs |> CollectAtMostOneResult (fun (resInfo, tcref) -> ResolveTypeLongIdentInTyconRefPrim ncenv typeNameResInfo ad resInfo genOk (depth+1) m tcref id2 rest2) | [] -> - let suggestTypes() = - tcref.ModuleOrNamespaceType.TypesByDemangledNameAndArity id.idRange - |> Seq.map (fun e -> e.Value.DisplayName) - |> HashSet + let suggestTypes (addToBuffer: string -> unit) = + for e in tcref.ModuleOrNamespaceType.TypesByDemangledNameAndArity id.idRange do + addToBuffer e.Value.DisplayName raze (UndefinedName(depth, FSComp.SR.undefinedNameType, id, suggestTypes)) @@ -2857,20 +2986,20 @@ let ResolveTypeLongIdentInTyconRef sink (ncenv: NameResolver) nenv typeNameResIn match lid with | [] -> error(Error(FSComp.SR.nrUnexpectedEmptyLongId(), m)) - | id::rest -> + | 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, item, emptyTyparInst, ItemOccurence.UseInType, nenv.eDisplayEnv, ad) + CallNameResolutionSink sink (rangeOfLid lid, nenv, item, emptyTyparInst, ItemOccurence.UseInType, ad) tcref /// Create an UndefinedName error with details let SuggestTypeLongIdentInModuleOrNamespace depth (modref: ModuleOrNamespaceRef) amap ad m (id: Ident) = - let suggestPossibleTypes() = - modref.ModuleOrNamespaceType.AllEntities - |> Seq.filter (fun e -> IsEntityAccessible amap m ad (modref.NestedTyconRef e)) - |> Seq.collect (fun e -> [e.DisplayName; e.DemangledModuleOrNamespaceName]) - |> HashSet + let suggestPossibleTypes (addToBuffer: string -> unit) = + for e in modref.ModuleOrNamespaceType.AllEntities do + if IsEntityAccessible amap m ad (modref.NestedTyconRef e) then + addToBuffer e.DisplayName + addToBuffer e.DemangledModuleOrNamespaceName let errorTextF s = FSComp.SR.undefinedNameTypeIn(s, fullDisplayTextOfModRef modref) UndefinedName(depth, errorTextF, id, suggestPossibleTypes) @@ -2884,21 +3013,22 @@ let rec private ResolveTypeLongIdentInModuleOrNamespace sink nenv (ncenv: NameRe match tcrefs with | _ :: _ -> tcrefs |> CollectResults (fun tcref -> success(resInfo, tcref)) | [] -> raze (SuggestTypeLongIdentInModuleOrNamespace depth modref ncenv.amap ad m id) - | id2::rest2 -> + | id2 :: rest2 -> let m = unionRanges m id.idRange let modulSearch = match modref.ModuleOrNamespaceType.ModulesAndNamespacesByDemangledName.TryGetValue id.idText with | true, AccessibleEntityRef ncenv.amap m ad modref submodref -> let item = Item.ModuleOrNamespaces [submodref] - CallNameResolutionSink sink (id.idRange, nenv, item, item, emptyTyparInst, ItemOccurence.Use, nenv.DisplayEnv, ad) + CallNameResolutionSink sink (id.idRange, nenv, item, emptyTyparInst, ItemOccurence.Use, ad) let resInfo = resInfo.AddEntity(id.idRange, submodref) ResolveTypeLongIdentInModuleOrNamespace sink nenv ncenv typeNameResInfo ad genOk resInfo (depth+1) m submodref submodref.ModuleOrNamespaceType id2 rest2 | _ -> - let suggestPossibleModules() = - modref.ModuleOrNamespaceType.ModulesAndNamespacesByDemangledName - |> Seq.filter (fun kv -> IsEntityAccessible ncenv.amap m ad (modref.NestedTyconRef kv.Value)) - |> Seq.collect (fun e -> [e.Value.DisplayName; e.Value.DemangledModuleOrNamespaceName]) - |> HashSet + let suggestPossibleModules (addToBuffer: string -> unit) = + for kv in modref.ModuleOrNamespaceType.ModulesAndNamespacesByDemangledName do + if IsEntityAccessible ncenv.amap m ad (modref.NestedTyconRef kv.Value) then + addToBuffer kv.Value.DisplayName + addToBuffer kv.Value.DemangledModuleOrNamespaceName + raze (UndefinedName(depth, FSComp.SR.undefinedNameNamespaceOrModule, id, suggestPossibleModules)) let tyconSearch = @@ -2906,10 +3036,9 @@ let rec private ResolveTypeLongIdentInModuleOrNamespace sink nenv (ncenv: NameRe match tcrefs with | _ :: _ -> tcrefs |> CollectResults (fun tcref -> ResolveTypeLongIdentInTyconRefPrim ncenv typeNameResInfo ad resInfo genOk (depth+1) m tcref id2 rest2) | [] -> - let suggestTypes() = - modref.ModuleOrNamespaceType.TypesByDemangledNameAndArity id.idRange - |> Seq.map (fun e -> e.Value.DisplayName) - |> HashSet + let suggestTypes (addToBuffer: string -> unit) = + for e in modref.ModuleOrNamespaceType.TypesByDemangledNameAndArity id.idRange do + addToBuffer e.Value.DisplayName raze (UndefinedName(depth, FSComp.SR.undefinedNameType, id, suggestTypes)) @@ -2922,7 +3051,7 @@ let rec ResolveTypeLongIdentPrim sink (ncenv: NameResolver) occurence first full match rest with | [] -> error (Error(FSComp.SR.nrGlobalUsedOnlyAsFirstName(), id.idRange)) - | id2::rest2 -> + | id2 :: rest2 -> ResolveTypeLongIdentPrim sink ncenv occurence false FullyQualified m nenv ad id2 rest2 staticResInfo genOk else match rest with @@ -2941,21 +3070,19 @@ let rec ResolveTypeLongIdentPrim sink (ncenv: NameResolver) occurence first full //CheckForTypeLegitimacyAndMultipleGenericTypeAmbiguities tcref rest typeNameResInfo m success(ResolutionInfo.Empty, tcref) | [] -> - let suggestPossibleTypes() = - nenv.TyconsByDemangledNameAndArity(fullyQualified) - |> Seq.filter (fun kv -> IsEntityAccessible ncenv.amap m ad kv.Value) - |> Seq.collect (fun e -> - match occurence with - | ItemOccurence.UseInAttribute -> - [yield e.Value.DisplayName - yield e.Value.DemangledModuleOrNamespaceName - if e.Value.DisplayName.EndsWithOrdinal("Attribute") then - yield e.Value.DisplayName.Replace("Attribute", "")] - | _ -> [e.Value.DisplayName; e.Value.DemangledModuleOrNamespaceName]) - |> HashSet + let suggestPossibleTypes (addToBuffer: string -> unit) = + for kv in nenv.TyconsByDemangledNameAndArity fullyQualified do + if IsEntityAccessible ncenv.amap m ad kv.Value then + addToBuffer kv.Value.DisplayName + addToBuffer kv.Value.DemangledModuleOrNamespaceName + match occurence with + | ItemOccurence.UseInAttribute -> + if kv.Value.DisplayName.EndsWithOrdinal("Attribute") then + addToBuffer (kv.Value.DisplayName.Replace("Attribute", "")) + | _ -> () raze (UndefinedName(0, FSComp.SR.undefinedNameType, id, suggestPossibleTypes)) - | id2::rest2 -> + | id2 :: rest2 -> let m2 = unionRanges m id.idRange let tyconSearch = match fullyQualified with @@ -3007,7 +3134,7 @@ let ResolveTypeLongIdent sink (ncenv: NameResolver) occurence fullyQualified nen match lid with | [] -> error(Error(FSComp.SR.nrUnexpectedEmptyLongId(), m)) - | id::rest -> + | id :: rest -> ResolveTypeLongIdentPrim sink ncenv occurence true fullyQualified m nenv ad id rest staticResInfo genOk // Register the result as a name resolution @@ -3015,7 +3142,7 @@ let ResolveTypeLongIdent sink (ncenv: NameResolver) occurence fullyQualified nen | 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, item, emptyTyparInst, occurence, nenv.eDisplayEnv, ad) + CallNameResolutionSink sink (m, nenv, item, emptyTyparInst, occurence, ad) | _ -> () res |?> snd @@ -3038,7 +3165,7 @@ let rec ResolveFieldInModuleOrNamespace (ncenv: NameResolver) nenv ad (resInfo: // search for type-qualified names, e.g. { Microsoft.FSharp.Core.Ref.contents = 1 } let tyconSearch() = match rest with - | id2::rest2 -> + | id2 :: rest2 -> let tcrefs = LookupTypeNameInEntityMaybeHaveArity (ncenv.amap, id.idRange, ad, id.idText, TypeNameResolutionStaticArgsInfo.Indefinite, modref) if isNil tcrefs then NoResultsOrUsefulErrors else let tcrefs = tcrefs |> List.map (fun tcref -> (ResolutionInfo.Empty, tcref)) @@ -3052,7 +3179,7 @@ let rec ResolveFieldInModuleOrNamespace (ncenv: NameResolver) nenv ad (resInfo: // search for names in nested modules, e.g. { Microsoft.FSharp.Core.contents = 1 } let modulSearch() = match rest with - | id2::rest2 -> + | id2 :: rest2 -> match modref.ModuleOrNamespaceType.ModulesAndNamespacesByDemangledName.TryGetValue id.idText with | true, AccessibleEntityRef ncenv.amap m ad modref submodref -> let resInfo = resInfo.AddEntity(id.idRange, submodref) @@ -3077,9 +3204,9 @@ let SuggestOtherLabelsOfSameRecordType g (nenv: NameResolutionEnv) ty (id: Ident labelsOfPossibleRecord let SuggestLabelsOfRelatedRecords g (nenv: NameResolutionEnv) (id: Ident) (allFields: Ident list) = - let suggestLabels() = + let suggestLabels (addToBuffer: string -> unit) = let givenFields = allFields |> List.map (fun fld -> fld.idText) |> List.filter ((<>) id.idText) |> HashSet - let fullyQualfied = + let fullyQualified = if givenFields.Count = 0 then // return labels from all records let result = NameMap.domainL nenv.eFieldLabels |> HashSet @@ -3109,21 +3236,15 @@ let SuggestLabelsOfRelatedRecords g (nenv: NameResolutionEnv) (id: Ident) (allFi labelsOfPossibleRecords.ExceptWith givenFields labelsOfPossibleRecords - if fullyQualfied.Count > 0 then fullyQualfied else - - // check if the user forgot to use qualified access - nenv.eTyconsByDemangledNameAndArity - |> Seq.choose (fun e -> - let hasRequireQualifiedAccessAttribute = HasFSharpAttribute g g.attrib_RequireQualifiedAccessAttribute e.Value.Attribs - if not hasRequireQualifiedAccessAttribute then - None - else - if e.Value.IsRecordTycon && e.Value.AllFieldsArray |> Seq.exists (fun x -> x.Name = id.idText) then - Some e.Value - else - None) - |> Seq.map (fun t -> t.DisplayName + "." + id.idText) - |> HashSet + if fullyQualified.Count > 0 then + fullyQualified |> Seq.iter addToBuffer + else + // check if the user forgot to use qualified access + for e in nenv.eTyconsByDemangledNameAndArity do + let hasRequireQualifiedAccessAttribute = HasFSharpAttribute g g.attrib_RequireQualifiedAccessAttribute e.Value.Attribs + if hasRequireQualifiedAccessAttribute then + if e.Value.IsRecordTycon && e.Value.AllFieldsArray |> Seq.exists (fun x -> x.Name = id.idText) then + addToBuffer (e.Value.DisplayName + "." + id.idText) UndefinedName(0, FSComp.SR.undefinedNameRecordLabel, id, suggestLabels) @@ -3146,19 +3267,23 @@ let ResolveFieldPrim sink (ncenv: NameResolver) nenv ad ty (mp, id: Ident) allFi |> ListSet.setify (fun fref1 fref2 -> tyconRefEq g fref1.TyconRef fref2.TyconRef) |> List.map (fun x -> ResolutionInfo.Empty, FieldResolution(x, false)) - if isAppTy g ty then + match tryTcrefOfAppTy g ty with + | ValueSome tcref -> match ncenv.InfoReader.TryFindRecdOrClassFieldInfoOfType(id.idText, m, ty) with | ValueSome (RecdFieldInfo(_, rfref)) -> [ResolutionInfo.Empty, FieldResolution(rfref, false)] | _ -> - if isRecdTy g ty then + if tcref.IsRecordTycon then // record label doesn't belong to record type -> suggest other labels of same record - let suggestLabels() = SuggestOtherLabelsOfSameRecordType g nenv ty id allFields + let suggestLabels (addToBuffer: string -> unit) = + for label in SuggestOtherLabelsOfSameRecordType g nenv ty id allFields do + addToBuffer label + let typeName = NicePrint.minimalStringOfType nenv.eDisplayEnv ty let errorText = FSComp.SR.nrRecordDoesNotContainSuchLabel(typeName, id.idText) error(ErrorWithSuggestions(errorText, m, id.idText, suggestLabels)) else lookup() - else + | _ -> lookup() | _ -> let lid = (mp@[id]) @@ -3178,7 +3303,7 @@ let ResolveFieldPrim sink (ncenv: NameResolver) nenv ad ty (mp, id: Ident) allFi let modulSearch ad () = match lid with | [] -> NoResultsOrUsefulErrors - | id2::rest2 -> + | id2 :: rest2 -> ResolveLongIndentAsModuleOrNamespaceThen sink ResultCollectionSettings.AtMostOneResult ncenv.amap m OpenQualified nenv ad id2 rest2 false (ResolveFieldInModuleOrNamespace ncenv nenv ad) @@ -3218,8 +3343,8 @@ let FreshenRecdFieldRef (ncenv: NameResolver) m (rfref: RecdFieldRef) = // QUERY (instantiationGenerator cleanup): it would be really nice not to flow instantiationGenerator to here. let private ResolveExprDotLongIdent (ncenv: NameResolver) m ad nenv ty (id: Ident) rest findFlag = let typeNameResInfo = TypeNameResolutionInfo.Default - let adhoctDotSearchAccessible = AtMostOneResult m (ResolveLongIdentInTypePrim ncenv nenv LookupKind.Expr ResolutionInfo.Empty 1 m ad id rest findFlag typeNameResInfo ty) - match adhoctDotSearchAccessible with + let adhocDotSearchAccessible = AtMostOneResult m (ResolveLongIdentInTypePrim ncenv nenv LookupKind.Expr ResolutionInfo.Empty 1 m ad id rest findFlag typeNameResInfo ty) + match adhocDotSearchAccessible with | Exception _ -> // If the dot is not resolved by adhoc overloading then look for a record field // that can resolve the name. @@ -3242,7 +3367,7 @@ let private ResolveExprDotLongIdent (ncenv: NameResolver) m ad nenv ty (id: Iden |> AtMostOneResult m |> ForceRaise | _ -> - ForceRaise adhoctDotSearchAccessible + ForceRaise adhocDotSearchAccessible let ComputeItemRange wholem (lid: Ident list) rest = match rest with @@ -3296,7 +3421,7 @@ let ResolveLongIdentAsExprAndComputeRange (sink: TcResultsSink) (ncenv: NameReso match item1, item with | Item.MethodGroup(name, minfos1, _), Item.MethodGroup(_, [], _) when not (isNil minfos1) -> - error(Error(FSComp.SR.methodIsNotStatic(name), wholem)) + error(Error(FSComp.SR.methodIsNotStatic name, wholem)) | _ -> () // Fake idents e.g. 'Microsoft.FSharp.Core.None' have identical ranges for each part @@ -3304,7 +3429,7 @@ let ResolveLongIdentAsExprAndComputeRange (sink: TcResultsSink) (ncenv: NameReso match lid with | [] | [_] -> false | head :: ids -> - ids |> List.forall (fun id -> id.idRange = head.idRange) + ids |> List.forall (fun id -> Range.equals id.idRange head.idRange) let callSink (refinedItem, tpinst) = if not isFakeIdents then @@ -3316,7 +3441,7 @@ let ResolveLongIdentAsExprAndComputeRange (sink: TcResultsSink) (ncenv: NameReso | Item.ActivePatternResult _ -> ItemOccurence.Binding | _ -> ItemOccurence.Use - CallNameResolutionSink sink (itemRange, nenv, refinedItem, item, tpinst, occurence, nenv.DisplayEnv, ad) + CallMethodGroupNameResolutionSink sink (itemRange, nenv, refinedItem, item, tpinst, occurence, ad) let callSinkWithSpecificOverload (minfo: MethInfo, pinfoOpt: PropInfo option, tpinst) = let refinedItem = @@ -3353,7 +3478,7 @@ let ResolveExprDotLongIdentAndComputeRange (sink: TcResultsSink) (ncenv: NameRes let resolveExpr findFlag = let resInfo, item, rest = match lid with - | id::rest -> + | id :: rest -> ResolveExprDotLongIdent ncenv wholem ad nenv ty id rest findFlag | _ -> error(InternalError("ResolveExprDotLongIdentAndComputeRange", wholem)) let itemRange = ComputeItemRange wholem lid rest @@ -3380,7 +3505,7 @@ let ResolveExprDotLongIdentAndComputeRange (sink: TcResultsSink) (ncenv: NameRes let staticOnly = thisIsActuallyATyAppNotAnExpr let refinedItem = FilterMethodGroups ncenv itemRange refinedItem staticOnly let unrefinedItem = FilterMethodGroups ncenv itemRange unrefinedItem staticOnly - CallNameResolutionSink sink (itemRange, nenv, refinedItem, unrefinedItem, tpinst, ItemOccurence.Use, nenv.DisplayEnv, ad) + CallMethodGroupNameResolutionSink sink (itemRange, nenv, refinedItem, unrefinedItem, tpinst, ItemOccurence.Use, ad) let callSinkWithSpecificOverload (minfo: MethInfo, pinfoOpt: PropInfo option, tpinst) = let refinedItem = @@ -3455,7 +3580,10 @@ let ItemOfTyconRef ncenv m (x: TyconRef) = Item.Types (x.DisplayName, [FreshenTycon ncenv m x]) let ItemOfTy g x = - let nm = if isAppTy g x then (tcrefOfAppTy g x).DisplayName else "?" + let nm = + match tryTcrefOfAppTy g x with + | ValueSome tcref -> tcref.DisplayName + | _ -> "?" Item.Types (nm, [x]) // Filter out 'PrivateImplementationDetail' classes @@ -3465,14 +3593,14 @@ let rec PartialResolveLookupInModuleOrNamespaceAsModuleOrNamespaceThen f plid (m let mty = modref.ModuleOrNamespaceType match plid with | [] -> f modref - | id:: rest -> + | id :: rest -> match mty.ModulesAndNamespacesByDemangledName.TryGetValue id with | true, mty -> PartialResolveLookupInModuleOrNamespaceAsModuleOrNamespaceThen f rest (modref.NestedTyconRef mty) | _ -> [] let PartialResolveLongIndentAsModuleOrNamespaceThen (nenv: NameResolutionEnv) plid f = match plid with - | id:: rest -> + | id :: rest -> match nenv.eModulesAndNamespaces.TryGetValue id with | true, modrefs -> List.collect (PartialResolveLookupInModuleOrNamespaceAsModuleOrNamespaceThen f rest) modrefs @@ -3538,7 +3666,7 @@ let ResolveCompletionsInType (ncenv: NameResolver) nenv (completionTargets: Reso IsILFieldInfoAccessible g amap m ad x) let pinfosIncludingUnseen = - AllPropInfosOfTypeInScope ncenv.InfoReader nenv (None, ad) PreferOverrides m ty + AllPropInfosOfTypeInScope ResultCollectionSettings.AllResults ncenv.InfoReader nenv None ad PreferOverrides m ty |> List.filter (fun x -> x.IsStatic = statics && IsPropInfoAccessible g amap m ad x) @@ -3623,13 +3751,13 @@ let ResolveCompletionsInType (ncenv: NameResolver) nenv (completionTargets: Reso |> List.choose (fun pinfo-> let pinfoOpt = DecodeFSharpEvent [pinfo] ad g ncenv m match pinfoOpt, completionTargets with - | Some(Item.Event(einfo)), ResolveCompletionTargets.All _ -> if IsStandardEventInfo ncenv.InfoReader m ad einfo then pinfoOpt else None + | Some(Item.Event einfo), ResolveCompletionTargets.All _ -> if IsStandardEventInfo ncenv.InfoReader m ad einfo then pinfoOpt else None | _ -> pinfoOpt) // REVIEW: add a name filter here in the common cases? let minfos = if completionTargets.ResolveAll then - let minfos = AllMethInfosOfTypeInScope ncenv.InfoReader nenv (None, ad) PreferOverrides m ty + let minfos = AllMethInfosOfTypeInScope ResultCollectionSettings.AllResults ncenv.InfoReader nenv None ad PreferOverrides m ty if isNil minfos then [] else @@ -3670,7 +3798,7 @@ let ResolveCompletionsInType (ncenv: NameResolver) nenv (completionTargets: Reso if methsWithStaticParams.IsEmpty then minfos else minfos |> List.filter (fun minfo -> let nm = minfo.LogicalName - not (nm.Contains "," && methsWithStaticParams |> List.exists (fun m -> nm.StartsWithOrdinal(m)))) + not (nm.Contains "," && methsWithStaticParams |> List.exists (fun m -> nm.StartsWithOrdinal m))) #endif minfos @@ -3682,7 +3810,7 @@ let ResolveCompletionsInType (ncenv: NameResolver) nenv (completionTargets: Reso let rec partitionl (l: MethInfo list) acc = match l with | [] -> acc - | h::t -> + | h :: t -> let nm = h.LogicalName partitionl t (NameMultiMap.add nm h acc) @@ -3731,7 +3859,7 @@ let rec ResolvePartialLongIdentInType (ncenv: NameResolver) nenv isApplicableMet rty (ty - |> AllPropInfosOfTypeInScope ncenv.InfoReader nenv (Some id, ad) IgnoreOverrides m + |> AllPropInfosOfTypeInScope ResultCollectionSettings.AllResults ncenv.InfoReader nenv (Some id) ad IgnoreOverrides m |> List.filter (fun pinfo -> pinfo.IsStatic = statics && IsPropInfoAccessible g amap m ad pinfo) |> List.collect (fun pinfo -> (FullTypeOfPinfo pinfo) |> ResolvePartialLongIdentInType ncenv nenv isApplicableMeth m ad false rest)) @ @@ -4025,6 +4153,7 @@ let rec ResolvePartialLongIdentPrim (ncenv: NameResolver) (nenv: NameResolutionE ResolvePartialLongIdentInModuleOrNamespace ncenv nenv isApplicableMeth m ad modref rest allowObsolete else []) + // Look for values called 'id' that accept the dot-notation let values, isItemVal = (match nenv.eUnqualifiedItems.TryGetValue id with @@ -4038,7 +4167,7 @@ let rec ResolvePartialLongIdentPrim (ncenv: NameResolver) (nenv: NameResolutionE | _ -> [], false | _ -> [], false) - let staticSometingInType = + let staticSomethingInType = [ if not isItemVal then // type.lookup: lookup a static something in a type for tcref in LookupTypeNameInEnvNoArity OpenQualified id nenv do @@ -4046,7 +4175,7 @@ let rec ResolvePartialLongIdentPrim (ncenv: NameResolver) (nenv: NameResolutionE let ty = FreshenTycon ncenv m tcref yield! ResolvePartialLongIdentInType ncenv nenv isApplicableMeth m ad true rest ty ] - namespaces @ values @ staticSometingInType + namespaces @ values @ staticSomethingInType /// Resolve a (possibly incomplete) long identifier to a set of possible resolutions. let ResolvePartialLongIdent ncenv nenv isApplicableMeth m ad plid allowObsolete = @@ -4176,7 +4305,7 @@ and ResolvePartialLongIdentToClassOrRecdFieldsImpl (ncenv: NameResolver) (nenv: mods @ recdTyCons @ recdFields - | id::rest -> + | id :: rest -> // Get results let modsOrNs = PartialResolveLongIndentAsModuleOrNamespaceThen nenv [id] (fun modref -> @@ -4185,6 +4314,7 @@ and ResolvePartialLongIdentToClassOrRecdFieldsImpl (ncenv: NameResolver) (nenv: ResolvePartialLongIdentInModuleOrNamespaceForRecordFields ncenv nenv m ad modref rest allowObsolete else []) + let qualifiedFields = match rest with | [] -> @@ -4245,7 +4375,7 @@ let ResolveCompletionsInTypeForItem (ncenv: NameResolver) nenv m ad statics ty ( | _ -> () let pinfosIncludingUnseen = - AllPropInfosOfTypeInScope ncenv.InfoReader nenv (None, ad) PreferOverrides m ty + AllPropInfosOfTypeInScope ResultCollectionSettings.AllResults ncenv.InfoReader nenv None ad PreferOverrides m ty |> List.filter (fun x -> x.IsStatic = statics && IsPropInfoAccessible g amap m ad x) @@ -4331,7 +4461,7 @@ let ResolveCompletionsInTypeForItem (ncenv: NameResolver) nenv m ad statics ty ( | Item.MethodGroup _ -> // REVIEW: add a name filter here in the common cases? let minfos = - let minfos = AllMethInfosOfTypeInScope ncenv.InfoReader nenv (None, ad) PreferOverrides m ty + let minfos = AllMethInfosOfTypeInScope ResultCollectionSettings.AllResults ncenv.InfoReader nenv None ad PreferOverrides m ty if isNil minfos then [] else let suppressedMethNames = Zset.ofList String.order (pinfoMethNames @ einfoMethNames) @@ -4370,7 +4500,7 @@ let ResolveCompletionsInTypeForItem (ncenv: NameResolver) nenv m ad statics ty ( if methsWithStaticParams.IsEmpty then minfos else minfos |> List.filter (fun minfo -> let nm = minfo.LogicalName - not (nm.Contains "," && methsWithStaticParams |> List.exists (fun m -> nm.StartsWithOrdinal(m)))) + not (nm.Contains "," && methsWithStaticParams |> List.exists (fun m -> nm.StartsWithOrdinal m))) #endif minfos @@ -4379,7 +4509,7 @@ let ResolveCompletionsInTypeForItem (ncenv: NameResolver) nenv m ad statics ty ( let rec partitionl (l: MethInfo list) acc = match l with | [] -> acc - | h::t -> + | h :: t -> let nm = h.LogicalName partitionl t (NameMultiMap.add nm h acc) @@ -4414,7 +4544,7 @@ let rec ResolvePartialLongIdentInTypeForItem (ncenv: NameResolver) nenv m ad sta let pinfos = ty - |> AllPropInfosOfTypeInScope ncenv.InfoReader nenv (Some id, ad) IgnoreOverrides m + |> AllPropInfosOfTypeInScope ResultCollectionSettings.AllResults ncenv.InfoReader nenv (Some id) ad IgnoreOverrides m |> List.filter (fun pinfo -> pinfo.IsStatic = statics && IsPropInfoAccessible g amap m ad pinfo) for pinfo in pinfos do diff --git a/src/fcs-fable/src/fsharp/NameResolution.fsi b/src/fcs-fable/src/fsharp/NameResolution.fsi index c887aad2fd..685871c056 100755 --- a/src/fcs-fable/src/fsharp/NameResolution.fsi +++ b/src/fcs-fable/src/fsharp/NameResolution.fsi @@ -2,18 +2,19 @@ module internal FSharp.Compiler.NameResolution -open FSharp.Compiler +open FSharp.Compiler open FSharp.Compiler.AccessibilityLogic -open FSharp.Compiler.Ast +open FSharp.Compiler.SyntaxTree open FSharp.Compiler.Infos open FSharp.Compiler.Range open FSharp.Compiler.Import open FSharp.Compiler.InfoReader -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.Text /// A NameResolver is a context for name resolution. It primarily holds an InfoReader. type NameResolver = @@ -21,6 +22,7 @@ type NameResolver = member InfoReader : InfoReader member amap : ImportMap member g : TcGlobals + member languageSupportsNameOf : bool /// Get the active pattern elements defined in a module, if any. Cache in the slot in the module type. val ActivePatternElemsOfModuleOrNamespace : ModuleOrNamespaceRef -> NameMap @@ -30,14 +32,8 @@ val ActivePatternElemsOfModuleOrNamespace : ModuleOrNamespaceRef -> NameMap ItemWithInst type FieldResolution = FieldResolution of RecdFieldRef * bool /// Information about an extension member held in the name resolution environment -[] -type ExtensionMember +type ExtensionMember = + /// F#-style Extrinsic extension member, defined in F# code + | FSExtMem of ValRef * ExtensionMethodPriority + + /// ILExtMem(declaringTyconRef, ilMetadata, pri) + /// + /// IL-style extension member, backed by some kind of method with an [] attribute + | ILExtMem of TyconRef * MethInfo * ExtensionMethodPriority + + /// Describes the sequence order of the introduction of an extension method. Extension methods that are introduced + /// later through 'open' get priority in overload resolution. + member Priority : ExtensionMethodPriority /// The environment of information used to resolve names [] type NameResolutionEnv = - {eDisplayEnv: DisplayEnv - eUnqualifiedItems: LayeredMap - ePatItems: NameMap - eModulesAndNamespaces: NameMultiMap - eFullyQualifiedModulesAndNamespaces: NameMultiMap - eFieldLabels: NameMultiMap - eTyconsByAccessNames: LayeredMultiMap - eFullyQualifiedTyconsByAccessNames: LayeredMultiMap - eTyconsByDemangledNameAndArity: LayeredMap - eFullyQualifiedTyconsByDemangledNameAndArity: LayeredMap - eIndexedExtensionMembers: TyconRefMultiMap - eUnindexedExtensionMembers: ExtensionMember list - eTypars: NameMap } + { /// Display environment information for output + eDisplayEnv: DisplayEnv + + /// Values and Data Tags available by unqualified name + eUnqualifiedItems: LayeredMap + + /// Data Tags and Active Pattern Tags available by unqualified name + ePatItems: NameMap + + /// Modules accessible via "." notation. Note this is a multi-map. + /// Adding a module abbreviation adds it a local entry to this List.map. + /// Likewise adding a ccu or opening a path adds entries to this List.map. + eModulesAndNamespaces: NameMultiMap + + /// Fully qualified modules and namespaces. 'open' does not change this. + eFullyQualifiedModulesAndNamespaces: NameMultiMap + + /// RecdField labels in scope. RecdField labels are those where type are inferred + /// by label rather than by known type annotation. + /// Bools indicate if from a record, where no warning is given on indeterminate lookup + eFieldLabels: NameMultiMap + + /// Tycons indexed by the various names that may be used to access them, e.g. + /// "List" --> multiple TyconRef's for the various tycons accessible by this name. + /// "List`1" --> TyconRef + eTyconsByAccessNames: LayeredMultiMap + + eFullyQualifiedTyconsByAccessNames: LayeredMultiMap + + /// Tycons available by unqualified, demangled names (i.e. (List,1) --> TyconRef) + eTyconsByDemangledNameAndArity: LayeredMap + + /// Tycons available by unqualified, demangled names (i.e. (List,1) --> TyconRef) + eFullyQualifiedTyconsByDemangledNameAndArity: LayeredMap + + /// Extension members by type and name + eIndexedExtensionMembers: TyconRefMultiMap + + /// Other extension members unindexed by type + eUnindexedExtensionMembers: ExtensionMember list + + /// Typars (always available by unqualified names). Further typars can be + /// in the tpenv, a structure folded through each top-level definition. + eTypars: NameMap + + } static member Empty : g:TcGlobals -> NameResolutionEnv member DisplayEnv : DisplayEnv member FindUnqualifiedItem : string -> Item @@ -185,7 +227,7 @@ val internal AddValRefToNameEnv : NameResolutionEnv -> ValRef val internal AddActivePatternResultTagsToNameEnv : ActivePatternInfo -> NameResolutionEnv -> TType -> range -> NameResolutionEnv /// Add a list of type definitions to the name resolution environment -val internal AddTyconRefsToNameEnv : BulkAdd -> bool -> TcGlobals -> ImportMap -> range -> bool -> NameResolutionEnv -> TyconRef list -> NameResolutionEnv +val internal AddTyconRefsToNameEnv : BulkAdd -> bool -> TcGlobals -> ImportMap -> AccessorDomain -> range -> bool -> NameResolutionEnv -> TyconRef list -> NameResolutionEnv /// Add an F# exception definition to the name resolution environment val internal AddExceptionDeclsToNameEnv : BulkAdd -> NameResolutionEnv -> TyconRef -> NameResolutionEnv @@ -200,7 +242,7 @@ val internal AddModuleOrNamespaceRefsToNameEnv : TcGlobals -> val internal AddModuleOrNamespaceRefToNameEnv : TcGlobals -> ImportMap -> range -> bool -> AccessorDomain -> NameResolutionEnv -> ModuleOrNamespaceRef -> NameResolutionEnv /// Add a list of modules or namespaces to the name resolution environment -val internal AddModulesAndNamespacesContentsToNameEnv : TcGlobals -> ImportMap -> AccessorDomain -> range -> bool -> NameResolutionEnv -> ModuleOrNamespaceRef list -> NameResolutionEnv +val internal AddEntitiesContentsToNameEnv : TcGlobals -> ImportMap -> AccessorDomain -> range -> bool -> NameResolutionEnv -> ModuleOrNamespaceRef list -> NameResolutionEnv /// A flag which indicates if it is an error to have two declared type parameters with identical names /// in the name resolution environment. @@ -292,12 +334,14 @@ type internal TcResolutions = /// Information of exact types found for expressions, that can be to the left of a dot. /// typ - the inferred type for an expression - member CapturedExpressionTypings : ResizeArray + member CapturedExpressionTypings : ResizeArray /// Exact name resolutions member CapturedNameResolutions : ResizeArray - /// Represents all the resolutions of names to groups of methods. + /// Represents additional resolutions of names to groups of methods. + /// CapturedNameResolutions should be checked when no captured method group is found. + /// See TypeCheckInfo.GetCapturedNameResolutions for example. member CapturedMethodGroupResolutions : ResizeArray /// Represents the empty set of resolutions @@ -324,9 +368,12 @@ type internal TcSymbolUses = /// Get the locations of all the printf format specifiers in the file member GetFormatSpecifierLocationsAndArity : unit -> (range * int)[] + /// Empty collection of symbol uses + static member Empty : TcSymbolUses + /// Represents open declaration statement. type internal OpenDeclaration = - { /// Long identifier as it's presented in soruce code. + { /// Long identifier as it's presented in source code. LongId: Ident list /// Full range of the open declaration. @@ -347,7 +394,7 @@ type internal OpenDeclaration = /// Source text and an array of line end positions, used for format string parsing type FormatStringCheckContext = { /// Source text - Source: string + SourceText: ISourceText /// Array of line start positions LineStartPositions: int[] } @@ -358,10 +405,13 @@ type ITypecheckResultsSink = abstract NotifyEnvWithScope : range * NameResolutionEnv * AccessorDomain -> unit /// Record that an expression has a specific type at the given range. - abstract NotifyExprHasType : pos * TType * DisplayEnv * NameResolutionEnv * AccessorDomain * range -> unit + abstract NotifyExprHasType : TType * NameResolutionEnv * AccessorDomain * range -> unit /// Record that a name resolution occurred at a specific location in the source - abstract NotifyNameResolution : pos * Item * Item * TyparInst * ItemOccurence * DisplayEnv * NameResolutionEnv * AccessorDomain * range * bool -> unit + abstract NotifyNameResolution : pos * Item * TyparInst * ItemOccurence * NameResolutionEnv * AccessorDomain * range * bool -> unit + + /// Record that a method group name resolution occurred at a specific location in the source + abstract NotifyMethodGroupNameResolution : pos * Item * Item * TyparInst * ItemOccurence * NameResolutionEnv * AccessorDomain * range * bool -> unit /// Record that a printf format specifier occurred at a specific location in the source abstract NotifyFormatSpecifierLocation : range * int -> unit @@ -370,7 +420,7 @@ type ITypecheckResultsSink = abstract NotifyOpenDeclaration : OpenDeclaration -> unit /// Get the current source - abstract CurrentSource : string option + abstract CurrentSourceText : ISourceText option /// Cached line-end normalized source text and an array of line end positions, used for format string parsing abstract FormatStringCheckContext : FormatStringCheckContext option @@ -379,7 +429,7 @@ type ITypecheckResultsSink = type internal TcResultsSinkImpl = /// Create a TcResultsSinkImpl - new : tcGlobals : TcGlobals * ?source:string -> TcResultsSinkImpl + new : tcGlobals : TcGlobals * ?sourceText: ISourceText -> TcResultsSinkImpl /// Get all the resolutions reported to the sink member GetResolutions : unit -> TcResolutions @@ -390,6 +440,9 @@ type internal TcResultsSinkImpl = /// Get all open declarations reported to the sink member GetOpenDeclarations : unit -> OpenDeclaration[] + /// Get the format specifier locations + member GetFormatSpecifierLocations : unit -> (range * int)[] + interface ITypecheckResultsSink /// An abstract type for reporting the results of name resolution and type checking, and which allows @@ -399,6 +452,13 @@ type TcResultsSink = static member NoSink : TcResultsSink static member WithSink : ITypecheckResultsSink -> TcResultsSink + +/// Indicates if we only need one result or all possible results from a resolution. +[] +type ResultCollectionSettings = + | AllResults + | AtMostOneResult + /// Temporarily redirect reporting of name resolution and type checking results val internal WithNewTypecheckResultsSink : ITypecheckResultsSink * TcResultsSink -> System.IDisposable @@ -409,25 +469,28 @@ val internal TemporarilySuspendReportingTypecheckResultsToSink : TcResultsSink - val internal CallEnvSink : TcResultsSink -> range * NameResolutionEnv * AccessorDomain -> unit /// Report a specific name resolution at a source range -val internal CallNameResolutionSink : TcResultsSink -> range * NameResolutionEnv * Item * Item * TyparInst * ItemOccurence * DisplayEnv * AccessorDomain -> unit +val internal CallNameResolutionSink : TcResultsSink -> range * NameResolutionEnv * Item * TyparInst * ItemOccurence * AccessorDomain -> unit + +/// Report a specific method group name resolution at a source range +val internal CallMethodGroupNameResolutionSink : TcResultsSink -> range * NameResolutionEnv * Item * Item * TyparInst * ItemOccurence * AccessorDomain -> unit /// Report a specific name resolution at a source range, replacing any previous resolutions -val internal CallNameResolutionSinkReplacing : TcResultsSink -> range * NameResolutionEnv * Item * Item * TyparInst * ItemOccurence * DisplayEnv * AccessorDomain -> unit +val internal CallNameResolutionSinkReplacing : TcResultsSink -> range * NameResolutionEnv * Item * TyparInst * ItemOccurence * AccessorDomain -> unit /// Report a specific name resolution at a source range -val internal CallExprHasTypeSink : TcResultsSink -> range * NameResolutionEnv * TType * DisplayEnv * AccessorDomain -> unit +val internal CallExprHasTypeSink : TcResultsSink -> range * NameResolutionEnv * TType * AccessorDomain -> unit /// Report an open declaration val internal CallOpenDeclarationSink : TcResultsSink -> OpenDeclaration -> unit /// Get all the available properties of a type (both intrinsic and extension) -val internal AllPropInfosOfTypeInScope : InfoReader -> NameResolutionEnv -> string option * AccessorDomain -> FindMemberFlag -> range -> TType -> PropInfo list +val internal AllPropInfosOfTypeInScope : ResultCollectionSettings -> InfoReader -> NameResolutionEnv -> string option -> AccessorDomain -> FindMemberFlag -> range -> TType -> PropInfo list /// Get all the available properties of a type (only extension) -val internal ExtensionPropInfosOfTypeInScope : InfoReader -> NameResolutionEnv -> string option * AccessorDomain -> range -> TType -> PropInfo list +val internal ExtensionPropInfosOfTypeInScope : ResultCollectionSettings -> InfoReader -> NameResolutionEnv -> string option -> AccessorDomain -> range -> TType -> PropInfo list /// Get the available methods of a type (both declared and inherited) -val internal AllMethInfosOfTypeInScope : InfoReader -> NameResolutionEnv -> string option * AccessorDomain -> FindMemberFlag -> range -> TType -> MethInfo list +val internal AllMethInfosOfTypeInScope : ResultCollectionSettings -> InfoReader -> NameResolutionEnv -> string option -> AccessorDomain -> FindMemberFlag -> range -> TType -> MethInfo list /// Used to report an error condition where name resolution failed due to an indeterminate type exception internal IndeterminateType of range @@ -436,7 +499,7 @@ exception internal IndeterminateType of range exception internal UpperCaseIdentifierInPattern of range /// Generate a new reference to a record field with a fresh type instantiation -val FreshenRecdFieldRef :NameResolver -> Range.range -> Tast.RecdFieldRef -> Item +val FreshenRecdFieldRef :NameResolver -> Range.range -> RecdFieldRef -> Item /// Indicates the kind of lookup being performed. Note, this type should be made private to nameres.fs. [] @@ -460,14 +523,8 @@ type PermitDirectReferenceToGeneratedType = | Yes | No -/// Indicates if we only need one result or all possible results from a resolution. -[] -type ResultCollectionSettings = -| AllResults -| AtMostOneResult - -/// Resolve a long identifier to a namespace or module. -val internal ResolveLongIndentAsModuleOrNamespace : TcResultsSink -> ResultCollectionSettings -> Import.ImportMap -> range -> bool -> FullyQualifiedFlag -> NameResolutionEnv -> AccessorDomain -> Ident -> Ident list -> isOpenDecl: bool -> ResultOrException<(int * ModuleOrNamespaceRef * ModuleOrNamespaceType) list > +/// Resolve a long identifier to a namespace, module or static class. +val internal ResolveLongIndentAsModuleOrNamespaceOrStaticClass : TcResultsSink -> ResultCollectionSettings -> Import.ImportMap -> range -> allowStaticClasses: bool -> first: bool -> FullyQualifiedFlag -> NameResolutionEnv -> AccessorDomain -> Ident -> Ident list -> isOpenDecl: bool -> ResultOrException<(int * ModuleOrNamespaceRef * ModuleOrNamespaceType) list > /// Resolve a long identifier to an object constructor. val internal ResolveObjectConstructor : NameResolver -> DisplayEnv -> range -> AccessorDomain -> TType -> ResultOrException @@ -539,3 +596,6 @@ val ResolveCompletionsInType : NameResolver -> NameResolutionEnv -> Resolv val GetVisibleNamespacesAndModulesAtPoint : NameResolver -> NameResolutionEnv -> range -> AccessorDomain -> ModuleOrNamespaceRef list val IsItemResolvable : NameResolver -> NameResolutionEnv -> range -> AccessorDomain -> string list -> Item -> bool + +val TrySelectExtensionMethInfoOfILExtMem : range -> ImportMap -> TType -> TyconRef * MethInfo * ExtensionMethodPriority -> MethInfo option + \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/NicePrint.fs b/src/fcs-fable/src/fsharp/NicePrint.fs old mode 100755 new mode 100644 index c718bf9105..84b2904ad5 --- a/src/fcs-fable/src/fsharp/NicePrint.fs +++ b/src/fcs-fable/src/fsharp/NicePrint.fs @@ -1,39 +1,41 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -//-------------------------------------------------------------------------- -// Print Signatures/Types, for signatures, intellisense, quick info, FSI responses -//-------------------------------------------------------------------------- - +/// Print Signatures/Types, for signatures, intellisense, quick info, FSI responses module internal FSharp.Compiler.NicePrint +open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler -open FSharp.Compiler.Rational -open FSharp.Compiler.Ast +open FSharp.Compiler.AttributeChecking open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Lib open FSharp.Compiler.Infos open FSharp.Compiler.InfoReader -open FSharp.Compiler.AttributeChecking open FSharp.Compiler.Layout open FSharp.Compiler.Layout.TaggedTextOps +open FSharp.Compiler.Lib open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.Rational +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps -open Microsoft.FSharp.Core.Printf +open FSharp.Core.Printf [] module internal PrintUtilities = let bracketIfL x lyt = if x then bracketL lyt else lyt + let squareAngleL x = LeftL.leftBracketAngle ^^ x ^^ RightL.rightBracketAngle + let angleL x = sepL Literals.leftAngle ^^ x ^^ rightL Literals.rightAngle - let braceL x = leftL Literals.leftBrace ^^ x ^^ rightL Literals.rightBrace - let braceBarL x = leftL Literals.leftBraceBar ^^ x ^^ rightL Literals.rightBraceBar + + let braceL x = wordL Literals.leftBrace ^^ x ^^ wordL Literals.rightBrace + + let braceBarL x = wordL Literals.leftBraceBar ^^ x ^^ wordL Literals.rightBraceBar let comment str = wordL (tagText (sprintf "(* %s *)" str)) @@ -46,11 +48,10 @@ module internal PrintUtilities = let suppressInheritanceAndInterfacesForTyInSimplifiedDisplays g amap m ty = isEnumTy g ty || isDelegateTy g ty || ExistsHeadTypeInEntireHierarchy g amap m ty g.exn_tcr || ExistsHeadTypeInEntireHierarchy g amap m ty g.tcref_System_Attribute - - let applyMaxMembers maxMembers (alldecls: _ list) = + let applyMaxMembers maxMembers (allDecls: _ list) = match maxMembers with - | Some n when alldecls.Length > n -> (alldecls |> List.truncate n) @ [wordL (tagPunctuation "...")] - | _ -> alldecls + | Some n when allDecls.Length > n -> (allDecls |> List.truncate n) @ [wordL (tagPunctuation "...")] + | _ -> allDecls /// fix up a name coming from IL metadata by quoting "funny" names (keywords, otherwise invalid identifiers) let adjustILName n = @@ -60,7 +61,7 @@ module internal PrintUtilities = let shrinkOverloads layoutFunction resultFunction group = match group with | [x] -> [resultFunction x (layoutFunction x)] - | (x:: rest) -> [ resultFunction x (layoutFunction x -- leftL (tagText (match rest.Length with 1 -> FSComp.SR.nicePrintOtherOverloads1() | n -> FSComp.SR.nicePrintOtherOverloadsN(n)))) ] + | (x :: rest) -> [ resultFunction x (layoutFunction x -- leftL (tagText (match rest.Length with 1 -> FSComp.SR.nicePrintOtherOverloads1() | n -> FSComp.SR.nicePrintOtherOverloadsN(n)))) ] | _ -> [] let layoutTyconRefImpl isAttribute (denv: DisplayEnv) (tcref: TyconRef) = @@ -185,12 +186,12 @@ module private PrintIL = | ILType.Modified (_, _, t) -> layoutILType denv ilTyparSubst t // Just recurse through them to the contained ILType /// Layout a function pointer signature using type-only-F#-style. No argument names are printed. - and private layoutILCallingSignature denv ilTyparSubst cons (signatur: ILCallingSignature) = + and private layoutILCallingSignature denv ilTyparSubst cons (signature: ILCallingSignature) = // We need a special case for // constructors (Their return types are reported as `void`, but this is // incorrect; so if we're dealing with a constructor we require that the // return type be passed along as the `cons` parameter.) - let args = signatur.ArgTypes |> List.map (layoutILType denv ilTyparSubst) + let args = signature.ArgTypes |> List.map (layoutILType denv ilTyparSubst) let res = match cons with | Some className -> @@ -198,7 +199,7 @@ module private PrintIL = // special case for constructor return-type (viz., the class itself) layoutILTypeRefName denv names ^^ (pruneParams className ilTyparSubst |> paramsL) | None -> - signatur.ReturnType |> layoutILType denv ilTyparSubst + signature.ReturnType |> layoutILType denv ilTyparSubst match args with | [] -> WordL.structUnit ^^ WordL.arrow ^^ res @@ -566,7 +567,7 @@ module private PrintTypes = | Const.String bs -> "\"" + bs + "\"" |> tagNumericLiteral | Const.Unit -> "()" |> tagPunctuation | Const.Decimal bs -> string bs + "M" |> tagNumericLiteral - // either "null" or "the defaut value for a struct" + // either "null" or "the default value for a struct" | Const.Zero -> tagKeyword(if isRefTy g ty then "null" else "default") wordL str @@ -616,7 +617,7 @@ module private PrintTypes = /// See also dataExprL - there is overlap between these that should be removed let rec private layoutAttribArg denv arg = match arg with - | Expr.Const(c, _, ty) -> + | Expr.Const (c, _, ty) -> if isEnumTy denv.g ty then WordL.keywordEnum ^^ angleL (layoutType denv ty) ^^ bracketL (layoutConst denv.g ty c) else @@ -734,8 +735,8 @@ module private PrintTypes = | _ -> squareAngleL (sepListL (rightL (tagPunctuation ";")) (List.map (layoutAttrib denv) attrs)) @@ restL - elif Tastops.isStructRecordOrUnionTyconTy denv.g ty || - ((Tastops.isUnionTy denv.g ty || Tastops.isRecdTy denv.g ty) && HasFSharpAttribute denv.g denv.g.attrib_StructAttribute attrs) then + elif isStructRecordOrUnionTyconTy denv.g ty || + ((isUnionTy denv.g ty || isRecdTy denv.g ty) && HasFSharpAttribute denv.g denv.g.attrib_StructAttribute attrs) then squareAngleL (wordL (tagClass "Struct")) @@ restL else match kind with @@ -809,50 +810,62 @@ module private PrintTypes = match tpc with | TyparConstraint.CoercesTo(tpct, _) -> [layoutTyparRefWithInfo denv env tp ^^ wordL (tagOperator ":>") --- layoutTypeWithInfo denv env tpct] + | TyparConstraint.MayResolveMember(traitInfo, _) -> [layoutTraitWithInfo denv env traitInfo] + | TyparConstraint.DefaultsTo(_, ty, _) -> if denv.showTyparDefaultConstraints then [wordL (tagKeyword "default") ^^ layoutTyparRefWithInfo denv env tp ^^ WordL.colon ^^ layoutTypeWithInfo denv env ty] else [] + | TyparConstraint.IsEnum(ty, _) -> if denv.shortConstraints then [wordL (tagKeyword "enum")] else [longConstraintPrefix (layoutTypeAppWithInfoAndPrec denv env (wordL (tagKeyword "enum")) 2 true [ty])] + | TyparConstraint.SupportsComparison _ -> if denv.shortConstraints then [wordL (tagKeyword "comparison")] else [wordL (tagKeyword "comparison") |> longConstraintPrefix] + | TyparConstraint.SupportsEquality _ -> if denv.shortConstraints then [wordL (tagKeyword "equality")] else [wordL (tagKeyword "equality") |> longConstraintPrefix] + | TyparConstraint.IsDelegate(aty, bty, _) -> if denv.shortConstraints then [WordL.keywordDelegate] else [layoutTypeAppWithInfoAndPrec denv env (WordL.keywordDelegate) 2 true [aty;bty] |> longConstraintPrefix] + | TyparConstraint.SupportsNull _ -> [wordL (tagKeyword "null") |> longConstraintPrefix] + | TyparConstraint.IsNonNullableStruct _ -> if denv.shortConstraints then [wordL (tagText "value type")] else [WordL.keywordStruct |> longConstraintPrefix] + | TyparConstraint.IsUnmanaged _ -> if denv.shortConstraints then [wordL (tagKeyword "unmanaged")] else [wordL (tagKeyword "unmanaged") |> longConstraintPrefix] + | TyparConstraint.IsReferenceType _ -> if denv.shortConstraints then [wordL (tagText "reference type")] else [(wordL (tagKeyword "not") ^^ wordL(tagKeyword "struct")) |> longConstraintPrefix] + | TyparConstraint.SimpleChoice(tys, _) -> [bracketL (sepListL (sepL (tagPunctuation "|")) (List.map (layoutTypeWithInfo denv env) tys)) |> longConstraintPrefix] + | TyparConstraint.RequiresDefaultConstructor _ -> if denv.shortConstraints then [wordL (tagKeyword "default") ^^ wordL (tagKeyword "constructor")] @@ -937,12 +950,12 @@ module private PrintTypes = | TType_app (tc, args) -> layoutTypeAppWithInfoAndPrec denv env (layoutTyconRef denv tc) prec tc.IsPrefixDisplay args - | TType_ucase (UCRef(tc, _), args) -> + | TType_ucase (UnionCaseRef(tc, _), args) -> layoutTypeAppWithInfoAndPrec denv env (layoutTyconRef denv tc) prec tc.IsPrefixDisplay args // Layout a tuple type | TType_anon (anonInfo, tys) -> - let core = sepListL (wordL (tagPunctuation ";")) (List.map2 (fun nm ty -> wordL (tagField nm) ^^ wordL (tagPunctuation ":") ^^ layoutTypeWithInfoAndPrec denv env prec ty) (Array.toList anonInfo.SortedNames) tys) + let core = sepListL (rightL (tagPunctuation ";")) (List.map2 (fun nm ty -> wordL (tagField nm) ^^ rightL (tagPunctuation ":") ^^ layoutTypeWithInfoAndPrec denv env prec ty) (Array.toList anonInfo.SortedNames) tys) if evalAnonInfoIsStruct anonInfo then WordL.keywordStruct --- braceBarL core else @@ -961,7 +974,7 @@ module private PrintTypes = match tps with | [] -> tauL | [h] -> layoutTyparRefWithInfo denv env h ^^ rightL (tagPunctuation ".") --- tauL - | (h::t) -> spaceListL (List.map (layoutTyparRefWithInfo denv env) (h::t)) ^^ rightL (tagPunctuation ".") --- tauL + | (h :: t) -> spaceListL (List.map (layoutTyparRefWithInfo denv env) (h :: t)) ^^ rightL (tagPunctuation ".") --- tauL // Layout a function type. | TType_fun _ -> @@ -988,43 +1001,63 @@ module private PrintTypes = and layoutType denv ty = layoutTypeWithInfo denv SimplifyTypes.typeSimplificationInfo0 ty + let layoutArgInfos denv env argInfos = + + // Format each argument, including its name and type + let argL (ty, argInfo: ArgReprInfo) = + + // Detect an optional argument + let isOptionalArg = HasFSharpAttribute denv.g denv.g.attrib_OptionalArgumentAttribute argInfo.Attribs + let isParamArray = HasFSharpAttribute denv.g denv.g.attrib_ParamArrayAttribute argInfo.Attribs + match argInfo.Name, isOptionalArg, isParamArray, tryDestOptionTy denv.g ty with + // Layout an optional argument + | Some(id), true, _, ValueSome ty -> + leftL (tagPunctuation "?") ^^ sepL (tagParameter id.idText) ^^ SepL.colon ^^ layoutTypeWithInfoAndPrec denv env 2 ty + // Layout an unnamed argument + | None, _, _, _ -> + layoutTypeWithInfoAndPrec denv env 2 ty + // Layout a named argument + | Some id, _, isParamArray, _ -> + let prefix = + if isParamArray then + layoutBuiltinAttribute denv denv.g.attrib_ParamArrayAttribute ^^ leftL (tagParameter id.idText) + else + leftL (tagParameter id.idText) + prefix ^^ SepL.colon ^^ layoutTypeWithInfoAndPrec denv env 2 ty + + let allArgsL = + argInfos + |> List.mapSquared argL + |> List.map (sepListL (wordL (tagPunctuation "*"))) + allArgsL + + let layoutReturnType denv env rty = layoutTypeWithInfoAndPrec denv env 4 rty + + let layoutGenericParameterTypes denv env = + function + | [] -> emptyL + | genParamTys -> + (wordL (tagPunctuation "<")) + ^^ + ( + genParamTys + |> List.map (layoutTypeWithInfoAndPrec denv env 4) + |> sepListL (wordL (tagPunctuation ",")) + ) + ^^ + (wordL (tagPunctuation ">")) + /// Layout a single type used as the type of a member or value let layoutTopType denv env argInfos rty cxs = // Parenthesize the return type to match the topValInfo - let rtyL = layoutTypeWithInfoAndPrec denv env 4 rty + let rtyL = layoutReturnType denv env rty let cxsL = layoutConstraintsWithInfo denv env cxs match argInfos with | [] -> rtyL --- cxsL | _ -> - - // Format each argument, including its name and type - let argL (ty, argInfo: ArgReprInfo) = - - // Detect an optional argument - let isOptionalArg = HasFSharpAttribute denv.g denv.g.attrib_OptionalArgumentAttribute argInfo.Attribs - let isParamArray = HasFSharpAttribute denv.g denv.g.attrib_ParamArrayAttribute argInfo.Attribs - match argInfo.Name, isOptionalArg, isParamArray, tryDestOptionTy denv.g ty with - // Layout an optional argument - | Some(id), true, _, ValueSome ty -> - leftL (tagPunctuation "?") ^^ sepL (tagParameter id.idText) ^^ SepL.colon ^^ layoutTypeWithInfoAndPrec denv env 2 ty - // Layout an unnamed argument - | None, _, _, _ -> - layoutTypeWithInfoAndPrec denv env 2 ty - // Layout a named argument - | Some id, _, isParamArray, _ -> - let prefix = - if isParamArray then - layoutBuiltinAttribute denv denv.g.attrib_ParamArrayAttribute ^^ leftL (tagParameter id.idText) - else - leftL (tagParameter id.idText) - prefix ^^ SepL.colon ^^ layoutTypeWithInfoAndPrec denv env 2 ty - let delimitReturnValue = tagPunctuation (if denv.useColonForReturnType then ":" else "->") - let allArgsL = - argInfos - |> List.mapSquared argL - |> List.map (sepListL (wordL (tagPunctuation "*"))) + layoutArgInfos denv env argInfos |> List.map (fun x -> (x ^^ wordL delimitReturnValue)) (List.foldBack (---) allArgsL rtyL) --- cxsL @@ -1047,7 +1080,7 @@ module private PrintTypes = let layoutTyparConstraint denv (tp, tpc) = match layoutConstraintWithInfo denv SimplifyTypes.typeSimplificationInfo0 (tp, tpc) with - | h::_ -> h + | h :: _ -> h | [] -> emptyL let prettyLayoutOfInstAndSig denv (typarInst, tys, retTy) = @@ -1073,15 +1106,20 @@ module private PrintTypes = let cxs = cxs |> List.filter (fun (tp, _) -> not (parentTyparTys |> List.exists (fun ty -> match tryDestTyparTy denv.g ty with ValueSome destTypar -> typarEq tp destTypar | _ -> false))) prettyTyparInst, prettyLayoutOfTopTypeInfoAux denv argInfos retTy cxs - // Layout: type spec - class, datatype, record, abbrev + let private prettyArgInfos denv allTyparInst = + function + | [] -> [(denv.g.unit_ty, ValReprInfo.unnamedTopArg1)] + | infos -> infos |> List.map (map1Of2 (instType allTyparInst)) + + // Layout: type spec - class, datatype, record, abbrev let private prettyLayoutOfMemberSigCore denv memberToParentInst (typarInst, methTypars: Typars, argInfos, retTy) = let niceMethodTypars, allTyparInst = let methTyparNames = methTypars |> List.mapi (fun i tp -> if (PrettyTypes.NeedsPrettyTyparName tp) then sprintf "a%d" (List.length memberToParentInst + i) else tp.Name) PrettyTypes.NewPrettyTypars memberToParentInst methTypars methTyparNames let retTy = instType allTyparInst retTy - let argInfos = argInfos |> List.map (fun infos -> if isNil infos then [(denv.g.unit_ty, ValReprInfo.unnamedTopArg1)] else infos |> List.map (map1Of2 (instType allTyparInst))) + let argInfos = argInfos |> List.map (prettyArgInfos denv allTyparInst) // Also format dummy types corresponding to any type variables on the container to make sure they // aren't chosen as names for displayed variables. @@ -1107,6 +1145,50 @@ module private PrintTypes = nameL nameL ^^ wordL (tagPunctuation ":") ^^ tauL + /// layouts the elements of an unresolved overloaded method call: + /// argInfos: unammed and named arguments + /// retTy: return type + /// genParamTy: generic parameter types + let prettyLayoutsOfUnresolvedOverloading denv argInfos retTy genParamTys = + let _niceMethodTypars, typarInst = + let memberToParentInst = List.empty + let typars = argInfos |> List.choose (function (TType.TType_var typar,_) -> Some typar | _ -> None) + let methTyparNames = typars |> List.mapi (fun i tp -> if (PrettyTypes.NeedsPrettyTyparName tp) then sprintf "a%d" (List.length memberToParentInst + i) else tp.Name) + PrettyTypes.NewPrettyTypars memberToParentInst typars methTyparNames + let retTy = instType typarInst retTy + let argInfos = prettyArgInfos denv typarInst argInfos + let argInfos,retTy,genParamTys, cxs = + // using 0, 1, 2 as discriminant for return, arguments and generic parameters + // respectively, in order to easily retrieve each of the types with their + // expected quality below. + let typesWithDiscrimants = + [ + yield 0, retTy + for ty,_ in argInfos do + yield 1, ty + for ty in genParamTys do + yield 2, ty + ] + let typesWithDiscrimants,typarsAndCxs = PrettyTypes.PrettifyDiscriminantAndTypePairs denv.g typesWithDiscrimants + let retTy = typesWithDiscrimants |> List.find (function (0, _) -> true | _ -> false) |> snd + let argInfos = + typesWithDiscrimants + |> List.choose (function (1,ty) -> Some ty | _ -> None) + |> List.zip argInfos + |> List.map (fun ((_,argInfo),tTy) -> tTy, argInfo) + let genParamTys = + typesWithDiscrimants + |> List.choose (function (2,ty) -> Some ty | _ -> None) + + argInfos, retTy, genParamTys, typarsAndCxs + + let env = SimplifyTypes.CollectInfo true (List.collect (List.map fst) [argInfos]) cxs + let cxsL = layoutConstraintsWithInfo denv env env.postfixConstraints + + (List.foldBack (---) (layoutArgInfos denv env [argInfos]) cxsL, + layoutReturnType denv env retTy, + layoutGenericParameterTypes denv env genParamTys) + let prettyLayoutOfType denv ty = let ty, cxs = PrettyTypes.PrettifyType denv.g ty let env = SimplifyTypes.CollectInfo true [ty] cxs @@ -1121,14 +1203,21 @@ module private PrintTypes = ty.GetAssemblyName() /// Printing TAST objects -module private PrintTastMemberOrVals = - open PrintTypes - let private prettyLayoutOfMember denv typarInst (v: Val) = +module private PrintTastMemberOrVals = + open PrintTypes + + let private prettyLayoutOfMemberShortOption denv typarInst (v:Val) short = let v = mkLocalValRef v let membInfo = Option.get v.MemberInfo let stat = PrintTypes.layoutMemberFlags membInfo.MemberFlags let _tps, argInfos, rty, _ = GetTypeOfMemberInFSharpForm denv.g v + if short then + for argInfo in argInfos do + for _,info in argInfo do + info.Attribs <- [] + info.Name <- None + let mkNameL niceMethodTypars tagFunction name = let nameL = DemangleOperatorNameAsLayout (tagFunction >> mkNav v.DefinitionRange) name @@ -1143,35 +1232,51 @@ module private PrintTastMemberOrVals = match membInfo.MemberFlags.MemberKind with | MemberKind.Member -> - let prettyTyparInst, niceMethodTypars, tauL = prettyLayoutOfMemberType denv v typarInst argInfos rty - let nameL = mkNameL niceMethodTypars tagMember v.LogicalName - let resL = stat --- (nameL ^^ WordL.colon ^^ tauL) + let prettyTyparInst, niceMethodTypars,tauL = prettyLayoutOfMemberType denv v typarInst argInfos rty + let resL = + if short then tauL + else + let nameL = mkNameL niceMethodTypars tagMember v.LogicalName + stat --- (nameL ^^ WordL.colon ^^ tauL) prettyTyparInst, resL + | MemberKind.ClassConstructor | MemberKind.Constructor -> let prettyTyparInst, _, tauL = prettyLayoutOfMemberType denv v typarInst argInfos rty - let newL = layoutAccessibility denv v.Accessibility WordL.keywordNew - let resL = stat ++ newL ^^ wordL (tagPunctuation ":") ^^ tauL + let resL = + if short then tauL + else + let newL = layoutAccessibility denv v.Accessibility WordL.keywordNew + stat ++ newL ^^ wordL (tagPunctuation ":") ^^ tauL prettyTyparInst, resL + | MemberKind.PropertyGetSet -> emptyTyparInst, stat + | MemberKind.PropertyGet -> if isNil argInfos then // use error recovery because intellisense on an incomplete file will show this errorR(Error(FSComp.SR.tastInvalidFormForPropertyGetter(), v.Id.idRange)) let nameL = mkNameL [] tagProperty v.CoreDisplayName - let resL = stat --- nameL --- (WordL.keywordWith ^^ WordL.keywordGet) + let resL = + if short then nameL --- (WordL.keywordWith ^^ WordL.keywordGet) + else stat --- nameL --- (WordL.keywordWith ^^ WordL.keywordGet) emptyTyparInst, resL else let argInfos = match argInfos with | [[(ty, _)]] when isUnitTy denv.g ty -> [] | _ -> argInfos - - let prettyTyparInst, niceMethodTypars, tauL = prettyLayoutOfMemberType denv v typarInst argInfos rty - let nameL = mkNameL niceMethodTypars tagProperty v.CoreDisplayName - let resL = stat --- (nameL ^^ WordL.colon ^^ (if isNil argInfos then tauL else tauL --- (WordL.keywordWith ^^ WordL.keywordGet))) + let prettyTyparInst, niceMethodTypars,tauL = prettyLayoutOfMemberType denv v typarInst argInfos rty + let resL = + if short then + if isNil argInfos then tauL + else tauL --- (WordL.keywordWith ^^ WordL.keywordGet) + else + let nameL = mkNameL niceMethodTypars tagProperty v.CoreDisplayName + stat --- (nameL ^^ WordL.colon ^^ (if isNil argInfos then tauL else tauL --- (WordL.keywordWith ^^ WordL.keywordGet))) prettyTyparInst, resL + | MemberKind.PropertySet -> if argInfos.Length <> 1 || isNil argInfos.Head then // use error recovery because intellisense on an incomplete file will show this @@ -1182,9 +1287,18 @@ module private PrintTastMemberOrVals = else let argInfos, valueInfo = List.frontAndBack argInfos.Head let prettyTyparInst, niceMethodTypars, tauL = prettyLayoutOfMemberType denv v typarInst (if isNil argInfos then [] else [argInfos]) (fst valueInfo) - let nameL = mkNameL niceMethodTypars tagProperty v.CoreDisplayName - let resL = stat --- (nameL ^^ wordL (tagPunctuation ":") ^^ (tauL --- (WordL.keywordWith ^^ WordL.keywordSet))) + let resL = + if short then + (tauL --- (WordL.keywordWith ^^ WordL.keywordSet)) + else + let nameL = mkNameL niceMethodTypars tagProperty v.CoreDisplayName + stat --- (nameL ^^ wordL (tagPunctuation ":") ^^ (tauL --- (WordL.keywordWith ^^ WordL.keywordSet))) prettyTyparInst, resL + + let prettyLayoutOfMember denv typarInst (v:Val) = prettyLayoutOfMemberShortOption denv typarInst v false + + let prettyLayoutOfMemberNoInstShort denv v = + prettyLayoutOfMemberShortOption denv emptyTyparInst v true |> snd let private layoutNonMemberVal denv (tps, v: Val, tau, cxs) = let env = SimplifyTypes.CollectInfo true [tau] cxs @@ -1237,16 +1351,25 @@ module private PrintTastMemberOrVals = prettyLayoutOfValOrMember denv emptyTyparInst v |> snd let layoutTyparConstraint denv x = x |> PrintTypes.layoutTyparConstraint denv + let outputType denv os x = x |> PrintTypes.layoutType denv |> bufferL os + let layoutType denv x = x |> PrintTypes.layoutType denv + let outputTypars denv nm os x = x |> PrintTypes.layoutTyparDecls denv (wordL nm) true |> bufferL os + let outputTyconRef denv os x = x |> PrintTypes.layoutTyconRef denv |> bufferL os + let layoutTyconRef denv x = x |> PrintTypes.layoutTyconRef denv + let layoutConst g ty c = PrintTypes.layoutConst g ty c let prettyLayoutOfMemberSig denv x = x |> PrintTypes.prettyLayoutOfMemberSig denv + let prettyLayoutOfUncurriedSig denv argInfos tau = PrintTypes.prettyLayoutOfUncurriedSig denv argInfos tau +let prettyLayoutsOfUnresolvedOverloading denv argInfos retTy genericParameters = PrintTypes.prettyLayoutsOfUnresolvedOverloading denv argInfos retTy genericParameters + //------------------------------------------------------------------------- /// Printing info objects @@ -1345,7 +1468,7 @@ module InfoMemberPrinting = layout ^^ RightL.rightParen ^^ WordL.colon ^^ PrintTypes.layoutType denv retTy - // Prettify this baby + // Prettify an ILMethInfo let prettifyILMethInfo (amap: Import.ImportMap) m (minfo: MethInfo) typarInst ilMethInfo = let (ILMethInfo(_, apparentTy, dty, mdef, _)) = ilMethInfo let (prettyTyparInst, prettyTys), _ = PrettyTypes.PrettifyInstAndTypes amap.g (typarInst, (apparentTy :: minfo.FormalMethodInst)) @@ -1356,7 +1479,6 @@ module InfoMemberPrinting = | Some declaringTyconRef -> MethInfo.CreateILExtensionMeth(amap, m, prettyApparentTy, declaringTyconRef, minfo.ExtensionMemberPriorityOption, mdef) prettyTyparInst, prettyMethInfo, prettyFormalMethInst - /// Format a method to a buffer using "standalone" display style. /// For example, these are the formats used when printing signatures of methods that have not been overridden, /// and the format used when showing the individual member in QuickInfo and DeclarationInfo. @@ -1405,12 +1527,24 @@ module InfoMemberPrinting = | None -> tagProperty | Some vref -> tagProperty >> mkNav vref.DefinitionRange let nameL = DemangleOperatorNameAsLayout tagProp pinfo.PropertyName + let getterSetter = + match pinfo.HasGetter, pinfo.HasSetter with + | (true, false) -> + wordL (tagKeyword "with") ^^ wordL (tagText "get") + | (false, true) -> + wordL (tagKeyword "with") ^^ wordL (tagText "set") + | (true, true) -> + wordL (tagKeyword "with") ^^ wordL (tagText "get, set") + | (false, false) -> + emptyL + wordL (tagText (FSComp.SR.typeInfoProperty())) ^^ layoutTyconRef denv pinfo.ApparentEnclosingTyconRef ^^ SepL.dot ^^ nameL ^^ RightL.colon ^^ - layoutType denv rty + layoutType denv rty ^^ + getterSetter let formatMethInfoToBufferFreeStyle amap m denv os (minfo: MethInfo) = let _, resL = prettyLayoutOfMethInfoFreeStyle amap m denv emptyTyparInst minfo @@ -1445,7 +1579,7 @@ module private TastDefinitionPrinting = let lhs = tagRecordField fld.Name |> mkNav fld.DefinitionRange - |> wordL + |> wordL let lhs = (if addAccess then layoutAccessibility denv fld.Accessibility lhs else lhs) let lhs = if fld.IsMutable then wordL (tagKeyword "mutable") --- lhs else lhs (lhs ^^ RightL.colon) --- layoutType denv fld.FormalType @@ -1567,7 +1701,7 @@ module private TastDefinitionPrinting = GetImmediateInterfacesOfType SkipUnrefInterfaces.Yes g amap m ty |> List.map (fun ity -> wordL (tagKeyword (if isInterfaceTy g ty then "inherit" else "interface")) --- layoutType denv ity) let props = - GetIntrinsicPropInfosOfType infoReader (None, ad, AllowMultiIntfInstantiations.Yes) PreferOverrides m ty + GetIntrinsicPropInfosOfType infoReader None ad AllowMultiIntfInstantiations.Yes PreferOverrides m ty |> List.filter (fun v -> shouldShow v.ArbitraryValRef) let events = @@ -1597,7 +1731,6 @@ module private TastDefinitionPrinting = let fieldLs = infoReader.GetILFieldInfosOfType (None, ad, m, ty) |> List.map (fun x -> (true, x.IsStatic, x.FieldName, 0, 0), layoutILFieldInfo denv amap m x) - let propLs = props @@ -1726,8 +1859,15 @@ module private TastDefinitionPrinting = let denv = denv.AddAccessibility tycon.TypeReprAccessibility match repr with | TRecdRepr _ -> - let recdFieldRefL fld = layoutRecdField false denv fld ^^ rightL (tagPunctuation ";") - let recdL = tycon.TrueFieldsAsList |> List.map recdFieldRefL |> applyMaxMembers denv.maxMembers |> aboveListL |> braceL + let recdFieldRefL fld = layoutRecdField false denv fld + + let recdL = + tycon.TrueFieldsAsList + |> List.map recdFieldRefL + |> applyMaxMembers denv.maxMembers + |> aboveListL + |> braceL + Some (addMembersAsWithEnd (addReprAccessL recdL)) | TFSharpObjectRepr r -> @@ -1759,8 +1899,7 @@ module private TastDefinitionPrinting = | _ -> [] let vsprs = tycon.MembersOfFSharpTyconSorted - |> List.filter (fun v -> isNil (Option.get v.MemberInfo).ImplementedSlotSigs) - |> List.filter (fun v -> v.IsDispatchSlot) + |> List.filter (fun v -> isNil (Option.get v.MemberInfo).ImplementedSlotSigs && v.IsDispatchSlot) |> List.map (fun vref -> PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv vref.Deref) let staticValsLs = tycon.TrueFieldsAsList @@ -1770,23 +1909,26 @@ module private TastDefinitionPrinting = tycon.TrueFieldsAsList |> List.filter (fun f -> not f.IsStatic) |> List.map (fun f -> WordL.keywordVal ^^ layoutRecdField true denv f) - let alldecls = inherits @ memberImplementLs @ memberCtorLs @ instanceValsLs @ vsprs @ memberInstanceLs @ staticValsLs @ memberStaticLs - if isNil alldecls then + let allDecls = inherits @ memberImplementLs @ memberCtorLs @ instanceValsLs @ vsprs @ memberInstanceLs @ staticValsLs @ memberStaticLs + if isNil allDecls then None else - let alldecls = applyMaxMembers denv.maxMembers alldecls - let emptyMeasure = match tycon.TypeOrMeasureKind with TyparKind.Measure -> isNil alldecls | _ -> false + let allDecls = applyMaxMembers denv.maxMembers allDecls + let emptyMeasure = match tycon.TypeOrMeasureKind with TyparKind.Measure -> isNil allDecls | _ -> false if emptyMeasure then None else - let declsL = aboveListL alldecls + let declsL = aboveListL allDecls let declsL = match start with Some s -> (wordL s @@-- declsL) @@ wordL (tagKeyword "end") | None -> declsL Some declsL | TUnionRepr _ -> let layoutUnionCases = tycon.UnionCasesAsList |> layoutUnionCases denv |> applyMaxMembers denv.maxMembers |> aboveListL Some (addMembersAsWithEnd (addReprAccessL layoutUnionCases)) + | TAsmRepr _ -> Some (wordL (tagText "(# \"\" #)")) + | TMeasureableRepr ty -> Some (layoutType denv ty) + | TILObjectRepr _ -> let td = tycon.ILTyconRawMetadata Some (PrintIL.layoutILTypeDef denv td) @@ -1807,6 +1949,7 @@ module private TastDefinitionPrinting = addMembersAsWithEnd (lhsL ^^ WordL.equals) | Some a -> (lhsL ^^ WordL.equals) --- (layoutType { denv with shortTypeNames = false } a) + layoutAttribs denv ty tycon.TypeOrMeasureKind tycon.Attribs reprL // Layout: exception definition @@ -1836,7 +1979,7 @@ module private TastDefinitionPrinting = | h :: t -> let x = layoutTycon denv infoReader ad m false WordL.keywordType h let xs = List.map (layoutTycon denv infoReader ad m false (wordL (tagKeyword "and"))) t - aboveListL (x::xs) + aboveListL (x :: xs) //-------------------------------------------------------------------------- @@ -1960,27 +2103,35 @@ module private PrintData = layoutConst denv.g ty c | Expr.Val (v, _, _) -> wordL (tagLocal v.DisplayName) + | Expr.Link rX -> dataExprWrapL denv isAtomic (!rX) - | Expr.Op (TOp.UnionCase(c), _, args, _) -> + + | Expr.Op (TOp.UnionCase (c), _, args, _) -> if denv.g.unionCaseRefEq c denv.g.nil_ucref then wordL (tagPunctuation "[]") elif denv.g.unionCaseRefEq c denv.g.cons_ucref then - let rec strip = function (Expr.Op (TOp.UnionCase _, _, [h;t], _)) -> h::strip t | _ -> [] + let rec strip = function (Expr.Op (TOp.UnionCase _, _, [h;t], _)) -> h :: strip t | _ -> [] listL (dataExprL denv) (strip expr) elif isNil args then wordL (tagUnionCase c.CaseName) else (wordL (tagUnionCase c.CaseName) ++ bracketL (commaListL (dataExprsL denv args))) - | Expr.Op (TOp.ExnConstr(c), _, args, _) -> (wordL (tagMethod c.LogicalName) ++ bracketL (commaListL (dataExprsL denv args))) + | Expr.Op (TOp.ExnConstr (c), _, args, _) -> (wordL (tagMethod c.LogicalName) ++ bracketL (commaListL (dataExprsL denv args))) + | Expr.Op (TOp.Tuple _, _, xs, _) -> tupleL (dataExprsL denv xs) + | Expr.Op (TOp.Recd (_, tc), _, xs, _) -> let fields = tc.TrueInstanceFieldsAsList let lay fs x = (wordL (tagRecordField fs.rfield_id.idText) ^^ sepL (tagPunctuation "=")) --- (dataExprL denv x) leftL (tagPunctuation "{") ^^ semiListL (List.map2 lay fields xs) ^^ rightL (tagPunctuation "}") - | Expr.Op (TOp.ValFieldGet (RecdFieldRef.RFRef (tcref, name)), _, _, _) -> + + | Expr.Op (TOp.ValFieldGet (RecdFieldRef.RecdFieldRef (tcref, name)), _, _, _) -> (layoutTyconRef denv tcref) ^^ sepL (tagPunctuation ".") ^^ wordL (tagField name) + | Expr.Op (TOp.Array, [_], xs, _) -> leftL (tagPunctuation "[|") ^^ semiListL (dataExprsL denv xs) ^^ RightL.rightBracketBar + | _ -> wordL (tagPunctuation "?") + and private dataExprsL denv xs = List.map (dataExprL denv) xs let dataExprL denv expr = PrintData.dataExprL denv expr @@ -1989,17 +2140,22 @@ let dataExprL denv expr = PrintData.dataExprL denv expr // Print Signatures/Types - output functions //-------------------------------------------------------------------------- - let outputValOrMember denv os x = x |> PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv |> bufferL os + let stringValOrMember denv x = x |> PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv |> showL + /// Print members with a qualification showing the type they are contained in let layoutQualifiedValOrMember denv typarInst v = PrintTastMemberOrVals.prettyLayoutOfValOrMember { denv with showMemberContainers=true; } typarInst v + let outputQualifiedValOrMember denv os v = outputValOrMember { denv with showMemberContainers=true; } os v + let outputQualifiedValSpec denv os v = outputQualifiedValOrMember denv os v + let stringOfQualifiedValOrMember denv v = PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst { denv with showMemberContainers=true; } v |> showL /// Convert a MethInfo to a string let formatMethInfoToBufferFreeStyle amap m denv buf d = InfoMemberPrinting.formatMethInfoToBufferFreeStyle amap m denv buf d + let prettyLayoutOfMethInfoFreeStyle amap m denv typarInst minfo = InfoMemberPrinting.prettyLayoutOfMethInfoFreeStyle amap m denv typarInst minfo /// Convert a PropInfo to a string @@ -2010,35 +2166,62 @@ let stringOfMethInfo amap m denv d = bufs (fun buf -> InfoMemberPrinting.formatM /// Convert a ParamData to a string let stringOfParamData denv paramData = bufs (fun buf -> InfoMemberPrinting.formatParamDataToBuffer denv buf paramData) + let layoutOfParamData denv paramData = InfoMemberPrinting.layoutParamData denv paramData + let outputILTypeRef denv os x = x |> PrintIL.layoutILTypeRef denv |> bufferL os + let layoutILTypeRef denv x = x |> PrintIL.layoutILTypeRef denv + let outputExnDef denv os x = x |> TastDefinitionPrinting.layoutExnDefn denv |> bufferL os + let layoutExnDef denv x = x |> TastDefinitionPrinting.layoutExnDefn denv + let stringOfTyparConstraints denv x = x |> PrintTypes.layoutConstraintsWithInfo denv SimplifyTypes.typeSimplificationInfo0 |> showL + let outputTycon denv infoReader ad m (* width *) os x = TastDefinitionPrinting.layoutTycon denv infoReader ad m true WordL.keywordType x (* |> Layout.squashTo width *) |> bufferL os + let layoutTycon denv infoReader ad m (* width *) x = TastDefinitionPrinting.layoutTycon denv infoReader ad m true WordL.keywordType x (* |> Layout.squashTo width *) + let layoutUnionCases denv x = x |> TastDefinitionPrinting.layoutUnionCaseFields denv true + let outputUnionCases denv os x = x |> TastDefinitionPrinting.layoutUnionCaseFields denv true |> bufferL os + /// Pass negative number as pos in case of single cased discriminated unions let isGeneratedUnionCaseField pos f = TastDefinitionPrinting.isGeneratedUnionCaseField pos f + let isGeneratedExceptionField pos f = TastDefinitionPrinting.isGeneratedExceptionField pos f + let stringOfTyparConstraint denv tpc = stringOfTyparConstraints denv [tpc] + let stringOfTy denv x = x |> PrintTypes.layoutType denv |> showL + let prettyLayoutOfType denv x = x |> PrintTypes.prettyLayoutOfType denv + let prettyLayoutOfTypeNoCx denv x = x |> PrintTypes.prettyLayoutOfTypeNoConstraints denv + let prettyStringOfTy denv x = x |> PrintTypes.prettyLayoutOfType denv |> showL + let prettyStringOfTyNoCx denv x = x |> PrintTypes.prettyLayoutOfTypeNoConstraints denv |> showL + let stringOfRecdField denv x = x |> TastDefinitionPrinting.layoutRecdField false denv |> showL + let stringOfUnionCase denv x = x |> TastDefinitionPrinting.layoutUnionCase denv WordL.bar |> showL + let stringOfExnDef denv x = x |> TastDefinitionPrinting.layoutExnDefn denv |> showL let stringOfFSAttrib denv x = x |> PrintTypes.layoutAttrib denv |> squareAngleL |> showL + let stringOfILAttrib denv x = x |> PrintTypes.layoutILAttrib denv |> squareAngleL |> showL let layoutInferredSigOfModuleExpr showHeader denv infoReader ad m expr = InferredSigPrinting.layoutInferredSigOfModuleExpr showHeader denv infoReader ad m expr -let prettyLayoutOfValOrMember denv typarInst v = PrintTastMemberOrVals.prettyLayoutOfValOrMember denv typarInst v + +let prettyLayoutOfValOrMember denv typarInst v = PrintTastMemberOrVals.prettyLayoutOfValOrMember denv typarInst v + let prettyLayoutOfValOrMemberNoInst denv v = PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv v + +let prettyLayoutOfMemberNoInstShort denv v = PrintTastMemberOrVals.prettyLayoutOfMemberNoInstShort denv v + let prettyLayoutOfInstAndSig denv x = PrintTypes.prettyLayoutOfInstAndSig denv x /// Generate text for comparing two types. @@ -2093,7 +2276,6 @@ let minimalStringsOfTwoTypes denv t1 t2= (makeName t1, makeName t2, stringOfTyparConstraints denv tpcs) - // Note: Always show imperative annotations when comparing value signatures let minimalStringsOfTwoValues denv v1 v2= let denvMin = { denv with showImperativeTyparAnnotations=true; showConstraintTyparAnnotations=false } @@ -2112,58 +2294,3 @@ let minimalStringOfType denv ty = let denvMin = { denv with showImperativeTyparAnnotations=false; showConstraintTyparAnnotations=false } showL (PrintTypes.layoutTypeWithInfoAndPrec denvMin SimplifyTypes.typeSimplificationInfo0 2 ty) - -#if ASSEMBLY_AND_MODULE_SIGNATURE_PRINTING -type DeclSpec = - | DVal of Val - | DTycon of Tycon - | DException of Tycon - | DModul of ModuleOrNamespace - -let rangeOfDeclSpec = function - | DVal v -> v.Range - | DTycon t -> t.Range - | DException t -> t.Range - | DModul m -> m.Range - -/// modul - provides (valspec)* - and also types, exns and submodules. -/// Each defines a decl block on a given range. -/// Can sort on the ranges to recover the original declaration order. -let rec moduleOrNamespaceTypeLP (topLevel: bool) (denv: DisplayEnv) (mtype: ModuleOrNamespaceType) = - // REVIEW: consider a better way to keep decls in order. - let declSpecs: DeclSpec list = - List.concat - [ mtype.AllValsAndMembers |> Seq.toList |> List.filter (fun v -> not v.IsCompilerGenerated && v.MemberInfo.IsNone) |> List.map DVal - mtype.TypeDefinitions |> List.map DTycon - mtype.ExceptionDefinitions |> List.map DException - mtype.ModuleAndNamespaceDefinitions |> List.map DModul - ] - - let declSpecs = List.sortWithOrder (Order.orderOn rangeOfDeclSpec rangeOrder) declSpecs - let declSpecL = - function // only show namespaces / modules at the top level; this is because we've no global namespace - | DVal vspec when not topLevel -> prettyLayoutOfValOrMember denv vspec - | DTycon tycon when not topLevel -> tyconL denv (wordL "type") tycon - | DException tycon when not topLevel -> layoutExnDefn denv tycon - | DModul mspec -> moduleOrNamespaceLP false denv mspec - | _ -> emptyL // this catches non-namespace / modules at the top-level - - aboveListL (List.map declSpecL declSpecs) - -and moduleOrNamespaceLP (topLevel: bool) (denv: DisplayEnv) (mspec: ModuleOrNamespace) = - let istype = mspec.ModuleOrNamespaceType.ModuleOrNamespaceKind - let nm = mspec.DemangledModuleOrNamespaceName - let denv = denv.AddOpenModuleOrNamespace (mkLocalModRef mspec) - let nmL = layoutAccessibility denv mspec.Accessibility (wordL nm) - let denv = denv.AddAccessibility mspec.Accessibility - let path = path.Add nm // tack on the current module to be used in calls to linearise all subterms - let body = moduleOrNamespaceTypeLP topLevel denv path mspec.ModuleOrNamespaceType - if istype = Namespace - then (wordL "namespace" ^^ nmL) @@-- body - else (wordL "module" ^^ nmL ^^ wordL "= begin") @@-- body @@ wordL "end" - -let moduleOrNamespaceTypeL (denv: DisplayEnv) (mtype: ModuleOrNamespaceType) = moduleOrNamespaceTypeLP false denv Path.Empty mtype -let moduleOrNamespaceL denv mspec = moduleOrNamespaceLP false denv Path.Empty mspec -let assemblyL denv (mspec: ModuleOrNamespace) = moduleOrNamespaceTypeLP true denv Path.Empty mspec.ModuleOrNamespaceType // we seem to get the *assembly* name as an outer module, this strips this off -#endif - diff --git a/src/fcs-fable/src/fsharp/Optimizer.fs b/src/fcs-fable/src/fsharp/Optimizer.fs old mode 100755 new mode 100644 index dc516d19f5..2df9a3fa7b --- a/src/fcs-fable/src/fsharp/Optimizer.fs +++ b/src/fcs-fable/src/fsharp/Optimizer.fs @@ -1,34 +1,33 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -//------------------------------------------------------------------------- -// The F# expression simplifier. The main aim is to inline simple, known functions -// and constant values, and to eliminate non-side-affecting bindings that -// are never used. -//------------------------------------------------------------------------- - - +/// The F# expression simplifier. The main aim is to inline simple, known functions +/// and constant values, and to eliminate non-side-affecting bindings that +/// are never used. module internal FSharp.Compiler.Optimizer open Internal.Utilities + +open FSharp.Compiler open FSharp.Compiler.AbstractIL.Diagnostics open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library - -open FSharp.Compiler -open FSharp.Compiler.Lib -open FSharp.Compiler.Range -open FSharp.Compiler.Ast open FSharp.Compiler.AttributeChecking +open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Infos -open FSharp.Compiler.Tast -open FSharp.Compiler.TastPickle -open FSharp.Compiler.Tastops -open FSharp.Compiler.Tastops.DebugPrint -open FSharp.Compiler.TcGlobals open FSharp.Compiler.Layout open FSharp.Compiler.Layout.TaggedTextOps +open FSharp.Compiler.Lib +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.TypedTreeOps.DebugPrint +open FSharp.Compiler.TypedTreePickle +open FSharp.Compiler.TcGlobals open FSharp.Compiler.TypeRelations open System.Collections.Generic @@ -100,7 +99,7 @@ type ExprValueInfo = /// arities: The number of bunches of untupled args and type args, and /// the number of args in each bunch. NOTE: This include type arguments. /// expr: The value, a lambda term. - /// ty: The type of lamba term + /// ty: The type of lambda term | CurriedLambdaValue of Unique * int * int * Expr * TType /// ConstExprValue(size, value) @@ -172,7 +171,8 @@ let braceL x = leftL (tagText "{") ^^ x ^^ rightL (tagText "}") let seqL xL xs = Seq.fold (fun z x -> z @@ xL x) emptyL xs let namemapL xL xmap = NameMap.foldBack (fun nm x z -> xL nm x @@ z) xmap emptyL -let rec exprValueInfoL g exprVal = +let rec exprValueInfoL g exprVal = + let exprL expr = exprL g expr match exprVal with | ConstValue (x, ty) -> NicePrint.layoutConst g ty x | UnknownValue -> wordL (tagText "?") @@ -349,13 +349,14 @@ type OptimizationSettings = member x.EliminateTupleFieldGet () = x.localOpt () - member x.EliminatUnionCaseFieldGet () = x.localOpt () + member x.EliminateUnionCaseFieldGet () = x.localOpt () /// eliminate non-compiler generated immediate bindings member x.EliminateImmediatelyConsumedLocals() = x.localOpt () - /// expand "let x = (exp1, exp2, ...)" bind fields as prior tmps - member x.ExpandStructrualValues() = x.localOpt () + /// expand "let x = (exp1, exp2, ...)" bindings as prior tmps + /// expand "let x = Some exp1" bindings as prior tmps + member x.ExpandStructuralValues() = x.localOpt () type cenv = { g: TcGlobals @@ -378,6 +379,8 @@ type cenv = casApplied : Dictionary } + override x.ToString() = "" + type IncrementalOptimizationEnv = { /// An identifier to help with name generation latestBoundId: Ident option @@ -394,7 +397,7 @@ type IncrementalOptimizationEnv = inLoop: bool /// The Val for the function binding being generated, if any. - functionVal: (Val * Tast.ValReprInfo) option + functionVal: (Val * ValReprInfo) option typarInfos: (Typar * TypeValueInfo) list @@ -413,6 +416,8 @@ type IncrementalOptimizationEnv = localExternalVals = LayeredMap.Empty globalModuleInfos = LayeredMap.Empty } + override x.ToString() = "" + //------------------------------------------------------------------------- // IsPartialExprVal - is the expr fully known? //------------------------------------------------------------------------- @@ -551,7 +556,7 @@ let inline BindInternalValsToUnknown cenv vs env = env #endif -let BindTypeVar tyv typeinfo env = { env with typarInfos= (tyv, typeinfo)::env.typarInfos } +let BindTypeVar tyv typeinfo env = { env with typarInfos= (tyv, typeinfo) :: env.typarInfos } let BindTypeVarsToUnknown (tps: Typar list) env = if isNil tps then env else @@ -564,7 +569,7 @@ let BindTypeVarsToUnknown (tps: Typar list) env = tp.typar_id <- ident (nm, tp.Range)) List.fold (fun sofar arg -> BindTypeVar arg UnknownTypeValue sofar) env tps -let BindCcu (ccu: Tast.CcuThunk) mval env (_g: TcGlobals) = +let BindCcu (ccu: CcuThunk) mval env (_g: TcGlobals) = { env with globalModuleInfos=env.globalModuleInfos.Add(ccu.AssemblyName, mval) } /// Lookup information about values @@ -572,22 +577,18 @@ let GetInfoForLocalValue cenv env (v: Val) m = // Abstract slots do not have values if v.IsDispatchSlot then UnknownValInfo else -#if FABLE_COMPILER - let ok, res = cenv.localInternalVals.TryGetValue(v.Stamp) -#else - let mutable res = Unchecked.defaultof<_> - let ok = cenv.localInternalVals.TryGetValue(v.Stamp, &res) -#endif - if ok then res else - match env.localExternalVals.TryFind v.Stamp with - | Some vval -> vval - | None -> - if v.MustInline then - errorR(Error(FSComp.SR.optValueMarkedInlineButWasNotBoundInTheOptEnv(fullDisplayTextOfValRef (mkLocalValRef v)), m)) + match cenv.localInternalVals.TryGetValue v.Stamp with + | true, res -> res + | _ -> + match env.localExternalVals.TryFind v.Stamp with + | Some vval -> vval + | None -> + if v.MustInline then + errorR(Error(FSComp.SR.optValueMarkedInlineButWasNotBoundInTheOptEnv(fullDisplayTextOfValRef (mkLocalValRef v)), m)) #if CHECKED - warning(Error(FSComp.SR.optLocalValueNotFoundDuringOptimization(v.DisplayName), m)) + warning(Error(FSComp.SR.optLocalValueNotFoundDuringOptimization(v.DisplayName), m)) #endif - UnknownValInfo + UnknownValInfo let TryGetInfoForCcu env (ccu: CcuThunk) = env.globalModuleInfos.TryFind(ccu.AssemblyName) @@ -618,14 +619,14 @@ let GetInfoForNonLocalVal cenv env (vref: ValRef) = // REVIEW: optionally turn x-module on/off on per-module basis or elif cenv.settings.crossModuleOpt () || vref.MustInline then match TryGetInfoForNonLocalEntityRef env vref.nlr.EnclosingEntity.nlr with - | Some(structInfo) -> - match structInfo.ValInfos.TryFind(vref) with + | Some structInfo -> + match structInfo.ValInfos.TryFind vref with | Some ninfo -> snd ninfo | None -> //dprintn ("\n\n*** Optimization info for value "+n+" from module "+(full_name_of_nlpath smv)+" not found, module contains values: "+String.concat ", " (NameMap.domainL structInfo.ValInfos)) //System.Diagnostics.Debug.Assert(false, sprintf "Break for module %s, value %s" (full_name_of_nlpath smv) n) if cenv.g.compilingFslib then - match structInfo.ValInfos.TryFindForFslib(vref) with + match structInfo.ValInfos.TryFindForFslib vref with | true, ninfo -> snd ninfo | _ -> UnknownValInfo else @@ -728,7 +729,7 @@ let MakeValueInfoForConst c ty = ConstValue(c, ty) /// Helper to evaluate a unary integer operation over known values let inline IntegerUnaryOp g f8 f16 f32 f64 fu8 fu16 fu32 fu64 a = match a with - | StripConstValue(c) -> + | StripConstValue c -> match c with | Const.Bool a -> Some(mkBoolVal g (f32 (if a then 1 else 0) <> 0)) | Const.Int32 a -> Some(mkInt32Val g (f32 a)) @@ -745,7 +746,7 @@ let inline IntegerUnaryOp g f8 f16 f32 f64 fu8 fu16 fu32 fu64 a = /// Helper to evaluate a unary signed integer operation over known values let inline SignedIntegerUnaryOp g f8 f16 f32 f64 a = match a with - | StripConstValue(c) -> + | StripConstValue c -> match c with | Const.Int32 a -> Some(mkInt32Val g (f32 a)) | Const.Int64 a -> Some(mkInt64Val g (f64 a)) @@ -757,7 +758,7 @@ let inline SignedIntegerUnaryOp g f8 f16 f32 f64 a = /// Helper to evaluate a binary integer operation over known values let inline IntegerBinaryOp g f8 f16 f32 f64 fu8 fu16 fu32 fu64 a b = match a, b with - | StripConstValue(c1), StripConstValue(c2) -> + | StripConstValue c1, StripConstValue c2 -> match c1, c2 with | (Const.Bool a), (Const.Bool b) -> Some(mkBoolVal g (f32 (if a then 1 else 0) (if b then 1 else 0) <> 0)) | (Const.Int32 a), (Const.Int32 b) -> Some(mkInt32Val g (f32 a b)) @@ -1135,7 +1136,7 @@ let AbstractOptimizationInfoToEssentials = /// Hide information because of a "let ... in ..." or "let rec ... in ... " let AbstractExprInfoByVars (boundVars: Val list, boundTyVars) ivalue = // Module and member bindings can be skipped when checking abstraction, since abstraction of these values has already been done when - // we hit the end of the module and called AbstractLazyModulInfoByHiding. If we don't skip these then we end up quadtratically retraversing + // we hit the end of the module and called AbstractLazyModulInfoByHiding. If we don't skip these then we end up quadratically retraversing // the inferred optimization data, i.e. at each binding all the way up a sequences of 'lets' in a module. let boundVars = boundVars |> List.filter (fun v -> not v.IsMemberOrModuleBinding) @@ -1177,9 +1178,9 @@ let AbstractExprInfoByVars (boundVars: Val list, boundTyVars) ivalue = UnknownValue // Otherwise check all sub-values - | TupleValue vinfos -> TupleValue (Array.map (abstractExprInfo) vinfos) - | RecdValue (tcref, vinfos) -> RecdValue (tcref, Array.map (abstractExprInfo) vinfos) - | UnionCaseValue (cspec, vinfos) -> UnionCaseValue(cspec, Array.map (abstractExprInfo) vinfos) + | TupleValue vinfos -> TupleValue (Array.map abstractExprInfo vinfos) + | RecdValue (tcref, vinfos) -> RecdValue (tcref, Array.map abstractExprInfo vinfos) + | UnionCaseValue (cspec, vinfos) -> UnionCaseValue(cspec, Array.map abstractExprInfo vinfos) | CurriedLambdaValue _ | ConstValue _ | ConstExprValue _ @@ -1269,7 +1270,7 @@ let rec IsSmallConstExpr x = match x with | Expr.Op (TOp.LValueOp (LAddrOf _, _), [], [], _) -> true // &x is always a constant | Expr.Val (v, _, _m) -> not v.IsMutable - | Expr.App(fe, _, _tyargs, args, _) -> isNil args && not (IsTyFuncValRefExpr fe) && IsSmallConstExpr fe + | Expr.App (fe, _, _tyargs, args, _) -> isNil args && not (IsTyFuncValRefExpr fe) && IsSmallConstExpr fe | _ -> false let ValueOfExpr expr = @@ -1338,10 +1339,10 @@ let rec ExprHasEffect g expr = | Expr.TyLambda _ | Expr.Const _ -> false /// type applications do not have effects, with the exception of type functions - | Expr.App(f0, _, _, [], _) -> (IsTyFuncValRefExpr f0) || ExprHasEffect g f0 - | Expr.Op(op, _, args, m) -> ExprsHaveEffect g args || OpHasEffect g m op - | Expr.LetRec(binds, body, _, _) -> BindingsHaveEffect g binds || ExprHasEffect g body - | Expr.Let(bind, body, _, _) -> BindingHasEffect g bind || ExprHasEffect g body + | Expr.App (f0, _, _, [], _) -> (IsTyFuncValRefExpr f0) || ExprHasEffect g f0 + | Expr.Op (op, _, args, m) -> ExprsHaveEffect g args || OpHasEffect g m op + | Expr.LetRec (binds, body, _, _) -> BindingsHaveEffect g binds || ExprHasEffect g body + | Expr.Let (bind, body, _, _) -> BindingHasEffect g bind || ExprHasEffect g body // REVIEW: could add Expr.Obj on an interface type - these are similar to records of lambda expressions | _ -> true @@ -1365,12 +1366,12 @@ and OpHasEffect g m op = | TOp.UnionCaseTagGet _ -> false | TOp.UnionCaseProof _ -> false | TOp.UnionCaseFieldGet (ucref, n) -> isUnionCaseFieldMutable g ucref n - | TOp.ILAsm(instrs, _) -> IlAssemblyCodeHasEffect instrs - | TOp.TupleFieldGet(_) -> false - | TOp.ExnFieldGet(ecref, n) -> isExnFieldMutable ecref n + | TOp.ILAsm (instrs, _) -> IlAssemblyCodeHasEffect instrs + | TOp.TupleFieldGet (_) -> false + | TOp.ExnFieldGet (ecref, n) -> isExnFieldMutable ecref n | TOp.RefAddrGet _ -> false | TOp.AnonRecdGet _ -> true // conservative - | TOp.ValFieldGet rfref -> rfref.RecdField.IsMutable || (TryFindTyconRefBoolAttribute g Range.range0 g.attrib_AllowNullLiteralAttribute rfref.TyconRef = Some(true)) + | TOp.ValFieldGet rfref -> rfref.RecdField.IsMutable || (TryFindTyconRefBoolAttribute g Range.range0 g.attrib_AllowNullLiteralAttribute rfref.TyconRef = Some true) | TOp.ValFieldGetAddr (rfref, _readonly) -> rfref.RecdField.IsMutable | TOp.UnionCaseFieldGetAddr _ -> false // union case fields are immutable | TOp.LValueOp (LAddrOf _, _) -> false // addresses of values are always constants @@ -1404,7 +1405,7 @@ let TryEliminateBinding cenv _env (TBind(vspec1, e1, spBind)) e2 _m = // But note the cases below cover some instances of side-effecting expressions as well.... let IsUniqueUse vspec2 args = valEq vspec1 vspec2 - && (not (vspec2.LogicalName.Contains(suffixForVariablesThatMayNotBeEliminated))) + && (not (vspec2.LogicalName.Contains suffixForVariablesThatMayNotBeEliminated)) // REVIEW: this looks slow. Look only for one variable instead && (let fvs = accFreeInExprs CollectLocals args emptyFreeVars not (Zset.contains vspec1 fvs.FreeLocals)) @@ -1412,35 +1413,38 @@ let TryEliminateBinding cenv _env (TBind(vspec1, e1, spBind)) e2 _m = // Immediate consumption of value as 2nd or subsequent argument to a construction or projection operation let rec GetImmediateUseContext rargsl argsr = match argsr with - | (Expr.Val(VRefLocal vspec2, _, _)) :: argsr2 + | (Expr.Val (VRefLocal vspec2, _, _)) :: argsr2 when valEq vspec1 vspec2 && IsUniqueUse vspec2 (List.rev rargsl@argsr2) -> Some(List.rev rargsl, argsr2) - | argsrh :: argsrt when not (ExprHasEffect cenv.g argsrh) -> GetImmediateUseContext (argsrh::rargsl) argsrt + | argsrh :: argsrt when not (ExprHasEffect cenv.g argsrh) -> GetImmediateUseContext (argsrh :: rargsl) argsrt | _ -> None match stripExpr e2 with // Immediate consumption of value as itself 'let x = e in x' - | Expr.Val(VRefLocal vspec2, _, _) + | Expr.Val (VRefLocal vspec2, _, _) when IsUniqueUse vspec2 [] -> Some e1 // Immediate consumption of value by a pattern match 'let x = e in match x with ...' - | Expr.Match(spMatch, _exprm, TDSwitch(Expr.Val(VRefLocal vspec2, _, _), cases, dflt, _), targets, m, ty2) - when (valEq vspec1 vspec2 && not (ExprHasEffect cenv.g e1) && + | Expr.Match (spMatch, _exprm, TDSwitch(Expr.Val (VRefLocal vspec2, _, _), cases, dflt, _), targets, m, ty2) + when (valEq vspec1 vspec2 && +#if FABLE_COMPILER + not (ExprHasEffect cenv.g e1) && +#endif let fvs = accFreeInTargets CollectLocals targets (accFreeInSwitchCases CollectLocals cases dflt emptyFreeVars) not (Zset.contains vspec1 fvs.FreeLocals)) -> - let spMatch = spBind.Combine(spMatch) - Some (Expr.Match(spMatch, e1.Range, TDSwitch(e1, cases, dflt, m), targets, m, ty2)) + let spMatch = spBind.Combine spMatch + Some (Expr.Match (spMatch, e1.Range, TDSwitch(e1, cases, dflt, m), targets, m, ty2)) // Immediate consumption of value as a function 'let f = e in f ...' and 'let x = e in f ... x ...' // Note functions are evaluated before args // Note: do not include functions with a single arg of unit type, introduced by abstractBigTargets - | Expr.App(f, f0ty, tyargs, args, m) - when not (vspec1.LogicalName.Contains(suffixForVariablesThatMayNotBeEliminated)) -> - match GetImmediateUseContext [] (f::args) with + | Expr.App (f, f0ty, tyargs, args, m) + when not (vspec1.LogicalName.Contains suffixForVariablesThatMayNotBeEliminated) -> + match GetImmediateUseContext [] (f :: args) with | Some([], rargs) -> Some (MakeApplicationAndBetaReduce cenv.g (e1, f0ty, [tyargs], rargs, m)) - | Some(f::largs, rargs) -> Some (MakeApplicationAndBetaReduce cenv.g (f, f0ty, [tyargs], largs @ (e1::rargs), m)) + | Some(f :: largs, rargs) -> Some (MakeApplicationAndBetaReduce cenv.g (f, f0ty, [tyargs], largs @ (e1 :: rargs), m)) | None -> None // Bug 6311: a special case of nested elimination of locals (which really should be handled more generally) @@ -1459,7 +1463,7 @@ let TryEliminateBinding cenv _env (TBind(vspec1, e1, spBind)) e2 _m = // 'let x = e in op[x;....]' | Expr.Op (c, tyargs, args, m) -> match GetImmediateUseContext [] args with - | Some(largs, rargs) -> Some (Expr.Op (c, tyargs, (largs @ (e1:: rargs)), m)) + | Some(largs, rargs) -> Some (Expr.Op (c, tyargs, (largs @ (e1 :: rargs)), m)) | None -> None | _ -> @@ -1473,8 +1477,8 @@ let TryEliminateLet cenv env bind e2 m = /// Detect the application of a value to an arbitrary number of arguments let rec (|KnownValApp|_|) expr = match stripExpr expr with - | Expr.Val(vref, _, _) -> Some(vref, [], []) - | Expr.App(KnownValApp(vref, typeArgs1, otherArgs1), _, typeArgs2, otherArgs2, _) -> Some(vref, typeArgs1@typeArgs2, otherArgs1@otherArgs2) + | Expr.Val (vref, _, _) -> Some(vref, [], []) + | Expr.App (KnownValApp(vref, typeArgs1, otherArgs1), _, typeArgs2, otherArgs2, _) -> Some(vref, typeArgs1@typeArgs2, otherArgs1@otherArgs2) | _ -> None /// Matches boolean decision tree: @@ -1527,16 +1531,16 @@ and RewriteBoolLogicCase data (TCase(test, tree)) = TCase(test, RewriteBoolLogicTree data tree) /// Repeatedly combine switch-over-match decision trees, see https://github.com/Microsoft/visualfsharp/issues/635. -/// The outer decision tree is doing a swithc over a boolean result, the inner match is producing only +/// The outer decision tree is doing a switch over a boolean result, the inner match is producing only /// constant boolean results in its targets. let rec CombineBoolLogic expr = // try to find nested boolean switch match expr with - | Expr.Match(outerSP, outerMatchRange, - TDBoolSwitch(Expr.Match(_innerSP, _innerMatchRange, innerTree, innerTargets, _innerDefaultRange, _innerMatchTy), - outerTestBool, outerCaseTree, outerDefaultTree, _outerSwitchRange ), - outerTargets, outerDefaultRange, outerMatchTy) -> + | Expr.Match (outerSP, outerMatchRange, + TDBoolSwitch(Expr.Match (_innerSP, _innerMatchRange, innerTree, innerTargets, _innerDefaultRange, _innerMatchTy), + outerTestBool, outerCaseTree, outerDefaultTree, _outerSwitchRange ), + outerTargets, outerDefaultRange, outerMatchTy) -> let costOuterCaseTree = match outerCaseTree with TDSuccess _ -> 0 | _ -> 1 let costOuterDefaultTree = match outerDefaultTree with TDSuccess _ -> 0 | _ -> 1 @@ -1544,7 +1548,7 @@ let rec CombineBoolLogic expr = // At most one expression, no overall duplication of TSwitch nodes if tc <= costOuterCaseTree + costOuterDefaultTree && ec <= 10 then let newExpr = - Expr.Match(outerSP, outerMatchRange, + Expr.Match (outerSP, outerMatchRange, RewriteBoolLogicTree (innerTargets, outerCaseTree, outerDefaultTree, outerTestBool) innerTree, outerTargets, outerDefaultRange, outerMatchTy) @@ -1561,6 +1565,8 @@ let rec CombineBoolLogic expr = // Similarly for other structural constructions, like records... // If the item is only projected from then the construction (allocation) can be eliminated. // This transform encourages that by allowing projections to be simplified. +// +// Apply the same to 'Some(x)' constructions //------------------------------------------------------------------------- let CanExpandStructuralBinding (v: Val) = @@ -1571,7 +1577,13 @@ let CanExpandStructuralBinding (v: Val) = let ExprIsValue = function Expr.Val _ -> true | _ -> false +let MakeStructuralBindingTemp (v: Val) i (arg: Expr) argTy = + let name = v.LogicalName + "_" + string i + let v, ve = mkCompGenLocal arg.Range name argTy + ve, mkCompGenBind v arg + let ExpandStructuralBindingRaw cenv expr = + assert cenv.settings.ExpandStructuralValues() match expr with | Expr.Let (TBind(v, rhs, tgtSeqPtOpt), body, m, _) when (isRefTupleExpr rhs && @@ -1581,19 +1593,16 @@ let ExpandStructuralBindingRaw cenv expr = expr (* avoid re-expanding when recursion hits original binding *) else let argTys = destRefTupleTy cenv.g v.Type - let argBind i (arg: Expr) argTy = - let name = v.LogicalName + "_" + string i - let v, ve = mkCompGenLocal arg.Range name argTy - ve, mkCompGenBind v arg - - let ves, binds = List.mapi2 argBind args argTys |> List.unzip + let ves, binds = List.mapi2 (MakeStructuralBindingTemp v) args argTys |> List.unzip let tuple = mkRefTupled cenv.g m ves argTys mkLetsBind m binds (mkLet tgtSeqPtOpt m v tuple body) | expr -> expr // Moves outer tuple binding inside near the tupled expression: -// let t = (let a0=v0 in let a1=v1 in ... in let an=vn in e0, e1, ..., em) in body -// let a0=v0 in let a1=v1 in ... in let an=vn in (let t = e0, e1, ..., em in body) +// let t = (let a0=v0 in let a1=v1 in ... in let an=vn in e0, e1, ..., em) in body +// becomes +// let a0=v0 in let a1=v1 in ... in let an=vn in (let t = e0, e1, ..., em in body) +// // This way ExpandStructuralBinding can replace expressions in constants, t is directly bound // to a tuple expression so that other optimizations such as OptimizeTupleFieldGet work, // and the tuple allocation can be eliminated. @@ -1609,6 +1618,7 @@ let rec RearrangeTupleBindings expr fin = | _ -> None let ExpandStructuralBinding cenv expr = + assert cenv.settings.ExpandStructuralValues() match expr with | Expr.Let (TBind(v, rhs, tgtSeqPtOpt), body, m, _) when (isRefTupleTy cenv.g v.Type && @@ -1617,14 +1627,27 @@ let ExpandStructuralBinding cenv expr = match RearrangeTupleBindings rhs (fun top -> mkLet tgtSeqPtOpt m v top body) with | Some e -> ExpandStructuralBindingRaw cenv e | None -> expr - | e -> ExpandStructuralBindingRaw cenv e + + // Expand 'let v = Some arg in ...' to 'let tmp = arg in let v = Some tp in ...' + // Used to give names to values of optional arguments prior as we inline. + | Expr.Let (TBind(v, Expr.Op(TOp.UnionCase uc, _, [arg], _), tgtSeqPtOpt), body, m, _) + when isOptionTy cenv.g v.Type && + not (ExprIsValue arg) && + cenv.g.unionCaseRefEq uc (mkSomeCase cenv.g) && + CanExpandStructuralBinding v -> + let argTy = destOptionTy cenv.g v.Type + let ve, bind = MakeStructuralBindingTemp v 0 arg argTy + let newExpr = mkSome cenv.g argTy ve m + mkLetBind m bind (mkLet tgtSeqPtOpt m v newExpr body) + | e -> + ExpandStructuralBindingRaw cenv e /// Detect a query { ... } let (|QueryRun|_|) g expr = match expr with - | Expr.App(Expr.Val (vref, _, _), _, _, [_builder; arg], _) when valRefEq g vref g.query_run_value_vref -> + | Expr.App (Expr.Val (vref, _, _), _, _, [_builder; arg], _) when valRefEq g vref g.query_run_value_vref -> Some (arg, None) - | Expr.App(Expr.Val (vref, _, _), _, [ elemTy ], [_builder; arg], _) when valRefEq g vref g.query_run_enumerable_vref -> + | Expr.App (Expr.Val (vref, _, _), _, [ elemTy ], [_builder; arg], _) when valRefEq g vref g.query_run_enumerable_vref -> Some (arg, Some elemTy) | _ -> None @@ -1633,7 +1656,7 @@ let (|MaybeRefTupled|) e = tryDestRefTupleExpr e let (|AnyInstanceMethodApp|_|) e = match e with - | Expr.App(Expr.Val (vref, _, _), _, tyargs, [obj; MaybeRefTupled args], _) -> Some (vref, tyargs, obj, args) + | Expr.App (Expr.Val (vref, _, _), _, tyargs, [obj; MaybeRefTupled args], _) -> Some (vref, tyargs, obj, args) | _ -> None let (|InstanceMethodApp|_|) g (expectedValRef: ValRef) e = @@ -1673,15 +1696,11 @@ let (|AnyRefTupleTrans|) e = /// Look for any QueryBuilder.* operation and transform let (|AnyQueryBuilderOpTrans|_|) g = function - | Expr.App((Expr.Val (vref, _, _) as v), vty, tyargs, [builder; AnyRefTupleTrans( (src::rest), replaceArgs) ], m) when + | Expr.App ((Expr.Val (vref, _, _) as v), vty, tyargs, [builder; AnyRefTupleTrans( (src :: rest), replaceArgs) ], m) when (match vref.ApparentEnclosingEntity with Parent tcref -> tyconRefEq g tcref g.query_builder_tcref | ParentNone -> false) -> - Some (src, (fun newSource -> Expr.App(v, vty, tyargs, [builder; replaceArgs(newSource::rest)], m))) + Some (src, (fun newSource -> Expr.App (v, vty, tyargs, [builder; replaceArgs(newSource :: rest)], m))) | _ -> None -let mkUnitDelayLambda (g: TcGlobals) m e = - let uv, _ = mkCompGenLocal m "unitVar" g.unit_ty - mkLambda m uv (e, tyOfExpr g e) - /// If this returns "Some" then the source is not IQueryable. // := // | query.Select(, ) --> Seq.map(qexprInner', ...) @@ -1696,7 +1715,7 @@ let mkUnitDelayLambda (g: TcGlobals) m e = // | query.For(, ) --> IQueryable if qexprInner is IQueryable, otherwise seq { qexprInner' } // | query.Yield --> not IQueryable, seq { } // | query.YieldFrom --> not IQueryable, seq { yield! } -// | query.Op(, ) --> IQueryable if qexprOuter is IQueryable, otherwise query.Op(qexpOuter', ) +// | query.Op(, ) --> IQueryable if qexprOuter is IQueryable, otherwise query.Op(qexprOuter', ) let rec tryRewriteToSeqCombinators g (e: Expr) = let m = e.Range match e with @@ -1718,7 +1737,7 @@ let rec tryRewriteToSeqCombinators g (e: Expr) = Some (mkCallSeqEmpty g m sourceElemTy) // query.For --> Seq.collect - | QueryFor g (_qTy, sourceElemTy, resultElemTy, QuerySourceEnumerable g (_, source), Expr.Lambda(_, _, _, [resultSelectorVar], resultSelector, mLambda, _)) -> + | QueryFor g (_qTy, sourceElemTy, resultElemTy, QuerySourceEnumerable g (_, source), Expr.Lambda (_, _, _, [resultSelectorVar], resultSelector, mLambda, _)) -> match tryRewriteToSeqCombinators g resultSelector with | Some newResultSelector -> Some (mkCallSeqCollect g m sourceElemTy resultElemTy (mkLambda mLambda resultSelectorVar (newResultSelector, tyOfExpr g newResultSelector)) source) @@ -1726,10 +1745,10 @@ let rec tryRewriteToSeqCombinators g (e: Expr) = // let --> let - | Expr.Let(bind, bodyExpr, m, _) -> + | Expr.Let (bind, bodyExpr, m, _) -> match tryRewriteToSeqCombinators g bodyExpr with | Some newBodyExpr -> - Some (Expr.Let(bind, newBodyExpr, m, newCache())) + Some (Expr.Let (bind, newBodyExpr, m, newCache())) | None -> None // match --> match @@ -1757,7 +1776,7 @@ let TryDetectQueryQuoteAndRun cenv (expr: Expr) = | QueryRun g (bodyOfRun, reqdResultInfo) -> //printfn "found Query.Run" match bodyOfRun with - | Expr.Quote(quotedExpr, _, true, _, _) -> // true = isFromQueryExpression + | Expr.Quote (quotedExpr, _, true, _, _) -> // true = isFromQueryExpression // This traverses uses of query operators like query.Where and query.AverageBy until we're left with something familiar. @@ -1817,16 +1836,28 @@ let TryDetectQueryQuoteAndRun cenv (expr: Expr) = | _ -> //printfn "Not eliminating because no Run found" None - -let IsSystemStringConcatOverload (methRef: ILMethodRef) = - methRef.Name = "Concat" && methRef.DeclaringTypeRef.FullName = "System.String" && - methRef.ReturnType.BasicQualifiedName = "System.String" && - methRef.ArgTypes |> List.forall(fun ilty -> ilty.BasicQualifiedName = "System.String") - -let IsSystemStringConcatArray (methRef: ILMethodRef) = - methRef.Name = "Concat" && methRef.DeclaringTypeRef.FullName = "System.String" && - methRef.ReturnType.BasicQualifiedName = "System.String" && - methRef.ArgTypes.Length = 1 && methRef.ArgTypes.Head.BasicQualifiedName = "System.String[]" + +let IsILMethodRefSystemStringConcat (mref: ILMethodRef) = + mref.Name = "Concat" && + mref.DeclaringTypeRef.Name = "System.String" && + (mref.ReturnType.IsNominal && mref.ReturnType.TypeRef.Name = "System.String") && + (mref.ArgCount >= 2 && mref.ArgCount <= 4 && + mref.ArgTypes + |> List.forall (fun ilTy -> + ilTy.IsNominal && ilTy.TypeRef.Name = "System.String")) + +let IsILMethodRefSystemStringConcatArray (mref: ILMethodRef) = + mref.Name = "Concat" && + mref.DeclaringTypeRef.Name = "System.String" && + (mref.ReturnType.IsNominal && mref.ReturnType.TypeRef.Name = "System.String") && + (mref.ArgCount = 1 && + mref.ArgTypes + |> List.forall (fun ilTy -> + match ilTy with + | ILType.Array (shape, ilTy) when shape = ILArrayShape.SingleDimensional && + ilTy.IsNominal && + ilTy.TypeRef.Name = "System.String" -> true + | _ -> false)) /// Optimize/analyze an expression let rec OptimizeExpr cenv (env: IncrementalOptimizationEnv) expr = @@ -1851,9 +1882,9 @@ let rec OptimizeExpr cenv (env: IncrementalOptimizationEnv) expr = | Expr.Val (v, _vFlags, m) -> OptimizeVal cenv env expr (v, m) - | Expr.Quote(ast, splices, isFromQueryExpression, m, ty) -> + | Expr.Quote (ast, splices, isFromQueryExpression, m, ty) -> let splices = ref (splices.Value |> Option.map (map3Of4 (List.map (OptimizeExpr cenv env >> fst)))) - Expr.Quote(ast, splices, isFromQueryExpression, m, ty), + Expr.Quote (ast, splices, isFromQueryExpression, m, ty), { TotalSize = 10 FunctionSize = 1 HasEffect = false @@ -1866,18 +1897,18 @@ let rec OptimizeExpr cenv (env: IncrementalOptimizationEnv) expr = | Expr.Op (op, tyargs, args, m) -> OptimizeExprOp cenv env (op, tyargs, args, m) - | Expr.App(f, fty, tyargs, argsl, m) -> + | Expr.App (f, fty, tyargs, argsl, m) -> // eliminate uses of query match TryDetectQueryQuoteAndRun cenv expr with | Some newExpr -> OptimizeExpr cenv env newExpr | None -> OptimizeApplication cenv env (f, fty, tyargs, argsl, m) - | Expr.Lambda(_lambdaId, _, _, argvs, _body, m, rty) -> + | Expr.Lambda (_lambdaId, _, _, argvs, _body, m, rty) -> let topValInfo = ValReprInfo ([], [argvs |> List.map (fun _ -> ValReprInfo.unnamedTopArg1)], ValReprInfo.unnamedRetVal) let ty = mkMultiLambdaTy m argvs rty OptimizeLambdas None cenv env topValInfo expr ty - | Expr.TyLambda(_lambdaId, tps, _body, _m, rty) -> + | Expr.TyLambda (_lambdaId, tps, _body, _m, rty) -> let topValInfo = ValReprInfo (ValReprInfo.InferTyparInfo tps, [], ValReprInfo.unnamedRetVal) let ty = mkForallTyIfNeeded tps rty OptimizeLambdas None cenv env topValInfo expr ty @@ -1885,7 +1916,7 @@ let rec OptimizeExpr cenv (env: IncrementalOptimizationEnv) expr = | Expr.TyChoose _ -> OptimizeExpr cenv env (TypeRelations.ChooseTyparSolutionsForFreeChoiceTypars cenv.g cenv.amap expr) - | Expr.Match(spMatch, exprm, dtree, targets, m, ty) -> + | Expr.Match (spMatch, exprm, dtree, targets, m, ty) -> OptimizeMatch cenv env (spMatch, exprm, dtree, targets, m, ty) | Expr.LetRec (binds, bodyExpr, m, _) -> @@ -1894,7 +1925,7 @@ let rec OptimizeExpr cenv (env: IncrementalOptimizationEnv) expr = | Expr.StaticOptimization (constraints, expr2, expr3, m) -> let expr2R, e2info = OptimizeExpr cenv env expr2 let expr3R, e3info = OptimizeExpr cenv env expr3 - Expr.StaticOptimization(constraints, expr2R, expr3R, m), + Expr.StaticOptimization (constraints, expr2R, expr3R, m), { TotalSize = min e2info.TotalSize e3info.TotalSize FunctionSize = min e2info.FunctionSize e3info.FunctionSize HasEffect = e2info.HasEffect || e3info.HasEffect @@ -1953,14 +1984,16 @@ and OptimizeInterfaceImpl cenv env baseValOpt (ty, overrides) = and MakeOptimizedSystemStringConcatCall cenv env m args = let rec optimizeArg argExpr accArgs = match argExpr, accArgs with - | Expr.Op(TOp.ILCall(_, _, _, _, _, _, _, methRef, _, _, _), _, [ Expr.Op(TOp.Array, _, args, _) ], _), _ when IsSystemStringConcatArray methRef -> + | Expr.Op(TOp.ILCall(_, _, _, _, _, _, _, mref, _, _, _), _, [ Expr.Op(TOp.Array, _, args, _) ], _), _ + when IsILMethodRefSystemStringConcatArray mref -> optimizeArgs args accArgs - | Expr.Op(TOp.ILCall(_, _, _, _, _, _, _, methRef, _, _, _), _, args, _), _ when IsSystemStringConcatOverload methRef -> + | Expr.Op(TOp.ILCall(_, _, _, _, _, _, _, mref, _, _, _), _, args, _), _ + when IsILMethodRefSystemStringConcat mref -> optimizeArgs args accArgs // Optimize string constants, e.g. "1" + "2" will turn into "12" - | Expr.Const(Const.String str1, _, _), Expr.Const(Const.String str2, _, _) :: accArgs -> + | Expr.Const (Const.String str1, _, _), Expr.Const (Const.String str2, _, _) :: accArgs -> mkString cenv.g m (str1 + str2) :: accArgs | arg, _ -> arg :: accArgs @@ -1986,7 +2019,8 @@ and MakeOptimizedSystemStringConcatCall cenv env m args = mkStaticCall_String_Concat_Array cenv.g m arg match expr with - | Expr.Op(TOp.ILCall(_, _, _, _, _, _, _, methRef, _, _, _) as op, tyargs, args, m) when IsSystemStringConcatOverload methRef || IsSystemStringConcatArray methRef -> + | Expr.Op(TOp.ILCall(_, _, _, _, _, _, _, mref, _, _, _) as op, tyargs, args, m) + when IsILMethodRefSystemStringConcat mref || IsILMethodRefSystemStringConcatArray mref -> OptimizeExprOpReductions cenv env (op, tyargs, args, m) | _ -> OptimizeExpr cenv env expr @@ -2024,40 +2058,40 @@ and OptimizeExprOp cenv env (op, tyargs, args, m) = Info = ValueOfExpr newExpr } // Handle these as special cases since mutables are allowed inside their bodies - | TOp.While (spWhile, marker), _, [Expr.Lambda(_, _, _, [_], e1, _, _);Expr.Lambda(_, _, _, [_], e2, _, _)] -> + | TOp.While (spWhile, marker), _, [Expr.Lambda (_, _, _, [_], e1, _, _);Expr.Lambda (_, _, _, [_], e2, _, _)] -> OptimizeWhileLoop cenv { env with inLoop=true } (spWhile, marker, e1, e2, m) - | TOp.For(spStart, dir), _, [Expr.Lambda(_, _, _, [_], e1, _, _);Expr.Lambda(_, _, _, [_], e2, _, _);Expr.Lambda(_, _, _, [v], e3, _, _)] -> + | TOp.For (spStart, dir), _, [Expr.Lambda (_, _, _, [_], e1, _, _);Expr.Lambda (_, _, _, [_], e2, _, _);Expr.Lambda (_, _, _, [v], e3, _, _)] -> OptimizeFastIntegerForLoop cenv { env with inLoop=true } (spStart, v, e1, dir, e2, e3, m) - | TOp.TryFinally(spTry, spFinally), [resty], [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [_], e2, _, _)] -> + | TOp.TryFinally (spTry, spFinally), [resty], [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [_], e2, _, _)] -> OptimizeTryFinally cenv env (spTry, spFinally, e1, e2, m, resty) - | TOp.TryCatch(spTry, spWith), [resty], [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [vf], ef, _, _); Expr.Lambda(_, _, _, [vh], eh, _, _)] -> + | TOp.TryCatch (spTry, spWith), [resty], [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [vf], ef, _, _); Expr.Lambda (_, _, _, [vh], eh, _, _)] -> OptimizeTryCatch cenv env (e1, vf, ef, vh, eh, m, resty, spTry, spWith) - | TOp.TraitCall(traitInfo), [], args -> + | TOp.TraitCall traitInfo, [], args -> OptimizeTraitCall cenv env (traitInfo, args, m) // This code hooks arr.Length. The idea is to ensure loops end up in the "same shape"as the forms of loops that the .NET JIT // guarantees to optimize. | TOp.ILCall (_, _, _, _, _, _, _, mref, _enclTypeArgs, _methTypeArgs, _tys), _, [arg] - when (mref.DeclaringTypeRef.Scope.IsAssemblyRef && - mref.DeclaringTypeRef.Scope.AssemblyRef.Name = cenv.g.ilg.typ_Array.TypeRef.Scope.AssemblyRef.Name && - mref.DeclaringTypeRef.Name = cenv.g.ilg.typ_Array.TypeRef.Name && + when (mref.DeclaringTypeRef.Name = cenv.g.ilg.typ_Array.TypeRef.Name && mref.Name = "get_Length" && isArray1DTy cenv.g (tyOfExpr cenv.g arg)) -> - OptimizeExpr cenv env (Expr.Op(TOp.ILAsm(i_ldlen, [cenv.g.int_ty]), [], [arg], m)) + OptimizeExpr cenv env (Expr.Op (TOp.ILAsm (i_ldlen, [cenv.g.int_ty]), [], [arg], m)) // Empty IL instruction lists are used as casts in prim-types.fs. But we can get rid of them // if the types match up. - | TOp.ILAsm([], [ty]), _, [a] when typeEquiv cenv.g (tyOfExpr cenv.g a) ty -> OptimizeExpr cenv env a + | TOp.ILAsm ([], [ty]), _, [a] when typeEquiv cenv.g (tyOfExpr cenv.g a) ty -> OptimizeExpr cenv env a // Optimize calls when concatenating strings, e.g. "1" + "2" + "3" + "4" .. etc. - | TOp.ILCall(_, _, _, _, _, _, _, methRef, _, _, _), _, [ Expr.Op(TOp.Array, _, args, _) ] when IsSystemStringConcatArray methRef -> + | TOp.ILCall(_, _, _, _, _, _, _, mref, _, _, _), _, [ Expr.Op(TOp.Array, _, args, _) ] + when IsILMethodRefSystemStringConcatArray mref -> MakeOptimizedSystemStringConcatCall cenv env m args - | TOp.ILCall(_, _, _, _, _, _, _, methRef, _, _, _), _, args when IsSystemStringConcatOverload methRef -> + | TOp.ILCall(_, _, _, _, _, _, _, mref, _, _, _), _, args + when IsILMethodRefSystemStringConcat mref -> MakeOptimizedSystemStringConcatCall cenv env m args | _ -> @@ -2071,7 +2105,7 @@ and OptimizeExprOpReductions cenv env (op, tyargs, args, m) = and OptimizeExprOpReductionsAfter cenv env (op, tyargs, argsR, arginfos, m) = let knownValue = match op, arginfos with - | TOp.ValFieldGet (rf), [e1info] -> TryOptimizeRecordFieldGet cenv env (e1info, rf, tyargs, m) + | TOp.ValFieldGet rf, [e1info] -> TryOptimizeRecordFieldGet cenv env (e1info, rf, tyargs, m) | TOp.TupleFieldGet (tupInfo, n), [e1info] -> TryOptimizeTupleFieldGet cenv env (tupInfo, e1info, tyargs, n, m) | TOp.UnionCaseFieldGet (cspec, n), [e1info] -> TryOptimizeUnionCaseGet cenv env (e1info, cspec, tyargs, n, m) | _ -> None @@ -2083,7 +2117,7 @@ and OptimizeExprOpReductionsAfter cenv env (op, tyargs, argsR, arginfos, m) = | None -> OptimizeExprOpFallback cenv env (op, tyargs, argsR, m) arginfos UnknownValue and OptimizeExprOpFallback cenv env (op, tyargs, argsR, m) arginfos valu = - // The generic case - we may collect information, but the construction/projection doesnRt disappear + // The generic case - we may collect information, but the construction/projection doesn't disappear let argsTSize = AddTotalSizes arginfos let argsFSize = AddFunctionSizes arginfos let argEffects = OrEffects arginfos @@ -2117,7 +2151,7 @@ and OptimizeExprOpFallback cenv env (op, tyargs, argsR, m) arginfos valu = | StripUnionCaseValue (uc, info) -> UnionCaseValue(uc, info) | _ -> valu 0, valu - | TOp.ILAsm(instrs, tys) -> + | TOp.ILAsm (instrs, tys) -> min instrs.Length 1, mkAssemblyCodeValueInfo cenv.g instrs argValues tys | TOp.Bytes bytes -> bytes.Length/10, valu @@ -2157,7 +2191,7 @@ and OptimizeExprOpFallback cenv env (op, tyargs, argsR, m) arginfos valu = match TryOptimizeValInfo cenv env m vinfo with | Some res -> res, vinfo | None -> - Expr.Op(op, tyargs, argsR, m), + Expr.Op (op, tyargs, argsR, m), { TotalSize=argsTSize + cost FunctionSize=argsFSize + cost HasEffect=argEffects || effect @@ -2179,7 +2213,7 @@ and OptimizeConst cenv env expr (c, m, ty) = Info=MakeValueInfoForConst c ty} /// Optimize/analyze a record lookup. -and TryOptimizeRecordFieldGet cenv _env (e1info, (RFRef (rtcref, _) as r), _tinst, m) = +and TryOptimizeRecordFieldGet cenv _env (e1info, (RecdFieldRef (rtcref, _) as r), _tinst, m) = match destRecdValue e1info.Info with | Some finfos when cenv.settings.EliminateRecdFieldGet() && not e1info.HasEffect -> match TryFindFSharpAttribute cenv.g cenv.g.attrib_CLIMutableAttribute rtcref.Attribs with @@ -2201,7 +2235,7 @@ and TryOptimizeTupleFieldGet cenv _env (_tupInfo, e1info, tys, n, m) = and TryOptimizeUnionCaseGet cenv _env (e1info, cspec, _tys, n, m) = match e1info.Info with - | StripUnionCaseValue(cspec2, args) when cenv.settings.EliminatUnionCaseFieldGet() && not e1info.HasEffect && cenv.g.unionCaseRefEq cspec cspec2 -> + | StripUnionCaseValue(cspec2, args) when cenv.settings.EliminateUnionCaseFieldGet() && not e1info.HasEffect && cenv.g.unionCaseRefEq cspec cspec2 -> if n >= args.Length then errorR(InternalError( "TryOptimizeUnionCaseGet: term argument out of range", m)) Some args.[n] | _ -> None @@ -2218,13 +2252,13 @@ and OptimizeFastIntegerForLoop cenv env (spStart, v, e1, dir, e2, e3, m) = let e2R, dir = match dir, e2R with // detect upwards for loops with bounds of the form "arr.Length - 1" and convert them to a C#-style for loop - | FSharpForLoopUp, Expr.Op(TOp.ILAsm([ (AI_sub | AI_sub_ovf)], _), _, [Expr.Op(TOp.ILAsm([ I_ldlen; (AI_conv DT_I4)], _), _, [arre], _); Expr.Const(Const.Int32 1, _, _)], _) + | FSharpForLoopUp, Expr.Op (TOp.ILAsm ([ (AI_sub | AI_sub_ovf)], _), _, [Expr.Op (TOp.ILAsm ([ I_ldlen; (AI_conv DT_I4)], _), _, [arre], _); Expr.Const (Const.Int32 1, _, _)], _) when not (snd(OptimizeExpr cenv env arre)).HasEffect -> mkLdlen cenv.g (e2R.Range) arre, CSharpForLoopUp // detect upwards for loops with constant bounds, but not MaxValue! - | FSharpForLoopUp, Expr.Const(Const.Int32 n, _, _) + | FSharpForLoopUp, Expr.Const (Const.Int32 n, _, _) when n < System.Int32.MaxValue -> mkIncr cenv.g (e2R.Range) e2R, CSharpForLoopUp @@ -2259,7 +2293,7 @@ and OptimizeLetRec cenv env (binds, bodyExpr, m) = // Trim out any optimization info that involves escaping values let evalueR = AbstractExprInfoByVars (vs, []) einfo.Info // REVIEW: size of constructing new closures - should probably add #freevars + #recfixups here - let bodyExprR = Expr.LetRec(bindsRR, bodyExprR, m, NewFreeVarsCache()) + let bodyExprR = Expr.LetRec (bindsRR, bodyExprR, m, Construct.NewFreeVarsCache()) let info = CombineValueInfos (einfo :: bindinfos) evalueR bodyExprR, info @@ -2269,7 +2303,7 @@ and OptimizeLinearExpr cenv env expr contf = // Eliminate subsumption coercions for functions. This must be done post-typechecking because we need // complete inference types. let expr = DetectAndOptimizeForExpression cenv.g OptimizeAllForExpressions expr - let expr = if cenv.settings.ExpandStructrualValues() then ExpandStructuralBinding cenv expr else expr + let expr = if cenv.settings.ExpandStructuralValues() then ExpandStructuralBinding cenv expr else expr let expr = stripExpr expr match expr with @@ -2279,11 +2313,11 @@ and OptimizeLinearExpr cenv env expr contf = if (flag = NormalSeq) && // Always eliminate '(); expr' sequences, even in debug code, to ensure that // conditional method calls don't leave a dangling breakpoint (see FSharp 1.0 bug 6034) - (cenv.settings.EliminateSequential () || (match e1R with Expr.Const(Const.Unit, _, _) -> true | _ -> false)) && + (cenv.settings.EliminateSequential () || (match e1R with Expr.Const (Const.Unit, _, _) -> true | _ -> false)) && not e1info.HasEffect then e2R, e2info else - Expr.Sequential(e1R, e2R, flag, spSeq, m), + Expr.Sequential (e1R, e2R, flag, spSeq, m), { TotalSize = e1info.TotalSize + e2info.TotalSize FunctionSize = e1info.FunctionSize + e2info.FunctionSize HasEffect = flag <> NormalSeq || e1info.HasEffect || e2info.HasEffect @@ -2297,7 +2331,7 @@ and OptimizeLinearExpr cenv env expr contf = let (bindR, bindingInfo), env = OptimizeBinding cenv false env bind OptimizeLinearExpr cenv env body (contf << (fun (bodyR, bodyInfo) -> // PERF: This call to ValueIsUsedOrHasEffect/freeInExpr amounts to 9% of all optimization time. - // Is it quadratic or quasi-quadtratic? + // Is it quadratic or quasi-quadratic? if ValueIsUsedOrHasEffect cenv (fun () -> (freeInExpr CollectLocals bodyR).FreeLocals) (bindR, bindingInfo) then // Eliminate let bindings on the way back up let exprR, adjust = TryEliminateLet cenv env bindR bodyR m @@ -2350,10 +2384,10 @@ and OptimizeTryFinally cenv env (spTry, spFinally, e1, e2, m, ty) = if cenv.settings.EliminateTryCatchAndTryFinally () && not e1info.HasEffect then let sp = match spTry with - | SequencePointAtTry _ -> SequencePointsAtSeq - | SequencePointInBodyOfTry -> SequencePointsAtSeq - | NoSequencePointAtTry -> SuppressSequencePointOnExprOfSequential - Expr.Sequential(e1R, e2R, ThenDoSeq, sp, m), info + | DebugPointAtTry.Yes _ -> DebugPointAtSequential.Both + | DebugPointAtTry.Body -> DebugPointAtSequential.Both + | DebugPointAtTry.No -> DebugPointAtSequential.StmtOnly + Expr.Sequential (e1R, e2R, ThenDoSeq, sp, m), info else mkTryFinally cenv.g (e1R, e2R, m, ty, spTry, spFinally), info @@ -2402,7 +2436,7 @@ and OptimizeTraitCall cenv env (traitInfo, args, m) = // Resolution fails when optimizing generic code, ignore the failure | _ -> let argsR, arginfos = OptimizeExprsThenConsiderSplits cenv env args - OptimizeExprOpFallback cenv env (TOp.TraitCall(traitInfo), [], argsR, m) arginfos UnknownValue + OptimizeExprOpFallback cenv env (TOp.TraitCall traitInfo, [], argsR, m) arginfos UnknownValue /// Make optimization decisions once we know the optimization information /// for a value @@ -2511,13 +2545,13 @@ and CanDevirtualizeApplication cenv v vref ty args = and TakeAddressOfStructArgumentIfNeeded cenv (vref: ValRef) ty args m = if vref.IsInstanceMember && isStructTy cenv.g ty then match args with - | objArg::rest -> + | objArg :: rest -> // We set NeverMutates here, allowing more address-taking. This is valid because we only ever use DevirtualizeApplication to transform // known calls to known generated F# code for CompareTo, Equals and GetHashCode. // If we ever reuse DevirtualizeApplication to transform an arbitrary virtual call into a // direct call then this assumption is not valid. let wrap, objArgAddress, _readonly, _writeonly = mkExprAddrOfExpr cenv.g true false NeverMutates objArg None m - wrap, (objArgAddress::rest) + wrap, (objArgAddress :: rest) | _ -> // no wrapper, args stay the same id, args @@ -2538,19 +2572,19 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = // e.g rewrite // 'LanguagePrimitives.HashCompare.GenericComparisonIntrinsic (x: C) (y: C)' // --> 'x.CompareTo(y: C)' where this is a direct call to the implementation of CompareTo, i.e. - // C::CompareTo(C) - // not C::CompareTo(obj) + // C :: CompareTo(C) + // not C :: CompareTo(obj) // // If C is a struct type then we have to take the address of 'c' - | Expr.Val(v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_comparison_inner_vref ty args -> + | Expr.Val (v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_comparison_inner_vref ty args -> let tcref, tyargs = StripToNominalTyconRef cenv ty match tcref.GeneratedCompareToValues with | Some (_, vref) -> Some (DevirtualizeApplication cenv env vref ty tyargs args m) | _ -> None - | Expr.Val(v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_comparison_withc_inner_vref ty args -> + | Expr.Val (v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_comparison_withc_inner_vref ty args -> let tcref, tyargs = StripToNominalTyconRef cenv ty match tcref.GeneratedCompareToWithComparerValues, args with @@ -2566,7 +2600,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = // to be augmented with a visible equality-without-comparer value. // REVIEW: GenericEqualityIntrinsic (which has no comparer) implements PER semantics (5537: this should be ER semantics) // We are devirtualizing to a Equals(T) method which also implements PER semantics (5537: this should be ER semantics) - | Expr.Val(v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_equality_er_inner_vref ty args -> + | Expr.Val (v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_equality_er_inner_vref ty args -> let tcref, tyargs = StripToNominalTyconRef cenv ty match tcref.GeneratedHashAndEqualsValues with @@ -2574,7 +2608,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = | _ -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericEqualityWithComparerFast - | Expr.Val(v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_equality_withc_inner_vref ty args -> + | Expr.Val (v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_equality_withc_inner_vref ty args -> let tcref, tyargs = StripToNominalTyconRef cenv ty match tcref.GeneratedHashAndEqualsWithComparerValues, args with | Some (_, _, withcEqualsVal), [comp; x; y] -> @@ -2584,7 +2618,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = | _ -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericEqualityWithComparer - | Expr.Val(v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_equality_per_inner_vref ty args && not(isRefTupleTy cenv.g ty) -> + | Expr.Val (v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_equality_per_inner_vref ty args && not(isRefTupleTy cenv.g ty) -> let tcref, tyargs = StripToNominalTyconRef cenv ty match tcref.GeneratedHashAndEqualsWithComparerValues, args with | Some (_, _, withcEqualsVal), [x; y] -> @@ -2593,7 +2627,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = | _ -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericHashIntrinsic - | Expr.Val(v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_hash_inner_vref ty args -> + | Expr.Val (v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_hash_inner_vref ty args -> let tcref, tyargs = StripToNominalTyconRef cenv ty match tcref.GeneratedHashAndEqualsWithComparerValues, args with | Some (_, withcGetHashCodeVal, _), [x] -> @@ -2602,7 +2636,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = | _ -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericHashWithComparerIntrinsic - | Expr.Val(v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_hash_withc_inner_vref ty args -> + | Expr.Val (v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_hash_withc_inner_vref ty args -> let tcref, tyargs = StripToNominalTyconRef cenv ty match tcref.GeneratedHashAndEqualsWithComparerValues, args with | Some (_, withcGetHashCodeVal, _), [comp; x] -> @@ -2611,7 +2645,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = | _ -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericComparisonWithComparerIntrinsic for tuple types - | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_comparison_inner_vref && isRefTupleTy cenv.g ty -> + | Expr.Val (v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_comparison_inner_vref && isRefTupleTy cenv.g ty -> let tyargs = destRefTupleTy cenv.g ty let vref = match tyargs.Length with @@ -2625,7 +2659,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = | None -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericHashWithComparerIntrinsic for tuple types - | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_hash_inner_vref && isRefTupleTy cenv.g ty -> + | Expr.Val (v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_hash_inner_vref && isRefTupleTy cenv.g ty -> let tyargs = destRefTupleTy cenv.g ty let vref = match tyargs.Length with @@ -2641,7 +2675,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericEqualityIntrinsic for tuple types // REVIEW (5537): GenericEqualityIntrinsic implements PER semantics, and we are replacing it to something also // implementing PER semantics. However GenericEqualityIntrinsic should implement ER semantics. - | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_equality_per_inner_vref && isRefTupleTy cenv.g ty -> + | Expr.Val (v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_equality_per_inner_vref && isRefTupleTy cenv.g ty -> let tyargs = destRefTupleTy cenv.g ty let vref = match tyargs.Length with @@ -2655,7 +2689,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = | None -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericComparisonWithComparerIntrinsic for tuple types - | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_comparison_withc_inner_vref && isRefTupleTy cenv.g ty -> + | Expr.Val (v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_comparison_withc_inner_vref && isRefTupleTy cenv.g ty -> let tyargs = destRefTupleTy cenv.g ty let vref = match tyargs.Length with @@ -2669,7 +2703,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = | None -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericHashWithComparerIntrinsic for tuple types - | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_hash_withc_inner_vref && isRefTupleTy cenv.g ty -> + | Expr.Val (v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_hash_withc_inner_vref && isRefTupleTy cenv.g ty -> let tyargs = destRefTupleTy cenv.g ty let vref = match tyargs.Length with @@ -2683,7 +2717,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = | None -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericEqualityWithComparerIntrinsic for tuple types - | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_equality_withc_inner_vref && isRefTupleTy cenv.g ty -> + | Expr.Val (v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_equality_withc_inner_vref && isRefTupleTy cenv.g ty -> let tyargs = destRefTupleTy cenv.g ty let vref = match tyargs.Length with @@ -2699,7 +2733,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = // Calls to LanguagePrimitives.IntrinsicFunctions.UnboxGeneric can be optimized to calls to UnboxFast when we know that the // target type isn't 'NullNotLiked', i.e. that the target type is not an F# union, record etc. // Note UnboxFast is just the .NET IL 'unbox.any' instruction. - | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.unbox_vref && + | Expr.Val (v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.unbox_vref && canUseUnboxFast cenv.g m ty -> Some(DevirtualizeApplication cenv env cenv.g.unbox_fast_vref ty tyargs args m) @@ -2707,13 +2741,13 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = // Calls to LanguagePrimitives.IntrinsicFunctions.TypeTestGeneric can be optimized to calls to TypeTestFast when we know that the // target type isn't 'NullNotTrueValue', i.e. that the target type is not an F# union, record etc. // Note TypeTestFast is just the .NET IL 'isinst' instruction followed by a non-null comparison - | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.istype_vref && + | Expr.Val (v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.istype_vref && canUseTypeTestFast cenv.g ty -> Some(DevirtualizeApplication cenv env cenv.g.istype_fast_vref ty tyargs args m) // Don't fiddle with 'methodhandleof' calls - just remake the application - | Expr.Val(vref, _, _), _, _ when valRefEq cenv.g vref cenv.g.methodhandleof_vref -> + | Expr.Val (vref, _, _), _, _ when valRefEq cenv.g vref cenv.g.methodhandleof_vref -> Some( MakeApplicationAndBetaReduce cenv.g (exprForValRef m vref, vref.Type, (if isNil tyargs then [] else [tyargs]), args, m), { TotalSize=1 FunctionSize=1 @@ -2744,7 +2778,7 @@ and TryInlineApplication cenv env finfo (tyargs: TType list, args: Expr list, m) let isBaseCall = not (List.isEmpty args) && match args.[0] with - | Expr.Val(vref, _, _) when vref.BaseOrThisInfo = BaseVal -> true + | Expr.Val (vref, _, _) when vref.BaseOrThisInfo = BaseVal -> true | _ -> false if isBaseCall then None else @@ -2759,9 +2793,12 @@ and TryInlineApplication cenv env finfo (tyargs: TType list, args: Expr list, m) match finfo.Info with | ValValue(vref, _) -> match vref.ApparentEnclosingEntity with - | Parent(tcr) when (tyconRefEq cenv.g cenv.g.lazy_tcr_canon tcr) -> + | Parent tcr when (tyconRefEq cenv.g cenv.g.lazy_tcr_canon tcr) -> match tcr.CompiledRepresentation with - | CompiledTypeRepr.ILAsmNamed(iltr, _, _) -> iltr.Scope.AssemblyRef.Name = "FSharp.Core" + | CompiledTypeRepr.ILAsmNamed(iltr, _, _) -> + match iltr.Scope with + | ILScopeRef.Assembly aref -> aref.Name = "FSharp.Core" + | _ -> false | _ -> false | _ -> false | _ -> false @@ -2816,7 +2853,7 @@ and OptimizeApplication cenv env (f0, f0ty, tyargs, args, m) = let shapes = match newf0 with - | Expr.Val(vref, _, _) -> + | Expr.Val (vref, _, _) -> match vref.ValReprInfo with | Some(ValReprInfo(_, detupArgsL, _)) -> let nargs = args.Length @@ -2880,7 +2917,7 @@ and OptimizeApplication cenv env (f0, f0ty, tyargs, args, m) = and OptimizeLambdas (vspec: Val option) cenv env topValInfo e ety = match e with | Expr.Lambda (lambdaId, _, _, _, _, m, _) - | Expr.TyLambda(lambdaId, _, _, m, _) -> + | Expr.TyLambda (lambdaId, _, _, m, _) -> let tps, ctorThisValOpt, baseValOpt, vsl, body, bodyty = IteratedAdjustArityOfLambda cenv.g cenv.amap topValInfo e let env = { env with functionVal = (match vspec with None -> None | Some v -> Some (v, topValInfo)) } let env = Option.foldBack (BindInternalValToUnknown cenv) ctorThisValOpt env @@ -2966,7 +3003,7 @@ and OptimizeDecisionTreeTargets cenv env m targets = and ReshapeExpr cenv (shape, e) = match shape, e with - | TupleValue(subshapes), Expr.Val(_vref, _vFlags, m) -> + | TupleValue subshapes, Expr.Val (_vref, _vFlags, m) -> let tinst = destRefTupleTy cenv.g (tyOfExpr cenv.g e) let subshapes = Array.toList subshapes mkRefTupled cenv.g m (List.mapi (fun i subshape -> ReshapeExpr cenv (subshape, mkTupleFieldGet cenv.g (tupInfoRef, e, tinst, i, m))) subshapes) tinst @@ -3003,7 +3040,7 @@ and ComputeSplitToMethodCondition flag threshold cenv env (e: Expr, einfo) = // None of them should be byrefs not (isByrefLikeTy cenv.g m v.Type) && // None of them should be local polymorphic constrained values - not (IsGenericValWithGenericContraints cenv.g v) && + not (IsGenericValWithGenericConstraints cenv.g v) && // None of them should be mutable not v.IsMutable)))) && not (isByrefLikeTy cenv.g m (tyOfExpr cenv.g e)) @@ -3100,8 +3137,8 @@ and TryOptimizeDecisionTreeTest cenv test vinfo = match test, vinfo with | DecisionTreeTest.UnionCase (c1, _), StripUnionCaseValue(c2, _) -> Some(cenv.g.unionCaseRefEq c1 c2) | DecisionTreeTest.ArrayLength (_, _), _ -> None - | DecisionTreeTest.Const c1, StripConstValue(c2) -> if c1 = Const.Zero || c2 = Const.Zero then None else Some(c1=c2) - | DecisionTreeTest.IsNull, StripConstValue(c2) -> Some(c2=Const.Zero) + | DecisionTreeTest.Const c1, StripConstValue c2 -> if c1 = Const.Zero || c2 = Const.Zero then None else Some(c1=c2) + | DecisionTreeTest.IsNull, StripConstValue c2 -> Some(c2=Const.Zero) | DecisionTreeTest.IsInst (_srcty1, _tgty1), _ -> None // These should not occur in optimization | DecisionTreeTest.ActivePatternCase (_, _, _vrefOpt1, _, _), _ -> None @@ -3114,11 +3151,11 @@ and OptimizeSwitch cenv env (e, cases, dflt, m) = let cases, dflt = if cenv.settings.EliminateSwitch() && not einfo.HasEffect then // Attempt to find a definite success, i.e. the first case where there is definite success - match (List.tryFind (function (TCase(d2, _)) when TryOptimizeDecisionTreeTest cenv d2 einfo.Info = Some(true) -> true | _ -> false) cases) with - | Some(TCase(_, case)) -> [], Some(case) + match (List.tryFind (function (TCase(d2, _)) when TryOptimizeDecisionTreeTest cenv d2 einfo.Info = Some true -> true | _ -> false) cases) with + | Some(TCase(_, case)) -> [], Some case | _ -> // Filter definite failures - cases |> List.filter (function (TCase(d2, _)) when TryOptimizeDecisionTreeTest cenv d2 einfo.Info = Some(false) -> false | _ -> true), + cases |> List.filter (function (TCase(d2, _)) when TryOptimizeDecisionTreeTest cenv d2 einfo.Info = Some false -> false | _ -> true), dflt else cases, dflt @@ -3304,7 +3341,7 @@ and OptimizeModuleExpr cenv env x = | TMDefLet(bind, m) -> if Zset.contains bind.Var deadSet then TMDefRec(false, [], [], m) else x | TMDefDo _ -> x - | TMDefs(defs) -> TMDefs(List.map elimModDef defs) + | TMDefs defs -> TMDefs(List.map elimModDef defs) | TMAbstract _ -> x and elimModuleBinding x = @@ -3341,26 +3378,26 @@ and OptimizeModuleDef cenv (env, bindInfosColl) x = ModuleOrNamespaceInfos = NameMap.ofList minfos}), (env, bindInfosColl) - | TMAbstract(mexpr) -> + | TMAbstract mexpr -> let mexpr, info = OptimizeModuleExpr cenv env mexpr let env = BindValsInModuleOrNamespace cenv info env - (TMAbstract(mexpr), info), (env, bindInfosColl) + (TMAbstract mexpr, info), (env, bindInfosColl) | TMDefLet(bind, m) -> let ((bindR, binfo) as bindInfo), env = OptimizeBinding cenv false env bind (TMDefLet(bindR, m), notlazy { ValInfos=ValInfos [mkValBind bind (mkValInfo binfo bind.Var)] ModuleOrNamespaceInfos = NameMap.empty }), - (env, ([bindInfo]::bindInfosColl)) + (env, ([bindInfo] :: bindInfosColl)) | TMDefDo(e, m) -> let (e, _einfo) = OptimizeExpr cenv env e (TMDefDo(e, m), EmptyModuleInfo), (env, bindInfosColl) - | TMDefs(defs) -> + | TMDefs defs -> let (defs, info), (env, bindInfosColl) = OptimizeModuleDefs cenv (env, bindInfosColl) defs - (TMDefs(defs), info), (env, bindInfosColl) + (TMDefs defs, info), (env, bindInfosColl) and OptimizeModuleBindings cenv (env, bindInfosColl) xs = List.mapFold (OptimizeModuleBinding cenv) (env, bindInfosColl) xs @@ -3381,7 +3418,7 @@ and OptimizeModuleDefs cenv (env, bindInfosColl) defs = let defs, minfos = List.unzip defs (defs, UnionOptimizationInfos minfos), (env, bindInfosColl) -and OptimizeImplFileInternal cenv env isIncrementalFragment hidden (TImplFile(qname, pragmas, mexpr, hasExplicitEntryPoint, isScript, anonRecdTypes)) = +and OptimizeImplFileInternal cenv env isIncrementalFragment hidden (TImplFile (qname, pragmas, mexpr, hasExplicitEntryPoint, isScript, anonRecdTypes)) = let env, mexprR, minfo = match mexpr with // FSI: FSI compiles everything as if you're typing incrementally into one module @@ -3400,10 +3437,10 @@ and OptimizeImplFileInternal cenv env isIncrementalFragment hidden (TImplFile(qn let hidden = ComputeHidingInfoAtAssemblyBoundary mexpr.Type hidden let minfo = AbstractLazyModulInfoByHiding true hidden minfo - env, TImplFile(qname, pragmas, mexprR, hasExplicitEntryPoint, isScript, anonRecdTypes), minfo, hidden + env, TImplFile (qname, pragmas, mexprR, hasExplicitEntryPoint, isScript, anonRecdTypes), minfo, hidden /// Entry point -let OptimizeImplFile(settings, ccu, tcGlobals, tcVal, importMap, optEnv, isIncrementalFragment, emitTailcalls, hidden, mimpls) = +let OptimizeImplFile (settings, ccu, tcGlobals, tcVal, importMap, optEnv, isIncrementalFragment, emitTailcalls, hidden, mimpls) = let cenv = { settings=settings scope=ccu diff --git a/src/fcs-fable/src/fsharp/Optimizer.fsi b/src/fcs-fable/src/fsharp/Optimizer.fsi old mode 100755 new mode 100644 index e156a26d3e..2a3de71536 --- a/src/fcs-fable/src/fsharp/Optimizer.fsi +++ b/src/fcs-fable/src/fsharp/Optimizer.fsi @@ -3,57 +3,61 @@ module internal FSharp.Compiler.Optimizer open FSharp.Compiler -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.TypedTreePickle type OptimizationSettings = - { abstractBigTargets : bool - jitOptUser : bool option - localOptUser : bool option - crossModuleOptUser : bool option - bigTargetSize : int - veryBigExprSize : int - lambdaInlineThreshold : int - reportingPhase : bool; + { abstractBigTargets: bool + jitOptUser: bool option + localOptUser: bool option + crossModuleOptUser: bool option + bigTargetSize: int + veryBigExprSize: int + lambdaInlineThreshold: int + reportingPhase: bool; reportNoNeedToTailcall: bool - reportFunctionSizes : bool - reportHasEffect : bool - reportTotalSizes : bool } + reportFunctionSizes: bool + reportHasEffect: bool + reportTotalSizes: bool } - member jitOpt : unit -> bool - member localOpt : unit -> bool - static member Defaults : OptimizationSettings + member jitOpt: unit -> bool + member localOpt: unit -> bool + static member Defaults: OptimizationSettings /// Optimization information type ModuleInfo + type LazyModuleInfo = Lazy + type ImplFileOptimizationInfo = LazyModuleInfo + type CcuOptimizationInfo = LazyModuleInfo [] type IncrementalOptimizationEnv = - static member Empty : IncrementalOptimizationEnv + static member Empty: IncrementalOptimizationEnv /// For building optimization environments incrementally -val internal BindCcu : CcuThunk -> CcuOptimizationInfo -> IncrementalOptimizationEnv -> TcGlobals -> IncrementalOptimizationEnv +val internal BindCcu: CcuThunk -> CcuOptimizationInfo -> IncrementalOptimizationEnv -> TcGlobals -> IncrementalOptimizationEnv /// Optimize one implementation file in the given environment -val internal OptimizeImplFile : OptimizationSettings * CcuThunk * TcGlobals * ConstraintSolver.TcValF * Import.ImportMap * IncrementalOptimizationEnv * isIncrementalFragment: bool * emitTaicalls: bool * SignatureHidingInfo * TypedImplFile -> (IncrementalOptimizationEnv * TypedImplFile * ImplFileOptimizationInfo * SignatureHidingInfo) * (Expr -> Expr) +val internal OptimizeImplFile: OptimizationSettings * CcuThunk * TcGlobals * ConstraintSolver.TcValF * Import.ImportMap * IncrementalOptimizationEnv * isIncrementalFragment: bool * emitTaicalls: bool * SignatureHidingInfo * TypedImplFile -> (IncrementalOptimizationEnv * TypedImplFile * ImplFileOptimizationInfo * SignatureHidingInfo) * (Expr -> Expr) #if DEBUG /// Displaying optimization data -val internal moduleInfoL : TcGlobals -> LazyModuleInfo -> Layout.layout +val internal moduleInfoL: TcGlobals -> LazyModuleInfo -> Layout.layout #endif /// Saving and re-reading optimization information -val p_CcuOptimizationInfo : CcuOptimizationInfo -> TastPickle.WriterState -> unit +val p_CcuOptimizationInfo: CcuOptimizationInfo -> WriterState -> unit /// Rewrite the module info using the export remapping -val RemapOptimizationInfo : TcGlobals -> Tastops.Remap -> (CcuOptimizationInfo -> CcuOptimizationInfo) +val RemapOptimizationInfo: TcGlobals -> Remap -> (CcuOptimizationInfo -> CcuOptimizationInfo) /// Ensure that 'internal' items are not exported in the optimization info -val AbstractOptimizationInfoToEssentials : (CcuOptimizationInfo -> CcuOptimizationInfo) +val AbstractOptimizationInfoToEssentials: (CcuOptimizationInfo -> CcuOptimizationInfo) /// Combine optimization infos val UnionOptimizationInfos: seq -> CcuOptimizationInfo @@ -61,4 +65,4 @@ val UnionOptimizationInfos: seq -> CcuOptimizationInfo /// Check if an expression has an effect val ExprHasEffect: TcGlobals -> Expr -> bool -val internal u_CcuOptimizationInfo : TastPickle.ReaderState -> CcuOptimizationInfo +val internal u_CcuOptimizationInfo: ReaderState -> CcuOptimizationInfo \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/ParseHelpers.fs b/src/fcs-fable/src/fsharp/ParseHelpers.fs new file mode 100644 index 0000000000..0024246643 --- /dev/null +++ b/src/fcs-fable/src/fsharp/ParseHelpers.fs @@ -0,0 +1,234 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +module public FSharp.Compiler.ParseHelpers + +open FSharp.Compiler.AbstractIL +open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.UnicodeLexing +open FSharp.Compiler.XmlDoc +open Internal.Utilities.Text.Lexing +open Internal.Utilities.Text.Parsing + +//------------------------------------------------------------------------ +// Parsing: Error recovery exception for fsyacc +//------------------------------------------------------------------------ + +/// The error raised by the parse_error_rich function, which is called by the parser engine +/// when a syntax error occurs. The first object is the ParseErrorContext which contains a dump of +/// information about the grammar at the point where the error occurred, e.g. what tokens +/// are valid to shift next at that point in the grammar. This information is processed in CompileOps.fs. +[] +exception SyntaxError of obj (* ParseErrorContext<_> *) * range: range + +//------------------------------------------------------------------------ +// Parsing: getting positions from the lexer +//------------------------------------------------------------------------ + +/// Get an F# compiler position from a lexer position +let internal posOfLexPosition (p: Position) = + mkPos p.Line p.Column + +/// Get an F# compiler range from a lexer range +let internal mkSynRange (p1: Position) (p2: Position) = + mkFileIndexRange p1.FileIndex (posOfLexPosition p1) (posOfLexPosition p2) + +type LexBuffer<'Char> with + member internal lexbuf.LexemeRange = mkSynRange lexbuf.StartPos lexbuf.EndPos + +/// Get the range corresponding to the result of a grammar rule while it is being reduced +let internal lhs (parseState: IParseState) = + let p1 = parseState.ResultStartPosition + let p2 = parseState.ResultEndPosition + mkSynRange p1 p2 + +/// Get the range covering two of the r.h.s. symbols of a grammar rule while it is being reduced +let internal rhs2 (parseState: IParseState) i j = + let p1 = parseState.InputStartPosition i + let p2 = parseState.InputEndPosition j + mkSynRange p1 p2 + +/// Get the range corresponding to one of the r.h.s. symbols of a grammar rule while it is being reduced +let internal rhs parseState i = rhs2 parseState i i + +type IParseState with + + /// Get the generator used for compiler-generated argument names. + member internal x.SynArgNameGenerator = + let key = "SynArgNameGenerator" + let bls = x.LexBuffer.BufferLocalStore + let gen = + match bls.TryGetValue key with + | true, gen -> gen + | _ -> + let gen = box (SynArgNameGenerator()) + bls.[key] <- gen + gen + gen :?> SynArgNameGenerator + + /// Reset the generator used for compiler-generated argument names. + member internal x.ResetSynArgNameGenerator() = x.SynArgNameGenerator.Reset() + +//------------------------------------------------------------------------ +// Parsing: grabbing XmlDoc +//------------------------------------------------------------------------ + +/// XmlDoc F# lexer/parser state, held in the BufferLocalStore for the lexer. +/// This is the only use of the lexer BufferLocalStore in the codebase. +module LexbufLocalXmlDocStore = + // The key into the BufferLocalStore used to hold the current accumulated XmlDoc lines + let private xmlDocKey = "XmlDoc" + + let internal ClearXmlDoc (lexbuf: Lexbuf) = + lexbuf.BufferLocalStore.[xmlDocKey] <- box (XmlDocCollector()) + + /// Called from the lexer to save a single line of XML doc comment. + let internal SaveXmlDocLine (lexbuf: Lexbuf, lineText, pos) = + let collector = + match lexbuf.BufferLocalStore.TryGetValue xmlDocKey with + | true, collector -> collector + | _ -> + let collector = box (XmlDocCollector()) + lexbuf.BufferLocalStore.[xmlDocKey] <- collector + collector + let collector = unbox(collector) + collector.AddXmlDocLine(lineText, pos) + + /// Called from the parser each time we parse a construct that marks the end of an XML doc comment range, + /// e.g. a 'type' declaration. The markerRange is the range of the keyword that delimits the construct. + let internal GrabXmlDocBeforeMarker (lexbuf: Lexbuf, markerRange: range) = + match lexbuf.BufferLocalStore.TryGetValue xmlDocKey with + | true, collector -> + let collector = unbox(collector) + PreXmlDoc.CreateFromGrabPoint(collector, markerRange.End) + | _ -> + PreXmlDoc.Empty + + +//------------------------------------------------------------------------ +// Parsing/lexing: status of #if/#endif processing in lexing, used for continutations +// for whitespace tokens in parser specification. +//------------------------------------------------------------------------ + +type LexerIfdefStackEntry = + | IfDefIf + | IfDefElse + +type LexerIfdefStackEntries = (LexerIfdefStackEntry * range) list + +type LexerIfdefStack = LexerIfdefStackEntries + +/// Specifies how the 'endline' function in the lexer should continue after +/// it reaches end of line or eof. The options are to continue with 'token' function +/// or to continue with 'skip' function. +type LexerEndlineContinuation = + | Token of LexerIfdefStackEntries + | Skip of LexerIfdefStackEntries * int * range: range + member x.LexerIfdefStack = + match x with + | LexerEndlineContinuation.Token ifd + | LexerEndlineContinuation.Skip(ifd, _, _) -> ifd + +type LexerIfdefExpression = + | IfdefAnd of LexerIfdefExpression*LexerIfdefExpression + | IfdefOr of LexerIfdefExpression*LexerIfdefExpression + | IfdefNot of LexerIfdefExpression + | IfdefId of string + +let rec LexerIfdefEval (lookup: string -> bool) = function + | IfdefAnd (l, r) -> (LexerIfdefEval lookup l) && (LexerIfdefEval lookup r) + | IfdefOr (l, r) -> (LexerIfdefEval lookup l) || (LexerIfdefEval lookup r) + | IfdefNot e -> not (LexerIfdefEval lookup e) + | IfdefId id -> lookup id + +//------------------------------------------------------------------------ +// Parsing: continuations for whitespace tokens +//------------------------------------------------------------------------ + +/// The parser defines a number of tokens for whitespace and +/// comments eliminated by the lexer. These carry a specification of +/// a continuation for the lexer for continued processing after we've dealt with +/// the whitespace. +[] +[] +type LexerWhitespaceContinuation = + | Token of ifdef: LexerIfdefStackEntries + | IfDefSkip of ifdef: LexerIfdefStackEntries * int * range: range + | String of ifdef: LexerIfdefStackEntries * range: range + | VerbatimString of ifdef: LexerIfdefStackEntries * range: range + | TripleQuoteString of ifdef: LexerIfdefStackEntries * range: range + | Comment of ifdef: LexerIfdefStackEntries * int * range: range + | SingleLineComment of ifdef: LexerIfdefStackEntries * int * range: range + | StringInComment of ifdef: LexerIfdefStackEntries * int * range: range + | VerbatimStringInComment of ifdef: LexerIfdefStackEntries * int * range: range + | TripleQuoteStringInComment of ifdef: LexerIfdefStackEntries * int * range: range + | MLOnly of ifdef: LexerIfdefStackEntries * range: range + | EndLine of LexerEndlineContinuation + + member x.LexerIfdefStack = + match x with + | LexCont.Token (ifdef=ifd) + | LexCont.IfDefSkip (ifdef=ifd) + | LexCont.String (ifdef=ifd) + | LexCont.VerbatimString (ifdef=ifd) + | LexCont.Comment (ifdef=ifd) + | LexCont.SingleLineComment (ifdef=ifd) + | LexCont.TripleQuoteString (ifdef=ifd) + | LexCont.StringInComment (ifdef=ifd) + | LexCont.VerbatimStringInComment (ifdef=ifd) + | LexCont.TripleQuoteStringInComment (ifdef=ifd) + | LexCont.MLOnly (ifdef=ifd) -> ifd + | LexCont.EndLine endl -> endl.LexerIfdefStack + +and LexCont = LexerWhitespaceContinuation + +//------------------------------------------------------------------------ +// Parse IL assembly code +//------------------------------------------------------------------------ + +let internal internalParseAssemblyCodeInstructions s isFeatureSupported m = +#if NO_INLINE_IL_PARSER + ignore s + ignore isFeatureSupported + + errorR(Error((193, "Inline IL not valid in a hosted environment"), m)) + [| |] +#else + try + FSharp.Compiler.AbstractIL.Internal.AsciiParser.ilInstrs + FSharp.Compiler.AbstractIL.Internal.AsciiLexer.token + (UnicodeLexing.StringAsLexbuf(isFeatureSupported, s)) + with _ -> + errorR(Error(FSComp.SR.astParseEmbeddedILError(), m)); [||] +#endif + +let ParseAssemblyCodeInstructions s m = + // Public API can not answer the isFeatureSupported questions, so here we support everything + let isFeatureSupported (_featureId:LanguageFeature) = true + internalParseAssemblyCodeInstructions s isFeatureSupported m + +let internal internalParseAssemblyCodeType s isFeatureSupported m = + ignore s + ignore isFeatureSupported + +#if NO_INLINE_IL_PARSER + errorR(Error((193, "Inline IL not valid in a hosted environment"), m)) + IL.EcmaMscorlibILGlobals.typ_Object +#else + let isFeatureSupported (_featureId:LanguageFeature) = true + try + FSharp.Compiler.AbstractIL.Internal.AsciiParser.ilType + FSharp.Compiler.AbstractIL.Internal.AsciiLexer.token + (UnicodeLexing.StringAsLexbuf(isFeatureSupported, s)) + with RecoverableParseError -> + errorR(Error(FSComp.SR.astParseEmbeddedILTypeError(), m)); + IL.EcmaMscorlibILGlobals.typ_Object +#endif + +/// Helper for parsing the inline IL fragments. +let ParseAssemblyCodeType s m = + // Public API can not answer the isFeatureSupported questions, so here we support everything + let isFeatureSupported (_featureId:LanguageFeature) = true + internalParseAssemblyCodeType s isFeatureSupported m diff --git a/src/fcs-fable/src/fsharp/PatternMatchCompilation.fs b/src/fcs-fable/src/fsharp/PatternMatchCompilation.fs old mode 100755 new mode 100644 index 0f4bf494ca..1864bfed8c --- a/src/fcs-fable/src/fsharp/PatternMatchCompilation.fs +++ b/src/fcs-fable/src/fsharp/PatternMatchCompilation.fs @@ -7,16 +7,18 @@ open FSharp.Compiler open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Diagnostics -open FSharp.Compiler.Range -open FSharp.Compiler.Ast +open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.Tastops.DebugPrint +open FSharp.Compiler.Lib open FSharp.Compiler.PrettyNaming -open FSharp.Compiler.TypeRelations +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Lib +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.TypedTreeOps.DebugPrint +open FSharp.Compiler.TypeRelations exception MatchIncomplete of bool * (string * bool) option * range exception RuleNeverMatched of range @@ -30,7 +32,6 @@ type ActionOnFailure = | FailFilter [] -/// Represents type-checked patterns type Pattern = | TPat_const of Const * range | TPat_wild of range (* note = TPat_disjs([], m), but we haven't yet removed that duplication *) @@ -46,6 +47,8 @@ type Pattern = | TPat_range of char * char * range | TPat_null of range | TPat_isinst of TType * TType * PatternValBinding option * range + | TPat_error of range + member this.Range = match this with | TPat_const(_, m) -> m @@ -60,8 +63,9 @@ type Pattern = | TPat_array(_, _, m) -> m | TPat_recd(_, _, _, m) -> m | TPat_range(_, _, m) -> m - | TPat_null(m) -> m + | TPat_null m -> m | TPat_isinst(_, _, _, m) -> m + | TPat_error m -> m and PatternValBinding = PBind of Val * TypeScheme @@ -104,16 +108,16 @@ let BindSubExprOfInput g amap gtps (PBind(v, tyscheme)) m (SubExpr(accessf, (ve2 accessf [] ve2 else let tyargs = - let someSolved = ref false + let mutable someSolved = false let freezeVar gtp = if isBeingGeneralized gtp tyscheme then mkTyparTy gtp else - someSolved := true + someSolved <- true TypeRelations.ChooseTyparSolution g amap gtp let solutions = List.map freezeVar gtps - if !someSolved then + if someSolved then TypeRelations.IterativelySubstituteTyparSolutions g gtps solutions else solutions @@ -152,7 +156,7 @@ let rec pathEq p1 p2 = | PathUnionConstr(p1, _, _, n1), PathUnionConstr(p2, _, _, n2) -> (n1 = n2) && pathEq p1 p2 | PathArray(p1, _, _, n1), PathArray(p2, _, _, n2) -> (n1 = n2) && pathEq p1 p2 | PathExnConstr(p1, _, n1), PathExnConstr(p2, _, n2) -> (n1 = n2) && pathEq p1 p2 - | PathEmpty(_), PathEmpty(_) -> true + | PathEmpty _, PathEmpty _ -> true | _ -> false @@ -202,21 +206,21 @@ let RefuteDiscrimSet g m path discrims = go p (fun _ -> mkRefTupled g m k tys, eCoversVals) | PathRecd (p, tcref, tinst, j) -> let flds, eCoversVals = tcref |> actualTysOfInstanceRecdFields (mkTyconRefInst tcref tinst) |> mkOneKnown tm j - go p (fun _ -> Expr.Op(TOp.Recd(RecdExpr, tcref), tinst, flds, m), eCoversVals) + go p (fun _ -> Expr.Op (TOp.Recd (RecdExpr, tcref), tinst, flds, m), eCoversVals) | PathUnionConstr (p, ucref, tinst, j) -> let flds, eCoversVals = ucref |> actualTysOfUnionCaseFields (mkTyconRefInst ucref.TyconRef tinst)|> mkOneKnown tm j - go p (fun _ -> Expr.Op(TOp.UnionCase(ucref), tinst, flds, m), eCoversVals) + go p (fun _ -> Expr.Op (TOp.UnionCase ucref, tinst, flds, m), eCoversVals) | PathArray (p, ty, len, n) -> let flds, eCoversVals = mkOneKnown tm n (List.replicate len ty) - go p (fun _ -> Expr.Op(TOp.Array, [ty], flds, m), eCoversVals) + go p (fun _ -> Expr.Op (TOp.Array, [ty], flds, m), eCoversVals) | PathExnConstr (p, ecref, n) -> let flds, eCoversVals = ecref |> recdFieldTysOfExnDefRef |> mkOneKnown tm n - go p (fun _ -> Expr.Op(TOp.ExnConstr(ecref), [], flds, m), eCoversVals) + go p (fun _ -> Expr.Op (TOp.ExnConstr ecref, [], flds, m), eCoversVals) - | PathEmpty(ty) -> tm ty + | PathEmpty ty -> tm ty and mkOneKnown tm n tys = let flds = List.mapi (fun i ty -> if i = n then tm ty else (mkUnknown ty, false)) tys @@ -230,21 +234,21 @@ let RefuteDiscrimSet g m path discrims = | [DecisionTreeTest.IsInst (_, _)] -> snd(mkCompGenLocal m otherSubtypeText ty), false | (DecisionTreeTest.Const c :: rest) -> - let consts = Set.ofList (c :: List.choose (function DecisionTreeTest.Const(c) -> Some c | _ -> None) rest) + let consts = Set.ofList (c :: List.choose (function DecisionTreeTest.Const c -> Some c | _ -> None) rest) let c' = - Seq.tryFind (fun c -> not (consts.Contains(c))) + Seq.tryFind (fun c -> not (consts.Contains c)) (match c with - | Const.Bool _ -> [ true; false ] |> List.toSeq |> Seq.map (fun v -> Const.Bool(v)) - | Const.SByte _ -> Seq.append (seq { 0y .. System.SByte.MaxValue }) (seq { System.SByte.MinValue .. 0y })|> Seq.map (fun v -> Const.SByte(v)) - | Const.Int16 _ -> Seq.append (seq { 0s .. System.Int16.MaxValue }) (seq { System.Int16.MinValue .. 0s }) |> Seq.map (fun v -> Const.Int16(v)) - | Const.Int32 _ -> Seq.append (seq { 0 .. System.Int32.MaxValue }) (seq { System.Int32.MinValue .. 0 })|> Seq.map (fun v -> Const.Int32(v)) - | Const.Int64 _ -> Seq.append (seq { 0L .. System.Int64.MaxValue }) (seq { System.Int64.MinValue .. 0L })|> Seq.map (fun v -> Const.Int64(v)) - | Const.IntPtr _ -> Seq.append (seq { 0L .. System.Int64.MaxValue }) (seq { System.Int64.MinValue .. 0L })|> Seq.map (fun v -> Const.IntPtr(v)) - | Const.Byte _ -> seq { 0uy .. System.Byte.MaxValue } |> Seq.map (fun v -> Const.Byte(v)) - | Const.UInt16 _ -> seq { 0us .. System.UInt16.MaxValue } |> Seq.map (fun v -> Const.UInt16(v)) - | Const.UInt32 _ -> seq { 0u .. System.UInt32.MaxValue } |> Seq.map (fun v -> Const.UInt32(v)) - | Const.UInt64 _ -> seq { 0UL .. System.UInt64.MaxValue } |> Seq.map (fun v -> Const.UInt64(v)) - | Const.UIntPtr _ -> seq { 0UL .. System.UInt64.MaxValue } |> Seq.map (fun v -> Const.UIntPtr(v)) + | Const.Bool _ -> [ true; false ] |> List.toSeq |> Seq.map (fun v -> Const.Bool v) + | Const.SByte _ -> Seq.append (seq { 0y .. System.SByte.MaxValue }) (seq { System.SByte.MinValue .. 0y })|> Seq.map (fun v -> Const.SByte v) + | Const.Int16 _ -> Seq.append (seq { 0s .. System.Int16.MaxValue }) (seq { System.Int16.MinValue .. 0s }) |> Seq.map (fun v -> Const.Int16 v) + | Const.Int32 _ -> Seq.append (seq { 0 .. System.Int32.MaxValue }) (seq { System.Int32.MinValue .. 0 })|> Seq.map (fun v -> Const.Int32 v) + | Const.Int64 _ -> Seq.append (seq { 0L .. System.Int64.MaxValue }) (seq { System.Int64.MinValue .. 0L })|> Seq.map (fun v -> Const.Int64 v) + | Const.IntPtr _ -> Seq.append (seq { 0L .. System.Int64.MaxValue }) (seq { System.Int64.MinValue .. 0L })|> Seq.map (fun v -> Const.IntPtr v) + | Const.Byte _ -> seq { 0uy .. System.Byte.MaxValue } |> Seq.map (fun v -> Const.Byte v) + | Const.UInt16 _ -> seq { 0us .. System.UInt16.MaxValue } |> Seq.map (fun v -> Const.UInt16 v) + | Const.UInt32 _ -> seq { 0u .. System.UInt32.MaxValue } |> Seq.map (fun v -> Const.UInt32 v) + | Const.UInt64 _ -> seq { 0UL .. System.UInt64.MaxValue } |> Seq.map (fun v -> Const.UInt64 v) + | Const.UIntPtr _ -> seq { 0UL .. System.UInt64.MaxValue } |> Seq.map (fun v -> Const.UIntPtr v) | Const.Double _ -> seq { 0 .. System.Int32.MaxValue } |> Seq.map (fun v -> Const.Double(float v)) | Const.Single _ -> seq { 0 .. System.Int32.MaxValue } |> Seq.map (fun v -> Const.Single(float32 v)) | Const.Char _ -> seq { 32us .. System.UInt16.MaxValue } |> Seq.map (fun v -> Const.Char(char v)) @@ -256,7 +260,7 @@ let RefuteDiscrimSet g m path discrims = match c' with | None -> raise CannotRefute | Some c -> - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref when tcref.IsEnumTycon -> // We must distinguish between F#-defined enums and other .NET enums, as they are represented differently in the TAST let enumValues = @@ -277,11 +281,11 @@ let RefuteDiscrimSet g m path discrims = let nonCoveredEnumValues = Seq.tryFind (fun (_, fldValue) -> not (consts.Contains fldValue)) enumValues match nonCoveredEnumValues with - | None -> Expr.Const(c, m, ty), true + | None -> Expr.Const (c, m, ty), true | Some (fldName, _) -> - let v = RecdFieldRef.RFRef(tcref, fldName) - Expr.Op(TOp.ValFieldGet v, [ty], [], m), false - | _ -> Expr.Const(c, m, ty), false + let v = RecdFieldRef.RecdFieldRef(tcref, fldName) + Expr.Op (TOp.ValFieldGet v, [ty], [], m), false + | _ -> Expr.Const (c, m, ty), false | (DecisionTreeTest.UnionCase (ucref1, tinst) :: rest) -> let ucrefs = ucref1 :: List.choose (function DecisionTreeTest.UnionCase(ucref, _) -> Some ucref | _ -> None) rest @@ -295,10 +299,10 @@ let RefuteDiscrimSet g m path discrims = | [] -> raise CannotRefute | ucref2 :: _ -> let flds = ucref2 |> actualTysOfUnionCaseFields (mkTyconRefInst tcref tinst) |> mkUnknowns - Expr.Op(TOp.UnionCase(ucref2), tinst, flds, m), false + Expr.Op (TOp.UnionCase ucref2, tinst, flds, m), false | [DecisionTreeTest.ArrayLength (n, ty)] -> - Expr.Op(TOp.Array, [ty], mkUnknowns (List.replicate (n+1) ty), m), false + Expr.Op (TOp.Array, [ty], mkUnknowns (List.replicate (n+1) ty), m), false | _ -> raise CannotRefute @@ -306,26 +310,26 @@ let RefuteDiscrimSet g m path discrims = let rec CombineRefutations g r1 r2 = match r1, r2 with - | Expr.Val(vref, _, _), other | other, Expr.Val(vref, _, _) when vref.LogicalName = "_" -> other - | Expr.Val(vref, _, _), other | other, Expr.Val(vref, _, _) when vref.LogicalName = notNullText -> other - | Expr.Val(vref, _, _), other | other, Expr.Val(vref, _, _) when vref.LogicalName = otherSubtypeText -> other + | Expr.Val (vref, _, _), other | other, Expr.Val (vref, _, _) when vref.LogicalName = "_" -> other + | Expr.Val (vref, _, _), other | other, Expr.Val (vref, _, _) when vref.LogicalName = notNullText -> other + | Expr.Val (vref, _, _), other | other, Expr.Val (vref, _, _) when vref.LogicalName = otherSubtypeText -> other - | Expr.Op((TOp.ExnConstr(ecref1) as op1), tinst1, flds1, m1), Expr.Op(TOp.ExnConstr(ecref2), _, flds2, _) when tyconRefEq g ecref1 ecref2 -> - Expr.Op(op1, tinst1, List.map2 (CombineRefutations g) flds1 flds2, m1) + | Expr.Op ((TOp.ExnConstr ecref1 as op1), tinst1, flds1, m1), Expr.Op (TOp.ExnConstr ecref2, _, flds2, _) when tyconRefEq g ecref1 ecref2 -> + Expr.Op (op1, tinst1, List.map2 (CombineRefutations g) flds1 flds2, m1) - | Expr.Op((TOp.UnionCase(ucref1) as op1), tinst1, flds1, m1), Expr.Op(TOp.UnionCase(ucref2), _, flds2, _) -> + | Expr.Op ((TOp.UnionCase ucref1 as op1), tinst1, flds1, m1), Expr.Op (TOp.UnionCase ucref2, _, flds2, _) -> if g.unionCaseRefEq ucref1 ucref2 then - Expr.Op(op1, tinst1, List.map2 (CombineRefutations g) flds1 flds2, m1) + Expr.Op (op1, tinst1, List.map2 (CombineRefutations g) flds1 flds2, m1) (* Choose the greater of the two ucrefs based on name ordering *) elif ucref1.CaseName < ucref2.CaseName then r2 else r1 - | Expr.Op(op1, tinst1, flds1, m1), Expr.Op(_, _, flds2, _) -> - Expr.Op(op1, tinst1, List.map2 (CombineRefutations g) flds1 flds2, m1) + | Expr.Op (op1, tinst1, flds1, m1), Expr.Op (_, _, flds2, _) -> + Expr.Op (op1, tinst1, List.map2 (CombineRefutations g) flds1 flds2, m1) - | Expr.Const(c1, m1, ty1), Expr.Const(c2, _, _) -> + | Expr.Const (c1, m1, ty1), Expr.Const (c2, _, _) -> let c12 = // Make sure longer strings are greater, not the case in the default ordinal comparison @@ -338,16 +342,17 @@ let rec CombineRefutations g r1 r2 = else s1 match c1, c2 with - | Const.String(s1), Const.String(s2) -> Const.String(MaxStrings s1 s2) - | Const.Decimal(s1), Const.Decimal(s2) -> Const.Decimal(max s1 s2) + | Const.String s1, Const.String s2 -> Const.String(MaxStrings s1 s2) + | Const.Decimal s1, Const.Decimal s2 -> Const.Decimal(max s1 s2) | _ -> max c1 c2 - Expr.Const(c12, m1, ty1) + Expr.Const (c12, m1, ty1) | _ -> r1 let ShowCounterExample g denv m refuted = try + let exprL expr = exprL g expr let refutations = refuted |> List.collect (function RefutedWhenClause -> [] | (RefutedInvestigation(path, discrim)) -> [RefuteDiscrimSet g m path discrim]) let counterExample, enumCoversKnown = match refutations with @@ -392,12 +397,12 @@ let rec isMemOfActives p1 actives = let rec lookupActive x l = match l with | [] -> raise (KeyNotFoundException()) - | (Active(h, r1, r2)::t) -> if pathEq x h then (r1, r2) else lookupActive x t + | (Active(h, r1, r2) :: t) -> if pathEq x h then (r1, r2) else lookupActive x t let rec removeActive x l = match l with | [] -> [] - | ((Active(h, _, _) as p) ::t) -> if pathEq x h then t else p:: removeActive x t + | ((Active(h, _, _) as p) :: t) -> if pathEq x h then t else p :: removeActive x t //--------------------------------------------------------------------------- // Utilities @@ -419,7 +424,11 @@ let getDiscrimOfPattern (g: TcGlobals) tpinst t = | TPat_array (args, ty, _m) -> Some(DecisionTreeTest.ArrayLength (args.Length, ty)) | TPat_query ((activePatExpr, resTys, apatVrefOpt, idx, apinfo), _, _m) -> - Some(DecisionTreeTest.ActivePatternCase (activePatExpr, instTypes tpinst resTys, apatVrefOpt, idx, apinfo)) + Some (DecisionTreeTest.ActivePatternCase (activePatExpr, instTypes tpinst resTys, apatVrefOpt, idx, apinfo)) + + | TPat_error range -> + Some (DecisionTreeTest.Error range) + | _ -> None let constOfDiscrim discrim = @@ -457,12 +466,12 @@ let isDiscrimSubsumedBy g amap m d1 d2 = let rec chooseSimultaneousEdgeSet prevOpt f l = match l with | [] -> [], [] - | h::t -> + | h :: t -> match f prevOpt h with - | Some x, _ -> + | Some x -> let l, r = chooseSimultaneousEdgeSet (Some x) f t x :: l, r - | None, _cont -> + | None -> let l, r = chooseSimultaneousEdgeSet prevOpt f t l, h :: r @@ -490,16 +499,20 @@ let discrimsHaveSameSimultaneousClass g d1 d2 = | _ -> false +let canInvestigate (pat: Pattern) = + match pat with + | TPat_null _ | TPat_isinst _ | TPat_exnconstr _ | TPat_unioncase _ + | TPat_array _ | TPat_const _ | TPat_query _ | TPat_range _ | TPat_error _ -> true + | _ -> false /// Decide the next pattern to investigate let ChooseInvestigationPointLeftToRight frontiers = match frontiers with - | Frontier (_i, actives, _) ::_t -> + | Frontier (_i, actives, _) :: _t -> let rec choose l = match l with | [] -> failwith "ChooseInvestigationPointLeftToRight: no non-immediate patterns in first rule" - | (Active(_, _, (TPat_null _ | TPat_isinst _ | TPat_exnconstr _ | TPat_unioncase _ | TPat_array _ | TPat_const _ | TPat_query _ | TPat_range _)) as active) - :: _ -> active + | Active (_, _, pat) as active :: _ when canInvestigate pat -> active | _ :: t -> choose t choose actives | [] -> failwith "ChooseInvestigationPointLeftToRight: no frontiers!" @@ -507,7 +520,7 @@ let ChooseInvestigationPointLeftToRight frontiers = #if OPTIMIZE_LIST_MATCHING -// This is an initial attempt to remove extra typetests/castclass for simple list pattern matching "match x with h::t -> ... | [] -> ..." +// 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 @@ -528,9 +541,7 @@ let (|ConstNeedsDefaultCase|_|) c = | Const.Decimal _ | Const.String _ | Const.Single _ - | Const.Double _ - | Const.SByte _ - | Const.Byte _ + | Const.Double _ | Const.Int16 _ | Const.UInt16 _ | Const.Int32 _ @@ -568,11 +579,11 @@ let rec BuildSwitch inpExprOpt g expr edges dflt m = // 'isinst' tests where we have stored the result of the 'isinst' in a variable // In this case the 'expr' already holds the result of the 'isinst' test. - | (TCase(DecisionTreeTest.IsInst _, success)):: edges, dflt when Option.isSome inpExprOpt -> + | (TCase(DecisionTreeTest.IsInst _, success)) :: edges, dflt when Option.isSome inpExprOpt -> TDSwitch(expr, [TCase(DecisionTreeTest.IsNull, BuildSwitch None g expr edges dflt m)], Some success, m) // isnull and isinst tests - | (TCase((DecisionTreeTest.IsNull | DecisionTreeTest.IsInst _), _) as edge):: edges, dflt -> + | (TCase((DecisionTreeTest.IsNull | DecisionTreeTest.IsInst _), _) as edge) :: edges, dflt -> TDSwitch(expr, [edge], Some (BuildSwitch inpExprOpt g expr edges dflt m), m) #if OPTIMIZE_LIST_MATCHING @@ -588,7 +599,7 @@ let rec BuildSwitch inpExprOpt g expr edges dflt m = // All these should also always have default cases | (TCase(DecisionTreeTest.Const ConstNeedsDefaultCase, _) :: _), None -> - error(InternalError("inexhaustive match - need a default cases!", m)) + error(InternalError("inexhaustive match - need a default case!", m)) // Split string, float, uint64, int64, unativeint, nativeint matches into serial equality tests | TCase((DecisionTreeTest.ArrayLength _ | DecisionTreeTest.Const (Const.Single _ | Const.Double _ | Const.String _ | Const.Decimal _ | Const.Int64 _ | Const.UInt64 _ | Const.IntPtr _ | Const.UIntPtr _)), _) :: _, Some dflt -> @@ -598,14 +609,14 @@ let rec BuildSwitch inpExprOpt g expr edges dflt m = let testexpr = match discrim with | DecisionTreeTest.ArrayLength(n, _) -> - let _v, vExpr, bind = mkCompGenLocalAndInvisbleBind g "testExpr" m testexpr + let _v, vExpr, bind = mkCompGenLocalAndInvisibleBind g "testExpr" m testexpr mkLetBind m bind (mkLazyAnd g m (mkNonNullTest g m vExpr) (mkILAsmCeq g m (mkLdlen g m vExpr) (mkInt g m n))) | DecisionTreeTest.Const (Const.String _ as c) -> - mkCallEqualsOperator g m g.string_ty testexpr (Expr.Const(c, m, g.string_ty)) + mkCallEqualsOperator g m g.string_ty testexpr (Expr.Const (c, m, g.string_ty)) | DecisionTreeTest.Const (Const.Decimal _ as c) -> - mkCallEqualsOperator g m g.decimal_ty testexpr (Expr.Const(c, m, g.decimal_ty)) + mkCallEqualsOperator g m g.decimal_ty testexpr (Expr.Const (c, m, g.decimal_ty)) | DecisionTreeTest.Const ((Const.Double _ | Const.Single _ | Const.Int64 _ | Const.UInt64 _ | Const.IntPtr _ | Const.UIntPtr _) as c) -> - mkILAsmCeq g m testexpr (Expr.Const(c, m, tyOfExpr g testexpr)) + mkILAsmCeq g m testexpr (Expr.Const (c, m, tyOfExpr g testexpr)) | _ -> error(InternalError("strange switch", m)) mkBoolSwitch m testexpr tree sofar) edges @@ -628,24 +639,24 @@ let rec BuildSwitch inpExprOpt g expr edges dflt m = match curr, edges with | None, [] -> [] | Some last, [] -> [List.rev last] - | None, h::t -> compactify (Some [h]) t - | Some (prev::moreprev), h::t -> + | None, h :: t -> compactify (Some [h]) t + | Some (prev :: moreprev), h :: t -> match constOfCase prev, constOfCase h with - | Const.SByte iprev, Const.SByte inext when int32(iprev) + 1 = int32 inext -> - compactify (Some (h::prev::moreprev)) t - | Const.Int16 iprev, Const.Int16 inext when int32(iprev) + 1 = int32 inext -> - compactify (Some (h::prev::moreprev)) t + | Const.SByte iprev, Const.SByte inext when int32 iprev + 1 = int32 inext -> + compactify (Some (h :: prev :: moreprev)) t + | Const.Int16 iprev, Const.Int16 inext when int32 iprev + 1 = int32 inext -> + compactify (Some (h :: prev :: moreprev)) t | Const.Int32 iprev, Const.Int32 inext when iprev+1 = inext -> - compactify (Some (h::prev::moreprev)) t - | Const.Byte iprev, Const.Byte inext when int32(iprev) + 1 = int32 inext -> - compactify (Some (h::prev::moreprev)) t - | Const.UInt16 iprev, Const.UInt16 inext when int32(iprev)+1 = int32 inext -> - compactify (Some (h::prev::moreprev)) t - | Const.UInt32 iprev, Const.UInt32 inext when int32(iprev)+1 = int32 inext -> - compactify (Some (h::prev::moreprev)) t + compactify (Some (h :: prev :: moreprev)) t + | Const.Byte iprev, Const.Byte inext when int32 iprev + 1 = int32 inext -> + compactify (Some (h :: prev :: moreprev)) t + | Const.UInt16 iprev, Const.UInt16 inext when int32 iprev+1 = int32 inext -> + compactify (Some (h :: prev :: moreprev)) t + | Const.UInt32 iprev, Const.UInt32 inext when int32 iprev+1 = int32 inext -> + compactify (Some (h :: prev :: moreprev)) t | Const.Char cprev, Const.Char cnext when (int32 cprev + 1 = int32 cnext) -> - compactify (Some (h::prev::moreprev)) t - | _ -> (List.rev (prev::moreprev)) :: compactify None edges + compactify (Some (h :: prev :: moreprev)) t + | _ -> (List.rev (prev :: moreprev)) :: compactify None edges | _ -> failwith "internal error: compactify" let edgeGroups = compactify None edges' @@ -653,11 +664,11 @@ let rec BuildSwitch inpExprOpt g expr edges dflt m = // For a total pattern match, run the active pattern, bind the result and // recursively build a switch in the choice type - | (TCase(DecisionTreeTest.ActivePatternCase _, _)::_), _ -> + | (TCase(DecisionTreeTest.ActivePatternCase _, _) :: _), _ -> error(InternalError("DecisionTreeTest.ActivePatternCase should have been eliminated", m)) // For a complete match, optimize one test to be the default - | (TCase(_, tree)::rest), None -> TDSwitch (expr, rest, Some tree, m) + | (TCase(_, tree) :: rest), None -> TDSwitch (expr, rest, Some tree, m) // Otherwise let codegen make the choices | _ -> TDSwitch (expr, edges, dflt, m) @@ -700,6 +711,7 @@ let rec isPatternPartial p = | TPat_range _ -> false | TPat_null _ -> false | TPat_isinst _ -> false + | TPat_error _ -> false let rec erasePartialPatterns inpp = match inpp with @@ -718,8 +730,11 @@ let rec erasePartialPatterns inpp = | TPat_wild _ | TPat_range _ | TPat_null _ - | TPat_isinst _ -> inpp -and erasePartials inps = List.map erasePartialPatterns inps + | TPat_isinst _ + | TPat_error _ -> inpp + +and erasePartials inps = + List.map erasePartialPatterns inps //--------------------------------------------------------------------------- @@ -736,123 +751,116 @@ let CompilePatternBasic warnOnIncomplete actionOnFailure (origInputVal, origInputValTypars, _origInputExprOpt: Expr option) - (clausesL: TypedMatchClause list) + (typedClauses: TypedMatchClause list) inputTy resultTy = - // Add the targets to a match builder - // Note the input expression has already been evaluated and saved into a variable. - // Hence no need for a new sequence point. - let mbuilder = new MatchBuilder(NoSequencePointAtInvisibleBinding, exprm) - clausesL |> List.iteri (fun _i c -> mbuilder.AddTarget c.Target |> ignore) - - // Add the incomplete or rethrow match clause on demand, printing a - // warning if necessary (only if it is ever exercised) - let incompleteMatchClauseOnce = ref None - let getIncompleteMatchClause (refuted) = - // This is lazy because emit a - // warning when the lazy thunk gets evaluated - match !incompleteMatchClauseOnce with + // Add the targets to a match builder. + // Note the input expression has already been evaluated and saved into a variable, + // hence no need for a new sequence point. + let matchBuilder = MatchBuilder (NoDebugPointAtInvisibleBinding, exprm) + typedClauses |> List.iter (fun c -> matchBuilder.AddTarget c.Target |> ignore) + + // Add the incomplete or rethrow match clause on demand, + // printing a warning if necessary (only if it is ever exercised). + let mutable incompleteMatchClauseOnce = None + let getIncompleteMatchClause refuted = + // This is lazy because emit a warning when the lazy thunk gets evaluated. + match incompleteMatchClauseOnce with | None -> - (* Emit the incomplete match warning *) - if warnOnIncomplete then - match actionOnFailure with - | ThrowIncompleteMatchException | IgnoreWithWarning -> - let ignoreWithWarning = (actionOnFailure = IgnoreWithWarning) - match ShowCounterExample g denv matchm refuted with - | Some(text, failingWhenClause, true) -> - warning (EnumMatchIncomplete(ignoreWithWarning, Some(text, failingWhenClause), matchm)) - | Some(text, failingWhenClause, false) -> - warning (MatchIncomplete(ignoreWithWarning, Some(text, failingWhenClause), matchm)) - | None -> - warning (MatchIncomplete(ignoreWithWarning, None, matchm)) - | _ -> - () - - let throwExpr = - match actionOnFailure with - | FailFilter -> - // Return 0 from the .NET exception filter - mkInt g matchm 0 - - | Rethrow -> - // Rethrow unmatched try-catch exn. No sequence point at the target since its not - // real code. - mkReraise matchm resultTy - - | Throw -> - // We throw instead of rethrow on unmatched try-catch in a computation expression. But why? - // Because this isn't a real .NET exception filter/handler but just a function we're passing - // to a computation expression builder to simulate one. - mkThrow matchm resultTy (exprForVal matchm origInputVal) - - | ThrowIncompleteMatchException -> - mkThrow matchm resultTy - (mkExnExpr(mk_MFCore_tcref g.fslibCcu "MatchFailureException", - [ mkString g matchm matchm.FileName - mkInt g matchm matchm.StartLine - mkInt g matchm matchm.StartColumn], matchm)) - - | IgnoreWithWarning -> - mkUnit g matchm - - // We don't emit a sequence point at any of the above cases because they don't correspond to - // user code. - // - // Note we don't emit sequence points at either the succeeding or failing - // targets of filters since if the exception is filtered successfully then we - // will run the handler and hit the sequence point there. - // That sequence point will have the pattern variables bound, which is exactly what we want. - let tg = TTarget(List.empty, throwExpr, SuppressSequencePointAtTarget ) - mbuilder.AddTarget tg |> ignore - let clause = TClause(TPat_wild matchm, None, tg, matchm) - incompleteMatchClauseOnce := Some(clause) - clause + // Emit the incomplete match warning. + if warnOnIncomplete then + match actionOnFailure with + | ThrowIncompleteMatchException | IgnoreWithWarning -> + let ignoreWithWarning = (actionOnFailure = IgnoreWithWarning) + match ShowCounterExample g denv matchm refuted with + | Some(text, failingWhenClause, true) -> + warning (EnumMatchIncomplete(ignoreWithWarning, Some(text, failingWhenClause), matchm)) + | Some(text, failingWhenClause, false) -> + warning (MatchIncomplete(ignoreWithWarning, Some(text, failingWhenClause), matchm)) + | None -> + warning (MatchIncomplete(ignoreWithWarning, None, matchm)) + | _ -> + () + + let throwExpr = + match actionOnFailure with + | FailFilter -> + // Return 0 from the .NET exception filter. + mkInt g matchm 0 + + | Rethrow -> + // Rethrow unmatched try-catch exn. No sequence point at the target since its not real code. + mkReraise matchm resultTy + + | Throw -> + // We throw instead of rethrow on unmatched try-catch in a computation expression. But why? + // Because this isn't a real .NET exception filter/handler but just a function we're passing + // to a computation expression builder to simulate one. + mkThrow matchm resultTy (exprForVal matchm origInputVal) + + | ThrowIncompleteMatchException -> + mkThrow matchm resultTy + (mkExnExpr(mk_MFCore_tcref g.fslibCcu "MatchFailureException", + [ mkString g matchm matchm.FileName + mkInt g matchm matchm.StartLine + mkInt g matchm matchm.StartColumn], matchm)) + + | IgnoreWithWarning -> + mkUnit g matchm + + // We don't emit a sequence point at any of the above cases because they don't correspond to user code. + // + // Note we don't emit sequence points at either the succeeding or failing targets of filters since if + // the exception is filtered successfully then we will run the handler and hit the sequence point there. + // That sequence point will have the pattern variables bound, which is exactly what we want. + let tg = TTarget(List.empty, throwExpr, DebugPointForTarget.No) + let _ = matchBuilder.AddTarget tg + let clause = TClause(TPat_wild matchm, None, tg, matchm) + incompleteMatchClauseOnce <- Some clause + clause | Some c -> c - // Helpers to get the variables bound at a target. We conceptually add a dummy clause that will always succeed with a "throw" - let clausesA = Array.ofList clausesL - let nclauses = clausesA.Length + // Helpers to get the variables bound at a target. + // We conceptually add a dummy clause that will always succeed with a "throw". + let clausesA = Array.ofList typedClauses + let nClauses = clausesA.Length let GetClause i refuted = - if i < nclauses then + if i < nClauses then clausesA.[i] - elif i = nclauses then getIncompleteMatchClause(refuted) + elif i = nClauses then getIncompleteMatchClause refuted else failwith "GetClause" let GetValsBoundByClause i refuted = (GetClause i refuted).BoundVals let GetWhenGuardOfClause i refuted = (GetClause i refuted).GuardExpr - // Different uses of parameterized active patterns have different identities as far as paths - // are concerned. Here we generate unique numbers that are completely different to any stamp - // by usig negative numbers. + // Different uses of parameterized active patterns have different identities as far as paths are concerned. + // Here we generate unique numbers that are completely different to any stamp by using negative numbers. let genUniquePathId() = - (newUnique()) - // Build versions of these functions which apply a dummy instantiation to the overall type arguments + // Build versions of these functions which apply a dummy instantiation to the overall type arguments. let GetSubExprOfInput, getDiscrimOfPattern = let tyargs = List.map (fun _ -> g.unit_ty) origInputValTypars let unit_tpinst = mkTyparInst origInputValTypars tyargs GetSubExprOfInput g (origInputValTypars, tyargs, unit_tpinst), getDiscrimOfPattern g unit_tpinst - // The main recursive loop of the pattern match compiler + // The main recursive loop of the pattern match compiler. let rec InvestigateFrontiers refuted frontiers = match frontiers with | [] -> failwith "CompilePattern: compile - empty clauses: at least the final clause should always succeed" - | (Frontier (i, active, valMap)) :: rest -> + | Frontier (i, active, valMap) :: rest -> - // Check to see if we've got a succeeding clause. There may still be a 'when' condition for the clause + // Check to see if we've got a succeeding clause. There may still be a 'when' condition for the clause. match active with | [] -> CompileSuccessPointAndGuard i refuted valMap rest | _ -> - (* Otherwise choose a point (i.e. a path) to investigate. *) + // Otherwise choose a point (i.e. a path) to investigate. let (Active(path, subexpr, pat)) = ChooseInvestigationPointLeftToRight frontiers - match pat with - // All these constructs should have been eliminated in BindProjectionPattern - | TPat_as _ | TPat_tuple _ | TPat_wild _ | TPat_disjs _ | TPat_conjs _ | TPat_recd _ -> failwith "Unexpected pattern" - - // Leaving the ones where we have real work to do - | _ -> - + if not (canInvestigate pat) then + // All these constructs should have been eliminated in BindProjectionPattern + failwith "Unexpected pattern" + else let simulSetOfEdgeDiscrims, fallthroughPathFrontiers = ChooseSimultaneousEdges frontiers path let inpExprOpt, bindOpt = ChoosePreBinder simulSetOfEdgeDiscrims subexpr @@ -864,8 +872,7 @@ let CompilePatternBasic // Work out what the default/fall-through tree looks like, is any // Check if match is complete, if so optimize the default case away. - - let defaultTreeOpt : DecisionTree option = CompileFallThroughTree fallthroughPathFrontiers path refuted simulSetOfCases + let defaultTreeOpt = CompileFallThroughTree fallthroughPathFrontiers path refuted simulSetOfCases // OK, build the whole tree and whack on the binding if any let finalDecisionTree = @@ -878,12 +885,11 @@ let CompilePatternBasic finalDecisionTree and CompileSuccessPointAndGuard i refuted valMap rest = - let vs2 = GetValsBoundByClause i refuted let es2 = vs2 |> List.map (fun v -> match valMap.TryFind v with - | None -> error(Error(FSComp.SR.patcMissingVariable(v.DisplayName), v.Range)) + | None -> mkUnit g v.Range | Some res -> res) let rhs' = TDSuccess(es2, i) match GetWhenGuardOfClause i refuted with @@ -902,29 +908,29 @@ let CompilePatternBasic // However, we are not allowed to copy expressions until type checking is complete, because this // would lose recursive fixup points within the expressions (see FSharp 1.0 bug 4821). - mkBoolSwitch m whenExpr rhs' (InvestigateFrontiers (RefutedWhenClause::refuted) rest) + mkBoolSwitch m whenExpr rhs' (InvestigateFrontiers (RefutedWhenClause :: refuted) rest) | None -> rhs' - /// Select the set of discriminators which we can handle in one test, or as a series of - /// iterated tests, e.g. in the case of TPat_isinst. Ensure we only take at most one class of TPat_query(_) at a time. + /// Select the set of discriminators which we can handle in one test, or as a series of iterated tests, + /// e.g. in the case of TPat_isinst. Ensure we only take at most one class of `TPat_query` at a time. /// Record the rule numbers so we know which rule the TPat_query cam from, so that when we project through /// the frontier we only project the right rule. and ChooseSimultaneousEdges frontiers path = frontiers |> chooseSimultaneousEdgeSet None (fun prevOpt (Frontier (i', active', _)) -> - if isMemOfActives path active' then - let p = lookupActive path active' |> snd - match getDiscrimOfPattern p with - | Some discrim -> - if (match prevOpt with None -> true | Some (EdgeDiscrim(_, discrimPrev, _)) -> discrimsHaveSameSimultaneousClass g discrim discrimPrev) then - Some (EdgeDiscrim(i', discrim, p.Range)), true - else - None, false - - | None -> - None, true - else - None, true) + if isMemOfActives path active' then + let _, p = lookupActive path active' + match getDiscrimOfPattern p with + | Some discrim -> + if (match prevOpt with None -> true | Some (EdgeDiscrim(_, discrimPrev, _)) -> discrimsHaveSameSimultaneousClass g discrim discrimPrev) then + Some (EdgeDiscrim(i', discrim, p.Range)) + else + None + + | None -> + None + else + None) and IsCopyableInputExpr origInputExpr = match origInputExpr with @@ -956,14 +962,14 @@ let CompilePatternBasic Some vExpr, Some(mkInvisibleBind v appExpr) // Any match on a struct union must take the address of its input. - // We can shortcut the addrof when the original input is a deref of a byref value. + // We can shortcut the addrOf when the original input is a deref of a byref value. | EdgeDiscrim(_i', (DecisionTreeTest.UnionCase (ucref, _)), _) :: _rest when isNil origInputValTypars && ucref.Tycon.IsStructRecordOrUnionTycon -> let argExpr = GetSubExprOfInput subexpr let argExpr = match argExpr, _origInputExprOpt with - | Expr.Val(v1, _, _), Some origInputExpr when valEq origInputVal v1.Deref && IsCopyableInputExpr origInputExpr -> origInputExpr + | Expr.Val (v1, _, _), Some origInputExpr when valEq origInputVal v1.Deref && IsCopyableInputExpr origInputExpr -> origInputExpr | _ -> argExpr let vOpt, addrExp, _readonly, _writeonly = mkExprAddrOfExprAux g true false NeverMutates argExpr None matchm match vOpt with @@ -1003,7 +1009,7 @@ let CompilePatternBasic let argExpr = GetSubExprOfInput subexpr let appExpr = mkApps g ((activePatExpr, tyOfExpr g activePatExpr), [], [argExpr], m) - Some(vExpr), Some(mkInvisibleBind v appExpr) + Some vExpr, Some(mkInvisibleBind v appExpr) | _ -> None, None @@ -1035,7 +1041,7 @@ let CompilePatternBasic (isNil origInputValTypars && not origInputVal.IsMemberOrModuleBinding && not ucref.Tycon.IsStructRecordOrUnionTycon && - ucref.UnionCase.RecdFields.Length >= 1 && + ucref.UnionCase.RecdFieldsArray.Length >= 1 && ucref.Tycon.UnionCasesArray.Length > 1) -> let v, vExpr = mkCompGenLocal m "unionCase" (mkProvenUnionCaseTy ucref tinst) @@ -1062,7 +1068,7 @@ let CompilePatternBasic // Project a successful edge through the frontiers. let investigation = Investigation(i', discrim, path) - let frontiers = frontiers |> List.collect (GenerateNewFrontiersAfterSucccessfulInvestigation inpExprOpt resPostBindOpt investigation) + let frontiers = frontiers |> List.collect (GenerateNewFrontiersAfterSuccessfulInvestigation inpExprOpt resPostBindOpt investigation) let tree = InvestigateFrontiers refuted frontiers // Bind the resVar for the union case, if we have one let tree = @@ -1081,11 +1087,13 @@ let CompilePatternBasic isMemOfActives path active' && let p = lookupActive path active' |> snd match getDiscrimOfPattern p with - | Some(discrim) -> List.exists (isDiscrimSubsumedBy g amap exprm discrim) simulSetOfDiscrims + | Some discrim -> List.exists (isDiscrimSubsumedBy g amap exprm discrim) simulSetOfDiscrims | None -> false match simulSetOfDiscrims with | DecisionTreeTest.Const (Const.Bool _b) :: _ when simulSetOfCases.Length = 2 -> None + | DecisionTreeTest.Const (Const.Byte _) :: _ when simulSetOfCases.Length = 256 -> None + | DecisionTreeTest.Const (Const.SByte _) :: _ when simulSetOfCases.Length = 256 -> None | DecisionTreeTest.Const (Const.Unit) :: _ -> None | DecisionTreeTest.UnionCase (ucref, _) :: _ when simulSetOfCases.Length = ucref.TyconRef.UnionCasesArray.Length -> None | DecisionTreeTest.ActivePatternCase _ :: _ -> error(InternalError("DecisionTreeTest.ActivePatternCase should have been eliminated", matchm)) @@ -1103,7 +1111,7 @@ let CompilePatternBasic // Build a new frontier that represents the result of a successful investigation // at rule point (i', discrim, path) - and GenerateNewFrontiersAfterSucccessfulInvestigation inpExprOpt resPostBindOpt (Investigation(i', discrim, path)) (Frontier (i, active, valMap) as frontier) = + and GenerateNewFrontiersAfterSuccessfulInvestigation inpExprOpt resPostBindOpt (Investigation(i', discrim, path)) (Frontier (i, active, valMap) as frontier) = if (isMemOfActives path active) then let (SubExpr(accessf, ve)), pat = lookupActive path active @@ -1237,8 +1245,17 @@ let CompilePatternBasic | _ -> [frontier] - | _ -> failwith "pattern compilation: GenerateNewFrontiersAfterSucccessfulInvestigation" - else [frontier] + | TPat_error range -> + match discrim with + | DecisionTreeTest.Error testRange when range = testRange -> + [Frontier (i, active', valMap)] + | _ -> + [frontier] + + | _ -> failwith "pattern compilation: GenerateNewFrontiersAfterSuccessfulInvestigation" + + else + [frontier] and BindProjectionPattern (Active(path, subExpr, p) as inp) ((accActive, accValMap) as s) = let (SubExpr(accessf, ve)) = subExpr @@ -1270,10 +1287,10 @@ let CompilePatternBasic BindProjectionPatterns newActives s | TPat_range (c1, c2, m) -> - let res = ref [] + let mutable res = [] for i = int c1 to int c2 do - res := BindProjectionPattern (Active(path, subExpr, TPat_const(Const.Char(char i), m))) s @ !res - !res + res <- BindProjectionPattern (Active(path, subExpr, TPat_const(Const.Char(char i), m))) s @ res + res // Assign an identifier to each TPat_query based on our knowledge of the 'identity' of the active pattern, if any | TPat_query ((_, _, apatVrefOpt, _, _), _, _) -> let uniqId = @@ -1281,36 +1298,36 @@ let CompilePatternBasic | Some (vref, _) when not (doesActivePatternHaveFreeTypars g vref) -> vref.Stamp | _ -> genUniquePathId() let inp = Active(PathQuery(path, uniqId), subExpr, p) - [(inp::accActive, accValMap)] + [(inp :: accActive, accValMap)] | _ -> - [(inp::accActive, accValMap)] + [(inp :: accActive, accValMap)] and BindProjectionPatterns ps s = List.foldBack (fun p sofar -> List.collect (BindProjectionPattern p) sofar) ps [s] - (* The setup routine of the match compiler *) + // The setup routine of the match compiler. let frontiers = - ((clausesL + ((typedClauses |> List.mapi (fun i c -> - let initialSubExpr = SubExpr((fun _tpinst x -> x), (exprForVal origInputVal.Range origInputVal, origInputVal)) - let investigations = BindProjectionPattern (Active(PathEmpty(inputTy), initialSubExpr, c.Pattern)) ([], ValMap<_>.Empty) + let initialSubExpr = SubExpr((fun _ x -> x), (exprForVal origInputVal.Range origInputVal, origInputVal)) + let investigations = BindProjectionPattern (Active(PathEmpty inputTy, initialSubExpr, c.Pattern)) ([], ValMap<_>.Empty) mkFrontiers investigations i) |> List.concat) @ - mkFrontiers [([], ValMap<_>.Empty)] nclauses) + mkFrontiers [([], ValMap<_>.Empty)] nClauses) let dtree = InvestigateFrontiers [] frontiers - let targets = mbuilder.CloseTargets() + let targets = matchBuilder.CloseTargets() // Report unused targets if warnOnUnused then let used = HashSet<_>(accTargetsOfDecisionTree dtree [], HashIdentity.Structural) - clausesL |> List.iteri (fun i c -> + typedClauses |> List.iteri (fun i c -> if not (used.Contains i) then warning (RuleNeverMatched c.Range)) dtree, targets @@ -1319,13 +1336,13 @@ let isPartialOrWhenClause (c: TypedMatchClause) = isPatternPartial c.Pattern || let rec CompilePattern g denv amap exprm matchm warnOnUnused actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) (clausesL: TypedMatchClause list) inputTy resultTy = - match clausesL with - | _ when List.exists isPartialOrWhenClause clausesL -> + match clausesL with + | _ when List.exists isPartialOrWhenClause clausesL -> // Partial clauses cause major code explosion if treated naively // Hence treat any pattern matches with any partial clauses clause-by-clause // First make sure we generate at least some of the obvious incomplete match warnings. - let warnOnUnused = false in (* we can't turn this on since we're pretending all partial's fail in order to control the complexity of this. *) + let warnOnUnused = false // we can't turn this on since we're pretending all partials fail in order to control the complexity of this. let warnOnIncomplete = true let clausesPretendAllPartialFail = List.collect (fun (TClause(p, whenOpt, tg, m)) -> [TClause(erasePartialPatterns p, whenOpt, tg, m)]) clausesL let _ = CompilePatternBasic g denv amap exprm matchm warnOnUnused warnOnIncomplete actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) clausesPretendAllPartialFail inputTy resultTy @@ -1333,25 +1350,24 @@ let rec CompilePattern g denv amap exprm matchm warnOnUnused actionOnFailure (o let rec atMostOnePartialAtATime clauses = match List.takeUntil isPartialOrWhenClause clauses with - | l, [] -> + | l, [] -> CompilePatternBasic g denv amap exprm matchm warnOnUnused warnOnIncomplete actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) l inputTy resultTy | l, (h :: t) -> - // Add the partial clause + // Add the partial clause. doGroupWithAtMostOnePartial (l @ [h]) t and doGroupWithAtMostOnePartial group rest = + // Compile the remaining clauses. + let decisionTree, targets = atMostOnePartialAtATime rest - // Compile the remaining clauses - let dtree, targets = atMostOnePartialAtATime rest - - // Make the expression that represents the remaining cases of the pattern match - let expr = mkAndSimplifyMatch NoSequencePointAtInvisibleBinding exprm matchm resultTy dtree targets + // Make the expression that represents the remaining cases of the pattern match. + let expr = mkAndSimplifyMatch NoDebugPointAtInvisibleBinding exprm matchm resultTy decisionTree targets // If the remainder of the match boiled away to nothing interesting. // We measure this simply by seeing if the range of the resulting expression is identical to matchm. let spTarget = - if expr.Range = matchm then SuppressSequencePointAtTarget - else SequencePointAtTarget + if Range.equals expr.Range matchm then DebugPointForTarget.No + else DebugPointForTarget.Yes // Make the clause that represents the remaining cases of the pattern match let clauseForRestOfMatch = TClause(TPat_wild matchm, None, TTarget(List.empty, expr, spTarget), matchm) @@ -1361,5 +1377,5 @@ let rec CompilePattern g denv amap exprm matchm warnOnUnused actionOnFailure (o atMostOnePartialAtATime clausesL - | _ -> - CompilePatternBasic g denv amap exprm matchm warnOnUnused true actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) clausesL inputTy resultTy + | _ -> + CompilePatternBasic g denv amap exprm matchm warnOnUnused true actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) clausesL inputTy resultTy diff --git a/src/fcs-fable/src/fsharp/PatternMatchCompilation.fsi b/src/fcs-fable/src/fsharp/PatternMatchCompilation.fsi old mode 100755 new mode 100644 index 8394611a16..67ca39e59b --- a/src/fcs-fable/src/fsharp/PatternMatchCompilation.fsi +++ b/src/fcs-fable/src/fsharp/PatternMatchCompilation.fsi @@ -4,12 +4,11 @@ module internal FSharp.Compiler.PatternMatchCompilation open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals open FSharp.Compiler.Range - /// What should the decision tree contain for any incomplete match? type ActionOnFailure = | ThrowIncompleteMatchException @@ -18,24 +17,26 @@ type ActionOnFailure = | Rethrow | FailFilter -[] /// Represents the typechecked, elaborated form of a pattern, prior to pattern-match compilation. +[] type Pattern = | TPat_const of Const * range | TPat_wild of range - | TPat_as of Pattern * PatternValBinding * range - | TPat_disjs of Pattern list * range - | TPat_conjs of Pattern list * range + | TPat_as of Pattern * PatternValBinding * range + | TPat_disjs of Pattern list * range + | TPat_conjs of Pattern list * range | TPat_query of (Expr * TType list * (ValRef * TypeInst) option * int * PrettyNaming.ActivePatternInfo) * Pattern * range | TPat_unioncase of UnionCaseRef * TypeInst * Pattern list * range | TPat_exnconstr of TyconRef * Pattern list * range - | TPat_tuple of TupInfo * Pattern list * TType list * range - | TPat_array of Pattern list * TType * range + | TPat_tuple of TupInfo * Pattern list * TType list * range + | TPat_array of Pattern list * TType * range | TPat_recd of TyconRef * TypeInst * Pattern list * range | TPat_range of char * char * range | TPat_null of range | TPat_isinst of TType * TType * PatternValBinding option * range - member Range : range + | TPat_error of range + + member Range: range and PatternValBinding = | PBind of Val * TypeScheme @@ -43,10 +44,10 @@ and PatternValBinding = and TypedMatchClause = | TClause of Pattern * Expr option * DecisionTreeTarget * range -val ilFieldToTastConst : ILFieldInit -> Tast.Const +val ilFieldToTastConst: ILFieldInit -> Const /// Compile a pattern into a decision tree and a set of targets. -val internal CompilePattern : +val internal CompilePattern: TcGlobals -> DisplayEnv -> Import.ImportMap -> @@ -66,9 +67,11 @@ val internal CompilePattern : TType -> // result type TType -> - // produce TAST nodes - DecisionTree * DecisionTreeTarget list + // produce TAST nodes + DecisionTree * DecisionTreeTarget list exception internal MatchIncomplete of bool * (string * bool) option * range + exception internal RuleNeverMatched of range + exception internal EnumMatchIncomplete of bool * (string * bool) option * range \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/PostInferenceChecks.fs b/src/fcs-fable/src/fsharp/PostInferenceChecks.fs old mode 100755 new mode 100644 index cf4d4e4ad9..711bae6cbb --- a/src/fcs-fable/src/fsharp/PostInferenceChecks.fs +++ b/src/fcs-fable/src/fsharp/PostInferenceChecks.fs @@ -11,18 +11,19 @@ open FSharp.Compiler open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library - open FSharp.Compiler.AccessibilityLogic -open FSharp.Compiler.Ast open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Range -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Lib open FSharp.Compiler.Infos -open FSharp.Compiler.PrettyNaming open FSharp.Compiler.InfoReader +open FSharp.Compiler.Lib +open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TypeRelations //-------------------------------------------------------------------------- @@ -93,7 +94,10 @@ type env = returnScope : int /// Are we in an app expression (Expr.App)? - isInAppExpr: bool } + isInAppExpr: bool + } + + override __.ToString() = "" let BindTypar env (tp: Typar) = { env with @@ -183,26 +187,42 @@ let CombineLimits limits = type cenv = { boundVals: Dictionary // really a hash set + limitVals: Dictionary + mutable potentialUnboundUsesOfVals: StampMap + mutable anonRecdTypes: StampMap + g: TcGlobals + amap: Import.ImportMap + /// For reading metadata infoReader: InfoReader + internalsVisibleToPaths : CompilationPath list + denv: DisplayEnv + viewCcu : CcuThunk + reportErrors: bool + isLastCompiland : bool*bool + isInternalTestSpanStackReferring: bool + // outputs mutable usesQuotations : bool + mutable entryPointGiven: bool } + override x.ToString() = "" + /// Check if the value is an argument of a function let IsValArgument env (v: Val) = - env.argVals.ContainsVal(v) + env.argVals.ContainsVal v /// Check if the value is a local, not an argument of a function. let IsValLocal env (v: Val) = @@ -211,7 +231,7 @@ let IsValLocal env (v: Val) = /// Get the limit of the val. let GetLimitVal cenv env m (v: Val) = let limit = - match cenv.limitVals.TryGetValue(v.Stamp) with + match cenv.limitVals.TryGetValue v.Stamp with | true, limit -> limit | _ -> if IsValLocal env v then @@ -263,7 +283,8 @@ let GetLimitValByRef cenv env m v = { scope = scope; flags = flags } let LimitVal cenv (v: Val) limit = - cenv.limitVals.[v.Stamp] <- limit + if not v.IgnoresByrefScope then + cenv.limitVals.[v.Stamp] <- limit let BindVal cenv env (v: Val) = //printfn "binding %s..." v.DisplayName @@ -285,11 +306,15 @@ let BindVal cenv env (v: Val) = let BindVals cenv env vs = List.iter (BindVal cenv env) vs +let RecordAnonRecdInfo cenv (anonInfo: AnonRecdTypeInfo) = + if not (cenv.anonRecdTypes.ContainsKey anonInfo.Stamp) then + cenv.anonRecdTypes <- cenv.anonRecdTypes.Add(anonInfo.Stamp, anonInfo) + //-------------------------------------------------------------------------- // approx walk of type //-------------------------------------------------------------------------- -let rec CheckTypeDeep (cenv: cenv) ((visitTy, visitTyconRefOpt, visitAppTyOpt, visitTraitSolutionOpt, visitTyparOpt) as f) g env isInner ty = +let rec CheckTypeDeep (cenv: cenv) ((visitTy, visitTyconRefOpt, visitAppTyOpt, visitTraitSolutionOpt, visitTyparOpt) as f) (g: TcGlobals) env isInner ty = // We iterate the _solved_ constraints as well, to pick up any record of trait constraint solutions // This means we walk _all_ the constraints _everywhere_ in a type, including // those attached to _solved_ type variables. This is used by PostTypeCheckSemanticChecks to detect uses of @@ -298,17 +323,24 @@ let rec CheckTypeDeep (cenv: cenv) ((visitTy, visitTyconRefOpt, visitAppTyOpt, v // In an ideal world we would, instead, record the solutions to these constraints as "witness variables" in expressions, // rather than solely in types. match ty with - | TType_var tp when tp.Solution.IsSome -> - tp.Constraints |> List.iter (fun cx -> + | TType_var tp when tp.Solution.IsSome -> + for cx in tp.Constraints do match cx with | TyparConstraint.MayResolveMember((TTrait(_, _, _, _, _, soln)), _) -> match visitTraitSolutionOpt, !soln with | Some visitTraitSolution, Some sln -> visitTraitSolution sln | _ -> () - | _ -> ()) + | _ -> () | _ -> () - let ty = stripTyparEqns ty + let ty = + if g.compilingFslib then + match stripTyparEqns ty with + // When compiling FSharp.Core, do not strip type equations at this point if we can't dereference a tycon. + | TType_app (tcref, _) when not tcref.CanDeref -> ty + | _ -> stripTyEqns g ty + else + stripTyEqns g ty visitTy ty match ty with @@ -334,8 +366,7 @@ let rec CheckTypeDeep (cenv: cenv) ((visitTy, visitTyconRefOpt, visitAppTyOpt, v | Some visitAppTy -> visitAppTy (tcref, tinst) | None -> () | TType_anon (anonInfo, tys) -> - if not (cenv.anonRecdTypes.ContainsKey anonInfo.Stamp) then - cenv.anonRecdTypes <- cenv.anonRecdTypes.Add(anonInfo.Stamp, anonInfo) + RecordAnonRecdInfo cenv anonInfo CheckTypesDeep cenv f g env tys | TType_ucase (_, tinst) -> CheckTypesDeep cenv f g env tinst @@ -349,10 +380,12 @@ let rec CheckTypeDeep (cenv: cenv) ((visitTy, visitTyconRefOpt, visitAppTyOpt, v visitTyar (env, tp) and CheckTypesDeep cenv f g env tys = - tys |> List.iter (CheckTypeDeep cenv f g env true) + for ty in tys do + CheckTypeDeep cenv f g env true ty and CheckTypesDeepNoInner cenv f g env tys = - tys |> List.iter (CheckTypeDeep cenv f g env false) + for ty in tys do + CheckTypeDeep cenv f g env false ty and CheckTypeConstraintDeep cenv f g env x = match x with @@ -445,7 +478,7 @@ let CheckTypeForAccess (cenv: cenv) env objName valAcc m ty = let visitType ty = // We deliberately only check the fully stripped type for accessibility, // because references to private type abbreviations are permitted - match tryDestAppTy cenv.g ty with + match tryTcrefOfAppTy cenv.g ty with | ValueNone -> () | ValueSome tcref -> let thisCompPath = compPathOfCcu cenv.viewCcu @@ -461,7 +494,7 @@ let WarnOnWrongTypeForAccess (cenv: cenv) env objName valAcc m ty = let visitType ty = // We deliberately only check the fully stripped type for accessibility, // because references to private type abbreviations are permitted - match tryDestAppTy cenv.g ty with + match tryTcrefOfAppTy cenv.g ty with | ValueNone -> () | ValueSome tcref -> let thisCompPath = compPathOfCcu cenv.viewCcu @@ -538,7 +571,7 @@ let mkArgsForAppliedVal isBaseCall (vref: ValRef) argsl = | Some topValInfo -> let argArities = topValInfo.AritiesOfArgs let argArities = if isBaseCall && argArities.Length >= 1 then List.tail argArities else argArities - // Check for partial applications: arguments to partial applciations don't get to use byrefs + // Check for partial applications: arguments to partial applications don't get to use byrefs if List.length argsl >= argArities.Length then List.map mkArgsPermit argArities else @@ -551,9 +584,9 @@ let rec mkArgsForAppliedExpr isBaseCall argsl x = // recognise val | Expr.Val (vref, _, _) -> mkArgsForAppliedVal isBaseCall vref argsl // step through instantiations - | Expr.App(f, _fty, _tyargs, [], _) -> mkArgsForAppliedExpr isBaseCall argsl f + | Expr.App (f, _fty, _tyargs, [], _) -> mkArgsForAppliedExpr isBaseCall argsl f // step through subsumption coercions - | Expr.Op(TOp.Coerce, _, [f], _) -> mkArgsForAppliedExpr isBaseCall argsl f + | Expr.Op (TOp.Coerce, _, [f], _) -> mkArgsForAppliedExpr isBaseCall argsl f | _ -> [] /// Check types occurring in the TAST. @@ -586,7 +619,7 @@ let CheckTypeAux permitByRefLike (cenv: cenv) env m ty onInnerByrefError = let visitAppTy (tcref, tinst) = if isByrefLikeTyconRef cenv.g m tcref then let visitType ty0 = - match tryDestAppTy cenv.g ty0 with + match tryTcrefOfAppTy cenv.g ty0 with | ValueNone -> () | ValueSome tcref2 -> if isByrefTyconRef cenv.g tcref2 then @@ -617,7 +650,7 @@ let CheckTypePermitSpanLike (cenv: cenv) env m ty = CheckType PermitByRefType.Sp /// Check types occurring in TAST but allow all byrefs. Only used on internally-generated types let CheckTypePermitAllByrefs (cenv: cenv) env m ty = CheckType PermitByRefType.All cenv env m ty -/// Check types ocurring in TAST but disallow inner types to be byref or byref-like types. +/// Check types occurring in TAST but disallow inner types to be byref or byref-like types. let CheckTypeNoInnerByrefs cenv env m ty = CheckType PermitByRefType.NoInnerByRefLike cenv env m ty let CheckTypeInstNoByrefs cenv env m tyargs = @@ -631,7 +664,7 @@ let CheckTypeInstNoInnerByrefs cenv env m tyargs = /// Applied functions get wrapped in coerce nodes for subsumption coercions let (|OptionalCoerce|) = function - | Expr.Op(TOp.Coerce _, _, [Expr.App(f, _, _, [], _)], _) -> f + | Expr.Op (TOp.Coerce _, _, [Expr.App (f, _, _, [], _)], _) -> f | x -> x /// Check an expression doesn't contain a 'reraise' @@ -675,6 +708,7 @@ and CheckValRef (cenv: cenv) (env: env) v m (context: PermitByRefExpr) = if isSpliceOperator cenv.g v then errorR(Error(FSComp.SR.chkNoFirstClassSplicing(), m)) if valRefEq cenv.g v cenv.g.addrof_vref then errorR(Error(FSComp.SR.chkNoFirstClassAddressOf(), m)) if valRefEq cenv.g v cenv.g.reraise_vref then errorR(Error(FSComp.SR.chkNoFirstClassRethrow(), m)) + if valRefEq cenv.g v cenv.g.nameof_vref then errorR(Error(FSComp.SR.chkNoFirstClassNameOf(), m)) // ByRefLike-typed values can only occur in permitting contexts if context.Disallow && isByrefLikeTy cenv.g m v.Type then @@ -742,29 +776,29 @@ and CheckForOverAppliedExceptionRaisingPrimitive (cenv: cenv) expr = // Some things are more easily checked prior to NormalizeAndAdjustPossibleSubsumptionExprs match expr with - | Expr.App(f, _fty, _tyargs, argsl, _m) -> + | Expr.App (f, _fty, _tyargs, argsl, _m) -> if cenv.reportErrors then // Special diagnostics for `raise`, `failwith`, `failwithf`, `nullArg`, `invalidOp` library intrinsics commonly used to raise exceptions // to warn on over-application. match f with - | OptionalCoerce(Expr.Val(v, _, funcRange)) + | OptionalCoerce(Expr.Val (v, _, funcRange)) when (valRefEq g v g.raise_vref || valRefEq g v g.failwith_vref || valRefEq g v g.null_arg_vref || valRefEq g v g.invalid_op_vref) -> match argsl with | [] | [_] -> () | _ :: _ :: _ -> warning(Error(FSComp.SR.checkRaiseFamilyFunctionArgumentCount(v.DisplayName, 1, argsl.Length), funcRange)) - | OptionalCoerce(Expr.Val(v, _, funcRange)) when valRefEq g v g.invalid_arg_vref -> + | OptionalCoerce(Expr.Val (v, _, funcRange)) when valRefEq g v g.invalid_arg_vref -> match argsl with | [] | [_] | [_; _] -> () | _ :: _ :: _ :: _ -> warning(Error(FSComp.SR.checkRaiseFamilyFunctionArgumentCount(v.DisplayName, 2, argsl.Length), funcRange)) - | OptionalCoerce(Expr.Val(failwithfFunc, _, funcRange)) when valRefEq g failwithfFunc g.failwithf_vref -> + | OptionalCoerce(Expr.Val (failwithfFunc, _, funcRange)) when valRefEq g failwithfFunc g.failwithf_vref -> match argsl with - | Expr.App (Expr.Val(newFormat, _, _), _, [_; typB; typC; _; _], [Expr.Const(Const.String formatString, formatRange, _)], _) :: xs when valRefEq g newFormat g.new_format_vref -> + | Expr.App (Expr.Val (newFormat, _, _), _, [_; typB; typC; _; _], [Expr.Const (Const.String formatString, formatRange, _)], _) :: xs when valRefEq g newFormat g.new_format_vref -> match CheckFormatStrings.TryCountFormatStringArguments formatRange g formatString typB typC with | Some n -> let expected = n + 1 @@ -800,7 +834,7 @@ and CheckCallLimitArgs cenv env m returnTy limitArgs (context: PermitByRefExpr) errorR(Error(FSComp.SR.chkNoByrefAddressOfValueFromExpression(), m)) // You cannot call a function that takes a byref of a span-like (not stack referring) and - // either a stack referring spanlike or a local-byref of a stack referring span-like. + // either a stack referring span-like or a local-byref of a stack referring span-like. let isCallLimited = HasLimitFlag LimitFlags.ByRefOfSpanLike limitArgs && (HasLimitFlag LimitFlags.StackReferringSpanLike limitArgs || @@ -932,7 +966,7 @@ and CheckExpr (cenv: cenv) (env: env) origExpr (context: PermitByRefExpr) : Limi | Expr.Val (vref, vFlags, m) -> CheckValUse cenv env (vref, vFlags, m) context - | Expr.Quote(ast, savedConv, _isFromQueryExpression, m, ty) -> + | Expr.Quote (ast, savedConv, _isFromQueryExpression, m, ty) -> CheckExprNoByrefs cenv {env with quote=true} ast if cenv.reportErrors then cenv.usesQuotations <- true @@ -940,7 +974,7 @@ and CheckExpr (cenv: cenv) (env: env) origExpr (context: PermitByRefExpr) : Limi // Translate to quotation data try let qscope = QuotationTranslator.QuotationGenerationScope.Create (g, cenv.amap, cenv.viewCcu, QuotationTranslator.IsReflectedDefinition.No) - let qdata = QuotationTranslator.ConvExprPublic qscope QuotationTranslator.QuotationTranslationEnv.Empty ast + let qdata = QuotationTranslator.ConvExprPublic qscope ast let typeDefs, spliceTypes, spliceExprs = qscope.Close() match savedConv.Value with | None -> savedConv:= Some (typeDefs, List.map fst spliceTypes, List.map fst spliceExprs, qdata) @@ -968,7 +1002,7 @@ and CheckExpr (cenv: cenv) (env: env) origExpr (context: PermitByRefExpr) : Limi NoLimit // Allow base calls to F# methods - | Expr.App((InnerExprPat(ExprValWithPossibleTypeInst(v, vFlags, _, _) as f)), _fty, tyargs, (Expr.Val(baseVal, _, _) :: rest), m) + | Expr.App ((InnerExprPat(ExprValWithPossibleTypeInst(v, vFlags, _, _) as f)), _fty, tyargs, (Expr.Val (baseVal, _, _) :: rest), m) when ((match vFlags with VSlotDirectCall -> true | _ -> false) && baseVal.BaseOrThisInfo = BaseVal) -> @@ -987,11 +1021,11 @@ and CheckExpr (cenv: cenv) (env: env) origExpr (context: PermitByRefExpr) : Limi CheckExprs cenv env rest (mkArgsForAppliedExpr true rest f) // Allow base calls to IL methods - | Expr.Op (TOp.ILCall (virt, _, _, _, _, _, _, mref, enclTypeArgs, methTypeArgs, tys), tyargs, (Expr.Val(baseVal, _, _)::rest), m) + | Expr.Op (TOp.ILCall (virt, _, _, _, _, _, _, mref, enclTypeArgs, methTypeArgs, tys), tyargs, (Expr.Val (baseVal, _, _) :: rest), m) when not virt && baseVal.BaseOrThisInfo = BaseVal -> // Disallow calls to abstract base methods on IL types. - match tryDestAppTy g baseVal.Type with + match tryTcrefOfAppTy g baseVal.Type with | ValueSome tcref when tcref.IsILTycon -> try // This is awkward - we have to explicitly re-resolve back to the IL metadata to determine if the method is abstract. @@ -1011,8 +1045,8 @@ and CheckExpr (cenv: cenv) (env: env) origExpr (context: PermitByRefExpr) : Limi CheckValRef cenv env baseVal m PermitByRefExpr.No CheckExprsPermitByRefLike cenv env rest - | Expr.Op (c, tyargs, args, m) -> - CheckExprOp cenv env (c, tyargs, args, m) context expr + | Expr.Op (op, tyargs, args, m) -> + CheckExprOp cenv env (op, tyargs, args, m) context expr // Allow 'typeof' calls as a special case, the only accepted use of System.Void! | TypeOfExpr g ty when isVoidTy g ty -> @@ -1023,13 +1057,13 @@ and CheckExpr (cenv: cenv) (env: env) origExpr (context: PermitByRefExpr) : Limi NoLimit // Allow '%expr' in quotations - | Expr.App(Expr.Val(vref, _, _), _, tinst, [arg], m) when isSpliceOperator g vref && env.quote -> + | Expr.App (Expr.Val (vref, _, _), _, tinst, [arg], m) when isSpliceOperator g vref && env.quote -> CheckTypeInstNoInnerByrefs cenv env m tinst // it's the splice operator, a byref instantiation is allowed CheckExprNoByrefs cenv env arg NoLimit // Check an application - | Expr.App(f, _fty, tyargs, argsl, m) -> + | Expr.App (f, _fty, tyargs, argsl, m) -> let returnTy = tyOfExpr g expr // This is to handle recursive cases. Don't check 'returnTy' again if we are still inside a app expression. @@ -1043,7 +1077,7 @@ and CheckExpr (cenv: cenv) (env: env) origExpr (context: PermitByRefExpr) : Limi let hasReceiver = match f with - | Expr.Val(vref, _, _) when vref.IsInstanceMember && not argsl.IsEmpty -> true + | Expr.Val (vref, _, _) when vref.IsInstanceMember && not argsl.IsEmpty -> true | _ -> false let contexts = mkArgsForAppliedExpr false argsl f @@ -1052,22 +1086,22 @@ and CheckExpr (cenv: cenv) (env: env) origExpr (context: PermitByRefExpr) : Limi else CheckCall cenv env m returnTy argsl contexts context - | Expr.Lambda(_, _ctorThisValOpt, _baseValOpt, argvs, _, m, rty) -> + | Expr.Lambda (_, _ctorThisValOpt, _baseValOpt, argvs, _, m, rty) -> let topValInfo = ValReprInfo ([], [argvs |> List.map (fun _ -> ValReprInfo.unnamedTopArg1)], ValReprInfo.unnamedRetVal) let ty = mkMultiLambdaTy m argvs rty in CheckLambdas false None cenv env false topValInfo false expr m ty PermitByRefExpr.Yes - | Expr.TyLambda(_, tps, _, m, rty) -> + | Expr.TyLambda (_, tps, _, m, rty) -> let topValInfo = ValReprInfo (ValReprInfo.InferTyparInfo tps, [], ValReprInfo.unnamedRetVal) let ty = mkForallTyIfNeeded tps rty in CheckLambdas false None cenv env false topValInfo false expr m ty PermitByRefExpr.Yes - | Expr.TyChoose(tps, e1, _) -> + | Expr.TyChoose (tps, e1, _) -> let env = BindTypars g env tps CheckExprNoByrefs cenv env e1 NoLimit - | Expr.Match(_, _, dtree, targets, m, ty) -> + | Expr.Match (_, _, dtree, targets, m, ty) -> CheckTypeNoInnerByrefs cenv env m ty // computed byrefs allowed at each branch CheckDecisionTree cenv env dtree CheckDecisionTreeTargets cenv env targets context @@ -1085,7 +1119,7 @@ and CheckExpr (cenv: cenv) (env: env) origExpr (context: PermitByRefExpr) : Limi | TTyconEqualsTycon(ty1, ty2) -> CheckTypeNoByrefs cenv env m ty1 CheckTypeNoByrefs cenv env m ty2 - | TTyconIsStruct(ty1) -> + | TTyconIsStruct ty1 -> CheckTypeNoByrefs cenv env m ty1) NoLimit @@ -1101,7 +1135,7 @@ and CheckMethod cenv env baseValOpt (TObjExprMethod(_, attribs, tps, vs, body, m let env = BindArgVals env vs CheckAttribs cenv env attribs CheckNoReraise cenv None body - CheckEscapes cenv true m (match baseValOpt with Some x -> x:: vs | None -> vs) body |> ignore + CheckEscapes cenv true m (match baseValOpt with Some x -> x :: vs | None -> vs) body |> ignore CheckExpr cenv { env with returnScope = env.returnScope + 1 } body PermitByRefExpr.YesReturnableNonLocal |> ignore and CheckInterfaceImpls cenv env baseValOpt l = @@ -1115,25 +1149,32 @@ and CheckExprOp cenv env (op, tyargs, args, m) context expr = let ctorLimitedZoneCheck() = if env.ctorLimitedZone then errorR(Error(FSComp.SR.chkObjCtorsCantUseExceptionHandling(), m)) - (* Special cases *) + // Ensure anonymous record type requirements are recorded + match op with + | TOp.AnonRecdGet (anonInfo, _) + | TOp.AnonRecd anonInfo -> + RecordAnonRecdInfo cenv anonInfo + | _ -> () + + // Special cases match op, tyargs, args with // Handle these as special cases since mutables are allowed inside their bodies - | TOp.While _, _, [Expr.Lambda(_, _, _, [_], e1, _, _);Expr.Lambda(_, _, _, [_], e2, _, _)] -> + | TOp.While _, _, [Expr.Lambda (_, _, _, [_], e1, _, _);Expr.Lambda (_, _, _, [_], e2, _, _)] -> CheckTypeInstNoByrefs cenv env m tyargs CheckExprsNoByRefLike cenv env [e1;e2] - | TOp.TryFinally _, [_], [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [_], e2, _, _)] -> + | TOp.TryFinally _, [_], [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [_], e2, _, _)] -> CheckTypeInstNoInnerByrefs cenv env m tyargs // result of a try/finally can be a byref ctorLimitedZoneCheck() let limit = CheckExpr cenv env e1 context // result of a try/finally can be a byref if in a position where the overall expression is can be a byref CheckExprNoByrefs cenv env e2 limit - | TOp.For(_), _, [Expr.Lambda(_, _, _, [_], e1, _, _);Expr.Lambda(_, _, _, [_], e2, _, _);Expr.Lambda(_, _, _, [_], e3, _, _)] -> + | TOp.For _, _, [Expr.Lambda (_, _, _, [_], e1, _, _);Expr.Lambda (_, _, _, [_], e2, _, _);Expr.Lambda (_, _, _, [_], e3, _, _)] -> CheckTypeInstNoByrefs cenv env m tyargs CheckExprsNoByRefLike cenv env [e1;e2;e3] - | TOp.TryCatch _, [_], [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [_], _e2, _, _); Expr.Lambda(_, _, _, [_], e3, _, _)] -> + | TOp.TryCatch _, [_], [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [_], _e2, _, _); Expr.Lambda (_, _, _, [_], e3, _, _)] -> CheckTypeInstNoInnerByrefs cenv env m tyargs // result of a try/catch can be a byref ctorLimitedZoneCheck() let limit1 = CheckExpr cenv env e1 context // result of a try/catch can be a byref if in a position where the overall expression is can be a byref @@ -1180,7 +1221,7 @@ and CheckExprOp cenv env (op, tyargs, args, m) context expr = CheckTypeInstNoByrefs cenv env m tyargs CheckExprsNoByRefLike cenv env args - | TOp.LValueOp(LAddrOf _, vref), _, _ -> + | TOp.LValueOp (LAddrOf _, vref), _, _ -> let limit1 = GetLimitValByRef cenv env m vref.Deref let limit2 = CheckExprsNoByRefLike cenv env args let limit = CombineTwoLimits limit1 limit2 @@ -1203,7 +1244,7 @@ and CheckExprOp cenv env (op, tyargs, args, m) context expr = limit - | TOp.LValueOp(LByrefSet, vref), _, [arg] -> + | TOp.LValueOp (LByrefSet, vref), _, [arg] -> let limit = GetLimitVal cenv env m vref.Deref let isVrefLimited = not (HasLimitFlag LimitFlags.ByRefOfStackReferringSpanLike limit) let isArgLimited = HasLimitFlag LimitFlags.StackReferringSpanLike (CheckExprPermitByRefLike cenv env arg) @@ -1211,7 +1252,7 @@ and CheckExprOp cenv env (op, tyargs, args, m) context expr = errorR(Error(FSComp.SR.chkNoWriteToLimitedSpan(vref.DisplayName), m)) NoLimit - | TOp.LValueOp(LByrefGet, vref), _, [] -> + | TOp.LValueOp (LByrefGet, vref), _, [] -> let limit = GetLimitVal cenv env m vref.Deref if HasLimitFlag LimitFlags.ByRefOfStackReferringSpanLike limit then @@ -1227,7 +1268,7 @@ and CheckExprOp cenv env (op, tyargs, args, m) context expr = else { scope = 1; flags = LimitFlags.None } - | TOp.LValueOp(LSet _, vref), _, [arg] -> + | TOp.LValueOp (LSet _, vref), _, [arg] -> let isVrefLimited = not (HasLimitFlag LimitFlags.StackReferringSpanLike (GetLimitVal cenv env m vref.Deref)) let isArgLimited = HasLimitFlag LimitFlags.StackReferringSpanLike (CheckExprPermitByRefLike cenv env arg) if isVrefLimited && isArgLimited then @@ -1287,8 +1328,8 @@ and CheckExprOp cenv env (op, tyargs, args, m) context expr = // C# applies a rule where the APIs to struct types can't return the addresses of fields in that struct. // There seems no particular reason for this given that other protections in the language, though allowing - // it would mean "readonly" on a struct doesn't imply immutabality-of-contents - it only implies - if context.PermitOnlyReturnable && (match obj with Expr.Val(vref, _, _) -> vref.BaseOrThisInfo = MemberThisVal | _ -> false) && isByrefTy g (tyOfExpr g obj) then + // it would mean "readonly" on a struct doesn't imply immutability-of-contents - it only implies + if context.PermitOnlyReturnable && (match obj with Expr.Val (vref, _, _) -> vref.BaseOrThisInfo = MemberThisVal | _ -> false) && isByrefTy g (tyOfExpr g obj) then errorR(Error(FSComp.SR.chkStructsMayNotReturnAddressesOfContents(), m)) if context.Disallow && cenv.reportErrors && isByrefLikeTy g m (tyOfExpr g expr) then @@ -1313,7 +1354,7 @@ and CheckExprOp cenv env (op, tyargs, args, m) context expr = if context.Disallow && cenv.reportErrors && isByrefLikeTy g m (tyOfExpr g expr) then errorR(Error(FSComp.SR.chkNoAddressFieldAtThisPoint(uref.CaseName), m)) - if context.PermitOnlyReturnable && (match obj with Expr.Val(vref, _, _) -> vref.BaseOrThisInfo = MemberThisVal | _ -> false) && isByrefTy g (tyOfExpr g obj) then + if context.PermitOnlyReturnable && (match obj with Expr.Val (vref, _, _) -> vref.BaseOrThisInfo = MemberThisVal | _ -> false) && isByrefTy g (tyOfExpr g obj) then errorR(Error(FSComp.SR.chkStructsMayNotReturnAddressesOfContents(), m)) CheckTypeInstNoByrefs cenv env m tyargs @@ -1341,20 +1382,20 @@ and CheckExprOp cenv env (op, tyargs, args, m) context expr = // permit byref for lhs lvalue of readonly value CheckExprsPermitByRefLike cenv env args - | [ I_ldsflda (fspec) ], [] -> + | [ I_ldsflda fspec ], [] -> if context.Disallow && cenv.reportErrors && isByrefLikeTy g m (tyOfExpr g expr) then errorR(Error(FSComp.SR.chkNoAddressFieldAtThisPoint(fspec.Name), m)) NoLimit - | [ I_ldflda (fspec) ], [obj] -> + | [ I_ldflda fspec ], [obj] -> if context.Disallow && cenv.reportErrors && isByrefLikeTy g m (tyOfExpr g expr) then errorR(Error(FSComp.SR.chkNoAddressFieldAtThisPoint(fspec.Name), m)) // Recursively check in same context, e.g. if at PermitOnlyReturnable the obj arg must also be returnable CheckExpr cenv env obj context - | [ I_ldelema (_, isNativePtr, _, _) ], lhsArray::indices -> + | [ I_ldelema (_, isNativePtr, _, _) ], lhsArray :: indices -> if context.Disallow && cenv.reportErrors && not isNativePtr && isByrefLikeTy g m (tyOfExpr g expr) then errorR(Error(FSComp.SR.chkNoAddressOfArrayElementAtThisPoint(), m)) // permit byref for lhs lvalue @@ -1374,7 +1415,7 @@ and CheckExprOp cenv env (op, tyargs, args, m) context expr = // allow args to be byref here CheckExprsPermitByRefLike cenv env args - | TOp.Recd(_, _), _, _ -> + | TOp.Recd (_, _), _, _ -> CheckTypeInstNoByrefs cenv env m tyargs CheckExprsPermitByRefLike cenv env args @@ -1387,12 +1428,12 @@ and CheckLambdas isTop (memInfo: ValMemberInfo option) cenv env inlined topValIn // The topValInfo here says we are _guaranteeing_ to compile a function value // as a .NET method with precisely the corresponding argument counts. match e with - | Expr.TyChoose(tps, e1, m) -> + | Expr.TyChoose (tps, e1, m) -> let env = BindTypars g env tps CheckLambdas isTop memInfo cenv env inlined topValInfo alwaysCheckNoReraise e1 m ety context | Expr.Lambda (_, _, _, _, _, m, _) - | Expr.TyLambda(_, _, _, m, _) -> + | Expr.TyLambda (_, _, _, m, _) -> let tps, ctorThisValOpt, baseValOpt, vsl, body, bodyty = destTopLambda g cenv.amap topValInfo (e, ety) in let env = BindTypars g env tps let thisAndBase = Option.toList ctorThisValOpt @ Option.toList baseValOpt @@ -1407,7 +1448,7 @@ and CheckLambdas isTop (memInfo: ValMemberInfo option) cenv env inlined topValIn for v in thisAndBase do v.SetHasBeenReferenced() // instance method 'this' is always considered used match mi.MemberFlags.IsInstance, restArgs with - | true, firstArg::_ -> firstArg.SetHasBeenReferenced() + | true, firstArg :: _ -> firstArg.SetHasBeenReferenced() | _ -> () // any byRef arguments are considered used, as they may be 'out's restArgs |> List.iter (fun arg -> if isByrefTy g arg.Type then arg.SetHasBeenReferenced()) @@ -1544,6 +1585,7 @@ and CheckDecisionTreeTest cenv env m discrim = | DecisionTreeTest.IsNull -> () | DecisionTreeTest.IsInst (srcTy, tgtTy) -> CheckTypeNoInnerByrefs cenv env m srcTy; CheckTypeNoInnerByrefs cenv env m tgtTy | DecisionTreeTest.ActivePatternCase (exp, _, _, _, _) -> CheckExprNoByrefs cenv env exp + | DecisionTreeTest.Error _ -> () and CheckAttrib cenv env (Attrib(_, _, args, props, _, _, _)) = props |> List.iter (fun (AttribNamedArg(_, _, _, expr)) -> CheckAttribExpr cenv env expr) @@ -1560,7 +1602,7 @@ and CheckAttribArgExpr cenv env expr = match expr with // Detect standard constants - | Expr.Const(c, m, _) -> + | Expr.Const (c, m, _) -> match c with | Const.Bool _ | Const.Int32 _ @@ -1581,13 +1623,13 @@ and CheckAttribArgExpr cenv env expr = if cenv.reportErrors then errorR (Error (FSComp.SR.tastNotAConstantExpression(), m)) - | Expr.Op(TOp.Array, [_elemTy], args, _m) -> + | Expr.Op (TOp.Array, [_elemTy], args, _m) -> List.iter (CheckAttribArgExpr cenv env) args | TypeOfExpr g _ -> () | TypeDefOfExpr g _ -> () - | Expr.Op(TOp.Coerce, _, [arg], _) -> + | Expr.Op (TOp.Coerce, _, [arg], _) -> CheckAttribArgExpr cenv env arg | EnumExpr g arg1 -> CheckAttribArgExpr cenv env arg1 @@ -1611,7 +1653,7 @@ and CheckAttribs cenv env (attribs: Attribs) = |> Seq.map fst |> Seq.toList // Filter for allowMultiple = false - |> List.filter (fun (tcref, m) -> TryFindAttributeUsageAttribute cenv.g m tcref <> Some(true)) + |> List.filter (fun (tcref, m) -> TryFindAttributeUsageAttribute cenv.g m tcref <> Some true) if cenv.reportErrors then for (tcref, m) in duplicates do @@ -1636,10 +1678,10 @@ and CheckValSpec permitByRefLike cenv env v = and AdjustAccess isHidden (cpath: unit -> CompilationPath) access = if isHidden then - let (TAccess(l)) = access + let (TAccess l) = access // FSharp 1.0 bug 1908: Values hidden by signatures are implicitly at least 'internal' let scoref = cpath().ILScopeRef - TAccess(CompPath(scoref, [])::l) + TAccess(CompPath(scoref, []) :: l) else access @@ -1712,21 +1754,16 @@ and CheckBinding cenv env alwaysCheckNoReraise context (TBind(v, bindRhs, _) as // no real need for that except that it helps us to bundle all reflected definitions up into // one blob for pickling to the binary format try - let ety = tyOfExpr g bindRhs - let tps, taue, _ = - match bindRhs with - | Expr.TyLambda (_, tps, b, _, _) -> tps, b, applyForallTy g ety (List.map mkTyparTy tps) - | _ -> [], bindRhs, ety - let env = QuotationTranslator.QuotationTranslationEnv.Empty.BindTypars tps let qscope = QuotationTranslator.QuotationGenerationScope.Create (g, cenv.amap, cenv.viewCcu, QuotationTranslator.IsReflectedDefinition.Yes) - QuotationTranslator.ConvExprPublic qscope env taue |> ignore - let _, _, argExprs = qscope.Close() - if not (isNil argExprs) then + let methName = v.CompiledName g.CompilerGlobalState + QuotationTranslator.ConvReflectedDefinition qscope methName v bindRhs |> ignore + + let _, _, exprSplices = qscope.Close() + if not (isNil exprSplices) then errorR(Error(FSComp.SR.chkReflectedDefCantSplice(), v.Range)) - QuotationTranslator.ConvMethodBase qscope env (v.CompiledName, v) |> ignore with | QuotationTranslator.InvalidQuotedTerm e -> - errorR(e) + errorR e match v.MemberInfo with | Some memberInfo when not v.IsIncrClassGeneratedMember -> @@ -1788,14 +1825,14 @@ let CheckModuleBinding cenv env (TBind(v, e, _) as bind) = let hasDefaultAugmentation = tcref.IsUnionTycon && match TryFindFSharpAttribute g g.attrib_DefaultAugmentationAttribute tcref.Attribs with - | Some(Attrib(_, _, [ AttribBoolArg(b) ], _, _, _, _)) -> b + | Some(Attrib(_, _, [ AttribBoolArg b ], _, _, _, _)) -> b | _ -> true (* not hiddenRepr *) let kind = (if v.IsMember then "member" else "value") let check skipValCheck nm = if not skipValCheck && v.IsModuleBinding && - tcref.ModuleOrNamespaceType.AllValsByLogicalName.ContainsKey(nm) && + tcref.ModuleOrNamespaceType.AllValsByLogicalName.ContainsKey nm && not (valEq tcref.ModuleOrNamespaceType.AllValsByLogicalName.[nm] v) then error(Duplicate(kind, v.DisplayName, v.Range)) @@ -1810,8 +1847,8 @@ let CheckModuleBinding cenv env (TBind(v, e, _) as bind) = | "Tags" -> errorR(NameClash(nm, kind, v.DisplayName, v.Range, FSComp.SR.typeInfoGeneratedType(), "Tags", tcref.Range)) | _ -> if hasDefaultAugmentation then - match tcref.GetUnionCaseByName(nm) with - | Some(uc) -> error(NameClash(nm, kind, v.DisplayName, v.Range, FSComp.SR.typeInfoUnionCase(), uc.DisplayName, uc.Range)) + match tcref.GetUnionCaseByName nm with + | Some uc -> error(NameClash(nm, kind, v.DisplayName, v.Range, FSComp.SR.typeInfoUnionCase(), uc.DisplayName, uc.Range)) | None -> () let hasNoArgs = @@ -1827,30 +1864,30 @@ let CheckModuleBinding cenv env (TBind(v, e, _) as bind) = // Default augmentation contains the nasty 'Case' etc. let prefix = "New" - if nm.StartsWithOrdinal(prefix) then + if nm.StartsWithOrdinal prefix then match tcref.GetUnionCaseByName(nm.[prefix.Length ..]) with - | Some(uc) -> error(NameClash(nm, kind, v.DisplayName, v.Range, FSComp.SR.chkUnionCaseCompiledForm(), uc.DisplayName, uc.Range)) + | Some uc -> error(NameClash(nm, kind, v.DisplayName, v.Range, FSComp.SR.chkUnionCaseCompiledForm(), uc.DisplayName, uc.Range)) | None -> () // Default augmentation contains the nasty 'Is' etc. let prefix = "Is" - if nm.StartsWithOrdinal(prefix) && hasDefaultAugmentation then + if nm.StartsWithOrdinal prefix && hasDefaultAugmentation then match tcref.GetUnionCaseByName(nm.[prefix.Length ..]) with - | Some(uc) -> error(NameClash(nm, kind, v.DisplayName, v.Range, FSComp.SR.chkUnionCaseDefaultAugmentation(), uc.DisplayName, uc.Range)) + | Some uc -> error(NameClash(nm, kind, v.DisplayName, v.Range, FSComp.SR.chkUnionCaseDefaultAugmentation(), uc.DisplayName, uc.Range)) | None -> () - match tcref.GetFieldByName(nm) with - | Some(rf) -> error(NameClash(nm, kind, v.DisplayName, v.Range, "field", rf.Name, rf.Range)) + match tcref.GetFieldByName nm with + | Some rf -> error(NameClash(nm, kind, v.DisplayName, v.Range, "field", rf.Name, rf.Range)) | None -> () check false v.CoreDisplayName check false v.DisplayName - check false v.CompiledName + check false (v.CompiledName cenv.g.CompilerGlobalState) // Check if an F# extension member clashes if v.IsExtensionMember then tcref.ModuleOrNamespaceType.AllValsAndMembersByLogicalNameUncached.[v.LogicalName] |> List.iter (fun v2 -> - if v2.IsExtensionMember && not (valEq v v2) && v.CompiledName = v2.CompiledName then + if v2.IsExtensionMember && not (valEq v v2) && (v.CompiledName cenv.g.CompilerGlobalState) = (v2.CompiledName cenv.g.CompilerGlobalState) then let minfo1 = FSMeth(g, generalizedTyconRef tcref, mkLocalValRef v, Some 0UL) let minfo2 = FSMeth(g, generalizedTyconRef tcref, mkLocalValRef v2, Some 0UL) if tyconRefEq g v.MemberApparentEntity v2.MemberApparentEntity && @@ -1915,7 +1952,7 @@ let CheckEntityDefn cenv env (tycon: Entity) = let ty = generalizedTyconRef tcref let env = { env with reflect = env.reflect || HasFSharpAttribute g g.attrib_ReflectedDefinitionAttribute tycon.Attribs } - let env = BindTypars g env (tycon.Typars(m)) + let env = BindTypars g env (tycon.Typars m) CheckAttribs cenv env tycon.Attribs @@ -1930,7 +1967,7 @@ let CheckEntityDefn cenv env (tycon: Entity) = let allVirtualMethsInParent = match GetSuperTypeOfType g cenv.amap m ty with | Some super -> - GetIntrinsicMethInfosOfType cenv.infoReader (None, AccessibleFromSomewhere, AllowMultiIntfInstantiations.Yes) IgnoreOverrides m super + GetIntrinsicMethInfosOfType cenv.infoReader None AccessibleFromSomewhere AllowMultiIntfInstantiations.Yes IgnoreOverrides m super |> List.filter (fun minfo -> minfo.IsVirtual) | None -> [] @@ -1948,7 +1985,7 @@ let CheckEntityDefn cenv env (tycon: Entity) = let immediateProps = GetImmediateIntrinsicPropInfosOfType (None, AccessibleFromSomewhere) g cenv.amap m ty let getHash (hash: Dictionary) nm = - match hash.TryGetValue(nm) with + match hash.TryGetValue nm with | true, h -> h | _ -> [] @@ -1958,7 +1995,7 @@ let CheckEntityDefn cenv env (tycon: Entity) = for minfo in immediateMeths do match h.TryGetValue minfo.LogicalName with | true, methods -> - h.[minfo.LogicalName] <- minfo::methods + h.[minfo.LogicalName] <- minfo :: methods | false, _ -> h.[minfo.LogicalName] <- [minfo] h @@ -2011,19 +2048,19 @@ let CheckEntityDefn cenv env (tycon: Entity) = match (optArgInfo, callerInfo) with | _, NoCallerInfo -> () | NotOptional, _ -> errorR(Error(FSComp.SR.tcCallerInfoNotOptional(callerInfo.ToString()), m)) - | CallerSide(_), CallerLineNumber -> + | CallerSide _, CallerLineNumber -> if not (typeEquiv g g.int32_ty ty) then errorR(Error(FSComp.SR.tcCallerInfoWrongType(callerInfo.ToString(), "int", NicePrint.minimalStringOfType cenv.denv ty), m)) | CalleeSide, CallerLineNumber -> if not ((isOptionTy g ty) && (typeEquiv g g.int32_ty (destOptionTy g ty))) then errorR(Error(FSComp.SR.tcCallerInfoWrongType(callerInfo.ToString(), "int", NicePrint.minimalStringOfType cenv.denv (destOptionTy g ty)), m)) - | CallerSide(_), CallerFilePath -> + | CallerSide _, CallerFilePath -> if not (typeEquiv g g.string_ty ty) then errorR(Error(FSComp.SR.tcCallerInfoWrongType(callerInfo.ToString(), "string", NicePrint.minimalStringOfType cenv.denv ty), m)) | CalleeSide, CallerFilePath -> if not ((isOptionTy g ty) && (typeEquiv g g.string_ty (destOptionTy g ty))) then errorR(Error(FSComp.SR.tcCallerInfoWrongType(callerInfo.ToString(), "string", NicePrint.minimalStringOfType cenv.denv (destOptionTy g ty)), m)) - | CallerSide(_), CallerMemberName -> + | CallerSide _, CallerMemberName -> if not (typeEquiv g g.string_ty ty) then errorR(Error(FSComp.SR.tcCallerInfoWrongType(callerInfo.ToString(), "string", NicePrint.minimalStringOfType cenv.denv ty), m)) | CalleeSide, CallerMemberName -> @@ -2079,14 +2116,14 @@ let CheckEntityDefn cenv env (tycon: Entity) = if not (typeEquivAux EraseNone cenv.amap.g ty1 ty2) then errorR(Error(FSComp.SR.chkGetterAndSetterHaveSamePropertyType(pinfo.PropertyName, NicePrint.minimalStringOfType cenv.denv ty1, NicePrint.minimalStringOfType cenv.denv ty2), m)) - hashOfImmediateProps.[nm] <- pinfo::others + hashOfImmediateProps.[nm] <- pinfo :: others if not (isInterfaceTy g ty) then let hashOfAllVirtualMethsInParent = new Dictionary() for minfo in allVirtualMethsInParent do let nm = minfo.LogicalName let others = getHash hashOfAllVirtualMethsInParent nm - hashOfAllVirtualMethsInParent.[nm] <- minfo::others + hashOfAllVirtualMethsInParent.[nm] <- minfo :: others for minfo in immediateMeths do if not minfo.IsDispatchSlot && not minfo.IsVirtual && minfo.IsInstance then let nm = minfo.LogicalName @@ -2098,9 +2135,9 @@ let CheckEntityDefn cenv env (tycon: Entity) = | Some minfo -> let mtext = NicePrint.stringOfMethInfo cenv.amap m cenv.denv minfo if parentMethsOfSameName |> List.exists (checkForDup EraseNone) then - warning(Error(FSComp.SR.tcNewMemberHidesAbstractMember(mtext), m)) + warning(Error(FSComp.SR.tcNewMemberHidesAbstractMember mtext, m)) else - warning(Error(FSComp.SR.tcNewMemberHidesAbstractMemberWithSuffix(mtext), m)) + warning(Error(FSComp.SR.tcNewMemberHidesAbstractMemberWithSuffix mtext, m)) if minfo.IsDispatchSlot then @@ -2111,9 +2148,9 @@ let CheckEntityDefn cenv env (tycon: Entity) = if parentMethsOfSameName |> List.exists (checkForDup EraseAll) then if parentMethsOfSameName |> List.exists (checkForDup EraseNone) then - errorR(Error(FSComp.SR.chkDuplicateMethodInheritedType(nm), m)) + errorR(Error(FSComp.SR.chkDuplicateMethodInheritedType nm, m)) else - errorR(Error(FSComp.SR.chkDuplicateMethodInheritedTypeWithSuffix(nm), m)) + errorR(Error(FSComp.SR.chkDuplicateMethodInheritedTypeWithSuffix nm, m)) if TyconRefHasAttribute g m g.attrib_IsByRefLikeAttribute tcref && not tycon.IsStructOrEnumTycon then errorR(Error(FSComp.SR.tcByRefLikeNotStruct(), tycon.Range)) @@ -2195,7 +2232,7 @@ let CheckEntityDefn cenv env (tycon: Entity) = for f in tycon.AllInstanceFieldsAsList do // Check if it's marked unsafe let zeroInitUnsafe = TryFindFSharpBoolAttribute g g.attrib_DefaultValueAttribute f.FieldAttribs - if zeroInitUnsafe = Some(true) then + if zeroInitUnsafe = Some true then if not (TypeHasDefaultValue g m ty) then errorR(Error(FSComp.SR.chkValueWithDefaultValueMustHaveDefaultValue(), m)) @@ -2243,8 +2280,8 @@ and CheckDefnInModule cenv env x = CheckNothingAfterEntryPoint cenv m CheckNoReraise cenv None e CheckExprNoByrefs cenv env e - | TMAbstract(def) -> CheckModuleExpr cenv env def - | TMDefs(defs) -> CheckDefnsInModule cenv env defs + | TMAbstract def -> CheckModuleExpr cenv env def + | TMDefs defs -> CheckDefnsInModule cenv env defs and CheckModuleSpec cenv env x = match x with @@ -2299,6 +2336,6 @@ let CheckTopImpl (g, amap, reportErrors, infoReader, internalsVisibleToPaths, vi CheckModuleExpr cenv env mexpr CheckAttribs cenv env extraAttribs - if cenv.usesQuotations && QuotationTranslator.QuotationGenerationScope.ComputeQuotationFormat(g) = QuotationTranslator.QuotationSerializationFormat.FSharp_20_Plus then + if cenv.usesQuotations && QuotationTranslator.QuotationGenerationScope.ComputeQuotationFormat g = QuotationTranslator.QuotationSerializationFormat.FSharp_20_Plus then viewCcu.UsesFSharp20PlusQuotations <- true cenv.entryPointGiven, cenv.anonRecdTypes diff --git a/src/fcs-fable/src/fsharp/PostInferenceChecks.fsi b/src/fcs-fable/src/fsharp/PostInferenceChecks.fsi index 25c6bf3ac3..312da64027 100644 --- a/src/fcs-fable/src/fsharp/PostInferenceChecks.fsi +++ b/src/fcs-fable/src/fsharp/PostInferenceChecks.fsi @@ -6,9 +6,20 @@ module internal FSharp.Compiler.PostTypeCheckSemanticChecks open FSharp.Compiler.Import open FSharp.Compiler.InfoReader -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals /// Perform the checks on the TAST for a file after type inference is complete. -val CheckTopImpl : TcGlobals * ImportMap * bool * InfoReader * CompilationPath list * CcuThunk * DisplayEnv * ModuleOrNamespaceExprWithSig * Attribs * (bool * bool) * isInternalTestSpanStackReferring: bool -> bool * StampMap +val CheckTopImpl: + g: TcGlobals * + amap: ImportMap * + reportErrors: bool * + infoReader: InfoReader * + internalsVisibleToPaths: CompilationPath list * + viewCcu: CcuThunk * + denv: DisplayEnv * + mexpr: ModuleOrNamespaceExprWithSig * + extraAttribs: Attribs * (bool * bool) * + isInternalTestSpanStackReferring: bool + -> bool * StampMap diff --git a/src/fcs-fable/src/fsharp/PrettyNaming.fs b/src/fcs-fable/src/fsharp/PrettyNaming.fs index a1ea08317b..f7521b50b9 100755 --- a/src/fcs-fable/src/fsharp/PrettyNaming.fs +++ b/src/fcs-fable/src/fsharp/PrettyNaming.fs @@ -1,704 +1,769 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -//---------------------------------------------------------------------------- -// Some general F# utilities for mangling / unmangling / manipulating names. -//-------------------------------------------------------------------------- - +/// Some general F# utilities for mangling / unmangling / manipulating names. /// Anything to do with special names of identifiers and other lexical rules module public FSharp.Compiler.PrettyNaming - open System - open System.Collections.Generic - open System.Collections.Concurrent - open System.Globalization - open System.Text - - open FSharp.Compiler - open FSharp.Compiler.AbstractIL.Internal.Library - - open Internal.Utilities - open Internal.Utilities.StructuredFormat - open Internal.Utilities.StructuredFormat.LayoutOps - - //------------------------------------------------------------------------ - // Operator name compilation - //----------------------------------------------------------------------- - - let [] parenGet = ".()" - let [] parenSet = ".()<-" - let [] qmark = "?" - let [] qmarkSet = "?<-" - - /// Prefix for compiled (mangled) operator names. - let [] opNamePrefix = "op_" - - let private opNameTable = - [|("[]", "op_Nil") - ("::", "op_ColonColon") - ("+", "op_Addition") - ("~%", "op_Splice") - ("~%%", "op_SpliceUntyped") - ("~++", "op_Increment") - ("~--", "op_Decrement") - ("-", "op_Subtraction") - ("*", "op_Multiply") - ("**", "op_Exponentiation") - ("/", "op_Division") - ("@", "op_Append") - ("^", "op_Concatenate") - ("%", "op_Modulus") - ("&&&", "op_BitwiseAnd") - ("|||", "op_BitwiseOr") - ("^^^", "op_ExclusiveOr") - ("<<<", "op_LeftShift") - ("~~~", "op_LogicalNot") - (">>>", "op_RightShift") - ("~+", "op_UnaryPlus") - ("~-", "op_UnaryNegation") - ("~&", "op_AddressOf") - ("~&&", "op_IntegerAddressOf") - ("&&", "op_BooleanAnd") - ("||", "op_BooleanOr") - ("<=", "op_LessThanOrEqual") - ("=", "op_Equality") - ("<>", "op_Inequality") - (">=", "op_GreaterThanOrEqual") - ("<", "op_LessThan") - (">", "op_GreaterThan") - ("|>", "op_PipeRight") - ("||>", "op_PipeRight2") - ("|||>", "op_PipeRight3") - ("<|", "op_PipeLeft") - ("<||", "op_PipeLeft2") - ("<|||", "op_PipeLeft3") - ("!", "op_Dereference") - (">>", "op_ComposeRight") - ("<<", "op_ComposeLeft") - ("<< >>", "op_TypedQuotationUnicode") - ("<<| |>>", "op_ChevronsBar") - ("<@ @>", "op_Quotation") - ("<@@ @@>", "op_QuotationUntyped") - ("+=", "op_AdditionAssignment") - ("-=", "op_SubtractionAssignment") - ("*=", "op_MultiplyAssignment") - ("/=", "op_DivisionAssignment") - ("..", "op_Range") - (".. ..", "op_RangeStep") - (qmark, "op_Dynamic") - (qmarkSet, "op_DynamicAssignment") - (parenGet, "op_ArrayLookup") - (parenSet, "op_ArrayAssign") - |] - - let private opCharTranslateTable = - [|( '>', "Greater") - ( '<', "Less") - ( '+', "Plus") - ( '-', "Minus") - ( '*', "Multiply") - ( '=', "Equals") - ( '~', "Twiddle") - ( '%', "Percent") - ( '.', "Dot") - ( '$', "Dollar") - ( '&', "Amp") - ( '|', "Bar") - ( '@', "At") - ( '#', "Hash") - ( '^', "Hat") - ( '!', "Bang") - ( '?', "Qmark") - ( '/', "Divide") - ( ':', "Colon") - ( '(', "LParen") - ( ',', "Comma") - ( ')', "RParen") - ( ' ', "Space") - ( '[', "LBrack") - ( ']', "RBrack") |] - - /// The set of characters usable in custom operators. - let private opCharSet = - let t = new HashSet<_>() - for (c, _) in opCharTranslateTable do - t.Add(c) |> ignore - t + +open System +open System.Collections.Generic +open System.Collections.Concurrent +open System.Globalization +open System.Text + +open FSharp.Compiler +open FSharp.Compiler.AbstractIL +open FSharp.Compiler.AbstractIL.Internal.Library + +open Internal.Utilities +open Internal.Utilities.StructuredFormat +open Internal.Utilities.StructuredFormat.LayoutOps + +//------------------------------------------------------------------------ +// Operator name compilation +//----------------------------------------------------------------------- + +let [] parenGet = ".()" +let [] parenSet = ".()<-" +let [] qmark = "?" +let [] qmarkSet = "?<-" + +/// Prefix for compiled (mangled) operator names. +let [] opNamePrefix = "op_" + +let private opNameTable = + [|("[]", "op_Nil") + ("::", "op_ColonColon") + ("+", "op_Addition") + ("~%", "op_Splice") + ("~%%", "op_SpliceUntyped") + ("~++", "op_Increment") + ("~--", "op_Decrement") + ("-", "op_Subtraction") + ("*", "op_Multiply") + ("**", "op_Exponentiation") + ("/", "op_Division") + ("@", "op_Append") + ("^", "op_Concatenate") + ("%", "op_Modulus") + ("&&&", "op_BitwiseAnd") + ("|||", "op_BitwiseOr") + ("^^^", "op_ExclusiveOr") + ("<<<", "op_LeftShift") + ("~~~", "op_LogicalNot") + (">>>", "op_RightShift") + ("~+", "op_UnaryPlus") + ("~-", "op_UnaryNegation") + ("~&", "op_AddressOf") + ("~&&", "op_IntegerAddressOf") + ("&&", "op_BooleanAnd") + ("||", "op_BooleanOr") + ("<=", "op_LessThanOrEqual") + ("=", "op_Equality") + ("<>", "op_Inequality") + (">=", "op_GreaterThanOrEqual") + ("<", "op_LessThan") + (">", "op_GreaterThan") + ("|>", "op_PipeRight") + ("||>", "op_PipeRight2") + ("|||>", "op_PipeRight3") + ("<|", "op_PipeLeft") + ("<||", "op_PipeLeft2") + ("<|||", "op_PipeLeft3") + ("!", "op_Dereference") + (">>", "op_ComposeRight") + ("<<", "op_ComposeLeft") + ("<< >>", "op_TypedQuotationUnicode") + ("<<| |>>", "op_ChevronsBar") + ("<@ @>", "op_Quotation") + ("<@@ @@>", "op_QuotationUntyped") + ("+=", "op_AdditionAssignment") + ("-=", "op_SubtractionAssignment") + ("*=", "op_MultiplyAssignment") + ("/=", "op_DivisionAssignment") + ("..", "op_Range") + (".. ..", "op_RangeStep") + (qmark, "op_Dynamic") + (qmarkSet, "op_DynamicAssignment") + (parenGet, "op_ArrayLookup") + (parenSet, "op_ArrayAssign") + |] + +let private opCharTranslateTable = + [|( '>', "Greater") + ( '<', "Less") + ( '+', "Plus") + ( '-', "Minus") + ( '*', "Multiply") + ( '=', "Equals") + ( '~', "Twiddle") + ( '%', "Percent") + ( '.', "Dot") + ( '$', "Dollar") + ( '&', "Amp") + ( '|', "Bar") + ( '@', "At") + ( '#', "Hash") + ( '^', "Hat") + ( '!', "Bang") + ( '?', "Qmark") + ( '/', "Divide") + ( ':', "Colon") + ( '(', "LParen") + ( ',', "Comma") + ( ')', "RParen") + ( ' ', "Space") + ( '[', "LBrack") + ( ']', "RBrack") |] + +/// The set of characters usable in custom operators. +let private opCharSet = + let t = new HashSet<_>() + for (c, _) in opCharTranslateTable do + t.Add(c) |> ignore + t - /// Returns `true` if given string is an operator or double backticked name, e.g. ( |>> ) or ( long identifier ). - /// (where ( long identifier ) is the display name for ``long identifier``). - let IsOperatorOrBacktickedName (name: string) = - let nameLen = name.Length - let rec loop i = (i < nameLen && (opCharSet.Contains(name.[i]) || loop (i+1))) - loop 0 - - /// Returns `true` if given string is an operator display name, e.g. ( |>> ) - let IsOperatorName (name: string) = - let name = - if name.StartsWithOrdinal("( ") && name.EndsWithOrdinal(" )") then - name.[2 .. name.Length - 3] - else name - // there is single operator containing a space - range operator with step: `.. ..` - name = ".. .." || name |> Seq.forall (fun c -> c <> ' ' && opCharSet.Contains c) - - let IsMangledOpName (n: string) = - n.StartsWithOrdinal(opNamePrefix) - - /// Compiles a custom operator into a mangled operator name. - /// For example, "!%" becomes "op_DereferencePercent". - /// This function should only be used for custom operators - /// if an operator is or potentially may be a built-in operator, - /// use the 'CompileOpName' function instead. - let private compileCustomOpName = - let t2 = - let t2 = Dictionary<_, _> (opCharTranslateTable.Length) - for x, y in opCharTranslateTable do - t2.Add (x, y) - t2 - /// The maximum length of the name for a custom operator character. - /// This value is used when initializing StringBuilders to avoid resizing. - let maxOperatorNameLength = - opCharTranslateTable - |> Array.maxBy (snd >> String.length) - |> snd - |> String.length - - /// Memoize compilation of custom operators. - /// They're typically used more than once so this avoids some CPU and GC overhead. - let compiledOperators = ConcurrentDictionary<_, string> (StringComparer.Ordinal) - - fun opp -> - // Has this operator already been compiled? - compiledOperators.GetOrAdd(opp, fun (op: string) -> - let opLength = op.Length - let sb = new Text.StringBuilder (opNamePrefix, opNamePrefix.Length + (opLength * maxOperatorNameLength)) - for i = 0 to opLength - 1 do - let c = op.[i] - match t2.TryGetValue c with - | true, x -> - sb.Append(x) |> ignore - | false, _ -> - sb.Append(string c) |> ignore - - /// The compiled (mangled) operator name. - let opName = sb.ToString () - - // Cache the compiled name so it can be reused. - opName) - - /// Compiles an operator into a mangled operator name. - /// For example, "!%" becomes "op_DereferencePercent". - /// This function accepts both built-in and custom operators. - let CompileOpName = - /// Maps the built-in F# operators to their mangled operator names. - let standardOpNames = - let opNames = Dictionary<_, _> (opNameTable.Length, StringComparer.Ordinal) - for x, y in opNameTable do - opNames.Add (x, y) - opNames - - fun op -> - match standardOpNames.TryGetValue op with - | true, x -> x - | false, _ -> - if IsOperatorOrBacktickedName op then - compileCustomOpName op - else op - - /// Decompiles the mangled name of a custom operator back into an operator. - /// For example, "op_DereferencePercent" becomes "!%". - /// This function should only be used for mangled names of custom operators - /// if a mangled name potentially represents a built-in operator, - /// use the 'DecompileOpName' function instead. - let private decompileCustomOpName = - // Memoize this operation. Custom operators are typically used more than once - // so this avoids repeating decompilation. - let decompiledOperators = ConcurrentDictionary<_, _> (StringComparer.Ordinal) - - /// The minimum length of the name for a custom operator character. - /// This value is used when initializing StringBuilders to avoid resizing. - let minOperatorNameLength = - opCharTranslateTable - |> Array.minBy (snd >> String.length) - |> snd - |> String.length - - fun opName -> - // Has this operator name already been decompiled? - match decompiledOperators.TryGetValue opName with - | true, op -> op - | false, _ -> - let opNameLen = opName.Length +/// Returns `true` if given string is an operator or double backticked name, e.g. ( |>> ) or ( long identifier ). +/// (where ( long identifier ) is the display name for ``long identifier``). +let IsOperatorOrBacktickedName (name: string) = + let nameLen = name.Length + let rec loop i = (i < nameLen && (opCharSet.Contains(name.[i]) || loop (i+1))) + loop 0 + +/// Returns `true` if given string is an operator display name, e.g. ( |>> ) +let IsOperatorName (name: string) = + let rec isOperatorName (name: string) idx endIndex = + if idx = endIndex then + true + else + let c = name.[idx] + if not (opCharSet.Contains(c)) || c = ' ' then + false + else + isOperatorName name (idx + 1) endIndex + + let skipParens = if name.StartsWithOrdinal("( ") && name.EndsWithOrdinal(" )") then true else false + let startIndex = if skipParens then 2 else 0 + let endIndex = if skipParens then name.Length - 2 else name.Length + + isOperatorName name startIndex endIndex || name = ".. .." + +let IsMangledOpName (n: string) = + n.StartsWithOrdinal(opNamePrefix) + +/// Compiles a custom operator into a mangled operator name. +/// For example, "!%" becomes "op_DereferencePercent". +/// This function should only be used for custom operators +/// if an operator is or potentially may be a built-in operator, +/// use the 'CompileOpName' function instead. +let private compileCustomOpName = + let t2 = + let t2 = Dictionary<_, _> (opCharTranslateTable.Length) + for x, y in opCharTranslateTable do + t2.Add (x, y) + t2 + /// The maximum length of the name for a custom operator character. + /// This value is used when initializing StringBuilders to avoid resizing. + let maxOperatorNameLength = + opCharTranslateTable + |> Array.maxBy (snd >> String.length) + |> snd + |> String.length + + /// Memoize compilation of custom operators. + /// They're typically used more than once so this avoids some CPU and GC overhead. + let compiledOperators = ConcurrentDictionary<_, string> (StringComparer.Ordinal) + + fun opp -> + // Has this operator already been compiled? + compiledOperators.GetOrAdd(opp, fun (op: string) -> + let opLength = op.Length + let sb = new Text.StringBuilder (opNamePrefix, opNamePrefix.Length + (opLength * maxOperatorNameLength)) + for i = 0 to opLength - 1 do + let c = op.[i] + match t2.TryGetValue c with + | true, x -> + sb.Append(x) |> ignore + | false, _ -> + sb.Append(c) |> ignore + + /// The compiled (mangled) operator name. + let opName = sb.ToString () + + // Cache the compiled name so it can be reused. + opName) + +/// Compiles an operator into a mangled operator name. +/// For example, "!%" becomes "op_DereferencePercent". +/// This function accepts both built-in and custom operators. +let CompileOpName = + /// Maps the built-in F# operators to their mangled operator names. + let standardOpNames = + let opNames = Dictionary<_, _> (opNameTable.Length, StringComparer.Ordinal) + for x, y in opNameTable do + opNames.Add (x, y) + opNames + + fun op -> + match standardOpNames.TryGetValue op with + | true, x -> x + | false, _ -> + if IsOperatorOrBacktickedName op then + compileCustomOpName op + else op + +/// Decompiles the mangled name of a custom operator back into an operator. +/// For example, "op_DereferencePercent" becomes "!%". +/// This function should only be used for mangled names of custom operators +/// if a mangled name potentially represents a built-in operator, +/// use the 'DecompileOpName' function instead. +let private decompileCustomOpName = + // Memoize this operation. Custom operators are typically used more than once + // so this avoids repeating decompilation. + let decompiledOperators = ConcurrentDictionary<_, _> (StringComparer.Ordinal) + + /// The minimum length of the name for a custom operator character. + /// This value is used when initializing StringBuilders to avoid resizing. + let minOperatorNameLength = + opCharTranslateTable + |> Array.minBy (snd >> String.length) + |> snd + |> String.length + + fun opName -> + // Has this operator name already been decompiled? + match decompiledOperators.TryGetValue opName with + | true, op -> op + | false, _ -> + let opNameLen = opName.Length - /// Function which decompiles the mangled operator name back into a string of operator characters. - /// Returns None if the name contains text which doesn't correspond to an operator - /// otherwise returns Some containing the original operator. - let rec decompile (sb : StringBuilder) idx = - // Have we reached the end of 'opName'? - if idx = opNameLen then - // Finished decompiling. - // Cache the decompiled operator before returning so it can be reused. - let decompiledOp = sb.ToString () - decompiledOperators.TryAdd (opName, decompiledOp) |> ignore - decompiledOp - else - let choice = - opCharTranslateTable - |> Array.tryFind (fun (_, opCharName) -> - // If this operator character name is longer than the remaining piece of 'opName', - // it's obviously not a match. - let opCharNameLen = opCharName.Length - if opNameLen - idx < opCharNameLen then false - else - // Does 'opCharName' match the current position in 'opName'? - String.Compare (opName, idx, opCharName, 0, opCharNameLen, StringComparison.Ordinal) = 0) - - match choice with - | None -> - // Couldn't decompile, so just return the original 'opName'. - opName - | Some (opChar, opCharName) -> - // 'opCharName' matched the current position in 'opName'. - // Append the corresponding operator character to the StringBuilder - // and continue decompiling at the index following this instance of 'opCharName'. - sb.Append (string opChar) |> ignore - decompile sb (idx + opCharName.Length) - - let opNamePrefixLen = opNamePrefix.Length - let sb = - /// The maximum number of operator characters that could be contained in the - /// decompiled operator given the length of the mangled custom operator name. - let maxPossibleOpCharCount = (opNameLen - opNamePrefixLen) / minOperatorNameLength - StringBuilder (maxPossibleOpCharCount) - - // Start decompiling just after the operator prefix. - decompile sb opNamePrefixLen - - - /// Decompiles a mangled operator name back into an operator. - /// For example, "op_DereferencePercent" becomes "!%". - /// This function accepts mangled names for both built-in and custom operators. - let DecompileOpName = - /// Maps the mangled operator names of built-in F# operators back to the operators. - let standardOps = - let ops = Dictionary (opNameTable.Length, StringComparer.Ordinal) - for x, y in opNameTable do - ops.Add(y, x) - ops - - fun opName -> - match standardOps.TryGetValue opName with - | true, res -> res - | false, _ -> - if IsMangledOpName opName then - decompileCustomOpName opName + /// Function which decompiles the mangled operator name back into a string of operator characters. + /// Returns None if the name contains text which doesn't correspond to an operator + /// otherwise returns Some containing the original operator. + let rec decompile (sb : StringBuilder) idx = + // Have we reached the end of 'opName'? + if idx = opNameLen then + // Finished decompiling. + // Cache the decompiled operator before returning so it can be reused. + let decompiledOp = sb.ToString () + decompiledOperators.TryAdd (opName, decompiledOp) |> ignore + decompiledOp else - opName + let choice = + opCharTranslateTable + |> Array.tryFind (fun (_, opCharName) -> + // If this operator character name is longer than the remaining piece of 'opName', + // it's obviously not a match. + let opCharNameLen = opCharName.Length + if opNameLen - idx < opCharNameLen then false + else + // Does 'opCharName' match the current position in 'opName'? + String.Compare (opName, idx, opCharName, 0, opCharNameLen, StringComparison.Ordinal) = 0) + + match choice with + | None -> + // Couldn't decompile, so just return the original 'opName'. + opName + | Some (opChar, opCharName) -> + // 'opCharName' matched the current position in 'opName'. + // Append the corresponding operator character to the StringBuilder + // and continue decompiling at the index following this instance of 'opCharName'. + sb.Append opChar |> ignore + decompile sb (idx + opCharName.Length) + + let opNamePrefixLen = opNamePrefix.Length + let sb = + /// The maximum number of operator characters that could be contained in the + /// decompiled operator given the length of the mangled custom operator name. + let maxPossibleOpCharCount = (opNameLen - opNamePrefixLen) / minOperatorNameLength + StringBuilder (maxPossibleOpCharCount) + + // Start decompiling just after the operator prefix. + decompile sb opNamePrefixLen - let DemangleOperatorName nm = - let nm = DecompileOpName nm - if IsOperatorOrBacktickedName nm then "( " + nm + " )" - else nm - let DemangleOperatorNameAsLayout nonOpTagged nm = - let nm = DecompileOpName nm - if IsOperatorOrBacktickedName nm then wordL (TaggedTextOps.tagPunctuation "(") ^^ wordL (TaggedTextOps.tagOperator nm) ^^ wordL (TaggedTextOps.tagPunctuation ")") - else wordL (nonOpTagged nm) - - let opNameCons = CompileOpName "::" - - let opNameNil = CompileOpName "[]" - let opNameEquals = CompileOpName "=" - let opNameEqualsNullable = CompileOpName "=?" - let opNameNullableEquals = CompileOpName "?=" - let opNameNullableEqualsNullable = CompileOpName "?=?" - - /// The characters that are allowed to be the first character of an identifier. - let IsIdentifierFirstCharacter c = - if c = '_' then true - else - match Char.GetUnicodeCategory c with - // Letters - | UnicodeCategory.UppercaseLetter - | UnicodeCategory.LowercaseLetter - | UnicodeCategory.TitlecaseLetter - | UnicodeCategory.ModifierLetter - | UnicodeCategory.OtherLetter - | UnicodeCategory.LetterNumber -> true - | _ -> false - - /// The characters that are allowed to be in an identifier. - let IsIdentifierPartCharacter c = - if c = '\'' then true // Tick - else - match Char.GetUnicodeCategory c with - // Letters - | UnicodeCategory.UppercaseLetter - | UnicodeCategory.LowercaseLetter - | UnicodeCategory.TitlecaseLetter - | UnicodeCategory.ModifierLetter - | UnicodeCategory.OtherLetter - | UnicodeCategory.LetterNumber - // Numbers - | UnicodeCategory.DecimalDigitNumber - // Connectors - | UnicodeCategory.ConnectorPunctuation - // Combiners - | UnicodeCategory.NonSpacingMark - | UnicodeCategory.SpacingCombiningMark -> true - | _ -> false - - /// Is this character a part of a long identifier? - let IsLongIdentifierPartCharacter c = - c = '.' - || IsIdentifierPartCharacter c - - let IsValidPrefixOperatorUse s = - if String.IsNullOrEmpty s then false else - match s with - | "?+" | "?-" | "+" | "-" | "+." | "-." | "%" | "%%" | "&" | "&&" -> true - | _ -> - s.[0] = '!' - // The check for the first character here could be eliminated since it's covered - // by the call to String.forall; it is a fast check used to avoid the call if possible. - || (s.[0] = '~' && String.forall (fun c -> c = '~') s) +/// Decompiles a mangled operator name back into an operator. +/// For example, "op_DereferencePercent" becomes "!%". +/// This function accepts mangled names for both built-in and custom operators. +let DecompileOpName = + /// Maps the mangled operator names of built-in F# operators back to the operators. + let standardOps = + let ops = Dictionary (opNameTable.Length, StringComparer.Ordinal) + for x, y in opNameTable do + ops.Add(y, x) + ops + + fun opName -> + match standardOps.TryGetValue opName with + | true, res -> res + | false, _ -> + if IsMangledOpName opName then + decompileCustomOpName opName + else + opName + +let DemangleOperatorName nm = + let nm = DecompileOpName nm + if IsOperatorOrBacktickedName nm then "( " + nm + " )" + else nm - let IsValidPrefixOperatorDefinitionName s = - if String.IsNullOrEmpty s then false else - match s with - | "~?+" | "~?-" | "~+" | "~-" | "~+." | "~-." | "~%" | "~%%" | "~&" | "~&&" -> true - | _ -> - (s.[0] = '!' && s <> "!=") - // The check for the first character here could be eliminated since it's covered - // by the call to String.forall; it is a fast check used to avoid the call if possible. - || (s.[0] = '~' && String.forall (fun c -> c = '~') s) - - let IsPrefixOperator s = - if String.IsNullOrEmpty s then false else - let s = DecompileOpName s - match s with - | "~?+" | "~?-" | "~+" | "~-" | "~+." | "~-." | "~%" | "~%%" | "~&" | "~&&" -> true - | _ -> - (s.[0] = '!' && s <> "!=") - // The check for the first character here could be eliminated since it's covered - // by the call to String.forall; it is a fast check used to avoid the call if possible. - || (s.[0] = '~' && String.forall (fun c -> c = '~') s) +let DemangleOperatorNameAsLayout nonOpTagged nm = + let nm = DecompileOpName nm + if IsOperatorOrBacktickedName nm then wordL (TaggedTextOps.tagPunctuation "(") ^^ wordL (TaggedTextOps.tagOperator nm) ^^ wordL (TaggedTextOps.tagPunctuation ")") + else wordL (nonOpTagged nm) - let IsPunctuation s = - if String.IsNullOrEmpty s then false else - match s with - | "," | ";" | "|" | ":" | "." | "*" - | "(" | ")" - | "[" | "]" - | "{" | "}" - | "<" | ">" - | "[|" | "|]" - | "[<" | ">]" - -> true +let opNameCons = CompileOpName "::" + +let opNameNil = CompileOpName "[]" + +let opNameEquals = CompileOpName "=" + +let opNameEqualsNullable = CompileOpName "=?" + +let opNameNullableEquals = CompileOpName "?=" + +let opNameNullableEqualsNullable = CompileOpName "?=?" + +/// The characters that are allowed to be the first character of an identifier. +let IsIdentifierFirstCharacter c = + if c = '_' then true + else + match Char.GetUnicodeCategory c with + // Letters + | UnicodeCategory.UppercaseLetter + | UnicodeCategory.LowercaseLetter + | UnicodeCategory.TitlecaseLetter + | UnicodeCategory.ModifierLetter + | UnicodeCategory.OtherLetter + | UnicodeCategory.LetterNumber -> true | _ -> false - let IsTernaryOperator s = - (DecompileOpName s = qmarkSet) - - let IsInfixOperator = - - /// EQUALS, INFIX_COMPARE_OP, LESS, GREATER - let relational = [| "=";"!=";"<";">";"$"|] - - /// INFIX_AT_HAT_OP - let concat = [| "@";"^" |] - - /// PLUS_MINUS_OP, MINUS - let plusMinus = [| "+"; "-" |] - - /// PERCENT_OP, STAR, INFIX_STAR_DIV_MOD_OP - let otherMath = [| "*";"/";"%" |] - - /// Characters ignored at the start of the operator name - /// when determining whether an operator is an infix operator. - let ignoredChars = [| '.'; '?' |] - - fun s (* where s is assumed to be a compiled name *) -> - // Certain operator idents are parsed as infix expression operators. - // The parsing as infix operators is hardwired in the grammar [see declExpr productions] - // where certain operator tokens are accepted in infix forms, i.e. . - // The lexer defines the strings that lead to those tokens. - //------ - // This function recognises these "infix operator" names. - let s = DecompileOpName s - let skipIgnoredChars = s.TrimStart(ignoredChars) - let afterSkipStartsWith prefix = skipIgnoredChars.StartsWithOrdinal(prefix) - let afterSkipStarts prefixes = Array.exists afterSkipStartsWith prefixes - // The following conditions follow the declExpr infix clauses. - // The test corresponds to the lexer definition for the token. - s = ":=" || // COLON_EQUALS - afterSkipStartsWith "|" || // BAR_BAR, INFIX_BAR_OP - afterSkipStartsWith "&" || // AMP, AMP_AMP, INFIX_AMP_OP - afterSkipStarts relational || // EQUALS, INFIX_COMPARE_OP, LESS, GREATER - s = "$" || // DOLLAR - afterSkipStarts concat || // INFIX_AT_HAT_OP - s = "::" || // COLON_COLON - afterSkipStarts plusMinus || // PLUS_MINUS_OP, MINUS - afterSkipStarts otherMath || // PERCENT_OP, STAR, INFIX_STAR_DIV_MOD_OP - s = "**" // INFIX_STAR_STAR_OP - - let (|Control|Equality|Relational|Indexer|FixedTypes|Other|) opName = - match opName with - | "&" | "or" | "&&" | "||" -> - Control - | "<>" | "=" -> - Equality - | "<" | ">" | "<=" | ">=" -> - Relational - | "<<" | "<|" | "<||" | "<||" | "|>" | "||>" | "|||>" | ">>" | "^" | ":=" | "@" -> - FixedTypes - | ".[]" -> - Indexer - | _ -> - Other +/// The characters that are allowed to be in an identifier. +let IsIdentifierPartCharacter c = + if c = '\'' then true // Tick + else + match Char.GetUnicodeCategory c with + // Letters + | UnicodeCategory.UppercaseLetter + | UnicodeCategory.LowercaseLetter + | UnicodeCategory.TitlecaseLetter + | UnicodeCategory.ModifierLetter + | UnicodeCategory.OtherLetter + | UnicodeCategory.LetterNumber + // Numbers + | UnicodeCategory.DecimalDigitNumber + // Connectors + | UnicodeCategory.ConnectorPunctuation + // Combiners + | UnicodeCategory.NonSpacingMark + | UnicodeCategory.SpacingCombiningMark -> true + | _ -> false + +/// Is this character a part of a long identifier? +let IsLongIdentifierPartCharacter c = + c = '.' + || IsIdentifierPartCharacter c + +let isTildeOnlyString (s: string) = + let rec loop (s: string) idx = + if idx >= s.Length then + true + elif s.[idx] <> '~' then + false + else + loop s (idx + 1) + loop s 0 - let [] private compilerGeneratedMarker = "@" +let IsValidPrefixOperatorUse s = + if String.IsNullOrEmpty s then false else + match s with + | "?+" | "?-" | "+" | "-" | "+." | "-." | "%" | "%%" | "&" | "&&" -> true + | _ -> s.[0] = '!' || isTildeOnlyString s - let [] private compilerGeneratedMarkerChar = '@' +let IsValidPrefixOperatorDefinitionName s = + if String.IsNullOrEmpty s then false else + + match s.[0] with + | '~' -> + isTildeOnlyString s || + + match s with + | "~?+" | "~?-" | "~+" | "~-" | "~+." | "~-." | "~%" | "~%%" | "~&" | "~&&" -> true + | _ -> false + + | '!' -> s <> "!=" + | _ -> false + +let IsPrefixOperator s = + if String.IsNullOrEmpty s then false else + let s = DecompileOpName s + IsValidPrefixOperatorDefinitionName s + +let IsPunctuation s = + if String.IsNullOrEmpty s then false else + match s with + | "," | ";" | "|" | ":" | "." | "*" + | "(" | ")" + | "[" | "]" + | "{" | "}" + | "<" | ">" + | "[|" | "|]" + | "[<" | ">]" + -> true + | _ -> false + +let IsTernaryOperator s = + (DecompileOpName s = qmarkSet) + +let IsInfixOperator = + + /// EQUALS, INFIX_COMPARE_OP, LESS, GREATER + let relational = [| "=";"!=";"<";">";"$"|] + + /// INFIX_AT_HAT_OP + let concat = [| "@";"^" |] + + /// PLUS_MINUS_OP, MINUS + let plusMinus = [| "+"; "-" |] + + /// PERCENT_OP, STAR, INFIX_STAR_DIV_MOD_OP + let otherMath = [| "*";"/";"%" |] + + /// Characters ignored at the start of the operator name + /// when determining whether an operator is an infix operator. + let ignoredChars = [| '.'; '?' |] + + fun s (* where s is assumed to be a compiled name *) -> + // Certain operator idents are parsed as infix expression operators. + // The parsing as infix operators is hardwired in the grammar [see declExpr productions] + // where certain operator tokens are accepted in infix forms, i.e. . + // The lexer defines the strings that lead to those tokens. + //------ + // This function recognises these "infix operator" names. + let s = DecompileOpName s + let skipIgnoredChars = s.TrimStart(ignoredChars) + let afterSkipStartsWith prefix = skipIgnoredChars.StartsWithOrdinal(prefix) + let afterSkipStarts prefixes = Array.exists afterSkipStartsWith prefixes + // The following conditions follow the declExpr infix clauses. + // The test corresponds to the lexer definition for the token. + s = ":=" || // COLON_EQUALS + afterSkipStartsWith "|" || // BAR_BAR, INFIX_BAR_OP + afterSkipStartsWith "&" || // AMP, AMP_AMP, INFIX_AMP_OP + afterSkipStarts relational || // EQUALS, INFIX_COMPARE_OP, LESS, GREATER + s = "$" || // DOLLAR + afterSkipStarts concat || // INFIX_AT_HAT_OP + s = "::" || // COLON_COLON + afterSkipStarts plusMinus || // PLUS_MINUS_OP, MINUS + afterSkipStarts otherMath || // PERCENT_OP, STAR, INFIX_STAR_DIV_MOD_OP + s = "**" // INFIX_STAR_STAR_OP + +let (|Control|Equality|Relational|Indexer|FixedTypes|Other|) opName = + match opName with + | "&" | "or" | "&&" | "||" -> + Control + | "<>" | "=" -> + Equality + | "<" | ">" | "<=" | ">=" -> + Relational + | "<<" | "<|" | "<||" | "<||" | "|>" | "||>" | "|||>" | ">>" | "^" | ":=" | "@" -> + FixedTypes + | ".[]" -> + Indexer + | _ -> + Other + +let [] private compilerGeneratedMarker = "@" + +let [] private compilerGeneratedMarkerChar = '@' - let IsCompilerGeneratedName (nm: string) = - nm.IndexOf compilerGeneratedMarkerChar <> -1 +let IsCompilerGeneratedName (nm: string) = + nm.IndexOf compilerGeneratedMarkerChar <> -1 - let CompilerGeneratedName nm = - if IsCompilerGeneratedName nm then nm else nm+compilerGeneratedMarker +let CompilerGeneratedName nm = + if IsCompilerGeneratedName nm then nm else nm+compilerGeneratedMarker - let GetBasicNameOfPossibleCompilerGeneratedName (name: string) = +let GetBasicNameOfPossibleCompilerGeneratedName (name: string) = #if FABLE_COMPILER - match name.IndexOf(compilerGeneratedMarker) with + match name.IndexOf(compilerGeneratedMarker) with #else - match name.IndexOf(compilerGeneratedMarker, StringComparison.Ordinal) with + match name.IndexOf(compilerGeneratedMarker, StringComparison.Ordinal) with #endif - | -1 | 0 -> name - | n -> name.[0..n-1] + | -1 | 0 -> name + | n -> name.[0..n-1] - let CompilerGeneratedNameSuffix (basicName: string) suffix = - basicName+compilerGeneratedMarker+suffix +let CompilerGeneratedNameSuffix (basicName: string) suffix = + basicName+compilerGeneratedMarker+suffix - //------------------------------------------------------------------------- - // Handle mangled .NET generic type names - //------------------------------------------------------------------------- +//------------------------------------------------------------------------- +// Handle mangled .NET generic type names +//------------------------------------------------------------------------- - let [] private mangledGenericTypeNameSym = '`' - - let TryDemangleGenericNameAndPos (n: string) = - (* check what comes after the symbol is a number *) - let pos = n.LastIndexOf mangledGenericTypeNameSym - if pos = -1 then ValueNone else - let mutable res = pos < n.Length - 1 - let mutable i = pos + 1 - while res && i < n.Length do - let char = n.[i] - if not (char >= '0' && char <= '9') then - res <- false - i <- i + 1 - if res then - ValueSome pos - else - ValueNone - - type NameArityPair = NameArityPair of string * int - - let DecodeGenericTypeName pos (mangledName: string) = - let res = mangledName.Substring(0, pos) - let num = mangledName.Substring(pos+1, mangledName.Length - pos - 1) - NameArityPair(res, int32 num) - - let DemangleGenericTypeNameWithPos pos (mangledName: string) = - mangledName.Substring(0, pos) - - let DemangleGenericTypeName (mangledName: string) = - match TryDemangleGenericNameAndPos mangledName with - | ValueSome pos -> DemangleGenericTypeNameWithPos pos mangledName - | _ -> mangledName - - let private chopStringTo (s: string) (c: char) = - match s.IndexOf c with - | -1 -> s - | idx -> - let i = idx + 1 - s.Substring(i, s.Length - i) - - /// Try to chop "get_" or "set_" from a string - let TryChopPropertyName (s: string) = - // extract the logical name from any mangled name produced by MakeMemberDataAndMangledNameForMemberVal - if s.Length <= 4 then None else - if s.StartsWithOrdinal("get_") || - s.StartsWithOrdinal("set_") - then Some (s.Substring(4, s.Length - 4)) - else - let s = chopStringTo s '.' - if s.StartsWithOrdinal("get_") || - s.StartsWithOrdinal("set_") - then Some (s.Substring(4, s.Length - 4)) - else None - - /// Try to chop "get_" or "set_" from a string. - /// If the string does not start with "get_" or "set_", this function raises an exception. - let ChopPropertyName s = - match TryChopPropertyName s with - | None -> - failwithf "Invalid internal property name: '%s'" s - | Some res -> res - - let SplitNamesForILPath (s : string) : string list = - if s.StartsWithOrdinal("``") && s.EndsWithOrdinal("``") && s.Length > 4 then [s.Substring(2, s.Length-4)] // identifier is enclosed in `` .. ``, so it is only a single element (this is very approximate) - else s.Split [| '.' ; '`' |] |> Array.toList // '.' chops members / namespaces / modules; '`' chops generic parameters for .NET types +let [] private mangledGenericTypeNameSym = '`' + +let TryDemangleGenericNameAndPos (n: string) = + // check what comes after the symbol is a number + let pos = n.LastIndexOf mangledGenericTypeNameSym + if pos = -1 then ValueNone else + let mutable res = pos < n.Length - 1 + let mutable i = pos + 1 + while res && i < n.Length do + let char = n.[i] + if not (char >= '0' && char <= '9') then + res <- false + i <- i + 1 + if res then + ValueSome pos + else + ValueNone + +type NameArityPair = NameArityPair of string * int + +let DecodeGenericTypeName pos (mangledName: string) = + let res = mangledName.Substring(0, pos) + let num = mangledName.Substring(pos+1, mangledName.Length - pos - 1) + NameArityPair(res, int32 num) + +let DemangleGenericTypeNameWithPos pos (mangledName: string) = + mangledName.Substring(0, pos) + +let DemangleGenericTypeName (mangledName: string) = + match TryDemangleGenericNameAndPos mangledName with + | ValueSome pos -> DemangleGenericTypeNameWithPos pos mangledName + | _ -> mangledName + +let private chopStringTo (s: string) (c: char) = + match s.IndexOf c with + | -1 -> s + | idx -> + let i = idx + 1 + s.Substring(i, s.Length - i) + +/// Try to chop "get_" or "set_" from a string +let TryChopPropertyName (s: string) = + // extract the logical name from any mangled name produced by MakeMemberDataAndMangledNameForMemberVal + if s.Length <= 4 then None else + if s.StartsWithOrdinal("get_") || + s.StartsWithOrdinal("set_") + then Some (s.Substring(4, s.Length - 4)) + else + let s = chopStringTo s '.' + if s.StartsWithOrdinal("get_") || + s.StartsWithOrdinal("set_") + then Some (s.Substring(4, s.Length - 4)) + else None + +/// Try to chop "get_" or "set_" from a string. +/// If the string does not start with "get_" or "set_", this function raises an exception. +let ChopPropertyName s = + match TryChopPropertyName s with + | None -> + failwithf "Invalid internal property name: '%s'" s + | Some res -> res + +let SplitNamesForILPath (s : string) : string list = + if s.StartsWithOrdinal("``") && s.EndsWithOrdinal("``") && s.Length > 4 then [s.Substring(2, s.Length-4)] // identifier is enclosed in `` .. ``, so it is only a single element (this is very approximate) + else s.Split [| '.' ; '`' |] |> Array.toList // '.' chops members / namespaces / modules; '`' chops generic parameters for .NET types - /// Return a string array delimited by the given separator. - /// Note that a quoted string is not going to be mangled into pieces. - let inline private isNotQuotedQuotation (text: string) n = n > 0 && text.[n-1] <> '\\' - let private splitAroundQuotation (text: string) (separator: char) = - let length = text.Length - let result = ResizeArray() - let mutable insideQuotation = false - let mutable start = 0 - for i = 0 to length - 1 do - match text.[i], insideQuotation with - // split when seeing a separator - | c, false when c = separator -> - result.Add(text.Substring(start, i - start)) - insideQuotation <- false - start <- i + 1 - | _, _ when i = length - 1 -> - result.Add(text.Substring(start, i - start + 1)) - // keep reading if a separator is inside quotation - | c, true when c = separator -> - insideQuotation <- true - // open or close quotation - | '\"', _ when isNotQuotedQuotation text i -> - insideQuotation <- not insideQuotation - // keep reading - | _ -> () - - result.ToArray() - - /// Return a string array delimited by the given separator up to the maximum number. - /// Note that a quoted string is not going to be mangled into pieces. - let private splitAroundQuotationWithCount (text: string) (separator: char) (count: int)= - if count <= 1 then [| text |] else - let mangledText = splitAroundQuotation text separator - match mangledText.Length > count with - | true -> Array.append (mangledText.[0..(count-2)]) ([| mangledText.[(count-1)..] |> String.concat (Char.ToString separator) |]) - | false -> mangledText - - let [] FSharpModuleSuffix = "Module" - - let [] MangledGlobalName = "`global`" - - let IllegalCharactersInTypeAndNamespaceNames = [| '.'; '+'; '$'; '&'; '['; ']'; '/'; '\\'; '*'; '\"'; '`' |] - - /// Determines if the specified name is a valid name for an active pattern. - let IsActivePatternName (nm: string) = - let nameLen = nm.Length - // The name must start and end with '|' - (nm.IndexOf '|' = 0) && - (nm.LastIndexOf '|' = nameLen - 1) && - // The name must contain at least one character between the starting and ending delimiters. - nameLen >= 3 && - ( - let core = nm.Substring(1, nameLen - 2) - // no operator characters except '|' and ' ' - core |> String.forall (fun c -> c = '|' || c = ' ' || not (opCharSet.Contains c)) && - // at least one non-operator or space character - core |> String.exists (fun c -> c = ' ' || not (opCharSet.Contains c)) - ) - - //IsActivePatternName "|+|" = false - //IsActivePatternName "|ABC|" = true - //IsActivePatternName "|ABC|DEF|" = true - //IsActivePatternName "|||" = false - //IsActivePatternName "||S|" = true - - type ActivePatternInfo = - | APInfo of bool * (string * Range.range) list * Range.range - - member x.IsTotal = let (APInfo(p, _, _)) = x in p - - member x.ActiveTags = let (APInfo(_, tags, _)) = x in List.map fst tags - - member x.ActiveTagsWithRanges = let (APInfo(_, tags, _)) = x in tags - - member x.Range = let (APInfo(_, _, m)) = x in m - - let ActivePatternInfoOfValName nm (m: Range.range) = - // Note: The approximate range calculations in this code assume the name is of the form "(|A|B|)" not "(| A | B |)" - // The ranges are used for IDE refactoring support etc. If names of the second type are used, - // renaming may be inaccurate/buggy. However names of the first form are dominant in F# code. - let rec loop (nm: string) (mp: Range.range) = - let n = nm.IndexOf '|' - if n > 0 then - let m1 = Range.mkRange mp.FileName mp.Start (Range.mkPos mp.StartLine (mp.StartColumn + n)) - let m2 = Range.mkRange mp.FileName (Range.mkPos mp.StartLine (mp.StartColumn + n + 1)) mp.End - (nm.[0..n-1], m1) :: loop nm.[n+1..] m2 - else - let m1 = Range.mkRange mp.FileName mp.Start (Range.mkPos mp.StartLine (mp.StartColumn + nm.Length)) - [(nm, m1)] - let nm = DecompileOpName nm - if IsActivePatternName nm then - // Skip the '|' at each end when recovering ranges - let m0 = Range.mkRange m.FileName (Range.mkPos m.StartLine (m.StartColumn + 1)) (Range.mkPos m.EndLine (m.EndColumn - 1)) - let names = loop nm.[1..nm.Length-2] m0 - let resH, resT = List.frontAndBack names - Some(if fst resT = "_" then APInfo(false, resH, m) else APInfo(true, names, m)) - else - None +/// Return a string array delimited by the given separator. +/// Note that a quoted string is not going to be mangled into pieces. +let inline private isNotQuotedQuotation (text: string) n = n > 0 && text.[n-1] <> '\\' + +let private splitAroundQuotation (text: string) (separator: char) = + let length = text.Length + let result = ResizeArray() + let mutable insideQuotation = false + let mutable start = 0 + for i = 0 to length - 1 do + match text.[i], insideQuotation with + // split when seeing a separator + | c, false when c = separator -> + result.Add(text.Substring(start, i - start)) + insideQuotation <- false + start <- i + 1 + | _, _ when i = length - 1 -> + result.Add(text.Substring(start, i - start + 1)) + // keep reading if a separator is inside quotation + | c, true when c = separator -> + insideQuotation <- true + // open or close quotation + | '\"', _ when isNotQuotedQuotation text i -> + insideQuotation <- not insideQuotation + // keep reading + | _ -> () + + result.ToArray() + +/// Return a string array delimited by the given separator up to the maximum number. +/// Note that a quoted string is not going to be mangled into pieces. +let private splitAroundQuotationWithCount (text: string) (separator: char) (count: int)= + if count <= 1 then [| text |] else + let mangledText = splitAroundQuotation text separator + match mangledText.Length > count with + | true -> Array.append (mangledText.[0..(count-2)]) ([| mangledText.[(count-1)..] |> String.concat (Char.ToString separator) |]) + | false -> mangledText + +let [] FSharpModuleSuffix = "Module" + +let [] MangledGlobalName = "`global`" - let private mangleStaticStringArg (nm: string, v: string) = - nm + "=" + "\"" + v.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"" - - let private tryDemangleStaticStringArg (mangledText: string) = - match splitAroundQuotationWithCount mangledText '=' 2 with - | [| nm; v |] -> - if v.Length >= 2 then - Some(nm, v.[1..v.Length-2].Replace("\\\\", "\\").Replace("\\\"", "\"")) +let IllegalCharactersInTypeAndNamespaceNames = [| '.'; '+'; '$'; '&'; '['; ']'; '/'; '\\'; '*'; '\"'; '`' |] + +/// Determines if the specified name is a valid name for an active pattern. +let IsActivePatternName (name: string) = + // The name must contain at least one character between the starting and ending delimiters. + let nameLen = name.Length + if nameLen < 3 || name.[0] <> '|' || name.[nameLen - 1] <> '|' then + false + else + let rec isCoreActivePatternName (name: string) idx seenNonOpChar = + if idx = name.Length - 1 then + seenNonOpChar else - Some(nm, v) - | _ -> None - - exception InvalidMangledStaticArg of string - - /// Demangle the static parameters - let demangleProvidedTypeName (typeLogicalName: string) = - if typeLogicalName.Contains "," then - let pieces = splitAroundQuotation typeLogicalName ',' - match pieces with - | [| x; "" |] -> x, [| |] - | _ -> - let argNamesAndValues = pieces.[1..] |> Array.choose tryDemangleStaticStringArg - if argNamesAndValues.Length = (pieces.Length - 1) then - pieces.[0], argNamesAndValues + let c = name.[idx] + if opCharSet.Contains(c) && c <> '|' && c <> ' ' then + false else - typeLogicalName, [| |] - else - typeLogicalName, [| |] - - /// Mangle the static parameters for a provided type or method - let mangleProvidedTypeName (typeLogicalName, nonDefaultArgs) = - let nonDefaultArgsText = - nonDefaultArgs - |> Array.map mangleStaticStringArg - |> String.concat "," - - if nonDefaultArgsText = "" then - typeLogicalName + isCoreActivePatternName name (idx + 1) (seenNonOpChar || c <> '|') + + isCoreActivePatternName name 1 false + +type ActivePatternInfo = + | APInfo of bool * (string * Range.range) list * Range.range + + member x.IsTotal = let (APInfo(p, _, _)) = x in p + + member x.ActiveTags = let (APInfo(_, tags, _)) = x in List.map fst tags + + member x.ActiveTagsWithRanges = let (APInfo(_, tags, _)) = x in tags + + member x.Range = let (APInfo(_, _, m)) = x in m + +let ActivePatternInfoOfValName nm (m: Range.range) = + // Note: The approximate range calculations in this code assume the name is of the form "(|A|B|)" not "(| A | B |)" + // The ranges are used for IDE refactoring support etc. If names of the second type are used, + // renaming may be inaccurate/buggy. However names of the first form are dominant in F# code. + let rec loop (nm: string) (mp: Range.range) = + let n = nm.IndexOf '|' + if n > 0 then + let m1 = Range.mkRange mp.FileName mp.Start (Range.mkPos mp.StartLine (mp.StartColumn + n)) + let m2 = Range.mkRange mp.FileName (Range.mkPos mp.StartLine (mp.StartColumn + n + 1)) mp.End + (nm.[0..n-1], m1) :: loop nm.[n+1..] m2 else - typeLogicalName + "," + nonDefaultArgsText - - - /// Mangle the static parameters for a provided type or method - let computeMangledNameWithoutDefaultArgValues(nm, staticArgs, defaultArgValues) = - let nonDefaultArgs = - (staticArgs, defaultArgValues) - ||> Array.zip - |> Array.choose (fun (staticArg, (defaultArgName, defaultArgValue)) -> - let actualArgValue = string staticArg - match defaultArgValue with - | Some v when v = actualArgValue -> None - | _ -> Some (defaultArgName, actualArgValue)) - mangleProvidedTypeName (nm, nonDefaultArgs) - - let outArgCompilerGeneratedName = "outArg" \ No newline at end of file + let m1 = Range.mkRange mp.FileName mp.Start (Range.mkPos mp.StartLine (mp.StartColumn + nm.Length)) + [(nm, m1)] + let nm = DecompileOpName nm + if IsActivePatternName nm then + // Skip the '|' at each end when recovering ranges + let m0 = Range.mkRange m.FileName (Range.mkPos m.StartLine (m.StartColumn + 1)) (Range.mkPos m.EndLine (m.EndColumn - 1)) + let names = loop nm.[1..nm.Length-2] m0 + let resH, resT = List.frontAndBack names + Some(if fst resT = "_" then APInfo(false, resH, m) else APInfo(true, names, m)) + else + None + +let private mangleStaticStringArg (nm: string, v: string) = + nm + "=" + "\"" + v.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"" + +let private tryDemangleStaticStringArg (mangledText: string) = + match splitAroundQuotationWithCount mangledText '=' 2 with + | [| nm; v |] -> + if v.Length >= 2 then + Some(nm, v.[1..v.Length-2].Replace("\\\\", "\\").Replace("\\\"", "\"")) + else + Some(nm, v) + | _ -> None + +exception InvalidMangledStaticArg of string + +/// Demangle the static parameters +let demangleProvidedTypeName (typeLogicalName: string) = + if typeLogicalName.Contains "," then + let pieces = splitAroundQuotation typeLogicalName ',' + match pieces with + | [| x; "" |] -> x, [| |] + | _ -> + let argNamesAndValues = pieces.[1..] |> Array.choose tryDemangleStaticStringArg + if argNamesAndValues.Length = (pieces.Length - 1) then + pieces.[0], argNamesAndValues + else + typeLogicalName, [| |] + else + typeLogicalName, [| |] + +/// Mangle the static parameters for a provided type or method +let mangleProvidedTypeName (typeLogicalName, nonDefaultArgs) = + let nonDefaultArgsText = + nonDefaultArgs + |> Array.map mangleStaticStringArg + |> String.concat "," + + if nonDefaultArgsText = "" then + typeLogicalName + else + typeLogicalName + "," + nonDefaultArgsText + + +/// Mangle the static parameters for a provided type or method +let computeMangledNameWithoutDefaultArgValues(nm, staticArgs, defaultArgValues) = + let nonDefaultArgs = + (staticArgs, defaultArgValues) + ||> Array.zip + |> Array.choose (fun (staticArg, (defaultArgName, defaultArgValue)) -> + let actualArgValue = string staticArg + match defaultArgValue with + | Some v when v = actualArgValue -> None + | _ -> Some (defaultArgName, actualArgValue)) + mangleProvidedTypeName (nm, nonDefaultArgs) + +let outArgCompilerGeneratedName = "outArg" + + +/// Reuses generated union case field name objects for common field numbers +let mkUnionCaseFieldName = + let names = + [| 1 .. 10 |] + |> Array.map (fun i -> "Item" + string i) + + fun nFields i -> + match nFields with + | 0 | 1 -> "Item" + | _ -> if i < 10 then names.[i] else "Item" + string (i + 1) + +/// Reuses generated exception field name objects for common field numbers +let mkExceptionFieldName = + let names = + [| 0 .. 9 |] + |> Array.map (fun i -> "Data" + string i) + + fun i -> + if i < 10 then names.[i] else "Data" + string i + +/// The prefix of the names used for the fake namespace path added to all dynamic code entries in FSI.EXE +let FsiDynamicModulePrefix = "FSI_" + +[] +module FSharpLib = + let Root = "Microsoft.FSharp" + let RootPath = IL.splitNamespace Root + let Core = Root + ".Core" + let CorePath = IL.splitNamespace Core + +[] +module CustomOperations = + [] + let Into = "into" + +let unassignedTyparName = "?" + +//-------------------------------------------------------------------------- +// Resource format for pickled data +//-------------------------------------------------------------------------- + +let FSharpOptimizationDataResourceName = "FSharpOptimizationData." +let FSharpSignatureDataResourceName = "FSharpSignatureData." +// For historical reasons, we use a different resource name for FSharp.Core, so older F# compilers +// don't complain when they see the resource. The prefix of these names must not be 'FSharpOptimizationData' +// or 'FSharpSignatureData' +let FSharpOptimizationDataResourceName2 = "FSharpOptimizationInfo." +let FSharpSignatureDataResourceName2 = "FSharpSignatureInfo." + diff --git a/src/fcs-fable/src/fsharp/QueueList.fs b/src/fcs-fable/src/fsharp/QueueList.fs old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/fsharp/QuotationPickler.fs b/src/fcs-fable/src/fsharp/QuotationPickler.fs old mode 100755 new mode 100644 index df71827809..0929b14f6c --- a/src/fcs-fable/src/fsharp/QuotationPickler.fs +++ b/src/fcs-fable/src/fsharp/QuotationPickler.fs @@ -5,7 +5,6 @@ module internal FSharp.Compiler.QuotationPickler open System.Text open Internal.Utilities.Collections open FSharp.Compiler.AbstractIL.Internal -open FSharp.Compiler open FSharp.Compiler.Lib let mkRLinear mk (vs, body) = List.foldBack (fun v acc -> mk (v, acc)) vs body @@ -46,8 +45,6 @@ type VarData = vType: TypeData vMutable: bool } -type FieldData = NamedTypeData * string -type RecdFieldData = NamedTypeData * string type PropInfoData = NamedTypeData * string * TypeData * TypeData list type CombOp = @@ -142,19 +139,19 @@ let mkLetRecCombRaw args = CombExpr(LetRecCombOp, [], args) let mkLetRec (ves, body) = let vs, es = List.unzip ves - mkLetRecRaw(mkRLinear mkLambda (vs, mkLetRecCombRaw (body::es))) + mkLetRecRaw(mkRLinear mkLambda (vs, mkLetRecCombRaw (body :: es))) let mkRecdMk (n, tys, args) = CombExpr(RecdMkOp n, tys, args) -let mkRecdGet ((d1, d2), tyargs, args) = CombExpr(RecdGetOp(d1, d2), tyargs, args) +let mkRecdGet (d1, d2, tyargs, args) = CombExpr(RecdGetOp(d1, d2), tyargs, args) -let mkRecdSet ((d1, d2), tyargs, args) = CombExpr(RecdSetOp(d1, d2), tyargs, args) +let mkRecdSet (d1, d2, tyargs, args) = CombExpr(RecdSetOp(d1, d2), tyargs, args) -let mkUnion ((d1, d2), tyargs, args) = CombExpr(SumMkOp(d1, d2), tyargs, args) +let mkUnion (d1, d2, tyargs, args) = CombExpr(SumMkOp(d1, d2), tyargs, args) -let mkUnionFieldGet ((d1, d2, d3), tyargs, arg) = CombExpr(SumFieldGetOp(d1, d2, d3), tyargs, [arg]) +let mkUnionFieldGet (d1, d2, d3, tyargs, arg) = CombExpr(SumFieldGetOp(d1, d2, d3), tyargs, [arg]) -let mkUnionCaseTagTest ((d1, d2), tyargs, arg) = CombExpr(SumTagTestOp(d1, d2), tyargs, [arg]) +let mkUnionCaseTagTest (d1, d2, tyargs, arg) = CombExpr(SumTagTestOp(d1, d2), tyargs, [arg]) let mkTupleGet (ty, n, e) = CombExpr(TupleGetOp n, [ty], [e]) @@ -216,9 +213,9 @@ let mkPropGet (d, tyargs, args) = CombExpr(PropGetOp(d), tyargs, args) let mkPropSet (d, tyargs, args) = CombExpr(PropSetOp(d), tyargs, args) -let mkFieldGet ((d1, d2), tyargs, args) = CombExpr(FieldGetOp(d1, d2), tyargs, args) +let mkFieldGet (d1, d2, tyargs, args) = CombExpr(FieldGetOp(d1, d2), tyargs, args) -let mkFieldSet ((d1, d2), tyargs, args) = CombExpr(FieldSetOp(d1, d2), tyargs, args) +let mkFieldSet (d1, d2, tyargs, args) = CombExpr(FieldSetOp(d1, d2), tyargs, args) let mkCtorCall (d, tyargs, args) = CombExpr(CtorCallOp(d), tyargs, args) @@ -410,7 +407,11 @@ let p_PropInfoData a st = let p_CombOp x st = match x with | CondOp -> p_byte 0 st - | ModuleValueOp (x, y, z) -> p_byte 1 st; p_tup3 p_NamedType p_string p_bool (x, y, z) st + | ModuleValueOp (x, y, z) -> + p_byte 1 st + p_NamedType x st + p_string y st + p_bool z st | LetRecOp -> p_byte 2 st | RecdMkOp a -> p_byte 3 st; p_NamedType a st | RecdGetOp (x, y) -> p_byte 4 st; p_recdFieldSpec (x, y) st diff --git a/src/fcs-fable/src/fsharp/QuotationPickler.fsi b/src/fcs-fable/src/fsharp/QuotationPickler.fsi old mode 100755 new mode 100644 index ffe2321588..f5a408e7d6 --- a/src/fcs-fable/src/fsharp/QuotationPickler.fsi +++ b/src/fcs-fable/src/fsharp/QuotationPickler.fsi @@ -51,8 +51,6 @@ type MethodBaseData = | Method of MethodData | Ctor of CtorData -type FieldData = NamedTypeData * string -type RecdFieldData = NamedTypeData * string type PropInfoData = NamedTypeData * string * TypeData * TypeData list val mkVar : int -> ExprData @@ -67,11 +65,11 @@ val mkModuleValueApp : NamedTypeData * string * bool * TypeData list * ExprData val mkLetRec : (VarData * ExprData) list * ExprData -> ExprData val mkLet : (VarData * ExprData) * ExprData -> ExprData val mkRecdMk : NamedTypeData * TypeData list * ExprData list -> ExprData -val mkRecdGet : RecdFieldData * TypeData list * ExprData list -> ExprData -val mkRecdSet : RecdFieldData * TypeData list * ExprData list -> ExprData -val mkUnion : (NamedTypeData * string) * TypeData list * ExprData list -> ExprData -val mkUnionFieldGet : (NamedTypeData * string * int) * TypeData list * ExprData -> ExprData -val mkUnionCaseTagTest : (NamedTypeData * string) * TypeData list * ExprData -> ExprData +val mkRecdGet : NamedTypeData * string * TypeData list * ExprData list -> ExprData +val mkRecdSet : NamedTypeData * string * TypeData list * ExprData list -> ExprData +val mkUnion : NamedTypeData * string * TypeData list * ExprData list -> ExprData +val mkUnionFieldGet : NamedTypeData * string * int * TypeData list * ExprData -> ExprData +val mkUnionCaseTagTest : NamedTypeData * string * TypeData list * ExprData -> ExprData val mkTuple : TypeData * ExprData list -> ExprData val mkTupleGet : TypeData * int * ExprData -> ExprData val mkCoerce : TypeData * ExprData -> ExprData @@ -104,8 +102,8 @@ val mkTryWith : ExprData * VarData * ExprData * VarData * ExprData -> ExprData val mkDelegate : TypeData * ExprData -> ExprData val mkPropGet : PropInfoData * TypeData list * ExprData list -> ExprData val mkPropSet : PropInfoData * TypeData list * ExprData list -> ExprData -val mkFieldGet : FieldData * TypeData list * ExprData list -> ExprData -val mkFieldSet : FieldData * TypeData list * ExprData list -> ExprData +val mkFieldGet : NamedTypeData * string * TypeData list * ExprData list -> ExprData +val mkFieldSet : NamedTypeData * string * TypeData list * ExprData list -> ExprData val mkCtorCall : CtorData * TypeData list * ExprData list -> ExprData val mkMethodCall : MethodData * TypeData list * ExprData list -> ExprData val mkAttributedExpression : ExprData * ExprData -> ExprData diff --git a/src/fcs-fable/src/fsharp/QuotationTranslator.fs b/src/fcs-fable/src/fsharp/QuotationTranslator.fs old mode 100755 new mode 100644 index 5cdafc871f..94072f6b49 --- a/src/fcs-fable/src/fsharp/QuotationTranslator.fs +++ b/src/fcs-fable/src/fsharp/QuotationTranslator.fs @@ -7,14 +7,16 @@ open FSharp.Compiler open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Diagnostics -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.CompilerGlobalState +open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Lib -open FSharp.Compiler.Ast open FSharp.Compiler.PrettyNaming -open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.TcGlobals open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.TcGlobals open System.Collections.Generic module QP = FSharp.Compiler.QuotationPickler @@ -44,7 +46,7 @@ type QuotationGenerationScope = referencedTypeDefs: ResizeArray referencedTypeDefsTable: Dictionary // Accumulate the type splices (i.e. captured type parameters) into here - typeSplices: ResizeArray + typeSplices: ResizeArray // Accumulate the expression splices into here exprSplices: ResizeArray isReflectedDefinition : IsReflectedDefinition @@ -135,11 +137,11 @@ 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 -> + | Expr.App ((InnerExprPat(Expr.Val (vref, vFlags, _) as f)), fty, tyargs, actualArgs, _m) when vref.IsMemberOrModuleBinding -> Some(vref, vFlags, f, fty, tyargs, actualArgs @ args) - | Expr.App(f, _fty, [], actualArgs, _) -> + | Expr.App (f, _fty, [], actualArgs, _) -> loop f (actualArgs @ args) - | (Expr.Val(vref, vFlags, _m) as f) when (match vref.DeclaringEntity with ParentNone -> false | _ -> true) -> + | (Expr.Val (vref, vFlags, _m) as f) when (match vref.DeclaringEntity with ParentNone -> false | _ -> true) -> let fty = tyOfExpr g f Some(vref, vFlags, f, fty, [], args) | _ -> @@ -148,14 +150,14 @@ let (|ModuleValueOrMemberUse|_|) g 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 () + | Expr.Op (TOp.ILAsm ([AI_sub], _), _, [Expr.Op (TOp.ILAsm ([I_ldlen; AI_conv ILBasicType.DT_I4], _), _, _, _); Expr.Const (Const.Int32 1, _, _) ], _) -> Some () | _ -> None let (|SimpleArrayLoopBody|_|) g expr = match expr with - | Expr.Lambda(_, a, b, ([_] as args), Expr.Let(TBind(forVarLoop, 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) + | Expr.Lambda (_, a, b, ([_] as args), Expr.Let (TBind(forVarLoop, 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 @@ -167,9 +169,9 @@ let (|ObjectInitializationCheck|_|) g expr = _, _, TDSwitch ( - Expr.Op(TOp.ILAsm([AI_clt], _), _, [Expr.Op(TOp.ValFieldGet((RFRef(_, name))), _, [Expr.Val(selfRef, NormalValUse, _)], _); Expr.Const(Const.Int32 1, _, _)], _), _, _, _ + Expr.Op (TOp.ILAsm ([AI_clt], _), _, [Expr.Op (TOp.ValFieldGet ((RecdFieldRef(_, name))), _, [Expr.Val (selfRef, NormalValUse, _)], _); Expr.Const (Const.Int32 1, _, _)], _), _, _, _ ), - [| TTarget([], Expr.App(Expr.Val(failInitRef, _, _), _, _, _, _), _); _ |], _, resultTy + [| TTarget([], Expr.App (Expr.Val (failInitRef, _, _), _, _, _, _), _); _ |], _, resultTy ) when IsCompilerGeneratedName name && name.StartsWithOrdinal("init") && @@ -225,7 +227,7 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. // Recognize applications of module functions. match expr with // Detect expression tree exprSplices - | Expr.App(InnerExprPat(Expr.Val(vf, _, _)), _, _, x0::rest, m) + | Expr.App (InnerExprPat(Expr.Val (vf, _, _)), _, _, x0 :: rest, m) when isSplice cenv.g vf -> let idx = cenv.exprSplices.Count let ty = tyOfExpr cenv.g expr @@ -263,7 +265,7 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. let objArgs, curriedArgs = match takesInstanceArg, curriedArgs with | false, curriedArgs -> [], curriedArgs - | true, (objArg::curriedArgs) -> [objArg], curriedArgs + | true, (objArg :: curriedArgs) -> [objArg], curriedArgs | true, [] -> wfail(InternalError("warning: unexpected missing object argument when generating quotation for call to F# object member " + vref.LogicalName, m)) if verboseCReflect then @@ -309,7 +311,7 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. if isMember then // This is an application of a member method // We only count one argument block for these. - let callArgs = (objArgs::untupledCurriedArgs) |> List.concat + let callArgs = (objArgs :: untupledCurriedArgs) |> List.concat let parentTyconR = ConvTyconRef cenv vref.TopValDeclaringEntity m let isNewObj = isNewObj || valUseFlags || isSelfInit @@ -318,7 +320,7 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. let argTys = curriedArgInfos |> List.concat |> List.map fst let methArgTypesR = ConvTypes cenv envinner m argTys let methRetTypeR = ConvReturnType cenv envinner m retTy - let methName = vref.CompiledName + let methName = vref.CompiledName cenv.g.CompilerGlobalState let numGenericArgs = tyargs.Length - numEnclTypeArgs ConvObjectModelCall cenv env m (isPropGet, isPropSet, isNewObj, parentTyconR, methArgTypesR, methRetTypeR, methName, tyargs, numGenericArgs, callArgs) else @@ -330,11 +332,11 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. // we got here if quotation is represents a call with unit argument // let f () = () // <@ f @> // => (\arg -> f arg) => arg is Expr.Val - no-effects, first case - // <@ f() @> // Expr.Const(Unit) - no-effects - first case + // <@ f() @> // Expr.Const (Unit) - no-effects - first case // <@ f (someFunctionThatReturnsUnit) @> - potential effects - second case match arg with | Expr.Val _ - | Expr.Const(Const.Unit, _, _) -> subCall + | Expr.Const (Const.Unit, _, _) -> subCall | _ -> let argQ = ConvExpr cenv env arg QP.mkSequential(argQ, subCall) @@ -344,33 +346,33 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. // Blast type application nodes and expression application nodes apart so values are left with just their type arguments - | Expr.App(f, fty, (_ :: _ as tyargs), (_ :: _ as args), m) -> + | Expr.App (f, fty, (_ :: _ as tyargs), (_ :: _ as args), m) -> let rfty = applyForallTy cenv.g fty tyargs ConvExpr cenv env (primMkApp (primMkApp (f, fty) tyargs [] m, rfty) [] args m) // Uses of possibly-polymorphic values - | Expr.App(InnerExprPat(Expr.Val(vref, _vFlags, m)), _fty, tyargs, [], _) -> + | Expr.App (InnerExprPat(Expr.Val (vref, _vFlags, m)), _fty, tyargs, [], _) -> ConvValRef true cenv env m vref tyargs // Simple applications - | Expr.App(f, _fty, tyargs, args, m) -> + | Expr.App (f, _fty, tyargs, args, m) -> if not (List.isEmpty tyargs) then wfail(Error(FSComp.SR.crefQuotationsCantContainGenericExprs(), m)) List.fold (fun fR arg -> QP.mkApp (fR, ConvExpr cenv env arg)) (ConvExpr cenv env f) args // REVIEW: what is the quotation view of literals accessing enumerations? Currently they show up as integers. - | Expr.Const(c, m, ty) -> + | Expr.Const (c, m, ty) -> ConvConst cenv env m c ty - | Expr.Val(vref, _vFlags, m) -> + | Expr.Val (vref, _vFlags, m) -> ConvValRef true cenv env m vref [] - | Expr.Let(bind, body, _, _) -> + | Expr.Let (bind, body, _, _) -> // The binding may be a compiler-generated binding that gets removed in the quotation presentation match ConvLetBind cenv env bind with | None, env -> ConvExpr cenv env body | Some(bindR), env -> QP.mkLet(bindR, ConvExpr cenv env body) - | Expr.LetRec(binds, body, _, _) -> + | Expr.LetRec (binds, body, _, _) -> let vs = valsOfBinds binds let vsR = vs |> List.map (ConvVal cenv env) let env = BindFlatVals env vs @@ -378,13 +380,13 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. let bindsR = List.zip vsR (binds |> List.map (fun b -> ConvExpr cenv env b.Expr)) QP.mkLetRec(bindsR, bodyR) - | Expr.Lambda(_, _, _, vs, b, _, _) -> + | Expr.Lambda (_, _, _, vs, b, _, _) -> let v, b = MultiLambdaToTupledLambda cenv.g vs b let vR = ConvVal cenv env v let bR = ConvExpr cenv (BindVal env v) b QP.mkLambda(vR, bR) - | Expr.Quote(ast, _, _, _, ety) -> + | Expr.Quote (ast, _, _, _, ety) -> // F# 2.0-3.1 had a bug with nested 'raw' quotations. F# 4.0 + FSharp.Core 4.4.0.0+ allows us to do the right thing. if cenv.quotationFormat = QuotationSerializationFormat.FSharp_40_Plus && // Look for a 'raw' quotation @@ -402,7 +404,7 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. ConvDecisionTree cenv env tgs typR dtree // initialization check - | Expr.Sequential(ObjectInitializationCheck cenv.g, x1, NormalSeq, _, _) -> ConvExpr cenv env x1 + | Expr.Sequential (ObjectInitializationCheck cenv.g, x1, NormalSeq, _, _) -> ConvExpr cenv env x1 | Expr.Sequential (x0, x1, NormalSeq, _, _) -> QP.mkSequential(ConvExpr cenv env x0, ConvExpr cenv env x1) | Expr.Obj (_, ty, _, _, [TObjExprMethod(TSlotSig(_, ctyp, _, _, _, _), _, tps, [tmvs], e, _) as tmethod], _, m) when isDelegateTy cenv.g ty -> let f = mkLambdas m tps tmvs (e, GetFSharpViewOfReturnType cenv.g (returnTyOfMethod cenv.g tmethod)) @@ -415,19 +417,19 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. | Expr.Sequential (x0, x1, ThenDoSeq, _, _) -> QP.mkSequential(ConvExpr cenv env x0, ConvExpr cenv env x1) | Expr.Obj (_lambdaId, _typ, _basev, _basecall, _overrides, _iimpls, m) -> wfail(Error(FSComp.SR.crefQuotationsCantContainObjExprs(), m)) - | Expr.Op(op, tyargs, args, m) -> + | Expr.Op (op, tyargs, args, m) -> match op, tyargs, args with | TOp.UnionCase ucref, _, _ -> - let mkR = ConvUnionCaseRef cenv ucref m + let tcR, s = ConvUnionCaseRef cenv ucref m let tyargsR = ConvTypes cenv env m tyargs let argsR = ConvExprs cenv env args - QP.mkUnion(mkR, tyargsR, argsR) + QP.mkUnion(tcR, s, tyargsR, argsR) | TOp.Tuple tupInfo, tyargs, _ -> let tyR = ConvType cenv env m (mkAnyTupledTy cenv.g tupInfo tyargs) let argsR = ConvExprs cenv env args - QP.mkTuple(tyR, argsR) // TODO: propagate to quotations + QP.mkTuple(tyR, argsR) | TOp.Recd (_, tcref), _, _ -> let rgtypR = ConvTyconRef cenv tcref m @@ -447,50 +449,50 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. let rgtypR = ConvILTypeRef cenv tref let tyargsR = ConvTypes cenv env m tyargs let argsR = ConvExprs cenv env args - QP.mkRecdGet((rgtypR, anonInfo.SortedNames.[n]), tyargsR, argsR) + QP.mkRecdGet(rgtypR, anonInfo.SortedNames.[n], tyargsR, argsR) | TOp.UnionCaseFieldGet (ucref, n), tyargs, [e] -> ConvUnionFieldGet cenv env m ucref n tyargs e - | TOp.ValFieldGetAddr(_rfref, _readonly), _tyargs, _ -> + | TOp.ValFieldGetAddr (_rfref, _readonly), _tyargs, _ -> wfail(Error(FSComp.SR.crefQuotationsCantContainAddressOf(), m)) | TOp.UnionCaseFieldGetAddr _, _tyargs, _ -> wfail(Error(FSComp.SR.crefQuotationsCantContainAddressOf(), m)) - | TOp.ValFieldGet(_rfref), _tyargs, [] -> + | TOp.ValFieldGet (_rfref), _tyargs, [] -> wfail(Error(FSComp.SR.crefQuotationsCantContainStaticFieldRef(), m)) - | TOp.ValFieldGet(rfref), tyargs, args -> + | TOp.ValFieldGet (rfref), tyargs, args -> ConvClassOrRecdFieldGet cenv env m rfref tyargs args - | TOp.TupleFieldGet(tupInfo, n), tyargs, [e] -> + | TOp.TupleFieldGet (tupInfo, n), tyargs, [e] -> let eR = ConvLValueExpr cenv env e let tyR = ConvType cenv env m (mkAnyTupledTy cenv.g tupInfo tyargs) QP.mkTupleGet(tyR, n, eR) - | TOp.ILAsm(([ I_ldfld(_, _, fspec) ] - | [ I_ldfld(_, _, fspec); AI_nop ] + | TOp.ILAsm (([ I_ldfld (_, _, fspec) ] + | [ I_ldfld (_, _, fspec); AI_nop ] | [ I_ldsfld (_, fspec) ] | [ I_ldsfld (_, fspec); AI_nop ]), _), enclTypeArgs, args -> ConvLdfld cenv env m fspec enclTypeArgs args - | TOp.ILAsm([ I_stfld(_, _, fspec) | I_stsfld (_, fspec) ], _), enclTypeArgs, args -> + | TOp.ILAsm ([ I_stfld (_, _, fspec) | I_stsfld (_, fspec) ], _), enclTypeArgs, args -> let tyargsR = ConvTypes cenv env m enclTypeArgs let parentTyconR = ConvILTypeRefUnadjusted cenv m fspec.DeclaringTypeRef let argsR = ConvLValueArgs cenv env args - QP.mkFieldSet( (parentTyconR, fspec.Name), tyargsR, argsR) + QP.mkFieldSet(parentTyconR, fspec.Name, tyargsR, argsR) - | TOp.ILAsm([ AI_ceq ], _), _, [arg1;arg2] -> + | TOp.ILAsm ([ AI_ceq ], _), _, [arg1;arg2] -> let ty = tyOfExpr cenv.g arg1 let eq = mkCallEqualsOperator cenv.g m ty arg1 arg2 ConvExpr cenv env eq - | TOp.ILAsm([ I_throw ], _), _, [arg1] -> + | TOp.ILAsm ([ I_throw ], _), _, [arg1] -> let raiseExpr = mkCallRaise cenv.g m (tyOfExpr cenv.g expr) arg1 ConvExpr cenv env raiseExpr - | TOp.ILAsm(_il, _), _, _ -> + | TOp.ILAsm (_il, _), _, _ -> wfail(Error(FSComp.SR.crefQuotationsCantContainInlineIL(), m)) | TOp.ExnConstr tcref, _, args -> @@ -510,21 +512,21 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. | TOp.ValFieldSet rfref, _tinst, args -> let argsR = ConvLValueArgs cenv env args let tyargsR = ConvTypes cenv env m tyargs - let ((_parentTyconR, fldOrPropName) as projR) = ConvRecdFieldRef cenv rfref m + let parentTyconR, fldOrPropName = ConvRecdFieldRef cenv rfref m if rfref.TyconRef.IsRecordTycon then - QP.mkRecdSet(projR, tyargsR, argsR) + QP.mkRecdSet(parentTyconR, fldOrPropName, tyargsR, argsR) else let fspec = rfref.RecdField let tcref = rfref.TyconRef let parentTyconR = ConvTyconRef cenv tcref m if useGenuineField tcref.Deref fspec then - QP.mkFieldSet( projR, tyargsR, argsR) + QP.mkFieldSet(parentTyconR, fldOrPropName, tyargsR, argsR) else let envinner = BindFormalTypars env (tcref.TyparsNoRange) let propRetTypeR = ConvType cenv envinner m fspec.FormalType QP.mkPropSet( (parentTyconR, fldOrPropName, propRetTypeR, []), tyargsR, argsR) - | TOp.ExnFieldGet(tcref, i), [], [obj] -> + | TOp.ExnFieldGet (tcref, i), [], [obj] -> let exnc = stripExnEqns tcref let fspec = exnc.TrueInstanceFieldsAsList.[i] let parentTyconR = ConvTyconRef cenv tcref m @@ -544,44 +546,44 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. // rebuild reraise() and Convert mkReraiseLibCall cenv.g toTy m |> ConvExpr cenv env - | TOp.LValueOp(LAddrOf _, vref), [], [] -> + | TOp.LValueOp (LAddrOf _, vref), [], [] -> QP.mkAddressOf(ConvValRef false cenv env m vref []) - | TOp.LValueOp(LByrefSet, vref), [], [e] -> + | TOp.LValueOp (LByrefSet, vref), [], [e] -> QP.mkAddressSet(ConvValRef false cenv env m vref [], ConvExpr cenv env e) - | TOp.LValueOp(LSet, vref), [], [e] -> + | TOp.LValueOp (LSet, vref), [], [e] -> // Sets of module values become property sets match vref.DeclaringEntity with | Parent tcref when IsCompiledAsStaticProperty cenv.g vref.Deref -> let parentTyconR = ConvTyconRef cenv tcref m - let propName = vref.CompiledName + let propName = vref.CompiledName cenv.g.CompilerGlobalState let propTy = ConvType cenv env m vref.Type QP.mkPropSet( (parentTyconR, propName, propTy, []), [], [ConvExpr cenv env e]) | _ -> QP.mkVarSet( ConvValRef false cenv env m vref [], ConvExpr cenv env e) - | TOp.LValueOp(LByrefGet, vref), [], [] -> + | TOp.LValueOp (LByrefGet, vref), [], [] -> ConvValRef false cenv env m vref [] | TOp.Array, [ty], xa -> QP.mkNewArray(ConvType cenv env m ty, ConvExprs cenv env xa) - | TOp.While _, [], [Expr.Lambda(_, _, _, [_], test, _, _);Expr.Lambda(_, _, _, [_], body, _, _)] -> + | TOp.While _, [], [Expr.Lambda (_, _, _, [_], test, _, _);Expr.Lambda (_, _, _, [_], body, _, _)] -> QP.mkWhileLoop(ConvExpr cenv env test, ConvExpr cenv env body) - | TOp.For(_, FSharpForLoopUp), [], [Expr.Lambda(_, _, _, [_], lim0, _, _); Expr.Lambda(_, _, _, [_], SimpleArrayLoopUpperBound, lm, _); SimpleArrayLoopBody cenv.g (arr, elemTy, body)] -> + | TOp.For (_, FSharpForLoopUp), [], [Expr.Lambda (_, _, _, [_], lim0, _, _); Expr.Lambda (_, _, _, [_], SimpleArrayLoopUpperBound, lm, _); SimpleArrayLoopBody cenv.g (arr, elemTy, body)] -> let lim1 = let len = mkCallArrayLength cenv.g lm elemTy arr // Array.length arr - mkCallSubtractionOperator cenv.g lm cenv.g.int32_ty len (Expr.Const(Const.Int32 1, m, cenv.g.int32_ty)) // len - 1 + mkCallSubtractionOperator cenv.g lm cenv.g.int32_ty len (Expr.Const (Const.Int32 1, m, cenv.g.int32_ty)) // len - 1 QP.mkForLoop(ConvExpr cenv env lim0, ConvExpr cenv env lim1, ConvExpr cenv env body) - | TOp.For(_, dir), [], [Expr.Lambda(_, _, _, [_], lim0, _, _);Expr.Lambda(_, _, _, [_], lim1, _, _);body] -> + | TOp.For (_, dir), [], [Expr.Lambda (_, _, _, [_], lim0, _, _);Expr.Lambda (_, _, _, [_], lim1, _, _);body] -> match dir with | FSharpForLoopUp -> QP.mkForLoop(ConvExpr cenv env lim0, ConvExpr cenv env lim1, ConvExpr cenv env body) | _ -> wfail(Error(FSComp.SR.crefQuotationsCantContainDescendingForLoops(), m)) - | TOp.ILCall(_, _, _, isNewObj, valUseFlags, isProp, _, ilMethRef, enclTypeArgs, methTypeArgs, _tys), [], callArgs -> + | TOp.ILCall (_, _, _, isNewObj, valUseFlags, isProp, _, ilMethRef, enclTypeArgs, methTypeArgs, _tys), [], callArgs -> let parentTyconR = ConvILTypeRefUnadjusted cenv m ilMethRef.DeclaringTypeRef let isNewObj = isNewObj || (match valUseFlags with CtorValUsedAsSuperInit | CtorValUsedAsSelfInit -> true | _ -> false) let methArgTypesR = List.map (ConvILType cenv env m) ilMethRef.ArgTypes @@ -592,10 +594,10 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. let tyargs = (enclTypeArgs@methTypeArgs) ConvObjectModelCall cenv env m (isPropGet, isPropSet, isNewObj, parentTyconR, methArgTypesR, methRetTypeR, methName, tyargs, methTypeArgs.Length, callArgs) - | TOp.TryFinally _, [_resty], [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [_], e2, _, _)] -> + | TOp.TryFinally _, [_resty], [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [_], e2, _, _)] -> QP.mkTryFinally(ConvExpr cenv env e1, ConvExpr cenv env e2) - | TOp.TryCatch _, [_resty], [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [vf], ef, _, _); Expr.Lambda(_, _, _, [vh], eh, _, _)] -> + | TOp.TryCatch _, [_resty], [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [vf], ef, _, _); Expr.Lambda (_, _, _, [vh], eh, _, _)] -> let vfR = ConvVal cenv env vf let envf = BindVal env vf let vhR = ConvVal cenv env vh @@ -603,17 +605,29 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. QP.mkTryWith(ConvExpr cenv env e1, vfR, ConvExpr cenv envf ef, vhR, ConvExpr cenv envh eh) | TOp.Bytes bytes, [], [] -> - ConvExpr cenv env (Expr.Op(TOp.Array, [cenv.g.byte_ty], List.ofArray (Array.map (mkByte cenv.g m) bytes), m)) + ConvExpr cenv env (Expr.Op (TOp.Array, [cenv.g.byte_ty], List.ofArray (Array.map (mkByte cenv.g m) bytes), m)) | TOp.UInt16s arr, [], [] -> - ConvExpr cenv env (Expr.Op(TOp.Array, [cenv.g.uint16_ty], List.ofArray (Array.map (mkUInt16 cenv.g m) arr), m)) - - | TOp.UnionCaseProof _, _, [e] -> ConvExpr cenv env e // Note: we erase the union case proof conversions when converting to quotations - | TOp.UnionCaseTagGet _tycr, _tinst, [_cx] -> wfail(Error(FSComp.SR.crefQuotationsCantFetchUnionIndexes(), m)) - | TOp.UnionCaseFieldSet (_c, _i), _tinst, [_cx;_x] -> wfail(Error(FSComp.SR.crefQuotationsCantSetUnionFields(), m)) - | TOp.ExnFieldSet(_tcref, _i), [], [_ex;_x] -> wfail(Error(FSComp.SR.crefQuotationsCantSetExceptionFields(), m)) - | TOp.RefAddrGet _, _, _ -> wfail(Error(FSComp.SR.crefQuotationsCantRequireByref(), m)) - | TOp.TraitCall (_ss), _, _ -> wfail(Error(FSComp.SR.crefQuotationsCantCallTraitMembers(), m)) + ConvExpr cenv env (Expr.Op (TOp.Array, [cenv.g.uint16_ty], List.ofArray (Array.map (mkUInt16 cenv.g m) arr), m)) + + | TOp.UnionCaseProof _, _, [e] -> + ConvExpr cenv env e // Note: we erase the union case proof conversions when converting to quotations + + | TOp.UnionCaseTagGet _tycr, _tinst, [_cx] -> + wfail(Error(FSComp.SR.crefQuotationsCantFetchUnionIndexes(), m)) + + | TOp.UnionCaseFieldSet (_c, _i), _tinst, [_cx;_x] -> + wfail(Error(FSComp.SR.crefQuotationsCantSetUnionFields(), m)) + + | TOp.ExnFieldSet (_tcref, _i), [], [_ex;_x] -> + wfail(Error(FSComp.SR.crefQuotationsCantSetExceptionFields(), m)) + + | TOp.RefAddrGet _, _, _ -> + wfail(Error(FSComp.SR.crefQuotationsCantRequireByref(), m)) + + | TOp.TraitCall (_ss), _, _ -> + wfail(Error(FSComp.SR.crefQuotationsCantCallTraitMembers(), m)) + | _ -> wfail(InternalError( "Unexpected expression shape", m)) @@ -624,14 +638,13 @@ and ConvLdfld cenv env m (fspec: ILFieldSpec) enclTypeArgs args = let tyargsR = ConvTypes cenv env m enclTypeArgs let parentTyconR = ConvILTypeRefUnadjusted cenv m fspec.DeclaringTypeRef let argsR = ConvLValueArgs cenv env args - QP.mkFieldGet( (parentTyconR, fspec.Name), tyargsR, argsR) + QP.mkFieldGet(parentTyconR, fspec.Name, tyargsR, argsR) and ConvUnionFieldGet cenv env m ucref n tyargs e = let tyargsR = ConvTypes cenv env m tyargs let tcR, s = ConvUnionCaseRef cenv ucref m - let projR = (tcR, s, n) let eR = ConvLValueExpr cenv env e - QP.mkUnionFieldGet(projR, tyargsR, eR) + QP.mkUnionFieldGet(tcR, s, n, tyargsR, eR) and ConvClassOrRecdFieldGet cenv env m rfref tyargs args = EmitDebugInfoIfNecessary cenv env m (ConvClassOrRecdFieldGetCore cenv env m rfref tyargs args) @@ -639,14 +652,14 @@ and ConvClassOrRecdFieldGet cenv env m rfref tyargs args = and private ConvClassOrRecdFieldGetCore cenv env m rfref tyargs args = let tyargsR = ConvTypes cenv env m tyargs let argsR = ConvLValueArgs cenv env args - let ((parentTyconR, fldOrPropName) as projR) = ConvRecdFieldRef cenv rfref m + let (parentTyconR, fldOrPropName) = ConvRecdFieldRef cenv rfref m if rfref.TyconRef.IsRecordTycon then - QP.mkRecdGet(projR, tyargsR, argsR) + QP.mkRecdGet(parentTyconR, fldOrPropName, tyargsR, argsR) else let fspec = rfref.RecdField let tcref = rfref.TyconRef if useGenuineField tcref.Deref fspec then - QP.mkFieldGet(projR, tyargsR, argsR) + QP.mkFieldGet(parentTyconR, fldOrPropName, tyargsR, argsR) else let envinner = BindFormalTypars env tcref.TyparsNoRange let propRetTypeR = ConvType cenv envinner m fspec.FormalType @@ -660,7 +673,7 @@ and ConvLetBind cenv env (bind : Binding) = // 'if istype e then ...unbox e .... ' // It's bit annoying that pattern matching does this transformation. Like all premature optimization we pay a // cost here to undo it. - | Expr.Op(TOp.ILAsm([ I_isinst _ ], _), [ty], [e], _) -> + | Expr.Op (TOp.ILAsm ([ I_isinst _ ], _), [ty], [e], _) -> None, BindIsInstVal env bind.Var (ty, e) // Remove let = from quotation tree @@ -668,7 +681,7 @@ and ConvLetBind cenv env (bind : Binding) = None, BindSubstVal env bind.Var bind.Expr // Remove let unionCase = ... from quotation tree - | Expr.Op(TOp.UnionCaseProof _, _, [e], _) -> + | Expr.Op (TOp.UnionCaseProof _, _, [e], _) -> None, BindSubstVal env bind.Var e | _ -> @@ -680,7 +693,7 @@ and ConvLetBind cenv env (bind : Binding) = and ConvLValueArgs cenv env args = match args with - | obj::rest -> ConvLValueExpr cenv env obj :: ConvExprs cenv env rest + | obj :: rest -> ConvLValueExpr cenv env obj :: ConvExprs cenv env rest | [] -> [] and ConvLValueExpr cenv env expr = @@ -689,14 +702,14 @@ and ConvLValueExpr cenv env expr = // This function has to undo the work of mkExprAddrOfExpr and ConvLValueExprCore cenv env expr = match expr with - | Expr.Op(op, tyargs, args, m) -> + | Expr.Op (op, tyargs, args, m) -> match op, args, tyargs with - | TOp.LValueOp(LAddrOf _, vref), _, _ -> ConvValRef false cenv env m vref [] - | TOp.ValFieldGetAddr(rfref, _), _, _ -> ConvClassOrRecdFieldGet cenv env m rfref tyargs args - | TOp.UnionCaseFieldGetAddr(ucref, n, _), [e], _ -> ConvUnionFieldGet cenv env m ucref n tyargs e - | TOp.ILAsm([ I_ldflda(fspec) ], _rtys), _, _ -> ConvLdfld cenv env m fspec tyargs args - | TOp.ILAsm([ I_ldsflda(fspec) ], _rtys), _, _ -> ConvLdfld cenv env m fspec tyargs args - | TOp.ILAsm(([ I_ldelema(_ro, _isNativePtr, shape, _tyarg) ] ), _), (arr::idxs), [elemty] -> + | TOp.LValueOp (LAddrOf _, vref), _, _ -> ConvValRef false cenv env m vref [] + | TOp.ValFieldGetAddr (rfref, _), _, _ -> ConvClassOrRecdFieldGet cenv env m rfref tyargs args + | TOp.UnionCaseFieldGetAddr (ucref, n, _), [e], _ -> ConvUnionFieldGet cenv env m ucref n tyargs e + | TOp.ILAsm ([ I_ldflda(fspec) ], _rtys), _, _ -> ConvLdfld cenv env m fspec tyargs args + | TOp.ILAsm ([ I_ldsflda(fspec) ], _rtys), _, _ -> ConvLdfld cenv env m fspec tyargs args + | TOp.ILAsm (([ I_ldelema(_ro, _isNativePtr, shape, _tyarg) ] ), _), (arr :: idxs), [elemty] -> match shape.Rank, idxs with | 1, [idx1] -> ConvExpr cenv env (mkCallArrayGet cenv.g m elemty arr idx1) | 2, [idx1; idx2] -> ConvExpr cenv env (mkCallArray2DGet cenv.g m elemty arr idx1 idx2) @@ -746,7 +759,7 @@ and ConvModuleValueAppCore cenv env m (vref: ValRef) tyargs (args: Expr list lis let isProperty = IsCompiledAsStaticProperty cenv.g vref.Deref let tcrefR = ConvTyconRef cenv tcref m let tyargsR = ConvTypes cenv env m tyargs - let nm = vref.CompiledName + let nm = vref.CompiledName cenv.g.CompilerGlobalState let argsR = List.map (ConvExprs cenv env) args QP.mkModuleValueApp(tcrefR, nm, isProperty, tyargsR, argsR) @@ -800,7 +813,7 @@ and ConvRecdFieldRef cenv (rfref: RecdFieldRef) m = and ConvVal cenv env (v: Val) = let tyR = ConvType cenv env v.Range v.Type - QP.freshVar (v.CompiledName, tyR, v.IsMutable) + QP.freshVar (v.CompiledName cenv.g.CompilerGlobalState, tyR, v.IsMutable) and ConvTyparRef cenv env m (tp: Typar) = match env.tyvs.TryFind tp.Stamp with @@ -821,7 +834,7 @@ and ConvType cenv env m ty = | TType_app(tcref, [tyarg]) when isArrayTyconRef cenv.g tcref -> QP.mkArrayTy(rankOfArrayTyconRef cenv.g tcref, ConvType cenv env m tyarg) - | TType_ucase(UCRef(tcref, _), tyargs) // Note: we erase union case 'types' when converting to quotations + | TType_ucase(UnionCaseRef(tcref, _), tyargs) // Note: we erase union case 'types' when converting to quotations | TType_app(tcref, tyargs) -> #if !NO_EXTENSIONTYPING match TryElimErasableTyconRef cenv m tcref with @@ -885,9 +898,9 @@ and ConvDecisionTree cenv env tgs typR x = match discrim with | DecisionTreeTest.UnionCase (ucref, tyargs) -> let e1R = ConvLValueExpr cenv env e1 - let ucR = ConvUnionCaseRef cenv ucref m + let tcR, s = ConvUnionCaseRef cenv ucref m let tyargsR = ConvTypes cenv env m tyargs - QP.mkCond (QP.mkUnionCaseTagTest (ucR, tyargsR, e1R), ConvDecisionTree cenv env tgs typR dtree, acc) + QP.mkCond (QP.mkUnionCaseTagTest (tcR, s, tyargsR, e1R), ConvDecisionTree cenv env tgs typR dtree, acc) | DecisionTreeTest.Const (Const.Bool true) -> let e1R = ConvExpr cenv env e1 @@ -907,7 +920,7 @@ and ConvDecisionTree cenv env tgs typR x = | DecisionTreeTest.IsNull -> // Decompile cached isinst tests match e1 with - | Expr.Val(vref, _, _) when env.isinstVals.ContainsVal vref.Deref -> + | Expr.Val (vref, _, _) when env.isinstVals.ContainsVal vref.Deref -> let (ty, e) = env.isinstVals.[vref.Deref] let tyR = ConvType cenv env m ty let eR = ConvExpr cenv env e @@ -926,6 +939,8 @@ and ConvDecisionTree cenv env tgs typR x = | DecisionTreeTest.ActivePatternCase _ -> wfail(InternalError( "DecisionTreeTest.ActivePatternCase test in quoted expression", m)) | DecisionTreeTest.ArrayLength _ -> wfail(Error(FSComp.SR.crefQuotationsCantContainArrayPatternMatching(), m)) + + | DecisionTreeTest.Error m -> wfail(InternalError( "DecisionTreeTest.Error in quoted expression", m)) ) EmitDebugInfoIfNecessary cenv env m converted @@ -992,6 +1007,7 @@ and ConvILTypeRef cenv (tr: ILTypeRef) = let assemblyRef = match tr.Scope with | ILScopeRef.Local -> "." + | ILScopeRef.PrimaryAssembly -> cenv.g.ilg.primaryAssemblyScopeRef.QualifiedName | _ -> tr.Scope.QualifiedName QP.Named(tr.BasicQualifiedName, assemblyRef) @@ -1046,7 +1062,8 @@ and ConvReturnType cenv envinner m retTy = | None -> ConvVoidType cenv m | Some ty -> ConvType cenv envinner m ty -let ConvExprPublic cenv env e = +let ConvExprPublic cenv e = + let env = QuotationTranslationEnv.Empty let astExpr = let astExpr = ConvExpr cenv env e // always emit debug info for the top level expression @@ -1111,6 +1128,24 @@ let ConvMethodBase cenv env (methName, v: Val) = Module = parentTyconR IsProperty = IsCompiledAsStaticProperty cenv.g v } +let ConvReflectedDefinition cenv methName v e = + let g = cenv.g + let ety = tyOfExpr g e + let tps, taue, _ = + match e with + | Expr.TyLambda (_, tps, body, _, _) -> tps, body, applyForallTy g ety (List.map mkTyparTy tps) + | _ -> [], e, ety + let env = QuotationTranslationEnv.Empty + let env = env.BindTypars tps + let astExpr = + let astExpr = ConvExpr cenv env taue + // always emit debug info for ReflectedDefinition expression + let old = cenv.emitDebugInfoInQuotations + try + cenv.emitDebugInfoInQuotations <- true + EmitDebugInfoIfNecessary cenv env e.Range astExpr + finally + cenv.emitDebugInfoInQuotations <- old -// FSComp.SR.crefQuotationsCantContainLiteralByteArrays - + let mbaseR = ConvMethodBase cenv env (methName, v) + mbaseR, astExpr diff --git a/src/fcs-fable/src/fsharp/QuotationTranslator.fsi b/src/fcs-fable/src/fsharp/QuotationTranslator.fsi index 184f1d3da4..d7fcb7a999 100755 --- a/src/fcs-fable/src/fsharp/QuotationTranslator.fsi +++ b/src/fcs-fable/src/fsharp/QuotationTranslator.fsi @@ -1,20 +1,14 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -// Convert quoted TAST data structures to structures ready for pickling - +/// Convert quoted TAST data structures to structures ready for pickling module internal FSharp.Compiler.QuotationTranslator open FSharp.Compiler -open FSharp.Compiler.Range +open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.Import -open FSharp.Compiler.Tast +open FSharp.Compiler.Range open FSharp.Compiler.TcGlobals -open FSharp.Compiler.AbstractIL.IL - -[] -type QuotationTranslationEnv = - static member Empty : QuotationTranslationEnv - member BindTypars : Typars -> QuotationTranslationEnv +open FSharp.Compiler.TypedTree exception InvalidQuotedTerm of exn exception IgnoringPartOfQuotedTermWarning of string * Range.range @@ -36,9 +30,8 @@ type QuotationGenerationScope = member Close: unit -> ILTypeRef list * (TType * range) list * (Expr * range) list static member ComputeQuotationFormat : TcGlobals -> QuotationSerializationFormat -val ConvExprPublic : QuotationGenerationScope -> QuotationTranslationEnv -> Expr -> QuotationPickler.ExprData -val ConvMethodBase : QuotationGenerationScope -> QuotationTranslationEnv -> string * Val -> QuotationPickler.MethodBaseData - +val ConvExprPublic : QuotationGenerationScope -> Expr -> QuotationPickler.ExprData +val ConvReflectedDefinition: QuotationGenerationScope -> string -> Val -> Expr -> QuotationPickler.MethodBaseData * QuotationPickler.ExprData val (|ModuleValueOrMemberUse|_|) : TcGlobals -> Expr -> (ValRef * ValUseFlag * Expr * TType * TypeInst * Expr list) option val (|SimpleArrayLoopUpperBound|_|) : Expr -> unit option diff --git a/src/fcs-fable/src/fsharp/SignatureConformance.fs b/src/fcs-fable/src/fsharp/SignatureConformance.fs index 6ba6dad410..b1bd00345e 100644 --- a/src/fcs-fable/src/fsharp/SignatureConformance.fs +++ b/src/fcs-fable/src/fsharp/SignatureConformance.fs @@ -9,26 +9,32 @@ open System.Text open FSharp.Compiler open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.Range -open FSharp.Compiler.Ast open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops open FSharp.Compiler.Lib open FSharp.Compiler.Infos +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps #if !NO_EXTENSIONTYPING open FSharp.Compiler.ExtensionTyping #endif -exception RequiredButNotSpecified of DisplayEnv * Tast.ModuleOrNamespaceRef * string * (StringBuilder -> unit) * range -exception ValueNotContained of DisplayEnv * Tast.ModuleOrNamespaceRef * Val * Val * (string * string * string -> string) -exception ConstrNotContained of DisplayEnv * UnionCase * UnionCase * (string * string -> string) -exception ExnconstrNotContained of DisplayEnv * Tycon * Tycon * (string * string -> string) -exception FieldNotContained of DisplayEnv * RecdField * RecdField * (string * string -> string) -exception InterfaceNotRevealed of DisplayEnv * TType * range +exception RequiredButNotSpecified of DisplayEnv * ModuleOrNamespaceRef * string * (StringBuilder -> unit) * range + +exception ValueNotContained of DisplayEnv * ModuleOrNamespaceRef * Val * Val * (string * string * string -> string) + +exception ConstrNotContained of DisplayEnv * UnionCase * UnionCase * (string * string -> string) +exception ExnconstrNotContained of DisplayEnv * Tycon * Tycon * (string * string -> string) + +exception FieldNotContained of DisplayEnv * RecdField * RecdField * (string * string -> string) + +exception InterfaceNotRevealed of DisplayEnv * TType * range // Use a type to capture the constant, common parameters type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = @@ -305,7 +311,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = let m = implVal.Range if implVal.IsMutable <> sigVal.IsMutable then (err denv FSComp.SR.ValueNotContainedMutabilityAttributesDiffer) elif implVal.LogicalName <> sigVal.LogicalName then (err denv FSComp.SR.ValueNotContainedMutabilityNamesDiffer) - elif implVal.CompiledName <> sigVal.CompiledName then (err denv FSComp.SR.ValueNotContainedMutabilityCompiledNamesDiffer) + elif (implVal.CompiledName g.CompilerGlobalState) <> (sigVal.CompiledName g.CompilerGlobalState) then (err denv FSComp.SR.ValueNotContainedMutabilityCompiledNamesDiffer) elif implVal.DisplayName <> sigVal.DisplayName then (err denv FSComp.SR.ValueNotContainedMutabilityDisplayNamesDiffer) elif isLessAccessible implVal.Accessibility sigVal.Accessibility then (err denv FSComp.SR.ValueNotContainedMutabilityAccessibilityMore) elif implVal.MustInline <> sigVal.MustInline then (err denv FSComp.SR.ValueNotContainedMutabilityInlineFlagsDiffer) @@ -346,8 +352,8 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = sigUnionCase.OtherRangeOpt <- Some (implUnionCase.Range, true) implUnionCase.OtherRangeOpt <- Some (sigUnionCase.Range, false) if implUnionCase.Id.idText <> sigUnionCase.Id.idText then err FSComp.SR.ModuleContainsConstructorButNamesDiffer - elif implUnionCase.RecdFields.Length <> sigUnionCase.RecdFields.Length then err FSComp.SR.ModuleContainsConstructorButDataFieldsDiffer - elif not (List.forall2 (checkField aenv) implUnionCase.RecdFields sigUnionCase.RecdFields) then err FSComp.SR.ModuleContainsConstructorButTypesOfFieldsDiffer + elif implUnionCase.RecdFieldsArray.Length <> sigUnionCase.RecdFieldsArray.Length then err FSComp.SR.ModuleContainsConstructorButDataFieldsDiffer + elif not (Array.forall2 (checkField aenv) implUnionCase.RecdFieldsArray sigUnionCase.RecdFieldsArray) then err FSComp.SR.ModuleContainsConstructorButTypesOfFieldsDiffer elif isLessAccessible implUnionCase.Accessibility sigUnionCase.Accessibility then err FSComp.SR.ModuleContainsConstructorButAccessibilityDiffers else checkAttribs aenv implUnionCase.Attribs sigUnionCase.Attribs (fun attribs -> implUnionCase.Attribs <- attribs) @@ -369,7 +375,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = match implMemberInfo, sigMemberInfo with | None, None -> true | Some implMembInfo, Some sigMembInfo -> - if not (implVal.CompiledName = sigVal.CompiledName) then + if not ((implVal.CompiledName g.CompilerGlobalState) = (sigVal.CompiledName g.CompilerGlobalState)) then err(FSComp.SR.ValueNotContainedMutabilityDotNetNamesDiffer) elif not (implMembInfo.MemberFlags.IsInstance = sigMembInfo.MemberFlags.IsInstance) then err(FSComp.SR.ValueNotContainedMutabilityStaticsDiffer) @@ -400,14 +406,6 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = | _ -> false - // ------------------------------------------------------------------------------- - // WARNING!!!! - // checkRecordFields and checkRecordFieldsForExn are the EXACT SAME FUNCTION. - // The only difference is the signature for err - this is because err is a function - // that reports errors, and checkRecordFields is called with a different - // sig for err then checkRecordFieldsForExn. - // ------------------------------------------------------------------------------- - and checkRecordFields m aenv (implTycon: Tycon) (implFields: TyconRecdFields) (sigFields: TyconRecdFields) = let implFields = implFields.TrueFieldsAsList let sigFields = sigFields.TrueFieldsAsList diff --git a/src/fcs-fable/src/fsharp/SimulatedMSBuildReferenceResolver.fs b/src/fcs-fable/src/fsharp/SimulatedMSBuildReferenceResolver.fs index cf0aeecf80..bf5ffc092f 100644 --- a/src/fcs-fable/src/fsharp/SimulatedMSBuildReferenceResolver.fs +++ b/src/fcs-fable/src/fsharp/SimulatedMSBuildReferenceResolver.fs @@ -10,11 +10,10 @@ open System open System.IO open System.Reflection open Microsoft.Win32 -open FSharp.Compiler open FSharp.Compiler.ReferenceResolver open FSharp.Compiler.AbstractIL.Internal.Library -let internal SimulatedMSBuildResolver = +let private SimulatedMSBuildResolver = let supportedFrameworks = [| "v4.7.2" "v4.7.1" @@ -26,9 +25,9 @@ let internal SimulatedMSBuildResolver = "v4.5" "v4.0" |] - { new Resolver with + { new Resolver with member x.HighestInstalledNetFrameworkVersion() = - + let root = x.DotNetFrameworkReferenceAssembliesRootDirectory let fwOpt = supportedFrameworks |> Seq.tryFind(fun fw -> Directory.Exists(Path.Combine(root, fw) )) match fwOpt with @@ -37,11 +36,11 @@ let internal SimulatedMSBuildResolver = member __.DotNetFrameworkReferenceAssembliesRootDirectory = #if !FX_RESHAPED_MSBUILD - if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then - let PF = + if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then + let PF = match Environment.GetEnvironmentVariable("ProgramFiles(x86)") with | null -> Environment.GetEnvironmentVariable("ProgramFiles") // if PFx86 is null, then we are 32-bit and just get PF - | s -> s + | s -> s PF + @"\Reference Assemblies\Microsoft\Framework\.NETFramework" else #endif @@ -51,153 +50,139 @@ let internal SimulatedMSBuildResolver = fsharpCoreDir, explicitIncludeDirs, implicitIncludeDir, logMessage, logWarningOrError) = #if !FX_NO_WIN_REGISTRY - let registrySearchPaths() = + let registrySearchPaths() = [ let registryKey = @"Software\Microsoft\.NetFramework" - use key = Registry.LocalMachine.OpenSubKey(registryKey) - match key with + use key = Registry.LocalMachine.OpenSubKey registryKey + match key with | null -> () - | _ -> + | _ -> for subKeyName in key.GetSubKeyNames() do - use subKey = key.OpenSubKey(subKeyName) + use subKey = key.OpenSubKey subKeyName use subSubKey = subKey.OpenSubKey("AssemblyFoldersEx") - match subSubKey with + match subSubKey with | null -> () - | _ -> + | _ -> for subSubSubKeyName in subSubKey.GetSubKeyNames() do - use subSubSubKey = subSubKey.OpenSubKey(subSubSubKeyName) - match subSubSubKey.GetValue(null) with + use subSubSubKey = subSubKey.OpenSubKey subSubSubKeyName + match subSubSubKey.GetValue null with | :? string as s -> yield s - | _ -> () + | _ -> () use subSubKey = key.OpenSubKey("AssemblyFolders") - match subSubKey with + match subSubKey with | null -> () - | _ -> + | _ -> for subSubSubKeyName in subSubKey.GetSubKeyNames() do - let subSubSubKey = subSubKey.OpenSubKey(subSubSubKeyName) - match subSubSubKey.GetValue(null) with + let subSubSubKey = subSubKey.OpenSubKey subSubSubKeyName + match subSubSubKey.GetValue null with | :? string as s -> yield s | _ -> () ] #endif let results = ResizeArray() - let searchPaths = - [ yield! targetFrameworkDirectories - yield! explicitIncludeDirs + let searchPaths = + [ yield! targetFrameworkDirectories + yield! explicitIncludeDirs yield fsharpCoreDir - yield implicitIncludeDir + yield implicitIncludeDir #if !FX_NO_WIN_REGISTRY - if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then - yield! registrySearchPaths() + if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then + yield! registrySearchPaths() #endif ] for (r, baggage) in references do //printfn "resolving %s" r let mutable found = false - let success path = - if not found then + let success path = + if not found then //printfn "resolved %s --> %s" r path found <- true - results.Add { itemSpec = path; prepareToolTip = snd; baggage=baggage } + results.Add { itemSpec = path; prepareToolTip = snd; baggage=baggage } - try - if not found && Path.IsPathRooted(r) then - if FileSystem.SafeExists(r) then + try + if not found && Path.IsPathRooted r then + if FileSystem.SafeExists r then success r with e -> logWarningOrError false "SR001" (e.ToString()) #if !FX_RESHAPED_MSBUILD // For this one we need to get the version search exactly right, without doing a load - try - if not found && r.StartsWithOrdinal("FSharp.Core, Version=") && Environment.OSVersion.Platform = PlatformID.Win32NT then - let n = AssemblyName(r) - let fscoreDir0 = - let PF = + try + if not found && r.StartsWithOrdinal("FSharp.Core, Version=") && Environment.OSVersion.Platform = PlatformID.Win32NT then + let n = AssemblyName r + let fscoreDir0 = + let PF = match Environment.GetEnvironmentVariable("ProgramFiles(x86)") with - | null -> Environment.GetEnvironmentVariable("ProgramFiles") - | s -> s + | null -> Environment.GetEnvironmentVariable("ProgramFiles") + | s -> s PF + @"\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\" + n.Version.ToString() - let trialPath = Path.Combine(fscoreDir0,n.Name + ".dll") - if FileSystem.SafeExists(trialPath) then + let trialPath = Path.Combine(fscoreDir0, n.Name + ".dll") + if FileSystem.SafeExists trialPath then success trialPath with e -> logWarningOrError false "SR001" (e.ToString()) #endif - let isFileName = - r.EndsWith("dll",StringComparison.OrdinalIgnoreCase) || - r.EndsWith("exe",StringComparison.OrdinalIgnoreCase) + let isFileName = + r.EndsWith("dll", StringComparison.OrdinalIgnoreCase) || + r.EndsWith("exe", StringComparison.OrdinalIgnoreCase) let qual = if isFileName then r else try AssemblyName(r).Name + ".dll" with _ -> r + ".dll" - for searchPath in searchPaths do - try - if not found then - let trialPath = Path.Combine(searchPath,qual) - if FileSystem.SafeExists(trialPath) then + for searchPath in searchPaths do + try + if not found then + let trialPath = Path.Combine(searchPath, qual) + if FileSystem.SafeExists trialPath then success trialPath with e -> logWarningOrError false "SR001" (e.ToString()) #if !FX_RESHAPED_MSBUILD - try - // Seach the GAC on Windows - if not found && not isFileName && Environment.OSVersion.Platform = PlatformID.Win32NT then - let n = AssemblyName(r) - let netfx = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() - let gac = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(netfx.TrimEnd('\\'))),"assembly") - match n.Version, n.GetPublicKeyToken() with - | null, _ | _,null -> - let options = - [ if Directory.Exists(gac) then - for gacdir in Directory.EnumerateDirectories(gac) do - let assemblyDir = Path.Combine(gacdir,n.Name) - if Directory.Exists(assemblyDir) then - for tdir in Directory.EnumerateDirectories(assemblyDir) do - let trialPath = Path.Combine(tdir,qual) - if FileSystem.SafeExists(trialPath) then + try + // Search the GAC on Windows + if not found && not isFileName && Environment.OSVersion.Platform = PlatformID.Win32NT then + let n = AssemblyName r + let netFx = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() + let gac = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(netFx.TrimEnd('\\'))), "assembly") + match n.Version, n.GetPublicKeyToken() with + | null, _ | _, null -> + let options = + [ if Directory.Exists gac then + for gacDir in Directory.EnumerateDirectories gac do + let assemblyDir = Path.Combine(gacDir, n.Name) + if Directory.Exists assemblyDir then + for tdir in Directory.EnumerateDirectories assemblyDir do + let trialPath = Path.Combine(tdir, qual) + if FileSystem.SafeExists trialPath then yield trialPath ] //printfn "sorting GAC paths: %A" options - options + options |> List.sort // puts latest version last |> List.tryLast |> function None -> () | Some p -> success p - | v,tok -> - if Directory.Exists(gac) then - for gacdir in Directory.EnumerateDirectories(gac) do - //printfn "searching GAC directory: %s" gacdir - let assemblyDir = Path.Combine(gacdir,n.Name) - if Directory.Exists(assemblyDir) then + | v, tok -> + if Directory.Exists gac then + for gacDir in Directory.EnumerateDirectories gac do + //printfn "searching GAC directory: %s" gacDir + let assemblyDir = Path.Combine(gacDir, n.Name) + if Directory.Exists assemblyDir then //printfn "searching GAC directory: %s" assemblyDir let tokText = String.concat "" [| for b in tok -> sprintf "%02x" b |] - let verdir = Path.Combine(assemblyDir,"v4.0_"+v.ToString()+"__"+tokText) - //printfn "searching GAC directory: %s" verdir + let verDir = Path.Combine(assemblyDir, "v4.0_"+v.ToString()+"__"+tokText) + //printfn "searching GAC directory: %s" verDir - if Directory.Exists(verdir) then - let trialPath = Path.Combine(verdir,qual) + if Directory.Exists verDir then + let trialPath = Path.Combine(verDir, qual) //printfn "searching GAC: %s" trialPath - if FileSystem.SafeExists(trialPath) then + if FileSystem.SafeExists trialPath then success trialPath with e -> logWarningOrError false "SR001" (e.ToString()) #endif results.ToArray() } -let internal GetBestAvailableResolver() = -#if !FX_RESHAPED_MSBUILD - let tryMSBuild v = - // Detect if MSBuild is on the machine, if so use the resolver from there - let mb = try Assembly.Load(sprintf "Microsoft.Build.Framework, Version=%s.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" v) |> Option.ofObj with _ -> None - let assembly = mb |> Option.bind (fun _ -> try Assembly.Load(sprintf "FSharp.Compiler.Service.MSBuild.v%s" v) |> Option.ofObj with _ -> None) - let ty = assembly |> Option.bind (fun a -> a.GetType("FSharp.Compiler.MSBuildReferenceResolver") |> Option.ofObj) - let obj = ty |> Option.bind (fun ty -> ty.InvokeMember("get_Resolver",BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.InvokeMethod ||| BindingFlags.NonPublic, null, null, [| |]) |> Option.ofObj) - let resolver = obj |> Option.bind (fun obj -> match obj with :? Resolver as r -> Some r | _ -> None) - resolver - match tryMSBuild "12" with - | Some r -> r - | None -> -#endif - SimulatedMSBuildResolver +let internal getResolver () = SimulatedMSBuildResolver #if INTERACTIVE @@ -205,21 +190,21 @@ let internal GetBestAvailableResolver() = SimulatedMSBuildResolver.DotNetFrameworkReferenceAssembliesRootDirectory SimulatedMSBuildResolver.HighestInstalledNetFrameworkVersion() -let fscoreDir = - if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then // file references only valid on Windows - let PF = +let fscoreDir = + if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then // file references only valid on Windows + let PF = match Environment.GetEnvironmentVariable("ProgramFiles(x86)") with | null -> Environment.GetEnvironmentVariable("ProgramFiles") // if PFx86 is null, then we are 32-bit and just get PF - | s -> s - PF + @"\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\4.4.0.0" - else + | s -> s + PF + @"\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\4.4.0.0" + else System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() -let resolve s = +let resolve s = SimulatedMSBuildResolver.Resolve - (ResolutionEnvironment.EditingOrCompilation,[| for a in s -> (a, "") |],"v4.5.1", - [SimulatedMSBuildResolver.DotNetFrameworkReferenceAssembliesRootDirectory + @"\v4.5.1" ],"", "", - fscoreDir,[],__SOURCE_DIRECTORY__,ignore, (fun _ _ -> ()), (fun _ _-> ())) + (ResolutionEnvironment.EditingOrCompilation, [| for a in s -> (a, "") |], "v4.5.1", + [SimulatedMSBuildResolver.DotNetFrameworkReferenceAssembliesRootDirectory + @"\v4.5.1" ], "", "", + fscoreDir, [], __SOURCE_DIRECTORY__, ignore, (fun _ _ -> ()), (fun _ _-> ())) // Resolve partial name to something on search path resolve ["FSharp.Core" ] diff --git a/src/fcs-fable/src/fsharp/SyntaxTree.fs b/src/fcs-fable/src/fsharp/SyntaxTree.fs new file mode 100644 index 0000000000..a071f1c526 --- /dev/null +++ b/src/fcs-fable/src/fsharp/SyntaxTree.fs @@ -0,0 +1,2271 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +module public rec FSharp.Compiler.SyntaxTree + +open System.Diagnostics + +open FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.Range +open FSharp.Compiler.XmlDoc + +/// Represents an identifier in F# code +[] +type Ident (text: string, range: range) = + member x.idText = text + member x.idRange = range + override x.ToString() = text + +/// Represents a long identifier e.g. 'A.B.C' +type LongIdent = Ident list + +/// Represents a long identifier with possible '.' at end. +/// +/// Typically dotms.Length = lid.Length-1, but they may be same if (incomplete) code ends in a dot, e.g. "Foo.Bar." +/// The dots mostly matter for parsing, and are typically ignored by the typechecker, but +/// if dotms.Length = lid.Length, then the parser must have reported an error, so the typechecker is allowed +/// more freedom about typechecking these expressions. +/// LongIdent can be empty list - it is used to denote that name of some AST element is absent (i.e. empty type name in inherit) +type LongIdentWithDots = + | LongIdentWithDots of id: LongIdent * dotms: range list + + /// Gets the syntax range of this constuct + member this.Range = + match this with + | LongIdentWithDots([], _) -> failwith "rangeOfLidwd" + | LongIdentWithDots([id], []) -> id.idRange + | LongIdentWithDots([id], [m]) -> unionRanges id.idRange m + | LongIdentWithDots(h :: t, []) -> unionRanges h.idRange (List.last t).idRange + | LongIdentWithDots(h :: t, dotms) -> unionRanges h.idRange (List.last t).idRange |> unionRanges (List.last dotms) + + /// Get the long ident for this construct + member this.Lid = match this with LongIdentWithDots(lid, _) -> lid + + /// Indicates if the construct ends in '.' due to error recovery + member this.ThereIsAnExtraDotAtTheEnd = match this with LongIdentWithDots(lid, dots) -> lid.Length = dots.Length + + /// Gets the syntax range for part of this constuct + member this.RangeSansAnyExtraDot = + match this with + | LongIdentWithDots([], _) -> failwith "rangeOfLidwd" + | LongIdentWithDots([id], _) -> id.idRange + | LongIdentWithDots(h :: t, dotms) -> + let nonExtraDots = if dotms.Length = t.Length then dotms else List.truncate t.Length dotms + unionRanges h.idRange (List.last t).idRange |> unionRanges (List.last nonExtraDots) + +/// Indicates if the construct arises from error recovery +[] +type ParserDetail = + /// The construct arises normally + | Ok + + /// The construct arises from error recovery + | ErrorRecovery + +/// Represents whether a type parameter has a static requirement or not (^T or 'T) +type TyparStaticReq = + /// The construct is a normal type inference variable + | NoStaticReq + + /// The construct is a statically inferred type inference variable '^T' + | HeadTypeStaticReq + +/// Represents a syntactic type parameter +[] +type SynTypar = + | Typar of ident: Ident * staticReq: TyparStaticReq * isCompGen: bool + + /// Gets the syntax range of this constuct + member this.Range = + match this with + | Typar(id, _, _) -> + id.idRange + +/// The unchecked abstract syntax tree of constants in F# types and expressions. +[] +type SynConst = + + /// F# syntax: () + | Unit + + /// F# syntax: true, false + | Bool of bool + + /// F# syntax: 13y, 0xFFy, 0o077y, 0b0111101y + | SByte of sbyte + + /// F# syntax: 13uy, 0x40uy, 0oFFuy, 0b0111101uy + | Byte of byte + + /// F# syntax: 13s, 0x4000s, 0o0777s, 0b0111101s + | Int16 of int16 + + /// F# syntax: 13us, 0x4000us, 0o0777us, 0b0111101us + | UInt16 of uint16 + + /// F# syntax: 13, 0x4000, 0o0777 + | Int32 of int32 + + /// F# syntax: 13u, 0x4000u, 0o0777u + | UInt32 of uint32 + + /// F# syntax: 13L + | Int64 of int64 + + /// F# syntax: 13UL + | UInt64 of uint64 + + /// F# syntax: 13n + | IntPtr of int64 + + /// F# syntax: 13un + | UIntPtr of uint64 + + /// F# syntax: 1.30f, 1.40e10f etc. + | Single of single + + /// F# syntax: 1.30, 1.40e10 etc. + | Double of double + + /// F# syntax: 'a' + | Char of char + + /// F# syntax: 23.4M + | Decimal of System.Decimal + + /// UserNum(value, suffix) + /// + /// F# syntax: 1Q, 1Z, 1R, 1N, 1G + | UserNum of value: string * suffix: string + + /// F# syntax: verbatim or regular string, e.g. "abc" + | String of text: string * range: range + + /// F# syntax: verbatim or regular byte string, e.g. "abc"B. + /// + /// Also used internally in the typechecker once an array of unit16 constants + /// is detected, to allow more efficient processing of large arrays of uint16 constants. + | Bytes of bytes: byte[] * range: range + + /// Used internally in the typechecker once an array of unit16 constants + /// is detected, to allow more efficient processing of large arrays of uint16 constants. + | UInt16s of uint16[] + + /// Old comment: "we never iterate, so the const here is not another SynConst.Measure" + | Measure of constant: SynConst * SynMeasure + + /// Gets the syntax range of this constuct + member c.Range dflt = + match c with + | SynConst.String (_, m0) | SynConst.Bytes (_, m0) -> m0 + | _ -> dflt + +/// Represents an unchecked syntax tree of F# unit of measure annotations. +[] +type SynMeasure = + + /// A named unit of measure + | Named of longId: LongIdent * range: range + + /// A product of two units of measure, e.g. 'kg * m' + | Product of SynMeasure * SynMeasure * range: range + + /// A sequence of several units of measure, e.g. 'kg m m' + | Seq of SynMeasure list * range: range + + /// A division of two units of measure, e.g. 'kg / m' + | Divide of SynMeasure * SynMeasure * range: range + + /// A power of a unit of measure, e.g. 'kg ^ 2' + | Power of SynMeasure * SynRationalConst * range: range + + /// The '1' unit of measure + | One + + /// An anonymous (inferred) unit of measure + | Anon of range: range + + /// A variable unit of measure + | Var of SynTypar * range: range + +/// Represents an unchecked syntax tree of F# unit of measure exponents. +[] +type SynRationalConst = + + | Integer of int32 + + | Rational of int32 * int32 * range: range + + | Negate of SynRationalConst + +/// Represents an accessibility modifier in F# syntax +[] +type SynAccess = + /// A construct marked or assumed 'public' + | Public + + /// A construct marked or assumed 'internal' + | Internal + + /// A construct marked or assumed 'private' + | Private + + override this.ToString () = + match this with + | Public -> "Public" + | Internal -> "Internal" + | Private -> "Private" + +/// Represents whether a debug point should be present for the target +/// of a decision tree, that is whether the construct corresponds to a debug +/// point in the original source. +[] +type DebugPointForTarget = + | Yes + | No + +/// Represents whether a debug point should be present for either the +/// first or second part of a sequential execution, that is whether the +/// construct corresponds to a debug point in the original source. +[] +type DebugPointAtSequential = + | Both + + // This means "suppress a in 'a;b'" and "suppress b in 'a before b'" + | StmtOnly + + // This means "suppress b in 'a;b'" and "suppress a in 'a before b'" + | ExprOnly + +/// Represents whether a debug point should be present for a 'try', that is whether +/// the construct corresponds to a debug point in the original source. +[] +type DebugPointAtTry = + | Yes of range: range + // Used for "use" and "for" + | Body + | No + +/// Represents whether a debug point should be present for the 'with' in a 'try .. with', +/// that is whether the construct corresponds to a debug point in the original source. +[] +type DebugPointAtWith = + | Yes of range: range + | No + +/// Represents whether a debug point should be present for the 'finally' in a 'try .. finally', +/// that is whether the construct corresponds to a debug point in the original source. +[] +type DebugPointAtFinally = + | Yes of range: range + | No + +/// Represents whether a debug point should be present for the 'for' in a 'for...' loop, +/// that is whether the construct corresponds to a debug point in the original source. +[] +type DebugPointAtFor = + | Yes of range: range + | No + +/// Represents whether a debug point should be present for the 'while' in a 'while...' loop, +/// that is whether the construct corresponds to a debug point in the original source. +[] +type DebugPointAtWhile = + | Yes of range: range + | No + +/// Represents whether a debug point should be present for a 'let' binding, +/// that is whether the construct corresponds to a debug point in the original source. +type DebugPointForBinding = + | DebugPointAtBinding of range: range + + // Indicates the omission of a sequence point for a binding for a 'do expr' + | NoDebugPointAtDoBinding + + // Indicates the omission of a sequence point for a binding for a 'let e = expr' where + // 'expr' has immediate control flow + | NoDebugPointAtLetBinding + + // Indicates the omission of a sequence point for a compiler generated binding + // where we've done a local expansion of some construct into something that involves + // a 'let'. e.g. we've inlined a function and bound its arguments using 'let' + // The let bindings are 'sticky' in that the inversion of the inlining would involve + // replacing the entire expression with the original and not just the let bindings alone. + | NoDebugPointAtStickyBinding + + // Given 'let v = e1 in e2', where this is a compiler generated binding, + // we are sometimes forced to generate a sequence point for the expression anyway based on its + // overall range. If the let binding is given the flag below then it is asserting that + // the binding has no interesting side effects and can be totally ignored and the range + // of the inner expression is used instead + | NoDebugPointAtInvisibleBinding + + // Don't drop sequence points when combining sequence points + member x.Combine(y: DebugPointForBinding) = + match x, y with + | DebugPointAtBinding _ as g, _ -> g + | _, (DebugPointAtBinding _ as g) -> g + | _ -> x + +/// Indicates if a for loop is 'for x in e1 -> e2', only valid in sequence expressions +type SeqExprOnly = + /// Indicates if a for loop is 'for x in e1 -> e2', only valid in sequence expressions + | SeqExprOnly of bool + +/// Represents the location of the separator block + optional position +/// of the semicolon (used for tooling support) +type BlockSeparator = range * pos option + +/// Represents a record field name plus a flag indicating if given record field name is syntactically +/// correct and can be used in name resolution. +type RecordFieldName = LongIdentWithDots * bool + +/// Indicates if an expression is an atomic expression. +/// +/// An atomic expression has no whitespace unlessenclosed in parentheses, e.g. +/// 1, "3", ident, ident.[expr] and (expr). If an atomic expression has type T, +/// then the largest expression ending at the same range as the atomic expression +/// also has type T. +type ExprAtomicFlag = + | Atomic = 0 + | NonAtomic = 1 + +/// The kind associated with a binding - "let", "do" or a standalone expression +type SynBindingKind = + + /// A standalone expression in a module + | StandaloneExpression + + /// A normal 'let' binding in a module + | NormalBinding + + /// A 'do' binding in a module. Must have type 'unit' + | DoBinding + +/// Represents the explicit declaration of a type parameter +[] +type SynTyparDecl = + | TyparDecl of attributes: SynAttributes * SynTypar + +/// The unchecked abstract syntax tree of F# type constraints +[] +type SynTypeConstraint = + + /// F# syntax: is 'typar: struct + | WhereTyparIsValueType of + typar: SynTypar * + range: range + + /// F# syntax: is 'typar: not struct + | WhereTyparIsReferenceType of + typar: SynTypar * + range: range + + /// F# syntax is 'typar: unmanaged + | WhereTyparIsUnmanaged of + typar: SynTypar * + range: range + + /// F# syntax is 'typar: null + | WhereTyparSupportsNull of + typar: SynTypar * + range: range + + /// F# syntax is 'typar: comparison + | WhereTyparIsComparable of + typar: SynTypar * + range: range + + /// F# syntax is 'typar: equality + | WhereTyparIsEquatable of + typar: SynTypar * + range: range + + /// F# syntax is default ^T: type + | WhereTyparDefaultsToType of + typar: SynTypar * + typeName: SynType * + range: range + + /// F# syntax is 'typar :> type + | WhereTyparSubtypeOfType of + typar: SynTypar * + typeName: SynType * + range: range + + /// F# syntax is ^T: (static member MemberName: ^T * int -> ^T) + | WhereTyparSupportsMember of + typars: SynType list * + memberSig: SynMemberSig * + range: range + + /// F# syntax is 'typar: enum<'UnderlyingType> + | WhereTyparIsEnum of + typar: SynTypar * + typeArgs: SynType list * + range: range + + /// F# syntax is 'typar: delegate<'Args, unit> + | WhereTyparIsDelegate of + typar: SynTypar * + typeArgs: SynType list * + range: range + +/// Represents a syntax tree for F# types +[] +type SynType = + + /// F# syntax: A.B.C + | LongIdent of + longDotId: LongIdentWithDots + + /// F# syntax: type or type type or (type, ..., type) type + /// isPostfix: indicates a postfix type application e.g. "int list" or "(int, string) dict" + | App of + typeName: SynType * + lessRange: range option * + typeArgs: SynType list * + commaRanges: range list * // interstitial commas + greaterRange: range option * + isPostfix: bool * + range: range + + /// F# syntax: type.A.B.C + | LongIdentApp of + typeName: SynType * + longDotId: LongIdentWithDots * + lessRange: range option * + typeArgs: SynType list * + commaRanges: range list * // interstitial commas + greaterRange: range option * + range: range + + /// F# syntax: type * ... * type + /// F# syntax: struct (type * ... * type) + // the bool is true if / rather than * follows the type + | Tuple of + isStruct: bool * + elementTypes:(bool*SynType) list * + range: range + + /// F# syntax: {| id: type; ...; id: type |} + /// F# syntax: struct {| id: type; ...; id: type |} + | AnonRecd of + isStruct: bool * + fields:(Ident * SynType) list * + range: range + + /// F# syntax: type[] + | Array of + rank: int * + elementType: SynType * + range: range + + /// F# syntax: type -> type + | Fun of + argType: SynType * + returnType: SynType * + range: range + + /// F# syntax: 'Var + | Var of + typar: SynTypar * + range: range + + /// F# syntax: _ + | Anon of range: range + + /// F# syntax: typ with constraints + | WithGlobalConstraints of + typeName: SynType * + constraints: SynTypeConstraint list * + range: range + + /// F# syntax: #type + | HashConstraint of + innerType: SynType * + range: range + + /// F# syntax: for units of measure e.g. m / s + | MeasureDivide of + dividend: SynType * + divisor: SynType * + range: range + + /// F# syntax: for units of measure e.g. m^3, kg^1/2 + | MeasurePower of + baseMeasure: SynType * + exponent: SynRationalConst * + range: range + + /// F# syntax: 1, "abc" etc, used in parameters to type providers + /// For the dimensionless units i.e. 1, and static parameters to provided types + | StaticConstant of + constant: SynConst * + range: range + + /// F# syntax: const expr, used in static parameters to type providers + | StaticConstantExpr of + expr: SynExpr * + range: range + + /// F# syntax: ident=1 etc., used in static parameters to type providers + | StaticConstantNamed of + ident: SynType * + value: SynType * + range: range + + /// Gets the syntax range of this constuct + member x.Range = + match x with + | SynType.App (range=m) + | SynType.LongIdentApp (range=m) + | SynType.Tuple (range=m) + | SynType.Array (range=m) + | SynType.AnonRecd (range=m) + | SynType.Fun (range=m) + | SynType.Var (range=m) + | SynType.Anon (range=m) + | SynType.WithGlobalConstraints (range=m) + | SynType.StaticConstant (range=m) + | SynType.StaticConstantExpr (range=m) + | SynType.StaticConstantNamed (range=m) + | SynType.HashConstraint (range=m) + | SynType.MeasureDivide (range=m) + | SynType.MeasurePower (range=m) -> m + | SynType.LongIdent lidwd -> lidwd.Range + +/// Represents a syntax tree for F# expressions +[] +type SynExpr = + + /// F# syntax: (expr) + /// + /// Parenthesized expressions. Kept in AST to distinguish A.M((x, y)) + /// from A.M(x, y), among other things. + | Paren of + expr: SynExpr * + leftParenRange: range * + rightParenRange: range option * + range: range + + /// F# syntax: <@ expr @>, <@@ expr @@> + /// + /// Quote(operator, isRaw, quotedSynExpr, isFromQueryExpression, m) + | Quote of + operator: SynExpr * + isRaw: bool * + quotedExpr: SynExpr * + isFromQueryExpression: bool * + range: range + + /// F# syntax: 1, 1.3, () etc. + | Const of + constant: SynConst * + range: range + + /// F# syntax: expr: type + | Typed of + expr: SynExpr * + targetType: SynType * + range: range + + /// F# syntax: e1, ..., eN + | Tuple of + isStruct: bool * + exprs: SynExpr list * + commaRanges: range list * // interstitial commas + range: range + + /// F# syntax: {| id1=e1; ...; idN=eN |} + /// F# syntax: struct {| id1=e1; ...; idN=eN |} + | AnonRecd of + isStruct: bool * + copyInfo:(SynExpr * BlockSeparator) option * + recordFields:(Ident * SynExpr) list * + range: range + + /// F# syntax: [ e1; ...; en ], [| e1; ...; en |] + | ArrayOrList of + isList: bool * + exprs: SynExpr list * + range: range + + /// F# syntax: { f1=e1; ...; fn=en } + /// inherit includes location of separator (for tooling) + /// copyOpt contains range of the following WITH part (for tooling) + /// every field includes range of separator after the field (for tooling) + | Record of + baseInfo:(SynType * SynExpr * range * BlockSeparator option * range) option * + copyInfo:(SynExpr * BlockSeparator) option * + recordFields:(RecordFieldName * (SynExpr option) * BlockSeparator option) list * + range: range + + /// F# syntax: new C(...) + /// The flag is true if known to be 'family' ('protected') scope + | New of + isProtected: bool * + targetType: SynType * + expr: SynExpr * + range: range + + /// F# syntax: { new ... with ... } + | ObjExpr of + objType: SynType * + argOptions:(SynExpr * Ident option) option * + bindings: SynBinding list * + extraImpls: SynInterfaceImpl list * + newExprRange: range * + range: range + + /// F# syntax: 'while ... do ...' + | While of + whileSeqPoint: DebugPointAtWhile * + whileExpr: SynExpr * + doExpr: SynExpr * + range: range + + /// F# syntax: 'for i = ... to ... do ...' + | For of + forSeqPoint: DebugPointAtFor * + ident: Ident * + identBody: SynExpr * + direction: bool * + toBody: SynExpr * + doBody: SynExpr * + range: range + + /// F# syntax: 'for ... in ... do ...' + | ForEach of + forSeqPoint: DebugPointAtFor * + seqExprOnly: SeqExprOnly * + isFromSource: bool * + pat: SynPat * + enumExpr: SynExpr * + bodyExpr: SynExpr * + range: range + + /// F# syntax: [ expr ], [| expr |] + | ArrayOrListOfSeqExpr of + isArray: bool * + expr: SynExpr * + range: range + + /// F# syntax: { expr } + | CompExpr of + isArrayOrList: bool * + isNotNakedRefCell: bool ref * + expr: SynExpr * + range: range + + /// First bool indicates if lambda originates from a method. Patterns here are always "simple" + /// Second bool indicates if this is a "later" part of an iterated sequence of lambdas + /// + /// F# syntax: fun pat -> expr + | Lambda of + fromMethod: bool * + inLambdaSeq: bool * + args: SynSimplePats * + body: SynExpr * + range: range + + /// F# syntax: function pat1 -> expr | ... | patN -> exprN + | MatchLambda of + isExnMatch: bool * + keywordRange: range * + matchClauses: SynMatchClause list * + matchSeqPoint: DebugPointForBinding * + range: range + + /// F# syntax: match expr with pat1 -> expr | ... | patN -> exprN + | Match of + matchSeqPoint: DebugPointForBinding * + expr: SynExpr * + clauses: SynMatchClause list * + range: range + + /// F# syntax: do expr + | Do of + expr: SynExpr * + range: range + + /// F# syntax: assert expr + | Assert of + expr: SynExpr * + range: range + + /// F# syntax: f x + /// + /// flag: indicates if the application is syntactically atomic, e.g. f.[1] is atomic, but 'f x' is not + /// isInfix is true for the first app of an infix operator, e.g. 1+2 + /// becomes App(App(+, 1), 2), where the inner node is marked isInfix + | App of + flag: ExprAtomicFlag * + isInfix: bool * + funcExpr: SynExpr * + argExpr: SynExpr * + range: range + + /// F# syntax: expr + | TypeApp of + expr: SynExpr * + lessRange: range * + typeArgs: SynType list * + commaRanges: range list * + greaterRange: range option * + typeArgsRange: range * + range: range + + /// F# syntax: let pat = expr in expr + /// F# syntax: let f pat1 .. patN = expr in expr + /// F# syntax: let rec f pat1 .. patN = expr in expr + /// F# syntax: use pat = expr in expr + | LetOrUse of + isRecursive: bool * + isUse: bool * + bindings: SynBinding list * + body: SynExpr * + range: range + + /// F# syntax: try expr with pat -> expr + | TryWith of + tryExpr: SynExpr * + tryRange: range * + withCases: SynMatchClause list * + withRange: range * + range: range * + trySeqPoint: DebugPointAtTry * + withSeqPoint: DebugPointAtWith + + /// F# syntax: try expr finally expr + | TryFinally of + tryExpr: SynExpr * + finallyExpr: SynExpr * + range: range * + trySeqPoint: DebugPointAtTry * + finallySeqPoint: DebugPointAtFinally + + /// F# syntax: lazy expr + | Lazy of + expr: SynExpr * + range: range + + /// F# syntax: expr; expr + /// + /// isTrueSeq: false indicates "let v = a in b; v" + | Sequential of + seqPoint: DebugPointAtSequential * + isTrueSeq: bool * + expr1: SynExpr * + expr2: SynExpr * + range: range + + /// F# syntax: if expr then expr + /// F# syntax: if expr then expr else expr + | IfThenElse of + ifExpr: SynExpr * + thenExpr: SynExpr * + elseExpr: SynExpr option * + spIfToThen: DebugPointForBinding * + isFromErrorRecovery: bool * + ifToThenRange: range * + range: range + + /// F# syntax: ident + /// Optimized representation for SynExpr.LongIdent (false, [id], id.idRange) + | Ident of + ident: Ident + + /// F# syntax: ident.ident...ident + /// + /// isOptional: true if preceded by a '?' for an optional named parameter + /// altNameRefCell: Normally 'None' except for some compiler-generated + /// variables in desugaring pattern matching. See SynSimplePat.Id + | LongIdent of + isOptional: bool * + longDotId: LongIdentWithDots * + altNameRefCell: SynSimplePatAlternativeIdInfo ref option * + range: range + + /// F# syntax: ident.ident...ident <- expr + | LongIdentSet of + longDotId: LongIdentWithDots * + expr: SynExpr * + range: range + + /// F# syntax: expr.ident.ident + | DotGet of + expr: SynExpr * + rangeOfDot: range * + longDotId: LongIdentWithDots * + range: range + + /// F# syntax: expr.ident...ident <- expr + | DotSet of + targetExpe: SynExpr * + longDotId: LongIdentWithDots * + rhsExpr: SynExpr * + range: range + + /// F# syntax: expr <- expr + | Set of + targetExpr: SynExpr * + rhsExpr: SynExpr * + range: range + + /// F# syntax: expr.[expr, ..., expr] + | DotIndexedGet of + objectExpr: SynExpr * + indexExprs: SynIndexerArg list * + dotRange: range * + range: range + + /// F# syntax: expr.[expr, ..., expr] <- expr + | DotIndexedSet of + objectExpr: SynExpr * + indexExprs: SynIndexerArg list * + valueExpr: SynExpr * + leftOfSetRange: range * + dotRange: range * + range: range + + /// F# syntax: Type.Items(e1) <- e2, rarely used named-property-setter notation, e.g. Foo.Bar.Chars(3) <- 'a' + | NamedIndexedPropertySet of + longDotId: LongIdentWithDots * + expr1: SynExpr * + expr2: SynExpr * + range: range + + /// F# syntax: expr.Items (e1) <- e2, rarely used named-property-setter notation, e.g. (stringExpr).Chars(3) <- 'a' + | DotNamedIndexedPropertySet of + targetExpr: SynExpr * + longDotId: LongIdentWithDots * + argExpr: SynExpr * + rhsExpr: SynExpr * + range: range + + /// F# syntax: expr :? type + | TypeTest of + expr: SynExpr * + targetType: SynType * + range: range + + /// F# syntax: expr :> type + | Upcast of + expr: SynExpr * + targetType: SynType * + range: range + + /// F# syntax: expr :?> type + | Downcast of + expr: SynExpr * + targetType: SynType * + range: range + + /// F# syntax: upcast expr + | InferredUpcast of + expr: SynExpr * + range: range + + /// F# syntax: downcast expr + | InferredDowncast of + expr: SynExpr * + range: range + + /// F# syntax: null + | Null of + range: range + + /// F# syntax: &expr, &&expr + | AddressOf of + isByref: bool * + expr: SynExpr * + opRange: range * + range: range + + /// F# syntax: ((typar1 or ... or typarN): (member-dig) expr) + | TraitCall of + supportTys: SynTypar list * + traitSig: SynMemberSig * + argExpr: SynExpr * + range: range + + /// F# syntax: ... in ... + /// Computation expressions only, based on JOIN_IN token from lex filter + | JoinIn of + lhsExpr: SynExpr * + lhsRange: range * + rhsExpr: SynExpr * + range: range + + /// Used in parser error recovery and internally during type checking for translating computation expressions. + | ImplicitZero of + range: range + + /// Used internally during type checking for translating computation expressions. + | SequentialOrImplicitYield of + seqPoint:DebugPointAtSequential * + expr1:SynExpr * + expr2:SynExpr * + ifNotStmt:SynExpr * + range:range + + /// F# syntax: yield expr + /// F# syntax: return expr + /// Computation expressions only + | YieldOrReturn of + flags: (bool * bool) * + expr: SynExpr * + range: range + + /// F# syntax: yield! expr + /// F# syntax: return! expr + /// Computation expressions only + | YieldOrReturnFrom of + flags: (bool * bool) * + expr: SynExpr * + range: range + + /// F# syntax: let! pat = expr in expr + /// F# syntax: use! pat = expr in expr + /// F# syntax: let! pat = expr and! ... and! ... and! pat = expr in expr + /// Computation expressions only + | LetOrUseBang of + bindSeqPoint: DebugPointForBinding * + isUse: bool * + isFromSource: bool * + pat: SynPat * + rhs: SynExpr * + andBangs:(DebugPointForBinding * bool * bool * SynPat * SynExpr * range) list * + body:SynExpr * + range: range + + /// F# syntax: match! expr with pat1 -> expr | ... | patN -> exprN + | MatchBang of + matchSeqPoint: DebugPointForBinding * + expr: SynExpr * + clauses: SynMatchClause list * + range: range + + /// F# syntax: do! expr + /// Computation expressions only + | DoBang of + expr: SynExpr * + range: range + + /// Only used in FSharp.Core + | LibraryOnlyILAssembly of + ilCode: ILInstr array * + typeArgs: SynType list * + args: SynExpr list * + retTy: SynType list * + range: range + + /// Only used in FSharp.Core + | LibraryOnlyStaticOptimization of + constraints: SynStaticOptimizationConstraint list * + expr: SynExpr * + optimizedExpr: SynExpr * + range: range + + /// Only used in FSharp.Core + | LibraryOnlyUnionCaseFieldGet of + expr: SynExpr * + longId: LongIdent * + fieldNum: int * + range: range + + /// Only used in FSharp.Core + | LibraryOnlyUnionCaseFieldSet of + expr: SynExpr * + longId: LongIdent * + fieldNum: int * + rhsExpr: SynExpr * + range: range + + /// Inserted for error recovery + | ArbitraryAfterError of + debugStr: string * + range: range + + /// Inserted for error recovery + | FromParseError of + expr: SynExpr * + range: range + + /// Inserted for error recovery when there is "expr." and missing tokens or error recovery after the dot + | DiscardAfterMissingQualificationAfterDot of + expr: SynExpr * + range: range + + /// 'use x = fixed expr' + | Fixed of + expr: SynExpr * + range: range + + /// Gets the syntax range of this constuct + member e.Range = + match e with + | SynExpr.Paren (_, leftParenRange, rightParenRange, r) -> + match rightParenRange with + | Some rightParenRange when leftParenRange.FileIndex <> rightParenRange.FileIndex -> leftParenRange + | _ -> r + | SynExpr.Quote (range=m) + | SynExpr.Const (range=m) + | SynExpr.Typed (range=m) + | SynExpr.Tuple (range=m) + | SynExpr.AnonRecd (range=m) + | SynExpr.ArrayOrList (range=m) + | SynExpr.Record (range=m) + | SynExpr.New (range=m) + | SynExpr.ObjExpr (range=m) + | SynExpr.While (range=m) + | SynExpr.For (range=m) + | SynExpr.ForEach (range=m) + | SynExpr.CompExpr (range=m) + | SynExpr.ArrayOrListOfSeqExpr (range=m) + | SynExpr.Lambda (range=m) + | SynExpr.Match (range=m) + | SynExpr.MatchLambda (range=m) + | SynExpr.Do (range=m) + | SynExpr.Assert (range=m) + | SynExpr.App (range=m) + | SynExpr.TypeApp (range=m) + | SynExpr.LetOrUse (range=m) + | SynExpr.TryWith (range=m) + | SynExpr.TryFinally (range=m) + | SynExpr.Sequential (range=m) + | SynExpr.SequentialOrImplicitYield (range=m) + | SynExpr.ArbitraryAfterError (range=m) + | SynExpr.FromParseError (range=m) + | SynExpr.DiscardAfterMissingQualificationAfterDot (range=m) + | SynExpr.IfThenElse (range=m) + | SynExpr.LongIdent (range=m) + | SynExpr.LongIdentSet (range=m) + | SynExpr.NamedIndexedPropertySet (range=m) + | SynExpr.DotIndexedGet (range=m) + | SynExpr.DotIndexedSet (range=m) + | SynExpr.DotGet (range=m) + | SynExpr.DotSet (range=m) + | SynExpr.Set (range=m) + | SynExpr.DotNamedIndexedPropertySet (range=m) + | SynExpr.LibraryOnlyUnionCaseFieldGet (range=m) + | SynExpr.LibraryOnlyUnionCaseFieldSet (range=m) + | SynExpr.LibraryOnlyILAssembly (range=m) + | SynExpr.LibraryOnlyStaticOptimization (range=m) + | SynExpr.TypeTest (range=m) + | SynExpr.Upcast (range=m) + | SynExpr.AddressOf (range=m) + | SynExpr.Downcast (range=m) + | SynExpr.JoinIn (range=m) + | SynExpr.InferredUpcast (range=m) + | SynExpr.InferredDowncast (range=m) + | SynExpr.Null (range=m) + | SynExpr.Lazy (range=m) + | SynExpr.TraitCall (range=m) + | SynExpr.ImplicitZero (range=m) + | SynExpr.YieldOrReturn (range=m) + | SynExpr.YieldOrReturnFrom (range=m) + | SynExpr.LetOrUseBang (range=m) + | SynExpr.MatchBang (range=m) + | SynExpr.DoBang (range=m) + | SynExpr.Fixed (range=m) -> m + | SynExpr.Ident id -> id.idRange + + /// Get the Range ignoring any (parse error) extra trailing dots + member e.RangeSansAnyExtraDot = + match e with + | SynExpr.DotGet (expr, _, lidwd, m) -> + if lidwd.ThereIsAnExtraDotAtTheEnd then + unionRanges expr.Range lidwd.RangeSansAnyExtraDot + else + m + | SynExpr.LongIdent (_, lidwd, _, _) -> lidwd.RangeSansAnyExtraDot + | SynExpr.DiscardAfterMissingQualificationAfterDot (expr, _) -> expr.Range + | _ -> e.Range + + /// Attempt to get the range of the first token or initial portion only - this + /// is ad-hoc, just a cheap way to improve a certain 'query custom operation' error range + member e.RangeOfFirstPortion = + match e with + // these are better than just .Range, and also commonly applicable inside queries + | SynExpr.Paren (_, m, _, _) -> m + | SynExpr.Sequential (_, _, e1, _, _) + | SynExpr.SequentialOrImplicitYield (_, e1, _, _, _) + | SynExpr.App (_, _, e1, _, _) -> + e1.RangeOfFirstPortion + | SynExpr.ForEach (_, _, _, pat, _, _, r) -> + let start = r.Start + let e = (pat.Range: range).Start + mkRange r.FileName start e + | _ -> e.Range + + /// Indicates if this expression arises from error recovery + member this.IsArbExprAndThusAlreadyReportedError = + match this with + | SynExpr.ArbitraryAfterError _ -> true + | _ -> false + +/// Represents a syntax tree for an F# indexer expression argument +[] +type SynIndexerArg = + /// A two-element range indexer argument + | Two of + expr1: SynExpr * + fromEnd1: bool * + expr2: SynExpr * + fromEnd2: bool * + range1: range * + range2: range + + /// A one-element item indexer argument + | One of + expr: SynExpr * + fromEnd: bool * range + + /// Gets the syntax range of this constuct + member x.Range = match x with Two (e1, _, e2, _, _, _) -> unionRanges e1.Range e2.Range | One (e, _, _) -> e.Range + + /// Get the one or two expressions as a list + member x.Exprs = match x with Two (e1, _, e2, _, _, _) -> [e1;e2] | One (e, _, _) -> [e] + +/// Represents a syntax tree for simple F# patterns +[] +type SynSimplePat = + + /// Indicates a simple pattern variable. + /// + /// altNameRefCell: + /// Normally 'None' except for some compiler-generated variables in desugaring pattern matching. + /// Pattern processing sets this reference for hidden variable introduced + /// by desugaring pattern matching in arguments. The info indicates an + /// alternative (compiler generated) identifier to be used because the + /// name of the identifier is already bound. + /// + /// isCompilerGenerated: true if a compiler generated name + /// isThisVar: true if 'this' variable in member + /// isOptArg: true if a '?' is in front of the name + | Id of + ident: Ident * + altNameRefCell: SynSimplePatAlternativeIdInfo ref option * + isCompilerGenerated: bool * + isThisVar: bool * + isOptArg: bool * + range: range + + /// A type annotated simple pattern + | Typed of + pat: SynSimplePat * + targetType: SynType * + range: range + + /// An attributed simple pattern + | Attrib of + pat: SynSimplePat * + attributes: SynAttributes * + range: range + +/// Represents the alternative identifier for a simple pattern +type SynSimplePatAlternativeIdInfo = + + /// We have not decided to use an alternative name in the pattern and related expression + | Undecided of Ident + + /// We have decided to use an alternative name in the pattern and related expression + | Decided of Ident + +/// Represents a syntax tree for a static optimization constraint in the F# core library +[] +type SynStaticOptimizationConstraint = + + /// A static optimization conditional that activates for a particular type instantiation + | WhenTyparTyconEqualsTycon of + typar: SynTypar * + rhsType: SynType * + range: range + + /// A static optimization conditional that activates for a struct + | WhenTyparIsStruct of + typar: SynTypar * + range: range + +/// Represents a simple set of variable bindings a, (a, b) or (a: Type, b: Type) at a lambda, +/// function definition or other binding point, after the elimination of pattern matching +/// from the construct, e.g. after changing a "function pat1 -> rule1 | ..." to a +/// "fun v -> match v with ..." +[] +type SynSimplePats = + + | SimplePats of + pats: SynSimplePat list * + range: range + + | Typed of + pats: SynSimplePats * + targetType: SynType * + range: range + +/// Represents a syntax tree for argumments patterns +type SynArgPats = + | Pats of + pats: SynPat list + + | NamePatPairs of + pats: (Ident * SynPat) list * + range: range + +/// Represents a syntax tree for an F# pattern +[] +type SynPat = + + /// A constant in a pattern + | Const of + constant: SynConst * + range: range + + /// A wildcard '_' in a pattern + | Wild of + range: range + + /// A named pattern 'pat as ident' + | Named of + pat: SynPat * + ident: Ident * + isSelfIdentifier: bool * + accessibility: SynAccess option * + range: range + + /// A typed pattern 'pat : type' + | Typed of + pat: SynPat * + targetType: SynType * + range: range + + /// An attributed pattern, used in argument or declaration position + | Attrib of + pat: SynPat * + attributes: SynAttributes * + range: range + + /// A disjunctive pattern 'pat1 | pat2' + | Or of + lhsPat: SynPat * + rhsPat: SynPat * + range: range + + /// A conjunctive pattern 'pat1 & pat2' + | Ands of + pats: SynPat list * + range: range + + /// A long identifier pattern possibly with argument patterns + | LongIdent of + longDotId: LongIdentWithDots * + extraId: Ident option * // holds additional ident for tooling + typarDecls: SynValTyparDecls option * // usually None: temporary used to parse "f<'a> x = x" + argPats: SynArgPats * + accessibility: SynAccess option * + range: range + + /// A tuple pattern + | Tuple of + isStruct: bool * + elementPats: SynPat list * + range: range + + /// A parentehsized pattern + | Paren of + pat: SynPat * + range: range + + /// An array or a list as a pattern + | ArrayOrList of + isArray: bool * + elementPats: SynPat list * + range: range + + /// A record pattern + | Record of + fieldPats: ((LongIdent * Ident) * SynPat) list * + range: range + + /// The 'null' pattern + | Null of + range: range + + /// '?id' -- for optional argument names + | OptionalVal of + ident: Ident * + range: range + + /// A type test pattern ':? type ' + | IsInst of + pat: SynType * + range: range + + /// <@ expr @>, used for active pattern arguments + | QuoteExpr of + expr: SynExpr * + range: range + + /// Deprecated character range: ranges + | DeprecatedCharRange of + startChar: char * + endChar: char * + range: range + + /// Used internally in the type checker + | InstanceMember of + thisId: Ident * + memberId: Ident * + toolingId: Ident option * // holds additional ident for tooling + accessibility: SynAccess option * + range: range + + /// A pattern arising from a parse error + | FromParseError of + pat: SynPat * + range: range + + /// Gets the syntax range of this constuct + member p.Range = + match p with + | SynPat.Const (range=m) + | SynPat.Wild (range=m) + | SynPat.Named (range=m) + | SynPat.Or (range=m) + | SynPat.Ands (range=m) + | SynPat.LongIdent (range=m) + | SynPat.ArrayOrList (range=m) + | SynPat.Tuple (range=m) + | SynPat.Typed (range=m) + | SynPat.Attrib (range=m) + | SynPat.Record (range=m) + | SynPat.DeprecatedCharRange (range=m) + | SynPat.Null (range=m) + | SynPat.IsInst (range=m) + | SynPat.QuoteExpr (range=m) + | SynPat.InstanceMember (range=m) + | SynPat.OptionalVal (range=m) + | SynPat.Paren (range=m) + | SynPat.FromParseError (range=m) -> m + +/// Represents a set of bindings that implement an interface +[] +type SynInterfaceImpl = + | InterfaceImpl of SynType * SynBinding list * range: range + +/// Represents a clause in a 'match' expression +[] +type SynMatchClause = + | Clause of + pat: SynPat * + whenExpr: SynExpr option * + resultExpr: SynExpr * + range: range * + spInfo: DebugPointForTarget + + /// Gets the syntax range of part of this constuct + member this.RangeOfGuardAndRhs = + match this with + | Clause(_, eo, e, _, _) -> + match eo with + | None -> e.Range + | Some x -> unionRanges e.Range x.Range + + /// Gets the syntax range of this constuct + member this.Range = + match this with + | Clause(_, eo, e, m, _) -> + match eo with + | None -> unionRanges e.Range m + | Some x -> unionRanges (unionRanges e.Range m) x.Range + +/// Represents an attribute +[] +type SynAttribute = + { /// The name of the type for the attribute + TypeName: LongIdentWithDots + + /// The argument of the attribute, perhaps a tuple + ArgExpr: SynExpr + + /// Target specifier, e.g. "assembly", "module", etc. + Target: Ident option + + /// Is this attribute being applied to a property getter or setter? + AppliesToGetterAndSetter: bool + + /// The syntax range of the attribute + Range: range + } + +/// List of attributes enclosed in [< ... >]. +type SynAttributeList = + { + /// The list of attributes + Attributes: SynAttribute list + + /// The syntax range of the list of attributes + Range: range + } + +type SynAttributes = SynAttributeList list + +/// Represents extra information about the declaration of a value +[] +type SynValData = + | SynValData of MemberFlags option * SynValInfo * Ident option + +/// Represents a binding for a 'let' or 'member' declaration +[] +type SynBinding = + | Binding of + accessibility: SynAccess option * + kind: SynBindingKind * + mustInline: bool * + isMutable: bool * + attributes: SynAttributes * + xmlDoc: PreXmlDoc * + valData: SynValData * + headPat: SynPat * + returnInfo: SynBindingReturnInfo option * + expr: SynExpr * + range: range * + seqPoint: DebugPointForBinding + + // no member just named "Range", as that would be confusing: + // - for everything else, the 'range' member that appears last/second-to-last is the 'full range' of the whole tree construct + // - but for Binding, the 'range' is only the range of the left-hand-side, the right-hand-side range is in the SynExpr + // - so we use explicit names to avoid confusion + member x.RangeOfBindingSansRhs = let (Binding(range=m)) = x in m + + member x.RangeOfBindingAndRhs = let (Binding(expr=e; range=m)) = x in unionRanges e.Range m + + member x.RangeOfHeadPat = let (Binding(headPat=headPat)) = x in headPat.Range + +/// Represents the return information in a binding for a 'let' or 'member' declaration +[] +type SynBindingReturnInfo = + SynBindingReturnInfo of + typeName: SynType * + range: range * + attributes: SynAttributes + +/// Represents the flags for a 'member' declaration +[] +type MemberFlags = + { + /// The member is an instance member (non-static) + IsInstance: bool + + /// The member is a dispatch slot + IsDispatchSlot: bool + + /// The member is an 'override' or explicit interface implementation + IsOverrideOrExplicitImpl: bool + + /// The member is 'final' + IsFinal: bool + + /// The kind of the member + MemberKind: MemberKind + } + +/// Note the member kind is actually computed partially by a syntax tree transformation in tc.fs +[] +type MemberKind = + + /// The member is a class initializer + | ClassConstructor + + /// The member is a object model constructor + | Constructor + + /// The member kind is not yet determined + | Member + + /// The member kind is property getter + | PropertyGet + + /// The member kind is property setter + | PropertySet + + /// An artificial member kind used prior to the point where a + /// get/set property is split into two distinct members. + | PropertyGetSet + +/// Represents the syntax tree for a member signature (used in signature files, abstract member declarations +/// and member constraints) +[] +type SynMemberSig = + + /// A member definition in a type in a signature file + | Member of + memberSig: SynValSig * + flags: MemberFlags * + range: range + + /// An interface definition in a type in a signature file + | Interface of + interfaceType: SynType * + range: range + + /// An 'inherit' definition in a type in a signature file + | Inherit of + inheritedType: SynType * + range: range + + /// A 'val' definition in a type in a signature file + | ValField of + field: SynField * + range: range + + /// A nested type definition in a signature file (an unimplemented feature) + | NestedType of + nestedType: SynTypeDefnSig * + range: range + +/// Represents the kind of a type definition whether explicit or inferred +[] +type SynTypeDefnKind = + | TyconUnspecified + | TyconClass + | TyconInterface + | TyconStruct + | TyconRecord + | TyconUnion + | TyconAbbrev + | TyconHiddenRepr + | TyconAugmentation + | TyconILAssemblyCode + | TyconDelegate of SynType * SynValInfo + +/// Represents the syntax tree for the core of a simple type definition, in either signature +/// or implementation. +[] +type SynTypeDefnSimpleRepr = + + /// A union type definition, type X = A | B + | Union of + accessibility: SynAccess option * + unionCases: SynUnionCase list * + range: range + + /// An enum type definition, type X = A = 1 | B = 2 + | Enum of + cases: SynEnumCase list * + range: range + + /// A record type definition, type X = { A: int; B: int } + | Record of + accessibility: SynAccess option * + recordFields: SynField list * + range: range + + /// An object oriented type definition. This is not a parse-tree form, but represents the core + /// type representation which the type checker splits out from the "ObjectModel" cases of type definitions. + | General of + kind: SynTypeDefnKind * + inherits: (SynType * range * Ident option) list * + slotsigs: (SynValSig * MemberFlags) list * + fields: SynField list * + isConcrete: bool * + isIncrClass: bool * + implicitCtorSynPats: SynSimplePats option * + range: range + + /// A type defined by using an IL assembly representation. Only used in FSharp.Core. + /// + /// F# syntax: "type X = (# "..."#) + | LibraryOnlyILAssembly of + ilType: ILType * + range: range + + /// A type abbreviation, "type X = A.B.C" + | TypeAbbrev of + detail: ParserDetail * + rhsType: SynType * + range: range + + /// An abstract definition, "type X" + | None of + range: range + + /// An exception definition, "exception E = ..." + | Exception of + exnRepr: SynExceptionDefnRepr + + /// Gets the syntax range of this constuct + member this.Range = + match this with + | Union (range=m) + | Enum (range=m) + | Record (range=m) + | General (range=m) + | LibraryOnlyILAssembly (range=m) + | TypeAbbrev (range=m) + | None (range=m) -> m + | Exception t -> t.Range + +/// Represents the syntax tree for one case in an enum definition. +[] +type SynEnumCase = + + | EnumCase of + attributes: SynAttributes * + ident: Ident * SynConst * + xmldoc: PreXmlDoc * + range: range + + /// Gets the syntax range of this constuct + member this.Range = + match this with + | EnumCase (range=m) -> m + +/// Represents the syntax tree for one case in a union definition. +[] +type SynUnionCase = + + | UnionCase of + attributes: SynAttributes * + ident: Ident * + caseType: SynUnionCaseType * + xmlDoc: PreXmlDoc * + accessibility: SynAccess option * + range: range + + /// Gets the syntax range of this constuct + member this.Range = + match this with + | UnionCase (range=m) -> m + +/// Represents the syntax tree for the right-hand-side of union definition, excluding members, +/// in either a signature or implementation. +[] +type SynUnionCaseType = + + /// Normal style declaration + | UnionCaseFields of cases: SynField list + + /// Full type spec given by 'UnionCase: ty1 * tyN -> rty'. Only used in FSharp.Core, otherwise a warning. + | UnionCaseFullType of SynType * SynValInfo + +/// Represents the syntax tree for the right-hand-side of a type definition in a signature. +/// Note: in practice, using a discriminated union to make a distinction between +/// "simple" types and "object oriented" types is not particularly useful. +[] +type SynTypeDefnSigRepr = + + /// Indicates the right right-hand-side is a class, struct, interface or other object-model type + | ObjectModel of + kind: SynTypeDefnKind * + memberSigs: SynMemberSig list * + range: range + + /// Indicates the right right-hand-side is a record, union or other simple type. + | Simple of + repr: SynTypeDefnSimpleRepr * + range: range + + | Exception of SynExceptionDefnRepr + + /// Gets the syntax range of this constuct + member this.Range = + match this with + | ObjectModel (range=m) + | Simple (range=m) -> m + | Exception e -> e.Range + +/// Represents the syntax tree for a type definition in a signature +[] +type SynTypeDefnSig = + + /// The information for a type definition in a signature + | TypeDefnSig of SynComponentInfo * SynTypeDefnSigRepr * SynMemberSig list * range: range + +/// Represents the syntax tree for a field declaration in a record or class +[] +type SynField = + | Field of + attributes: SynAttributes * + isStatic: bool * + idOpt: Ident option * + fieldType: SynType * + isMutable: bool * + xmlDoc: PreXmlDoc * + accessibility: SynAccess option * + range: range + +/// Represents the syntax tree associated with the name of a type definition or module +/// in signature or implementation. +/// +/// This includes the name, attributes, type parameters, constraints, documentation and accessibility +/// for a type definition or module. For modules, entries such as the type parameters are +/// always empty. +[] +type SynComponentInfo = + | ComponentInfo of + attributes: SynAttributes * + typeParams: SynTyparDecl list * + constraints: SynTypeConstraint list * + longId: LongIdent * + xmlDoc: PreXmlDoc * + preferPostfix: bool * + accessibility: SynAccess option * + range: range + + /// Gets the syntax range of this constuct + member this.Range = + match this with + | ComponentInfo (range=m) -> m + +/// Represents the syntax tree for a 'val' definition in an abstract slot or a signature file +[] +type SynValSig = + | ValSpfn of + attributes: SynAttributes * + ident: Ident * + explicitValDecls: SynValTyparDecls * + synType: SynType * + arity: SynValInfo * + isInline: bool * + isMutable: bool * + xmlDoc: PreXmlDoc * + accessibility: SynAccess option * + synExpr: SynExpr option * + range: range + + member x.RangeOfId = let (ValSpfn(ident=id)) = x in id.idRange + + member x.SynInfo = let (ValSpfn(arity=v)) = x in v + + member x.SynType = let (ValSpfn(synType=ty)) = x in ty + +/// The argument names and other metadata for a member or function +[] +type SynValInfo = + + /// SynValInfo(curriedArgInfos, returnInfo) + | SynValInfo of SynArgInfo list list * SynArgInfo + + member x.ArgInfos = (let (SynValInfo(args, _)) = x in args) + +/// Represents the argument names and other metadata for a parameter for a member or function +[] +type SynArgInfo = + + | SynArgInfo of + attributes: SynAttributes * + optional: bool * + ident: Ident option + +/// Represents the names and other metadata for the type parameters for a member or function +[] +type SynValTyparDecls = + + | SynValTyparDecls of + typars: SynTyparDecl list * + canInfer: bool * + constraints: SynTypeConstraint list + +/// Represents the syntactic elements associated with the "return" of a function or method. +type SynReturnInfo = + | SynReturnInfo of returnType: (SynType * SynArgInfo) * range: range + +/// Represents the right hand side of an exception declaration 'exception E = ... ' +[] +type SynExceptionDefnRepr = + + | SynExceptionDefnRepr of + attributes: SynAttributes * + caseName: SynUnionCase * + longId: LongIdent option * + xmlDoc: PreXmlDoc * + accessibility: SynAccess option * + range: range + + /// Gets the syntax range of this constuct + member this.Range = match this with SynExceptionDefnRepr (range=m) -> m + +/// Represents the right hand side of an exception declaration 'exception E = ... ' plus +/// any member definitions for the exception +[] +type SynExceptionDefn = + + | SynExceptionDefn of + exnRepr: SynExceptionDefnRepr * + members: SynMemberDefns * + range: range + + /// Gets the syntax range of this constuct + member this.Range = + match this with + | SynExceptionDefn (range=m) -> m + +/// Represents the right hand side of a type or exception declaration 'type C = ... ' plus +/// any additional member definitions for the type +[] +type SynTypeDefnRepr = + + /// An object model type definition (class or interface) + | ObjectModel of + kind: SynTypeDefnKind * + members: SynMemberDefns * + range: range + + /// A simple type definition (record, union, abbreviation) + | Simple of + simpleRepr: SynTypeDefnSimpleRepr * + range: range + + /// An exception definition + | Exception of + exnRepr: SynExceptionDefnRepr + + /// Gets the syntax range of this constuct + member this.Range = + match this with + | ObjectModel (range=m) + | Simple (range=m) -> m + | Exception t -> t.Range + +/// Represents a type or exception declaration 'type C = ... ' plus +/// any additional member definitions for the type +[] +type SynTypeDefn = + | TypeDefn of + typeInfo: SynComponentInfo * + typeRepr: SynTypeDefnRepr * + members: SynMemberDefns * + range: range + + /// Gets the syntax range of this constuct + member this.Range = + match this with + | TypeDefn (range=m) -> m + +/// Represents a definition element within a type definition, e.g. 'member ... ' +[] +type SynMemberDefn = + + /// An 'open' definition within a type + | Open of + longId: LongIdent * + range: range + + /// A 'member' definition within a type + | Member of + memberDefn: SynBinding * + range: range + + /// An implicit constructor definition + | ImplicitCtor of + accessibility: SynAccess option * + attributes: SynAttributes * + ctorArgs: SynSimplePats * + selfIdentifier: Ident option * + range: range + + /// An implicit inherit definition, 'inherit (args...) as base' + | ImplicitInherit of + inheritType: SynType * + inheritArgs: SynExpr * + inheritAlias: Ident option * + range: range + + /// A 'let' definition within a class + | LetBindings of + bindings: SynBinding list * + isStatic: bool * + isRecursive: bool * + range: range + + /// An abstract slot definition within a class or interface + | AbstractSlot of + slotSig: SynValSig * + flags: MemberFlags * + range: range + + /// An interface implementation definition within a class + | Interface of + interfaceType: SynType * + members: SynMemberDefns option * + range: range + + /// An 'inherit' definition within a class + | Inherit of + baseType: SynType * + asIdent: Ident option * + range: range + + /// A 'val' definition within a class + | ValField of + fieldInfo: SynField * + range: range + + /// A nested type definition, a feature that is not implemented + | NestedType of + typeDefn: SynTypeDefn * + accessibility: SynAccess option * + range: range + + /// An auto-property definition, F# syntax: 'member val X = expr' + | AutoProperty of + attributes: SynAttributes * + isStatic: bool * + ident: Ident * + typeOpt: SynType option * + propKind: MemberKind * + memberFlags:(MemberKind -> MemberFlags) * + xmlDoc: PreXmlDoc * + accessibility: SynAccess option * + synExpr: SynExpr * + getSetRange: range option * + range: range + + /// Gets the syntax range of this constuct + member d.Range = + match d with + | SynMemberDefn.Member (range=m) + | SynMemberDefn.Interface (range=m) + | SynMemberDefn.Open (range=m) + | SynMemberDefn.LetBindings (range=m) + | SynMemberDefn.ImplicitCtor (range=m) + | SynMemberDefn.ImplicitInherit (range=m) + | SynMemberDefn.AbstractSlot (range=m) + | SynMemberDefn.Inherit (range=m) + | SynMemberDefn.ValField (range=m) + | SynMemberDefn.AutoProperty (range=m) + | SynMemberDefn.NestedType (range=m) -> m + +type SynMemberDefns = SynMemberDefn list + +/// Represents a definition within a module +[] +type SynModuleDecl = + + /// A module abbreviation definition 'module X = A.B.C' + | ModuleAbbrev of + ident: Ident * + longId: LongIdent * + range: range + + /// A nested module definition 'module X = ...' + | NestedModule of + moduleInfo: SynComponentInfo * + isRecursive: bool * + decls: SynModuleDecl list * + isContinuing: bool * + range: range + + /// A 'let' definition within a module + | Let of + isRecursive: bool * + bindings: SynBinding list * + range: range + + /// A 'do expr' within a module + | DoExpr of + spInfo: DebugPointForBinding * + expr: SynExpr * + range: range + + /// One or more 'type' definitions within a module + | Types of + typeDefns: SynTypeDefn list * + range: range + + /// An 'exception' definition within a module + | Exception of + exnDefn: SynExceptionDefn * + range: range + + /// An 'open' definition within a module + | Open of + longDotId: LongIdentWithDots * + range: range + + /// An attribute definition within a module, for assembly and .NET module attributes + | Attributes of + attributes: SynAttributes * + range: range + + /// A hash directive within a module + | HashDirective of + hashDirective: ParsedHashDirective * + range: range + + /// A namespace fragment within a module + | NamespaceFragment of + fragment: SynModuleOrNamespace + + /// Gets the syntax range of this constuct + member d.Range = + match d with + | SynModuleDecl.ModuleAbbrev (range=m) + | SynModuleDecl.NestedModule (range=m) + | SynModuleDecl.Let (range=m) + | SynModuleDecl.DoExpr (range=m) + | SynModuleDecl.Types (range=m) + | SynModuleDecl.Exception (range=m) + | SynModuleDecl.Open (range=m) + | SynModuleDecl.HashDirective (range=m) + | SynModuleDecl.NamespaceFragment (SynModuleOrNamespace (range=m)) + | SynModuleDecl.Attributes (range=m) -> m + +/// Represents the right hand side of an exception definition in a signature file +[] +type SynExceptionSig = + | SynExceptionSig of + exnRepr: SynExceptionDefnRepr * + members: SynMemberSig list * + range: range + +/// Represents a definition within a module or namespace in a signature file +[] +type SynModuleSigDecl = + + /// A module abbreviation definition within a module or namespace in a signature file + | ModuleAbbrev of + ident: Ident * + longId: LongIdent * + range: range + + /// A nested module definition within a module or namespace in a signature file + | NestedModule of + moduleInfo: SynComponentInfo * + isRecursive: bool * + moduleDecls: SynModuleSigDecl list * + range: range + + /// A 'val' definition within a module or namespace in a signature file, corresponding + /// to a 'let' definition in the implementation + | Val of + valSig: SynValSig * range: range + + /// A set of one or more type definitions within a module or namespace in a signature file + | Types of + types: SynTypeDefnSig list * + range: range + + /// An exception definition within a module or namespace in a signature file + | Exception of + exnSig: SynExceptionSig * + range: range + + /// An 'open' definition within a module or namespace in a signature file + | Open of + longId: LongIdent * + range: range + + /// A hash directive within a module or namespace in a signature file + | HashDirective of + hashDirective: ParsedHashDirective * + range: range + + /// A namespace fragment within a namespace in a signature file + | NamespaceFragment of + SynModuleOrNamespaceSig + + /// Gets the syntax range of this constuct + member d.Range = + match d with + | SynModuleSigDecl.ModuleAbbrev (range=m) + | SynModuleSigDecl.NestedModule (range=m) + | SynModuleSigDecl.Val (range=m) + | SynModuleSigDecl.Types (range=m) + | SynModuleSigDecl.Exception (range=m) + | SynModuleSigDecl.Open (range=m) + | SynModuleSigDecl.NamespaceFragment (SynModuleOrNamespaceSig(range=m)) + | SynModuleSigDecl.HashDirective (range=m) -> m + +/// Represents the kind of a module or namespace definition +[] +type SynModuleOrNamespaceKind = + /// A module is explicitly named 'module N' + | NamedModule + + /// A module is anonymously named, e.g. a script + | AnonModule + + /// A namespace is explicitly declared + | DeclaredNamespace + + /// A namespace is declared 'global' + | GlobalNamespace + + /// Indicates if this is a module definition + member x.IsModule = + match x with + | NamedModule | AnonModule -> true + | _ -> false + +/// Represents the definition of a module or namespace +[] +type SynModuleOrNamespace = + | SynModuleOrNamespace of + longId: LongIdent * + isRecursive: bool * + kind: SynModuleOrNamespaceKind * + decls: SynModuleDecl list * + xmlDoc: PreXmlDoc * + attribs: SynAttributes * + accessibility: SynAccess option * + range: range + + /// Gets the syntax range of this constuct + member this.Range = + match this with + | SynModuleOrNamespace (range=m) -> m + +/// Represents the definition of a module or namespace in a signature file +[] +type SynModuleOrNamespaceSig = + | SynModuleOrNamespaceSig of + longId: LongIdent * + isRecursive: bool * + kind: SynModuleOrNamespaceKind * + decls: SynModuleSigDecl list * + xmlDoc: PreXmlDoc * + attribs: SynAttributes * + accessibility: SynAccess option * + range: range + +/// Represents a parsed hash directive +[] +type ParsedHashDirective = + | ParsedHashDirective of + ident: string * + args: string list * + range: range + +/// Represents the syntax tree for the contents of a parsed implementation file +[] +type ParsedImplFileFragment = + + /// An implementation file which is an anonymous module definition, e.g. a script + | AnonModule of + decls: SynModuleDecl list * + range: range + + /// An implementation file is a named module definition, 'module N' + | NamedModule of + namedModule: SynModuleOrNamespace + + /// An implementation file fragment which declares a namespace fragment + | NamespaceFragment of + longId: LongIdent * + isRecursive: bool * + kind: SynModuleOrNamespaceKind * + decls: SynModuleDecl list * + xmlDoc: PreXmlDoc * + attributes: SynAttributes * + range: range + +/// Represents the syntax tree for the contents of a parsed signature file +[] +type ParsedSigFileFragment = + + /// A signature file which is an anonymous module, e.g. the signature file for the final file in an application + | AnonModule of + decls: SynModuleSigDecl list * + range: range + + /// A signature file which is a module, 'module N' + | NamedModule of + namedModule: SynModuleOrNamespaceSig + + /// A signature file namespace fragment + | NamespaceFragment of + longId: LongIdent * + isRecursive: bool * + kind: SynModuleOrNamespaceKind * + decls: SynModuleSigDecl list * + xmlDoc: PreXmlDoc * + attributes: SynAttributes * + range: range + +/// Represents a parsed syntax tree for an F# Interactive interaction +[] +type ParsedFsiInteraction = + | IDefns of + defns: SynModuleDecl list * + range: range + + | IHash of + hashDirective: ParsedHashDirective * + range: range + +/// Represents a parsed implementation file made up of fragments +[] +type ParsedImplFile = + | ParsedImplFile of + hashDirectives: ParsedHashDirective list * + fragments: ParsedImplFileFragment list + +/// Represents a parsed signature file made up of fragments +[] +type ParsedSigFile = + | ParsedSigFile of + hashDirectives: ParsedHashDirective list * + fragments: ParsedSigFileFragment list + +/// Represents a scoped pragma +[] +type ScopedPragma = + /// A pragma to turn a warning off + | WarningOff of range: range * warningNumber: int + +/// Represents a qualifying name for anonymous module specifications and implementations, +[] +type QualifiedNameOfFile = + | QualifiedNameOfFile of Ident + + /// The name of the file + member x.Text = (let (QualifiedNameOfFile t) = x in t.idText) + + /// The identifier for the name of the file + member x.Id = (let (QualifiedNameOfFile t) = x in t) + + /// Gets the syntax range of this constuct + member x.Range = (let (QualifiedNameOfFile t) = x in t.idRange) + +/// Represents the full syntax tree, file name and other parsing information for an implementation file +[] +type ParsedImplFileInput = + | ParsedImplFileInput of + fileName: string * + isScript: bool * + qualifiedNameOfFile: QualifiedNameOfFile * + scopedPragmas: ScopedPragma list * + hashDirectives: ParsedHashDirective list * + modules: SynModuleOrNamespace list * + isLastCompiland: (bool * bool) + +/// Represents the full syntax tree, file name and other parsing information for a signature file +[] +type ParsedSigFileInput = + | ParsedSigFileInput of + fileName: string * + qualifiedNameOfFile: QualifiedNameOfFile * + scopedPragmas: ScopedPragma list * + hashDirectives: ParsedHashDirective list * + modules: SynModuleOrNamespaceSig list + +/// Represents the syntax tree for a parsed implementation or signature file +[] +type ParsedInput = + /// A parsed implementation file + | ImplFile of ParsedImplFileInput + + /// A parsed signature file + | SigFile of ParsedSigFileInput + + /// Gets the syntax range of this constuct + member inp.Range = + match inp with + | ParsedInput.ImplFile (ParsedImplFileInput (modules=SynModuleOrNamespace(range=m) :: _)) + | ParsedInput.SigFile (ParsedSigFileInput (modules=SynModuleOrNamespaceSig(range=m) :: _)) -> m + | ParsedInput.ImplFile (ParsedImplFileInput (fileName=filename)) + | ParsedInput.SigFile (ParsedSigFileInput (fileName=filename)) -> rangeN filename 0 diff --git a/src/fcs-fable/src/fsharp/SyntaxTreeOps.fs b/src/fcs-fable/src/fsharp/SyntaxTreeOps.fs new file mode 100644 index 0000000000..43d473a137 --- /dev/null +++ b/src/fcs-fable/src/fsharp/SyntaxTreeOps.fs @@ -0,0 +1,726 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +module public FSharp.Compiler.SyntaxTreeOps + +open Internal.Utilities.Text.Parsing + +open FSharp.Compiler +open FSharp.Compiler.AbstractIL +open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features +open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.Range +open FSharp.Compiler.XmlDoc + +//---------------------------------------------------------------------- +// Construct syntactic AST nodes +//----------------------------------------------------------------------- + +type SynArgNameGenerator() = + let mutable count = 0 + let generatedArgNamePrefix = "_arg" + + member __.New() : string = count <- count + 1; generatedArgNamePrefix + string count + member __.Reset() = count <- 0 + +//---------------------------------------------------------------------- +// AST and parsing utilities. +//---------------------------------------------------------------------- + +let ident (s, r) = Ident(s, r) + +let textOfId (id: Ident) = id.idText + +let pathOfLid lid = List.map textOfId lid + +let arrPathOfLid lid = Array.ofList (pathOfLid lid) + +let textOfPath path = String.concat "." path + +let textOfLid lid = textOfPath (pathOfLid lid) + +let rangeOfLid (lid: Ident list) = + match lid with + | [] -> failwith "rangeOfLid" + | [id] -> id.idRange + | h :: t -> unionRanges h.idRange (List.last t).idRange + +let mkSynId m s = Ident(s, m) + +let pathToSynLid m p = List.map (mkSynId m) p + +let mkSynIdGet m n = SynExpr.Ident (mkSynId m n) + +let mkSynLidGet m path n = + let lid = pathToSynLid m path @ [mkSynId m n] + let dots = List.replicate (lid.Length - 1) m + SynExpr.LongIdent (false, LongIdentWithDots(lid, dots), None, m) + +let mkSynIdGetWithAlt m id altInfo = + match altInfo with + | None -> SynExpr.Ident id + | _ -> SynExpr.LongIdent (false, LongIdentWithDots([id], []), altInfo, m) + +let mkSynSimplePatVar isOpt id = SynSimplePat.Id (id, None, false, false, isOpt, id.idRange) + +let mkSynCompGenSimplePatVar id = SynSimplePat.Id (id, None, true, false, false, id.idRange) + +/// Match a long identifier, including the case for single identifiers which gets a more optimized node in the syntax tree. +let (|LongOrSingleIdent|_|) inp = + match inp with + | SynExpr.LongIdent (isOpt, lidwd, altId, _m) -> Some (isOpt, lidwd, altId, lidwd.RangeSansAnyExtraDot) + | SynExpr.Ident id -> Some (false, LongIdentWithDots([id], []), None, id.idRange) + | _ -> None + +let (|SingleIdent|_|) inp = + match inp with + | SynExpr.LongIdent (false, LongIdentWithDots([id], _), None, _) -> Some id + | SynExpr.Ident id -> Some id + | _ -> None + +/// This affects placement of sequence points +let rec IsControlFlowExpression e = + match e with + | SynExpr.ObjExpr _ + | SynExpr.Lambda _ + | SynExpr.LetOrUse _ + | SynExpr.Sequential _ + // Treat "ident { ... }" as a control flow expression + | SynExpr.App (_, _, SynExpr.Ident _, SynExpr.CompExpr _, _) + | SynExpr.IfThenElse _ + | SynExpr.LetOrUseBang _ + | SynExpr.Match _ + | SynExpr.TryWith _ + | SynExpr.TryFinally _ + | SynExpr.For _ + | SynExpr.ForEach _ + | SynExpr.While _ -> true + | SynExpr.Typed (e, _, _) -> IsControlFlowExpression e + | _ -> false + +let mkAnonField (ty: SynType) = Field([], false, None, ty, false, PreXmlDoc.Empty, None, ty.Range) + +let mkNamedField (ident, ty: SynType) = Field([], false, Some ident, ty, false, PreXmlDoc.Empty, None, ty.Range) + +let mkSynPatVar vis (id: Ident) = SynPat.Named (SynPat.Wild id.idRange, id, false, vis, id.idRange) + +let mkSynThisPatVar (id: Ident) = SynPat.Named (SynPat.Wild id.idRange, id, true, None, id.idRange) + +let mkSynPatMaybeVar lidwd vis m = SynPat.LongIdent (lidwd, None, None, SynArgPats.Pats [], vis, m) + +/// Extract the argument for patterns corresponding to the declaration of 'new ... = ...' +let (|SynPatForConstructorDecl|_|) x = + match x with + | SynPat.LongIdent (LongIdentWithDots([_], _), _, _, SynArgPats.Pats [arg], _, _) -> Some arg + | _ -> None + +/// Recognize the '()' in 'new()' +let (|SynPatForNullaryArgs|_|) x = + match x with + | SynPat.Paren(SynPat.Const(SynConst.Unit, _), _) -> Some() + | _ -> None + +let (|SynExprErrorSkip|) (p: SynExpr) = + match p with + | SynExpr.FromParseError (p, _) -> p + | _ -> p + +let (|SynExprParen|_|) (e: SynExpr) = + match e with + | SynExpr.Paren (SynExprErrorSkip e, a, b, c) -> Some (e, a, b, c) + | _ -> None + +let (|SynPatErrorSkip|) (p: SynPat) = + match p with + | SynPat.FromParseError(p, _) -> p + | _ -> p + +/// Push non-simple parts of a patten match over onto the r.h.s. of a lambda. +/// Return a simple pattern and a function to build a match on the r.h.s. if the pattern is complex +let rec SimplePatOfPat (synArgNameGenerator: SynArgNameGenerator) p = + match p with + | SynPat.Typed(p', ty, m) -> + let p2, laterF = SimplePatOfPat synArgNameGenerator p' + SynSimplePat.Typed(p2, ty, m), + laterF + + | SynPat.Attrib(p', attribs, m) -> + let p2, laterF = SimplePatOfPat synArgNameGenerator p' + SynSimplePat.Attrib(p2, attribs, m), + laterF + + | SynPat.Named (SynPat.Wild _, v, thisV, _, m) -> + SynSimplePat.Id (v, None, false, thisV, false, m), + None + + | SynPat.OptionalVal (v, m) -> + SynSimplePat.Id (v, None, false, false, true, m), + None + + | SynPat.Paren (p, _) -> SimplePatOfPat synArgNameGenerator p + + | SynPat.FromParseError (p, _) -> SimplePatOfPat synArgNameGenerator p + + | _ -> + let m = p.Range + let isCompGen, altNameRefCell, id, item = + match p with + | SynPat.LongIdent(LongIdentWithDots([id], _), _, None, SynArgPats.Pats [], None, _) -> + // The pattern is 'V' or some other capitalized identifier. + // It may be a real variable, in which case we want to maintain its name. + // But it may also be a nullary union case or some other identifier. + // In this case, we want to use an alternate compiler generated name for the hidden variable. + let altNameRefCell = Some (ref (Undecided (mkSynId m (synArgNameGenerator.New())))) + let item = mkSynIdGetWithAlt m id altNameRefCell + false, altNameRefCell, id, item + | _ -> + let nm = synArgNameGenerator.New() + let id = mkSynId m nm + let item = mkSynIdGet m nm + true, None, id, item + SynSimplePat.Id (id, altNameRefCell, isCompGen, false, false, id.idRange), + Some (fun e -> + let clause = Clause(p, None, e, m, DebugPointForTarget.No) + SynExpr.Match (NoDebugPointAtInvisibleBinding, item, [clause], clause.Range)) + +let appFunOpt funOpt x = match funOpt with None -> x | Some f -> f x + +let composeFunOpt funOpt1 funOpt2 = match funOpt2 with None -> funOpt1 | Some f -> Some (fun x -> appFunOpt funOpt1 (f x)) + +let rec SimplePatsOfPat synArgNameGenerator p = + match p with + | SynPat.FromParseError (p, _) -> SimplePatsOfPat synArgNameGenerator p + + | SynPat.Typed(p', ty, m) -> + let p2, laterF = SimplePatsOfPat synArgNameGenerator p' + SynSimplePats.Typed(p2, ty, m), + laterF + + | SynPat.Tuple (false, ps, m) + + | SynPat.Paren(SynPat.Tuple (false, ps, m), _) -> + let ps2, laterF = + List.foldBack + (fun (p', rhsf) (ps', rhsf') -> + p':: ps', + (composeFunOpt rhsf rhsf')) + (List.map (SimplePatOfPat synArgNameGenerator) ps) + ([], None) + SynSimplePats.SimplePats (ps2, m), + laterF + + | SynPat.Paren(SynPat.Const (SynConst.Unit, m), _) + + | SynPat.Const (SynConst.Unit, m) -> + SynSimplePats.SimplePats ([], m), + None + + | _ -> + let m = p.Range + let sp, laterF = SimplePatOfPat synArgNameGenerator p + SynSimplePats.SimplePats ([sp], m), laterF + +let PushPatternToExpr synArgNameGenerator isMember pat (rhs: SynExpr) = + let nowPats, laterF = SimplePatsOfPat synArgNameGenerator pat + nowPats, SynExpr.Lambda (isMember, false, nowPats, appFunOpt laterF rhs, rhs.Range) + +let private isSimplePattern pat = + let _nowPats, laterF = SimplePatsOfPat (SynArgNameGenerator()) pat + Option.isNone laterF + +/// "fun (UnionCase x) (UnionCase y) -> body" +/// ==> +/// "fun tmp1 tmp2 -> +/// let (UnionCase x) = tmp1 in +/// let (UnionCase y) = tmp2 in +/// body" +let PushCurriedPatternsToExpr synArgNameGenerator wholem isMember pats rhs = + // Two phases + // First phase: Fold back, from right to left, pushing patterns into r.h.s. expr + let spatsl, rhs = + (pats, ([], rhs)) + ||> List.foldBack (fun arg (spatsl, body) -> + let spats, bodyf = SimplePatsOfPat synArgNameGenerator arg + // accumulate the body. This builds "let (UnionCase y) = tmp2 in body" + let body = appFunOpt bodyf body + // accumulate the patterns + let spatsl = spats :: spatsl + (spatsl, body)) + // Second phase: build lambdas. Mark subsequent ones with "true" indicating they are part of an iterated sequence of lambdas + let expr = + match spatsl with + | [] -> rhs + | h :: t -> + let expr = List.foldBack (fun spats e -> SynExpr.Lambda (isMember, true, spats, e, wholem)) t rhs + let expr = SynExpr.Lambda (isMember, false, h, expr, wholem) + expr + spatsl, expr + +let opNameParenGet = CompileOpName parenGet + +let opNameQMark = CompileOpName qmark + +let mkSynOperator opm oper = mkSynIdGet opm (CompileOpName oper) + +let mkSynInfix opm (l: SynExpr) oper (r: SynExpr) = + let firstTwoRange = unionRanges l.Range opm + let wholeRange = unionRanges l.Range r.Range + let app1 = SynExpr.App (ExprAtomicFlag.NonAtomic, true, mkSynOperator opm oper, l, firstTwoRange) + SynExpr.App (ExprAtomicFlag.NonAtomic, false, app1, r, wholeRange) + +let mkSynBifix m oper x1 x2 = + let app1 = SynExpr.App (ExprAtomicFlag.NonAtomic, true, mkSynOperator m oper, x1, m) + SynExpr.App (ExprAtomicFlag.NonAtomic, false, app1, x2, m) + +let mkSynTrifix m oper x1 x2 x3 = + let app1 = SynExpr.App (ExprAtomicFlag.NonAtomic, true, mkSynOperator m oper, x1, m) + let app2 = SynExpr.App (ExprAtomicFlag.NonAtomic, false, app1, x2, m) + SynExpr.App (ExprAtomicFlag.NonAtomic, false, app2, x3, m) + +let mkSynPrefixPrim opm m oper x = + SynExpr.App (ExprAtomicFlag.NonAtomic, false, mkSynOperator opm oper, x, m) + +let mkSynPrefix opm m oper x = + if oper = "~&" then + SynExpr.AddressOf (true, x, opm, m) + elif oper = "~&&" then + SynExpr.AddressOf (false, x, opm, m) + else + mkSynPrefixPrim opm m oper x + +let mkSynCaseName m n = [mkSynId m (CompileOpName n)] + +let mkSynApp1 f x1 m = SynExpr.App (ExprAtomicFlag.NonAtomic, false, f, x1, m) + +let mkSynApp2 f x1 x2 m = mkSynApp1 (mkSynApp1 f x1 m) x2 m + +let mkSynApp3 f x1 x2 x3 m = mkSynApp1 (mkSynApp2 f x1 x2 m) x3 m + +let mkSynApp4 f x1 x2 x3 x4 m = mkSynApp1 (mkSynApp3 f x1 x2 x3 m) x4 m + +let mkSynApp5 f x1 x2 x3 x4 x5 m = mkSynApp1 (mkSynApp4 f x1 x2 x3 x4 m) x5 m + +let mkSynDotParenSet m a b c = mkSynTrifix m parenSet a b c + +let mkSynDotBrackGet m mDot a b fromEnd = SynExpr.DotIndexedGet (a, [SynIndexerArg.One (b, fromEnd, m)], mDot, m) + +let mkSynQMarkSet m a b c = mkSynTrifix m qmarkSet a b c + +let mkSynDotBrackSliceGet m mDot arr sliceArg = SynExpr.DotIndexedGet (arr, [sliceArg], mDot, m) + +let mkSynDotBrackSeqSliceGet m mDot arr (argsList: list) = + SynExpr.DotIndexedGet (arr, argsList, mDot, m) + +let mkSynDotParenGet lhsm dotm a b = + match b with + | SynExpr.Tuple (false, [_;_], _, _) -> + errorR(Deprecated(FSComp.SR.astDeprecatedIndexerNotation(), lhsm)) + SynExpr.Const (SynConst.Unit, lhsm) + + | SynExpr.Tuple (false, [_;_;_], _, _) -> + errorR(Deprecated(FSComp.SR.astDeprecatedIndexerNotation(), lhsm)) + SynExpr.Const (SynConst.Unit, lhsm) + + | _ -> mkSynInfix dotm a parenGet b + +let mkSynUnit m = SynExpr.Const (SynConst.Unit, m) + +let mkSynUnitPat m = SynPat.Const(SynConst.Unit, m) + +let mkSynDelay m e = + SynExpr.Lambda (false, false, SynSimplePats.SimplePats ([mkSynCompGenSimplePatVar (mkSynId m "unitVar")], m), e, m) + +let mkSynAssign (l: SynExpr) (r: SynExpr) = + let m = unionRanges l.Range r.Range + match l with + //| SynExpr.Paren (l2, m2) -> mkSynAssign m l2 r + | LongOrSingleIdent(false, v, None, _) -> SynExpr.LongIdentSet (v, r, m) + | SynExpr.DotGet (e, _, v, _) -> SynExpr.DotSet (e, v, r, m) + | SynExpr.DotIndexedGet (e1, e2, mDot, mLeft) -> SynExpr.DotIndexedSet (e1, e2, r, mLeft, mDot, m) + | SynExpr.LibraryOnlyUnionCaseFieldGet (x, y, z, _) -> SynExpr.LibraryOnlyUnionCaseFieldSet (x, y, z, r, m) + | SynExpr.App (_, _, SynExpr.App (_, _, SingleIdent nm, a, _), b, _) when nm.idText = opNameQMark -> + mkSynQMarkSet m a b r + | SynExpr.App (_, _, SynExpr.App (_, _, SingleIdent nm, a, _), b, _) when nm.idText = opNameParenGet -> + mkSynDotParenSet m a b r + | SynExpr.App (_, _, SynExpr.LongIdent (false, v, None, _), x, _) -> SynExpr.NamedIndexedPropertySet (v, x, r, m) + | SynExpr.App (_, _, SynExpr.DotGet (e, _, v, _), x, _) -> SynExpr.DotNamedIndexedPropertySet (e, v, x, r, m) + | l -> SynExpr.Set (l, r, m) + +let mkSynDot dotm m l r = + match l with + | SynExpr.LongIdent (isOpt, LongIdentWithDots(lid, dots), None, _) -> + // REVIEW: MEMORY PERFORMANCE: This list operation is memory intensive (we create a lot of these list nodes) + SynExpr.LongIdent (isOpt, LongIdentWithDots(lid@[r], dots@[dotm]), None, m) + | SynExpr.Ident id -> + SynExpr.LongIdent (false, LongIdentWithDots([id;r], [dotm]), None, m) + | SynExpr.DotGet (e, dm, LongIdentWithDots(lid, dots), _) -> + // REVIEW: MEMORY PERFORMANCE: This is memory intensive (we create a lot of these list nodes) + SynExpr.DotGet (e, dm, LongIdentWithDots(lid@[r], dots@[dotm]), m) + | expr -> + SynExpr.DotGet (expr, dotm, LongIdentWithDots([r], []), m) + +let mkSynDotMissing dotm m l = + match l with + | SynExpr.LongIdent (isOpt, LongIdentWithDots(lid, dots), None, _) -> + // REVIEW: MEMORY PERFORMANCE: This list operation is memory intensive (we create a lot of these list nodes) + SynExpr.LongIdent (isOpt, LongIdentWithDots(lid, dots@[dotm]), None, m) + | SynExpr.Ident id -> + SynExpr.LongIdent (false, LongIdentWithDots([id], [dotm]), None, m) + | SynExpr.DotGet (e, dm, LongIdentWithDots(lid, dots), _) -> + SynExpr.DotGet (e, dm, LongIdentWithDots(lid, dots@[dotm]), m)// REVIEW: MEMORY PERFORMANCE: This is memory intensive (we create a lot of these list nodes) + | expr -> + SynExpr.DiscardAfterMissingQualificationAfterDot (expr, m) + +let mkSynFunMatchLambdas synArgNameGenerator isMember wholem ps e = + let _, e = PushCurriedPatternsToExpr synArgNameGenerator wholem isMember ps e + e + +let arbExpr (debugStr, range: range) = SynExpr.ArbitraryAfterError (debugStr, range.MakeSynthetic()) + +let unionRangeWithListBy projectRangeFromThing m listOfThing = + (m, listOfThing) ||> List.fold (fun m thing -> unionRanges m (projectRangeFromThing thing)) + +let mkAttributeList attrs range = + [{ Attributes = attrs + Range = range }] + +let ConcatAttributesLists (attrsLists: SynAttributeList list) = + attrsLists + |> List.map (fun x -> x.Attributes) + |> List.concat + +let (|Attributes|) synAttributes = + ConcatAttributesLists synAttributes + +let rangeOfNonNilAttrs (attrs: SynAttributes) = + (attrs.Head.Range, attrs.Tail) ||> unionRangeWithListBy (fun a -> a.Range) + +/// Operations related to the syntactic analysis of arguments of value, function and member definitions and signatures. +module SynInfo = + + /// The argument information for an argument without a name + let unnamedTopArg1 = SynArgInfo([], false, None) + + /// The argument information for a curried argument without a name + let unnamedTopArg = [unnamedTopArg1] + + /// The argument information for a '()' argument + let unitArgData = unnamedTopArg + + /// The 'argument' information for a return value where no attributes are given for the return value (the normal case) + let unnamedRetVal = SynArgInfo([], false, None) + + /// The 'argument' information for the 'this'/'self' parameter in the cases where it is not given explicitly + let selfMetadata = unnamedTopArg + + /// Determine if a syntactic information represents a member without arguments (which is implicitly a property getter) + let HasNoArgs (SynValInfo(args, _)) = isNil args + + /// Check if one particular argument is an optional argument. Used when adjusting the + /// types of optional arguments for function and member signatures. + let IsOptionalArg (SynArgInfo(_, isOpt, _)) = isOpt + + /// Check if there are any optional arguments in the syntactic argument information. Used when adjusting the + /// types of optional arguments for function and member signatures. + let HasOptionalArgs (SynValInfo(args, _)) = List.exists (List.exists IsOptionalArg) args + + /// Add a parameter entry to the syntactic value information to represent the '()' argument to a property getter. This is + /// used for the implicit '()' argument in property getter signature specifications. + let IncorporateEmptyTupledArgForPropertyGetter (SynValInfo(args, retInfo)) = SynValInfo([] :: args, retInfo) + + /// Add a parameter entry to the syntactic value information to represent the 'this' argument. This is + /// used for the implicit 'this' argument in member signature specifications. + let IncorporateSelfArg (SynValInfo(args, retInfo)) = SynValInfo(selfMetadata :: args, retInfo) + + /// Add a parameter entry to the syntactic value information to represent the value argument for a property setter. This is + /// used for the implicit value argument in property setter signature specifications. + let IncorporateSetterArg (SynValInfo(args, retInfo)) = + let args = + match args with + | [] -> [unnamedTopArg] + | [arg] -> [arg@[unnamedTopArg1]] + | _ -> failwith "invalid setter type" + SynValInfo(args, retInfo) + + /// Get the argument counts for each curried argument group. Used in some adhoc places in tc.fs. + let AritiesOfArgs (SynValInfo(args, _)) = List.map List.length args + + /// Get the argument attributes from the syntactic information for an argument. + let AttribsOfArgData (SynArgInfo(Attributes attribs, _, _)) = attribs + + /// Infer the syntactic argument info for a single argument from a simple pattern. + let rec InferSynArgInfoFromSimplePat attribs p = + match p with + | SynSimplePat.Id(nm, _, isCompGen, _, isOpt, _) -> + SynArgInfo(attribs, isOpt, (if isCompGen then None else Some nm)) + | SynSimplePat.Typed(a, _, _) -> InferSynArgInfoFromSimplePat attribs a + | SynSimplePat.Attrib(a, attribs2, _) -> InferSynArgInfoFromSimplePat (attribs @ attribs2) a + + /// Infer the syntactic argument info for one or more arguments one or more simple patterns. + let rec InferSynArgInfoFromSimplePats x = + match x with + | SynSimplePats.SimplePats(ps, _) -> List.map (InferSynArgInfoFromSimplePat []) ps + | SynSimplePats.Typed(ps, _, _) -> InferSynArgInfoFromSimplePats ps + + /// Infer the syntactic argument info for one or more arguments a pattern. + let InferSynArgInfoFromPat p = + // It is ok to use a fresh SynArgNameGenerator here, because compiler generated names are filtered from SynArgInfo, see InferSynArgInfoFromSimplePat above + let sp, _ = SimplePatsOfPat (SynArgNameGenerator()) p + InferSynArgInfoFromSimplePats sp + + /// Make sure only a solitary unit argument has unit elimination + let AdjustArgsForUnitElimination infosForArgs = + match infosForArgs with + | [[]] -> infosForArgs + | _ -> infosForArgs |> List.map (function [] -> unitArgData | x -> x) + + /// Transform a property declared using '[static] member P = expr' to a method taking a "unit" argument. + /// This is similar to IncorporateEmptyTupledArgForPropertyGetter, but applies to member definitions + /// rather than member signatures. + let AdjustMemberArgs memFlags infosForArgs = + match infosForArgs with + | [] when memFlags=MemberKind.Member -> [] :: infosForArgs + | _ -> infosForArgs + + /// For 'let' definitions, we infer syntactic argument information from the r.h.s. of a definition, if it + /// is an immediate 'fun ... -> ...' or 'function ...' expression. This is noted in the F# language specification. + /// This does not apply to member definitions. + let InferLambdaArgs origRhsExpr = + let rec loop e = + match e with + | SynExpr.Lambda (false, _, spats, rest, _) -> + InferSynArgInfoFromSimplePats spats :: loop rest + | _ -> [] + loop origRhsExpr + + let InferSynReturnData (retInfo: SynReturnInfo option) = + match retInfo with + | None -> unnamedRetVal + | Some(SynReturnInfo((_, retInfo), _)) -> retInfo + + let private emptySynValInfo = SynValInfo([], unnamedRetVal) + + let emptySynValData = SynValData(None, emptySynValInfo, None) + + /// Infer the syntactic information for a 'let' or 'member' definition, based on the argument pattern, + /// any declared return information (e.g. .NET attributes on the return element), and the r.h.s. expression + /// in the case of 'let' definitions. + let InferSynValData (memberFlagsOpt, pat, retInfo, origRhsExpr) = + + let infosForExplicitArgs = + match pat with + | Some(SynPat.LongIdent(_, _, _, SynArgPats.Pats curriedArgs, _, _)) -> List.map InferSynArgInfoFromPat curriedArgs + | _ -> [] + + let explicitArgsAreSimple = + match pat with + | Some(SynPat.LongIdent(_, _, _, SynArgPats.Pats curriedArgs, _, _)) -> List.forall isSimplePattern curriedArgs + | _ -> true + + let retInfo = InferSynReturnData retInfo + + match memberFlagsOpt with + | None -> + let infosForLambdaArgs = InferLambdaArgs origRhsExpr + let infosForArgs = infosForExplicitArgs @ (if explicitArgsAreSimple then infosForLambdaArgs else []) + let infosForArgs = AdjustArgsForUnitElimination infosForArgs + SynValData(None, SynValInfo(infosForArgs, retInfo), None) + + | Some memFlags -> + let infosForObjArgs = + if memFlags.IsInstance then [ selfMetadata ] else [] + + let infosForArgs = AdjustMemberArgs memFlags.MemberKind infosForExplicitArgs + let infosForArgs = AdjustArgsForUnitElimination infosForArgs + + let argInfos = infosForObjArgs @ infosForArgs + SynValData(Some memFlags, SynValInfo(argInfos, retInfo), None) + +let mkSynBindingRhs staticOptimizations rhsExpr mRhs retInfo = + let rhsExpr = List.foldBack (fun (c, e1) e2 -> SynExpr.LibraryOnlyStaticOptimization (c, e1, e2, mRhs)) staticOptimizations rhsExpr + let rhsExpr, retTyOpt = + match retInfo with + | Some (SynReturnInfo((ty, SynArgInfo(rAttribs, _, _)), tym)) -> SynExpr.Typed (rhsExpr, ty, rhsExpr.Range), Some(SynBindingReturnInfo(ty, tym, rAttribs) ) + | None -> rhsExpr, None + rhsExpr, retTyOpt + +let mkSynBinding (xmlDoc, headPat) (vis, isInline, isMutable, mBind, spBind, retInfo, origRhsExpr, mRhs, staticOptimizations, attrs, memberFlagsOpt) = + let info = SynInfo.InferSynValData (memberFlagsOpt, Some headPat, retInfo, origRhsExpr) + let rhsExpr, retTyOpt = mkSynBindingRhs staticOptimizations origRhsExpr mRhs retInfo + Binding (vis, NormalBinding, isInline, isMutable, attrs, xmlDoc, info, headPat, retTyOpt, rhsExpr, mBind, spBind) + +let NonVirtualMemberFlags k = + { MemberKind=k + IsInstance=true + IsDispatchSlot=false + IsOverrideOrExplicitImpl=false + IsFinal=false } + +let CtorMemberFlags = + { MemberKind=MemberKind.Constructor + IsInstance=false + IsDispatchSlot=false + IsOverrideOrExplicitImpl=false + IsFinal=false } + +let ClassCtorMemberFlags = + { MemberKind=MemberKind.ClassConstructor + IsInstance=false + IsDispatchSlot=false + IsOverrideOrExplicitImpl=false + IsFinal=false } + +let OverrideMemberFlags k = + { MemberKind=k + IsInstance=true + IsDispatchSlot=false + IsOverrideOrExplicitImpl=true + IsFinal=false } + +let AbstractMemberFlags k = + { MemberKind=k + IsInstance=true + IsDispatchSlot=true + IsOverrideOrExplicitImpl=false + IsFinal=false } + +let StaticMemberFlags k = + { MemberKind=k + IsInstance=false + IsDispatchSlot=false + IsOverrideOrExplicitImpl=false + IsFinal=false } + +let inferredTyparDecls = SynValTyparDecls([], true, []) + +let noInferredTypars = SynValTyparDecls([], false, []) + +let rec synExprContainsError inpExpr = + let rec walkBind (Binding(_, _, _, _, _, _, _, _, _, synExpr, _, _)) = walkExpr synExpr + + and walkExprs es = es |> List.exists walkExpr + + and walkBinds es = es |> List.exists walkBind + + and walkMatchClauses cl = + cl |> List.exists (fun (Clause(_, whenExpr, e, _, _)) -> walkExprOpt whenExpr || walkExpr e) + + and walkExprOpt eOpt = eOpt |> Option.exists walkExpr + + and walkExpr e = + match e with + | SynExpr.FromParseError _ + | SynExpr.DiscardAfterMissingQualificationAfterDot _ + | SynExpr.ArbitraryAfterError _ -> true + + | SynExpr.LongIdent _ + | SynExpr.Quote _ + | SynExpr.LibraryOnlyILAssembly _ + | SynExpr.LibraryOnlyStaticOptimization _ + | SynExpr.Null _ + | SynExpr.Ident _ + | SynExpr.ImplicitZero _ + | SynExpr.Const _ -> false + + | SynExpr.TypeTest (e, _, _) + | SynExpr.Upcast (e, _, _) + | SynExpr.AddressOf (_, e, _, _) + | SynExpr.CompExpr (_, _, e, _) + | SynExpr.ArrayOrListOfSeqExpr (_, e, _) + | SynExpr.Typed (e, _, _) + | SynExpr.FromParseError (e, _) + | SynExpr.Do (e, _) + | SynExpr.Assert (e, _) + | SynExpr.DotGet (e, _, _, _) + | SynExpr.LongIdentSet (_, e, _) + | SynExpr.New (_, _, e, _) + | SynExpr.TypeApp (e, _, _, _, _, _, _) + | SynExpr.LibraryOnlyUnionCaseFieldGet (e, _, _, _) + | SynExpr.Downcast (e, _, _) + | SynExpr.InferredUpcast (e, _) + | SynExpr.InferredDowncast (e, _) + | SynExpr.Lazy (e, _) + | SynExpr.TraitCall (_, _, e, _) + | SynExpr.YieldOrReturn (_, e, _) + | SynExpr.YieldOrReturnFrom (_, e, _) + | SynExpr.DoBang (e, _) + | SynExpr.Fixed (e, _) + | SynExpr.Paren (e, _, _, _) -> + walkExpr e + + | SynExpr.NamedIndexedPropertySet (_, e1, e2, _) + | SynExpr.DotSet (e1, _, e2, _) + | SynExpr.Set (e1, e2, _) + | SynExpr.LibraryOnlyUnionCaseFieldSet (e1, _, _, e2, _) + | SynExpr.JoinIn (e1, _, e2, _) + | SynExpr.App (_, _, e1, e2, _) -> + walkExpr e1 || walkExpr e2 + + | SynExpr.ArrayOrList (_, es, _) + | SynExpr.Tuple (_, es, _, _) -> + walkExprs es + + | SynExpr.AnonRecd (_, origExpr, flds, _) -> + (match origExpr with Some (e, _) -> walkExpr e | None -> false) || + walkExprs (List.map snd flds) + + | SynExpr.Record (_, origExpr, fs, _) -> + (match origExpr with Some (e, _) -> walkExpr e | None -> false) || + let flds = fs |> List.choose (fun (_, v, _) -> v) + walkExprs flds + + | SynExpr.ObjExpr (_, _, bs, is, _, _) -> + walkBinds bs || walkBinds [ for (InterfaceImpl(_, bs, _)) in is do yield! bs ] + + | SynExpr.ForEach (_, _, _, _, e1, e2, _) + | SynExpr.While (_, e1, e2, _) -> + walkExpr e1 || walkExpr e2 + + | SynExpr.For (_, _, e1, _, e2, e3, _) -> + walkExpr e1 || walkExpr e2 || walkExpr e3 + + | SynExpr.MatchLambda (_, _, cl, _, _) -> + walkMatchClauses cl + + | SynExpr.Lambda (_, _, _, e, _) -> + walkExpr e + + | SynExpr.Match (_, e, cl, _) -> + walkExpr e || walkMatchClauses cl + + | SynExpr.LetOrUse (_, _, bs, e, _) -> + walkBinds bs || walkExpr e + + | SynExpr.TryWith (e, _, cl, _, _, _, _) -> + walkExpr e || walkMatchClauses cl + + | SynExpr.TryFinally (e1, e2, _, _, _) -> + walkExpr e1 || walkExpr e2 + + | SynExpr.Sequential (_, _, e1, e2, _) -> + walkExpr e1 || walkExpr e2 + + | SynExpr.SequentialOrImplicitYield (_, e1, e2, _, _) -> + walkExpr e1 || walkExpr e2 + + | SynExpr.IfThenElse (e1, e2, e3opt, _, _, _, _) -> + walkExpr e1 || walkExpr e2 || walkExprOpt e3opt + + | SynExpr.DotIndexedGet (e1, es, _, _) -> + walkExpr e1 || walkExprs [ for e in es do yield! e.Exprs ] + + | SynExpr.DotIndexedSet (e1, es, e2, _, _, _) -> + walkExpr e1 || walkExprs [ for e in es do yield! e.Exprs ] || walkExpr e2 + + | SynExpr.DotNamedIndexedPropertySet (e1, _, e2, e3, _) -> + walkExpr e1 || walkExpr e2 || walkExpr e3 + + | SynExpr.MatchBang (_, e, cl, _) -> + walkExpr e || walkMatchClauses cl + + | SynExpr.LetOrUseBang (rhs=e1;body=e2;andBangs=es) -> + walkExpr e1 || walkExprs [ for (_,_,_,_,e,_) in es do yield e ] || walkExpr e2 + + walkExpr inpExpr diff --git a/src/fcs-fable/src/fsharp/TcGlobals.fs b/src/fcs-fable/src/fsharp/TcGlobals.fs index 109fad1eef..68ef24cb76 100755 --- a/src/fcs-fable/src/fsharp/TcGlobals.fs +++ b/src/fcs-fable/src/fsharp/TcGlobals.fs @@ -11,21 +11,21 @@ module internal FSharp.Compiler.TcGlobals open System.Collections.Generic open System.Diagnostics -open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Extensions.ILX open FSharp.Compiler.AbstractIL.Internal.Library - -open FSharp.Compiler.Tast -open FSharp.Compiler.Range -open FSharp.Compiler.Ast +open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.Lib +open FSharp.Compiler.Features open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.Range +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics open Internal.Utilities -let internal DummyFileNameForRangesWithoutASpecificLocation = "startup" +let internal DummyFileNameForRangesWithoutASpecificLocation = startupFileName let private envRange = rangeN DummyFileNameForRangesWithoutASpecificLocation 0 /// Represents an intrinsic value from FSharp.Core known to the compiler @@ -179,13 +179,14 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d mlCompatibility: bool, isInteractive:bool, // The helper to find system types amongst referenced DLLs tryFindSysTypeCcu, - emitDebugInfoInQuotations: bool, noDebugData: bool) = - - let vara = NewRigidTypar "a" envRange - let varb = NewRigidTypar "b" envRange - let varc = NewRigidTypar "c" envRange - let vard = NewRigidTypar "d" envRange - let vare = NewRigidTypar "e" envRange + emitDebugInfoInQuotations: bool, noDebugData: bool, + pathMap: PathMap, langVersion: LanguageVersion) = + + let vara = Construct.NewRigidTypar "a" envRange + let varb = Construct.NewRigidTypar "b" envRange + let varc = Construct.NewRigidTypar "c" envRange + let vard = Construct.NewRigidTypar "d" envRange + let vare = Construct.NewRigidTypar "e" envRange let varaTy = mkTyparTy vara let varbTy = mkTyparTy varb @@ -238,7 +239,7 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d // Search for a type. If it is not found, leave a dangling CCU reference with some useful diagnostic information should // the type actually be dereferenced let findSysTypeCcu path typeName = - match tryFindSysTypeCcu path typeName with + match tryFindSysTypeCcu path typeName with | None -> CcuThunk.CreateDelayed(dummyAssemblyNameCarryingUsefulErrorInformation path typeName) | Some ccu -> ccu @@ -385,6 +386,7 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d let mkListTy ty = TType_app(v_list_tcr_nice, [ty]) let mkSeqTy ty1 = TType_app(v_seq_tcr, [ty1]) let mkRefCellTy ty = TType_app(v_refcell_tcr_canon, [ty]) + let mkOptionTy ty = TType_app(v_option_tcr_nice, [ty]) let mkQuerySourceTy ty1 ty2 = TType_app(v_querySource_tcr, [ty1; ty2]) let v_tcref_System_Collections_IEnumerable = findSysTyconRef sysCollections "IEnumerable"; let mkArrayType rank (ty : TType) : TType = @@ -458,7 +460,7 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d let v_struct_tuple5_tcr = findSysTyconRef sys "ValueTuple`5" let v_struct_tuple6_tcr = findSysTyconRef sys "ValueTuple`6" let v_struct_tuple7_tcr = findSysTyconRef sys "ValueTuple`7" - let v_struct_tuple8_tcr = findSysTyconRef sys "ValueTuple`8" + let v_struct_tuple8_tcr = findSysTyconRef sys "ValueTuple`8" let v_choice2_tcr = mk_MFCore_tcref fslibCcu "Choice`2" let v_choice3_tcr = mk_MFCore_tcref fslibCcu "Choice`3" @@ -651,18 +653,20 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d let v_hash_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "hash" , None , Some "Hash" , [vara], ([[varaTy]], v_int_ty)) let v_box_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "box" , None , Some "Box" , [vara], ([[varaTy]], v_obj_ty)) let v_isnull_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "isNull" , None , Some "IsNull" , [vara], ([[varaTy]], v_bool_ty)) - let v_isnotnull_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "isNotNull" , None , Some "IsNotNull" , [vara], ([[varaTy]], v_bool_ty)) + let v_isnotnull_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "isNotNull" , None , Some "IsNotNull" , [vara], ([[varaTy]], v_bool_ty)) let v_raise_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "raise" , None , Some "Raise" , [vara], ([[mkSysNonGenericTy sys "Exception"]], varaTy)) - let v_failwith_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "failwith" , None , Some "FailWith" , [vara], ([[v_string_ty]], varaTy)) - let v_invalid_arg_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "invalidArg" , None , Some "InvalidArg" , [vara], ([[v_string_ty]; [v_string_ty]], varaTy)) - let v_null_arg_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "nullArg" , None , Some "NullArg" , [vara], ([[v_string_ty]], varaTy)) - let v_invalid_op_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "invalidOp" , None , Some "InvalidOp" , [vara], ([[v_string_ty]], varaTy)) - let v_failwithf_info = makeIntrinsicValRef(fslib_MFExtraTopLevelOperators_nleref, "failwithf" , None, Some "PrintFormatToStringThenFail" , [vara;varb], ([[mk_format4_ty varaTy v_unit_ty v_string_ty v_string_ty]], varaTy)) + let v_failwith_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "failwith" , None , Some "FailWith" , [vara], ([[v_string_ty]], varaTy)) + let v_invalid_arg_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "invalidArg" , None , Some "InvalidArg" , [vara], ([[v_string_ty]; [v_string_ty]], varaTy)) + let v_null_arg_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "nullArg" , None , Some "NullArg" , [vara], ([[v_string_ty]], varaTy)) + let v_invalid_op_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "invalidOp" , None , Some "InvalidOp" , [vara], ([[v_string_ty]], varaTy)) + let v_failwithf_info = makeIntrinsicValRef(fslib_MFExtraTopLevelOperators_nleref, "failwithf" , None , Some "PrintFormatToStringThenFail" , [vara;varb], ([[mk_format4_ty varaTy v_unit_ty v_string_ty v_string_ty]], varaTy)) let v_reraise_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "reraise" , None , Some "Reraise", [vara], ([[v_unit_ty]], varaTy)) let v_typeof_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "typeof" , None , Some "TypeOf" , [vara], ([], v_system_Type_ty)) let v_methodhandleof_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "methodhandleof" , None , Some "MethodHandleOf", [vara;varb], ([[varaTy --> varbTy]], v_system_RuntimeMethodHandle_ty)) let v_sizeof_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "sizeof" , None , Some "SizeOf" , [vara], ([], v_int_ty)) + let v_nameof_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "nameof" , None , Some "NameOf" , [vara], ([[varaTy]], v_string_ty)) + let v_unchecked_defaultof_info = makeIntrinsicValRef(fslib_MFOperatorsUnchecked_nleref, "defaultof" , None , Some "DefaultOf", [vara], ([], varaTy)) let v_typedefof_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "typedefof" , None , Some "TypeDefOf", [vara], ([], v_system_Type_ty)) let v_range_op_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "op_Range" , None , None , [vara], ([[varaTy];[varaTy]], mkSeqTy varaTy)) @@ -679,6 +683,9 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d let v_array3D_set_info = makeIntrinsicValRef(fslib_MFIntrinsicFunctions_nleref, "SetArray3D" , None , None , [vara], ([[mkArrayType 3 varaTy];[v_int_ty]; [v_int_ty]; [v_int_ty]; [varaTy]], v_unit_ty)) let v_array4D_set_info = makeIntrinsicValRef(fslib_MFIntrinsicFunctions_nleref, "SetArray4D" , None , None , [vara], ([[mkArrayType 4 varaTy];[v_int_ty]; [v_int_ty]; [v_int_ty]; [v_int_ty]; [varaTy]], v_unit_ty)) + let v_option_toNullable_info = makeIntrinsicValRef(fslib_MFOptionModule_nleref, "toNullable" , None , Some "ToNullable" , [vara], ([[mkOptionTy varaTy]], mkNullableTy varaTy)) + let v_option_defaultValue_info = makeIntrinsicValRef(fslib_MFOptionModule_nleref, "defaultValue" , None , Some "DefaultValue" , [vara], ([[varaTy]; [mkOptionTy varaTy]], varaTy)) + let v_nativeptr_tobyref_info = makeIntrinsicValRef(fslib_MFNativePtrModule_nleref, "toByRef" , None , Some "ToByRefInlined", [vara], ([[mkNativePtrTy varaTy]], mkByrefTy varaTy)) let v_seq_collect_info = makeIntrinsicValRef(fslib_MFSeqModule_nleref, "collect" , None , Some "Collect", [vara;varb;varc], ([[varaTy --> varbTy]; [mkSeqTy varaTy]], mkSeqTy varcTy)) @@ -696,9 +703,7 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d let v_seq_empty_info = makeIntrinsicValRef(fslib_MFSeqModule_nleref, "empty" , None , Some "Empty" , [vara], ([], mkSeqTy varaTy)) let v_new_format_info = makeIntrinsicValRef(fslib_MFCore_nleref, ".ctor" , Some "PrintfFormat`5", None , [vara;varb;varc;vard;vare], ([[v_string_ty]], mkPrintfFormatTy varaTy varbTy varcTy vardTy vareTy)) let v_sprintf_info = makeIntrinsicValRef(fslib_MFExtraTopLevelOperators_nleref, "sprintf" , None , Some "PrintFormatToStringThen", [vara], ([[mk_format4_ty varaTy v_unit_ty v_string_ty v_string_ty]], varaTy)) - let v_lazy_force_info = - // Lazy\Value for > 4.0 - makeIntrinsicValRef(fslib_MFLazyExtensions_nleref, "Force" , Some "Lazy`1" , None , [vara], ([[mkLazyTy varaTy]; []], varaTy)) + let v_lazy_force_info = makeIntrinsicValRef(fslib_MFLazyExtensions_nleref, "Force" , Some "Lazy`1" , None , [vara], ([[mkLazyTy varaTy]; []], varaTy)) let v_lazy_create_info = makeIntrinsicValRef(fslib_MFLazyExtensions_nleref, "Create" , Some "Lazy`1" , None , [vara], ([[v_unit_ty --> varaTy]], mkLazyTy varaTy)) let v_seq_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "seq" , None , Some "CreateSequence" , [vara], ([[mkSeqTy varaTy]], mkSeqTy varaTy)) @@ -728,7 +733,7 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d let v_fail_static_init_info = makeIntrinsicValRef(fslib_MFIntrinsicFunctions_nleref, "FailStaticInit" , None , None , [], ([[v_unit_ty]], v_unit_ty)) let v_check_this_info = makeIntrinsicValRef(fslib_MFIntrinsicFunctions_nleref, "CheckThis" , None , None , [vara], ([[varaTy]], varaTy)) let v_quote_to_linq_lambda_info = makeIntrinsicValRef(fslib_MFLinqRuntimeHelpersQuotationConverter_nleref, "QuotationToLambdaExpression" , None , None , [vara], ([[mkQuotedExprTy varaTy]], mkLinqExpressionTy varaTy)) - + let tref_DebuggableAttribute = findSysILTypeRef tname_DebuggableAttribute let tref_CompilerGeneratedAttribute = findSysILTypeRef tname_CompilerGeneratedAttribute @@ -736,6 +741,7 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d let mutable debuggerBrowsableNeverAttributeCache = None let mkDebuggerNonUserCodeAttribute() = mkILCustomAttribute ilg (findSysILTypeRef tname_DebuggerNonUserCodeAttribute, [], [], []) let mkCompilerGeneratedAttribute () = mkILCustomAttribute ilg (tref_CompilerGeneratedAttribute, [], [], []) + let compilerGlobalState = CompilerGlobalState() // Requests attributes to be added to compiler generated methods. let addGeneratedAttrs (attrs: ILAttributes) = @@ -870,14 +876,9 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d TType_app (tcref, tinst) else let dict = getDecompileTypeDict() -#if FABLE_COMPILER - let ok, builder = dict.TryGetValue(tcref.Stamp) -#else - let mutable builder = Unchecked.defaultof<_> - let ok = dict.TryGetValue(tcref.Stamp, &builder) -#endif - if ok then builder tinst - else TType_app (tcref, tinst) + match dict.TryGetValue tcref.Stamp with + | true, builder -> builder tinst + | _ -> TType_app (tcref, tinst) /// For cosmetic purposes "improve" some .NET types, e.g. Int32 --> int32. /// Doing this normalization is a fairly performance critical piece of code as it is frequently invoked @@ -885,24 +886,14 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d let improveTy (tcref: EntityRef) tinst = if compilingFslib then let dict = getBetterTypeDict1() -#if FABLE_COMPILER - let ok, builder = dict.TryGetValue(tcref.LogicalName) -#else - let mutable builder = Unchecked.defaultof<_> - let ok = dict.TryGetValue(tcref.LogicalName, &builder) -#endif - if ok then builder tcref tinst - else TType_app (tcref, tinst) + match dict.TryGetValue tcref.LogicalName with + | true, builder -> builder tcref tinst + | _ -> TType_app (tcref, tinst) else let dict = getBetterTypeDict2() -#if FABLE_COMPILER - let ok, builder = dict.TryGetValue(tcref.Stamp) -#else - let mutable builder = Unchecked.defaultof<_> - let ok = dict.TryGetValue(tcref.Stamp, &builder) -#endif - if ok then builder tinst - else TType_app (tcref, tinst) + match dict.TryGetValue tcref.Stamp with + | true, builder -> builder tinst + | _ -> TType_app (tcref, tinst) override x.ToString() = "" @@ -916,6 +907,8 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d member __.mlCompatibility = mlCompatibility member __.emitDebugInfoInQuotations = emitDebugInfoInQuotations member __.directoryToResolveRelativePaths= directoryToResolveRelativePaths + member __.pathMap = pathMap + member __.langVersion = langVersion member __.unionCaseRefEq x y = primUnionCaseRefEq compilingFslib fslibCcu x y member __.valRefEq x y = primValRefEq compilingFslib fslibCcu x y member __.fslibCcu = fslibCcu @@ -1108,6 +1101,9 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d member __.tcref_System_Attribute = v_System_Attribute_tcr + // Review: Does this need to be an option type? + member val System_Runtime_CompilerServices_RuntimeFeature_ty = tryFindSysTyconRef sysCompilerServices "RuntimeFeature" |> Option.map mkNonGenericTy + member val iltyp_TypedReference = tryFindSysILTypeRef "System.TypedReference" |> Option.map mkILNonGenericValueTy member val iltyp_StreamingContext = tryFindSysILTypeRef tname_StreamingContext |> Option.map mkILNonGenericValueTy member val iltyp_SerializationInfo = tryFindSysILTypeRef tname_SerializationInfo |> Option.map mkILNonGenericBoxedTy @@ -1345,6 +1341,7 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d member val methodhandleof_vref = ValRefForIntrinsic v_methodhandleof_info member val typeof_vref = ValRefForIntrinsic v_typeof_info member val sizeof_vref = ValRefForIntrinsic v_sizeof_info + member val nameof_vref = ValRefForIntrinsic v_nameof_info member val typedefof_vref = ValRefForIntrinsic v_typedefof_info member val enum_vref = ValRefForIntrinsic v_enum_operator_info member val enumOfValue_vref = ValRefForIntrinsic v_enumOfValue_info @@ -1372,15 +1369,15 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d member val unbox_fast_vref = ValRefForIntrinsic v_unbox_fast_info member val istype_vref = ValRefForIntrinsic v_istype_info member val istype_fast_vref = ValRefForIntrinsic v_istype_fast_info - member val query_source_vref = ValRefForIntrinsic v_query_source_info - member val query_value_vref = ValRefForIntrinsic v_query_value_info - member val query_run_value_vref = ValRefForIntrinsic v_query_run_value_info - member val query_run_enumerable_vref = ValRefForIntrinsic v_query_run_enumerable_info - member val query_for_vref = ValRefForIntrinsic v_query_for_value_info - member val query_yield_vref = ValRefForIntrinsic v_query_yield_value_info - member val query_yield_from_vref = ValRefForIntrinsic v_query_yield_from_value_info - member val query_select_vref = ValRefForIntrinsic v_query_select_value_info - member val query_where_vref = ValRefForIntrinsic v_query_where_value_info + member val query_source_vref = ValRefForIntrinsic v_query_source_info + member val query_value_vref = ValRefForIntrinsic v_query_value_info + member val query_run_value_vref = ValRefForIntrinsic v_query_run_value_info + member val query_run_enumerable_vref = ValRefForIntrinsic v_query_run_enumerable_info + member val query_for_vref = ValRefForIntrinsic v_query_for_value_info + member val query_yield_vref = ValRefForIntrinsic v_query_yield_value_info + member val query_yield_from_vref = ValRefForIntrinsic v_query_yield_from_value_info + member val query_select_vref = ValRefForIntrinsic v_query_select_value_info + member val query_where_vref = ValRefForIntrinsic v_query_where_value_info member val query_zero_vref = ValRefForIntrinsic v_query_zero_value_info member __.seq_collect_info = v_seq_collect_info @@ -1420,6 +1417,9 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d member __.array3D_set_info = v_array3D_set_info member __.array4D_set_info = v_array4D_set_info + member val option_toNullable_info = v_option_toNullable_info + member val option_defaultValue_info = v_option_defaultValue_info + member __.deserialize_quoted_FSharp_20_plus_info = v_deserialize_quoted_FSharp_20_plus_info member __.deserialize_quoted_FSharp_40_plus_info = v_deserialize_quoted_FSharp_40_plus_info member __.cast_quotation_info = v_cast_quotation_info @@ -1488,17 +1488,17 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d (if enableEnC then 4 else 0) let tref_DebuggableAttribute_DebuggingModes = mkILTyRefInTyRef (tref_DebuggableAttribute, tname_DebuggableAttribute_DebuggingModes) mkILCustomAttribute ilg - (tref_DebuggableAttribute, [mkILNonGenericValueTy tref_DebuggableAttribute_DebuggingModes], + (tref_DebuggableAttribute, [mkILNonGenericValueTy tref_DebuggableAttribute_DebuggingModes], (* See System.Diagnostics.DebuggableAttribute.DebuggingModes *) [ILAttribElem.Int32( debuggingMode )], []) - member __.CompilerGeneratedAttribute = mkCompilerGeneratedAttribute () - - member __.eraseClassUnionDef = EraseUnions.mkClassUnionDef (addMethodGeneratedAttrs, addPropertyGeneratedAttrs, addPropertyNeverAttrs, addFieldGeneratedAttrs, addFieldNeverAttrs, mkDebuggerTypeProxyAttribute) ilg + member internal __.CompilerGlobalState = Some compilerGlobalState + + member __.CompilerGeneratedAttribute = mkCompilerGeneratedAttribute () + member __.eraseClassUnionDef = EraseUnions.mkClassUnionDef (addMethodGeneratedAttrs, addPropertyGeneratedAttrs, addPropertyNeverAttrs, addFieldGeneratedAttrs, addFieldNeverAttrs, mkDebuggerTypeProxyAttribute) ilg #if DEBUG // This global is only used during debug output -let global_g = ref (None : TcGlobals option) +let mutable global_g = None : TcGlobals option #endif - diff --git a/src/fcs-fable/src/fsharp/TypeChecker.fs b/src/fcs-fable/src/fsharp/TypeChecker.fs old mode 100755 new mode 100644 index 72c3a216a8..2cb72a3047 --- a/src/fcs-fable/src/fsharp/TypeChecker.fs +++ b/src/fcs-fable/src/fsharp/TypeChecker.fs @@ -9,33 +9,37 @@ open System.Collections.Generic open Internal.Utilities +open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Internal.Library.ResultOrException open FSharp.Compiler.AbstractIL.Diagnostics - -open FSharp.Compiler -open FSharp.Compiler.Range -open FSharp.Compiler.Rational -open FSharp.Compiler.Ast -open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.PatternMatchCompilation -open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Lib -open FSharp.Compiler.Infos open FSharp.Compiler.AccessibilityLogic open FSharp.Compiler.AttributeChecking -open FSharp.Compiler.TypeRelations +open FSharp.Compiler.CompilerGlobalState +open FSharp.Compiler.ConstraintSolver +open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features +open FSharp.Compiler.Infos +open FSharp.Compiler.InfoReader +open FSharp.Compiler.Lib open FSharp.Compiler.MethodCalls open FSharp.Compiler.MethodOverrides -open FSharp.Compiler.ConstraintSolver open FSharp.Compiler.NameResolution +open FSharp.Compiler.PatternMatchCompilation open FSharp.Compiler.PrettyNaming -open FSharp.Compiler.InfoReader +open FSharp.Compiler.Range +open FSharp.Compiler.Rational +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.TypeRelations +open FSharp.Compiler.XmlDoc #if !NO_EXTENSIONTYPING open FSharp.Compiler.ExtensionTyping @@ -65,7 +69,7 @@ exception TyconBadArgs of DisplayEnv * TyconRef * int * range exception UnionCaseWrongArguments of DisplayEnv * int * int * range exception UnionCaseWrongNumberOfArgs of DisplayEnv * int * int * range exception FieldsFromDifferentTypes of DisplayEnv * RecdFieldRef * RecdFieldRef * range -exception FieldGivenTwice of DisplayEnv * Tast.RecdFieldRef * range +exception FieldGivenTwice of DisplayEnv * RecdFieldRef * range exception MissingFields of string list * range exception FunctionValueUnexpected of DisplayEnv * TType * range exception UnitTypeExpected of DisplayEnv * TType * range @@ -222,7 +226,7 @@ type TcEnv = /// Compute the value of this computed, cached field let computeAccessRights eAccessPath eInternalsVisibleCompPaths eFamilyType = - AccessibleFrom (eAccessPath :: eInternalsVisibleCompPaths, eFamilyType) // env.eAccessRights + AccessibleFrom (eAccessPath :: eInternalsVisibleCompPaths, eFamilyType) // env.AccessRights let emptyTcEnv g = let cpath = compPathInternal // allow internal access initially @@ -234,7 +238,7 @@ let emptyTcEnv g = eAccessRights = computeAccessRights cpath [] None // compute this field eInternalsVisibleCompPaths = [] eContextInfo = ContextInfo.NoContext - eModuleOrNamespaceTypeAccumulator = ref (NewEmptyModuleOrNamespaceType Namespace) + eModuleOrNamespaceTypeAccumulator = ref (Construct.NewEmptyModuleOrNamespaceType Namespace) eFamilyType = None eCtorInfo = None eCallerMemberName = None } @@ -285,7 +289,7 @@ let addFreeItemOfTy ty eUngeneralizableItems = if isEmptyFreeTyvars fvs then eUngeneralizableItems else UngeneralizableItem(fun () -> freeInType CollectAllNoCaching ty) :: eUngeneralizableItems -/// Add the contents of a module type to the TcEnv, i.e. register the contants as ungeneralizable. +/// Add the contents of a module type to the TcEnv, i.e. register the contents as ungeneralizable. /// Add a module type to the TcEnv, i.e. register it as ungeneralizable. let addFreeItemOfModuleTy mtyp eUngeneralizableItems = let fvs = freeInModuleTy mtyp @@ -323,7 +327,7 @@ let AddLocalValMap tcSink scopem (vals: Val NameMap) env = { env with eNameResEnv = AddValMapToNameEnv vals env.eNameResEnv eUngeneralizableItems = NameMap.foldBackRange (typeOfVal >> addFreeItemOfTy) vals env.eUngeneralizableItems } - CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights) + CallEnvSink tcSink (scopem, env.NameEnv, env.AccessRights) env /// Add a list of local values to TcEnv and report them to the sink @@ -335,7 +339,7 @@ let AddLocalVals tcSink scopem (vals: Val list) env = { env with eNameResEnv = AddValListToNameEnv vals env.eNameResEnv eUngeneralizableItems = List.foldBack (typeOfVal >> addFreeItemOfTy) vals env.eUngeneralizableItems } - CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights) + CallEnvSink tcSink (scopem, env.NameEnv, env.AccessRights) env /// Add a local value to TcEnv and report it to the sink @@ -350,14 +354,14 @@ let AddLocalVal tcSink scopem v env = let AddLocalExnDefnAndReport tcSink scopem env (exnc: Tycon) = let env = { env with eNameResEnv = AddExceptionDeclsToNameEnv BulkAdd.No env.eNameResEnv (mkLocalEntityRef exnc) } // Also make VisualStudio think there is an identifier in scope at the range of the identifier text of its binding location - CallEnvSink tcSink (exnc.Range, env.NameEnv, env.eAccessRights) - CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights) + CallEnvSink tcSink (exnc.Range, env.NameEnv, env.AccessRights) + CallEnvSink tcSink (scopem, env.NameEnv, env.AccessRights) env /// Add a list of type definitions to TcEnv let AddLocalTyconRefs ownDefinition g amap m tcrefs env = if isNil tcrefs then env else - { env with eNameResEnv = AddTyconRefsToNameEnv BulkAdd.No ownDefinition g amap m false env.eNameResEnv tcrefs } + { env with eNameResEnv = AddTyconRefsToNameEnv BulkAdd.No ownDefinition g amap env.eAccessRights m false env.eNameResEnv tcrefs } /// Add a list of type definitions to TcEnv let AddLocalTycons g amap m (tycons: Tycon list) env = @@ -370,11 +374,11 @@ let AddLocalTyconsAndReport tcSink scopem g amap m tycons env = CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights) env -/// Adjust the TcEnv to account for opening the set of modules and namespaces implied by an `open` declaration -let OpenModulesOrNamespaces tcSink g amap scopem root env mvvs openDeclaration = +/// Adjust the TcEnv to account for opening the set of modules, namespaces or static classes implied by an `open` declaration +let OpenEntities tcSink g amap scopem root env mvvs openDeclaration = let env = if isNil mvvs then env else - { env with eNameResEnv = AddModulesAndNamespacesContentsToNameEnv g amap env.eAccessRights scopem root env.eNameResEnv mvvs } + { env with eNameResEnv = AddEntitiesContentsToNameEnv g amap env.eAccessRights scopem root env.eNameResEnv mvvs } CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights) CallOpenDeclarationSink tcSink openDeclaration env @@ -406,10 +410,10 @@ let AddNonLocalCcu g amap scopem env assemblyName (ccu: CcuThunk, internalsVisib let env = AddRootModuleOrNamespaceRefs g amap scopem env modrefs let env = if isNil tcrefs then env else - { env with eNameResEnv = AddTyconRefsToNameEnv BulkAdd.Yes false g amap scopem true env.eNameResEnv tcrefs } + { env with eNameResEnv = AddTyconRefsToNameEnv BulkAdd.Yes false g amap env.eAccessRights scopem true env.eNameResEnv tcrefs } env -/// Adjust the TcEnv to account for a fully processed "namespace" declaration in thie file +/// Adjust the TcEnv to account for a fully processed "namespace" declaration in this file let AddLocalRootModuleOrNamespace tcSink g amap scopem env (mtyp: ModuleOrNamespaceType) = // Compute the top-rooted module or namespace references let modrefs = mtyp.ModuleAndNamespaceDefinitions |> List.map mkLocalModRef @@ -417,7 +421,7 @@ let AddLocalRootModuleOrNamespace tcSink g amap scopem env (mtyp: ModuleOrNamesp let tcrefs = mtyp.TypeAndExceptionDefinitions |> List.map mkLocalTyconRef let env = AddRootModuleOrNamespaceRefs g amap scopem env modrefs let env = { env with - eNameResEnv = if isNil tcrefs then env.eNameResEnv else AddTyconRefsToNameEnv BulkAdd.No false g amap scopem true env.eNameResEnv tcrefs + eNameResEnv = if isNil tcrefs then env.eNameResEnv else AddTyconRefsToNameEnv BulkAdd.No false g amap env.eAccessRights scopem true env.eNameResEnv tcrefs eUngeneralizableItems = addFreeItemOfModuleTy mtyp env.eUngeneralizableItems } CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights) env @@ -430,7 +434,7 @@ let AddModuleAbbreviationAndReport tcSink scopem id modrefs env = CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights) let item = Item.ModuleOrNamespaces modrefs - CallNameResolutionSink tcSink (id.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink tcSink (id.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.AccessRights) env /// Add a "module X = ..." definition to the TcEnv @@ -534,7 +538,7 @@ type cenv = conditionalDefines = conditionalDefines isInternalTestSpanStackReferring = isInternalTestSpanStackReferring } - override __.ToString() = "cenv(...)" + override __.ToString() = "" let CopyAndFixupTypars m rigid tpsorig = ConstraintSolver.FreshenAndFixupTypars m rigid [] [] tpsorig @@ -545,7 +549,7 @@ let UnifyTypes cenv (env: TcEnv) m actualTy expectedTy = /// Make the initial type checking environment for a single file with an empty accumulator for the overall contents for the file let MakeInitialEnv env = // Note: here we allocate a new module type accumulator - let mtypeAcc = ref (NewEmptyModuleOrNamespaceType Namespace) + let mtypeAcc = ref (Construct.NewEmptyModuleOrNamespaceType Namespace) { env with eModuleOrNamespaceTypeAccumulator = mtypeAcc }, mtypeAcc /// Make an environment suitable for a module or namespace. Does not create a new accumulator but uses one we already have/ @@ -557,13 +561,13 @@ let MakeInnerEnvWithAcc env nm mtypeAcc modKind = eCompPath = cpath eAccessPath = cpath eAccessRights = computeAccessRights cpath env.eInternalsVisibleCompPaths env.eFamilyType // update this computed field - eNameResEnv = { env.eNameResEnv with eDisplayEnv = env.DisplayEnv.AddOpenPath (pathOfLid path) } + eNameResEnv = { env.NameEnv with eDisplayEnv = env.DisplayEnv.AddOpenPath (pathOfLid path) } eModuleOrNamespaceTypeAccumulator = mtypeAcc } /// Make an environment suitable for a module or namespace, creating a new accumulator. let MakeInnerEnv env nm modKind = // Note: here we allocate a new module type accumulator - let mtypeAcc = ref (NewEmptyModuleOrNamespaceType modKind) + let mtypeAcc = ref (Construct.NewEmptyModuleOrNamespaceType modKind) MakeInnerEnvWithAcc env nm mtypeAcc modKind, mtypeAcc /// Make an environment suitable for processing inside a type definition @@ -622,10 +626,10 @@ let BuildRootModuleExpr enclosingNamespacePath (cpath: CompilationPath) mexpr = /// Try to take the "FSINNN" prefix off a namespace path let TryStripPrefixPath (g: TcGlobals) (enclosingNamespacePath: Ident list) = match enclosingNamespacePath with - | p::rest when + | p :: rest when g.isInteractive && not (isNil rest) && - p.idText.StartsWithOrdinal(FsiDynamicModulePrefix) && + p.idText.StartsWithOrdinal FsiDynamicModulePrefix && p.idText.[FsiDynamicModulePrefix.Length..] |> String.forall System.Char.IsDigit -> Some(p, rest) | _ -> None @@ -642,13 +646,13 @@ let ImplicitlyOpenOwnNamespace tcSink g amap scopem enclosingNamespacePath env = | None -> enclosingNamespacePath match enclosingNamespacePathToOpen with - | id::rest -> + | id :: rest -> let ad = env.eAccessRights - match ResolveLongIndentAsModuleOrNamespace tcSink ResultCollectionSettings.AllResults amap scopem true OpenQualified env.eNameResEnv ad id rest true with + match ResolveLongIndentAsModuleOrNamespaceOrStaticClass tcSink ResultCollectionSettings.AllResults amap scopem true true OpenQualified env.eNameResEnv ad id rest true with | Result modrefs -> let modrefs = List.map p23 modrefs let openDecl = OpenDeclaration.Create (enclosingNamespacePathToOpen, modrefs, scopem, true) - OpenModulesOrNamespaces tcSink g amap scopem false env modrefs openDecl + OpenEntities tcSink g amap scopem false env modrefs openDecl | Exception _ -> env | _ -> env @@ -671,22 +675,22 @@ let ShrinkContext env oldRange newRange = | ContextInfo.SequenceExpression _ -> env | ContextInfo.CollectionElement (b,m) -> - if m <> oldRange then env else + if not (Range.equals m oldRange) then env else { env with eContextInfo = ContextInfo.CollectionElement(b,newRange) } | ContextInfo.FollowingPatternMatchClause m -> - if m <> oldRange then env else + if not (Range.equals m oldRange) then env else { env with eContextInfo = ContextInfo.FollowingPatternMatchClause newRange } | ContextInfo.PatternMatchGuard m -> - if m <> oldRange then env else + if not (Range.equals m oldRange) then env else { env with eContextInfo = ContextInfo.PatternMatchGuard newRange } | ContextInfo.IfExpression m -> - if m <> oldRange then env else + if not (Range.equals m oldRange) then env else { env with eContextInfo = ContextInfo.IfExpression newRange } | ContextInfo.OmittedElseBranch m -> - if m <> oldRange then env else + if not (Range.equals m oldRange) then env else { env with eContextInfo = ContextInfo.OmittedElseBranch newRange } | ContextInfo.ElseBranchResult m -> - if m <> oldRange then env else + if not (Range.equals m oldRange) then env else { env with eContextInfo = ContextInfo.ElseBranchResult newRange } /// Optimized unification routine that avoids creating new inference @@ -780,9 +784,9 @@ let UnifyFunctionType extraInfo cenv denv mFunExpr ty = let ReportImplicitlyIgnoredBoolExpression denv m ty expr = let checkExpr m expr = match expr with - | Expr.App(Expr.Val(vf, _, _), _, _, exprs, _) when vf.LogicalName = opNameEquals -> + | Expr.App (Expr.Val (vf, _, _), _, _, exprs, _) when vf.LogicalName = opNameEquals -> match exprs with - | Expr.App(Expr.Val(propRef, _, _), _, _, Expr.Val(vf, _, _) :: _, _) :: _ -> + | Expr.App (Expr.Val (propRef, _, _), _, _, Expr.Val (vf, _, _) :: _, _) :: _ -> if propRef.IsPropertyGetterMethod then let propertyName = propRef.PropertyName let hasCorrespondingSetter = @@ -798,19 +802,19 @@ let ReportImplicitlyIgnoredBoolExpression denv m ty expr = UnitTypeExpectedWithEquality (denv, ty, m) else UnitTypeExpectedWithEquality (denv, ty, m) - | Expr.Op(TOp.ILCall(_, _, _, _, _, _, _, methodRef, _, _, _), _, Expr.Val(vf, _, _) :: _, _) :: _ when methodRef.Name.StartsWithOrdinal("get_") -> + | Expr.Op (TOp.ILCall (_, _, _, _, _, _, _, methodRef, _, _, _), _, Expr.Val (vf, _, _) :: _, _) :: _ when methodRef.Name.StartsWithOrdinal("get_") -> UnitTypeExpectedWithPossiblePropertySetter (denv, ty, vf.DisplayName, PrettyNaming.ChopPropertyName(methodRef.Name), m) - | Expr.Val(vf, _, _) :: _ -> + | Expr.Val (vf, _, _) :: _ -> UnitTypeExpectedWithPossibleAssignment (denv, ty, vf.IsMutable, vf.DisplayName, m) | _ -> UnitTypeExpectedWithEquality (denv, ty, m) | _ -> UnitTypeExpected (denv, ty, m) match expr with - | Expr.Let(_, Expr.Sequential(_, inner, _, _, _), _, _) - | Expr.Sequential(_, inner, _, _, _) -> + | Expr.Let (_, Expr.Sequential (_, inner, _, _, _), _, _) + | Expr.Sequential (_, inner, _, _, _) -> let rec extractNext expr = match expr with - | Expr.Sequential(_, inner, _, _, _) -> extractNext inner + | Expr.Sequential (_, inner, _, _, _) -> extractNext inner | _ -> checkExpr expr.Range expr extractNext inner | expr -> checkExpr m expr @@ -846,6 +850,10 @@ let UnifyUnitType cenv (env: TcEnv) m ty expr = false +let TryUnifyUnitTypeWithoutWarning cenv (env:TcEnv) m ty = + let denv = env.DisplayEnv + AddCxTypeEqualsTypeUndoIfFailedOrWarnings denv cenv.css m ty cenv.g.unit_ty + // Logically extends System.AttributeTargets module AttributeTargets = let FieldDecl = AttributeTargets.Field ||| AttributeTargets.Property @@ -858,7 +866,7 @@ module AttributeTargets = let ForNewConstructors tcSink (env: TcEnv) mObjTy methodName meths = let origItem = Item.CtorGroup(methodName, meths) - let callSink (item, minst) = CallNameResolutionSink tcSink (mObjTy, env.NameEnv, item, origItem, minst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + let callSink (item, minst) = CallMethodGroupNameResolutionSink tcSink (mObjTy, env.NameEnv, item, origItem, minst, ItemOccurence.Use, env.AccessRights) let sendToSink minst refinedMeths = callSink (Item.CtorGroup(methodName, refinedMeths), minst) match meths with | [] -> @@ -891,7 +899,7 @@ let TcConst cenv ty m env c = | SynMeasure.Power(ms, exponent, _) -> Measure.RationalPower (tcMeasure ms, TcSynRationalConst exponent) | SynMeasure.Product(ms1, ms2, _) -> Measure.Prod(tcMeasure ms1, tcMeasure ms2) - | SynMeasure.Divide(ms1, ((SynMeasure.Seq (_::(_::_), _)) as ms2), m) -> + | SynMeasure.Divide(ms1, ((SynMeasure.Seq (_ :: (_ :: _), _)) as ms2), m) -> warning(Error(FSComp.SR.tcImplicitMeasureFollowingSlash(), m)) Measure.Prod(tcMeasure ms1, Measure.Inv (tcMeasure ms2)) | SynMeasure.Divide(ms1, ms2, _) -> @@ -962,7 +970,7 @@ let AdjustValSynInfoInSignature g ty (SynValInfo(argsData, retData) as sigMD) = /// The ValReprInfo for a value, except the number of typars is not yet inferred type PartialValReprInfo = PartialValReprInfo of ArgReprInfo list list * ArgReprInfo -let TranslateTopArgSynInfo isArg m tcAttributes (SynArgInfo(attrs, isOpt, nm)) = +let TranslateTopArgSynInfo isArg m tcAttributes (SynArgInfo(Attributes attrs, isOpt, nm)) = // Synthesize an artificial "OptionalArgument" attribute for the parameter let optAttrs = if isOpt then @@ -986,7 +994,7 @@ let TranslateTopArgSynInfo isArg m tcAttributes (SynArgInfo(attrs, isOpt, nm)) = /// Members have an arity inferred from their syntax. This "valSynData" is not quite the same as the arities /// used in the middle and backends of the compiler ("topValInfo"). -/// "0" in a valSynData (see Ast.arity_of_pat) means a "unit" arg in a topValInfo +/// "0" in a valSynData (see arity_of_pat) means a "unit" arg in a topValInfo /// Hence remove all "zeros" from arity and replace them with 1 here. /// Note we currently use the compiled form for choosing unique names, to distinguish overloads because this must match up /// between signature and implementation, and the signature just has "unit". @@ -1054,12 +1062,12 @@ let MakeMemberDataAndMangledNameForMemberVal(g, tcref, isExtrinsic, attrs, optIm let name = DecompileOpName id.idText // Check symbolic members. Expect valSynData implied arity to be [[2]]. match SynInfo.AritiesOfArgs valSynData with - | [] | [0] -> warning(Error(FSComp.SR.memberOperatorDefinitionWithNoArguments(name), m)) + | [] | [0] -> warning(Error(FSComp.SR.memberOperatorDefinitionWithNoArguments name, m)) | n :: otherArgs -> let opTakesThreeArgs = PrettyNaming.IsTernaryOperator name if n<>2 && not opTakesThreeArgs then warning(Error(FSComp.SR.memberOperatorDefinitionWithNonPairArgument(name, n), m)) if n<>3 && opTakesThreeArgs then warning(Error(FSComp.SR.memberOperatorDefinitionWithNonTripleArgument(name, n), m)) - if not (isNil otherArgs) then warning(Error(FSComp.SR.memberOperatorDefinitionWithCurriedArguments(name), m)) + if not (isNil otherArgs) then warning(Error(FSComp.SR.memberOperatorDefinitionWithCurriedArguments name, m)) if isExtrinsic && IsMangledOpName id.idText then warning(Error(FSComp.SR.tcMemberOperatorDefinitionInExtrinsic(), id.idRange)) @@ -1252,7 +1260,7 @@ type TcPatPhase2Input = type CheckedBindingInfo = | CheckedBindingInfo of ValInline * - Tast.Attribs * + Attribs * XmlDoc * (TcPatPhase2Input -> PatternMatchCompilation.Pattern) * ExplicitTyparInfo * @@ -1261,7 +1269,7 @@ type CheckedBindingInfo = ArgAndRetAttribs * TType * range * - SequencePointInfoForBinding * + DebugPointForBinding * bool * // compiler generated? Const option * // literal value? bool // fixed? @@ -1273,7 +1281,7 @@ let GeneralizedTypeForTypeScheme typeScheme = let (TypeScheme(generalizedTypars, tau)) = typeScheme mkForallTyIfNeeded generalizedTypars tau -/// Create a type scheme for somthing that is not generic +/// Create a type scheme for something that is not generic let NonGenericTypeScheme ty = TypeScheme([], ty) //------------------------------------------------------------------------- @@ -1296,7 +1304,7 @@ let PublishModuleDefn cenv env mspec = if intoFslibCcu then mty else mty.AddEntity mspec) let item = Item.ModuleOrNamespaces([mkLocalModRef mspec]) - CallNameResolutionSink cenv.tcSink (mspec.Range, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Binding, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (mspec.Range, env.NameEnv, item, emptyTyparInst, ItemOccurence.Binding, env.AccessRights) let PublishTypeDefn cenv env tycon = UpdateAccModuleOrNamespaceType cenv env (fun _ mty -> @@ -1429,7 +1437,7 @@ let MakeAndPublishVal cenv env (altActualParent, inSig, declKind, vrec, vscheme, // Members of interface implementations have the accessibility of the interface // they are implementing. let vis = - if Tastops.MemberIsExplicitImpl cenv.g memberInfo then + if MemberIsExplicitImpl cenv.g memberInfo then let slotSig = List.head memberInfo.ImplementedSlotSigs match slotSig.ImplementedType with | TType_app (tyconref, _) -> Some tyconref.Accessibility @@ -1503,11 +1511,13 @@ let MakeAndPublishVal cenv env (altActualParent, inSig, declKind, vrec, vscheme, | None -> None + let mut = if isMutable then Mutable else Immutable let vspec = - NewVal (logicalName, id.idRange, compiledName, ty, - (if ((* (isByrefTy cenv.g ty) || *) isMutable) then Mutable else Immutable), - compgen, topValData, vis, vrec, memberInfoOpt, baseOrThis, attrs, inlineFlag, doc, isTopBinding, isExtrinsic, isIncrClass, isTyFunc, - (hasDeclaredTypars || inSig), isGeneratedEventVal, konst, actualParent) + Construct.NewVal + (logicalName, id.idRange, compiledName, ty, mut, + compgen, topValData, vis, vrec, memberInfoOpt, baseOrThis, attrs, inlineFlag, + doc, isTopBinding, isExtrinsic, isIncrClass, isTyFunc, + (hasDeclaredTypars || inSig), isGeneratedEventVal, konst, actualParent) CheckForAbnormalOperatorNames cenv id.idRange vspec.CoreDisplayName memberInfoOpt @@ -1526,12 +1536,12 @@ let MakeAndPublishVal cenv env (altActualParent, inSig, declKind, vrec, vscheme, baseOrThisInfo = ValBaseOrThisInfo.MemberThisVal && vspec.LogicalName = "__" -> false | _ -> true - match cenv.tcSink.CurrentSink with + match cenv.tcSink.CurrentSink with | Some _ when not vspec.IsCompilerGenerated && shouldNotifySink vspec -> let nenv = AddFakeNamedValRefToNameEnv vspec.DisplayName env.NameEnv (mkLocalValRef vspec) CallEnvSink cenv.tcSink (vspec.Range, nenv, env.eAccessRights) let item = Item.Value(mkLocalValRef vspec) - CallNameResolutionSink cenv.tcSink (vspec.Range, nenv, item, item, emptyTyparInst, ItemOccurence.Binding, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (vspec.Range, nenv, item, emptyTyparInst, ItemOccurence.Binding, env.eAccessRights) | _ -> () vspec @@ -1546,12 +1556,12 @@ let MakeAndPublishVals cenv env (altActualParent, inSig, declKind, vrec, valSche let MakeAndPublishBaseVal cenv env baseIdOpt ty = baseIdOpt |> Option.map (fun (id: Ident) -> - let valscheme = ValScheme(id, NonGenericTypeScheme(ty), None, None, false, ValInline.Never, BaseVal, None, false, false, false, false) + let valscheme = ValScheme(id, NonGenericTypeScheme ty, None, None, false, ValInline.Never, BaseVal, None, false, false, false, false) MakeAndPublishVal cenv env (ParentNone, false, ExpressionBinding, ValNotInRecScope, valscheme, [], XmlDoc.Empty, None, false)) let InstanceMembersNeedSafeInitCheck cenv m thisTy = ExistsInEntireHierarchyOfType - (fun ty -> not (isStructTy cenv.g ty) && (match tryDestAppTy cenv.g ty with ValueSome tcref when tcref.HasSelfReferentialConstructor -> true | _ -> false)) + (fun ty -> not (isStructTy cenv.g ty) && (match tryTcrefOfAppTy cenv.g ty with ValueSome tcref when tcref.HasSelfReferentialConstructor -> true | _ -> false)) cenv.g cenv.amap m @@ -1559,9 +1569,12 @@ let InstanceMembersNeedSafeInitCheck cenv m thisTy = thisTy let MakeSafeInitField (g: TcGlobals) env m isStatic = - let id = ident(globalNng.FreshCompilerGeneratedName("init", m), m) + let id = + // Ensure that we have an g.CompilerGlobalState + assert(g.CompilerGlobalState |> Option.isSome) + ident(g.CompilerGlobalState.Value.NiceNameGenerator.FreshCompilerGeneratedName("init", m), m) let taccess = TAccess [env.eAccessPath] - NewRecdField isStatic None id false g.int_ty true true [] [] XmlDoc.Empty taccess true + Construct.NewRecdField isStatic None id false g.int_ty true true [] [] XmlDoc.Empty taccess true // Make the "delayed reference" boolean value recording the safe initialization of a type in a hierarchy where there is a HasSelfReferentialConstructor let ComputeInstanceSafeInitInfo cenv env m thisTy = @@ -1609,8 +1622,8 @@ let AdjustAndForgetUsesOfRecValue cenv (vrefTgt: ValRef) (valScheme: ValScheme) let fixedUpExpr = let vrefFlags, tyargs0 = match fixupPoint.Value with - | Expr.App(Expr.Val (_, vrefFlags, _), _, tyargs0, [], _) -> vrefFlags, tyargs0 - | Expr.Val(_, vrefFlags, _) -> vrefFlags, [] + | Expr.App (Expr.Val (_, vrefFlags, _), _, tyargs0, [], _) -> vrefFlags, tyargs0 + | Expr.Val (_, vrefFlags, _) -> vrefFlags, [] | _ -> errorR(Error(FSComp.SR.tcUnexpectedExprAtRecInfPoint(), m)) NormalValUse, [] @@ -1638,7 +1651,7 @@ let RecordUseOfRecValue cenv vrec (vrefTgt: ValRef) vexp m = | ValInRecScope isComplete -> let fixupPoint = ref vexp cenv.recUses <- cenv.recUses.Add (vrefTgt.Deref, (fixupPoint, m, isComplete)) - Expr.Link (fixupPoint) + Expr.Link fixupPoint | ValNotInRecScope -> vexp @@ -1727,7 +1740,7 @@ let GeneralizeVals cenv denv enclosingDeclaredTypars generalizedTypars types = let DontGeneralizeVals types = let dontGeneralizeVal (PrelimValScheme1(id, _, ty, partialValReprInfoOpt, memberInfoOpt, isMutable, inlineFlag, baseOrThis, argAttribs, vis, compgen)) = - PrelimValScheme2(id, NonGenericTypeScheme(ty), partialValReprInfoOpt, memberInfoOpt, isMutable, inlineFlag, baseOrThis, argAttribs, vis, compgen, false) + PrelimValScheme2(id, NonGenericTypeScheme ty, partialValReprInfoOpt, memberInfoOpt, isMutable, inlineFlag, baseOrThis, argAttribs, vis, compgen, false) NameMap.map dontGeneralizeVal types let InferGenericArityFromTyScheme (TypeScheme(generalizedTypars, _)) partialValReprInfo = @@ -1786,7 +1799,7 @@ let CombineSyntacticAndInferredArities g declKind rhsExpr prelimScheme = // Don't use any expression information for members, where syntax dictates the arity completely | _ when memberInfoOpt.IsSome -> partialValReprInfoOpt - | Some(partialValReprInfoFromSyntax), true -> + | Some partialValReprInfoFromSyntax, true -> let (PartialValReprInfo(curriedArgInfosFromSyntax, retInfoFromSyntax)) = partialValReprInfoFromSyntax let partialArityInfo = if isMutable then @@ -1811,11 +1824,11 @@ let CombineSyntacticAndInferredArities g declKind rhsExpr prelimScheme = // If the expression infers additional arguments then use those (this shouldn't happen, since the // arity inference done on the syntactic form should give identical results) | [], ais | ais, [] -> ais - | (h1::t1), (h2::t2) -> choose h1 h2 :: loop t1 t2 + | (h1 :: t1), (h2 :: t2) -> choose h1 h2 :: loop t1 t2 let curriedArgInfos = loop curriedArgInfosFromSyntax curriedArgInfosFromExpression PartialValReprInfo (curriedArgInfos, retInfoFromSyntax) - Some(partialArityInfo) + Some partialArityInfo let BuildValScheme declKind partialArityInfoOpt prelimScheme = let (PrelimValScheme2(id, typeScheme, _, memberInfoOpt, isMutable, inlineFlag, baseOrThis, _, vis, compgen, hasDeclaredTypars)) = prelimScheme @@ -1834,71 +1847,72 @@ let UseCombinedArity g declKind rhsExpr prelimScheme = let UseNoArity prelimScheme = BuildValScheme ExpressionBinding None prelimScheme -let MakeSimpleVals cenv env names = +/// Make and publish the Val nodes for a collection of simple (non-generic) value specifications +let MakeAndPublishSimpleVals cenv env names = let tyschemes = DontGeneralizeVals names let valSchemes = NameMap.map UseNoArity tyschemes let values = MakeAndPublishVals cenv env (ParentNone, false, ExpressionBinding, ValNotInRecScope, valSchemes, [], XmlDoc.Empty, None) let vspecMap = NameMap.map fst values values, vspecMap -let MakeAndPublishSimpleVals cenv env m names mergeNamesInOneNameresEnv = - +/// Make and publish the Val nodes for a collection of value specifications at Lambda and Match positions +/// +/// We merge the additions to the name resolution environment into one using a merged range so all values are brought +/// into scope simultaneously. The technique used to do this is a disturbing and unfortunate hack that +/// intercepts `NotifyNameResolution` calls being emitted by `MakeAndPublishSimpleVals` + +let MakeAndPublishSimpleValsForMergedScope cenv env m (names: NameMap<_>) = let values, vspecMap = - if not mergeNamesInOneNameresEnv then MakeSimpleVals cenv env names + if names.Count <= 1 then + MakeAndPublishSimpleVals cenv env names else - // reason: now during typecheck we create new name resolution environment for all components of tupled arguments in lambda. - // When trying to find best environment for the given position first we pick the most deeply nested scope that contains given position - // (and that will be lambda body - correct one), then we look for the better subtree on the left hand side - // (and that will be name resolution environment containing second parameter parameter - without the first one). - // fix: I've tried to make fix as local as possible to reduce overall impact on the source code. - // Idea of the fix: replace existing typecheck results sink and capture all reported name resolutions (this will be all parameters in lambda). - // After that - we restore the sink back, generate new name resolution environment that contains all captured names and report generated environment - // to the old sink. - - - // default behavior - send EnvWithScope notification for every resolved name - // what we do here is override this default behavior and capture only all name resolution notifications - // later we'll process them and create one name resolution env that will contain names from all notifications let nameResolutions = ResizeArray() + + let notifyNameResolution (pos, item, itemGroup, itemTyparInst, occurence, nenv, ad, (m: range), replacing) = + if not m.IsSynthetic then + nameResolutions.Add(pos, item, itemGroup, itemTyparInst, occurence, nenv, ad, m, replacing) + let values, vspecMap = let sink = { new ITypecheckResultsSink with member this.NotifyEnvWithScope(_, _, _) = () // ignore EnvWithScope reports - member this.NotifyNameResolution(pos, item, itemGroup, itemTyparInst, occurence, denv, nenv, ad, m, replacing) = - if not m.IsSynthetic then - nameResolutions.Add(pos, item, itemGroup, itemTyparInst, occurence, denv, nenv, ad, m, replacing) - member this.NotifyExprHasType(_, _, _, _, _, _) = assert false // no expr typings in MakeSimpleVals + + member this.NotifyNameResolution(pos, item, itemTyparInst, occurence, nenv, ad, m, replacing) = + notifyNameResolution (pos, item, item, itemTyparInst, occurence, nenv, ad, m, replacing) + + member this.NotifyMethodGroupNameResolution(pos, item, itemGroup, itemTyparInst, occurence, nenv, ad, m, replacing) = + notifyNameResolution (pos, item, itemGroup, itemTyparInst, occurence, nenv, ad, m, replacing) + + member this.NotifyExprHasType(_, _, _, _) = assert false // no expr typings in MakeAndPublishSimpleVals member this.NotifyFormatSpecifierLocation(_, _) = () member this.NotifyOpenDeclaration(_) = () - member this.CurrentSource = None + member this.CurrentSourceText = None member this.FormatStringCheckContext = None } use _h = WithNewTypecheckResultsSink(sink, cenv.tcSink) - MakeSimpleVals cenv env names + MakeAndPublishSimpleVals cenv env names if nameResolutions.Count <> 0 then - let (_, _, _, _, _, _, _, ad, m1, _replacing) = nameResolutions.[0] + let (_, _, _, _, _, _, ad, m1, _replacing) = nameResolutions.[0] // mergedNameEnv - name resolution env that contains all names // mergedRange - union of ranges of names let mergedNameEnv, mergedRange = - ((env.NameEnv, m1), nameResolutions) ||> Seq.fold (fun (nenv, merged) (_, item, _, _, _, _, _, _, m, _) -> + ((env.NameEnv, m1), nameResolutions) ||> Seq.fold (fun (nenv, merged) (_, item, _, _, _, _, _, m, _) -> // MakeAndPublishVal creates only Item.Value - let item = match item with Item.Value(item) -> item | _ -> failwith "impossible" + let item = match item with Item.Value item -> item | _ -> failwith "impossible" (AddFakeNamedValRefToNameEnv item.DisplayName nenv item), (unionRanges m merged) ) // send notification about mergedNameEnv CallEnvSink cenv.tcSink (mergedRange, mergedNameEnv, ad) // call CallNameResolutionSink for all captured name resolutions using mergedNameEnv - for (_, item, itemGroup, itemTyparInst, occurence, denv, _nenv, ad, m, _replacing) in nameResolutions do - CallNameResolutionSink cenv.tcSink (m, mergedNameEnv, item, itemGroup, itemTyparInst, occurence, denv, ad) + for (_, item, itemGroup, itemTyparInst, occurence, _nenv, ad, m, _replacing) in nameResolutions do + CallMethodGroupNameResolutionSink cenv.tcSink (m, mergedNameEnv, item, itemGroup, itemTyparInst, occurence, ad) values, vspecMap let envinner = AddLocalValMap cenv.tcSink m vspecMap env envinner, values, vspecMap - - //------------------------------------------------------------------------- // Helpers to freshen existing types and values, i.e. when a reference // to C<_> occurs then generate C for a fresh type inference variable ?ty. @@ -1923,7 +1937,7 @@ let FreshenPossibleForallTy g m rigid ty = let tps, renaming, tinst = CopyAndFixupTypars m rigid tpsorig tpsorig, tps, tinst, instType renaming tau -let infoOfTyconRef m (tcref: TyconRef) = +let FreshenTyconRef2 m (tcref: TyconRef) = let tps, renaming, tinst = FreshenTypeInst m (tcref.Typars m) tps, renaming, tinst, TType_app (tcref, tinst) @@ -2004,7 +2018,7 @@ let BuildFieldMap cenv env isPartial ty flds m = // Record the precise resolution of the field for intellisense let item = FreshenRecdFieldRef cenv.nameResolver m fref2 - CallNameResolutionSink cenv.tcSink ((snd fld).idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, ad) + CallNameResolutionSink cenv.tcSink ((snd fld).idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, ad) CheckRecdFieldAccessible cenv.amap m env.eAccessRights fref2 |> ignore CheckFSharpAttributes cenv.g fref2.PropertyAttribs m |> CommitOperationResult @@ -2019,7 +2033,7 @@ let BuildFieldMap cenv env isPartial ty flds m = errorR (FieldsFromDifferentTypes(env.DisplayEnv, fref1, fref2, m)) fs, rfldsList else - Map.add fref2.FieldName fldExpr fs, (fref2.FieldName, fldExpr)::rfldsList + Map.add fref2.FieldName fldExpr fs, (fref2.FieldName, fldExpr) :: rfldsList | _ -> error(Error(FSComp.SR.tcRecordFieldInconsistentTypes(), m))) tcref, fldsmap, List.rev rfldsList @@ -2105,30 +2119,30 @@ module GeneralizationHelpers = let ftps = item.GetFreeTyvars().FreeTypars if not ftps.IsEmpty then for ftp in ftps do - acc.Add(ftp) + acc.Add ftp Zset.Create(typarOrder, acc) let ComputeUnabstractableTycons env = - let acc_in_free_item acc (item: UngeneralizableItem) = + let accInFreeItem acc (item: UngeneralizableItem) = let ftycs = if item.WillNeverHaveFreeTypars then item.CachedFreeLocalTycons else let ftyvs = item.GetFreeTyvars() ftyvs.FreeTycons if ftycs.IsEmpty then acc else unionFreeTycons ftycs acc - List.fold acc_in_free_item emptyFreeTycons env.eUngeneralizableItems + List.fold accInFreeItem emptyFreeTycons env.eUngeneralizableItems let ComputeUnabstractableTraitSolutions env = - let acc_in_free_item acc (item: UngeneralizableItem) = + let accInFreeItem acc (item: UngeneralizableItem) = let ftycs = if item.WillNeverHaveFreeTypars then item.CachedFreeTraitSolutions else let ftyvs = item.GetFreeTyvars() ftyvs.FreeTraitSolutions if ftycs.IsEmpty then acc else unionFreeLocals ftycs acc - List.fold acc_in_free_item emptyFreeLocals env.eUngeneralizableItems + List.fold accInFreeItem emptyFreeLocals env.eUngeneralizableItems let rec IsGeneralizableValue g t = match t with @@ -2138,42 +2152,42 @@ module GeneralizationHelpers = | Expr.Val (vref, _, m) -> not (isByrefLikeTy g m vref.Type) // Look through coercion nodes corresponding to introduction of subsumption - | Expr.Op(TOp.Coerce, [inputTy;actualTy], [e1], _) when isFunTy g actualTy && isFunTy g inputTy -> + | Expr.Op (TOp.Coerce, [inputTy;actualTy], [e1], _) when isFunTy g actualTy && isFunTy g inputTy -> IsGeneralizableValue g e1 - | Expr.Op(op, _, args, _) -> + | Expr.Op (op, _, args, _) -> let canGeneralizeOp = match op with | TOp.Tuple _ -> true | TOp.UnionCase uc -> not (isUnionCaseRefDefinitelyMutable uc) - | TOp.Recd(ctorInfo, tcref) -> + | TOp.Recd (ctorInfo, tcref) -> match ctorInfo with | RecdExpr -> not (isRecdOrUnionOrStructTyconRefDefinitelyMutable tcref) | RecdExprIsObjInit -> false | TOp.Array -> isNil args | TOp.ExnConstr ec -> not (isExnDefinitelyMutable ec) - | TOp.ILAsm([], _) -> true + | TOp.ILAsm ([], _) -> true | _ -> false canGeneralizeOp && List.forall (IsGeneralizableValue g) args - | Expr.LetRec(binds, body, _, _) -> + | Expr.LetRec (binds, body, _, _) -> binds |> List.forall (fun b -> not b.Var.IsMutable) && binds |> List.forall (fun b -> IsGeneralizableValue g b.Expr) && IsGeneralizableValue g body - | Expr.Let(bind, body, _, _) -> + | Expr.Let (bind, body, _, _) -> not bind.Var.IsMutable && IsGeneralizableValue g bind.Expr && IsGeneralizableValue g body // Applications of type functions are _not_ normally generalizable unless explicitly marked so - | Expr.App(Expr.Val (vref, _, _), _, _, [], _) when vref.IsTypeFunction -> + | Expr.App (Expr.Val (vref, _, _), _, _, [], _) when vref.IsTypeFunction -> HasFSharpAttribute g g.attrib_GeneralizableValueAttribute vref.Attribs - | Expr.App(e1, _, _, [], _) -> IsGeneralizableValue g e1 - | Expr.TyChoose(_, b, _) -> IsGeneralizableValue g b + | Expr.App (e1, _, _, [], _) -> IsGeneralizableValue g e1 + | Expr.TyChoose (_, b, _) -> IsGeneralizableValue g b | Expr.Obj (_, ty, _, _, _, _, _) -> isInterfaceTy g ty || isDelegateTy g ty | Expr.Link eref -> IsGeneralizableValue g !eref @@ -2276,24 +2290,17 @@ module GeneralizationHelpers = ConstraintSolver.ChooseTyparSolutionAndSolve cenv.css denv tp) generalizedTypars - let CanonicalizePartialInferenceProblem (cenv, denv, m) tps = - // Canonicalize constraints prior to generalization - let csenv = (MakeConstraintSolverEnv ContextInfo.NoContext cenv.css m denv) - TryD (fun () -> ConstraintSolver.CanonicalizeRelevantMemberConstraints csenv 0 NoTrace tps) - (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) - |> RaiseOperationResult - - let ComputeAndGeneralizeGenericTypars (cenv, - denv: DisplayEnv, - m, - freeInEnv: FreeTypars, - canInferTypars, - genConstrainedTyparFlag, - inlineFlag, - exprOpt, - allDeclaredTypars: Typars, - maxInferredTypars: Typars, - tauTy, + let ComputeAndGeneralizeGenericTypars (cenv, + denv: DisplayEnv, + m, + freeInEnv: FreeTypars, + canInferTypars, + genConstrainedTyparFlag, + inlineFlag, + exprOpt, + allDeclaredTypars: Typars, + maxInferredTypars: Typars, + tauTy, resultFirst) = let allDeclaredTypars = NormalizeDeclaredTyparsForEquiRecursiveInference cenv.g allDeclaredTypars @@ -2325,8 +2332,7 @@ module GeneralizationHelpers = generalizedTypars |> List.iter (SetTyparRigid cenv.g denv m) // Generalization removes constraints related to generalized type variables - let csenv = MakeConstraintSolverEnv ContextInfo.NoContext cenv.css m denv - EliminateConstraintsForGeneralizedTypars csenv NoTrace generalizedTypars + EliminateConstraintsForGeneralizedTypars denv cenv.css m NoTrace generalizedTypars generalizedTypars @@ -2436,7 +2442,7 @@ type NormalizedBindingRhs = let PushOnePatternToRhs (cenv: cenv) isMember p (NormalizedBindingRhs(spatsL, rtyOpt, rhsExpr)) = let spats, rhsExpr = PushPatternToExpr cenv.synArgNameGenerator isMember p rhsExpr - NormalizedBindingRhs(spats::spatsL, rtyOpt, rhsExpr) + NormalizedBindingRhs(spats :: spatsL, rtyOpt, rhsExpr) type NormalizedBindingPatternInfo = NormalizedBindingPat of SynPat * NormalizedBindingRhs * SynValData * SynValTyparDecls @@ -2448,16 +2454,16 @@ type NormalizedBinding = | NormalizedBinding of SynAccess option * SynBindingKind * - bool * (* pesudo/mustinline value? *) + bool * (* pseudo/mustinline value? *) bool * (* mutable *) - SynAttributes * + SynAttribute list * XmlDoc * SynValTyparDecls * SynValData * SynPat * NormalizedBindingRhs * range * - SequencePointInfoForBinding + DebugPointForBinding type IsObjExprBinding = @@ -2526,18 +2532,18 @@ module BindingNormalization = | _ -> MakeNormalizedInstanceMemberBinding cenv thisId memberId toolId vis m typars args rhsExpr valSynData let private NormalizeBindingPattern cenv nameResolver isObjExprBinding (env: TcEnv) valSynData pat rhsExpr = - let ad = env.eAccessRights + let ad = env.AccessRights let (SynValData(memberFlagsOpt, _, _)) = valSynData let rec normPattern pat = // One major problem with versions of F# prior to 1.9.x was that data constructors easily 'pollute' the namespace // of available items, to the point that you can't even define a function with the same name as an existing union case. match pat with | SynPat.FromParseError(p, _) -> normPattern p - | SynPat.LongIdent (LongIdentWithDots(longId, _), toolId, tyargs, SynConstructorArgs.Pats args, vis, m) -> + | SynPat.LongIdent (LongIdentWithDots(longId, _), toolId, tyargs, SynArgPats.Pats args, vis, m) -> let typars = match tyargs with None -> inferredTyparDecls | Some typars -> typars match memberFlagsOpt with | None -> - match ResolvePatternLongIdent cenv.tcSink nameResolver AllIdsOK true m ad env.eNameResEnv TypeNameResolutionInfo.Default longId with + match ResolvePatternLongIdent cenv.tcSink nameResolver AllIdsOK true m ad env.NameEnv TypeNameResolutionInfo.Default longId with | Item.NewDef id -> if id.idText = opNameCons then NormalizedBindingPat(pat, rhsExpr, valSynData, typars) @@ -2580,7 +2586,7 @@ module BindingNormalization = let NormalizeBinding isObjExprBinding cenv (env: TcEnv) b = match b with - | Binding (vis, bkind, isInline, isMutable, attrs, doc, valSynData, p, retInfo, rhsExpr, mBinding, spBind) -> + | Binding (vis, bkind, isInline, isMutable, Attributes attrs, doc, valSynData, p, retInfo, rhsExpr, mBinding, spBind) -> let (NormalizedBindingPat(pat, rhsExpr, valSynData, typars)) = NormalizeBindingPattern cenv cenv.nameResolver isObjExprBinding env valSynData p (NormalizedBindingRhs ([], retInfo, rhsExpr)) NormalizedBinding(vis, bkind, isInline, isMutable, attrs, doc.ToXmlDoc(), typars, valSynData, pat, rhsExpr, mBinding, spBind) @@ -2600,7 +2606,7 @@ module EventDeclarationNormalization = match argInfos with | [[thisArgInfo];[]] -> [[thisArgInfo];SynInfo.unnamedTopArg] // instance property getter | [[]] -> [SynInfo.unnamedTopArg] // static property getter - | _ -> error(BadEventTransformation(m)) + | _ -> error(BadEventTransformation m) // reconstitute valSynInfo SynValInfo(argInfos, retInfo) @@ -2611,7 +2617,7 @@ module EventDeclarationNormalization = let private ConvertMemberFlagsOpt m memberFlagsOpt = match memberFlagsOpt with | Some memberFlags -> Some (ConvertMemberFlags memberFlags) - | _ -> error(BadEventTransformation(m)) + | _ -> error(BadEventTransformation m) let private ConvertSynData m valSynData = let (SynValData(memberFlagsOpt, valSynInfo, thisIdOpt)) = valSynData @@ -2646,7 +2652,7 @@ module EventDeclarationNormalization = match rhsExpr with // Detect 'fun () -> e' which results from the compilation of a property getter | SynExpr.Lambda (_, _, SynSimplePats.SimplePats([], _), trueRhsExpr, m) -> - let rhsExpr = mkSynApp1 (SynExpr.DotGet(SynExpr.Paren(trueRhsExpr, range0, None, m), range0, LongIdentWithDots([ident(target, m)], []), m)) (SynExpr.Ident(ident(argName, m))) m + let rhsExpr = mkSynApp1 (SynExpr.DotGet (SynExpr.Paren (trueRhsExpr, range0, None, m), range0, LongIdentWithDots([ident(target, m)], []), m)) (SynExpr.Ident (ident(argName, m))) m // reconstitute rhsExpr let bindingRhs = NormalizedBindingRhs([], None, rhsExpr) @@ -2656,7 +2662,7 @@ module EventDeclarationNormalization = bindingRhs, valSynData | _ -> - error(BadEventTransformation(m)) + error(BadEventTransformation m) // reconstitute the binding NormalizedBinding(vis1, bindingKind, isInline, isMutable, [], bindingXmlDoc, noInferredTypars, valSynData, declPattern, bindingRhs, mBinding, spBind) @@ -2765,7 +2771,7 @@ let TcVal checkAttributes cenv env tpenv (vref: ValRef) optInst optAfterResoluti // [] // let Null = null let tpsorig, _, tinst, tau = FreshenPossibleForallTy cenv.g m TyparRigidity.Flexible vty - tpsorig, Expr.Const(c, m, tau), isSpecial, tau, tinst, tpenv + tpsorig, Expr.Const (c, m, tau), isSpecial, tau, tinst, tpenv | None -> // References to 'this' in classes get dereferenced from their implicit reference cell and poked @@ -2855,7 +2861,7 @@ let LightweightTcValForUsingInBuildMethodCall g (vref: ValRef) vrefFlags (vrefTy match v.LiteralValue with | Some c -> let _, _, _, tau = FreshenPossibleForallTy g m TyparRigidity.Flexible vty - Expr.Const(c, m, tau), tau + Expr.Const (c, m, tau), tau | None -> // Instantiate the value let tau = @@ -2893,12 +2899,12 @@ type ApplicableExpr = let (ApplicableExpr (cenv, fe, first)) = x let combinedExpr = match fe with - | Expr.App(e1, e1ty, tyargs1, args1, e1m) when + | Expr.App (e1, e1ty, tyargs1, args1, e1m) when (not first || isNil args1) && (not (isForallTy cenv.g e1ty) || isFunTy cenv.g (applyTys cenv.g e1ty (tyargs1, args1))) -> - Expr.App(e1, e1ty, tyargs1, args1@[e2], unionRanges e1m m) + Expr.App (e1, e1ty, tyargs1, args1@[e2], unionRanges e1m m) | _ -> - Expr.App(fe, tyOfExpr cenv.g fe, [], [e2], m) + Expr.App (fe, tyOfExpr cenv.g fe, [], [e2], m) ApplicableExpr(cenv, combinedExpr, false) member x.Expr = @@ -2940,15 +2946,16 @@ let MakeApplicableExprNoFlex cenv expr = /// first transform the tree (currently in optimization) let MakeApplicableExprWithFlex cenv (env: TcEnv) expr = - let exprTy = tyOfExpr cenv.g expr + let g = cenv.g + let exprTy = tyOfExpr g expr let m = expr.Range - let isNonFlexibleType ty = isSealedTy cenv.g ty + let isNonFlexibleType ty = isSealedTy g ty - let argTys, retTy = stripFunTy cenv.g exprTy - let curriedActualTypes = argTys |> List.map (tryDestRefTupleTy cenv.g) + let argTys, retTy = stripFunTy g exprTy + let curriedActualTypes = argTys |> List.map (tryDestRefTupleTy g) if (curriedActualTypes.IsEmpty || - curriedActualTypes |> List.exists (List.exists (isByrefTy cenv.g)) || + curriedActualTypes |> List.exists (List.exists (isByrefTy g)) || curriedActualTypes |> List.forall (List.forall isNonFlexibleType)) then ApplicableExpr (cenv, expr, true) @@ -2963,50 +2970,51 @@ let MakeApplicableExprWithFlex cenv (env: TcEnv) expr = flexibleType) // Create a coercion to represent the expansion of the application - let expr = mkCoerceExpr (expr, mkIteratedFunTy (List.map (mkRefTupledTy cenv.g) curriedFlexibleTypes) retTy, m, exprTy) + let expr = mkCoerceExpr (expr, mkIteratedFunTy (List.map (mkRefTupledTy g) curriedFlexibleTypes) retTy, m, exprTy) ApplicableExpr (cenv, expr, true) /// Checks, warnings and constraint assertions for downcasts let TcRuntimeTypeTest isCast isOperator cenv denv m tgtTy srcTy = - if TypeDefinitelySubsumesTypeNoCoercion 0 cenv.g cenv.amap m tgtTy srcTy then - warning(TypeTestUnnecessary(m)) + let g = cenv.g + if TypeDefinitelySubsumesTypeNoCoercion 0 g cenv.amap m tgtTy srcTy then + warning(TypeTestUnnecessary m) - if isTyparTy cenv.g srcTy && not (destTyparTy cenv.g srcTy).IsCompatFlex then + if isTyparTy g srcTy && not (destTyparTy g srcTy).IsCompatFlex then error(IndeterminateRuntimeCoercion(denv, srcTy, tgtTy, m)) - if isSealedTy cenv.g srcTy then + if isSealedTy g srcTy then error(RuntimeCoercionSourceSealed(denv, srcTy, m)) - if isSealedTy cenv.g tgtTy || isTyparTy cenv.g tgtTy || not (isInterfaceTy cenv.g srcTy) then + if isSealedTy g tgtTy || isTyparTy g tgtTy || not (isInterfaceTy g srcTy) then if isCast then AddCxTypeMustSubsumeType (ContextInfo.RuntimeTypeTest isOperator) denv cenv.css m NoTrace srcTy tgtTy else AddCxTypeMustSubsumeType ContextInfo.NoContext denv cenv.css m NoTrace srcTy tgtTy - if isErasedType cenv.g tgtTy then + if isErasedType g tgtTy then if isCast then - warning(Error(FSComp.SR.tcTypeCastErased(NicePrint.minimalStringOfType denv tgtTy, NicePrint.minimalStringOfType denv (stripTyEqnsWrtErasure EraseAll cenv.g tgtTy)), m)) + warning(Error(FSComp.SR.tcTypeCastErased(NicePrint.minimalStringOfType denv tgtTy, NicePrint.minimalStringOfType denv (stripTyEqnsWrtErasure EraseAll g tgtTy)), m)) else - error(Error(FSComp.SR.tcTypeTestErased(NicePrint.minimalStringOfType denv tgtTy, NicePrint.minimalStringOfType denv (stripTyEqnsWrtErasure EraseAll cenv.g tgtTy)), m)) + error(Error(FSComp.SR.tcTypeTestErased(NicePrint.minimalStringOfType denv tgtTy, NicePrint.minimalStringOfType denv (stripTyEqnsWrtErasure EraseAll g tgtTy)), m)) else - getErasedTypes cenv.g tgtTy |> - List.iter (fun ety -> if isMeasureTy cenv.g ety + getErasedTypes g tgtTy |> + List.iter (fun ety -> if isMeasureTy g ety then warning(Error(FSComp.SR.tcTypeTestLosesMeasures(NicePrint.minimalStringOfType denv ety), m)) - else warning(Error(FSComp.SR.tcTypeTestLossy(NicePrint.minimalStringOfType denv ety, NicePrint.minimalStringOfType denv (stripTyEqnsWrtErasure EraseAll cenv.g ety)), m))) + else warning(Error(FSComp.SR.tcTypeTestLossy(NicePrint.minimalStringOfType denv ety, NicePrint.minimalStringOfType denv (stripTyEqnsWrtErasure EraseAll g ety)), m))) /// Checks, warnings and constraint assertions for upcasts let TcStaticUpcast cenv denv m tgtTy srcTy = if isTyparTy cenv.g tgtTy then if not (destTyparTy cenv.g tgtTy).IsCompatFlex then error(IndeterminateStaticCoercion(denv, srcTy, tgtTy, m)) - //else warning(UpcastUnnecessary(m)) + //else warning(UpcastUnnecessary m) if isSealedTy cenv.g tgtTy && not (isTyparTy cenv.g tgtTy) then warning(CoercionTargetSealed(denv, tgtTy, m)) if typeEquiv cenv.g srcTy tgtTy then - warning(UpcastUnnecessary(m)) + warning(UpcastUnnecessary m) AddCxTypeMustSubsumeType ContextInfo.NoContext denv cenv.css m NoTrace tgtTy srcTy @@ -3040,15 +3048,33 @@ let BuildPossiblyConditionalMethodCall cenv env isMutable m isProp minfo valUseF BuildMethodCall tcVal cenv.g cenv.amap isMutable m isProp minfo valUseFlags minst objArgs args -let TryFindIntrinsicOrExtensionMethInfo (cenv: cenv) (env: TcEnv) m ad nm ty = - AllMethInfosOfTypeInScope cenv.infoReader env.NameEnv (Some(nm), ad) IgnoreOverrides m ty +let TryFindIntrinsicOrExtensionMethInfo collectionSettings (cenv: cenv) (env: TcEnv) m ad nm ty = + AllMethInfosOfTypeInScope collectionSettings cenv.infoReader env.NameEnv (Some nm) ad IgnoreOverrides m ty + +let TryFindFSharpSignatureInstanceGetterProperty (cenv: cenv) (env: TcEnv) m nm ty (sigTys: TType list) = + TryFindPropInfo cenv.infoReader m env.AccessRights nm ty + |> List.tryFind (fun propInfo -> + not propInfo.IsStatic && propInfo.HasGetter && + ( + match propInfo.GetterMethod.GetParamTypes(cenv.amap, m, []) with + | [] -> false + | argTysList -> + + let argTys = (argTysList |> List.reduce (@)) @ [ propInfo.GetterMethod.GetFSharpReturnTy(cenv.amap, m, []) ] in + if argTys.Length <> sigTys.Length then + false + else + (argTys, sigTys) + ||> List.forall2 (typeEquiv cenv.g) + ) + ) /// Build the 'test and dispose' part of a 'use' statement let BuildDisposableCleanup cenv env m (v: Val) = v.SetHasBeenReferenced() let ad = env.eAccessRights let disposeMethod = - match TryFindIntrinsicOrExtensionMethInfo cenv env m ad "Dispose" cenv.g.system_IDisposable_ty with + match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AllResults cenv env m ad "Dispose" cenv.g.system_IDisposable_ty with | [x] -> x | _ -> error(InternalError(FSComp.SR.tcCouldNotFindIDisposable(), m)) @@ -3064,7 +3090,7 @@ let BuildDisposableCleanup cenv env m (v: Val) = else mkUnit cenv.g m else - let disposeObjVar, disposeObjExpr = Tastops.mkCompGenLocal m "objectToDispose" cenv.g.system_IDisposable_ty + let disposeObjVar, disposeObjExpr = mkCompGenLocal m "objectToDispose" cenv.g.system_IDisposable_ty let disposeExpr, _ = BuildPossiblyConditionalMethodCall cenv env PossiblyMutates m false disposeMethod NormalValUse [] [disposeObjExpr] [] let inpe = mkCoerceExpr(exprForVal v.Range v, cenv.g.obj_ty, m, v.Type) mkIsInstConditional cenv.g m cenv.g.system_IDisposable_ty inpe disposeObjVar disposeExpr (mkUnit cenv.g m) @@ -3073,8 +3099,8 @@ let BuildDisposableCleanup cenv env m (v: Val) = let BuildOffsetToStringData cenv env m = let ad = env.eAccessRights let offsetToStringDataMethod = - match TryFindIntrinsicOrExtensionMethInfo cenv env m ad "get_OffsetToStringData" cenv.g.system_RuntimeHelpers_ty with - | [x] -> x + match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AllResults cenv env m ad "get_OffsetToStringData" cenv.g.system_RuntimeHelpers_ty with + | [x] -> x | _ -> error(Error(FSComp.SR.tcCouldNotFindOffsetToStringData(), m)) let offsetExpr, _ = BuildPossiblyConditionalMethodCall cenv env NeverMutates m false offsetToStringDataMethod NormalValUse [] [] [] @@ -3095,7 +3121,7 @@ let BuildILFieldGet g amap m objExpr (finfo: ILFieldInfo) = | None -> error (Error(FSComp.SR.tcTPFieldMustBeLiteral(), m)) | Some lit -> - Expr.Const(TcFieldInit m lit, m, fieldType) + Expr.Const (TcFieldInit m lit, m, fieldType) | _ -> #endif let wrap, objExpr, _readonly, _writeonly = mkExprAddrOfExpr g isValueType false NeverMutates objExpr None m @@ -3144,7 +3170,7 @@ let BuildRecdFieldSet g m objExpr (rfinfo: RecdFieldInfo) argExpr = let (|BinOpExpr|_|) e = match e with - | SynExpr.App (_, _, SynExpr.App(_, _, SingleIdent opId, a, _), b, _) -> Some (opId, a, b) + | SynExpr.App (_, _, SynExpr.App (_, _, SingleIdent opId, a, _), b, _) -> Some (opId, a, b) | _ -> None let (|SimpleEqualsExpr|_|) e = @@ -3169,12 +3195,12 @@ let (|JoinRelation|_|) cenv env (e: SynExpr) = | 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) | 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) + let b = SynExpr.App (ExprAtomicFlag.Atomic, false, mkSynLidGet b.Range [MangledGlobalName;"System"] "Nullable", b, b.Range) Some (a, b) | BinOpExpr(opId, a, b) when isOpName opNameNullableEqualsNullable cenv.g.nullable_equals_nullable_operator_vref opId.idText -> @@ -3224,7 +3250,7 @@ let GetMethodArgs arg = let CompilePatternForMatch cenv (env: TcEnv) mExpr matchm warnOnUnused actionOnFailure (inputVal, generalizedTypars, inputExprOpt) clauses inputTy resultTy = let dtree, targets = CompilePattern cenv.g env.DisplayEnv cenv.amap mExpr matchm warnOnUnused actionOnFailure (inputVal, generalizedTypars, inputExprOpt) clauses inputTy resultTy - mkAndSimplifyMatch NoSequencePointAtInvisibleBinding mExpr matchm resultTy dtree targets + mkAndSimplifyMatch NoDebugPointAtInvisibleBinding mExpr matchm resultTy dtree targets /// Compile a pattern let CompilePatternForMatchClauses cenv env mExpr matchm warnOnUnused actionOnFailure inputExprOpt inputTy resultTy tclauses = @@ -3235,7 +3261,7 @@ let CompilePatternForMatchClauses cenv env mExpr matchm warnOnUnused actionOnFai let expr = CompilePatternForMatch cenv env mExpr matchm warnOnUnused actionOnFailure (asVal, generalizedTypars, None) [TClause(pat1, None, TTarget(ListSet.remove valEq asVal vs, e, spTarget), m2)] inputTy resultTy asVal, expr | _ -> - let matchValueTmp, _ = Tastops.mkCompGenLocal mExpr "matchValue" inputTy + let matchValueTmp, _ = mkCompGenLocal mExpr "matchValue" inputTy let expr = CompilePatternForMatch cenv env mExpr matchm warnOnUnused actionOnFailure (matchValueTmp, [], inputExprOpt) tclauses inputTy resultTy matchValueTmp, expr @@ -3250,18 +3276,17 @@ let CompilePatternForMatchClauses cenv env mExpr matchm warnOnUnused actionOnFai // localAlloc is relevant if the enumerator is a mutable struct and indicates // if the enumerator can be allocated as a mutable local variable let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr = - let ad = env.eAccessRights + let ad = env.AccessRights let err k ty = let txt = NicePrint.minimalStringOfType env.DisplayEnv ty - let msg = if k then FSComp.SR.tcTypeCannotBeEnumerated(txt) else FSComp.SR.tcEnumTypeCannotBeEnumerated(txt) + let msg = if k then FSComp.SR.tcTypeCannotBeEnumerated txt else FSComp.SR.tcEnumTypeCannotBeEnumerated txt Exception(Error(msg, m)) let findMethInfo k m nm ty = - match TryFindIntrinsicOrExtensionMethInfo cenv env m ad nm ty with + match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad nm ty with | [] -> err k ty - | res :: _ -> Result res - + | res :: _ -> Result res // Ensure there are no curried arguments, and indeed no arguments at all let hasArgs (minfo: MethInfo) minst = @@ -3320,7 +3345,7 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr typeEquiv cenv.g cenv.g.obj_ty ty | _ -> false - match TryFindIntrinsicOrExtensionMethInfo cenv env m ad "get_Item" tyToSearchForGetEnumeratorAndItem with + match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AllResults cenv env m ad "get_Item" tyToSearchForGetEnumeratorAndItem with | (minfo :: others) when (allEquivReturnTypes minfo others && List.exists isInt32OrObjectIndexer (minfo :: others)) -> minfo.GetFSharpReturnTy(cenv.amap, m, []) @@ -3328,7 +3353,7 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr | _ -> // Some types such as XmlNodeList have only an Item method - match TryFindIntrinsicOrExtensionMethInfo cenv env m ad "Item" tyToSearchForGetEnumeratorAndItem with + match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AllResults cenv env m ad "Item" tyToSearchForGetEnumeratorAndItem with | (minfo :: others) when (allEquivReturnTypes minfo others && List.exists isInt32OrObjectIndexer (minfo :: others)) -> minfo.GetFSharpReturnTy(cenv.amap, m, []) @@ -3343,14 +3368,14 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr let (enumeratorVar, enumeratorExpr), retTypeOfGetEnumerator = if isEnumeratorTypeStruct then if localAlloc then - Tastops.mkMutableCompGenLocal m "enumerator" retTypeOfGetEnumerator, retTypeOfGetEnumerator + mkMutableCompGenLocal m "enumerator" retTypeOfGetEnumerator, retTypeOfGetEnumerator else let refCellTyForRetTypeOfGetEnumerator = mkRefCellTy cenv.g retTypeOfGetEnumerator - let v, e = Tastops.mkMutableCompGenLocal m "enumerator" refCellTyForRetTypeOfGetEnumerator + let v, e = mkMutableCompGenLocal m "enumerator" refCellTyForRetTypeOfGetEnumerator (v, mkRefCellGet cenv.g m retTypeOfGetEnumerator e), refCellTyForRetTypeOfGetEnumerator else - Tastops.mkCompGenLocal m "enumerator" retTypeOfGetEnumerator, retTypeOfGetEnumerator + mkCompGenLocal m "enumerator" retTypeOfGetEnumerator, retTypeOfGetEnumerator let getEnumExpr, getEnumTy = let (getEnumExpr, getEnumTy) as res = BuildPossiblyConditionalMethodCall cenv env PossiblyMutates m false getEnumerator_minfo NormalValUse getEnumerator_minst [exprToSearchForGetEnumeratorAndItem] [] @@ -3367,8 +3392,7 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr let currentExpr, enumElemTy = // Implicitly dereference byref for expr 'for x in ...' if isByrefTy cenv.g enumElemTy then - let v, _ = mkCompGenLocal m "byrefReturn" enumElemTy - let expr = mkCompGenLet currentExpr.Range v currentExpr (mkAddrGet m (mkLocalValRef v)) + let expr = mkDerefAddrExpr m currentExpr currentExpr.Range enumElemTy expr, destByrefTy cenv.g enumElemTy else currentExpr, enumElemTy @@ -3385,7 +3409,7 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr match tryType (mkCoerceExpr(expr, ty, expr.Range, exprty), ty) with | Result res -> Some res | Exception e -> - PreserveStackTrace(e) + PreserveStackTrace e raise e else None @@ -3400,7 +3424,7 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr match probe ienumerable with | Some res -> res | None -> - PreserveStackTrace(e) + PreserveStackTrace e raise e @@ -3417,7 +3441,7 @@ let ConvertArbitraryExprToEnumerable cenv ty (env: TcEnv) (expr: Expr) = let expr = mkCompGenLet m enumerableVar expr - (mkCallSeqOfFunctions cenv.g m retTypeOfGetEnumerator enumElemTy + (mkCallSeqOfFunctions cenv.g m retTypeOfGetEnumerator enumElemTy (mkUnitDelayLambda cenv.g m getEnumExpr) (mkLambda m enumeratorVar (guardExpr, guardTy)) (mkLambda m enumeratorVar (betterCurrentExpr, enumElemTy))) @@ -3467,7 +3491,7 @@ let mkSeqFinally cenv env m genTy e1 e2 = mkCallSeqFinally cenv.g m genResultTy e1 e2 let mkSeqExprMatchClauses (pat', vspecs) innerExpr = - [TClause(pat', None, TTarget(vspecs, innerExpr, SequencePointAtTarget), pat'.Range) ] + [TClause(pat', None, TTarget(vspecs, innerExpr, DebugPointForTarget.Yes), pat'.Range) ] let compileSeqExprMatchClauses cenv env inputExprMark (pat: Pattern, vspecs) innerExpr inputExprOpt bindPatTy genInnerTy = let patMark = pat.Range @@ -3477,7 +3501,7 @@ let compileSeqExprMatchClauses cenv env inputExprMark (pat: Pattern, vspecs) inn let elimFastIntegerForLoop (spBind, id, start, dir, finish, innerExpr, m) = let pseudoEnumExpr = if dir then mkSynInfix m start ".." finish - else mkSynTrifix m ".. .." start (SynExpr.Const(SynConst.Int32 -1, start.Range)) finish + else mkSynTrifix m ".. .." start (SynExpr.Const (SynConst.Int32 -1, start.Range)) finish SynExpr.ForEach (spBind, SeqExprOnly false, true, mkSynPatVar None id, pseudoEnumExpr, innerExpr, m) let (|ExprAsPat|_|) (f: SynExpr) = @@ -3491,35 +3515,84 @@ let (|ExprAsPat|_|) (f: SynExpr) = None | _ -> None +/// Check if a computation or sequence expression is syntactically free of 'yield' (though not yield!) +let YieldFree cenv expr = + if cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield then + + // Implement yield free logic for F# Language including the LanguageFeature.ImplicitYield + let rec YieldFree expr = + match expr with + | SynExpr.Sequential (_, _, e1, e2, _) -> + YieldFree e1 && YieldFree e2 + + | SynExpr.IfThenElse (_, e2, e3opt, _, _, _, _) -> + YieldFree e2 && Option.forall YieldFree e3opt + + | SynExpr.TryWith (e1, _, clauses, _, _, _, _) -> + YieldFree e1 && clauses |> List.forall (fun (Clause(_, _, e, _, _)) -> YieldFree e) + + | (SynExpr.Match (_, _, clauses, _) | SynExpr.MatchBang (_, _, clauses, _)) -> + clauses |> List.forall (fun (Clause(_, _, e, _, _)) -> YieldFree e) + + | SynExpr.For (_, _, _, _, _, body, _) + | SynExpr.TryFinally (body, _, _, _, _) + | SynExpr.LetOrUse (_, _, _, body, _) + | SynExpr.While (_, _, body, _) + | SynExpr.ForEach (_, _, _, _, _, body, _) -> + YieldFree body + + | SynExpr.LetOrUseBang(_, _, _, _, _, _, body, _) -> + YieldFree body + + | SynExpr.YieldOrReturn((true, _), _, _) -> false + + | _ -> true + + YieldFree expr + else + // Implement yield free logic for F# Language without the LanguageFeature.ImplicitYield + let rec YieldFree expr = + match expr with + | SynExpr.Sequential (_, _, e1, e2, _) -> + YieldFree e1 && YieldFree e2 + + | SynExpr.IfThenElse (_, e2, e3opt, _, _, _, _) -> + YieldFree e2 && Option.forall YieldFree e3opt + + | SynExpr.TryWith (e1, _, clauses, _, _, _, _) -> + YieldFree e1 && clauses |> List.forall (fun (Clause(_, _, e, _, _)) -> YieldFree e) + + | (SynExpr.Match (_, _, clauses, _) | SynExpr.MatchBang (_, _, clauses, _)) -> + clauses |> List.forall (fun (Clause(_, _, e, _, _)) -> YieldFree e) + + | SynExpr.For (_, _, _, _, _, body, _) + | SynExpr.TryFinally (body, _, _, _, _) + | SynExpr.LetOrUse (_, _, _, body, _) + | SynExpr.While (_, _, body, _) + | SynExpr.ForEach (_, _, _, _, _, body, _) -> + YieldFree body + + | SynExpr.LetOrUseBang _ + | SynExpr.YieldOrReturnFrom _ + | SynExpr.YieldOrReturn _ + | SynExpr.ImplicitZero _ + | SynExpr.Do _ -> false + + | _ -> true + + 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|_|) acceptDeprecated c = - - let rec YieldFree expr = - match expr with - | SynExpr.Sequential (_, _, e1, e2, _) -> YieldFree e1 && YieldFree e2 - | SynExpr.IfThenElse (_, e2, e3opt, _, _, _, _) -> YieldFree e2 && Option.forall YieldFree e3opt - | SynExpr.TryWith (e1, _, clauses, _, _, _, _) -> YieldFree e1 && clauses |> List.forall (fun (Clause(_, _, e, _, _)) -> YieldFree e) - | (SynExpr.Match (_, _, clauses, _) | SynExpr.MatchBang (_, _, clauses, _)) -> - clauses |> List.forall (fun (Clause(_, _, e, _, _)) -> YieldFree e) - | SynExpr.For (_, _, _, _, _, body, _) - | SynExpr.TryFinally (body, _, _, _, _) - | SynExpr.LetOrUse (_, _, _, body, _) - | SynExpr.While (_, _, body, _) - | SynExpr.ForEach (_, _, _, _, _, body, _) -> YieldFree body - | SynExpr.YieldOrReturnFrom _ - | SynExpr.YieldOrReturn _ - | SynExpr.LetOrUseBang _ - | SynExpr.ImplicitZero _ - | SynExpr.Do _ -> false - | _ -> true +let (|SimpleSemicolonSequence|_|) cenv acceptDeprecated cexpr = - let rec IsSimpleSemicolonSequenceElement expr = - match expr with - | SynExpr.IfThenElse _ when acceptDeprecated && YieldFree expr -> true - | SynExpr.IfThenElse _ + let IsSimpleSemicolonSequenceElement expr = + match expr with + | SynExpr.IfThenElse _ when acceptDeprecated && YieldFree cenv expr -> true + | SynExpr.IfThenElse _ | SynExpr.TryWith _ | SynExpr.Match _ | SynExpr.For _ @@ -3531,27 +3604,23 @@ let (|SimpleSemicolonSequence|_|) acceptDeprecated c = | SynExpr.Do _ | SynExpr.MatchBang _ | SynExpr.LetOrUseBang _ - | SynExpr.ImplicitZero _ | SynExpr.While _ -> false | _ -> true - let rec GetSimpleSemicolonSequenceOfComprehension expr acc = + let rec TryGetSimpleSemicolonSequenceOfComprehension expr acc = match expr with - | SynExpr.Sequential(_, true, e1, e2, _) -> + | SynExpr.Sequential (_, true, e1, e2, _) -> if IsSimpleSemicolonSequenceElement e1 then - GetSimpleSemicolonSequenceOfComprehension e2 (e1::acc) + TryGetSimpleSemicolonSequenceOfComprehension e2 (e1 :: acc) else None | e -> if IsSimpleSemicolonSequenceElement e then - Some(List.rev (e::acc)) + Some(List.rev (e :: acc)) else None - if YieldFree c then - GetSimpleSemicolonSequenceOfComprehension c [] - else - None + TryGetSimpleSemicolonSequenceOfComprehension cexpr [] //------------------------------------------------------------------------- // Mutually recursive shapes @@ -3693,7 +3762,7 @@ type InitializationGraphAnalysisState = type PreInitializationGraphEliminationBinding = { FixupPoints: RecursiveUseFixupPoints - Binding: Tast.Binding } + Binding: Binding } /// Check for safety and determine if we need to insert lazy thunks @@ -3712,15 +3781,15 @@ let EliminateInitializationGraphs hash // The output of the analysis - let outOfOrder = ref false - let runtimeChecks = ref false - let directRecursiveData = ref false - let reportedEager = ref false - let definiteDependencies = ref [] + let mutable outOfOrder = false + let mutable runtimeChecks = false + let mutable directRecursiveData = false + let mutable reportedEager = false + let mutable definiteDependencies = [] let rec stripChooseAndExpr e = match stripExpr e with - | Expr.TyChoose(_, b, _) -> stripChooseAndExpr b + | Expr.TyChoose (_, b, _) -> stripChooseAndExpr b | e -> e let availIfInOrder = ValHash<_>.Create() @@ -3767,7 +3836,7 @@ let EliminateInitializationGraphs | Expr.Val (v, _, m) -> CheckValRef st v m // Expressions where subparts may be fixable - | Expr.Op((TOp.Tuple _ | TOp.UnionCase _ | TOp.Recd _), _, args, _) -> + | Expr.Op ((TOp.Tuple _ | TOp.UnionCase _ | TOp.Recd _), _, args, _) -> List.iter (CheckExpr (fixable st)) args // Composite expressions @@ -3781,7 +3850,7 @@ let EliminateInitializationGraphs | Expr.Match (_, _, pt, targets, _, _) -> CheckDecisionTree (strict st) pt Array.iter (CheckDecisionTreeTarget (strict st)) targets - | Expr.App(e1, _, _, args, _) -> + | Expr.App (e1, _, _, args, _) -> CheckExpr (strict st) e1 List.iter (CheckExpr (strict st)) args // Binary expressions @@ -3789,9 +3858,9 @@ let EliminateInitializationGraphs | Expr.StaticOptimization (_, e1, e2, _) -> CheckExpr (strict st) e1; CheckExpr (strict st) e2 // n-ary expressions - | Expr.Op(op, _, args, m) -> CheckExprOp st op m; List.iter (CheckExpr (strict st)) args + | Expr.Op (op, _, args, m) -> CheckExprOp st op m; List.iter (CheckExpr (strict st)) args // misc - | Expr.Link(eref) -> CheckExpr st !eref + | Expr.Link eref -> CheckExpr st !eref | Expr.TyChoose (_, b, _) -> CheckExpr st b | Expr.Quote _ -> () @@ -3812,21 +3881,21 @@ let EliminateInitializationGraphs | MaybeLazy -> if recursiveVals.TryFind v.Deref |> Option.isSome then warning (RecursiveUseCheckedAtRuntime (denv, v, m)) - if not !reportedEager then - (warning (LetRecCheckedAtRuntime m); reportedEager := true) - runtimeChecks := true + if not reportedEager then + (warning (LetRecCheckedAtRuntime m); reportedEager <- true) + runtimeChecks <- true | Top | DefinitelyStrict -> if recursiveVals.TryFind v.Deref |> Option.isSome then if availIfInOrder.TryFind v.Deref |> Option.isNone then warning (LetRecEvaluatedOutOfOrder (denv, boundv, v, m)) - outOfOrder := true - if not !reportedEager then - (warning (LetRecCheckedAtRuntime m); reportedEager := true) - definiteDependencies := (boundv, v) :: !definiteDependencies + outOfOrder <- true + if not reportedEager then + (warning (LetRecCheckedAtRuntime m); reportedEager <- true) + definiteDependencies <- (boundv, v) :: definiteDependencies | InnerTop -> if recursiveVals.TryFind v.Deref |> Option.isSome then - directRecursiveData := true + directRecursiveData <- true | DefinitelyLazy -> () and checkDelayed st b = match st with @@ -3848,16 +3917,16 @@ let EliminateInitializationGraphs // ddg = definiteDependencyGraph let ddgNodes = recursiveVals.Values |> Seq.toList |> List.map mkLocalValRef - let ddg = Graph((fun v -> v.Stamp), ddgNodes, !definiteDependencies ) + let ddg = Graph((fun v -> v.Stamp), ddgNodes, definiteDependencies ) ddg.IterateCycles (fun path -> error (LetRecUnsound (denv, path, path.Head.Range))) - let requiresLazyBindings = !runtimeChecks || !outOfOrder - if !directRecursiveData && requiresLazyBindings then + let requiresLazyBindings = runtimeChecks || outOfOrder + if directRecursiveData && requiresLazyBindings then error(Error(FSComp.SR.tcInvalidMixtureOfRecursiveForms(), bindsm)) if requiresLazyBindings then let morphBinding (pgrbind: PreInitializationGraphEliminationBinding) = - let (RecursiveUseFixupPoints(fixupPoints)) = pgrbind.FixupPoints + let (RecursiveUseFixupPoints fixupPoints) = pgrbind.FixupPoints let (TBind(v, e, seqPtOpt)) = pgrbind.Binding match stripChooseAndExpr e with | Expr.Lambda _ | Expr.TyLambda _ -> @@ -3868,11 +3937,11 @@ let EliminateInitializationGraphs let vty = (mkLazyTy g ty) let fty = (g.unit_ty --> ty) - let flazy, felazy = Tastops.mkCompGenLocal m v.LogicalName fty + let flazy, felazy = mkCompGenLocal m v.LogicalName fty let frhs = mkUnitDelayLambda g m e if mustHaveArity then flazy.SetValReprInfo (Some(InferArityOfExpr g AllowTypeDirectedDetupling.Yes fty [] [] frhs)) - let vlazy, velazy = Tastops.mkCompGenLocal m v.LogicalName vty + let vlazy, velazy = mkCompGenLocal m v.LogicalName vty let vrhs = (mkLazyDelayed g m ty felazy) if mustHaveArity then vlazy.SetValReprInfo (Some(InferArityOfExpr g AllowTypeDirectedDetupling.Yes vty [] [] vrhs)) @@ -3895,10 +3964,10 @@ let EliminateInitializationGraphs // Check the shape of an object constructor and rewrite calls //------------------------------------------------------------------------- -let CheckAndRewriteObjectCtor g env (ctorLambaExpr: Expr) = +let CheckAndRewriteObjectCtor g env (ctorLambdaExpr: Expr) = - let m = ctorLambaExpr.Range - let tps, vsl, body, returnTy = stripTopLambda (ctorLambaExpr, tyOfExpr g ctorLambaExpr) + let m = ctorLambdaExpr.Range + let tps, vsl, body, returnTy = stripTopLambda (ctorLambdaExpr, tyOfExpr g ctorLambdaExpr) // Rewrite legitimate self-construction calls to CtorValUsedAsSelfInit let error (expr: Expr) = @@ -3918,7 +3987,7 @@ let CheckAndRewriteObjectCtor g env (ctorLambaExpr: Expr) = let ty = tyOfExpr g recdExpr let thisExpr = mkGetArg0 m ty let setExpr = mkRefCellSet g m ty (exprForValRef m (mkLocalValRef safeInitVal)) thisExpr - Expr.Sequential(recdExpr, setExpr, ThenDoSeq, SuppressSequencePointOnExprOfSequential, m) + Expr.Sequential (recdExpr, setExpr, ThenDoSeq, DebugPointAtSequential.StmtOnly, m) let recdExpr = match ctorInfo.safeInitInfo with | NoSafeInitInfo -> recdExpr @@ -3927,7 +3996,7 @@ let CheckAndRewriteObjectCtor g env (ctorLambaExpr: Expr) = let thisExpr = mkGetArg0 m thisTy let thisTyInst = argsOfAppTy g thisTy let setExpr = mkRecdFieldSetViaExprAddr (thisExpr, rfref, thisTyInst, mkOne g m, m) - Expr.Sequential(recdExpr, setExpr, ThenDoSeq, SuppressSequencePointOnExprOfSequential, m) + Expr.Sequential (recdExpr, setExpr, ThenDoSeq, DebugPointAtSequential.StmtOnly, m) recdExpr @@ -3935,32 +4004,32 @@ let CheckAndRewriteObjectCtor g env (ctorLambaExpr: Expr) = match expr with // = { fields } // The constructor ends in an object initialization expression - good - | Expr.Op(TOp.Recd(RecdExprIsObjInit, _), _, _, _) -> rewriteConstruction expr + | Expr.Op (TOp.Recd (RecdExprIsObjInit, _), _, _, _) -> rewriteConstruction expr // = "a; " - | Expr.Sequential(a, body, NormalSeq, spSeq, b) -> Expr.Sequential(a, checkAndRewrite body, NormalSeq, spSeq, b) + | Expr.Sequential (a, body, NormalSeq, spSeq, b) -> Expr.Sequential (a, checkAndRewrite body, NormalSeq, spSeq, b) // = " then " - | Expr.Sequential(body, a, ThenDoSeq, spSeq, b) -> Expr.Sequential(checkAndRewrite body, a, ThenDoSeq, spSeq, b) + | Expr.Sequential (body, a, ThenDoSeq, spSeq, b) -> Expr.Sequential (checkAndRewrite body, a, ThenDoSeq, spSeq, b) // = "let pat = expr in " - | Expr.Let(bind, body, m, _) -> mkLetBind m bind (checkAndRewrite body) + | Expr.Let (bind, body, m, _) -> mkLetBind m bind (checkAndRewrite body) // The constructor is a sequence "let pat = expr in " - | Expr.Match(spBind, a, b, targets, c, d) -> Expr.Match(spBind, a, b, (targets |> Array.map (fun (TTarget(vs, body, spTarget)) -> TTarget(vs, checkAndRewrite body, spTarget))), c, d) + | Expr.Match (spBind, a, b, targets, c, d) -> Expr.Match (spBind, a, b, (targets |> Array.map (fun (TTarget(vs, body, spTarget)) -> TTarget(vs, checkAndRewrite body, spTarget))), c, d) // = "let rec binds in " - | Expr.LetRec(a, body, _, _) -> Expr.LetRec (a, checkAndRewrite body, m, NewFreeVarsCache()) + | Expr.LetRec (a, body, _, _) -> Expr.LetRec (a, checkAndRewrite body, m, Construct.NewFreeVarsCache()) // = "new C(...)" - | Expr.App(f, b, c, d, m) -> + | Expr.App (f, b, c, d, m) -> // The application had better be an application of a ctor let f = checkAndRewriteCtorUsage f - let expr = Expr.App(f, b, c, d, m) + let expr = Expr.App (f, b, c, d, m) rewriteConstruction expr | _ -> - error(expr) + error expr and checkAndRewriteCtorUsage expr = match expr with @@ -3972,12 +4041,12 @@ let CheckAndRewriteObjectCtor g env (ctorLambaExpr: Expr) = // Type applications are ok, e.g. // type C<'a>(x: int) = // new() = C<'a>(3) - | Expr.App(f, fty, tyargs, [], m) -> + | Expr.App (f, fty, tyargs, [], m) -> let f = checkAndRewriteCtorUsage f - Expr.App(f, fty, tyargs, [], m) + Expr.App (f, fty, tyargs, [], m) // Self-calls are OK and get rewritten. - | Expr.Val(vref, NormalValUse, a) -> + | Expr.Val (vref, NormalValUse, a) -> let isCtor = match vref.MemberInfo with | None -> false @@ -3986,9 +4055,9 @@ let CheckAndRewriteObjectCtor g env (ctorLambaExpr: Expr) = if not isCtor then error expr else - Expr.Val(vref, CtorValUsedAsSelfInit, a) + Expr.Val (vref, CtorValUsedAsSelfInit, a) | _ -> - error(expr) + error expr let body = checkAndRewrite body mkMultiLambdas m tps vsl (body, returnTy) @@ -4002,19 +4071,19 @@ let buildApp cenv expr resultTy arg m = match expr, arg with // Special rule for building applications of the 'x && y' operator - | ApplicableExpr(_, Expr.App(Expr.Val(vf, _, _), _, _, [x0], _), _), _ + | ApplicableExpr(_, Expr.App (Expr.Val (vf, _, _), _, _, [x0], _), _), _ when valRefEq g vf g.and_vref || valRefEq g vf g.and2_vref -> MakeApplicableExprNoFlex cenv (mkLazyAnd g m x0 arg), resultTy // Special rule for building applications of the 'x || y' operator - | ApplicableExpr(_, Expr.App(Expr.Val(vf, _, _), _, _, [x0], _), _), _ + | ApplicableExpr(_, Expr.App (Expr.Val (vf, _, _), _, _, [x0], _), _), _ when valRefEq g vf g.or_vref || valRefEq g vf g.or2_vref -> MakeApplicableExprNoFlex cenv (mkLazyOr g m x0 arg ), resultTy // Special rule for building applications of the 'reraise' operator - | ApplicableExpr(_, Expr.App(Expr.Val(vf, _, _), _, _, [], _), _), _ + | ApplicableExpr(_, Expr.App (Expr.Val (vf, _, _), _, _, [], _), _), _ when valRefEq g vf g.reraise_vref -> // exprty is of type: "unit -> 'a". Break it and store the 'a type here, used later as return type. @@ -4022,21 +4091,21 @@ let buildApp cenv expr resultTy arg m = // Special rules for NativePtr.ofByRef to generalize result. // See RFC FS-1053.md - | ApplicableExpr(_, Expr.App(Expr.Val(vf, _, _), _, _, [], _), _), _ + | ApplicableExpr(_, Expr.App (Expr.Val (vf, _, _), _, _, [], _), _), _ when (valRefEq g vf g.nativeptr_tobyref_vref) -> let argty = NewInferenceType() let resultTy = mkByrefTyWithInference g argty (NewByRefKindInferenceType g m) - expr.SupplyArgument(arg, m), resultTy + expr.SupplyArgument (arg, m), resultTy // Special rules for building applications of the '&expr' operator, which gets the // address of an expression. // // See also RFC FS-1053.md - | ApplicableExpr(_, Expr.App(Expr.Val(vf, _, _), _, _, [], _), _), _ + | ApplicableExpr(_, Expr.App (Expr.Val (vf, _, _), _, _, [], _), _), _ when valRefEq g vf g.addrof_vref -> - let wrap, e1a', readonly, _writeonly = mkExprAddrOfExpr g true false AddressOfOp arg (Some(vf)) m + let wrap, e1a', readonly, _writeonly = mkExprAddrOfExpr g true false AddressOfOp arg (Some vf) m // Assert the result type to be readonly if we couldn't take the address let resultTy = let argTy = tyOfExpr g arg @@ -4058,23 +4127,22 @@ let buildApp cenv expr resultTy arg m = // Special rules for building applications of the &&expr' operators, which gets the // address of an expression. - | ApplicableExpr(_, Expr.App(Expr.Val(vf, _, _), _, _, [], _), _), _ + | ApplicableExpr(_, Expr.App (Expr.Val (vf, _, _), _, _, [], _), _), _ when valRefEq g vf g.addrof2_vref -> - warning(UseOfAddressOfOperator(m)) - let wrap, e1a', _readonly, _writeonly = mkExprAddrOfExpr g true false AddressOfOp arg (Some(vf)) m + warning(UseOfAddressOfOperator m) + let wrap, e1a', _readonly, _writeonly = mkExprAddrOfExpr g true false AddressOfOp arg (Some vf) m MakeApplicableExprNoFlex cenv (wrap(e1a')), resultTy | _ when isByrefTy g resultTy -> // Handle byref returns, byref-typed returns get implicitly dereferenced - let v, _ = mkCompGenLocal m "byrefReturn" resultTy - let expr = expr.SupplyArgument(arg, m) - let expr = mkCompGenLet m v expr.Expr (mkAddrGet m (mkLocalValRef v)) + let expr = expr.SupplyArgument (arg, m) + let expr = mkDerefAddrExpr m expr.Expr m resultTy let resultTy = destByrefTy g resultTy MakeApplicableExprNoFlex cenv expr, resultTy | _ -> - expr.SupplyArgument(arg, m), resultTy + expr.SupplyArgument (arg, m), resultTy //------------------------------------------------------------------------- // Additional data structures used by type checking @@ -4084,33 +4152,33 @@ type DelayedItem = /// DelayedTypeApp (typeArgs, mTypeArgs, mExprAndTypeArgs) /// /// Represents the in "item" - | DelayedTypeApp of Ast.SynType list * range * range + | DelayedTypeApp of SynType list * range * range /// DelayedApp (isAtomic, argExpr, mFuncAndArg) /// /// Represents the args in "item args", or "item.[args]". - | DelayedApp of ExprAtomicFlag * Ast.SynExpr * range + | DelayedApp of ExprAtomicFlag * SynExpr * range /// Represents the long identifiers in "item.Ident1", or "item.Ident1.Ident2" etc. - | DelayedDotLookup of Ast.Ident list * range + | DelayedDotLookup of Ident list * range /// Represents an incomplete "item." | DelayedDot /// Represents the valueExpr in "item <- valueExpr", also "item.[indexerArgs] <- valueExpr" etc. - | DelayedSet of Ast.SynExpr * range + | DelayedSet of SynExpr * range let MakeDelayedSet(e: SynExpr, m) = // We have longId <- e. Wrap 'e' in another pair of parentheses to ensure it's never interpreted as // a named argument, e.g. for "el.Checked <- (el = el2)" - DelayedSet (SynExpr.Paren(e, range0, None, e.Range), m) + DelayedSet (SynExpr.Paren (e, range0, None, e.Range), m) type NewSlotsOK = | NewSlotsOK | NoNewSlots -type ImplictlyBoundTyparsAllowed = +type ImplicitlyBoundTyparsAllowed = | NewTyparsOKButWarnIfNotRigid | NewTyparsOK | NoNewTypars @@ -4145,7 +4213,7 @@ type ContainerInfo = /// Indicates a declaration is contained in an expression let ExprContainerInfo = ContainerInfo(ParentNone, None) /// Indicates a declaration is contained in the given module -let ModuleOrNamespaceContainerInfo modref = ContainerInfo(Parent(modref), Some(MemberOrValContainerInfo(modref, None, None, NoSafeInitInfo, []))) +let ModuleOrNamespaceContainerInfo modref = ContainerInfo(Parent modref, Some(MemberOrValContainerInfo(modref, None, None, NoSafeInitInfo, []))) /// Indicates a declaration is contained in the given type definition in the given module let TyconContainerInfo (parent, tcref, declaredTyconTypars, safeInitInfo) = ContainerInfo(parent, Some(MemberOrValContainerInfo(tcref, None, None, safeInitInfo, declaredTyconTypars))) @@ -4162,7 +4230,7 @@ type ValSpecResult = ValSpecResult of ParentRef * ValMemberInfoTransient option type RecDefnBindingInfo = RecDefnBindingInfo of ContainerInfo * NewSlotsOK * DeclKind * SynBinding -type MutRecDataForOpen = MutRecDataForOpen of LongIdent * range +type MutRecDataForOpen = MutRecDataForOpen of LongIdent * range * appliedScope: range type MutRecDataForModuleAbbrev = MutRecDataForModuleAbbrev of Ident * LongIdent * range type MutRecSigsInitialData = MutRecShape list @@ -4223,8 +4291,7 @@ type PostGeneralizationRecursiveBinding = type PostBindCtorThisVarRefCellRecursiveBinding = { ValScheme: ValScheme - Binding: Tast.Binding } - + Binding: Binding } let CanInferExtraGeneralizedTyparsForRecBinding (pgrbind: PreGeneralizationRecursiveBinding) = let flex = pgrbind.RecBindingInfo.ExplicitTyparInfo @@ -4263,8 +4330,7 @@ let rec TcTyparConstraint ridx cenv newOk checkCxs occ (env: TcEnv) tpenv c = | WhereTyparDefaultsToType(tp, ty, m) -> let ty', tpenv = TcTypeAndRecover cenv newOk checkCxs occ env tpenv ty let tp', tpenv = TcTypar cenv env newOk tpenv tp - let csenv = MakeConstraintSolverEnv env.eContextInfo cenv.css m env.DisplayEnv - AddConstraint csenv 0 m NoTrace tp' (TyparConstraint.DefaultsTo(ridx, ty', m)) |> CommitOperationResult + AddCxTyparDefaultsTo env.DisplayEnv cenv.css m env.eContextInfo tp' ridx ty' tpenv | WhereTyparSubtypeOfType(tp, ty, m) -> @@ -4337,7 +4403,7 @@ and TcPseudoMemberSpec cenv newOk env synTypes tpenv memSpfn m = | SynMemberSig.Member (valSpfn, memberFlags, m) -> // REVIEW: Test pseudo constraints cannot refer to polymorphic methods. // REVIEW: Test pseudo constraints cannot be curried. - let members, tpenv = TcValSpec cenv env ModuleOrMemberBinding newOk (ExprContainerInfo) (Some memberFlags) (Some (List.head tys)) tpenv valSpfn [] + let members, tpenv = TcValSpec cenv env ModuleOrMemberBinding newOk ExprContainerInfo (Some memberFlags) (Some (List.head tys)) tpenv valSpfn [] match members with | [ValSpecResult(_, _, id, _, _, memberConstraintTy, partialValReprInfo, _)] -> let memberConstraintTypars, _ = tryDestForallTy cenv.g memberConstraintTy @@ -4349,7 +4415,7 @@ and TcPseudoMemberSpec cenv newOk env synTypes tpenv memSpfn m = let logicalCompiledName = ComputeLogicalName id memberFlags let item = Item.ArgName (id, memberConstraintTy, None) - CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.AccessRights) TTrait(tys, logicalCompiledName, memberFlags, argTys, returnTy, ref None), tpenv | _ -> error(Error(FSComp.SR.tcInvalidConstraint(), m)) @@ -4369,7 +4435,7 @@ and TcValSpec cenv env declKind newOk containerInfo memFlagsOpt thisTyOpt tpenv // An implemented interface type is in terms of the type's type parameters. // We need a signature in terms of the values' type parameters. // let optIntfSlotTy = Option.map (instType renaming) optIntfSlotTy in - enclosingDeclaredTypars, Some(tcref), Some thisTy, declKind + enclosingDeclaredTypars, Some tcref, Some thisTy, declKind | None -> [], None, thisTyOpt, ModuleOrMemberBinding let allDeclaredTypars = enclosingDeclaredTypars @ declaredTypars @@ -4395,7 +4461,7 @@ and TcValSpec cenv env declKind newOk containerInfo memFlagsOpt thisTyOpt tpenv match memFlagsOpt, thisTyOpt with | Some memberFlags, Some thisTy -> - let generateOneMember(memberFlags) = + let generateOneMember memberFlags = // Decode members in the signature let ty', valSynInfo = @@ -4485,7 +4551,7 @@ and TcValSpec cenv env declKind newOk containerInfo memFlagsOpt thisTyOpt tpenv | MemberKind.Member | MemberKind.PropertyGet | MemberKind.PropertySet -> - generateOneMember(memberFlags), tpenv + generateOneMember memberFlags, tpenv | MemberKind.PropertyGetSet -> [ yield! generateOneMember({memberFlags with MemberKind=MemberKind.PropertyGet}) yield! generateOneMember({memberFlags with MemberKind=MemberKind.PropertySet}) ], tpenv @@ -4510,9 +4576,7 @@ and TcTyparOrMeasurePar optKind cenv (env: TcEnv) newOk tpenv (Typar(id, _, _) a | Some TyparKind.Type, TyparKind.Measure -> error (Error(FSComp.SR.tcExpectedTypeParameter(), id.idRange)); res, tpenv | _, _ -> let item = Item.TypeVar(id.idText, res) - CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.UseInType, env.DisplayEnv, env.eAccessRights) - // record the ' as well for tokenization - // CallNameResolutionSink cenv.tcSink (tp.Range.StartRange, env.NameEnv, item, item, ItemOccurence.UseInType, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.UseInType, env.AccessRights) res, tpenv let key = id.idText match env.eNameResEnv.eTypars.TryGetValue key with @@ -4522,48 +4586,44 @@ and TcTyparOrMeasurePar optKind cenv (env: TcEnv) newOk tpenv (Typar(id, _, _) a | Some res -> checkRes res | None -> if newOk = NoNewTypars then - let predictTypeParameters() = - let predictions1 = - env.eNameResEnv.eTypars - |> Seq.map (fun p -> "'" + p.Key) - - let predictions2 = - match tpenv with - | UnscopedTyparEnv elements -> - elements - |> Seq.map (fun p -> "'" + p.Key) - - [ yield! predictions1 - yield! predictions2 ] - |> HashSet - + let suggestTypeParameters (addToBuffer: string -> unit) = + for p in env.eNameResEnv.eTypars do + addToBuffer ("'" + p.Key) + + match tpenv with + | UnscopedTyparEnv elements -> + for p in elements do + addToBuffer ("'" + p.Key) + let reportedId = Ident("'" + id.idText, id.idRange) - error (UndefinedName(0, FSComp.SR.undefinedNameTypeParameter, reportedId, predictTypeParameters)) + error (UndefinedName(0, FSComp.SR.undefinedNameTypeParameter, reportedId, suggestTypeParameters)) // OK, this is an implicit declaration of a type parameter // The kind defaults to Type - let tp' = NewTypar ((match optKind with None -> TyparKind.Type | Some kind -> kind), TyparRigidity.WarnIfNotRigid, tp, false, TyparDynamicReq.Yes, [], false, false) + let kind = match optKind with None -> TyparKind.Type | Some kind -> kind + let tp' = Construct.NewTypar (kind, TyparRigidity.WarnIfNotRigid, tp, false, TyparDynamicReq.Yes, [], false, false) let item = Item.TypeVar(id.idText, tp') - CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.UseInType, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.UseInType, env.AccessRights) tp', AddUnscopedTypar key tp' tpenv and TcTypar cenv env newOk tpenv tp = TcTyparOrMeasurePar (Some TyparKind.Type) cenv env newOk tpenv tp -and TcTyparDecl cenv env (TyparDecl(synAttrs, (Typar(id, _, _) as stp))) = +and TcTyparDecl cenv env (TyparDecl(Attributes synAttrs, (Typar(id, _, _) as stp))) = let attrs = TcAttributes cenv env AttributeTargets.GenericParameter synAttrs let hasMeasureAttr = HasFSharpAttribute cenv.g cenv.g.attrib_MeasureAttribute attrs let hasEqDepAttr = HasFSharpAttribute cenv.g cenv.g.attrib_EqualityConditionalOnAttribute attrs let hasCompDepAttr = HasFSharpAttribute cenv.g cenv.g.attrib_ComparisonConditionalOnAttribute attrs let attrs = attrs |> List.filter (IsMatchingFSharpAttribute cenv.g cenv.g.attrib_MeasureAttribute >> not) - let tp = NewTypar ((if hasMeasureAttr then TyparKind.Measure else TyparKind.Type), TyparRigidity.WarnIfNotRigid, stp, false, TyparDynamicReq.Yes, attrs, hasEqDepAttr, hasCompDepAttr) + let kind = if hasMeasureAttr then TyparKind.Measure else TyparKind.Type + let tp = Construct.NewTypar (kind, TyparRigidity.WarnIfNotRigid, stp, false, TyparDynamicReq.Yes, attrs, hasEqDepAttr, hasCompDepAttr) match TryFindFSharpStringAttribute cenv.g cenv.g.attrib_CompiledNameAttribute attrs with | Some compiledName -> tp.SetILName (Some compiledName) | None -> () let item = Item.TypeVar(id.idText, tp) - CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.UseInType, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.UseInType, env.eAccessRights) tp @@ -4574,16 +4634,17 @@ and TcTyparDecls cenv env synTypars = List.map (TcTyparDecl cenv env) synTypars /// If optKind=None, we need to determine the kind (we're in *synthesis* mode) /// and TcTypeOrMeasure optKind cenv newOk checkCxs occ env (tpenv: SyntacticUnscopedTyparEnv) ty = + let g = cenv.g match ty with | SynType.LongIdent(LongIdentWithDots([], _)) -> // special case when type name is absent - i.e. empty inherit part in type declaration - cenv.g.obj_ty, tpenv + g.obj_ty, tpenv | SynType.LongIdent(LongIdentWithDots(tc, _) as lidwd) -> let m = lidwd.Range let ad = env.eAccessRights - let tcref = ForceRaise(ResolveTypeLongIdent cenv.tcSink cenv.nameResolver occ OpenQualified env.eNameResEnv ad tc TypeNameResolutionStaticArgsInfo.DefiniteEmpty PermitDirectReferenceToGeneratedType.No) + let tcref = ForceRaise(ResolveTypeLongIdent cenv.tcSink cenv.nameResolver occ OpenQualified env.NameEnv ad tc TypeNameResolutionStaticArgsInfo.DefiniteEmpty PermitDirectReferenceToGeneratedType.No) match optKind, tcref.TypeOrMeasureKind with | Some TyparKind.Type, TyparKind.Measure -> error(Error(FSComp.SR.tcExpectedTypeNotUnitOfMeasure(), m)) @@ -4614,7 +4675,7 @@ and TcTypeOrMeasure optKind cenv newOk checkCxs occ env (tpenv: SyntacticUnscope TType_measure (NewErrorMeasure ()), tpenv | _, TyparKind.Type -> - if postfix && tcref.Typars(m) |> List.exists (fun tp -> match tp.Kind with TyparKind.Measure -> true | _ -> false) + 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 checkCxs occ env tpenv m tcref [] args | _, TyparKind.Measure -> @@ -4631,7 +4692,7 @@ and TcTypeOrMeasure optKind cenv newOk checkCxs occ env (tpenv: SyntacticUnscope let ad = env.eAccessRights let ltyp, tpenv = TcType cenv newOk checkCxs occ env tpenv ltyp match ltyp with - | AppTy cenv.g (tcref, tinst) -> + | 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 checkCxs occ env tpenv m tcref tinst args | _ -> error(Error(FSComp.SR.tcTypeHasNoNestedTypes(), m)) @@ -4653,13 +4714,13 @@ and TcTypeOrMeasure optKind cenv newOk checkCxs occ env (tpenv: SyntacticUnscope | SynType.AnonRecd(isStruct, args,m) -> let tupInfo = mkTupInfo isStruct let args',tpenv = TcTypesAsTuple cenv newOk checkCxs occ env tpenv (args |> List.map snd |> List.map (fun x -> (false,x))) m - let unsortedIds = args |> List.map fst |> List.toArray - let anonInfo = AnonRecdTypeInfo.Create(cenv.topCcu, tupInfo, unsortedIds) + let unsortedFieldIds = args |> List.map fst |> List.toArray + let anonInfo = AnonRecdTypeInfo.Create(cenv.topCcu, tupInfo, unsortedFieldIds) // Sort into canonical order - let sortedArgTys, sortedCheckedArgTys = List.zip args args' |> List.indexed |> List.sortBy (fun (i,_) -> unsortedIds.[i].idText) |> List.map snd |> List.unzip - sortedArgTys |> List.iteri (fun i (x,_) -> + let sortedFieldTys, sortedCheckedArgTys = List.zip args args' |> List.indexed |> List.sortBy (fun (i,_) -> unsortedFieldIds.[i].idText) |> List.map snd |> List.unzip + sortedFieldTys |> List.iteri (fun i (x,_) -> let item = Item.AnonRecdField(anonInfo, sortedCheckedArgTys, i, x.idRange) - CallNameResolutionSink cenv.tcSink (x.idRange,env.NameEnv,item,item,emptyTyparInst,ItemOccurence.UseInType,env.DisplayEnv,env.eAccessRights)) + CallNameResolutionSink cenv.tcSink (x.idRange,env.NameEnv,item,emptyTyparInst,ItemOccurence.UseInType,env.eAccessRights)) TType_anon(anonInfo, sortedCheckedArgTys),tpenv | SynType.Fun(domainTy, resultTy, _) -> @@ -4669,7 +4730,7 @@ and TcTypeOrMeasure optKind cenv newOk checkCxs occ env (tpenv: SyntacticUnscope | SynType.Array (n, elemTy, m) -> let elemTy, tpenv = TcTypeAndRecover cenv newOk checkCxs occ env tpenv elemTy - mkArrayTy cenv.g n elemTy m, tpenv + mkArrayTy g n elemTy m, tpenv | SynType.Var (tp, _) -> let tp', tpenv = TcTyparOrMeasurePar optKind cenv env newOk tpenv tp @@ -4775,18 +4836,18 @@ and TcTypesAsTuple cenv newOk checkCxs occ env tpenv args m = match args with | [] -> error(InternalError("empty tuple type", m)) | [(_, ty)] -> let ty, tpenv = TcTypeAndRecover cenv newOk checkCxs occ env tpenv ty in [ty], tpenv - | (isquot, ty)::args -> + | (isquot, ty) :: args -> let ty, tpenv = TcTypeAndRecover cenv newOk checkCxs occ env tpenv ty let tys, tpenv = TcTypesAsTuple cenv newOk checkCxs occ env tpenv args m if isquot then errorR(Error(FSComp.SR.tcUnexpectedSlashInType(), m)) - ty::tys, tpenv + ty :: tys, tpenv // Type-check a list of measures separated by juxtaposition, * or / and TcMeasuresAsTuple cenv newOk checkCxs occ env (tpenv: SyntacticUnscopedTyparEnv) args m = let rec gather args tpenv isquot acc = match args with | [] -> acc, tpenv - | (nextisquot, ty)::args -> + | (nextisquot, ty) :: args -> let ms1, tpenv = TcMeasure cenv newOk checkCxs occ env tpenv ty m gather args tpenv nextisquot (if isquot then Measure.Prod(acc, Measure.Inv ms1) else Measure.Prod(acc, ms1)) gather args tpenv false Measure.One @@ -4809,32 +4870,33 @@ and TcTyparConstraints cenv newOk checkCxs occ env tpenv wcs = #if !NO_EXTENSIONTYPING and TcStaticConstantParameter cenv (env: TcEnv) tpenv kind (v: SynType) idOpt container = + let g = cenv.g let fail() = error(Error(FSComp.SR.etInvalidStaticArgument(NicePrint.minimalStringOfType env.DisplayEnv kind), v.Range)) let record ttype = match idOpt with | Some id -> let item = Item.ArgName (id, ttype, Some container) - CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.AccessRights) | _ -> () match v with | SynType.StaticConstant(sc, _) -> let v = match sc with - | SynConst.Byte n when typeEquiv cenv.g cenv.g.byte_ty kind -> record(cenv.g.byte_ty); box (n: byte) - | SynConst.Int16 n when typeEquiv cenv.g cenv.g.int16_ty kind -> record(cenv.g.int16_ty); box (n: int16) - | SynConst.Int32 n when typeEquiv cenv.g cenv.g.int32_ty kind -> record(cenv.g.int32_ty); box (n: int) - | SynConst.Int64 n when typeEquiv cenv.g cenv.g.int64_ty kind -> record(cenv.g.int64_ty); box (n: int64) - | SynConst.SByte n when typeEquiv cenv.g cenv.g.sbyte_ty kind -> record(cenv.g.sbyte_ty); box (n: sbyte) - | SynConst.UInt16 n when typeEquiv cenv.g cenv.g.uint16_ty kind -> record(cenv.g.uint16_ty); box (n: uint16) - | SynConst.UInt32 n when typeEquiv cenv.g cenv.g.uint32_ty kind -> record(cenv.g.uint32_ty); box (n: uint32) - | SynConst.UInt64 n when typeEquiv cenv.g cenv.g.uint64_ty kind -> record(cenv.g.uint64_ty); box (n: uint64) - | SynConst.Decimal n when typeEquiv cenv.g cenv.g.decimal_ty kind -> record(cenv.g.decimal_ty); box (n: decimal) - | SynConst.Single n when typeEquiv cenv.g cenv.g.float32_ty kind -> record(cenv.g.float32_ty); box (n: single) - | SynConst.Double n when typeEquiv cenv.g cenv.g.float_ty kind -> record(cenv.g.float_ty); box (n: double) - | SynConst.Char n when typeEquiv cenv.g cenv.g.char_ty kind -> record(cenv.g.char_ty); box (n: char) - | SynConst.String (s, _) when s <> null && typeEquiv cenv.g cenv.g.string_ty kind -> record(cenv.g.string_ty); box (s: string) - | SynConst.Bool b when typeEquiv cenv.g cenv.g.bool_ty kind -> record(cenv.g.bool_ty); box (b: bool) + | SynConst.Byte n when typeEquiv g g.byte_ty kind -> record(g.byte_ty); box (n: byte) + | SynConst.Int16 n when typeEquiv g g.int16_ty kind -> record(g.int16_ty); box (n: int16) + | SynConst.Int32 n when typeEquiv g g.int32_ty kind -> record(g.int32_ty); box (n: int) + | SynConst.Int64 n when typeEquiv g g.int64_ty kind -> record(g.int64_ty); box (n: int64) + | SynConst.SByte n when typeEquiv g g.sbyte_ty kind -> record(g.sbyte_ty); box (n: sbyte) + | SynConst.UInt16 n when typeEquiv g g.uint16_ty kind -> record(g.uint16_ty); box (n: uint16) + | SynConst.UInt32 n when typeEquiv g g.uint32_ty kind -> record(g.uint32_ty); box (n: uint32) + | SynConst.UInt64 n when typeEquiv g g.uint64_ty kind -> record(g.uint64_ty); box (n: uint64) + | SynConst.Decimal n when typeEquiv g g.decimal_ty kind -> record(g.decimal_ty); box (n: decimal) + | SynConst.Single n when typeEquiv g g.float32_ty kind -> record(g.float32_ty); box (n: single) + | SynConst.Double n when typeEquiv g g.float_ty kind -> record(g.float_ty); box (n: double) + | SynConst.Char n when typeEquiv g g.char_ty kind -> record(g.char_ty); box (n: char) + | SynConst.String (s, _) when s <> null && typeEquiv g g.string_ty kind -> record(g.string_ty); box (s: string) + | SynConst.Bool b when typeEquiv g g.bool_ty kind -> record(g.bool_ty); box (b: bool) | _ -> fail() v, tpenv | SynType.StaticConstantExpr(e, _ ) -> @@ -4843,33 +4905,33 @@ and TcStaticConstantParameter cenv (env: TcEnv) tpenv kind (v: SynType) idOpt co let te, tpenv' = TcExprNoRecover cenv kind env tpenv e // Evaluate the constant expression using static attribute argument rules - let te = EvalLiteralExprOrAttribArg cenv.g te + let te = EvalLiteralExprOrAttribArg g te let v = match stripExpr te with // Check we have a residue constant. We know the type was correct because we checked the expression with this type. - | Expr.Const(c, _, _) -> + | Expr.Const (c, _, _) -> match c with - | Const.Byte n -> record(cenv.g.byte_ty); box (n: byte) - | Const.Int16 n -> record(cenv.g.int16_ty); box (n: int16) - | Const.Int32 n -> record(cenv.g.int32_ty); box (n: int) - | Const.Int64 n -> record(cenv.g.int64_ty); box (n: int64) - | Const.SByte n -> record(cenv.g.sbyte_ty); box (n: sbyte) - | Const.UInt16 n -> record(cenv.g.uint16_ty); box (n: uint16) - | Const.UInt32 n -> record(cenv.g.uint32_ty); box (n: uint32) - | Const.UInt64 n -> record(cenv.g.uint64_ty); box (n: uint64) - | Const.Decimal n -> record(cenv.g.decimal_ty); box (n: decimal) - | Const.Single n -> record(cenv.g.float32_ty); box (n: single) - | Const.Double n -> record(cenv.g.float_ty); box (n: double) - | Const.Char n -> record(cenv.g.char_ty); box (n: char) + | Const.Byte n -> record(g.byte_ty); box (n: byte) + | Const.Int16 n -> record(g.int16_ty); box (n: int16) + | Const.Int32 n -> record(g.int32_ty); box (n: int) + | Const.Int64 n -> record(g.int64_ty); box (n: int64) + | Const.SByte n -> record(g.sbyte_ty); box (n: sbyte) + | Const.UInt16 n -> record(g.uint16_ty); box (n: uint16) + | Const.UInt32 n -> record(g.uint32_ty); box (n: uint32) + | Const.UInt64 n -> record(g.uint64_ty); box (n: uint64) + | Const.Decimal n -> record(g.decimal_ty); box (n: decimal) + | Const.Single n -> record(g.float32_ty); box (n: single) + | Const.Double n -> record(g.float_ty); box (n: double) + | Const.Char n -> record(g.char_ty); box (n: char) | Const.String null -> fail() - | Const.String s -> record(cenv.g.string_ty); box (s: string) - | Const.Bool b -> record(cenv.g.bool_ty); box (b: bool) + | Const.String s -> record(g.string_ty); box (s: string) + | Const.Bool b -> record(g.bool_ty); box (b: bool) | _ -> fail() | _ -> error(Error(FSComp.SR.tcInvalidConstantExpression(), v.Range)) v, tpenv' - | SynType.LongIdent(lidwd) -> + | SynType.LongIdent lidwd -> let m = lidwd.Range - TcStaticConstantParameter cenv env tpenv kind (SynType.StaticConstantExpr(SynExpr.LongIdent(false, lidwd, None, m), m)) idOpt container + TcStaticConstantParameter cenv env tpenv kind (SynType.StaticConstantExpr(SynExpr.LongIdent (false, lidwd, None, m), m)) idOpt container | _ -> fail() @@ -4931,7 +4993,7 @@ and TcProvidedTypeAppToStaticConstantArgs cenv env optGeneratedTypePath tpenv (t | TProvidedTypeExtensionPoint info -> info.ProvidedType | _ -> failwith "unreachable" - let staticParameters = typeBeforeArguments.PApplyWithProvider((fun (typeBeforeArguments, provider) -> typeBeforeArguments.GetStaticParameters(provider)), range=m) + let staticParameters = typeBeforeArguments.PApplyWithProvider((fun (typeBeforeArguments, provider) -> typeBeforeArguments.GetStaticParameters provider), range=m) let staticParameters = staticParameters.PApplyArray(id, "GetStaticParameters", m) let argsInStaticParameterOrderIncludingDefaults = CrackStaticConstantArgs cenv env tpenv (staticParameters, args, ArgumentContainer.Type tcref, tcref.DisplayName, m) @@ -4993,8 +5055,9 @@ and TcProvidedTypeApp cenv env tpenv tcref args m = /// In this case, 'args' is only the instantiation of the suffix type arguments, and pathTypeArgs gives /// the prefix of type arguments. and TcTypeApp cenv newOk checkCxs occ env tpenv m tcref pathTypeArgs (synArgTys: SynType list) = - CheckTyconAccessible cenv.amap m env.eAccessRights tcref |> ignore - CheckEntityAttributes cenv.g tcref m |> CommitOperationResult + let g = cenv.g + CheckTyconAccessible cenv.amap m env.AccessRights tcref |> ignore + CheckEntityAttributes g tcref m |> CommitOperationResult #if !NO_EXTENSIONTYPING // Provided types are (currently) always non-generic. Their names may include mangled @@ -5002,7 +5065,7 @@ and TcTypeApp cenv newOk checkCxs occ env tpenv m tcref pathTypeArgs (synArgTys: if tcref.Deref.IsProvided then TcProvidedTypeApp cenv env tpenv tcref synArgTys m else #endif - let tps, _, tinst, _ = infoOfTyconRef m tcref + let tps, _, tinst, _ = FreshenTyconRef2 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. @@ -5023,7 +5086,7 @@ and TcTypeApp cenv newOk checkCxs occ env tpenv m tcref pathTypeArgs (synArgTys: List.iter2 (UnifyTypes cenv env m) tinst actualArgTys // Try to decode System.Tuple --> F~ tuple types etc. - let ty = cenv.g.decompileType tcref actualArgTys + let ty = g.decompileType tcref actualArgTys ty, tpenv @@ -5109,9 +5172,9 @@ and ValidateOptArgOrder (spats: SynSimplePats) = let pats, m = getPats spats - let hitOptArg = ref false + let mutable hitOptArg = false - List.iter (fun pat -> if isOptArg pat then hitOptArg := true elif !hitOptArg then error(Error(FSComp.SR.tcOptionalArgsMustComeAfterNonOptionalArgs(), m))) pats + List.iter (fun pat -> if isOptArg pat then hitOptArg <- true elif hitOptArg then error(Error(FSComp.SR.tcOptionalArgsMustComeAfterNonOptionalArgs(), m))) pats /// Bind the patterns used in argument position for a function, method or lambda. @@ -5183,7 +5246,7 @@ and TcPatBindingName cenv env id ty isMemberThis vis1 topValData (inlineFlag, de // For non-left-most paths, we register the name resolutions here if not isLeftMost && not vspec.IsCompilerGenerated && not (vspec.LogicalName.StartsWithOrdinal("_")) then let item = Item.Value(mkLocalValRef vspec) - CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Binding, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Binding, env.AccessRights) PBind(vspec, typeScheme)), names, takenNames @@ -5197,7 +5260,7 @@ and TcPatAndRecover warnOnUpper cenv (env: TcEnv) topValInfo vFlags (tpenv, name let m = pat.Range errorRecovery e m //solveTypAsError cenv env.DisplayEnv m ty - (fun _ -> TPat_wild m), (tpenv, names, takenNames) + (fun _ -> TPat_error m), (tpenv, names, takenNames) /// Typecheck a pattern. Patterns are type-checked in three phases: /// 1. TcPat builds a List.map from simple variable names to inferred types for @@ -5208,19 +5271,26 @@ and TcPatAndRecover warnOnUpper cenv (env: TcEnv) topValInfo vFlags (tpenv, name /// the second-phase function in terms of a List.map from names to actual /// value specifications. and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty pat = - let ad = env.eAccessRights + let ad = env.AccessRights match pat with | SynPat.Const (c, m) -> match c with | SynConst.Bytes (bytes, m) -> UnifyTypes cenv env m ty (mkByteArrayTy cenv.g) TcPat warnOnUpper cenv env None vFlags (tpenv, names, takenNames) ty (SynPat.ArrayOrList (true, [ for b in bytes -> SynPat.Const(SynConst.Byte b, m) ], m)) + | SynConst.UserNum _ -> - error(Error(FSComp.SR.tcInvalidNonPrimitiveLiteralInPatternMatch(), m)) - | _ -> - let c' = TcConst cenv ty m env c - (fun (_: TcPatPhase2Input) -> TPat_const(c', m)), (tpenv, names, takenNames) - + errorR (Error (FSComp.SR.tcInvalidNonPrimitiveLiteralInPatternMatch (), m)) + (fun _ -> TPat_error m), (tpenv, names, takenNames) + + | _ -> + try + let c' = TcConst cenv ty m env c + (fun _ -> TPat_const (c', m)), (tpenv, names, takenNames) + with e -> + errorRecovery e m + (fun _ -> TPat_error m), (tpenv, names, takenNames) + | SynPat.Wild m -> (fun _ -> TPat_wild m), (tpenv, names, takenNames) @@ -5238,8 +5308,10 @@ and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p (tpenv, names, takenNames) | _ -> failwith "TcPat" - | SynPat.OptionalVal (_, m) -> - error(Error(FSComp.SR.tcOptionalArgsOnlyOnMembers(), m)) + | SynPat.OptionalVal (id, m) -> + errorR (Error (FSComp.SR.tcOptionalArgsOnlyOnMembers (), m)) + let bindf, names, takenNames = TcPatBindingName cenv env id ty false None topValInfo vFlags (names, takenNames) + (fun values -> TPat_as (TPat_wild m, bindf values, m)), (tpenv, names, takenNames) | SynPat.Named (p, id, isMemberThis, vis, m) -> let bindf, names, takenNames = TcPatBindingName cenv env id ty isMemberThis vis topValInfo vFlags (names, takenNames) @@ -5252,22 +5324,28 @@ and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p UnifyTypes cenv env m ty cty' TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p - | SynPat.Attrib (_, _, m) -> - error(Error(FSComp.SR.tcAttributesInvalidInPatterns(), m)) + | SynPat.Attrib (p, attrs, _) -> + errorR (Error (FSComp.SR.tcAttributesInvalidInPatterns (), rangeOfNonNilAttrs attrs)) + for attrList in attrs do + TcAttributes cenv env Unchecked.defaultof<_> attrList.Attributes |> ignore + TcPat warnOnUpper cenv env None vFlags (tpenv, names, takenNames) ty p | SynPat.Or (pat1, pat2, m) -> let pat1', (tpenv, names1, takenNames1) = TcPat warnOnUpper cenv env None vFlags (tpenv, names, takenNames) ty pat1 let pat2', (tpenv, names2, takenNames2) = TcPat warnOnUpper cenv env None vFlags (tpenv, names, takenNames) ty pat2 if not (takenNames1 = takenNames2) then - // We don't try to recover from this error since we get later bad internal errors during pattern - // matching - error (UnionPatternsBindDifferentNames m) - names1 |> Map.iter (fun _ (PrelimValScheme1(id1, _, ty1, _, _, _, _, _, _, _, _)) -> - match names2.TryGetValue id1.idText with - | true, PrelimValScheme1(_, _, ty2, _, _, _, _, _, _, _, _) -> - UnifyTypes cenv env m ty1 ty2 - | _ -> ()) - (fun values -> TPat_disjs ([pat1' values;pat2' values.RightPath], m)), (tpenv, names1, takenNames1) + errorR (UnionPatternsBindDifferentNames m) + + names1 |> Map.iter (fun _ (PrelimValScheme1 (id1, _, ty1, _, _, _, _, _, _, _, _)) -> + match names2.TryGetValue id1.idText with + | true, PrelimValScheme1 (id2, _, ty2, _, _, _, _, _, _, _, _) -> + try UnifyTypes cenv env id2.idRange ty1 ty2 + with e -> errorRecovery e m + | _ -> ()) + + let names = NameMap.layer names1 names2 + let takenNames = Set.union takenNames1 takenNames2 + (fun values -> TPat_disjs ([pat1' values; pat2' values.RightPath], m)), (tpenv, names, takenNames) | SynPat.Ands (pats, m) -> let pats', acc = TcPatterns warnOnUpper cenv env vFlags (tpenv, names, takenNames) (List.map (fun _ -> ty) pats) pats @@ -5277,25 +5355,45 @@ and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p if Option.isSome tyargs then errorR(Error(FSComp.SR.tcInvalidTypeArgumentUsage(), m)) let warnOnUpperForId = match args with - | SynConstructorArgs.Pats [] -> warnOnUpper + | SynArgPats.Pats [] -> warnOnUpper | _ -> AllIdsOK - let checkNoArgsForLiteral() = - let numArgs = - match args with - | SynConstructorArgs.Pats args -> args.Length - | SynConstructorArgs.NamePatPairs (pairs, _) -> pairs.Length - if numArgs <> 0 then error(Error(FSComp.SR.tcLiteralDoesNotTakeArguments(), m)) + let lidRange = rangeOfLid longId - match ResolvePatternLongIdent cenv.tcSink cenv.nameResolver warnOnUpperForId false m ad env.eNameResEnv TypeNameResolutionInfo.Default longId with + let checkNoArgsForLiteral () = + match args with + | SynArgPats.Pats [] + | SynArgPats.NamePatPairs ([], _) -> () + | _ -> errorR (Error (FSComp.SR.tcLiteralDoesNotTakeArguments (), m)) + + let getArgPatterns () = + match args with + | SynArgPats.Pats args -> args + | SynArgPats.NamePatPairs (pairs, _) -> List.map snd pairs + + let tcArgPatterns () = + let args = getArgPatterns () + TcPatterns warnOnUpper cenv env vFlags (tpenv, names, takenNames) (NewInferenceTypes args) args + + match ResolvePatternLongIdent cenv.tcSink cenv.nameResolver warnOnUpperForId false m ad env.NameEnv TypeNameResolutionInfo.Default longId with | Item.NewDef id -> - match args with - | SynConstructorArgs.Pats [] - | SynConstructorArgs.NamePatPairs ([], _)-> TcPat warnOnUpperForId cenv env topValInfo vFlags (tpenv, names, takenNames) ty (mkSynPatVar vis id) - | _ -> error (UndefinedName(0, FSComp.SR.undefinedNamePatternDiscriminator, id, NoSuggestions)) + let _, acc = tcArgPatterns () + match getArgPatterns () with + | [] -> TcPat warnOnUpperForId cenv env topValInfo vFlags acc ty (mkSynPatVar vis id) + | _ -> + errorR (UndefinedName (0, FSComp.SR.undefinedNamePatternDiscriminator, id, NoSuggestions)) + (fun _ -> TPat_error m), acc + + | Item.ActivePatternCase (APElemRef (apinfo, vref, idx)) as item -> + // Report information about the 'active recognizer' occurrence to IDE + CallNameResolutionSink cenv.tcSink (rangeOfLid longId, env.NameEnv, item, emptyTyparInst, ItemOccurence.Pattern, env.eAccessRights) + + match args with + | SynArgPats.Pats _ -> () + | _ -> errorR (Error (FSComp.SR.tcNamedActivePattern (apinfo.ActiveTags.[idx]), m)) + + let args = getArgPatterns () - | Item.ActivePatternCase(APElemRef(apinfo, vref, idx)) as item -> - let args = match args with SynConstructorArgs.Pats args -> args | _ -> error(Error(FSComp.SR.tcNamedActivePattern(apinfo.ActiveTags.[idx]), m)) // TOTAL/PARTIAL ACTIVE PATTERNS let _, vexp, _, _, tinst, _ = TcVal true cenv env tpenv vref None None m let vexp = MakeApplicableExprWithFlex cenv env vexp @@ -5315,30 +5413,30 @@ and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p List.frontAndBack args if not (isNil activePatArgsAsSynPats) && apinfo.ActiveTags.Length <> 1 then - error(Error(FSComp.SR.tcRequireActivePatternWithOneResult(), m)) + errorR (Error (FSComp.SR.tcRequireActivePatternWithOneResult (), m)) // Parse the arguments to an active pattern // Note we parse arguments to parameterized pattern labels as patterns, not expressions. // This means the range of syntactic expression forms that can be used here is limited. let rec convSynPatToSynExpr x = match x with - | SynPat.FromParseError(p, _) -> convSynPatToSynExpr p - | SynPat.Const (c, m) -> SynExpr.Const(c, m) - | SynPat.Named (SynPat.Wild _, id, _, None, _) -> SynExpr.Ident(id) + | SynPat.FromParseError (p, _) -> convSynPatToSynExpr p + | SynPat.Const (c, m) -> SynExpr.Const (c, m) + | SynPat.Named (SynPat.Wild _, id, _, None, _) -> SynExpr.Ident id | SynPat.Typed (p, cty, m) -> SynExpr.Typed (convSynPatToSynExpr p, cty, m) - | SynPat.LongIdent (LongIdentWithDots(longId, dotms) as lidwd, _, _tyargs, args, None, m) -> - let args = match args with SynConstructorArgs.Pats args -> args | _ -> failwith "impossible: active patterns can be used only with SynConstructorArgs.Pats" + | SynPat.LongIdent (LongIdentWithDots (longId, dotms) as lidwd, _, _tyargs, args, None, m) -> + let args = match args with SynArgPats.Pats args -> args | _ -> failwith "impossible: active patterns can be used only with SynArgPats.Pats" let e = if dotms.Length = longId.Length then - let e = SynExpr.LongIdent(false, LongIdentWithDots(longId, List.truncate (dotms.Length - 1) dotms), None, m) - SynExpr.DiscardAfterMissingQualificationAfterDot(e, unionRanges e.Range (List.last dotms)) - else SynExpr.LongIdent(false, lidwd, None, m) + let e = SynExpr.LongIdent (false, LongIdentWithDots(longId, List.truncate (dotms.Length - 1) dotms), None, m) + SynExpr.DiscardAfterMissingQualificationAfterDot (e, unionRanges e.Range (List.last dotms)) + else SynExpr.LongIdent (false, lidwd, None, m) List.fold (fun f x -> mkSynApp1 f (convSynPatToSynExpr x) m) e args - | SynPat.Tuple (isStruct, args, m) -> SynExpr.Tuple(isStruct, List.map convSynPatToSynExpr args, [], m) + | SynPat.Tuple (isStruct, args, m) -> SynExpr.Tuple (isStruct, List.map convSynPatToSynExpr args, [], m) | SynPat.Paren (p, _) -> convSynPatToSynExpr p - | SynPat.ArrayOrList (isArray, args, m) -> SynExpr.ArrayOrList(isArray,List.map convSynPatToSynExpr args, m) + | SynPat.ArrayOrList (isArray, args, m) -> SynExpr.ArrayOrList (isArray,List.map convSynPatToSynExpr args, m) | SynPat.QuoteExpr (e,_) -> e - | SynPat.Null m -> SynExpr.Null(m) + | SynPat.Null m -> SynExpr.Null m | _ -> error(Error(FSComp.SR.tcInvalidArgForParameterizedPattern(), x.Range)) let activePatArgsAsSynExprs = List.map convSynPatToSynExpr activePatArgsAsSynPats @@ -5351,142 +5449,189 @@ and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p if idx >= activePatResTys.Length then error(Error(FSComp.SR.tcInvalidIndexIntoActivePatternArray(), m)) let argty = List.item idx activePatResTys - let arg', (tpenv, names, takenNames) = TcPat warnOnUpper cenv env None vFlags (tpenv, names, takenNames) argty patarg - + let arg', acc = TcPat warnOnUpper cenv env None vFlags (tpenv, names, takenNames) argty patarg + // The identity of an active pattern consists of its value and the types it is applied to. // If there are any expression args then we've lost identity. let activePatIdentity = if isNil activePatArgsAsSynExprs then Some (vref, tinst) else None (fun values -> - // Report information about the 'active recognizer' occurrence to IDE - CallNameResolutionSink cenv.tcSink (rangeOfLid longId, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Pattern, env.DisplayEnv, env.eAccessRights) - TPat_query((activePatExpr, activePatResTys, activePatIdentity, idx, apinfo), arg' values, m)), - (tpenv, names, takenNames) + TPat_query((activePatExpr, activePatResTys, activePatIdentity, idx, apinfo), arg' values, m)), acc | (Item.UnionCase _ | Item.ExnCase _) as item -> - // DATA MATCH CONSTRUCTORS + // Report information about the case occurrence to IDE + CallNameResolutionSink cenv.tcSink (lidRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Pattern, env.eAccessRights) + let mkf, argTys, argNames = ApplyUnionCaseOrExnTypesForPat m cenv env ty item let numArgTys = argTys.Length - let args = + let args, extraPatternsFromNames = match args with - | SynConstructorArgs.Pats args -> args - | SynConstructorArgs.NamePatPairs (pairs, m) -> - // rewrite patterns from the form (name-N = pat-N...) to (..._, pat-N, _...) + | SynArgPats.Pats args -> args, [] + | SynArgPats.NamePatPairs (pairs, m) -> + // rewrite patterns from the form (name-N = pat-N; ...) to (..._, pat-N, _...) // so type T = Case of name: int * value: int // | Case(value = v) // will become // | Case(_, v) let result = Array.zeroCreate numArgTys + let extraPatterns = List () + for (id, pat) in pairs do match argNames |> List.tryFindIndex (fun id2 -> id.idText = id2.idText) with | None -> + extraPatterns.Add pat match item with | Item.UnionCase(uci, _) -> - error(Error(FSComp.SR.tcUnionCaseConstructorDoesNotHaveFieldWithGivenName(uci.Name, id.idText), id.idRange)) + errorR (Error (FSComp.SR.tcUnionCaseConstructorDoesNotHaveFieldWithGivenName (uci.Name, id.idText), id.idRange)) | Item.ExnCase tcref -> - error(Error(FSComp.SR.tcExceptionConstructorDoesNotHaveFieldWithGivenName(tcref.DisplayName, id.idText), id.idRange)) + errorR (Error (FSComp.SR.tcExceptionConstructorDoesNotHaveFieldWithGivenName (tcref.DisplayName, id.idText), id.idRange)) | _ -> - error(Error(FSComp.SR.tcConstructorDoesNotHaveFieldWithGivenName(id.idText), id.idRange)) + errorR (Error (FSComp.SR.tcConstructorDoesNotHaveFieldWithGivenName (id.idText), id.idRange)) | Some idx -> + let argItem = + match item with + | Item.UnionCase (uci, _) -> Item.UnionCaseField (uci, idx) + | Item.ExnCase tref -> Item.RecdField (RecdFieldInfo ([], RecdFieldRef (tref, id.idText))) + | _ -> failwithf "Expecting union case or exception item, got: %O" item + + CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, argItem, emptyTyparInst, ItemOccurence.Pattern, ad) + match box result.[idx] with - | null -> - result.[idx] <- pat - let argContainerOpt = match item with - | Item.UnionCase(uci, _) -> Some(ArgumentContainer.UnionCase(uci)) - | Item.ExnCase tref -> Some(ArgumentContainer.Type(tref)) - | _ -> None - let argItem = Item.ArgName (argNames.[idx], argTys.[idx], argContainerOpt) - CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, argItem, argItem, emptyTyparInst, ItemOccurence.Pattern, env.DisplayEnv, ad) + | null -> result.[idx] <- pat | _ -> - error(Error(FSComp.SR.tcUnionCaseFieldCannotBeUsedMoreThanOnce(id.idText), id.idRange)) + extraPatterns.Add pat + errorR (Error (FSComp.SR.tcUnionCaseFieldCannotBeUsedMoreThanOnce (id.idText), id.idRange)) + for i = 0 to numArgTys - 1 do if isNull (box result.[i]) then - result.[i] <- SynPat.Wild(m.MakeSynthetic()) + result.[i] <- SynPat.Wild (m.MakeSynthetic()) + + let extraPatterns = + if isNull extraPatterns then [] else List.ofSeq extraPatterns let args = List.ofArray result - if result.Length = 1 then args - else [ SynPat.Tuple(false, args, m) ] - - let args = - match args with - | []-> [] - // note: the next will always be parenthesized - | [SynPatErrorSkip(SynPat.Tuple (false, args, _)) | SynPatErrorSkip(SynPat.Paren(SynPatErrorSkip(SynPat.Tuple (false, args, _)), _))] when numArgTys > 1 -> args - - // note: we allow both 'C _' and 'C (_)' regardless of number of argument of the pattern - | [SynPatErrorSkip(SynPat.Wild _ as e) | SynPatErrorSkip(SynPat.Paren(SynPatErrorSkip(SynPat.Wild _ as e), _))] -> Array.toList (Array.create numArgTys e) - | [arg] -> [arg] - | _ when numArgTys = 0 -> error(Error(FSComp.SR.tcUnionCaseDoesNotTakeArguments(), m)) - | _ when numArgTys = 1 -> error(Error(FSComp.SR.tcUnionCaseRequiresOneArgument(), m)) - | _ -> error(Error(FSComp.SR.tcUnionCaseExpectsTupledArguments(numArgTys), m)) - UnionCaseOrExnCheck env numArgTys args.Length m + if result.Length = 1 then args, extraPatterns + else [ SynPat.Tuple(false, args, m) ], extraPatterns + + let args, extraPatterns = + match args with + | [] -> [], [] + + // note: the next will always be parenthesized + | [SynPatErrorSkip(SynPat.Tuple (false, args, _)) | SynPatErrorSkip(SynPat.Paren(SynPatErrorSkip(SynPat.Tuple (false, args, _)), _))] when numArgTys > 1 -> args, [] + + // note: we allow both 'C _' and 'C (_)' regardless of number of argument of the pattern + | [SynPatErrorSkip(SynPat.Wild _ as e) | SynPatErrorSkip(SynPat.Paren(SynPatErrorSkip(SynPat.Wild _ as e), _))] -> List.replicate numArgTys e, [] + + | args when numArgTys = 0 -> + errorR (Error (FSComp.SR.tcUnionCaseDoesNotTakeArguments (), m)) + [], args + + + | arg :: rest when numArgTys = 1 -> + if numArgTys = 1 && not (List.isEmpty rest) then + errorR (Error (FSComp.SR.tcUnionCaseRequiresOneArgument (), m)) + [arg], rest + + | [arg] -> [arg], [] + + | args -> + errorR (Error (FSComp.SR.tcUnionCaseExpectsTupledArguments numArgTys, m)) + [], args + + let args, extraPatterns = + let numArgs = args.Length + if numArgs = numArgTys then + args, extraPatterns + else + if numArgs < numArgTys then + if numArgs <> 0 && numArgTys <> 0 then + errorR (UnionCaseWrongArguments (env.DisplayEnv, numArgTys, numArgs, m)) + args @ (List.init (numArgTys - numArgs) (fun _ -> SynPat.Wild (m.MakeSynthetic()))), extraPatterns + else + let args, remaining = args |> List.splitAt numArgTys + for remainingArg in remaining do + errorR (UnionCaseWrongArguments (env.DisplayEnv, numArgTys, numArgs, remainingArg.Range)) + args, extraPatterns @ remaining + + let extraPatterns = extraPatterns @ extraPatternsFromNames let args', acc = TcPatterns warnOnUpper cenv env vFlags (tpenv, names, takenNames) argTys args - (fun values -> - // Report information about the case occurrence to IDE - CallNameResolutionSink cenv.tcSink (rangeOfLid longId, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Pattern, env.DisplayEnv, env.eAccessRights) - mkf m (List.map (fun f -> f values) args')), acc + let _, acc = TcPatterns warnOnUpper cenv env vFlags acc (NewInferenceTypes extraPatterns) extraPatterns + (fun values -> mkf m (List.map (fun f -> f values) args')), acc | Item.ILField finfo -> - // LITERAL .NET FIELDS - CheckILFieldInfoAccessible cenv.g cenv.amap m env.eAccessRights finfo - if not finfo.IsStatic then errorR (Error (FSComp.SR.tcFieldIsNotStatic(finfo.FieldName), m)) + CheckILFieldInfoAccessible cenv.g cenv.amap lidRange env.AccessRights finfo + if not finfo.IsStatic then + errorR (Error (FSComp.SR.tcFieldIsNotStatic (finfo.FieldName), lidRange)) CheckILFieldAttributes cenv.g finfo m match finfo.LiteralValue with - | None -> error (Error(FSComp.SR.tcFieldNotLiteralCannotBeUsedInPattern(), m)) + | None -> error (Error (FSComp.SR.tcFieldNotLiteralCannotBeUsedInPattern (), lidRange)) | Some lit -> - checkNoArgsForLiteral() - UnifyTypes cenv env m ty (finfo.FieldType(cenv.amap, m)) - let c' = TcFieldInit m lit - let item = Item.ILField(finfo) - CallNameResolutionSink cenv.tcSink (m, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Pattern, env.DisplayEnv, env.AccessRights) - (fun _ -> TPat_const (c', m)), (tpenv, names, takenNames) - + checkNoArgsForLiteral () + let _, acc = tcArgPatterns () + + UnifyTypes cenv env m ty (finfo.FieldType (cenv.amap, m)) + let c' = TcFieldInit lidRange lit + let item = Item.ILField finfo + CallNameResolutionSink cenv.tcSink (lidRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Pattern, env.AccessRights) + (fun _ -> TPat_const (c', m)), acc + | Item.RecdField rfinfo -> - // LITERAL F# FIELDS - CheckRecdFieldInfoAccessible cenv.amap m env.eAccessRights rfinfo - if not rfinfo.IsStatic then errorR (Error (FSComp.SR.tcFieldIsNotStatic(rfinfo.Name), m)) - CheckRecdFieldInfoAttributes cenv.g rfinfo m |> CommitOperationResult + CheckRecdFieldInfoAccessible cenv.amap lidRange env.AccessRights rfinfo + if not rfinfo.IsStatic then errorR (Error (FSComp.SR.tcFieldIsNotStatic(rfinfo.Name), lidRange)) + CheckRecdFieldInfoAttributes cenv.g rfinfo lidRange |> CommitOperationResult match rfinfo.LiteralValue with - | None -> error (Error(FSComp.SR.tcFieldNotLiteralCannotBeUsedInPattern(), m)) + | None -> error (Error(FSComp.SR.tcFieldNotLiteralCannotBeUsedInPattern(), lidRange)) | Some lit -> checkNoArgsForLiteral() + let _, acc = tcArgPatterns () + UnifyTypes cenv env m ty rfinfo.FieldType - let item = Item.RecdField(rfinfo) + let item = Item.RecdField rfinfo // FUTURE: can we do better than emptyTyparInst here, in order to display instantiations // of type variables in the quick info provided in the IDE. - CallNameResolutionSink cenv.tcSink (m, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Pattern, env.DisplayEnv, env.AccessRights) - (fun _ -> TPat_const (lit, m)), (tpenv, names, takenNames) + CallNameResolutionSink cenv.tcSink (lidRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Pattern, env.AccessRights) + (fun _ -> TPat_const (lit, m)), acc | Item.Value vref -> match vref.LiteralValue with | None -> error (Error(FSComp.SR.tcNonLiteralCannotBeUsedInPattern(), m)) | Some lit -> - let _, _, _, vexpty, _, _ = TcVal true cenv env tpenv vref None None m - CheckValAccessible m env.eAccessRights vref - CheckFSharpAttributes cenv.g vref.Attribs m |> CommitOperationResult + let _, _, _, vexpty, _, _ = TcVal true cenv env tpenv vref None None lidRange + CheckValAccessible lidRange env.AccessRights vref + CheckFSharpAttributes cenv.g vref.Attribs lidRange |> CommitOperationResult checkNoArgsForLiteral() + let _, acc = tcArgPatterns () + UnifyTypes cenv env m ty vexpty - let item = Item.Value(vref) - CallNameResolutionSink cenv.tcSink (m, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Pattern, env.DisplayEnv, env.AccessRights) - (fun _ -> TPat_const (lit, m)), (tpenv, names, takenNames) + let item = Item.Value vref + CallNameResolutionSink cenv.tcSink (lidRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Pattern, env.AccessRights) + (fun _ -> TPat_const (lit, m)), acc | _ -> error (Error(FSComp.SR.tcRequireVarConstRecogOrLiteral(), m)) - | SynPat.QuoteExpr(_, m) -> error (Error(FSComp.SR.tcInvalidPattern(), m)) - + | SynPat.QuoteExpr(_, m) -> + errorR (Error(FSComp.SR.tcInvalidPattern(), m)) + (fun _ -> TPat_error m), (tpenv, names, takenNames) + | SynPat.Tuple (isExplicitStruct, args, m) -> - let tupInfo, argTys = UnifyTupleTypeAndInferCharacteristics env.eContextInfo cenv env.DisplayEnv m ty isExplicitStruct args - let args', acc = TcPatterns warnOnUpper cenv env vFlags (tpenv, names, takenNames) argTys args - (fun values -> TPat_tuple(tupInfo, List.map (fun f -> f values) args', argTys, m)), acc + try + let tupInfo, argTys = UnifyTupleTypeAndInferCharacteristics env.eContextInfo cenv env.DisplayEnv m ty isExplicitStruct args + let args', acc = TcPatterns warnOnUpper cenv env vFlags (tpenv, names, takenNames) argTys args + (fun values -> TPat_tuple(tupInfo, List.map (fun f -> f values) args', argTys, m)), acc + with e -> + errorRecovery e m + let _, acc = TcPatterns warnOnUpper cenv env vFlags (tpenv, names, takenNames) (NewInferenceTypes args) args + (fun _ -> TPat_error m), acc | SynPat.Paren (p, _) -> TcPat warnOnUpper cenv env None vFlags (tpenv, names, takenNames) ty p | SynPat.ArrayOrList (isArray, args, m) -> let argty = NewInferenceType () - UnifyTypes cenv env m ty (if isArray then mkArrayType cenv.g argty else Tastops.mkListTy cenv.g argty) + UnifyTypes cenv env m ty (if isArray then mkArrayType cenv.g argty else mkListTy cenv.g argty) let args', acc = TcPatterns warnOnUpper cenv env vFlags (tpenv, names, takenNames) (List.map (fun _ -> argty) args) args (fun values -> let args' = List.map (fun f -> f values) args' @@ -5496,7 +5641,7 @@ and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p | SynPat.Record (flds, m) -> let tcref, fldsmap, _fldsList = BuildFieldMap cenv env true ty flds m // REVIEW: use _fldsList to type check pattern in code order not field defn order - let _, inst, tinst, gtyp = infoOfTyconRef m tcref + let _, inst, tinst, gtyp = FreshenTyconRef2 m tcref UnifyTypes cenv env m ty gtyp let fields = tcref.TrueInstanceFieldsAsList let ftys = fields |> List.map (fun fsp -> actualTyOfRecdField inst fsp, fsp) @@ -5514,12 +5659,14 @@ and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p (fun _ -> TPat_range(c1, c2, m)), (tpenv, names, takenNames) | SynPat.Null m -> - AddCxTypeMustSupportNull env.DisplayEnv cenv.css m NoTrace ty + try AddCxTypeMustSupportNull env.DisplayEnv cenv.css m NoTrace ty + with e -> errorRecovery e m (fun _ -> TPat_null m), (tpenv, names, takenNames) | SynPat.InstanceMember (_, _, _, _, m) -> errorR(Error(FSComp.SR.tcIllegalPattern(), pat.Range)) (fun _ -> TPat_wild m), (tpenv, names, takenNames) + | SynPat.FromParseError (pat, _) -> suppressErrorReporting (fun () -> TcPatAndRecover warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) (NewErrorType()) pat) @@ -5527,11 +5674,7 @@ and TcPatterns warnOnUpper cenv env vFlags s argTys args = assert (List.length args = List.length argTys) List.mapFold (fun s (ty, pat) -> TcPat warnOnUpper cenv env None vFlags s ty pat) s (List.zip argTys args) - -and solveTypAsError cenv denv m ty = - let ty2 = NewErrorType () - assert((destTyparTy cenv.g ty2).IsFromError) - SolveTypeEqualsTypeKeepAbbrevs (MakeConstraintSolverEnv ContextInfo.NoContext cenv.css m denv) 0 m NoTrace ty ty2 |> ignore +and solveTypAsError cenv denv m ty = ConstraintSolver.SolveTypeAsError denv cenv.css m ty and RecordNameAndTypeResolutions_IdeallyWithoutHavingOtherEffects cenv env tpenv expr = // This function is motivated by cases like @@ -5661,6 +5804,12 @@ and TcStmt cenv env tpenv synExpr = else mkCompGenSequential m expr (mkUnit cenv.g m), tpenv +and TryTcStmt cenv env tpenv synExpr = + let expr, ty, tpenv = TcExprOfUnknownType cenv env tpenv synExpr + let m = synExpr.Range + let hasTypeUnit = TryUnifyUnitTypeWithoutWarning cenv env m ty + hasTypeUnit, expr, tpenv + /// During checking of expressions of the form (x(y)).z(w1, w2) /// keep a stack of things on the right. This lets us recognize /// method applications and other item-based syntax. @@ -5671,22 +5820,22 @@ and TcExprThen cenv overallTy env tpenv synExpr delayed = if isOpt then errorR(Error(FSComp.SR.tcSyntaxErrorUnexpectedQMark(), mLongId)) // Check to see if pattern translation decided to use an alternative identifier. match altNameRefCellOpt with - | Some {contents = Decided altId} -> TcExprThen cenv overallTy env tpenv (SynExpr.LongIdent(isOpt, LongIdentWithDots([altId], []), None, mLongId)) delayed + | Some {contents = Decided altId} -> TcExprThen cenv overallTy env tpenv (SynExpr.LongIdent (isOpt, LongIdentWithDots([altId], []), None, mLongId)) delayed | _ -> TcLongIdentThen cenv overallTy env tpenv longId delayed // f x | SynExpr.App (hpa, _, func, arg, mFuncAndArg) -> - TcExprThen cenv overallTy env tpenv func ((DelayedApp (hpa, arg, mFuncAndArg)):: delayed) + TcExprThen cenv overallTy env tpenv func ((DelayedApp (hpa, arg, mFuncAndArg)) :: delayed) // e | SynExpr.TypeApp (func, _, typeArgs, _, _, mTypeArgs, mFuncAndTypeArgs) -> - TcExprThen cenv overallTy env tpenv func ((DelayedTypeApp (typeArgs, mTypeArgs, mFuncAndTypeArgs)):: delayed) + TcExprThen cenv overallTy env tpenv func ((DelayedTypeApp (typeArgs, mTypeArgs, mFuncAndTypeArgs)) :: delayed) // e1.id1 // e1.id1.id2 // etc. | SynExpr.DotGet (e1, _, LongIdentWithDots(longId, _), _) -> - TcExprThen cenv overallTy env tpenv e1 ((DelayedDotLookup (longId, synExpr.RangeSansAnyExtraDot))::delayed) + TcExprThen cenv overallTy env tpenv e1 ((DelayedDotLookup (longId, synExpr.RangeSansAnyExtraDot)) :: delayed) // e1.[e2] // e1.[e21, ..., e2n] @@ -5714,7 +5863,7 @@ and TcExprs cenv env m tpenv flexes argTys args = and CheckSuperInit cenv objTy m = // Check the type is not abstract - match tryDestAppTy cenv.g objTy with + match tryTcrefOfAppTy cenv.g objTy with | ValueSome tcref when isAbstractTycon tcref.Deref -> errorR(Error(FSComp.SR.tcAbstractTypeCannotBeInstantiated(), m)) | _ -> () @@ -5729,11 +5878,18 @@ and TcExprUndelayedNoType cenv env tpenv synExpr: Expr * TType * _ = expr, overallTy, tpenv and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = + + // LanguageFeatures.ImplicitYield do not require this validation + let implicitYieldEnabled = cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield + let validateObjectSequenceOrRecordExpression = not implicitYieldEnabled + let validateExpressionWithIfRequiresParenthesis = not implicitYieldEnabled + let acceptDeprecatedIfThenExpression = not implicitYieldEnabled + match synExpr with | SynExpr.Paren (expr2, _, _, mWholeExprIncludingParentheses) -> // We invoke CallExprHasTypeSink for every construct which is atomic in the syntax, i.e. where a '.' immediately following the // construct is a dot-lookup for the result of the construct. - CallExprHasTypeSink cenv.tcSink (mWholeExprIncludingParentheses, env.NameEnv, overallTy, env.DisplayEnv, env.eAccessRights) + CallExprHasTypeSink cenv.tcSink (mWholeExprIncludingParentheses, env.NameEnv, overallTy, env.AccessRights) let env = ShrinkContext env mWholeExprIncludingParentheses expr2.Range TcExpr cenv overallTy env tpenv expr2 @@ -5741,11 +5897,11 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = | SynExpr.TypeApp _ | SynExpr.Ident _ | SynExpr.LongIdent _ | SynExpr.App _ | SynExpr.DotGet _ -> error(Error(FSComp.SR.tcExprUndelayed(), synExpr.Range)) | SynExpr.Const (SynConst.String (s, m), _) -> - CallExprHasTypeSink cenv.tcSink (m, env.NameEnv, overallTy, env.DisplayEnv, env.eAccessRights) + CallExprHasTypeSink cenv.tcSink (m, env.NameEnv, overallTy, env.AccessRights) TcConstStringExpr cenv overallTy env m tpenv s | SynExpr.Const (synConst, m) -> - CallExprHasTypeSink cenv.tcSink (m, env.NameEnv, overallTy, env.DisplayEnv, env.eAccessRights) + CallExprHasTypeSink cenv.tcSink (m, env.NameEnv, overallTy, env.AccessRights) TcConstExpr cenv overallTy env m tpenv synConst | SynExpr.Lambda _ -> @@ -5803,9 +5959,9 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = // SynExpr.AddressOf is noted in the syntax ast in order to recognize it as concrete type information // during type checking, in particular prior to resolving overloads. This helps distinguish // its use at method calls from the use of the conflicting 'ref' mechanism for passing byref parameters - | SynExpr.AddressOf(byref, synInnerExpr, opm, m) -> + | SynExpr.AddressOf (byref, synInnerExpr, opm, m) -> TcExpr cenv overallTy env tpenv (mkSynPrefixPrim opm m (if byref then "~&" else "~&&") synInnerExpr) - + | SynExpr.Upcast (synInnerExpr, _, m) | SynExpr.InferredUpcast (synInnerExpr, m) -> let innerExpr, srcTy, tpenv = TcExprOfUnknownType cenv env tpenv synInnerExpr let tgtTy, tpenv = @@ -5821,7 +5977,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = let expr = mkCoerceExpr(innerExpr, tgtTy, m, srcTy) expr, tpenv - | SynExpr.Downcast(synInnerExpr, _, m) | SynExpr.InferredDowncast (synInnerExpr, m) -> + | SynExpr.Downcast (synInnerExpr, _, m) | SynExpr.InferredDowncast (synInnerExpr, m) -> let innerExpr, srcTy, tpenv = TcExprOfUnknownType cenv env tpenv synInnerExpr let tgtTy, tpenv, isOperator = match synExpr with @@ -5857,21 +6013,21 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = let expr = mkAnyTupled cenv.g m tupInfo args' argTys expr, tpenv - | SynExpr.AnonRecd (isStruct, optOrigExpr, unsortedArgs, mWholeExpr) -> - TcAnonRecdExpr cenv overallTy env tpenv (isStruct, optOrigExpr, unsortedArgs, mWholeExpr) + | SynExpr.AnonRecd (isStruct, optOrigExpr, unsortedFieldExprs, mWholeExpr) -> + TcAnonRecdExpr cenv overallTy env tpenv (isStruct, optOrigExpr, unsortedFieldExprs, mWholeExpr) | SynExpr.ArrayOrList (isArray, args, m) -> - CallExprHasTypeSink cenv.tcSink (m, env.NameEnv, overallTy, env.DisplayEnv, env.eAccessRights) + CallExprHasTypeSink cenv.tcSink (m, env.NameEnv, overallTy, env.AccessRights) let argty = NewInferenceType () - UnifyTypes cenv env m overallTy (if isArray then mkArrayType cenv.g argty else Tastops.mkListTy cenv.g argty) + UnifyTypes cenv env m overallTy (if isArray then mkArrayType cenv.g argty else mkListTy cenv.g argty) // Always allow subsumption if a nominal type is known prior to type checking any arguments let flex = not (isTyparTy cenv.g argty) - let first = ref true + let mutable first = true let getInitEnv m = - if !first then - first := false + if first then + first <- false env else { env with eContextInfo = ContextInfo.CollectionElement (isArray, m) } @@ -5879,7 +6035,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = let args', tpenv = List.mapFold (fun tpenv (x: SynExpr) -> TcExprFlex cenv flex false argty (getInitEnv x.Range) tpenv x) tpenv args let expr = - if isArray then Expr.Op(TOp.Array, [argty], args', m) + if isArray then Expr.Op (TOp.Array, [argty], args', m) else List.foldBack (mkCons cenv.g argty) args' (mkNil cenv.g m argty) expr, tpenv @@ -5888,12 +6044,12 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = UnifyTypes cenv env mNewExpr overallTy objTy TcNewExpr cenv env tpenv objTy (Some synObjTy.Range) superInit arg mNewExpr - | SynExpr.ObjExpr(objTy, argopt, binds, extraImpls, mNewExpr, m) -> - CallExprHasTypeSink cenv.tcSink (m, env.NameEnv, overallTy, env.DisplayEnv, env.eAccessRights) + | SynExpr.ObjExpr (objTy, argopt, binds, extraImpls, mNewExpr, m) -> + CallExprHasTypeSink cenv.tcSink (m, env.NameEnv, overallTy, env.eAccessRights) TcObjectExpr cenv overallTy env tpenv (objTy, argopt, binds, extraImpls, mNewExpr, m) | SynExpr.Record (inherits, optOrigExpr, flds, mWholeExpr) -> - CallExprHasTypeSink cenv.tcSink (mWholeExpr, env.NameEnv, overallTy, env.DisplayEnv, env.eAccessRights) + CallExprHasTypeSink cenv.tcSink (mWholeExpr, env.NameEnv, overallTy, env.AccessRights) TcRecdExpr cenv overallTy env tpenv (inherits, optOrigExpr, flds, mWholeExpr) | SynExpr.While (spWhile, synGuardExpr, synBodyExpr, m) -> @@ -5911,7 +6067,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = // notify name resolution sink about loop variable let item = Item.Value(mkLocalValRef idv) - CallNameResolutionSink cenv.tcSink (idv.Range, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Binding, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (idv.Range, env.NameEnv, item, emptyTyparInst, ItemOccurence.Binding, env.AccessRights) let bodyExpr, tpenv = TcStmt cenv envinner tpenv body mkFastForLoop cenv.g (spBind, m, idv, startExpr, dir, finishExpr, bodyExpr), tpenv @@ -5927,39 +6083,37 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = match comp with | SynExpr.New _ -> errorR(Error(FSComp.SR.tcInvalidObjectExpressionSyntaxForm(), m)) - | SimpleSemicolonSequence false _ -> + | SimpleSemicolonSequence cenv false _ when validateObjectSequenceOrRecordExpression -> errorR(Error(FSComp.SR.tcInvalidObjectSequenceOrRecordExpression(), m)) | _ -> () if not !isNotNakedRefCell && not cenv.g.compilingFslib then error(Error(FSComp.SR.tcInvalidSequenceExpressionSyntaxForm(), m)) - TcComputationOrSequenceExpression cenv env overallTy m None tpenv comp + TcSequenceExpression cenv env tpenv comp overallTy m | SynExpr.ArrayOrListOfSeqExpr (isArray, comp, m) -> - CallExprHasTypeSink cenv.tcSink (m, env.NameEnv, overallTy, env.DisplayEnv, env.eAccessRights) - + CallExprHasTypeSink cenv.tcSink (m, env.NameEnv, overallTy, env.eAccessRights) match comp with - | SynExpr.CompExpr(_, _, (SimpleSemicolonSequence true elems as body), _) -> - match body with - | SimpleSemicolonSequence false _ -> - () - | _ -> - errorR(Deprecated(FSComp.SR.tcExpressionWithIfRequiresParenthesis(), m)) + | SynExpr.CompExpr (_, _, (SimpleSemicolonSequence cenv acceptDeprecatedIfThenExpression elems as body), _) -> + match body 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), m), m) - else SynExpr.ArrayOrList(isArray, elems, m) + 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), m), m) + else SynExpr.ArrayOrList (isArray, elems, m) else if elems.Length > 500 then error(Error(FSComp.SR.tcListLiteralMaxSize(), m)) - SynExpr.ArrayOrList(isArray, elems, m) + SynExpr.ArrayOrList (isArray, elems, m) TcExprUndelayed cenv overallTy env tpenv replacementExpr | _ -> @@ -6001,7 +6155,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = | SynExpr.TryWith (synBodyExpr, _mTryToWith, synWithClauses, mWithToLast, mTryToLast, spTry, spWith) -> let bodyExpr, tpenv = TcExpr cenv overallTy env tpenv synBodyExpr // Compile the pattern twice, once as a List.filter with all succeeding targets returning "1", and once as a proper catch block. - let filterClauses = synWithClauses |> List.map (function (Clause(pat, optWhenExpr, _, m, _)) -> Clause(pat, optWhenExpr, (SynExpr.Const(SynConst.Int32 1, m)), m, SuppressSequencePointAtTarget)) + let filterClauses = synWithClauses |> List.map (function (Clause(pat, optWhenExpr, _, m, _)) -> Clause(pat, optWhenExpr, (SynExpr.Const (SynConst.Int32 1, m)), m, DebugPointForTarget.No)) let checkedFilterClauses, tpenv = TcMatchClauses cenv cenv.g.exn_ty cenv.g.int_ty env tpenv filterClauses let checkedHandlerClauses, tpenv = TcMatchClauses cenv cenv.g.exn_ty overallTy env tpenv synWithClauses let v1, filterExpr = CompilePatternForMatchClauses cenv env mWithToLast mWithToLast true FailFilter None cenv.g.exn_ty cenv.g.int_ty checkedFilterClauses @@ -6013,13 +6167,13 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = let finallyExpr, tpenv = TcStmt cenv env tpenv synFinallyExpr mkTryFinally cenv.g (bodyExpr, finallyExpr, mTryToLast, overallTy, spTry, spFinally), tpenv - | SynExpr.JoinIn(e1, mInToken, e2, mAll) -> + | SynExpr.JoinIn (e1, mInToken, e2, mAll) -> errorR(Error(FSComp.SR.parsUnfinishedExpression("in"), mInToken)) let _, _, tpenv = suppressErrorReporting (fun () -> TcExprOfUnknownType cenv env tpenv e1) let _, _, tpenv = suppressErrorReporting (fun () -> TcExprOfUnknownType cenv env tpenv e2) mkDefault(mAll, overallTy), tpenv - | SynExpr.ArbitraryAfterError(_debugStr, m) -> + | SynExpr.ArbitraryAfterError (_debugStr, m) -> //solveTypAsError cenv env.DisplayEnv m overallTy mkDefault(m, overallTy), tpenv @@ -6042,7 +6196,20 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = if (GetCtorShapeCounter env) <> 1 then errorR(Error(FSComp.SR.tcExpressionFormRequiresObjectConstructor(), m)) let expr2, tpenv = TcStmtThatCantBeCtorBody cenv env tpenv synExpr2 - Expr.Sequential(expr1, expr2, ThenDoSeq, sp, m), tpenv + Expr.Sequential (expr1, expr2, ThenDoSeq, sp, m), tpenv + + // Used to implement the type-directed 'implicit yield' rule for computation expressions + | SynExpr.SequentialOrImplicitYield (sp, synExpr1, synExpr2, otherExpr, m) -> + let isStmt, expr1, tpenv = TryTcStmt cenv env tpenv synExpr1 + if isStmt then + let env = ShrinkContext env m synExpr2.Range + let expr2, tpenv = TcExprThatCanBeCtorBody cenv overallTy env tpenv synExpr2 + Expr.Sequential(expr1, expr2, NormalSeq, sp, m), tpenv + else + // The first expression wasn't unit-typed, so proceed to the alternative interpretation + // Note a copy of the first expression is embedded in 'otherExpr' and thus + // this will type-check the first expression over again. + TcExpr cenv overallTy env tpenv otherExpr | SynExpr.Do (synInnerExpr, m) -> UnifyTypes cenv env m overallTy cenv.g.unit_ty @@ -6058,7 +6225,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = // This means uses of this construct have to be very carefully written let e2', _, tpenv = TcExprOfUnknownType cenv env tpenv e2 let e3', tpenv = TcExpr cenv overallTy env tpenv e3 - Expr.StaticOptimization(constraints', e2', e3', m), tpenv + Expr.StaticOptimization (constraints', e2', e3', m), tpenv /// e1.longId <- e2 | SynExpr.DotSet (e1, (LongIdentWithDots(longId, _) as lidwd), e2, mStmt) -> @@ -6099,13 +6266,14 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = else TcLongIdentThen cenv overallTy env tpenv lidwd [ DelayedApp(ExprAtomicFlag.Atomic, e1, mStmt); MakeDelayedSet(e2, mStmt) ] - | SynExpr.TraitCall(tps, memSpfn, arg, m) -> + | SynExpr.TraitCall (tps, memSpfn, arg, m) -> let synTypes = tps |> List.map (fun tp -> SynType.Var(tp, m)) - let (TTrait(_, logicalCompiledName, _, argTys, returnTy, _) as traitInfo), tpenv = TcPseudoMemberSpec cenv NewTyparsOK env synTypes tpenv memSpfn m - if BakedInTraitConstraintNames.Contains logicalCompiledName then - warning(BakedInMemberConstraintName(logicalCompiledName, m)) + let traitInfo, tpenv = TcPseudoMemberSpec cenv NewTyparsOK env synTypes tpenv memSpfn m + if BakedInTraitConstraintNames.Contains traitInfo.MemberName then + warning(BakedInMemberConstraintName(traitInfo.MemberName, m)) - let returnTy = GetFSharpViewOfReturnType cenv.g returnTy + let argTys = traitInfo.ArgumentTypes + let returnTy = GetFSharpViewOfReturnType cenv.g traitInfo.ReturnType let args, namedCallerArgs = GetMethodArgs arg if not (isNil namedCallerArgs) then errorR(Error(FSComp.SR.tcNamedArgumentsCannotBeUsedInMemberTraits(), m)) // Subsumption at trait calls if arguments have nominal type prior to unification of any arguments or return type @@ -6113,7 +6281,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = let args', tpenv = TcExprs cenv env m tpenv flexes argTys args AddCxMethodConstraint env.DisplayEnv cenv.css m NoTrace traitInfo UnifyTypes cenv env m overallTy returnTy - Expr.Op(TOp.TraitCall(traitInfo), [], args', m), tpenv + Expr.Op (TOp.TraitCall traitInfo, [], args', m), tpenv | SynExpr.LibraryOnlyUnionCaseFieldGet (e1, c, n, m) -> let e1', ty1, tpenv = TcExprOfUnknownType cenv env tpenv e1 @@ -6149,10 +6317,10 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = | [ returnTy ] -> returnTy | _ -> error(InternalError("Only zero or one pushed items are permitted in IL assembly code", m)) UnifyTypes cenv env m overallTy returnTy - mkAsmExpr(Array.toList s, tyargs', args', rtys', m), tpenv + mkAsmExpr (Array.toList s, tyargs', args', rtys', m), tpenv - | SynExpr.Quote(oper, raw, ast, isFromQueryExpression, m) -> - CallExprHasTypeSink cenv.tcSink (m, env.NameEnv, overallTy, env.DisplayEnv, env.eAccessRights) + | SynExpr.Quote (oper, raw, ast, isFromQueryExpression, m) -> + CallExprHasTypeSink cenv.tcSink (m, env.NameEnv, overallTy, env.AccessRights) TcQuotationExpr cenv overallTy env tpenv (oper, raw, ast, isFromQueryExpression, m) | SynExpr.YieldOrReturn ((isTrueYield, _), _, m) @@ -6169,7 +6337,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = error(Error(FSComp.SR.tcConstructRequiresSequenceOrComputations(), m)) | SynExpr.DoBang (_, m) - | SynExpr.LetOrUseBang (_, _, _, _, _, _, m) -> + | SynExpr.LetOrUseBang (range=m) -> error(Error(FSComp.SR.tcConstructRequiresComputationExpression(), m)) | SynExpr.MatchBang (_, _, _, m) -> @@ -6181,7 +6349,7 @@ and TcIteratedLambdas cenv isFirst (env: TcEnv) overallTy takenNames tpenv e = | SynExpr.Lambda (isMember, isSubsequent, spats, bodyExpr, m) when isMember || isFirst || isSubsequent -> let domainTy, resultTy = UnifyFunctionType None cenv env.DisplayEnv m overallTy let vs, (tpenv, names, takenNames) = TcSimplePats cenv isMember CheckCxs domainTy env (tpenv, Map.empty, takenNames) spats - let envinner, _, vspecMap = MakeAndPublishSimpleVals cenv env m names true + let envinner, _, vspecMap = MakeAndPublishSimpleValsForMergedScope cenv env m names let byrefs = vspecMap |> Map.map (fun _ v -> isByrefTy cenv.g v.Type, v) let envinner = if isMember then envinner else ExitFamilyRegion envinner let bodyExpr, tpenv = TcIteratedLambdas cenv false envinner resultTy takenNames tpenv bodyExpr @@ -6202,24 +6370,25 @@ and TcIteratedLambdas cenv isFirst (env: TcEnv) overallTy takenNames tpenv e = // .NET metadata. This means we manually typecheck 'e1' and look to see if it has a nominal type. We then // do the right thing in each case. and TcIndexerThen cenv env overallTy mWholeExpr mDot tpenv wholeExpr e1 indexArgs delayed = - let ad = env.eAccessRights + let ad = env.AccessRights let e1', e1ty, tpenv = TcExprOfUnknownType cenv env tpenv e1 // Find the first type in the effective hierarchy that either has a DefaultMember attribute OR // has a member called 'Item' + let isIndex = indexArgs |> List.forall( fun x -> match x with SynIndexerArg.One _ -> true | _ -> false) let propName = - match indexArgs with - | [SynIndexerArg.One _] -> + if isIndex then FoldPrimaryHierarchyOfType (fun ty acc -> match acc with | None -> - match tryDestAppTy cenv.g ty with + match tryTcrefOfAppTy cenv.g ty with | ValueSome tcref -> TryFindTyconRefStringAttribute cenv.g mWholeExpr cenv.g.attrib_DefaultMemberAttribute tcref | _ -> - match AllPropInfosOfTypeInScope cenv.infoReader env.NameEnv (Some "Item", ad) IgnoreOverrides mWholeExpr ty with + let item = Some "Item" + match AllPropInfosOfTypeInScope ResultCollectionSettings.AtMostOneResult cenv.infoReader env.NameEnv item ad IgnoreOverrides mWholeExpr ty with | [] -> None - | _ -> Some "Item" + | _ -> item | _ -> acc) cenv.g cenv.amap @@ -6227,7 +6396,7 @@ and TcIndexerThen cenv env overallTy mWholeExpr mDot tpenv wholeExpr e1 indexArg AllowMultiIntfInstantiations.Yes e1ty None - | _ -> Some "GetSlice" + else Some "GetSlice" let isNominal = isAppTy cenv.g e1ty @@ -6235,44 +6404,132 @@ and TcIndexerThen cenv env overallTy mWholeExpr mDot tpenv wholeExpr e1 indexArg let isString = typeEquiv cenv.g cenv.g.string_ty e1ty let idxRange = indexArgs |> List.map (fun e -> e.Range) |> List.reduce unionRanges - let GetIndexArgs (es: SynIndexerArg list) = [ for e in es do yield! e.Exprs ] - let MakeIndexParam vopt = - match indexArgs with - | [] -> failwith "unexpected empty index list" - | [SynIndexerArg.One h] -> SynExpr.Paren(h, range0, None, idxRange) - | _ -> SynExpr.Paren(SynExpr.Tuple(false, GetIndexArgs indexArgs @ Option.toList vopt, [], idxRange), range0, None, idxRange) + + // xs.GetReverseIndex rank offset - 1 + let rewriteReverseExpr (rank: int) (offset: SynExpr) (range: range) = + let rankExpr = SynExpr.Const(SynConst.Int32(rank), range) + let sliceArgs = SynExpr.Paren(SynExpr.Tuple(false, [rankExpr; offset], [], range), range, Some range, range) + let xsId = e1 + + mkSynApp1 + (mkSynDot range range xsId (mkSynId range "GetReverseIndex")) + sliceArgs + range + + let rewriteReverseOption (app: SynExpr) (rank: int) (range: range) = + match app with + | SynExpr.App(atomicFlag, isInfix, funcExpr, e1, outerRange) -> SynExpr.App(atomicFlag, isInfix, funcExpr, rewriteReverseExpr rank e1 range, outerRange) + | _ -> app + + let expandedIndexArgs = + indexArgs + |> List.mapi ( fun pos indexerArg -> + match indexerArg with + | SynIndexerArg.One(expr, fromEnd, range) -> + [ if fromEnd then rewriteReverseExpr pos expr range else expr ] + | SynIndexerArg.Two + ( + a1, + fromEnd1, + a2, + fromEnd2, + range1, + range2) -> + [ + if fromEnd1 then rewriteReverseOption a1 pos range1 else a1 ; + if fromEnd2 then rewriteReverseOption a2 pos range2 else a2 + ] + ) + |> List.collect (id) + + let MakeIndexParam setSliceArrayOption = + match indexArgs with + | [] -> failwith "unexpected empty index list" + | [SynIndexerArg.One _] -> SynExpr.Paren (expandedIndexArgs.Head, range0, None, idxRange) + | _ -> SynExpr.Paren (SynExpr.Tuple (false, expandedIndexArgs @ Option.toList setSliceArrayOption, [], idxRange), range0, None, idxRange) let attemptArrayString = - if isArray || isString then - - let indexOpPath = ["Microsoft";"FSharp";"Core";"LanguagePrimitives";"IntrinsicFunctions"] - let sliceOpPath = ["Microsoft";"FSharp";"Core";"Operators";"OperatorIntrinsics"] - let info = - match isString, isArray, wholeExpr with - | false, true, SynExpr.DotIndexedGet(_, [SynIndexerArg.One(SynExpr.Tuple (false, ([_;_] as idxs), _, _))], _, _) -> Some (indexOpPath, "GetArray2D", idxs) - | false, true, SynExpr.DotIndexedGet(_, [SynIndexerArg.One(SynExpr.Tuple (false, ([_;_;_] as idxs), _, _))], _, _) -> Some (indexOpPath, "GetArray3D", idxs) - | false, true, SynExpr.DotIndexedGet(_, [SynIndexerArg.One(SynExpr.Tuple (false, ([_;_;_;_] as idxs), _, _))], _, _) -> Some (indexOpPath, "GetArray4D", idxs) - | false, true, SynExpr.DotIndexedGet(_, [SynIndexerArg.One idx], _, _) -> Some (indexOpPath, "GetArray", [idx]) - | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.One(SynExpr.Tuple (false, ([_;_] as idxs), _, _))], e3, _, _, _) -> Some (indexOpPath, "SetArray2D", (idxs @ [e3])) - | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.One(SynExpr.Tuple (false, ([_;_;_] as idxs), _, _))], e3, _, _, _) -> Some (indexOpPath, "SetArray3D", (idxs @ [e3])) - | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.One(SynExpr.Tuple (false, ([_;_;_;_] as idxs), _, _))], e3, _, _, _) -> Some (indexOpPath, "SetArray4D", (idxs @ [e3])) - | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.One _], e3, _, _, _) -> Some (indexOpPath, "SetArray", (GetIndexArgs indexArgs @ [e3])) - | true, false, SynExpr.DotIndexedGet(_, [SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetStringSlice", GetIndexArgs indexArgs) - | true, false, SynExpr.DotIndexedGet(_, [SynIndexerArg.One _], _, _) -> Some (indexOpPath, "GetString", GetIndexArgs indexArgs) - | false, true, SynExpr.DotIndexedGet(_, [SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice", GetIndexArgs indexArgs) - | false, true, SynExpr.DotIndexedGet(_, [SynIndexerArg.One _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice2DFixed1", GetIndexArgs indexArgs) - | false, true, SynExpr.DotIndexedGet(_, [SynIndexerArg.Two _;SynIndexerArg.One _], _, _) -> Some (sliceOpPath, "GetArraySlice2DFixed2", GetIndexArgs indexArgs) - | false, true, SynExpr.DotIndexedGet(_, [SynIndexerArg.Two _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice2D", GetIndexArgs indexArgs) - | false, true, SynExpr.DotIndexedGet(_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice3D", GetIndexArgs indexArgs) - | false, true, SynExpr.DotIndexedGet(_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice4D", GetIndexArgs indexArgs) - | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice", (GetIndexArgs indexArgs @ [e3])) - | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.Two _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice2D", (GetIndexArgs indexArgs @ [e3])) - | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.One _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice2DFixed1", (GetIndexArgs indexArgs @ [e3])) - | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.Two _;SynIndexerArg.One _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice2DFixed2", (GetIndexArgs indexArgs @ [e3])) - | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice3D", (GetIndexArgs indexArgs @ [e3])) - | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4D", (GetIndexArgs indexArgs @ [e3])) - | _ -> None // error(Error(FSComp.SR.tcInvalidIndexerExpression(), mWholeExpr)) - match info with + let indexOpPath = ["Microsoft";"FSharp";"Core";"LanguagePrimitives";"IntrinsicFunctions"] + let sliceOpPath = ["Microsoft";"FSharp";"Core";"Operators";"OperatorIntrinsics"] + + let info = + if isArray then + let fixedIndex3d4dEnabled = cenv.g.langVersion.SupportsFeature LanguageFeature.FixedIndexSlice3d4d + match wholeExpr with + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _; SynIndexerArg.One _], _, _) -> Some (indexOpPath, "GetArray2D", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _; SynIndexerArg.One _; SynIndexerArg.One _;], _, _) -> Some (indexOpPath, "GetArray3D", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _; SynIndexerArg.One _; SynIndexerArg.One _; SynIndexerArg.One _], _, _) -> Some (indexOpPath, "GetArray4D", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _], _, _) -> Some (indexOpPath, "GetArray", expandedIndexArgs) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.One _; SynIndexerArg.One _], e3, _, _, _) -> Some (indexOpPath, "SetArray2D", (expandedIndexArgs @ [e3])) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.One _; SynIndexerArg.One _; SynIndexerArg.One _;], e3, _, _, _) -> Some (indexOpPath, "SetArray3D", (expandedIndexArgs @ [e3])) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.One _; SynIndexerArg.One _; SynIndexerArg.One _; SynIndexerArg.One _], e3, _, _, _) -> Some (indexOpPath, "SetArray4D", (expandedIndexArgs @ [e3])) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.One _], e3, _, _, _) -> Some (indexOpPath, "SetArray", (expandedIndexArgs @ [e3])) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice2DFixed1", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _;SynIndexerArg.One _], _, _) -> Some (sliceOpPath, "GetArraySlice2DFixed2", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice2D", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice3D", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice4D", expandedIndexArgs) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice", (expandedIndexArgs @ [e3])) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.Two _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice2D", (expandedIndexArgs @ [e3])) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.One _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice2DFixed1", (expandedIndexArgs @ [e3])) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.Two _;SynIndexerArg.One _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice2DFixed2", (expandedIndexArgs @ [e3])) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice3D", (expandedIndexArgs @ [e3])) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4D", (expandedIndexArgs @ [e3])) + | _ when fixedIndex3d4dEnabled -> + match wholeExpr with + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice3DFixedSingle1", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice3DFixedSingle2", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.One _], _, _) -> Some (sliceOpPath, "GetArraySlice3DFixedSingle3", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _;SynIndexerArg.One _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice3DFixedDouble1", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.One _], _, _) -> Some (sliceOpPath, "GetArraySlice3DFixedDouble2", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.One _], _, _) -> Some (sliceOpPath, "GetArraySlice3DFixedDouble3", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice4DFixedSingle1", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice4DFixedSingle2", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice4DFixedSingle3", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.One _], _, _) -> Some (sliceOpPath, "GetArraySlice4DFixedSingle4", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _;SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice4DFixedDouble1", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice4DFixedDouble2", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.One _], _, _) -> Some (sliceOpPath, "GetArraySlice4DFixedDouble3", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.One _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice4DFixedDouble4", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.One _], _, _) -> Some (sliceOpPath, "GetArraySlice4DFixedDouble5", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.One _], _, _) -> Some (sliceOpPath, "GetArraySlice4DFixedDouble6", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.One _;SynIndexerArg.One _], _, _) -> Some (sliceOpPath, "GetArraySlice4DFixedTriple1", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.One _], _, _) -> Some (sliceOpPath, "GetArraySlice4DFixedTriple2", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _;SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.One _], _, _) -> Some (sliceOpPath, "GetArraySlice4DFixedTriple3", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _;SynIndexerArg.One _;SynIndexerArg.One _;SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetArraySlice4DFixedTriple4", expandedIndexArgs) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice3DFixedSingle1", (expandedIndexArgs @ [e3])) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice3DFixedSingle2", (expandedIndexArgs @ [e3])) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.One _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice3DFixedSingle3", (expandedIndexArgs @ [e3])) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.One _;SynIndexerArg.One _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice3DFixedDouble1", (expandedIndexArgs @ [e3])) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.One _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice3DFixedDouble2", (expandedIndexArgs @ [e3])) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.One _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice3DFixedDouble3", (expandedIndexArgs @ [e3])) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4DFixedSingle1", expandedIndexArgs @ [e3]) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4DFixedSingle2", expandedIndexArgs @ [e3]) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4DFixedSingle3", expandedIndexArgs @ [e3]) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.One _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4DFixedSingle4", expandedIndexArgs @ [e3]) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.One _;SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4DFixedDouble1", expandedIndexArgs @ [e3]) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4DFixedDouble2", expandedIndexArgs @ [e3]) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.One _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4DFixedDouble3", expandedIndexArgs @ [e3]) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.One _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4DFixedDouble4", expandedIndexArgs @ [e3]) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.One _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4DFixedDouble5", expandedIndexArgs @ [e3]) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.Two _;SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.One _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4DFixedDouble6", expandedIndexArgs @ [e3]) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.One _;SynIndexerArg.One _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4DFixedTriple1", expandedIndexArgs @ [e3]) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.One _;SynIndexerArg.One _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4DFixedTriple2", expandedIndexArgs @ [e3]) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.One _;SynIndexerArg.One _;SynIndexerArg.Two _;SynIndexerArg.One _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4DFixedTriple3", expandedIndexArgs @ [e3]) + | SynExpr.DotIndexedSet (_, [SynIndexerArg.One _;SynIndexerArg.One _;SynIndexerArg.One _;SynIndexerArg.Two _], e3, _, _, _) -> Some (sliceOpPath, "SetArraySlice4DFixedTriple4", expandedIndexArgs @ [e3]) + | _ -> None + | _ -> None + + elif isString then + match wholeExpr with + | SynExpr.DotIndexedGet (_, [SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetStringSlice", expandedIndexArgs) + | SynExpr.DotIndexedGet (_, [SynIndexerArg.One _], _, _) -> Some (indexOpPath, "GetString", expandedIndexArgs) + | _ -> None + + else None + + match info with | None -> None | Some (path, functionName, indexArgs) -> let operPath = mkSynLidGet mDot path (CompileOpName functionName) @@ -6282,7 +6539,6 @@ and TcIndexerThen cenv env overallTy mWholeExpr mDot tpenv wholeExpr e1 indexArg let f', resultTy = buildApp cenv (MakeApplicableExprNoFlex cenv f) resultTy e1' mWholeExpr let delayed = List.foldBack (fun idx acc -> DelayedApp(ExprAtomicFlag.Atomic, idx, mWholeExpr) :: acc) indexArgs delayed // atomic, otherwise no ar.[1] <- xyz Some (PropagateThenTcDelayed cenv overallTy env tpenv mWholeExpr f' resultTy ExprAtomicFlag.Atomic delayed ) - else None match attemptArrayString with | Some res -> res @@ -6298,10 +6554,10 @@ and TcIndexerThen cenv env overallTy mWholeExpr mDot tpenv wholeExpr e1 indexArg | SynExpr.DotIndexedGet _ -> DelayedDotLookup([ident(nm, mWholeExpr)], mWholeExpr) :: DelayedApp(ExprAtomicFlag.Atomic, MakeIndexParam None, mWholeExpr) :: delayed // e1.[e2] <- e3 - | SynExpr.DotIndexedSet(_, _, e3, mOfLeftOfSet, _, _) -> - match indexArgs with - | [SynIndexerArg.One(_)] -> DelayedDotLookup([ident(nm, mOfLeftOfSet)], mOfLeftOfSet) :: DelayedApp(ExprAtomicFlag.Atomic, MakeIndexParam None, mOfLeftOfSet) :: MakeDelayedSet(e3, mWholeExpr) :: delayed - | _ -> DelayedDotLookup([ident("SetSlice", mOfLeftOfSet)], mOfLeftOfSet) :: DelayedApp(ExprAtomicFlag.Atomic, MakeIndexParam (Some e3), mWholeExpr) :: delayed + | SynExpr.DotIndexedSet (_, _, e3, mOfLeftOfSet, _, _) -> + match isIndex with + | true -> DelayedDotLookup([ident(nm, mOfLeftOfSet)], mOfLeftOfSet) :: DelayedApp(ExprAtomicFlag.Atomic, MakeIndexParam None, mOfLeftOfSet) :: MakeDelayedSet(e3, mWholeExpr) :: delayed + | false -> DelayedDotLookup([ident("SetSlice", mOfLeftOfSet)], mOfLeftOfSet) :: DelayedApp(ExprAtomicFlag.Atomic, MakeIndexParam (Some e3), mWholeExpr) :: delayed | _ -> error(InternalError("unreachable", mWholeExpr)) PropagateThenTcDelayed cenv overallTy env tpenv mDot (MakeApplicableExprNoFlex cenv e1') e1ty ExprAtomicFlag.Atomic delayed @@ -6316,7 +6572,7 @@ and TcIndexerThen cenv env overallTy mWholeExpr mDot tpenv wholeExpr e1 indexArg /// For 'inherit Type(args)', mWholeExprOrObjTy is the whole expression /// For an implicit inherit from System.Object or a default constructor, mWholeExprOrObjTy is the type name of the type being defined and TcNewExpr cenv env tpenv objTy mObjTyOpt superInit arg mWholeExprOrObjTy = - let ad = env.eAccessRights + let ad = env.AccessRights // Handle the case 'new 'a()' if (isTyparTy cenv.g objTy) then if superInit then error(Error(FSComp.SR.tcCannotInheritFromVariableType(), mWholeExprOrObjTy)) @@ -6335,7 +6591,7 @@ and TcNewExpr cenv env tpenv objTy mObjTyOpt superInit arg mWholeExprOrObjTy = /// Check an 'inheritedTys declaration in an implicit or explicit class and TcCtorCall isNaked cenv env tpenv overallTy objTy mObjTyOpt item superInit args mWholeCall delayed afterTcOverloadResolutionOpt = - let ad = env.eAccessRights + let ad = env.AccessRights let isSuperInit = (if superInit then CtorValUsedAsSuperInit else NormalValUse) let mItem = match mObjTyOpt with Some m -> m | None -> mWholeCall @@ -6364,7 +6620,7 @@ and TcCtorCall isNaked cenv env tpenv overallTy objTy mObjTyOpt item superInit a | Item.DelegateCtor ty, [arg] -> // Re-record the name resolution since we now know it's a constructor call match mObjTyOpt with - | Some mObjTy -> CallNameResolutionSink cenv.tcSink (mObjTy, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + | Some mObjTy -> CallNameResolutionSink cenv.tcSink (mObjTy, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.AccessRights) | None -> () TcNewDelegateThen cenv objTy env tpenv mItem mWholeCall ty arg ExprAtomicFlag.NonAtomic delayed @@ -6512,7 +6768,7 @@ and FreshenObjExprAbstractSlot cenv (env: TcEnv) (implty: TType) virtNameAndArit let _, synValInfo = GetNameAndArityOfObjExprBinding cenv env bind let arity = match SynInfo.AritiesOfArgs synValInfo with - | _::x::_ -> x + | _ :: x :: _ -> x | _ -> 0 match absSlotsByName with @@ -6522,15 +6778,14 @@ and FreshenObjExprAbstractSlot cenv (env: TcEnv) (implty: TType) virtNameAndArit tcref.MembersOfFSharpTyconByName |> Seq.exists (fun kv -> kv.Value |> List.exists (fun valRef -> valRef.DisplayName = bindName)) - let suggestVirtualMembers() = - virtNameAndArityPairs - |> List.map (fst >> fst) - |> HashSet + let suggestVirtualMembers (addToBuffer: string -> unit) = + for ((x,_),_) in virtNameAndArityPairs do + addToBuffer x if containsNonAbstractMemberWithSameName then errorR(ErrorWithSuggestions(FSComp.SR.tcMemberFoundIsNotAbstractOrVirtual(tcref.DisplayName, bindName), mBinding, bindName, suggestVirtualMembers)) else - errorR(ErrorWithSuggestions(FSComp.SR.tcNoAbstractOrVirtualMemberFound(bindName), mBinding, bindName, suggestVirtualMembers)) + errorR(ErrorWithSuggestions(FSComp.SR.tcNoAbstractOrVirtualMemberFound bindName, mBinding, bindName, suggestVirtualMembers)) | [(_, absSlot: MethInfo)] -> errorR(Error(FSComp.SR.tcArgumentArityMismatch(bindName, List.sum absSlot.NumArgs, arity, getSignature absSlot, getDetails absSlot), mBinding)) | (_, absSlot: MethInfo) :: _ -> @@ -6602,11 +6857,11 @@ and TcObjectExprBinding cenv (env: TcEnv) implty tpenv (absSlotInfo, bind) = | _ -> declaredTypars // Canonicalize constraints prior to generalization - GeneralizationHelpers.CanonicalizePartialInferenceProblem (cenv, denv, m) declaredTypars + ConstraintSolver.CanonicalizePartialInferenceProblem cenv.css denv m declaredTypars let freeInEnv = GeneralizationHelpers.ComputeUngeneralizableTypars env - let generalizedTypars = GeneralizationHelpers.ComputeAndGeneralizeGenericTypars(cenv, denv, m, freeInEnv, false, CanGeneralizeConstrainedTypars, inlineFlag, Some(rhsExpr), declaredTypars, [], bindingTy, false) + let generalizedTypars = GeneralizationHelpers.ComputeAndGeneralizeGenericTypars(cenv, denv, m, freeInEnv, false, CanGeneralizeConstrainedTypars, inlineFlag, Some rhsExpr, declaredTypars, [], bindingTy, false) let declaredTypars = ChooseCanonicalDeclaredTyparsAfterInference cenv.g env.DisplayEnv declaredTypars m let generalizedTypars = PlaceTyparsInDeclarationOrder declaredTypars generalizedTypars @@ -6618,7 +6873,7 @@ and TcObjectExprBinding cenv (env: TcEnv) implty tpenv (absSlotInfo, bind) = and ComputeObjectExprOverrides cenv (env: TcEnv) tpenv impls = // Compute the method sets each implemented type needs to implement - let slotImplSets = DispatchSlotChecking.GetSlotImplSets cenv.infoReader env.DisplayEnv true (impls |> List.map (fun (m, ty, _) -> ty, m)) + let slotImplSets = DispatchSlotChecking.GetSlotImplSets cenv.infoReader env.DisplayEnv env.AccessRights true (impls |> List.map (fun (m, ty, _) -> ty, m)) let allImpls = (impls, slotImplSets) ||> List.map2 (fun (m, ty, binds) implTySet -> @@ -6641,7 +6896,7 @@ and ComputeObjectExprOverrides cenv (env: TcEnv) tpenv impls = |> List.unzip // 2. collect all name/arity of all overrides - let dispatchSlots = reqdSlots |> List.map (fun (RequiredSlot(dispatchSlot, _)) -> dispatchSlot) + let dispatchSlots = reqdSlots |> List.map (fun reqdSlot -> reqdSlot.MethodInfo) let virtNameAndArityPairs = dispatchSlots |> List.map (fun virt -> let vkey = (virt.LogicalName, virt.NumArgs) //dprintfn "vkey = %A" vkey @@ -6693,10 +6948,10 @@ and TcObjectExpr cenv overallTy env tpenv (synObjTy, argopt, binds, extraImpls, let mObjTy = synObjTy.Range let objTy, tpenv = TcType cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv synObjTy - match tryDestAppTy cenv.g objTy with + match tryTcrefOfAppTy cenv.g objTy with | ValueNone -> error(Error(FSComp.SR.tcNewMustBeUsedWithNamedType(), mNewExpr)) | ValueSome tcref -> - let isRecordTy = isRecdTy cenv.g objTy + let isRecordTy = tcref.IsRecordTycon if not isRecordTy && not (isInterfaceTy cenv.g objTy) && isSealedTy cenv.g objTy then errorR(Error(FSComp.SR.tcCannotCreateExtensionOfSealedType(), mNewExpr)) CheckSuperType cenv objTy synObjTy.Range @@ -6706,7 +6961,7 @@ and TcObjectExpr cenv overallTy env tpenv (synObjTy, argopt, binds, extraImpls, // Object expression members can access protected members of the implemented type let env = EnterFamilyRegion tcref env - let ad = env.eAccessRights + let ad = env.AccessRights if // record construction ? isRecordTy || @@ -6748,11 +7003,11 @@ and TcObjectExpr cenv overallTy env tpenv (synObjTy, argopt, binds, extraImpls, | Item.CtorGroup(methodName, minfos), Some (arg, baseIdOpt) -> let meths = minfos |> List.map (fun minfo -> minfo, None) let afterResolution = ForNewConstructors cenv.tcSink env synObjTy.Range methodName minfos - let ad = env.eAccessRights + let ad = env.AccessRights let expr, tpenv = TcMethodApplicationThen cenv env objTy None tpenv None [] mWholeExpr mObjTy methodName ad PossiblyMutates false meths afterResolution CtorValUsedAsSuperInit [arg] ExprAtomicFlag.Atomic [] // The 'base' value is always bound - let baseIdOpt = (match baseIdOpt with None -> Some(ident("base", mObjTy)) | Some id -> Some(id)) + 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 @@ -6781,7 +7036,7 @@ and TcObjectExpr cenv overallTy env tpenv (synObjTy, argopt, binds, extraImpls, DispatchSlotChecking.CheckOverridesAreAllUsedOnce (env.DisplayEnv, cenv.g, cenv.amap, true, implty, dispatchSlotsKeyed, availPriorOverrides, overrideSpecs) - DispatchSlotChecking.CheckDispatchSlotsAreImplemented (env.DisplayEnv, cenv.g, cenv.amap, m, env.NameEnv, cenv.tcSink, false, implty, dispatchSlots, availPriorOverrides, overrideSpecs) |> ignore) + DispatchSlotChecking.CheckDispatchSlotsAreImplemented (env.DisplayEnv, cenv.infoReader, m, env.NameEnv, cenv.tcSink, false, implty, dispatchSlots, availPriorOverrides, overrideSpecs) |> ignore) // 6c. create the specs of overrides let allTypeImpls = @@ -6793,7 +7048,8 @@ and TcObjectExpr cenv overallTy env tpenv (synObjTy, argopt, binds, extraImpls, let searchForOverride = dispatchSlotsKeyed |> NameMultiMap.find id.idText - |> List.tryPick (fun (RequiredSlot(virt, _)) -> + |> List.tryPick (fun reqdSlot -> + let virt = reqdSlot.MethodInfo if DispatchSlotChecking.IsExactMatch cenv.g cenv.amap m virt ovinfo then Some virt else @@ -6804,7 +7060,7 @@ and TcObjectExpr cenv overallTy env tpenv (synObjTy, argopt, binds, extraImpls, | Some x -> x | None -> error(Error(FSComp.SR.tcAtLeastOneOverrideIsInvalid(), synObjTy.Range)) - yield TObjExprMethod(overridden.GetSlotSig(cenv.amap, m), bindingAttribs, mtps, [thisVal]::methodVars, bindingBody, id.idRange) ] + yield TObjExprMethod(overridden.GetSlotSig(cenv.amap, m), bindingAttribs, mtps, [thisVal] :: methodVars, bindingBody, id.idRange) ] (implty, overrides')) let (objTy', overrides') = allTypeImpls.Head @@ -6838,7 +7094,7 @@ and TcConstStringExpr cenv overallTy env m tpenv s = let formatStringCheckContext = match cenv.tcSink.CurrentSink with None -> None | Some sink -> sink.FormatStringCheckContext let normalizedString = (s.Replace("\r\n", "\n").Replace("\r", "\n")) - let (aty', ety'), specifierLocations = (try CheckFormatStrings.ParseFormatString m cenv.g formatStringCheckContext normalizedString bty cty dty with Failure s -> error (Error(FSComp.SR.tcUnableToParseFormatString(s), m))) + let (aty', ety'), specifierLocations = (try CheckFormatStrings.ParseFormatString m cenv.g formatStringCheckContext normalizedString bty cty dty with Failure s -> error (Error(FSComp.SR.tcUnableToParseFormatString s, m))) match cenv.tcSink.CurrentSink with | None -> () @@ -6864,38 +7120,38 @@ and TcConstExpr cenv overallTy env m tpenv c = // NOTE: these aren't "really" constants | SynConst.Bytes (bytes, m) -> UnifyTypes cenv env m overallTy (mkByteArrayTy cenv.g) - Expr.Op(TOp.Bytes bytes, [], [], m), tpenv + Expr.Op (TOp.Bytes bytes, [], [], m), tpenv | SynConst.UInt16s arr -> - UnifyTypes cenv env m overallTy (mkArrayType cenv.g cenv.g.uint16_ty); Expr.Op(TOp.UInt16s arr, [], [], m), tpenv + UnifyTypes cenv env m overallTy (mkArrayType cenv.g cenv.g.uint16_ty); Expr.Op (TOp.UInt16s arr, [], [], m), tpenv | SynConst.UserNum (s, suffix) -> let expr = let modName = "NumericLiteral" + suffix let ad = env.eAccessRights - match ResolveLongIndentAsModuleOrNamespace cenv.tcSink ResultCollectionSettings.AtMostOneResult cenv.amap m true OpenQualified env.eNameResEnv ad (ident (modName, m)) [] false with + match ResolveLongIndentAsModuleOrNamespaceOrStaticClass cenv.tcSink ResultCollectionSettings.AtMostOneResult cenv.amap m true true OpenQualified env.eNameResEnv ad (ident (modName, m)) [] false with | Result [] - | Exception _ -> error(Error(FSComp.SR.tcNumericLiteralRequiresModule(modName), m)) + | Exception _ -> error(Error(FSComp.SR.tcNumericLiteralRequiresModule modName, m)) | Result ((_, mref, _) :: _) -> let expr = try match int32 s with - | 0 -> SynExpr.App(ExprAtomicFlag.Atomic, false, mkSynLidGet m [modName] "FromZero", SynExpr.Const(SynConst.Unit, m), m) - | 1 -> SynExpr.App(ExprAtomicFlag.Atomic, false, mkSynLidGet m [modName] "FromOne", SynExpr.Const(SynConst.Unit, m), m) - | i32 -> SynExpr.App(ExprAtomicFlag.Atomic, false, mkSynLidGet m [modName] "FromInt32", SynExpr.Const(SynConst.Int32 i32, m), m) + | 0 -> SynExpr.App (ExprAtomicFlag.Atomic, false, mkSynLidGet m [modName] "FromZero", SynExpr.Const (SynConst.Unit, m), m) + | 1 -> SynExpr.App (ExprAtomicFlag.Atomic, false, mkSynLidGet m [modName] "FromOne", SynExpr.Const (SynConst.Unit, m), m) + | i32 -> SynExpr.App (ExprAtomicFlag.Atomic, false, mkSynLidGet m [modName] "FromInt32", SynExpr.Const (SynConst.Int32 i32, m), m) with _ -> try let i64 = int64 s - SynExpr.App(ExprAtomicFlag.Atomic, false, mkSynLidGet m [modName] "FromInt64", SynExpr.Const(SynConst.Int64 i64, m), m) + SynExpr.App (ExprAtomicFlag.Atomic, false, mkSynLidGet m [modName] "FromInt64", SynExpr.Const (SynConst.Int64 i64, m), m) with _ -> - SynExpr.App(ExprAtomicFlag.Atomic, false, mkSynLidGet m [modName] "FromString", SynExpr.Const(SynConst.String (s, m), m), m) + SynExpr.App (ExprAtomicFlag.Atomic, false, mkSynLidGet m [modName] "FromString", SynExpr.Const (SynConst.String (s, m), m), m) if suffix <> "I" then expr else match ccuOfTyconRef mref with | Some ccu when ccuEq ccu cenv.g.fslibCcu -> - SynExpr.Typed(expr, SynType.LongIdent(LongIdentWithDots(pathToSynLid m ["System";"Numerics";"BigInteger"], [])), m) + SynExpr.Typed (expr, SynType.LongIdent(LongIdentWithDots(pathToSynLid m ["System";"Numerics";"BigInteger"], [])), m) | _ -> expr @@ -6910,12 +7166,12 @@ and TcConstExpr cenv overallTy env m tpenv c = // TcAssertExpr //------------------------------------------------------------------------- -// Check an 'assert(x)' expression. +// Check an 'assert x' expression. and TcAssertExpr cenv overallTy env (m: range) tpenv x = let synm = m.MakeSynthetic() // Mark as synthetic so the language service won't pick it up. - let callDiagnosticsExpr = SynExpr.App(ExprAtomicFlag.Atomic, false, mkSynLidGet synm ["System";"Diagnostics";"Debug"] "Assert", + let callDiagnosticsExpr = SynExpr.App (ExprAtomicFlag.Atomic, false, mkSynLidGet synm ["System";"Diagnostics";"Debug"] "Assert", // wrap an extra parentheses so 'assert(x=1) isn't considered a named argument to a method call - SynExpr.Paren(x, range0, None, synm), synm) + SynExpr.Paren (x, range0, None, synm), synm) TcExpr cenv overallTy env tpenv callDiagnosticsExpr @@ -6925,7 +7181,7 @@ and TcRecdExpr cenv overallTy env tpenv (inherits, optOrigExpr, flds, mWholeExpr let requiresCtor = (GetCtorShapeCounter env = 1) // Get special expression forms for constructors let haveCtor = Option.isSome inherits - let optOrigExprInfo, tpenv = + let optOrigExpr, tpenv = match optOrigExpr with | None -> None, tpenv | Some (origExpr, _) -> @@ -6933,10 +7189,9 @@ and TcRecdExpr cenv overallTy env tpenv (inherits, optOrigExpr, flds, mWholeExpr | Some (_, _, mInherits, _, _) -> error(Error(FSComp.SR.tcInvalidRecordConstruction(), mInherits)) | None -> let olde, tpenv = TcExpr cenv overallTy env tpenv origExpr - let oldvaddr, oldvaddre = mkCompGenLocal mWholeExpr "inputRecord" (if isStructTy cenv.g overallTy then mkByrefTy cenv.g overallTy else overallTy) - Some (olde, oldvaddr, oldvaddre), tpenv + Some (olde), tpenv - let hasOrigExpr = optOrigExprInfo.IsSome + let hasOrigExpr = optOrigExpr.IsSome let fldsList = let flds = @@ -6955,7 +7210,7 @@ and TcRecdExpr cenv overallTy env tpenv (inherits, optOrigExpr, flds, mWholeExpr | [] -> [] | _ -> let tcref, _, fldsList = BuildFieldMap cenv env hasOrigExpr overallTy flds mWholeExpr - let _, _, _, gtyp = infoOfTyconRef mWholeExpr tcref + let _, _, _, gtyp = FreshenTyconRef2 mWholeExpr tcref UnifyTypes cenv env mWholeExpr overallTy gtyp [ for n, v in fldsList do @@ -6963,6 +7218,13 @@ and TcRecdExpr cenv overallTy env tpenv (inherits, optOrigExpr, flds, mWholeExpr | Some v -> yield n, v | None -> () ] + let optOrigExprInfo = + match optOrigExpr with + | None -> None + | Some(olde) -> + let oldvaddr, oldvaddre = mkCompGenLocal mWholeExpr "inputRecord" (if isStructTy cenv.g overallTy then mkByrefTy cenv.g overallTy else overallTy) + Some(olde, oldvaddr, oldvaddre) + if hasOrigExpr && not (isRecdTy cenv.g overallTy) then errorR(Error(FSComp.SR.tcExpressionFormRequiresRecordTypes(), mWholeExpr)) @@ -6984,7 +7246,7 @@ and TcRecdExpr cenv overallTy env tpenv (inherits, optOrigExpr, flds, mWholeExpr match inherits, GetSuperTypeOfType cenv.g cenv.amap mWholeExpr overallTy with | Some (superTy, arg, m, _, _), Some realSuperTy -> // Constructor expression, with an explicit 'inheritedTys clause. Check the inherits clause. - let e, tpenv = TcExpr cenv realSuperTy env tpenv (SynExpr.New(true, superTy, arg, m)) + let e, tpenv = TcExpr cenv realSuperTy env tpenv (SynExpr.New (true, superTy, arg, m)) Some e, tpenv | None, Some realSuperTy when requiresCtor -> // Constructor expression, No 'inherited' clause, hence look for a default constructor @@ -7007,26 +7269,39 @@ and TcRecdExpr cenv overallTy env tpenv (inherits, optOrigExpr, flds, mWholeExpr // Check '{| .... |}' -and TcAnonRecdExpr cenv overallTy env tpenv (isStruct, optOrigExpr, unsortedArgs, mWholeExpr) = +and TcAnonRecdExpr cenv overallTy env tpenv (isStruct, optOrigSynExpr, unsortedFieldIdsAndSynExprsGiven, mWholeExpr) = + let unsortedFieldSynExprsGiven = List.map snd unsortedFieldIdsAndSynExprsGiven - match optOrigExpr with + match optOrigSynExpr with | None -> - let unsortedIds = unsortedArgs |> List.map fst |> List.toArray - let anonInfo, sortedArgTys = UnifyAnonRecdTypeAndInferCharacteristics env.eContextInfo cenv env.DisplayEnv mWholeExpr overallTy isStruct unsortedIds + let unsortedFieldIds = unsortedFieldIdsAndSynExprsGiven |> List.map fst |> List.toArray + let anonInfo, sortedFieldTys = UnifyAnonRecdTypeAndInferCharacteristics env.eContextInfo cenv env.DisplayEnv mWholeExpr overallTy isStruct unsortedFieldIds // Sort into canonical order - let sortedIndexedArgs = unsortedArgs |> List.indexed |> List.sortBy (fun (i,_) -> unsortedIds.[i].idText) + let sortedIndexedArgs = + unsortedFieldIdsAndSynExprsGiven + |> List.indexed + |> List.sortBy (fun (i,_) -> unsortedFieldIds.[i].idText) + + // Map from sorted indexes to unsorted indexes let sigma = List.map fst sortedIndexedArgs |> List.toArray - let sortedArgs = List.map snd sortedIndexedArgs - sortedArgs |> List.iteri (fun j (x, _) -> - let item = Item.AnonRecdField(anonInfo, sortedArgTys, j, x.idRange) - CallNameResolutionSink cenv.tcSink (x.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights)) - let unsortedArgTys = sortedArgTys |> List.indexed |> List.sortBy (fun (j, _) -> sigma.[j]) |> List.map snd - let flexes = unsortedArgTys |> List.map (fun _ -> true) - let unsortedCheckedArgs, tpenv = TcExprs cenv env mWholeExpr tpenv flexes unsortedArgTys (List.map snd unsortedArgs) - let sortedCheckedArgs = unsortedCheckedArgs |> List.indexed |> List.sortBy (fun (i,_) -> unsortedIds.[i].idText) |> List.map snd + let sortedFieldExprs = List.map snd sortedIndexedArgs + + sortedFieldExprs |> List.iteri (fun j (x, _) -> + let item = Item.AnonRecdField(anonInfo, sortedFieldTys, j, x.idRange) + CallNameResolutionSink cenv.tcSink (x.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights)) + + let unsortedFieldTys = + sortedFieldTys + |> List.indexed + |> List.sortBy (fun (sortedIdx, _) -> sigma.[sortedIdx]) + |> List.map snd + + let flexes = unsortedFieldTys |> List.map (fun _ -> true) - mkAnonRecd cenv.g mWholeExpr anonInfo sortedCheckedArgs sortedArgTys, tpenv + let unsortedCheckedArgs, tpenv = TcExprs cenv env mWholeExpr tpenv flexes unsortedFieldTys unsortedFieldSynExprsGiven + + mkAnonRecd cenv.g mWholeExpr anonInfo unsortedFieldIds unsortedCheckedArgs unsortedFieldTys, tpenv | Some (origExpr, _) -> // The fairly complex case '{| origExpr with X = 1; Y = 2 |}' @@ -7059,59 +7334,107 @@ and TcAnonRecdExpr cenv overallTy env tpenv (isStruct, optOrigExpr, unsortedArgs /// - Choice1Of2 for a new binding /// - Choice2Of2 for a binding coming from the original expression let unsortedIdAndExprsAll = - [| for (id, e) in unsortedArgs do + [| for (id, e) in unsortedFieldIdsAndSynExprsGiven do yield (id, Choice1Of2 e) match tryDestAnonRecdTy cenv.g origExprTy with | ValueSome (anonInfo, tinst) -> for (i, id) in Array.indexed anonInfo.SortedIds do yield id, Choice2Of2 (mkAnonRecdFieldGetViaExprAddr (anonInfo, oldveaddr, tinst, i, mOrigExpr)) | ValueNone -> - if isRecdTy cenv.g origExprTy then - let tcref, tinst = destAppTy cenv.g origExprTy + match tryAppTy cenv.g origExprTy with + | ValueSome(tcref, tinst) when tcref.IsRecordTycon -> let fspecs = tcref.Deref.TrueInstanceFieldsAsList for fspec in fspecs do yield fspec.Id, Choice2Of2 (mkRecdFieldGetViaExprAddr (oldveaddr, tcref.MakeNestedRecdFieldRef fspec, tinst, mOrigExpr)) - else + | _ -> error (Error (FSComp.SR.tcCopyAndUpdateNeedsRecordType(), mOrigExpr)) |] |> Array.distinctBy (fst >> textOfId) - let unsortedIdsAll = Array.map fst unsortedIdAndExprsAll - let anonInfo, sortedArgTysAll = UnifyAnonRecdTypeAndInferCharacteristics env.eContextInfo cenv env.DisplayEnv mWholeExpr overallTy isStruct unsortedIdsAll - let sortedIndexedArgsAll = unsortedIdAndExprsAll |> Array.indexed |> Array.sortBy (snd >> fst >> textOfId) - let sigma = Array.map fst sortedIndexedArgsAll // map from sorted indexes to unsorted indexes - let sortedArgsAll = Array.map snd sortedIndexedArgsAll - sortedArgsAll |> Array.iteri (fun j (x, expr) -> + let unsortedFieldIdsAll = Array.map fst unsortedIdAndExprsAll + + let anonInfo, sortedFieldTysAll = UnifyAnonRecdTypeAndInferCharacteristics env.eContextInfo cenv env.DisplayEnv mWholeExpr overallTy isStruct unsortedFieldIdsAll + + let sortedIndexedFieldsAll = unsortedIdAndExprsAll |> Array.indexed |> Array.sortBy (snd >> fst >> textOfId) + + // map from sorted indexes to unsorted indexes + let sigma = Array.map fst sortedIndexedFieldsAll + + let sortedFieldsAll = Array.map snd sortedIndexedFieldsAll + + // Report _all_ identifiers to name resolution. We should likely just report the ones + // that are explicit in source code. + sortedFieldsAll |> Array.iteri (fun j (x, expr) -> match expr with | Choice1Of2 _ -> - let item = Item.AnonRecdField(anonInfo, sortedArgTysAll, j, x.idRange) - CallNameResolutionSink cenv.tcSink (x.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + let item = Item.AnonRecdField(anonInfo, sortedFieldTysAll, j, x.idRange) + CallNameResolutionSink cenv.tcSink (x.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) | Choice2Of2 _ -> ()) - let unsortedArgTysNew = sortedArgTysAll |> List.indexed |> List.sortBy (fun (j, _) -> sigma.[j]) |> List.take unsortedArgs.Length |> List.map snd - let flexes = unsortedArgTysNew |> List.map (fun _ -> true) + let unsortedFieldTysAll = + sortedFieldTysAll + |> List.indexed + |> List.sortBy (fun (sortedIdx, _) -> sigma.[sortedIdx]) + |> List.map snd + + let unsortedFieldTysGiven = + unsortedFieldTysAll + |> List.take unsortedFieldIdsAndSynExprsGiven.Length + + let flexes = unsortedFieldTysGiven |> List.map (fun _ -> true) + + // Check the expressions in unsorted order + let unsortedFieldExprsGiven, tpenv = + TcExprs cenv env mWholeExpr tpenv flexes unsortedFieldTysGiven unsortedFieldSynExprsGiven + + let unsortedFieldExprsGiven = unsortedFieldExprsGiven |> List.toArray + + let unsortedFieldIds = + unsortedIdAndExprsAll + |> Array.map fst - let unsortedCheckedArgsNew, tpenv = TcExprs cenv env mWholeExpr tpenv flexes unsortedArgTysNew (List.map snd unsortedArgs) - let sortedArgTysAllArray = Array.ofList sortedArgTysAll - let unsortedCheckedArgsNewArray = unsortedCheckedArgsNew |> List.toArray - let sortedCheckedArgsAll = - sortedArgsAll |> Array.mapi (fun j (_, expr) -> + let unsortedFieldExprs = + unsortedIdAndExprsAll + |> Array.mapi (fun unsortedIdx (_, expr) -> match expr with - | Choice1Of2 _ -> unsortedCheckedArgsNewArray.[sigma.[j]] - | Choice2Of2 subExpr -> UnifyTypes cenv env mOrigExpr (tyOfExpr cenv.g subExpr) sortedArgTysAllArray.[j]; subExpr) + | Choice1Of2 _ -> unsortedFieldExprsGiven.[unsortedIdx] + | Choice2Of2 subExpr -> UnifyTypes cenv env mOrigExpr (tyOfExpr cenv.g subExpr) unsortedFieldTysAll.[unsortedIdx]; subExpr) + |> List.ofArray - let expr = mkAnonRecd cenv.g mWholeExpr anonInfo (List.ofArray sortedCheckedArgsAll) sortedArgTysAll + // Permute the expressions to sorted order in the TAST + let expr = mkAnonRecd cenv.g mWholeExpr anonInfo unsortedFieldIds unsortedFieldExprs unsortedFieldTysAll let expr = wrap expr + + // Bind the original expression let expr = mkCompGenLet mOrigExpr oldv origExprChecked expr expr, tpenv and TcForEachExpr cenv overallTy env tpenv (pat, enumSynExpr, bodySynExpr, mWholeExpr, spForLoop) = + let tryGetOptimizeSpanMethodsAux g m ty isReadOnlySpan = + match (if isReadOnlySpan then tryDestReadOnlySpanTy g m ty else tryDestSpanTy g m ty) with + | ValueSome(struct(_, destTy)) -> + match TryFindFSharpSignatureInstanceGetterProperty cenv env m "Item" ty [ g.int32_ty; (if isReadOnlySpan then mkInByrefTy g destTy else mkByrefTy g destTy) ], + TryFindFSharpSignatureInstanceGetterProperty cenv env m "Length" ty [ g.int32_ty ] with + | Some(itemPropInfo), Some(lengthPropInfo) -> + ValueSome(struct(itemPropInfo.GetterMethod, lengthPropInfo.GetterMethod, isReadOnlySpan)) + | _ -> + ValueNone + | _ -> + ValueNone + + let tryGetOptimizeSpanMethods g m ty = + let result = tryGetOptimizeSpanMethodsAux g m ty false + if result.IsSome then + result + else + tryGetOptimizeSpanMethodsAux g m ty true + UnifyTypes cenv env mWholeExpr overallTy cenv.g.unit_ty let mPat = pat.Range //let mBodyExpr = bodySynExpr.Range let mEnumExpr = enumSynExpr.Range - let mForLoopStart = match spForLoop with SequencePointAtForLoop(mStart) -> mStart | NoSequencePointAtForLoop -> mEnumExpr + let mForLoopStart = match spForLoop with DebugPointAtFor.Yes mStart -> mStart | DebugPointAtFor.No -> mEnumExpr // Check the expression being enumerated let enumExpr, enumExprTy, tpenv = TcExprOfUnknownType cenv env tpenv enumSynExpr @@ -7121,7 +7444,7 @@ and TcForEachExpr cenv overallTy env tpenv (pat, enumSynExpr, bodySynExpr, mWhol match enumExpr with // optimize 'for i in n .. m do' - | Expr.App(Expr.Val(vf, _, _), _, [tyarg], [startExpr;finishExpr], _) + | Expr.App (Expr.Val (vf, _, _), _, [tyarg], [startExpr;finishExpr], _) when valRefEq cenv.g vf cenv.g.range_op_vref && typeEquiv cenv.g tyarg cenv.g.int_ty -> (cenv.g.int32_ty, (fun _ x -> x), id, Choice1Of3 (startExpr, finishExpr)) @@ -7130,7 +7453,7 @@ and TcForEachExpr cenv overallTy env tpenv (pat, enumSynExpr, bodySynExpr, mWhol let arrVar, arrExpr = mkCompGenLocal mEnumExpr "arr" enumExprTy let idxVar, idxExpr = mkCompGenLocal mPat "idx" cenv.g.int32_ty let elemTy = destArrayTy cenv.g enumExprTy - + // Evaluate the array index lookup let bodyExprFixup elemVar bodyExpr = mkCompGenLet mForLoopStart elemVar (mkLdelem cenv.g mForLoopStart elemTy arrExpr idxExpr) bodyExpr @@ -7139,13 +7462,37 @@ and TcForEachExpr cenv overallTy env tpenv (pat, enumSynExpr, bodySynExpr, mWhol // Ask for a loop over integers for the given range (elemTy, bodyExprFixup, overallExprFixup, Choice2Of3 (idxVar, mkZero cenv.g mForLoopStart, mkDecr cenv.g mForLoopStart (mkLdlen cenv.g mForLoopStart arrExpr))) - + | _ -> + // try optimize 'for i in span do' for span or readonlyspan + match tryGetOptimizeSpanMethods cenv.g mWholeExpr enumExprTy with + | ValueSome(struct(getItemMethInfo, getLengthMethInfo, isReadOnlySpan)) -> + let tcVal = LightweightTcValForUsingInBuildMethodCall cenv.g + let spanVar, spanExpr = mkCompGenLocal mEnumExpr "span" enumExprTy + let idxVar, idxExpr = mkCompGenLocal mPat "idx" cenv.g.int32_ty + let struct(_, elemTy) = if isReadOnlySpan then destReadOnlySpanTy cenv.g mWholeExpr enumExprTy else destSpanTy cenv.g mWholeExpr enumExprTy + let elemAddrTy = if isReadOnlySpan then mkInByrefTy cenv.g elemTy else mkByrefTy cenv.g elemTy + + // Evaluate the span index lookup + let bodyExprFixup elemVar bodyExpr = + let elemAddrVar, _ = mkCompGenLocal mForLoopStart "addr" elemAddrTy + let e = mkCompGenLet mForLoopStart elemVar (mkAddrGet mForLoopStart (mkLocalValRef elemAddrVar)) bodyExpr + let getItemCallExpr, _ = BuildMethodCall tcVal cenv.g cenv.amap PossiblyMutates mWholeExpr true getItemMethInfo ValUseFlag.NormalValUse [] [ spanExpr ] [ idxExpr ] + mkCompGenLet mForLoopStart elemAddrVar getItemCallExpr e + + // Evaluate the span expression once and put it in spanVar + let overallExprFixup overallExpr = mkCompGenLet mForLoopStart spanVar enumExpr overallExpr + + let getLengthCallExpr, _ = BuildMethodCall tcVal cenv.g cenv.amap PossiblyMutates mWholeExpr true getLengthMethInfo ValUseFlag.NormalValUse [] [ spanExpr ] [] + + // Ask for a loop over integers for the given range + (elemTy, bodyExprFixup, overallExprFixup, Choice2Of3 (idxVar, mkZero cenv.g mForLoopStart, mkDecr cenv.g mForLoopStart getLengthCallExpr)) - let enumerableVar, enumerableExprInVar = mkCompGenLocal mEnumExpr "inputSequence" enumExprTy - let enumeratorVar, enumeratorExpr, _, enumElemTy, getEnumExpr, getEnumTy, guardExpr, _, currentExpr = - AnalyzeArbitraryExprAsEnumerable cenv env true mEnumExpr enumExprTy enumerableExprInVar - (enumElemTy, (fun _ x -> x), id, Choice3Of3(enumerableVar, enumeratorVar, enumeratorExpr, getEnumExpr, getEnumTy, guardExpr, currentExpr)) + | _ -> + let enumerableVar, enumerableExprInVar = mkCompGenLocal mEnumExpr "inputSequence" enumExprTy + let enumeratorVar, enumeratorExpr, _, enumElemTy, getEnumExpr, getEnumTy, guardExpr, _, currentExpr = + AnalyzeArbitraryExprAsEnumerable cenv env true mEnumExpr enumExprTy enumerableExprInVar + (enumElemTy, (fun _ x -> x), id, Choice3Of3(enumerableVar, enumeratorVar, enumeratorExpr, getEnumExpr, getEnumTy, guardExpr, currentExpr)) let pat, _, vspecs, envinner, tpenv = TcMatchPattern cenv enumElemTy env tpenv (pat, None) let elemVar, pat = @@ -7165,7 +7512,7 @@ and TcForEachExpr cenv overallTy env tpenv (pat, enumSynExpr, bodySynExpr, mWhol let valsDefinedByMatching = ListSet.remove valEq elemVar vspecs CompilePatternForMatch cenv env enumSynExpr.Range pat.Range false IgnoreWithWarning (elemVar, [], None) - [TClause(pat, None, TTarget(valsDefinedByMatching, bodyExpr, SequencePointAtTarget), mForLoopStart)] + [TClause(pat, None, TTarget(valsDefinedByMatching, bodyExpr, DebugPointForTarget.Yes), mForLoopStart)] enumElemTy overallTy @@ -7191,15 +7538,15 @@ and TcForEachExpr cenv overallTy env tpenv (pat, enumSynExpr, bodySynExpr, mWhol // This compiled for must be matched EXACTLY by CompiledForEachExpr in opt.fs and creflect.fs mkCompGenLet mForLoopStart enumerableVar enumExpr (let cleanupE = BuildDisposableCleanup cenv env mWholeExpr enumeratorVar - let spBind = match spForLoop with SequencePointAtForLoop(spStart) -> SequencePointAtBinding(spStart) | NoSequencePointAtForLoop -> NoSequencePointAtStickyBinding + let spBind = match spForLoop with DebugPointAtFor.Yes spStart -> DebugPointAtBinding spStart | DebugPointAtFor.No -> NoDebugPointAtStickyBinding (mkLet spBind mForLoopStart enumeratorVar getEnumExpr (mkTryFinally cenv.g (mkWhile cenv.g - (NoSequencePointAtWhileLoop, + (DebugPointAtWhile.No, WhileLoopForCompiledForEachExprMarker, guardExpr, mkCompGenLet mForLoopStart elemVar currentExpr bodyExpr, mForLoopStart), - cleanupE, mForLoopStart, cenv.g.unit_ty, NoSequencePointAtTry, NoSequencePointAtFinally)))) + cleanupE, mForLoopStart, cenv.g.unit_ty, DebugPointAtTry.No, DebugPointAtFinally.No)))) let overallExpr = overallExprFixup overallExpr overallExpr, tpenv @@ -7218,7 +7565,7 @@ and TcQuotationExpr cenv overallTy env tpenv (_oper, raw, ast, isFromQueryExpres let expr, tpenv = TcExpr cenv astTy env tpenv ast // Wrap the expression - let expr = Expr.Quote(expr, ref None, isFromQueryExpression, m, overallTy) + let expr = Expr.Quote (expr, ref None, isFromQueryExpression, m, overallTy) // Coerce it if needed let expr = if raw then mkCoerceExpr(expr, (mkRawQuotedExprTy cenv.g), m, (tyOfExpr cenv.g expr)) else expr @@ -7226,24 +7573,13 @@ and TcQuotationExpr cenv overallTy env tpenv (_oper, raw, ast, isFromQueryExpres // We serialize the quoted expression to bytes in IlxGen after type inference etc. is complete. expr, tpenv -//------------------------------------------------------------------------- -// TcComputationOrSequenceExpression -//------------------------------------------------------------------------- - -and TcComputationOrSequenceExpression cenv (env: TcEnv) overallTy m interpValOpt tpenv comp = - match interpValOpt with - | Some (interpExpr: Expr, builderTy) -> - TcComputationExpression cenv env overallTy m interpExpr builderTy tpenv comp - | None -> - TcSequenceExpression cenv env tpenv comp overallTy m - /// Ignores an attribute and IgnoreAttribute _ = None -// Used for all computation expressions except sequence expressions -and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv comp = +/// Used for all computation expressions except sequence expressions +and TcComputationExpression cenv env overallTy mWhole (interpExpr: Expr) builderTy tpenv (comp: SynExpr) = - //dprintfn "TcComputationOrSequenceExpression, comp = \n%A\n-------------------\n" comp + //dprintfn "TcComputationExpression, comp = \n%A\n-------------------\n" comp let ad = env.eAccessRights let mkSynDelay2 (e: SynExpr) = mkSynDelay (e.Range.MakeSynthetic()) e @@ -7254,9 +7590,9 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv // Give bespoke error messages for the FSharp.Core "query" builder let isQuery = match interpExpr with - | Expr.Val(vf, _, m) -> + | Expr.Val (vf, _, m) -> let item = Item.CustomBuilder (vf.DisplayName, vf) - CallNameResolutionSink cenv.tcSink (m, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (m, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) valRefEq cenv.g vf cenv.g.query_value_vref | _ -> false @@ -7265,29 +7601,31 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv 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) + | [] -> 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, LongIdentWithDots([mkSynId m nm], []), m)) args m + mkSynApp1 (SynExpr.DotGet (builderVal, range0, LongIdentWithDots([mkSynId m nm], []), m)) args m + + 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 cenv env mBuilderVal ad "Source" builderTy // Optionally wrap sources of "let!", "yield!", "use!" in "query.Source" let mkSourceExpr callExpr = match sourceMethInfo with | [] -> callExpr | _ -> mkSynCall "Source" callExpr.Range [callExpr] + let mkSourceExprConditional isFromSource callExpr = + if isFromSource then mkSourceExpr callExpr else callExpr /// Decide if the builder is an auto-quote builder - let isAutoQuote = - match TryFindIntrinsicOrExtensionMethInfo cenv env mBuilderVal ad "Quote" builderTy with - | [] -> false - | _ -> true + let isAutoQuote = hasMethInfo "Quote" let customOperationMethods = - AllMethInfosOfTypeInScope cenv.infoReader env.NameEnv (None, ad) IgnoreOverrides mBuilderVal builderTy + 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 = @@ -7345,7 +7683,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv | true, [_] -> () | _ -> errorR(Error(FSComp.SR.tcCustomOperationMayNotBeOverloaded nm.idText, nm.idRange)) Some opData - | 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 @@ -7442,10 +7780,9 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let (_, argInfo) = List.item i argInfos HasFSharpAttribute cenv.g cenv.g.attrib_ProjectionParameterAttribute argInfo.Attribs - let (|ForEachThen|_|) e = match e with - | SynExpr.ForEach (_spBind, SeqExprOnly false, isFromSource, pat1, expr1, SynExpr.Sequential(_, true, clause, rest, _), _) -> Some (isFromSource, pat1, expr1, clause, rest) + | SynExpr.ForEach (_spBind, SeqExprOnly false, isFromSource, pat1, expr1, SynExpr.Sequential (_, true, clause, rest, _), _) -> Some (isFromSource, pat1, expr1, clause, rest) | _ -> None let (|CustomOpId|_|) predicate e = @@ -7456,7 +7793,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv // e1 in e2 ('in' is parsed as 'JOIN_IN') let (|InExpr|_|) (e: SynExpr) = match e with - | SynExpr.JoinIn(e1, _, e2, mApp) -> Some (e1, e2, mApp) + | SynExpr.JoinIn (e1, _, e2, mApp) -> Some (e1, e2, mApp) | _ -> None // e1 on e2 (note: 'on' is the 'JoinConditionWord') @@ -7465,16 +7802,16 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv | None -> None | Some _ -> match e with - | SynExpr.App(_, _, SynExpr.App(_, _, e1, SingleIdent opName, _), e2, _) when opName.idText = customOperationJoinConditionWord nm -> + | SynExpr.App (_, _, SynExpr.App (_, _, e1, SingleIdent opName, _), e2, _) when opName.idText = customOperationJoinConditionWord nm -> let item = Item.CustomOperation (opName.idText, (fun () -> None), None) - CallNameResolutionSink cenv.tcSink (opName.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (opName.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.AccessRights) 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 -> + | SynExpr.App (_, _, SynExpr.App (_, _, x, SingleIdent nm2, _), ExprAsPat intoPat, _) when nm2.idText = CustomOperations.Into -> Some (x, nm2.idRange, intoPat) | _ -> None @@ -7486,7 +7823,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv | IntoSuffix (x, intoWordRange, intoPat) -> // record the "into" as a custom operation for colorization let item = Item.CustomOperation ("into", (fun () -> None), None) - CallNameResolutionSink cenv.tcSink (intoWordRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (intoWordRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) (x, intoPat, alreadyGivenError) | _ -> if not alreadyGivenError then @@ -7505,10 +7842,10 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let JoinOrGroupJoinOp detector e = match e with - | SynExpr.App(_, _, CustomOpId detector nm, ExprAsPat innerSourcePat, mJoinCore) -> + | 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) -> + | 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) @@ -7561,7 +7898,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv Some(nm, innerSourcePat, innerSource, Some keySelectors, Some intoPat, mGroupJoinCore) // zip intoPat in secondSource - | InExpr (SynExpr.App(_, _, CustomOpId customOperationIsLikeZip nm, ExprAsPat secondSourcePat, _), secondSource, mZipCore) -> + | InExpr (SynExpr.App (_, _, CustomOpId customOperationIsLikeZip nm, ExprAsPat secondSourcePat, _), secondSource, mZipCore) -> Some(nm, secondSourcePat, secondSource, None, None, mZipCore) // zip (without secondSource or in - gives error) @@ -7570,7 +7907,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv Some(nm, arbPat e.Range, arbExpr("_secondSource", e.Range), None, None, e.Range) // zip secondSource (without in - gives error) - | SynExpr.App(_, _, CustomOpId customOperationIsLikeZip nm, ExprAsPat secondSourcePat, 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", e.Range), None, None, mZipCore) @@ -7595,14 +7932,13 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv | _ -> None - let (|StripApps|) e = let rec strip e = match e with - | SynExpr.FromParseError(SynExpr.App(_, _, f, arg, _), _) - | SynExpr.App(_, _, f, arg, _) -> + | SynExpr.FromParseError (SynExpr.App (_, _, f, arg, _), _) + | SynExpr.App (_, _, f, arg, _) -> let g, acc = strip f - g, (arg::acc) + g, (arg :: acc) | _ -> e, [] let g, acc = strip e g, List.rev acc @@ -7620,20 +7956,20 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv match optInto with | Some (intoWordRange, optInfo) -> let item = Item.CustomOperation ("into", (fun () -> None), None) - CallNameResolutionSink cenv.tcSink (intoWordRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (intoWordRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) Some optInfo | None -> None Some (nm, Option.get (tryGetDataForCustomOperation nm), core, core.Range, optIntoInfo) | _ -> None - let mkSynLambda p e m = SynExpr.Lambda(false, false, p, e, m) + let mkSynLambda p e m = SynExpr.Lambda (false, false, p, e, m) let mkExprForVarSpace m (patvs: Val list) = match patvs with - | [] -> SynExpr.Const(SynConst.Unit, m) + | [] -> SynExpr.Const (SynConst.Unit, m) | [v] -> SynExpr.Ident v.Id - | vs -> SynExpr.Tuple(false, (vs |> List.map (fun v -> SynExpr.Ident v.Id)), [], m) + | vs -> SynExpr.Tuple (false, (vs |> List.map (fun v -> SynExpr.Ident v.Id)), [], m) let mkSimplePatForVarSpace m (patvs: Val list) = let spats = @@ -7651,9 +7987,23 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let (|OptionalSequential|) e = match e with - | SynExpr.Sequential(_sp, true, dataComp1, dataComp2, _) -> (dataComp1, Some dataComp2) + | 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 = + match innerComp1 with + | SynExpr.IfThenElse (_, _, _, _, _, mIfToThen, _m) -> mIfToThen + | SynExpr.Match (DebugPointAtBinding mMatch, _, _, _) -> mMatch + | SynExpr.TryWith (_, _, _, _, _, DebugPointAtTry.Yes mTry, _) -> mTry + | SynExpr.TryFinally (_, _, _, DebugPointAtTry.Yes mTry, _) -> mTry + | SynExpr.For (DebugPointAtFor.Yes mBind, _, _, _, _, _, _) -> mBind + | SynExpr.ForEach (DebugPointAtFor.Yes mBind, _, _, _, _, _, _) -> mBind + | SynExpr.While (DebugPointAtWhile.Yes mWhile, _, _, _) -> mWhile + | _ -> innerComp1.Range + // 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 @@ -7664,7 +8014,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv 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 + | SynExpr.Tuple (false, (StripApps(SingleIdent nm2, args) :: _), _, m) when expectedArgCountForCustomOperator nm2 > 0 && not (List.isEmpty args) -> let estimatedRangeOfIntendedLeftAndRightArguments = unionRanges (List.last args).Range m.EndRange @@ -7684,6 +8034,13 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv 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 @@ -7714,7 +8071,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv if not q then error(Error(FSComp.SR.tcCustomOperationMayNotBeUsedHere(), nm.idRange)) - let firstSource = if isFromSource then mkSourceExpr firstSource else firstSource + let firstSource = mkSourceExprConditional isFromSource firstSource let secondSource = mkSourceExpr secondSource // Add the variables to the variable space, on demand @@ -7755,7 +8112,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv // 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, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (nm.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) let mkJoinExpr keySelector1 keySelector2 innerPat e = let mSynthetic = mOpCore.MakeSynthetic() @@ -7774,7 +8131,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv (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(...) + // 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 @@ -7787,7 +8144,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv // 2. incompatible types: int and string // with SynExpr.ArbitraryAfterError we have only first one let wrapInArbErrSequence l caption = - SynExpr.Sequential(SequencePointInfoForSeq.SequencePointsAtSeq, true, l, (arbExpr(caption, l.Range.EndRange)), l.Range) + SynExpr.Sequential (DebugPointAtSequential.Both, true, l, (arbExpr(caption, l.Range.EndRange)), l.Range) let mkOverallExprGivenVarSpaceExpr, varSpaceInner = let isNullableOp opId = @@ -7854,15 +8211,16 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let varSpaceExpr = mkExprForVarSpace mOpCore valsInner let varSpacePat = mkPatForVarSpace mOpCore valsInner let joinExpr = mkOverallExprGivenVarSpaceExpr varSpaceExpr - Some (trans true q varSpaceInner (SynExpr.ForEach (NoSequencePointAtForLoop, SeqExprOnly false, false, varSpacePat, joinExpr, innerComp, mOpCore)) translatedCtxt) + Some (trans true q varSpaceInner (SynExpr.ForEach (DebugPointAtFor.No, SeqExprOnly false, false, varSpacePat, joinExpr, innerComp, mOpCore)) translatedCtxt) | SynExpr.ForEach (spForLoop, SeqExprOnly _seqExprOnly, isFromSource, pat, sourceExpr, innerComp, _) -> - let wrappedSourceExpr = if isFromSource then mkSourceExpr sourceExpr else sourceExpr - let mFor = match spForLoop with SequencePointAtForLoop(m) -> m | _ -> pat.Range + let wrappedSourceExpr = mkSourceExprConditional isFromSource sourceExpr + let mFor = match spForLoop with DebugPointAtFor.Yes m -> m | _ -> pat.Range let mPat = pat.Range - let spBind = match spForLoop with SequencePointAtForLoop(m) -> SequencePointAtBinding(m) | NoSequencePointAtForLoop -> NoSequencePointAtStickyBinding - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env mFor ad "For" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("For"), mFor)) + let spBind = match spForLoop with DebugPointAtFor.Yes m -> DebugPointAtBinding m | DebugPointAtFor.No -> NoDebugPointAtStickyBinding + if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mFor ad "For" builderTy) then + error(Error(FSComp.SR.tcRequireBuilderMethod("For"), mFor)) // Add the variables to the query variable space, on demand let varSpace = @@ -7873,34 +8231,38 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv Some (trans true q varSpace innerComp (fun holeFill -> - translatedCtxt (mkSynCall "For" mFor [wrappedSourceExpr; SynExpr.MatchLambda(false, sourceExpr.Range, [Clause(pat, None, holeFill, mPat, SequencePointAtTarget)], spBind, mFor) ])) ) + translatedCtxt (mkSynCall "For" mFor [wrappedSourceExpr; SynExpr.MatchLambda (false, sourceExpr.Range, [Clause(pat, None, holeFill, mPat, DebugPointForTarget.Yes)], spBind, mFor) ])) ) | SynExpr.For (spBind, id, start, dir, finish, innerComp, m) -> - let mFor = match spBind with SequencePointAtForLoop m -> m | _ -> m + let mFor = match spBind with DebugPointAtFor.Yes m -> m | _ -> m if isQuery then errorR(Error(FSComp.SR.tcNoIntegerForLoopInQuery(), mFor)) Some (trans true q varSpace (elimFastIntegerForLoop (spBind, id, start, dir, finish, innerComp, m)) translatedCtxt ) | SynExpr.While (spWhile, guardExpr, innerComp, _) -> let mGuard = guardExpr.Range - let mWhile = match spWhile with SequencePointAtWhileLoop(m) -> m | _ -> mGuard + let mWhile = match spWhile with DebugPointAtWhile.Yes m -> m | _ -> mGuard if isQuery then error(Error(FSComp.SR.tcNoWhileInQuery(), mWhile)) - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env mWhile ad "While" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("While"), mWhile)) - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env mWhile ad "Delay" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Delay"), 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)) Some(trans true q varSpace innerComp (fun holeFill -> translatedCtxt (mkSynCall "While" mWhile [mkSynDelay2 guardExpr; mkSynCall "Delay" mWhile [mkSynDelay innerComp.Range holeFill]])) ) | SynExpr.TryFinally (innerComp, unwindExpr, mTryToLast, spTry, _spFinally) -> - let mTry = match spTry with SequencePointAtTry(m) -> m | _ -> mTryToLast + let mTry = match spTry with DebugPointAtTry.Yes m -> m | _ -> mTryToLast if isQuery then error(Error(FSComp.SR.tcNoTryFinallyInQuery(), mTry)) - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env mTry ad "TryFinally" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("TryFinally"), mTry)) - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env mTry ad "Delay" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Delay"), 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)) Some (translatedCtxt (mkSynCall "TryFinally" mTry [mkSynCall "Delay" mTry [mkSynDelay innerComp.Range (transNoQueryOps innerComp)]; mkSynDelay2 unwindExpr])) | SynExpr.Paren (_, _, _, m) -> error(Error(FSComp.SR.tcConstructIsAmbiguousInComputationExpression(), m)) | SynExpr.ImplicitZero m -> - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env m ad "Zero" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Zero"), m)) + if 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), _) @@ -7912,11 +8274,11 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let varSpacePat = mkPatForVarSpace mClause patvs let dataCompPrior = - translatedCtxt (transNoQueryOps (SynExpr.YieldOrReturn((true, false), varSpaceExpr, mClause))) + translatedCtxt (transNoQueryOps (SynExpr.YieldOrReturn ((true, false), varSpaceExpr, mClause))) // Rebind using for ... let rebind = - SynExpr.ForEach (NoSequencePointAtForLoop, SeqExprOnly false, false, varSpacePat, dataCompPrior, comp, comp.Range) + SynExpr.ForEach (DebugPointAtFor.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 false q varSpace rebind id @@ -7931,108 +8293,13 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let dataCompPriorToOp = let isYield = not (customOperationMaintainsVarSpaceUsingBind nm) - translatedCtxt (transNoQueryOps (SynExpr.YieldOrReturn((isYield, false), varSpaceExpr, mClause))) + translatedCtxt (transNoQueryOps (SynExpr.YieldOrReturn ((isYield, false), varSpaceExpr, mClause))) - let rec consumeClauses (varSpace: LazyWithContext<_, _>) dataCompPrior compClausesExpr lastUsesBind = - // Substitute 'yield ' into the context + // Now run the consumeCustomOpClauses + Some (consumeCustomOpClauses q varSpace dataCompPriorToOp comp false mClause) - let patvs, _env = varSpace.Force comp.Range - let varSpaceSimplePat = mkSimplePatForVarSpace mClause patvs - let varSpacePat = mkPatForVarSpace mClause patvs - - match compClausesExpr with - - // Detect one custom operation... This clause will always match at least once... - | OptionalSequential (CustomOperationClause (nm, (opName, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, isLikeZip, isLikeJoin, isLikeGroupJoin, _, methInfo), opExpr, mClause, optionalIntoPat), optionalCont) -> - - // 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, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) - - if isLikeZip || isLikeJoin || isLikeGroupJoin then - 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_IdeallyWithoutHavingOtherEffects cenv env tpenv opExpr - dataCompPrior - | Some contExpr -> consumeClauses varSpace dataCompPrior contExpr lastUsesBind - else - - let maintainsVarSpace = customOperationMaintainsVarSpace nm - let maintainsVarSpaceUsingBind = customOperationMaintainsVarSpaceUsingBind nm - - let expectedArgCount = expectedArgCountForCustomOperator nm - - let dataCompAfterOp = - match opExpr with - | StripApps(SingleIdent nm, args) -> - if args.Length = expectedArgCount 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, arg.Range.MakeSynthetic()) else arg) - mkSynCall methInfo.DisplayName mClause (dataCompPrior :: args) - else - 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)) - | 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(NoSequencePointAtLetBinding, false, false, intoPat, dataCompAfterOp, contExpr, intoPat.Range) - else - SynExpr.ForEach (NoSequencePointAtForLoop, SeqExprOnly false, false, intoPat, dataCompAfterOp, contExpr, intoPat.Range) - - trans true q emptyVarSpace rebind id - - // select a.Name; ... - // distinct; ... - // - // Process the rest of the clauses - | None -> - if maintainsVarSpace || maintainsVarSpaceUsingBind then - consumeClauses varSpace dataCompAfterOp contExpr maintainsVarSpaceUsingBind - else - consumeClauses emptyVarSpace dataCompAfterOp contExpr false - - // 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(NoSequencePointAtLetBinding, false, false, varSpacePat, dataCompPrior, compClausesExpr, compClausesExpr.Range) - else - SynExpr.ForEach (NoSequencePointAtForLoop, SeqExprOnly false, false, varSpacePat, dataCompPrior, compClausesExpr, compClausesExpr.Range) - - trans true q varSpace rebind id - - // Now run the consumeClauses - Some (consumeClauses varSpace dataCompPriorToOp comp false) - - | SynExpr.Sequential(sp, true, innerComp1, innerComp2, m) -> + | 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 @@ -8050,43 +8317,51 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv // "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 m1 = - match innerComp1 with - | SynExpr.IfThenElse (_, _, _, _, _, mIfToThen, _m) -> mIfToThen - | SynExpr.Match (SequencePointAtBinding mMatch, _, _, _) -> mMatch - | SynExpr.TryWith (_, _, _, _, _, SequencePointAtTry mTry, _) -> mTry - | SynExpr.TryFinally (_, _, _, SequencePointAtTry mTry, _) -> mTry - | SynExpr.For (SequencePointAtForLoop mBind, _, _, _, _, _, _) -> mBind - | SynExpr.ForEach (SequencePointAtForLoop mBind, _, _, _, _, _, _) -> mBind - | SynExpr.While (SequencePointAtWhileLoop mWhile, _, _, _) -> mWhile - | _ -> innerComp1.Range - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env m ad "Combine" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Combine"), m)) - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env m ad "Delay" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Delay"), m)) + 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)) Some (translatedCtxt (mkSynCall "Combine" m1 [c; mkSynCall "Delay" m1 [mkSynDelay innerComp2.Range (transNoQueryOps innerComp2)]])) | None -> // "do! expr; cexpr" is treated as { let! () = expr in cexpr } match innerComp1 with - | SynExpr.DoBang(rhsExpr, m) -> + | SynExpr.DoBang (rhsExpr, m) -> let sp = match sp with - | SuppressSequencePointOnStmtOfSequential -> SequencePointAtBinding m - | SuppressSequencePointOnExprOfSequential -> NoSequencePointAtDoBinding - | SequencePointsAtSeq -> SequencePointAtBinding m - Some(trans true q varSpace (SynExpr.LetOrUseBang(sp, false, true, SynPat.Const(SynConst.Unit, rhsExpr.Range), rhsExpr, innerComp2, m)) translatedCtxt) + | DebugPointAtSequential.ExprOnly -> DebugPointAtBinding m + | DebugPointAtSequential.StmtOnly -> NoDebugPointAtDoBinding + | DebugPointAtSequential.Both -> DebugPointAtBinding m + Some(trans true q varSpace (SynExpr.LetOrUseBang (sp, false, true, SynPat.Const(SynConst.Unit, rhsExpr.Range), rhsExpr, [], innerComp2, m)) translatedCtxt) + // "expr; cexpr" is treated as sequential execution | _ -> - Some (trans true q varSpace innerComp2 (fun holeFill -> translatedCtxt (SynExpr.Sequential(sp, true, innerComp1, holeFill, m)))) + Some (trans true 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, mIfToThen, mIfToEndOfElseBranch) -> match elseCompOpt with | Some elseComp -> if isQuery then error(Error(FSComp.SR.tcIfThenElseMayNotBeUsedWithinQueries(), mIfToThen)) - Some (translatedCtxt (SynExpr.IfThenElse(guardExpr, transNoQueryOps thenComp, Some(transNoQueryOps elseComp), spIfToThen, isRecovery, mIfToThen, mIfToEndOfElseBranch))) + Some (translatedCtxt (SynExpr.IfThenElse (guardExpr, transNoQueryOps thenComp, Some(transNoQueryOps elseComp), spIfToThen, isRecovery, mIfToThen, mIfToEndOfElseBranch))) | None -> let elseComp = - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env mIfToThen ad "Zero" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Zero"), mIfToThen)) + if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mIfToThen ad "Zero" builderTy) then + error(Error(FSComp.SR.tcRequireBuilderMethod("Zero"), mIfToThen)) mkSynCall "Zero" mIfToThen [] - Some (trans true q varSpace thenComp (fun holeFill -> translatedCtxt (SynExpr.IfThenElse(guardExpr, holeFill, Some elseComp, spIfToThen, isRecovery, mIfToThen, mIfToEndOfElseBranch)))) + Some (trans true q varSpace thenComp (fun holeFill -> translatedCtxt (SynExpr.IfThenElse (guardExpr, holeFill, Some elseComp, spIfToThen, isRecovery, mIfToThen, mIfToEndOfElseBranch)))) // 'let binds in expr' | SynExpr.LetOrUse (isRec, false, binds, innerComp, m) -> @@ -8116,25 +8391,26 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv // error case error(Error(FSComp.SR.tcCustomOperationMayNotBeUsedInConjunctionWithNonSimpleLetBindings(), mQueryOp))) - Some (trans true q varSpace innerComp (fun holeFill -> translatedCtxt (SynExpr.LetOrUse (isRec, false, binds, holeFill, m)))) // 'use x = expr in expr' | SynExpr.LetOrUse (_, true, [Binding (_, NormalBinding, _, _, _, _, _, pat, _, rhsExpr, _, spBind)], innerComp, _) -> - let bindRange = match spBind with SequencePointAtBinding m -> m | _ -> rhsExpr.Range + let bindRange = match spBind with DebugPointAtBinding m -> m | _ -> rhsExpr.Range if isQuery then error(Error(FSComp.SR.tcUseMayNotBeUsedInQueries(), bindRange)) let innerCompRange = innerComp.Range - let consumeExpr = SynExpr.MatchLambda(false, innerCompRange, [Clause(pat, None, transNoQueryOps innerComp, innerCompRange, SequencePointAtTarget)], spBind, innerCompRange) - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env bindRange ad "Using" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Using"), bindRange)) + let consumeExpr = SynExpr.MatchLambda(false, innerCompRange, [Clause(pat, None, transNoQueryOps innerComp, innerCompRange, DebugPointForTarget.Yes)], spBind, innerCompRange) + if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env bindRange ad "Using" builderTy) then + error(Error(FSComp.SR.tcRequireBuilderMethod("Using"), bindRange)) Some (translatedCtxt (mkSynCall "Using" bindRange [rhsExpr; consumeExpr ])) - // 'let! pat = expr in expr' --> build.Bind(e1, (function _argN -> match _argN with pat -> expr)) - | SynExpr.LetOrUseBang(spBind, false, isFromSource, pat, rhsExpr, innerComp, _) -> + // '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 (spBind, false, isFromSource, pat, rhsExpr, [], innerComp, _) -> - let bindRange = match spBind with SequencePointAtBinding(m) -> m | _ -> rhsExpr.Range + let bindRange = match spBind with DebugPointAtBinding m -> m | _ -> rhsExpr.Range if isQuery then error(Error(FSComp.SR.tcBindMayNotBeUsedInQueries(), bindRange)) - let innerRange = innerComp.Range - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env bindRange ad "Bind" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Bind"), bindRange)) // Add the variables to the query variable space, on demand let varSpace = @@ -8143,78 +8419,307 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let _, _, vspecs, envinner, _ = TcMatchPattern cenv (NewInferenceType()) env tpenv (pat, None) vspecs, envinner) - let rhsExpr = if isFromSource then mkSourceExpr rhsExpr else rhsExpr - Some (trans true q varSpace innerComp (fun holeFill -> - let consumeExpr = SynExpr.MatchLambda(false, pat.Range, [Clause(pat, None, holeFill, innerRange, SequencePointAtTarget)], spBind, innerRange) - translatedCtxt (mkSynCall "Bind" bindRange [rhsExpr; consumeExpr]))) + let rhsExpr = mkSourceExprConditional isFromSource rhsExpr + Some (transBind q varSpace bindRange "Bind" [rhsExpr] pat spBind 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(spBind, true, isFromSource, (SynPat.Named (SynPat.Wild _, id, false, _, _) as pat), rhsExpr, innerComp, _) - | SynExpr.LetOrUseBang(spBind, true, isFromSource, (SynPat.LongIdent (LongIdentWithDots([id], _), _, _, _, _, _) as pat), rhsExpr, innerComp, _) -> + // '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 (spBind, true, isFromSource, (SynPat.Named (SynPat.Wild _, id, false, _, _) as pat) , rhsExpr, [], innerComp, _) + | SynExpr.LetOrUseBang (spBind, true, isFromSource, (SynPat.LongIdent (longDotId=LongIdentWithDots([id], _)) as pat), rhsExpr, [], innerComp, _) -> - let bindRange = match spBind with SequencePointAtBinding(m) -> m | _ -> rhsExpr.Range + let bindRange = match spBind with DebugPointAtBinding m -> m | _ -> rhsExpr.Range if isQuery then error(Error(FSComp.SR.tcBindMayNotBeUsedInQueries(), bindRange)) - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env bindRange ad "Using" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Using"), bindRange)) - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env bindRange ad "Bind" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Bind"), bindRange)) - let consumeExpr = SynExpr.MatchLambda(false, bindRange, [Clause(pat, None, transNoQueryOps innerComp, innerComp.Range, SequencePointAtTarget)], spBind, bindRange) + + if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env bindRange ad "Using" builderTy) then + error(Error(FSComp.SR.tcRequireBuilderMethod("Using"), bindRange)) + if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env bindRange ad "Bind" builderTy) then + error(Error(FSComp.SR.tcRequireBuilderMethod("Bind"), bindRange)) + + let consumeExpr = SynExpr.MatchLambda(false, bindRange, [Clause(pat, None, transNoQueryOps innerComp, innerComp.Range, DebugPointForTarget.Yes)], spBind, bindRange) let consumeExpr = mkSynCall "Using" bindRange [SynExpr.Ident(id); consumeExpr ] - let consumeExpr = SynExpr.MatchLambda(false, bindRange, [Clause(pat, None, consumeExpr, id.idRange, SequencePointAtTarget)], spBind, bindRange) - let rhsExpr = if isFromSource then mkSourceExpr rhsExpr else rhsExpr + let consumeExpr = SynExpr.MatchLambda(false, bindRange, [Clause(pat, None, consumeExpr, id.idRange, DebugPointForTarget.Yes)], spBind, bindRange) + let rhsExpr = mkSourceExprConditional isFromSource rhsExpr + // TODO: consider allowing translation to BindReturn Some(translatedCtxt (mkSynCall "Bind" bindRange [rhsExpr; consumeExpr])) - // 'use! pat = e1 in e2' where 'pat' is not a simple name --> error - | SynExpr.LetOrUseBang(_spBind, true, _isFromSource, pat, _rhsExpr, _innerComp, _) -> - error(Error(FSComp.SR.tcInvalidUseBangBinding(), pat.Range)) + // 'use! pat = e1 ... in e2' where 'pat' is not a simple name --> error + | SynExpr.LetOrUseBang (_spBind, true, _isFromSource, pat, _rhsExpr, andBangs, _innerComp, _) -> + 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(letSpBind, false, isFromSource, letPat, letRhsExpr, andBangBindings, innerComp, letBindRange) -> + if cenv.g.langVersion.SupportsFeature LanguageFeature.AndBang then + if isQuery then error(Error(FSComp.SR.tcBindMayNotBeUsedInQueries(), letBindRange)) + let bindRange = match letSpBind with DebugPointAtBinding m -> m | _ -> letRhsExpr.Range + let sources = (letRhsExpr :: [for (_, _, _, _, andExpr, _) in andBangBindings -> andExpr ]) |> List.map (mkSourceExprConditional isFromSource) + let pats = letPat :: [for (_, _, _, 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 bindRange ad bindReturnNName builderTy)) + if hasBindReturnN && Option.isSome (convertSimpleReturnToExpr varSpace innerComp) 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()) env tpenv (consumePat, None) + vspecs, envinner) + + Some (transBind q varSpace bindRange bindNName sources consumePat letSpBind innerComp translatedCtxt) + + else + + // Check if this is a Bind2 etc. + let hasBindN = not (isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env bindRange 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()) env tpenv (consumePat, None) + vspecs, envinner) + + Some (transBind q varSpace bindRange bindNName sources consumePat letSpBind innerComp translatedCtxt) + else + + // 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 bindRange ad mergeSourcesName builderTy) then + (n-1) + else + loop (n+1) + loop 2 + + if maxMergeSources = 1 then error(Error(FSComp.SR.tcRequireMergeSourcesOrBindN(bindNName), bindRange)) + + 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 bindRange ad mergeSourcesName builderTy) then + error(Error(FSComp.SR.tcRequireMergeSourcesOrBindN(bindNName), bindRange)) + + let source = mkSynCall mergeSourcesName sourcesRange (List.map fst sourcesAndPats) + let pat = SynPat.Tuple(false, List.map snd sourcesAndPats, letPat.Range) + source, pat + + else + + // Call MergeSourcesMax(e1, e2, e3, e4, (...)) + let nowSourcesAndPats, laterSourcesAndPats = List.splitAt (maxMergeSources - 1) sourcesAndPats + let mergeSourcesName = mkMergeSourcesName maxMergeSources + + if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env bindRange ad mergeSourcesName builderTy) then + error(Error(FSComp.SR.tcRequireMergeSourcesOrBindN(bindNName), bindRange)) + + 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) + + // 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()) env tpenv (consumePat, None) + vspecs, envinner) + + // Build the 'Bind' call + Some (transBind q varSpace bindRange "Bind" [mergedSources] consumePat letSpBind innerComp translatedCtxt) + else + error(Error(FSComp.SR.tcAndBangNotSupported(), comp.Range)) | SynExpr.Match (spMatch, expr, clauses, m) -> - let mMatch = match spMatch with SequencePointAtBinding mMatch -> mMatch | _ -> m + let mMatch = match spMatch with DebugPointAtBinding mMatch -> mMatch | _ -> m if isQuery then error(Error(FSComp.SR.tcMatchMayNotBeUsedWithQuery(), mMatch)) let clauses = clauses |> List.map (fun (Clause(pat, cond, innerComp, patm, sp)) -> Clause(pat, cond, transNoQueryOps innerComp, patm, sp)) - Some(translatedCtxt (SynExpr.Match(spMatch, expr, clauses, m))) + Some(translatedCtxt (SynExpr.Match (spMatch, expr, clauses, m))) // 'match! expr with pats ...' --> build.Bind(e1, (function pats ...)) | SynExpr.MatchBang (spMatch, expr, clauses, m) -> - let mMatch = match spMatch with SequencePointAtBinding mMatch -> mMatch | _ -> m + let mMatch = match spMatch with DebugPointAtBinding mMatch -> mMatch | _ -> m if isQuery then error(Error(FSComp.SR.tcMatchMayNotBeUsedWithQuery(), mMatch)) - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env mMatch ad "Bind" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Bind"), mMatch)) + + if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mMatch ad "Bind" builderTy) then + error(Error(FSComp.SR.tcRequireBuilderMethod("Bind"), mMatch)) + let clauses = clauses |> List.map (fun (Clause(pat, cond, innerComp, patm, sp)) -> Clause(pat, cond, transNoQueryOps innerComp, patm, sp)) - let consumeExpr = SynExpr.MatchLambda(false, mMatch, clauses, spMatch, mMatch) + let consumeExpr = SynExpr.MatchLambda (false, mMatch, clauses, spMatch, mMatch) + + // TODO: consider allowing translation to BindReturn Some(translatedCtxt (mkSynCall "Bind" mMatch [expr; consumeExpr])) - | SynExpr.TryWith (innerComp, _mTryToWith, clauses, _mWithToLast, mTryToLast, spTry, _spWith) -> - let mTry = match spTry with SequencePointAtTry(m) -> m | _ -> mTryToLast - - if isQuery then error(Error(FSComp.SR.tcTryWithMayNotBeUsedInQueries(), mTry)) - let clauses = clauses |> List.map (fun (Clause(pat, cond, clauseComp, patm, sp)) -> Clause(pat, cond, transNoQueryOps clauseComp, patm, sp)) - let consumeExpr = SynExpr.MatchLambda(true, mTryToLast, clauses, NoSequencePointAtStickyBinding, mTryToLast) - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env mTry ad "TryWith" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("TryWith"), mTry)) - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env mTry ad "Delay" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Delay"), mTry)) - Some(translatedCtxt (mkSynCall "TryWith" mTry [mkSynCall "Delay" mTry [mkSynDelay2 (transNoQueryOps innerComp)]; consumeExpr])) + | SynExpr.TryWith (innerComp, _mTryToWith, clauses, _mWithToLast, mTryToLast, spTry, _spWith) -> + let mTry = match spTry with DebugPointAtTry.Yes m -> m | _ -> mTryToLast + + if isQuery then error(Error(FSComp.SR.tcTryWithMayNotBeUsedInQueries(), mTry)) + let clauses = clauses |> List.map (fun (Clause(pat, cond, clauseComp, patm, sp)) -> Clause(pat, cond, transNoQueryOps clauseComp, patm, sp)) + let consumeExpr = SynExpr.MatchLambda(true, mTryToLast, clauses, NoDebugPointAtStickyBinding, 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)) + + Some(translatedCtxt (mkSynCall "TryWith" mTry [mkSynCall "Delay" mTry [mkSynDelay2 (transNoQueryOps innerComp)]; consumeExpr])) + + | SynExpr.YieldOrReturnFrom ((isYield, _), yieldExpr, m) -> + let yieldExpr = mkSourceExpr yieldExpr + if isYield then + if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "YieldFrom" builderTy) then + error(Error(FSComp.SR.tcRequireBuilderMethod("YieldFrom"), m)) + Some (translatedCtxt (mkSynCall "YieldFrom" m [yieldExpr])) + + else + if isQuery then error(Error(FSComp.SR.tcReturnMayNotBeUsedInQueries(), m)) + if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "ReturnFrom" builderTy) then + errorR(Error(FSComp.SR.tcRequireBuilderMethod("ReturnFrom"), m)) + Some (translatedCtxt yieldExpr) + else + Some (translatedCtxt (mkSynCall "ReturnFrom" m [yieldExpr])) + + | SynExpr.YieldOrReturn ((isYield, _), yieldExpr, m) -> + let methName = (if isYield then "Yield" else "Return") + if isQuery && not isYield then error(Error(FSComp.SR.tcReturnMayNotBeUsedInQueries(), m)) + if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad methName builderTy) then + error(Error(FSComp.SR.tcRequireBuilderMethod(methName), m)) + Some(translatedCtxt (mkSynCall methName m [yieldExpr])) + + | _ -> None + + and consumeCustomOpClauses q (varSpace: LazyWithContext<_, _>) dataCompPrior compClausesExpr lastUsesBind mClause = + + // Substitute 'yield ' into the context + + let patvs, _env = varSpace.Force comp.Range + let varSpaceSimplePat = mkSimplePatForVarSpace mClause patvs + let varSpacePat = mkPatForVarSpace mClause patvs + + match compClausesExpr with + + // Detect one custom operation... This clause will always match at least once... + | OptionalSequential + (CustomOperationClause + (nm, (opName, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, isLikeZip, isLikeJoin, isLikeGroupJoin, _, methInfo), + opExpr, mClause, optionalIntoPat), + optionalCont) -> + + // 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) + + if isLikeZip || isLikeJoin || isLikeGroupJoin then + 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_IdeallyWithoutHavingOtherEffects cenv env tpenv opExpr + dataCompPrior + | Some contExpr -> consumeCustomOpClauses q varSpace dataCompPrior contExpr lastUsesBind mClause + else + + let maintainsVarSpace = customOperationMaintainsVarSpace nm + let maintainsVarSpaceUsingBind = customOperationMaintainsVarSpaceUsingBind nm + + let expectedArgCount = expectedArgCountForCustomOperator nm + + let dataCompAfterOp = + match opExpr with + | StripApps(SingleIdent nm, args) -> + if args.Length = expectedArgCount 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, arg.Range.MakeSynthetic()) + else arg) + mkSynCall methInfo.DisplayName mClause (dataCompPrior :: args) + else + 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)) + | 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 (NoDebugPointAtLetBinding, false, false, intoPat, dataCompAfterOp, [], contExpr, intoPat.Range) + else + SynExpr.ForEach (DebugPointAtFor.No, SeqExprOnly false, false, intoPat, dataCompAfterOp, contExpr, intoPat.Range) - | SynExpr.YieldOrReturnFrom((isYield, _), yieldExpr, m) -> - let yieldExpr = mkSourceExpr yieldExpr - if isYield then - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env m ad "YieldFrom" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("YieldFrom"), m)) - Some (translatedCtxt (mkSynCall "YieldFrom" m [yieldExpr])) - - else - if isQuery then error(Error(FSComp.SR.tcReturnMayNotBeUsedInQueries(), m)) - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env m ad "ReturnFrom" builderTy) then - errorR(Error(FSComp.SR.tcRequireBuilderMethod("ReturnFrom"), m)) - Some (translatedCtxt yieldExpr) - else - Some (translatedCtxt (mkSynCall "ReturnFrom" m [yieldExpr])) - + trans true q emptyVarSpace rebind id - | SynExpr.YieldOrReturn((isYield, _), yieldExpr, m) -> - let methName = (if isYield then "Yield" else "Return") - if isQuery && not isYield then error(Error(FSComp.SR.tcReturnMayNotBeUsedInQueries(), m)) - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env m ad methName builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod(methName), m)) - Some(translatedCtxt (mkSynCall methName m [yieldExpr])) + // 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 - | _ -> None + // 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 (NoDebugPointAtLetBinding, false, false, varSpacePat, dataCompPrior, [], compClausesExpr, compClausesExpr.Range) + else + SynExpr.ForEach (DebugPointAtFor.No, SeqExprOnly false, false, varSpacePat, dataCompPrior, compClausesExpr, compClausesExpr.Range) + + trans true q varSpace rebind id + and transNoQueryOps comp = + trans true false emptyVarSpace comp id - and transNoQueryOps comp = trans true false emptyVarSpace comp id and trans firstTry q varSpace comp translatedCtxt = match tryTrans firstTry q varSpace comp translatedCtxt with | Some e -> e @@ -8222,16 +8727,17 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv // This only occurs in final position in a sequence match comp with // "do! expr;" in final position is treated as { let! () = expr in return () } when Return is provided 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)) let bodyExpr = - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env m ad "Return" builderTy) then + if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "Return" builderTy) then SynExpr.ImplicitZero m else SynExpr.YieldOrReturn((false, true), SynExpr.Const(SynConst.Unit, m), m) - trans true q varSpace (SynExpr.LetOrUseBang(NoSequencePointAtDoBinding, false, false, SynPat.Const(SynConst.Unit, mUnit), rhsExpr, bodyExpr, m)) translatedCtxt + trans true q varSpace (SynExpr.LetOrUseBang (NoDebugPointAtDoBinding, false, false, SynPat.Const(SynConst.Unit, mUnit), rhsExpr, [], bodyExpr, m)) translatedCtxt + // "expr;" in final position is treated as { expr; zero } // Suppress the sequence point on the "zero" | _ -> @@ -8243,24 +8749,152 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv 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)) - trans true q varSpace (SynExpr.ImplicitZero comp.Range) (fun holeFill -> translatedCtxt (SynExpr.Sequential(SuppressSequencePointOnStmtOfSequential, true, comp, holeFill, comp.Range))) + trans true q varSpace (SynExpr.ImplicitZero comp.Range) (fun holeFill -> + let fillExpr = + if enableImplicitYield then + let implicitYieldExpr = mkSynCall "Yield" comp.Range [comp] + SynExpr.SequentialOrImplicitYield(DebugPointAtSequential.ExprOnly, comp, holeFill, implicitYieldExpr, comp.Range) + else + SynExpr.Sequential(DebugPointAtSequential.ExprOnly, true, comp, holeFill, comp.Range) + translatedCtxt fillExpr) + + and transBind q varSpace bindRange bindName bindArgs (consumePat: SynPat) spBind (innerComp: SynExpr) translatedCtxt = + + let innerRange = innerComp.Range + + let innerCompReturn = + if cenv.g.langVersion.SupportsFeature LanguageFeature.AndBang then + convertSimpleReturnToExpr varSpace innerComp + else None + + 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, [Clause(consumePat, None, innerExpr, innerRange, DebugPointForTarget.Yes)], spBind, innerRange) + translatedCtxt (mkSynCall bindName bindRange (bindArgs @ [consumeExpr])) + + match customOpInfo with + | None -> dataCompPriorToOp + | 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)) + + // Build the `Bind` call + trans true q varSpace innerComp (fun holeFill -> + let consumeExpr = SynExpr.MatchLambda(false, consumePat.Range, [Clause(consumePat, None, holeFill, innerRange, DebugPointForTarget.Yes)], spBind, innerRange) + translatedCtxt (mkSynCall bindName bindRange (bindArgs @ [consumeExpr]))) + + and convertSimpleReturnToExpr varSpace innerComp = + match innerComp with + | SynExpr.YieldOrReturn ((false, _), returnExpr, _) -> Some (returnExpr, None) + | SynExpr.Match (spMatch, expr, clauses, m) -> + let clauses = + clauses |> List.map (fun (Clause(pat, cond, innerComp2, patm, sp)) -> + match convertSimpleReturnToExpr varSpace innerComp2 with + | None -> None // failure + | Some (_, Some _) -> None // custom op on branch = failure + | Some (innerExpr2, None) -> Some (Clause(pat, cond, innerExpr2, patm, sp))) + if clauses |> List.forall Option.isSome then + Some (SynExpr.Match (spMatch, expr, (clauses |> List.map Option.get), m), None) + else + None + + | SynExpr.IfThenElse (guardExpr, thenComp, elseCompOpt, spIfToThen, isRecovery, mIfToThen, mIfToEndOfElseBranch) -> + match convertSimpleReturnToExpr varSpace thenComp with + | None -> None + | Some (_, Some _) -> None + | Some (thenExpr, None) -> + let elseExprOptOpt = + match elseCompOpt with + | None -> Some 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, mIfToThen, mIfToEndOfElseBranch), None) + + | SynExpr.LetOrUse (isRec, false, binds, innerComp, m) -> + match convertSimpleReturnToExpr varSpace innerComp with + | None -> None + | Some (_, Some _) -> None + | Some (innerExpr, None) -> Some (SynExpr.LetOrUse (isRec, false, binds, innerExpr, m), None) + + | 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) -> + + // 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) + else + None + + | _ -> None - let basicSynExpr = trans true (hasCustomOperations ()) (LazyWithContext.NotLazy ([], env)) comp (fun holeFill -> holeFill) + /// Check is an expression has no computation expression constructs + and isSimpleExpr comp = + + match comp with + | ForEachThenJoinOrGroupJoinOrZipClause _ -> false + | SynExpr.ForEach _ -> false + | SynExpr.For _ -> false + | SynExpr.While _ -> false + | SynExpr.TryFinally _ -> false + | SynExpr.ImplicitZero _ -> false + | OptionalSequential (JoinOrGroupJoinOrZipClause _, _) -> false + | OptionalSequential (CustomOperationClause _, _) -> false + | SynExpr.Sequential (_, _, innerComp1, innerComp2, _) -> isSimpleExpr innerComp1 && isSimpleExpr innerComp2 + | SynExpr.IfThenElse (_, thenComp, elseCompOpt, _, _, _, _) -> + isSimpleExpr thenComp && (match elseCompOpt with None -> true | Some c -> isSimpleExpr c) + | SynExpr.LetOrUse (_, _, _, innerComp, _) -> isSimpleExpr innerComp + | SynExpr.LetOrUseBang _ -> false + | SynExpr.Match (_, _, clauses, _) -> + clauses |> List.forall (fun (Clause(_, _, innerComp, _, _)) -> isSimpleExpr innerComp) + | SynExpr.MatchBang _ -> false + | SynExpr.TryWith (innerComp, _, clauses, _, _, _, _) -> + isSimpleExpr innerComp && + clauses |> List.forall (fun (Clause(_, _, clauseComp, _, _)) -> isSimpleExpr clauseComp) + | SynExpr.YieldOrReturnFrom _ -> false + | SynExpr.YieldOrReturn _ -> false + | _ -> true + + let basicSynExpr = + trans true (hasCustomOperations ()) (LazyWithContext.NotLazy ([], env)) comp (fun holeFill -> holeFill) let delayedExpr = - match TryFindIntrinsicOrExtensionMethInfo cenv env mBuilderVal ad "Delay" builderTy with + match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad "Delay" builderTy with | [] -> basicSynExpr | _ -> mkSynCall "Delay" mBuilderVal [(mkSynDelay2 basicSynExpr)] - let quotedSynExpr = if isAutoQuote then - SynExpr.Quote(mkSynIdGet (mBuilderVal.MakeSynthetic()) (CompileOpName "<@ @>"), (*isRaw=*)false, delayedExpr, (*isFromQueryExpression=*)true, mWhole) + SynExpr.Quote (mkSynIdGet (mBuilderVal.MakeSynthetic()) (CompileOpName "<@ @>"), (*isRaw=*)false, delayedExpr, (*isFromQueryExpression=*)true, mWhole) else delayedExpr - let runExpr = - match TryFindIntrinsicOrExtensionMethInfo cenv env mBuilderVal ad "Run" builderTy with + match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad "Run" builderTy with | [] -> quotedSynExpr | _ -> mkSynCall "Run" mBuilderVal [quotedSynExpr] @@ -8269,7 +8903,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv SynExpr.Lambda (false, false, SynSimplePats.SimplePats ([mkSynSimplePatVar false (mkSynId mBuilderVal builderValName)], mBuilderVal), runExpr, mBuilderVal) let env = - match comp with + match comp with | SynExpr.YieldOrReturn ((true, _), _, _) -> { env with eContextInfo = ContextInfo.YieldInComputationExpression } | SynExpr.YieldOrReturn ((_, true), _, _) -> { env with eContextInfo = ContextInfo.ReturnInComputationExpression } | _ -> env @@ -8295,6 +8929,13 @@ and TcSequenceExpression cenv env tpenv comp overallTy m = // Allow subsumption at 'yield' if the element type is nominal prior to the analysis of the body of the sequence expression 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 + // present in the computation expression. + let enableImplicitYield = + cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield + && (YieldFree cenv comp) + let mkDelayedExpr (coreExpr: Expr) = let m = coreExpr.Range let overallTy = tyOfExpr cenv.g coreExpr @@ -8313,7 +8954,7 @@ and TcSequenceExpression cenv env tpenv comp overallTy m = // peephole optimization: "for x in e1 -> e2" == "e1 |> List.map (fun x -> e2)" *) | (TPat_as (TPat_wild _, PBind (v, _), _), vs, - Expr.App(Expr.Val(vf, _, _), _, [genEnumElemTy], [yexpr], _)) + Expr.App (Expr.Val (vf, _, _), _, [genEnumElemTy], [yexpr], _)) when vs.Length = 1 && valRefEq cenv.g vf cenv.g.seq_singleton_vref -> let enumExprMark = enumExpr.Range @@ -8354,36 +8995,35 @@ and TcSequenceExpression cenv env tpenv comp overallTy m = let innerExprMark = innerExpr.Range Some(mkSeqFinally cenv env innerExprMark genOuterTy innerExpr unwindExpr, tpenv) - | SynExpr.Paren (_, _, _, m) -> + + | SynExpr.Paren (_, _, _, 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.DoBang(_rhsExpr, m) -> + | SynExpr.DoBang (_rhsExpr, m) -> error(Error(FSComp.SR.tcDoBangIllegalInSequenceExpression(), m)) - | SynExpr.Sequential(sp, true, innerComp1, innerComp2, m) -> + | SynExpr.Sequential (sp, true, innerComp1, innerComp2, m) -> // "expr; cexpr" is treated as sequential execution // "cexpr; cexpr" is treated as append - match tryTcSequenceExprBody env genOuterTy tpenv innerComp1 with - | None -> - let innerExpr1, tpenv = TcStmtThatCantBeCtorBody cenv env tpenv innerComp1 - let innerExpr2, tpenv = tcSequenceExprBody env genOuterTy tpenv innerComp2 - - Some(Expr.Sequential(innerExpr1, innerExpr2, NormalSeq, sp, m), tpenv) - - | Some (innerExpr1, tpenv) -> + let res, tpenv = tcSequenceExprBodyAsSequenceOrStatement env genOuterTy tpenv innerComp1 + match res with + | Choice1Of2 innerExpr1 -> let innerExpr2, tpenv = tcSequenceExprBody env genOuterTy tpenv innerComp2 let innerExpr2 = mkDelayedExpr innerExpr2 Some(mkSeqAppend cenv env innerComp1.Range genOuterTy innerExpr1 innerExpr2, tpenv) + | Choice2Of2 stmt1 -> + let innerExpr2, tpenv = tcSequenceExprBody env genOuterTy tpenv innerComp2 + Some(Expr.Sequential(stmt1, innerExpr2, NormalSeq, sp, m), tpenv) | SynExpr.IfThenElse (guardExpr, thenComp, elseCompOpt, spIfToThen, _isRecovery, mIfToThen, mIfToEndOfElseBranch) -> let guardExpr', tpenv = TcExpr cenv cenv.g.bool_ty env tpenv guardExpr let thenExpr, tpenv = tcSequenceExprBody env genOuterTy tpenv thenComp let elseComp = (match elseCompOpt with Some c -> c | None -> SynExpr.ImplicitZero mIfToThen) let elseExpr, tpenv = tcSequenceExprBody env genOuterTy tpenv elseComp - Some(mkCond spIfToThen SequencePointAtTarget mIfToEndOfElseBranch genOuterTy guardExpr' thenExpr elseExpr, tpenv) + Some(mkCond spIfToThen DebugPointForTarget.Yes mIfToEndOfElseBranch genOuterTy guardExpr' thenExpr elseExpr, tpenv) // 'let x = expr in expr' | SynExpr.LetOrUse (_, false (* not a 'use' binding *), _, _, _) -> @@ -8410,7 +9050,7 @@ and TcSequenceExpression cenv env tpenv comp overallTy m = //SEQPOINT NEEDED - we must consume spBind on this path Some(mkSeqUsing cenv env wholeExprMark bindPatTy genOuterTy inputExpr consumeExpr, tpenv) - | SynExpr.LetOrUseBang(_, _, _, _, _, _, m) -> + | SynExpr.LetOrUseBang (range=m) -> error(Error(FSComp.SR.tcUseForInSequenceExpression(), m)) | SynExpr.Match (spMatch, expr, clauses, _) -> @@ -8428,10 +9068,10 @@ and TcSequenceExpression cenv env tpenv comp overallTy m = 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 (_, mTryToWith, _, _, _, _, _) -> + | SynExpr.TryWith (tryRange=mTryToWith) -> error(Error(FSComp.SR.tcTryIllegalInSequenceExpression(), mTryToWith)) - | SynExpr.YieldOrReturnFrom((isYield, _), yieldExpr, m) -> + | SynExpr.YieldOrReturnFrom ((isYield, _), yieldExpr, m) -> let resultExpr, genExprTy, tpenv = TcExprOfUnknownType cenv env tpenv yieldExpr if not isYield then errorR(Error(FSComp.SR.tcUseYieldBangForMultipleResults(), m)) @@ -8439,7 +9079,7 @@ and TcSequenceExpression cenv env tpenv comp overallTy m = AddCxTypeMustSubsumeType ContextInfo.NoContext env.DisplayEnv cenv.css m NoTrace genOuterTy genExprTy Some(mkCoerceExpr(resultExpr, genOuterTy, m, genExprTy), tpenv) - | SynExpr.YieldOrReturn((isYield, _), yieldExpr, m) -> + | SynExpr.YieldOrReturn ((isYield, _), yieldExpr, m) -> let genResultTy = NewInferenceType () if not isYield then errorR(Error(FSComp.SR.tcSeqResultsUseYield(), m)) UnifyTypes cenv env m genOuterTy (mkSeqTy cenv.g genResultTy) @@ -8450,15 +9090,34 @@ and TcSequenceExpression cenv env tpenv comp overallTy m = | _ -> None and tcSequenceExprBody env genOuterTy tpenv comp = + 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, DebugPointAtSequential.ExprOnly, m) + resExpr, tpenv + + and tcSequenceExprBodyAsSequenceOrStatement env genOuterTy tpenv comp = match tryTcSequenceExprBody env genOuterTy tpenv comp with - | Some e -> e + | Some (expr, tpenv) -> Choice1Of2 expr, tpenv | None -> - // seq { ...; expr } is treated as 'seq { ... ; expr; yield! Seq.empty }' - // Note this means seq { ...; () } is treated as 'seq { ... ; (); yield! Seq.empty }' - let m = comp.Range let env = { env with eContextInfo = ContextInfo.SequenceExpression genOuterTy } - let expr, tpenv = TcStmtThatCantBeCtorBody cenv env tpenv comp - Expr.Sequential(expr, mkSeqEmpty cenv env m genOuterTy, NormalSeq, SuppressSequencePointOnStmtOfSequential, m), tpenv + if enableImplicitYield then + let hasTypeUnit, expr, tpenv = TryTcStmt cenv env tpenv comp + if hasTypeUnit then + Choice2Of2 expr, tpenv + else + let genResultTy = NewInferenceType () + UnifyTypes cenv env m genOuterTy (mkSeqTy cenv.g genResultTy) + let exprTy = tyOfExpr cenv.g expr + AddCxTypeMustSubsumeType env.eContextInfo env.DisplayEnv cenv.css m NoTrace genResultTy exprTy + let resExpr = mkCallSeqSingleton cenv.g m genResultTy (mkCoerceExpr(expr, genResultTy, m, exprTy)) + Choice1Of2 resExpr, tpenv + else + let stmt, tpenv = TcStmtThatCantBeCtorBody cenv env tpenv comp + Choice2Of2 stmt, tpenv let coreExpr, tpenv = tcSequenceExprBody env overallTy tpenv comp let delayedExpr = mkDelayedExpr coreExpr @@ -8512,7 +9171,7 @@ and Propagate cenv overallTy env tpenv (expr: ApplicableExpr) exprty delayed = // See RFC FS-1053.md let isAddrOf = match expr with - | ApplicableExpr(_, Expr.App(Expr.Val(vf, _, _), _, _, [], _), _) + | ApplicableExpr(_, Expr.App (Expr.Val (vf, _, _), _, _, [], _), _) when (valRefEq cenv.g vf cenv.g.addrof_vref || valRefEq cenv.g vf cenv.g.nativeptr_tobyref_vref) -> true | _ -> false @@ -8553,14 +9212,14 @@ and TcDelayed cenv overallTy env tpenv mExpr expr exprty (atomicFlag: ExprAtomic // OK, we've typechecked the thing on the left of the delayed lookup chain. // We can now record for posterity the type of this expression and the location of the expression. if (atomicFlag = ExprAtomicFlag.Atomic) then - CallExprHasTypeSink cenv.tcSink (mExpr, env.NameEnv, exprty, env.DisplayEnv, env.eAccessRights) + CallExprHasTypeSink cenv.tcSink (mExpr, env.NameEnv, exprty, env.eAccessRights) match delayed with | [] | DelayedDot :: _ -> UnifyTypes cenv env mExpr overallTy exprty expr.Expr, tpenv - // expr.M(args) where x.M is a .NET method or index property + // Expr.M (args) where x.M is a .NET method or index property // expr.M(args) where x.M is a .NET method or index property // expr.M where x.M is a .NET method or index property | DelayedDotLookup (longId, mDotLookup) :: otherDelayed -> @@ -8594,41 +9253,91 @@ and delayRest rest mPrior delayed = let mPriorAndLongId = unionRanges mPrior (rangeOfLid longId) DelayedDotLookup (rest, mPriorAndLongId) :: delayed +/// Typecheck "nameof" expressions +and TcNameOfExpr cenv env tpenv (synArg: SynExpr) = + + let rec stripParens expr = + match expr with + | SynExpr.Paren(expr, _, _, _) -> stripParens expr + | _ -> expr + + let cleanSynArg = stripParens synArg + let m = cleanSynArg.Range + let rec check overallTyOpt expr (delayed: DelayedItem list) = + match expr with + | LongOrSingleIdent (false, (LongIdentWithDots(longId, _) as lidd), _, _) when longId.Length > 0 -> + let ad = env.eAccessRights + let id, rest = List.headAndTail longId + match ResolveLongIndentAsModuleOrNamespaceOrStaticClass cenv.tcSink ResultCollectionSettings.AllResults cenv.amap m false true OpenQualified env.eNameResEnv ad id rest true with + | Result modref when delayed.IsEmpty && modref |> List.exists (p23 >> IsEntityAccessible cenv.amap m ad) -> + () // resolved to a module or namespace, done with checks + | _ -> + let (TypeNameResolutionInfo(_, staticArgsInfo)) = GetLongIdentTypeNameInfo delayed + match ResolveTypeLongIdent cenv.tcSink cenv.nameResolver ItemOccurence.UseInAttribute OpenQualified env.eNameResEnv ad longId staticArgsInfo PermitDirectReferenceToGeneratedType.No with + | Result tcref when IsEntityAccessible cenv.amap m ad tcref -> + () // resolved to a type name, done with checks + | _ -> + let overallTy = match overallTyOpt with None -> NewInferenceType() | Some t -> t + let _, _ = TcLongIdentThen cenv overallTy env tpenv lidd delayed + () // checked as an expression, done with checks + List.last longId + + | SynExpr.TypeApp (hd, _, types, _, _, _, m) -> + check overallTyOpt hd (DelayedTypeApp(types, m, m) :: delayed) + + | SynExpr.Paren(expr, _, _, _) when overallTyOpt.IsNone && delayed.IsEmpty -> + check overallTyOpt expr [] + + | SynExpr.Typed (synBodyExpr, synType, _m) when delayed.IsEmpty && overallTyOpt.IsNone -> + let tgtTy, _tpenv = TcTypeAndRecover cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv synType + check (Some tgtTy) synBodyExpr [] + + | _ -> + error (Error(FSComp.SR.expressionHasNoName(), m)) + let lastIdent = check None cleanSynArg [] + let constRange = mkRange m.FileName m.Start (mkPos m.StartLine (m.StartColumn + lastIdent.idText.Length + 2)) // `2` are for quotes + Expr.Const(Const.String(lastIdent.idText), constRange, cenv.g.string_ty) + //------------------------------------------------------------------------- // TcFunctionApplicationThen: Typecheck "expr x" + projections //------------------------------------------------------------------------- and TcFunctionApplicationThen cenv overallTy env tpenv mExprAndArg expr exprty (synArg: SynExpr) atomicFlag delayed = - let denv = env.DisplayEnv let mArg = synArg.Range let mFunExpr = expr.Range + // If the type of 'synArg' unifies as a function type, then this is a function application, otherwise // it is an error or a computation expression match UnifyFunctionTypeUndoIfFailed cenv denv mFunExpr exprty with - | ValueSome (domainTy, resultTy) -> - - // Notice the special case 'seq { ... }'. In this case 'seq' is actually a function in the F# library. - // Set a flag in the syntax tree to say we noticed a leading 'seq' - match synArg with - | SynExpr.CompExpr (false, isNotNakedRefCell, _comp, _m) -> - isNotNakedRefCell := - !isNotNakedRefCell - || - (match expr with - | ApplicableExpr(_, Expr.Op(TOp.Coerce, _, [Expr.App(Expr.Val(vf, _, _), _, _, _, _)], _), _) when valRefEq cenv.g vf cenv.g.seq_vref -> true - | _ -> false) - | _ -> () - - let arg, tpenv = TcExpr cenv domainTy env tpenv synArg - let exprAndArg, resultTy = buildApp cenv expr resultTy arg mExprAndArg - TcDelayed cenv overallTy env tpenv mExprAndArg exprAndArg resultTy atomicFlag delayed - | _ -> + | ValueSome (domainTy, resultTy) -> + match expr with + | ApplicableExpr(_, NameOfExpr cenv.g _, _) when cenv.g.langVersion.SupportsFeature LanguageFeature.NameOf -> + let replacementExpr = TcNameOfExpr cenv env tpenv synArg + TcDelayed cenv overallTy env tpenv mExprAndArg (ApplicableExpr(cenv, replacementExpr, true)) cenv.g.string_ty ExprAtomicFlag.Atomic delayed + | _ -> + // Notice the special case 'seq { ... }'. In this case 'seq' is actually a function in the F# library. + // Set a flag in the syntax tree to say we noticed a leading 'seq' + match synArg with + | SynExpr.CompExpr (false, isNotNakedRefCell, _comp, _m) -> + isNotNakedRefCell := + !isNotNakedRefCell + || + (match expr with + | ApplicableExpr(_, Expr.Op(TOp.Coerce, _, [SeqExpr cenv.g], _), _) -> true + | _ -> false) + | _ -> () + + let arg, tpenv = TcExpr cenv domainTy env tpenv synArg + let exprAndArg, resultTy = buildApp cenv expr resultTy arg mExprAndArg + TcDelayed cenv overallTy env tpenv mExprAndArg exprAndArg resultTy atomicFlag delayed + + | ValueNone -> // OK, 'expr' doesn't have function type, but perhaps 'expr' is a computation expression builder, and 'arg' is '{ ... }' match synArg with | SynExpr.CompExpr (false, _isNotNakedRefCell, comp, _m) -> - let bodyOfCompExpr, tpenv = TcComputationOrSequenceExpression cenv env overallTy mFunExpr (Some(expr.Expr, exprty)) tpenv comp + let bodyOfCompExpr, tpenv = TcComputationExpression cenv env overallTy mFunExpr expr.Expr exprty tpenv comp TcDelayed cenv overallTy env tpenv mExprAndArg (MakeApplicableExprNoFlex cenv bodyOfCompExpr) (tyOfExpr cenv.g bodyOfCompExpr) ExprAtomicFlag.NonAtomic delayed | _ -> error (NotAFunction(denv, overallTy, mFunExpr, mArg)) @@ -8637,25 +9346,26 @@ and TcFunctionApplicationThen cenv overallTy env tpenv mExprAndArg expr exprty ( // TcLongIdentThen: Typecheck "A.B.C.E.F ... " constructs //------------------------------------------------------------------------- -and TcLongIdentThen cenv overallTy env tpenv (LongIdentWithDots(longId, _)) delayed = +and GetLongIdentTypeNameInfo delayed = + // Given 'MyOverloadedType.MySubType...' use the number of given type arguments to help + // resolve type name lookup of 'MyOverloadedType' + // Also determine if type names should resolve to Item.Types or Item.CtorGroup + match delayed with + | DelayedTypeApp (tyargs, _, _) :: (DelayedDot | DelayedDotLookup _) :: _ -> + // cases like 'MyType.Sth' + TypeNameResolutionInfo(ResolveTypeNamesToTypeRefs, TypeNameResolutionStaticArgsInfo.FromTyArgs tyargs.Length) - let ad = env.eAccessRights - let typeNameResInfo = - // Given 'MyOverloadedType.MySubType...' use arity of #given type arguments to help - // resolve type name lookup of 'MyOverloadedType' - // Also determine if type names should resolve to Item.Types or Item.CtorGroup - match delayed with - | DelayedTypeApp (tyargs, _, _) :: (DelayedDot | DelayedDotLookup _) :: _ -> - // cases like 'MyType.Sth' - TypeNameResolutionInfo(ResolveTypeNamesToTypeRefs, TypeNameResolutionStaticArgsInfo.FromTyArgs tyargs.Length) + | DelayedTypeApp (tyargs, _, _) :: _ -> + // Note, this also covers the case 'MyType.' (without LValue_get), which is needed for VS (when typing) + TypeNameResolutionInfo(ResolveTypeNamesToCtors, TypeNameResolutionStaticArgsInfo.FromTyArgs tyargs.Length) - | DelayedTypeApp (tyargs, _, _) :: _ -> - // Note, this also covers the case 'MyType.' (without LValue_get), which is needed for VS (when typing) - TypeNameResolutionInfo(ResolveTypeNamesToCtors, TypeNameResolutionStaticArgsInfo.FromTyArgs tyargs.Length) + | _ -> + TypeNameResolutionInfo.Default - | _ -> - TypeNameResolutionInfo.Default +and TcLongIdentThen cenv overallTy env tpenv (LongIdentWithDots(longId, _)) delayed = + let ad = env.eAccessRights + let typeNameResInfo = GetLongIdentTypeNameInfo delayed let nameResolutionResult = ResolveLongIdentAsExprAndComputeRange cenv.tcSink cenv.nameResolver (rangeOfLid longId) ad env.eNameResEnv typeNameResInfo longId TcItemThen cenv overallTy env tpenv nameResolutionResult delayed @@ -8664,6 +9374,7 @@ and TcLongIdentThen cenv overallTy env tpenv (LongIdentWithDots(longId, _)) dela //------------------------------------------------------------------------- *) // mItem is the textual range covered by the long identifiers that make up the item and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) delayed = + let g = cenv.g let delayed = delayRest rest mItem delayed let ad = env.eAccessRights match item with @@ -8680,27 +9391,27 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del let mkConstrApp _mArgs = function [arg] -> arg | _ -> error(InternalError("ApplyUnionCaseOrExn", mItem)) mkConstrApp, [ucaseAppTy], [ for (s, m) in apinfo.ActiveTagsWithRanges -> mkSynId m s ] | _ -> - let ucref = mkChoiceCaseRef cenv.g mItem aparity n - let _, _, tinst, _ = infoOfTyconRef mItem ucref.TyconRef - let ucinfo = UnionCaseInfo(tinst, ucref) + let ucref = mkChoiceCaseRef g mItem aparity n + let _, _, tinst, _ = FreshenTyconRef2 mItem ucref.TyconRef + let ucinfo = UnionCaseInfo (tinst, ucref) ApplyUnionCaseOrExnTypes mItem cenv env ucaseAppTy (Item.UnionCase(ucinfo, false)) | _ -> ApplyUnionCaseOrExnTypes mItem cenv env ucaseAppTy item let numArgTys = List.length argTys // Subsumption at data constructions if argument type is nominal prior to equations for any arguments or return types - let flexes = argTys |> List.map (isTyparTy cenv.g >> not) + let flexes = argTys |> List.map (isTyparTy g >> not) let (|FittedArgs|_|) arg = match arg with - | SynExprParen(SynExpr.Tuple(false, args, _, _), _, _, _) - | SynExpr.Tuple(false, args, _, _) when numArgTys > 1 -> Some args + | SynExprParen(SynExpr.Tuple (false, args, _, _), _, _, _) + | SynExpr.Tuple (false, args, _, _) when numArgTys > 1 -> Some args | SynExprParen(arg, _, _, _) | arg when numArgTys = 1 -> Some [arg] | _ -> None match delayed with // This is where the constructor is applied to an argument - | ((DelayedApp (atomicFlag, (FittedArgs args as origArg), mExprAndArg))::otherDelayed) -> + | ((DelayedApp (atomicFlag, (FittedArgs args as origArg), mExprAndArg)) :: otherDelayed) -> // assert the overall result type if possible if isNil otherDelayed then UnifyTypes cenv env mExprAndArg overallTy ucaseAppTy @@ -8736,12 +9447,12 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del | Some i -> if isNull(box fittedArgs.[i]) then fittedArgs.[i] <- arg - let argContainerOpt = match item with - | Item.UnionCase(uci, _) -> Some(ArgumentContainer.UnionCase(uci)) - | Item.ExnCase tref -> Some(ArgumentContainer.Type(tref)) - | _ -> None - let argItem = Item.ArgName (argNames.[i], argTys.[i], argContainerOpt) - CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, argItem, argItem, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, ad) + let argItem = + match item with + | Item.UnionCase (uci, _) -> Item.UnionCaseField (uci, i) + | Item.ExnCase tref -> Item.RecdField (RecdFieldInfo ([], RecdFieldRef (tref, id.idText))) + | _ -> failwithf "Expecting union case or exception item, got: %O" item + CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, argItem, emptyTyparInst, ItemOccurence.Use, ad) else error(Error(FSComp.SR.tcUnionCaseFieldCannotBeUsedMoreThanOnce(id.idText), id.idRange)) currentIndex <- SEEN_NAMED_ARGUMENT | None -> @@ -8754,8 +9465,8 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del let isSpecialCaseForBackwardCompatibility = (currentIndex <> SEEN_NAMED_ARGUMENT) && (currentIndex < numArgTys) && - match stripTyEqns cenv.g argTys.[currentIndex] with - | TType_app(tcref, _) -> tyconRefEq cenv.g cenv.g.bool_tcr tcref || tyconRefEq cenv.g cenv.g.system_Bool_tcref tcref + match stripTyEqns g argTys.[currentIndex] with + | TType_app(tcref, _) -> tyconRefEq g g.bool_tcr tcref || tyconRefEq g g.system_Bool_tcref tcref | TType_var(_) -> true | _ -> false @@ -8792,8 +9503,8 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del // This is where the constructor is an active pattern result applied to no argument // Unit-taking active pattern result can be applied to no args if (numArgTys = 1 && match item with Item.ActivePatternResult _ -> true | _ -> false) then - UnifyTypes cenv env mItem (List.head argTys) cenv.g.unit_ty - 1, (fun () -> mkConstrApp mItem [mkUnit cenv.g mItem]) + UnifyTypes cenv env mItem (List.head argTys) g.unit_ty + 1, (fun () -> mkConstrApp mItem [mkUnit g mItem]) // This is where the constructor expects no arguments and is applied to no argument elif numArgTys = 0 then @@ -8804,17 +9515,17 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del (fun () -> let vs, args = argTys |> List.mapi (fun i ty -> mkCompGenLocal mItem ("arg" + string i) ty) |> List.unzip let constrApp = mkConstrApp mItem args - let lam = mkMultiLambda mItem vs (constrApp, tyOfExpr cenv.g constrApp) + let lam = mkMultiLambda mItem vs (constrApp, tyOfExpr g constrApp) lam) UnionCaseOrExnCheck env numArgTys numArgs mItem let expr = mkExpr() - let exprTy = tyOfExpr cenv.g expr + let exprTy = tyOfExpr g expr PropagateThenTcDelayed cenv overallTy env tpenv mItem (MakeApplicableExprNoFlex cenv expr) exprTy ExprAtomicFlag.Atomic delayed - | Item.Types(nm, (ty::_)) -> + | Item.Types(nm, (ty :: _)) -> match delayed with - | ((DelayedTypeApp(tyargs, _mTypeArgs, mExprAndTypeArgs))::(DelayedDotLookup (longId, mLongId))::otherDelayed) -> + | ((DelayedTypeApp(tyargs, _mTypeArgs, mExprAndTypeArgs)) :: (DelayedDotLookup (longId, mLongId)) :: otherDelayed) -> // If Item.Types is returned then the ty will be of the form TType_app(tcref, genericTyargs) where tyargs // is a fresh instantiation for tcref. TcNestedTypeApplication will chop off precisely #genericTyargs args @@ -8823,14 +9534,14 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del // Report information about the whole expression including type arguments to VS let item = Item.Types(nm, [ty]) - CallNameResolutionSink cenv.tcSink (mExprAndTypeArgs, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (mExprAndTypeArgs, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) TcItemThen cenv overallTy env tpenv (ResolveExprDotLongIdentAndComputeRange cenv.tcSink cenv.nameResolver (unionRanges mExprAndTypeArgs mLongId) ad env.eNameResEnv ty longId IgnoreOverrides true) otherDelayed - | ((DelayedTypeApp(tyargs, _mTypeArgs, mExprAndTypeArgs))::_delayed') -> + | ((DelayedTypeApp(tyargs, _mTypeArgs, mExprAndTypeArgs)) :: _delayed') -> // A case where we have an incomplete name e.g. 'Foo.' - we still want to report it to VS! let ty, _ = TcNestedTypeApplication cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv mExprAndTypeArgs ty tyargs let item = Item.Types(nm, [ty]) - CallNameResolutionSink cenv.tcSink (mExprAndTypeArgs, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (mExprAndTypeArgs, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) // Same error as in the following case error(Error(FSComp.SR.tcInvalidUseOfTypeName(), mItem)) @@ -8845,7 +9556,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del // Static method calls Type.Foo(arg1, ..., argn) let meths = List.map (fun minfo -> minfo, None) minfos match delayed with - | (DelayedApp (atomicFlag, arg, mExprAndArg)::otherDelayed) -> + | (DelayedApp (atomicFlag, arg, mExprAndArg) :: otherDelayed) -> TcMethodApplicationThen cenv env overallTy None tpenv None [] mExprAndArg mItem methodName ad NeverMutates false meths afterResolution NormalValUse [arg] atomicFlag otherDelayed | (DelayedTypeApp(tys, mTypeArgs, mExprAndTypeArgs) :: otherDelayed) -> @@ -8856,7 +9567,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del // Replace the resolution including the static parameters, plus the extra information about the original method info let item = Item.MethodGroup(methodName, [minfoAfterStaticArguments], Some minfos.[0]) - CallNameResolutionSinkReplacing cenv.tcSink (mItem, env.NameEnv, item, item, [], ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSinkReplacing cenv.tcSink (mItem, env.NameEnv, item, [], ItemOccurence.Use, env.eAccessRights) match otherDelayed with | DelayedApp(atomicFlag, arg, mExprAndArg) :: otherDelayed -> @@ -8872,7 +9583,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del // FUTURE: can we do better than emptyTyparInst here, in order to display instantiations // of type variables in the quick info provided in the IDE? But note we haven't yet even checked if the // number of type arguments is correct... - CallNameResolutionSink cenv.tcSink (mExprAndTypeArgs, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (mExprAndTypeArgs, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) match otherDelayed with | DelayedApp(atomicFlag, arg, mExprAndArg) :: otherDelayed -> @@ -8893,21 +9604,21 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del | (minfo :: _) -> minfo.ApparentEnclosingType | [] -> error(Error(FSComp.SR.tcTypeHasNoAccessibleConstructor(), mItem)) match delayed with - | ((DelayedApp (_, arg, mExprAndArg))::otherDelayed) -> + | ((DelayedApp (_, arg, mExprAndArg)) :: otherDelayed) -> - CallExprHasTypeSink cenv.tcSink (mExprAndArg, env.NameEnv, objTy, env.DisplayEnv, env.eAccessRights) + CallExprHasTypeSink cenv.tcSink (mExprAndArg, env.NameEnv, objTy, env.eAccessRights) TcCtorCall true cenv env tpenv overallTy objTy (Some mItem) item false [arg] mExprAndArg otherDelayed (Some afterResolution) - | ((DelayedTypeApp(tyargs, _mTypeArgs, mExprAndTypeArgs))::(DelayedApp (_, arg, mExprAndArg))::otherDelayed) -> + | ((DelayedTypeApp(tyargs, _mTypeArgs, mExprAndTypeArgs)) :: (DelayedApp (_, arg, mExprAndArg)) :: otherDelayed) -> let objTyAfterTyArgs, tpenv = TcNestedTypeApplication cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv mExprAndTypeArgs objTy tyargs - CallExprHasTypeSink cenv.tcSink (mExprAndArg, env.NameEnv, objTyAfterTyArgs, env.DisplayEnv, env.eAccessRights) + CallExprHasTypeSink cenv.tcSink (mExprAndArg, env.NameEnv, objTyAfterTyArgs, env.eAccessRights) let itemAfterTyArgs, minfosAfterTyArgs = #if !NO_EXTENSIONTYPING // If the type is provided and took static arguments then the constructor will have changed // to a provided constructor on the statically instantiated type. Re-resolve that constructor. match objTyAfterTyArgs with - | AppTy cenv.g (tcref, _) when tcref.Deref.IsProvided -> + | AppTy g (tcref, _) when tcref.Deref.IsProvided -> let newItem = ForceRaise (ResolveObjectConstructor cenv.nameResolver env.DisplayEnv mExprAndArg ad objTyAfterTyArgs) match newItem with | Item.CtorGroup(_, newMinfos) -> newItem, newMinfos @@ -8919,13 +9630,13 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del minfosAfterTyArgs |> List.iter (fun minfo -> UnifyTypes cenv env mExprAndTypeArgs minfo.ApparentEnclosingType objTyAfterTyArgs) TcCtorCall true cenv env tpenv overallTy objTyAfterTyArgs (Some mExprAndTypeArgs) itemAfterTyArgs false [arg] mExprAndArg otherDelayed (Some afterResolution) - | ((DelayedTypeApp(tyargs, _mTypeArgs, mExprAndTypeArgs))::otherDelayed) -> + | ((DelayedTypeApp(tyargs, _mTypeArgs, mExprAndTypeArgs)) :: otherDelayed) -> let objTy, tpenv = TcNestedTypeApplication cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv mExprAndTypeArgs objTy tyargs // A case where we have an incomplete name e.g. 'Foo.' - we still want to report it to VS! let resolvedItem = Item.Types(nm, [objTy]) - CallNameResolutionSink cenv.tcSink (mExprAndTypeArgs, env.NameEnv, resolvedItem, resolvedItem, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (mExprAndTypeArgs, env.NameEnv, resolvedItem, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) minfos |> List.iter (fun minfo -> UnifyTypes cenv env mExprAndTypeArgs minfo.ApparentEnclosingType objTy) TcCtorCall true cenv env tpenv overallTy objTy (Some mExprAndTypeArgs) item false [] mExprAndTypeArgs otherDelayed (Some afterResolution) @@ -8936,6 +9647,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del | Item.FakeInterfaceCtor _ -> error(Error(FSComp.SR.tcInvalidUseOfInterfaceType(), mItem)) + | Item.ImplicitOp(id, sln) -> let isPrefix = PrettyNaming.IsPrefixOperator id.idText @@ -8953,8 +9665,8 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del Typar(mkSynId mItem (cenv.synArgNameGenerator.New()), HeadTypeStaticReq, true) ] let retTyData = Typar(mkSynId mItem (cenv.synArgNameGenerator.New()), HeadTypeStaticReq, true) - let argTypars = argData |> List.map (fun d -> NewTypar (TyparKind.Type, TyparRigidity.Flexible, d, false, TyparDynamicReq.Yes, [], false, false)) - let retTypar = NewTypar (TyparKind.Type, TyparRigidity.Flexible, retTyData, false, TyparDynamicReq.Yes, [], false, false) + let argTypars = argData |> List.map (fun d -> Construct.NewTypar (TyparKind.Type, TyparRigidity.Flexible, d, false, TyparDynamicReq.Yes, [], false, false)) + let retTypar = Construct.NewTypar (TyparKind.Type, TyparRigidity.Flexible, retTyData, false, TyparDynamicReq.Yes, [], false, false) let argTys = argTypars |> List.map mkTyparTy let retTy = mkTyparTy retTypar @@ -8964,35 +9676,35 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del let logicalCompiledName = ComputeLogicalName id memberFlags let traitInfo = TTrait(argTys, logicalCompiledName, memberFlags, argTys, Some retTy, sln) - let expr = Expr.Op(TOp.TraitCall(traitInfo), [], ves, mItem) + let expr = Expr.Op (TOp.TraitCall traitInfo, [], ves, mItem) let expr = mkLambdas mItem [] vs (expr, retTy) let rec isSimpleArgument e = match e with - | SynExpr.New(_, _, synExpr, _) - | SynExpr.Paren(synExpr, _, _, _) - | SynExpr.Typed(synExpr, _, _) + | SynExpr.New (_, _, synExpr, _) + | SynExpr.Paren (synExpr, _, _, _) + | SynExpr.Typed (synExpr, _, _) | SynExpr.TypeApp (synExpr, _, _, _, _, _, _) | SynExpr.TypeTest (synExpr, _, _) - | SynExpr.Upcast(synExpr, _, _) - | SynExpr.DotGet(synExpr, _, _, _) - | SynExpr.Downcast(synExpr, _, _) - | SynExpr.InferredUpcast(synExpr, _) - | SynExpr.InferredDowncast(synExpr, _) - | SynExpr.AddressOf(_, synExpr, _, _) - | SynExpr.Quote(_, _, synExpr, _, _) -> isSimpleArgument synExpr + | SynExpr.Upcast (synExpr, _, _) + | SynExpr.DotGet (synExpr, _, _, _) + | SynExpr.Downcast (synExpr, _, _) + | SynExpr.InferredUpcast (synExpr, _) + | SynExpr.InferredDowncast (synExpr, _) + | SynExpr.AddressOf (_, synExpr, _, _) + | SynExpr.Quote (_, _, synExpr, _, _) -> isSimpleArgument synExpr | SynExpr.Null _ | SynExpr.Ident _ | SynExpr.Const _ | SynExpr.LongIdent _ -> true - | SynExpr.Tuple(_, synExprs, _, _) - | SynExpr.ArrayOrList(_, synExprs, _) -> synExprs |> List.forall isSimpleArgument - | SynExpr.Record(_, copyOpt, fields, _) -> copyOpt |> Option.forall (fst >> isSimpleArgument) && fields |> List.forall (p23 >> Option.forall isSimpleArgument) + | SynExpr.Tuple (_, synExprs, _, _) + | SynExpr.ArrayOrList (_, synExprs, _) -> synExprs |> List.forall isSimpleArgument + | SynExpr.Record (_, copyOpt, fields, _) -> copyOpt |> Option.forall (fst >> isSimpleArgument) && fields |> List.forall (p23 >> Option.forall isSimpleArgument) | SynExpr.App (_, _, synExpr, synExpr2, _) -> isSimpleArgument synExpr && isSimpleArgument synExpr2 - | SynExpr.IfThenElse(synExpr, synExpr2, synExprOpt, _, _, _, _) -> isSimpleArgument synExpr && isSimpleArgument synExpr2 && Option.forall isSimpleArgument synExprOpt - | SynExpr.DotIndexedGet(synExpr, _, _, _) -> isSimpleArgument synExpr + | SynExpr.IfThenElse (synExpr, synExpr2, synExprOpt, _, _, _, _) -> isSimpleArgument synExpr && isSimpleArgument synExpr2 && Option.forall isSimpleArgument synExprOpt + | SynExpr.DotIndexedGet (synExpr, _, _, _) -> isSimpleArgument synExpr | SynExpr.ObjExpr _ | SynExpr.AnonRecd _ | SynExpr.While _ @@ -9010,6 +9722,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del | SynExpr.TryFinally _ | SynExpr.Lazy _ | SynExpr.Sequential _ + | SynExpr.SequentialOrImplicitYield _ | SynExpr.LetOrUse _ | SynExpr.DotSet _ | SynExpr.DotIndexedSet _ @@ -9022,9 +9735,9 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del | SynExpr.LibraryOnlyStaticOptimization _ | SynExpr.LibraryOnlyUnionCaseFieldGet _ | SynExpr.LibraryOnlyUnionCaseFieldSet _ - | SynExpr.ArbitraryAfterError(_, _) - | SynExpr.FromParseError(_, _) - | SynExpr.DiscardAfterMissingQualificationAfterDot(_, _) + | SynExpr.ArbitraryAfterError (_, _) + | SynExpr.FromParseError (_, _) + | SynExpr.DiscardAfterMissingQualificationAfterDot (_, _) | SynExpr.ImplicitZero _ | SynExpr.YieldOrReturn _ | SynExpr.YieldOrReturnFrom _ @@ -9035,8 +9748,8 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del -> false - // Propagte the known application structure into function types - Propagate cenv overallTy env tpenv (MakeApplicableExprNoFlex cenv expr) (tyOfExpr cenv.g expr) delayed + // Propagate the known application structure into function types + Propagate cenv overallTy env tpenv (MakeApplicableExprNoFlex cenv expr) (tyOfExpr g expr) delayed // Take all simple arguments and process them before applying the constraint. let delayed1, delayed2 = @@ -9044,7 +9757,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del List.takeWhile pred delayed, List.skipWhile pred delayed let intermediateTy = if isNil delayed2 then overallTy else NewInferenceType () - let resultExpr, tpenv = TcDelayed cenv intermediateTy env tpenv mItem (MakeApplicableExprNoFlex cenv expr) (tyOfExpr cenv.g expr) ExprAtomicFlag.NonAtomic delayed1 + let resultExpr, tpenv = TcDelayed cenv intermediateTy env tpenv mItem (MakeApplicableExprNoFlex cenv expr) (tyOfExpr g expr) ExprAtomicFlag.NonAtomic delayed1 // Add the constraint after the application arguments have been checked to allow annotations to kick in on rigid type parameters AddCxMethodConstraint env.DisplayEnv cenv.css mItem NoTrace traitInfo @@ -9056,14 +9769,14 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del | Item.DelegateCtor ty -> match delayed with - | ((DelayedApp (atomicFlag, arg, mItemAndArg))::otherDelayed) -> + | ((DelayedApp (atomicFlag, arg, mItemAndArg)) :: otherDelayed) -> TcNewDelegateThen cenv overallTy env tpenv mItem mItemAndArg ty arg atomicFlag otherDelayed - | ((DelayedTypeApp(tyargs, _mTypeArgs, mItemAndTypeArgs))::(DelayedApp (atomicFlag, arg, mItemAndArg))::otherDelayed) -> + | ((DelayedTypeApp(tyargs, _mTypeArgs, mItemAndTypeArgs)) :: (DelayedApp (atomicFlag, arg, mItemAndArg)) :: otherDelayed) -> let ty, tpenv = TcNestedTypeApplication cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv mItemAndTypeArgs ty tyargs // Report information about the whole expression including type arguments to VS let item = Item.DelegateCtor ty - CallNameResolutionSink cenv.tcSink (mItemAndTypeArgs, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (mItemAndTypeArgs, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) TcNewDelegateThen cenv overallTy env tpenv mItem mItemAndArg ty arg atomicFlag otherDelayed | _ -> error(Error(FSComp.SR.tcInvalidUseOfDelegate(), mItem)) @@ -9074,32 +9787,33 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del // Mutable value set: 'v <- e' | DelayedSet(e2, mStmt) :: otherDelayed -> if not (isNil otherDelayed) then error(Error(FSComp.SR.tcInvalidAssignment(), mStmt)) - UnifyTypes cenv env mStmt overallTy cenv.g.unit_ty - vref.Deref.SetHasBeenReferenced() - CheckValAccessible mItem env.eAccessRights vref - CheckValAttributes cenv.g vref mItem |> CommitOperationResult + UnifyTypes cenv env mStmt overallTy g.unit_ty + vref.Deref.SetHasBeenReferenced() + CheckValAccessible mItem env.AccessRights vref + CheckValAttributes g vref mItem |> CommitOperationResult let vty = vref.Type let vty2 = - if isByrefTy cenv.g vty then - destByrefTy cenv.g vty + if isByrefTy g vty then + destByrefTy g vty else - if not vref.IsMutable then error (ValNotMutable(env.DisplayEnv, vref, mStmt)) + if not vref.IsMutable then + errorR (ValNotMutable (env.DisplayEnv, vref, mStmt)) vty // Always allow subsumption on assignment to fields let e2', tpenv = TcExprFlex cenv true false vty2 env tpenv e2 let vexp = - if isInByrefTy cenv.g vty then + if isInByrefTy g vty then errorR(Error(FSComp.SR.writeToReadOnlyByref(), mStmt)) mkAddrSet mStmt vref e2' - elif isByrefTy cenv.g vty then + elif isByrefTy g vty then mkAddrSet mStmt vref e2' else mkValSet mStmt vref e2' - PropagateThenTcDelayed cenv overallTy env tpenv mStmt (MakeApplicableExprNoFlex cenv vexp) (tyOfExpr cenv.g vexp) ExprAtomicFlag.NonAtomic otherDelayed + PropagateThenTcDelayed cenv overallTy env tpenv mStmt (MakeApplicableExprNoFlex cenv vexp) (tyOfExpr g vexp) ExprAtomicFlag.NonAtomic otherDelayed // Value instantiation: v ... - | (DelayedTypeApp(tys, _mTypeArgs, mExprAndTypeArgs)::otherDelayed) -> + | (DelayedTypeApp(tys, _mTypeArgs, mExprAndTypeArgs) :: otherDelayed) -> // Note: we know this is a NormalValUse or PossibleConstrainedCall because: // - it isn't a CtorValUsedAsSuperInit // - it isn't a CtorValUsedAsSelfInit @@ -9126,44 +9840,42 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del if pinfo.IsIndexer then GetMemberApplicationArgs delayed cenv env tpenv else ExprAtomicFlag.Atomic, None, [mkSynUnit mItem], delayed, tpenv - if not pinfo.IsStatic then error (Error (FSComp.SR.tcPropertyIsNotStatic(nm), mItem)) + if not pinfo.IsStatic then error (Error (FSComp.SR.tcPropertyIsNotStatic nm, mItem)) match delayed with | DelayedSet(e2, mStmt) :: otherDelayed -> if not (isNil otherDelayed) then error(Error(FSComp.SR.tcInvalidAssignment(), mStmt)) // Static Property Set (possibly indexer) - UnifyTypes cenv env mStmt overallTy cenv.g.unit_ty + UnifyTypes cenv env mStmt overallTy g.unit_ty let meths = pinfos |> SettersOfPropInfos if meths.IsEmpty then let meths = pinfos |> GettersOfPropInfos - let isByrefMethReturnSetter = meths |> List.exists (function (_,Some pinfo) -> isByrefTy cenv.g (pinfo.GetPropertyType(cenv.amap,mItem)) | _ -> false) - if isByrefMethReturnSetter then - // x.P <- ... byref setter - if isNil meths then error (Error (FSComp.SR.tcPropertyIsNotReadable(nm), mItem)) - TcMethodApplicationThen cenv env overallTy None tpenv tyargsOpt [] mItem mItem nm ad NeverMutates true meths afterResolution NormalValUse args ExprAtomicFlag.Atomic delayed - else - error (Error (FSComp.SR.tcPropertyCannotBeSet1 nm, mItem)) + let isByrefMethReturnSetter = meths |> List.exists (function (_,Some pinfo) -> isByrefTy g (pinfo.GetPropertyType(cenv.amap,mItem)) | _ -> false) + if not isByrefMethReturnSetter then + errorR (Error (FSComp.SR.tcPropertyCannotBeSet1 nm, mItem)) + // x.P <- ... byref setter + if isNil meths then error (Error (FSComp.SR.tcPropertyIsNotReadable nm, mItem)) + TcMethodApplicationThen cenv env overallTy None tpenv tyargsOpt [] mItem mItem nm ad NeverMutates true meths afterResolution NormalValUse args ExprAtomicFlag.Atomic delayed else let args = if pinfo.IsIndexer then args else [] - if isNil meths then error (Error (FSComp.SR.tcPropertyCannotBeSet1 nm, mItem)) + if isNil meths then + errorR (Error (FSComp.SR.tcPropertyCannotBeSet1 nm, mItem)) // Note: static calls never mutate a struct object argument TcMethodApplicationThen cenv env overallTy None tpenv tyargsOpt [] mStmt mItem nm ad NeverMutates true meths afterResolution NormalValUse (args@[e2]) ExprAtomicFlag.NonAtomic otherDelayed | _ -> // Static Property Get (possibly indexer) let meths = pinfos |> GettersOfPropInfos - if isNil meths then error (Error (FSComp.SR.tcPropertyIsNotReadable(nm), mItem)) + if isNil meths then error (Error (FSComp.SR.tcPropertyIsNotReadable nm, mItem)) // Note: static calls never mutate a struct object argument TcMethodApplicationThen cenv env overallTy None tpenv tyargsOpt [] mItem mItem nm ad NeverMutates true meths afterResolution NormalValUse args ExprAtomicFlag.Atomic delayed | Item.ILField finfo -> - CheckILFieldInfoAccessible cenv.g cenv.amap mItem ad finfo - if not finfo.IsStatic then error (Error (FSComp.SR.tcFieldIsNotStatic(finfo.FieldName), mItem)) - CheckILFieldAttributes cenv.g finfo mItem + ILFieldStaticChecks g cenv.amap cenv.infoReader ad mItem finfo let fref = finfo.ILFieldRef let exprty = finfo.FieldType(cenv.amap, mItem) match delayed with | DelayedSet(e2, mStmt) :: _delayed' -> - UnifyTypes cenv env mStmt overallTy cenv.g.unit_ty + UnifyTypes cenv env mStmt overallTy g.unit_ty // Always allow subsumption on assignment to fields let e2', tpenv = TcExprFlex cenv true false exprty env tpenv e2 let expr = BuildILStaticFieldSet mStmt finfo e2' @@ -9173,7 +9885,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del let expr = match finfo.LiteralValue with | Some lit -> - Expr.Const(TcFieldInit mItem lit, mItem, exprty) + Expr.Const (TcFieldInit mItem lit, mItem, exprty) | None -> let isValueType = finfo.IsValueType let valu = if isValueType then AsValue else AsObject @@ -9191,7 +9903,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del // Get static F# field or literal CheckRecdFieldInfoAccessible cenv.amap mItem ad rfinfo if not rfinfo.IsStatic then error (Error (FSComp.SR.tcFieldIsNotStatic(rfinfo.Name), mItem)) - CheckRecdFieldInfoAttributes cenv.g rfinfo mItem |> CommitOperationResult + CheckRecdFieldInfoAttributes g rfinfo mItem |> CommitOperationResult let fref = rfinfo.RecdFieldRef let fieldTy = rfinfo.FieldType match delayed with @@ -9200,7 +9912,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del // Set static F# field CheckRecdFieldMutation mItem env.DisplayEnv rfinfo - UnifyTypes cenv env mStmt overallTy cenv.g.unit_ty + UnifyTypes cenv env mStmt overallTy g.unit_ty let fieldTy = rfinfo.FieldType // Always allow subsumption on assignment to fields let e2', tpenv = TcExprFlex cenv true false fieldTy env tpenv e2 @@ -9211,7 +9923,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del let expr = match rfinfo.LiteralValue with // Get literal F# field - | Some lit -> Expr.Const(lit, mItem, exprty) + | Some lit -> Expr.Const (lit, mItem, exprty) // Get static F# field | None -> mkStaticRecdFieldGet (fref, rfinfo.TypeInst, mItem) PropagateThenTcDelayed cenv overallTy env tpenv mItem (MakeApplicableExprWithFlex cenv env expr) exprty ExprAtomicFlag.Atomic delayed @@ -9224,7 +9936,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del // 'delayed' is about to be dropped on the floor, first do rudimentary checking to get name resolutions in its body RecordNameAndTypeResolutions_IdeallyWithoutHavingOtherEffects_Delayed cenv env tpenv delayed match usageTextOpt() with - | None -> error(Error(FSComp.SR.tcCustomOperationNotUsedCorrectly(nm), mItem)) + | None -> error(Error(FSComp.SR.tcCustomOperationNotUsedCorrectly nm, mItem)) | Some usageText -> error(Error(FSComp.SR.tcCustomOperationNotUsedCorrectly2(nm, usageText), mItem)) | _ -> error(Error(FSComp.SR.tcLookupMayNotBeUsedHere(), mItem)) @@ -9268,9 +9980,9 @@ and TcLookupThen cenv overallTy env tpenv mObjExpr objExpr objExprTy longId dela // Canonicalize inference problem prior to '.' lookup on variable types if isTyparTy cenv.g objExprTy then - GeneralizationHelpers.CanonicalizePartialInferenceProblem (cenv, env.DisplayEnv, mExprAndLongId) (freeInTypeLeftToRight cenv.g false objExprTy) + ConstraintSolver.CanonicalizePartialInferenceProblem cenv.css env.DisplayEnv mExprAndLongId (freeInTypeLeftToRight cenv.g false objExprTy) - let item, mItem, rest, afterResolution = ResolveExprDotLongIdentAndComputeRange cenv.tcSink cenv.nameResolver mExprAndLongId ad env.eNameResEnv objExprTy longId findFlag false + let item, mItem, rest, afterResolution = ResolveExprDotLongIdentAndComputeRange cenv.tcSink cenv.nameResolver mExprAndLongId ad env.NameEnv objExprTy longId findFlag false let mExprAndItem = unionRanges mObjExpr mItem let delayed = delayRest rest mExprAndItem delayed @@ -9286,7 +9998,7 @@ and TcLookupThen cenv overallTy env tpenv mObjExpr objExpr objExprTy longId dela | Some minfoAfterStaticArguments -> // Replace the resolution including the static parameters, plus the extra information about the original method info let item = Item.MethodGroup(methodName, [minfoAfterStaticArguments], Some minfos.[0]) - CallNameResolutionSinkReplacing cenv.tcSink (mExprAndItem, env.NameEnv, item, item, [], ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSinkReplacing cenv.tcSink (mExprAndItem, env.NameEnv, item, [], ItemOccurence.Use, env.eAccessRights) TcMethodApplicationThen cenv env overallTy None tpenv None objArgs mExprAndItem mItem methodName ad mutates false [(minfoAfterStaticArguments, None)] afterResolution NormalValUse args atomicFlag delayed | None -> @@ -9309,7 +10021,7 @@ and TcLookupThen cenv overallTy env tpenv mObjExpr objExpr objExprTy longId dela if pinfo.IsIndexer then GetMemberApplicationArgs delayed cenv env tpenv else ExprAtomicFlag.Atomic, None, [mkSynUnit mItem], delayed, tpenv - if pinfo.IsStatic then error (Error (FSComp.SR.tcPropertyIsStatic(nm), mItem)) + if pinfo.IsStatic then error (Error (FSComp.SR.tcPropertyIsStatic nm, mItem)) match delayed with @@ -9321,12 +10033,11 @@ and TcLookupThen cenv overallTy env tpenv mObjExpr objExpr objExprTy longId dela if meths.IsEmpty then let meths = pinfos |> GettersOfPropInfos let isByrefMethReturnSetter = meths |> List.exists (function (_,Some pinfo) -> isByrefTy cenv.g (pinfo.GetPropertyType(cenv.amap,mItem)) | _ -> false) - if isByrefMethReturnSetter then - // x.P <- ... byref setter - if isNil meths then error (Error (FSComp.SR.tcPropertyIsNotReadable(nm), mItem)) - TcMethodApplicationThen cenv env overallTy None tpenv tyargsOpt objArgs mExprAndItem mItem nm ad PossiblyMutates true meths afterResolution NormalValUse args atomicFlag delayed - else - error (Error (FSComp.SR.tcPropertyCannotBeSet1 nm, mItem)) + if not isByrefMethReturnSetter then + errorR (Error (FSComp.SR.tcPropertyCannotBeSet1 nm, mItem)) + // x.P <- ... byref setter + if isNil meths then error (Error (FSComp.SR.tcPropertyIsNotReadable nm, mItem)) + TcMethodApplicationThen cenv env overallTy None tpenv tyargsOpt objArgs mExprAndItem mItem nm ad PossiblyMutates true meths afterResolution NormalValUse args atomicFlag delayed else let args = if pinfo.IsIndexer then args else [] let mut = (if isStructTy cenv.g (tyOfExpr cenv.g objExpr) then DefinitelyMutates else PossiblyMutates) @@ -9334,7 +10045,7 @@ and TcLookupThen cenv overallTy env tpenv mObjExpr objExpr objExprTy longId dela | _ -> // Instance property getter let meths = GettersOfPropInfos pinfos - if isNil meths then error (Error (FSComp.SR.tcPropertyIsNotReadable(nm), mItem)) + if isNil meths then error (Error (FSComp.SR.tcPropertyIsNotReadable nm, mItem)) TcMethodApplicationThen cenv env overallTy None tpenv tyargsOpt objArgs mExprAndItem mItem nm ad PossiblyMutates true meths afterResolution NormalValUse args atomicFlag delayed | Item.RecdField rfinfo -> @@ -9402,8 +10113,8 @@ and TcEventValueThen cenv overallTy env tpenv mItem mExprAndItem objDetails (ein let nm = einfo.EventName let ad = env.eAccessRights match objDetails, einfo.IsStatic with - | Some _, true -> error (Error (FSComp.SR.tcEventIsStatic(nm), mItem)) - | None, false -> error (Error (FSComp.SR.tcEventIsNotStatic(nm), mItem)) + | Some _, true -> error (Error (FSComp.SR.tcEventIsStatic nm, mItem)) + | None, false -> error (Error (FSComp.SR.tcEventIsNotStatic nm, mItem)) | _ -> () let delegateType = einfo.GetDelegateType(cenv.amap, mItem) @@ -9421,7 +10132,7 @@ and TcEventValueThen cenv overallTy env tpenv mItem mExprAndItem objDetails (ein | None -> f [] | Some (objExpr, objExprTy) -> mkCompGenLetIn mItem "eventTarget" objExprTy objExpr (fun (_, ve) -> f [ve]) - // Bind the object target expression to make sure we only run its sdie effects once, and to make + // Bind the object target expression to make sure we only run its side effects once, and to make // sure if it's a mutable reference then we dereference it - see FSharp 1.0 bug 942 let expr = bindObjArgs (fun objVars -> @@ -9496,9 +10207,9 @@ and TcMethodApplicationThen and GetNewInferenceTypeForMethodArg cenv env tpenv x = match x with | SynExprParen(a, _, _, _) -> GetNewInferenceTypeForMethodArg cenv env tpenv a - | SynExpr.AddressOf(true, a, _, m) -> mkByrefTyWithInference cenv.g (GetNewInferenceTypeForMethodArg cenv env tpenv a) (NewByRefKindInferenceType cenv.g m) - | SynExpr.Lambda(_, _, _, a, _) -> mkFunTy (NewInferenceType ()) (GetNewInferenceTypeForMethodArg cenv env tpenv a) - | SynExpr.Quote(_, raw, a, _, _) -> + | SynExpr.AddressOf (true, a, _, m) -> mkByrefTyWithInference cenv.g (GetNewInferenceTypeForMethodArg cenv env tpenv a) (NewByRefKindInferenceType cenv.g m) + | SynExpr.Lambda (_, _, _, a, _) -> mkFunTy (NewInferenceType ()) (GetNewInferenceTypeForMethodArg cenv env tpenv a) + | SynExpr.Quote (_, raw, a, _, _) -> if raw then mkRawQuotedExprTy cenv.g else mkQuotedExprTy cenv.g (GetNewInferenceTypeForMethodArg cenv env tpenv a) | _ -> NewInferenceType () @@ -9560,76 +10271,76 @@ and TcMethodApplication // In one case (the second "single named item" rule) we delay the application of a // argument until we've produced a lambda that detuples an input tuple let curriedCallerArgsOpt, unnamedDelayedCallerArgExprOpt, exprTy = - match curriedCallerArgs with - | [] -> - None, None, exprTy - | _ -> - let unnamedCurriedCallerArgs, namedCurriedCallerArgs = curriedCallerArgs |> List.map GetMethodArgs |> List.unzip + match curriedCallerArgs with + | [] -> + None, None, exprTy + | _ -> + let unnamedCurriedCallerArgs, namedCurriedCallerArgs = curriedCallerArgs |> List.map GetMethodArgs |> List.unzip - // There is an mismatch when _uses_ of indexed property setters in the tc.fs code that calls this function. - // The arguments are passed as if they are curried with arity [numberOfIndexParameters;1], however in the TAST, indexed property setters - // are uncurried and have arity [numberOfIndexParameters+1]. - // - // Here we work around this mismatch by crunching all property argument lists to uncirred form. - // Ideally the problem needs to be solved at its root cause at the callsites to this function - let unnamedCurriedCallerArgs, namedCurriedCallerArgs = - if isProp then - [List.concat unnamedCurriedCallerArgs], [List.concat namedCurriedCallerArgs] - else - unnamedCurriedCallerArgs, namedCurriedCallerArgs + // There is an mismatch when _uses_ of indexed property setters in the tc.fs code that calls this function. + // The arguments are passed as if they are curried with arity [numberOfIndexParameters;1], however in the TAST, indexed property setters + // are uncurried and have arity [numberOfIndexParameters+1]. + // + // Here we work around this mismatch by crunching all property argument lists to uncurried form. + // Ideally the problem needs to be solved at its root cause at the callsites to this function + let unnamedCurriedCallerArgs, namedCurriedCallerArgs = + if isProp then + [List.concat unnamedCurriedCallerArgs], [List.concat namedCurriedCallerArgs] + else + unnamedCurriedCallerArgs, namedCurriedCallerArgs - let MakeUnnamedCallerArgInfo x = (x, GetNewInferenceTypeForMethodArg cenv env tpenv x, x.Range) - - // "single named item" rule. This is where we have a single accessible method - // member x.M(arg1) - // being used with - // x.M (x, y) - // Without this rule this requires - // x.M ((x, y)) - match candidates with - | [calledMeth] - when (namedCurriedCallerArgs |> List.forall isNil && - let curriedCalledArgs = calledMeth.GetParamAttribs(cenv.amap, mItem) - curriedCalledArgs.Length = 1 && - curriedCalledArgs.Head.Length = 1 && - curriedCalledArgs.Head.Head |> isSimpleFormalArg) -> - let unnamedCurriedCallerArgs = curriedCallerArgs |> List.map (MakeUnnamedCallerArgInfo >> List.singleton) - let namedCurriedCallerArgs = namedCurriedCallerArgs |> List.map (fun _ -> []) - (Some (unnamedCurriedCallerArgs, namedCurriedCallerArgs), None, exprTy) - - // "single named item" rule. This is where we have a single accessible method - // member x.M(arg1, arg2) - // being used with - // x.M p - // We typecheck this as if it has been written "(fun (v1, v2) -> x.M(v1, v2)) p" - // Without this rule this requires - // x.M (fst p, snd p) - | [calledMeth] - when (namedCurriedCallerArgs |> List.forall isNil && - unnamedCurriedCallerArgs.Length = 1 && - unnamedCurriedCallerArgs.Head.Length = 1 && - let curriedCalledArgs = calledMeth.GetParamAttribs(cenv.amap, mItem) - curriedCalledArgs.Length = 1 && - curriedCalledArgs.Head.Length > 1 && - curriedCalledArgs.Head |> List.forall isSimpleFormalArg) -> - - // The call lambda has function type - let exprTy = mkFunTy (NewInferenceType ()) exprTy + let MakeUnnamedCallerArgInfo x = (x, GetNewInferenceTypeForMethodArg cenv env tpenv x, x.Range) + + // "single named item" rule. This is where we have a single accessible method + // member x.M(arg1) + // being used with + // x.M (x, y) + // Without this rule this requires + // x.M ((x, y)) + match candidates with + | [calledMeth] + when (namedCurriedCallerArgs |> List.forall isNil && + let curriedCalledArgs = calledMeth.GetParamAttribs(cenv.amap, mItem) + curriedCalledArgs.Length = 1 && + curriedCalledArgs.Head.Length = 1 && + curriedCalledArgs.Head.Head |> isSimpleFormalArg) -> + let unnamedCurriedCallerArgs = curriedCallerArgs |> List.map (MakeUnnamedCallerArgInfo >> List.singleton) + let namedCurriedCallerArgs = namedCurriedCallerArgs |> List.map (fun _ -> []) + (Some (unnamedCurriedCallerArgs, namedCurriedCallerArgs), None, exprTy) + + // "single named item" rule. This is where we have a single accessible method + // member x.M(arg1, arg2) + // being used with + // x.M p + // We typecheck this as if it has been written "(fun (v1, v2) -> x.M(v1, v2)) p" + // Without this rule this requires + // x.M (fst p, snd p) + | [calledMeth] + when (namedCurriedCallerArgs |> List.forall isNil && + unnamedCurriedCallerArgs.Length = 1 && + unnamedCurriedCallerArgs.Head.Length = 1 && + let curriedCalledArgs = calledMeth.GetParamAttribs(cenv.amap, mItem) + curriedCalledArgs.Length = 1 && + curriedCalledArgs.Head.Length > 1 && + curriedCalledArgs.Head |> List.forall isSimpleFormalArg) -> + + // The call lambda has function type + let exprTy = mkFunTy (NewInferenceType ()) exprTy - (None, Some unnamedCurriedCallerArgs.Head.Head, exprTy) + (None, Some unnamedCurriedCallerArgs.Head.Head, exprTy) - | _ -> - let unnamedCurriedCallerArgs = unnamedCurriedCallerArgs |> List.mapSquared MakeUnnamedCallerArgInfo - let namedCurriedCallerArgs = namedCurriedCallerArgs |> List.mapSquared (fun (isOpt, nm, x) -> - let ty = GetNewInferenceTypeForMethodArg cenv env tpenv x - // #435263: compiler crash with .net optional parameters and F# optional syntax - // named optional arguments should always have option type - let ty = if isOpt then mkOptionTy denv.g ty else ty - nm, isOpt, x, ty, x.Range - ) - - (Some (unnamedCurriedCallerArgs, namedCurriedCallerArgs), None, exprTy) - + | _ -> + let unnamedCurriedCallerArgs = unnamedCurriedCallerArgs |> List.mapSquared MakeUnnamedCallerArgInfo + let namedCurriedCallerArgs = namedCurriedCallerArgs |> List.mapSquared (fun (isOpt, nm, x) -> + let ty = GetNewInferenceTypeForMethodArg cenv env tpenv x + // #435263: compiler crash with .net optional parameters and F# optional syntax + // named optional arguments should always have option type + // STRUCT OPTIONS: if we allow struct options as optional arguments then we should relax this and rely + // on later inference to work out if this is a struct option or ref option + let ty = if isOpt then mkOptionTy denv.g ty else ty + nm, isOpt, x, ty, x.Range) + + (Some (unnamedCurriedCallerArgs, namedCurriedCallerArgs), None, exprTy) let CalledMethHasSingleArgumentGroupOfThisLength n (calledMeth: MethInfo) = let curriedMethodArgAttribs = calledMeth.GetParamAttribs(cenv.amap, mItem) @@ -9703,13 +10414,13 @@ and TcMethodApplication let callerArgCounts = (List.sumBy List.length unnamedCurriedCallerArgs, List.sumBy List.length namedCurriedCallerArgs) - let callerArgs = List.zip unnamedCurriedCallerArgs namedCurriedCallerArgs + let callerArgs = { Unnamed = unnamedCurriedCallerArgs; Named = namedCurriedCallerArgs } let makeOneCalledMeth (minfo, pinfoOpt, usesParamArrayConversion) = let minst = FreshenMethInfo mItem minfo let callerTyArgs = match tyargsOpt with - | Some tyargs -> minfo.AdjustUserTypeInstForFSharpStyleIndexedExtensionMembers(tyargs) + | Some tyargs -> minfo.AdjustUserTypeInstForFSharpStyleIndexedExtensionMembers tyargs | None -> minst CalledMeth(cenv.infoReader, Some(env.NameEnv), isCheckingAttributeCall, FreshenMethInfo, mMethExpr, ad, minfo, minst, callerTyArgs, pinfoOpt, callerObjArgTys, callerArgs, usesParamArrayConversion, true, objTyOpt) @@ -9720,9 +10431,8 @@ and TcMethodApplication if meth.UsesParamArrayConversion then yield makeOneCalledMeth (minfo, pinfoOpt, false) ] - let uniquelyResolved = - let csenv = MakeConstraintSolverEnv ContextInfo.NoContext cenv.css mMethExpr denv - UnifyUniqueOverloading csenv callerArgCounts methodName ad preArgumentTypeCheckingCalledMethGroup returnTy + let uniquelyResolved = + UnifyUniqueOverloading denv cenv.css mMethExpr callerArgCounts methodName ad preArgumentTypeCheckingCalledMethGroup returnTy uniquelyResolved, preArgumentTypeCheckingCalledMethGroup @@ -9774,7 +10484,7 @@ and TcMethodApplication [| for meth in preArgumentTypeCheckingCalledMethGroup do match ExamineMethodForLambdaPropagation meth with | Some (unnamedInfo, namedInfo) -> - let calledObjArgTys = meth.CalledObjArgTys(mMethExpr) + let calledObjArgTys = meth.CalledObjArgTys mMethExpr if (calledObjArgTys, callerObjArgTys) ||> Seq.forall2 (fun calledTy callerTy -> AddCxTypeMustSubsumeTypeMatchingOnlyUndoIfFailed denv cenv.css mMethExpr calledTy callerTy) then yield (List.toArraySquared unnamedInfo, List.toArraySquared namedInfo) | None -> () |] @@ -9803,28 +10513,24 @@ and TcMethodApplication /// Select the called method that's the result of overload resolution let finalCalledMeth = - let callerArgs = List.zip unnamedCurriedCallerArgs namedCurriedCallerArgs + let callerArgs = { Unnamed = unnamedCurriedCallerArgs ; Named = namedCurriedCallerArgs } let postArgumentTypeCheckingCalledMethGroup = preArgumentTypeCheckingCalledMethGroup |> List.map (fun (minfo: MethInfo, minst, pinfoOpt, usesParamArrayConversion) -> let callerTyArgs = match tyargsOpt with - | Some tyargs -> minfo.AdjustUserTypeInstForFSharpStyleIndexedExtensionMembers(tyargs) + | Some tyargs -> minfo.AdjustUserTypeInstForFSharpStyleIndexedExtensionMembers tyargs | None -> minst CalledMeth(cenv.infoReader, Some(env.NameEnv), isCheckingAttributeCall, FreshenMethInfo, mMethExpr, ad, minfo, minst, callerTyArgs, pinfoOpt, callerObjArgTys, callerArgs, usesParamArrayConversion, true, objTyOpt)) - let callerArgCounts = (unnamedCurriedCallerArgs.Length, namedCurriedCallerArgs.Length) - let csenv = MakeConstraintSolverEnv ContextInfo.NoContext cenv.css mMethExpr denv - // Commit unassociated constraints prior to member overload resolution where there is ambiguity // about the possible target of the call. if not uniquelyResolved then - GeneralizationHelpers.CanonicalizePartialInferenceProblem (cenv, denv, mItem) + ConstraintSolver.CanonicalizePartialInferenceProblem cenv.css denv mItem (//freeInTypeLeftToRight cenv.g false returnTy @ - (unnamedCurriedCallerArgs |> List.collectSquared (fun callerArg -> freeInTypeLeftToRight cenv.g false callerArg.Type))) + (unnamedCurriedCallerArgs |> List.collectSquared (fun callerArg -> freeInTypeLeftToRight cenv.g false callerArg.CallerArgumentType))) - let result, errors = - ResolveOverloading csenv NoTrace methodName 0 None callerArgCounts ad postArgumentTypeCheckingCalledMethGroup true (Some returnTy) + let result, errors = ResolveOverloadingForCall denv cenv.css mMethExpr methodName 0 None callerArgs ad postArgumentTypeCheckingCalledMethGroup true (Some returnTy) match afterResolution, result with | AfterResolution.DoNothing, _ -> () @@ -9872,21 +10578,12 @@ and TcMethodApplication let finalCalledMethInfo = finalCalledMeth.Method let finalCalledMethInst = finalCalledMeth.CalledTyArgs - let finalArgSets = finalCalledMeth.ArgSets let finalAssignedItemSetters = finalCalledMeth.AssignedItemSetters - let finalCalledPropInfoOpt = finalCalledMeth.AssociatedPropertyInfo let finalAttributeAssignedNamedItems = finalCalledMeth.AttributeAssignedNamedArgs - let finalUnnamedCalledOptArgs = finalCalledMeth.UnnamedCalledOptArgs - let finalUnnamedCalledOutArgs = finalCalledMeth.UnnamedCalledOutArgs - let finalAssignedNamedArgs = finalArgSets |> List.collect (fun argSet -> argSet.AssignedNamedArgs) - let finalParamArrayCallerArgs = finalArgSets |> List.collect (fun argSet -> argSet.ParamArrayCallerArgs) - let finalUnnamedCalledArgs = finalArgSets |> List.collect (fun argSet -> argSet.UnnamedCalledArgs) - let finalUnnamedCallerArgs = finalArgSets |> List.collect (fun argSet -> argSet.UnnamedCallerArgs) - // STEP 4. Check the attributes on the method and the corresponding event/property, if any - finalCalledPropInfoOpt |> Option.iter (fun pinfo -> CheckPropInfoAttributes pinfo mItem |> CommitOperationResult) + finalCalledMeth.AssociatedPropertyInfo |> Option.iter (fun pinfo -> CheckPropInfoAttributes pinfo mItem |> CommitOperationResult) let isInstance = not (isNil objArgs) MethInfoChecks cenv.g cenv.amap isInstance tyargsOpt objArgs ad mItem finalCalledMethInfo @@ -9915,351 +10612,76 @@ and TcMethodApplication | _ -> () end - if (finalArgSets |> List.existsi (fun i argSet -> argSet.UnnamedCalledArgs |> List.existsi (fun j ca -> ca.Position <> (i, j)))) then + if (finalCalledMeth.ArgSets |> List.existsi (fun i argSet -> argSet.UnnamedCalledArgs |> List.existsi (fun j ca -> ca.Position <> (i, j)))) then errorR(Deprecated(FSComp.SR.tcUnnamedArgumentsDoNotFormPrefix(), mMethExpr)) + /// STEP 5. Build the argument list. Adjust for optional arguments, byref arguments and coercions. - // STEP 5. Build the argument list. Adjust for optional arguments, byref arguments and coercions. - // For example, if you pass an F# reference cell to a byref then we must get the address of the - // contents of the ref. Likewise lots of adjustments are made for optional arguments etc. - - // Some of the code below must allocate temporary variables or bind other variables to particular values. - // As usual we represent variable allocators by expr -> expr functions - // which we then use to wrap the whole expression. These will either do nothing or pre-bind a variable. It doesn't - // matter what order they are applied in as long as they are all composed together. - let emptyPreBinder (e: Expr) = e - - // For unapplied 'e.M' we first evaluate 'e' outside the lambda, i.e. 'let v = e in (fun arg -> v.M(arg))' - let objArgPreBinder, objArgs = - match objArgs, lambdaVars with - | [objArg], Some _ -> - if finalCalledMethInfo.IsExtensionMember && finalCalledMethInfo.ObjArgNeedsAddress(cenv.amap, mMethExpr) then - error(Error(FSComp.SR.tcCannotPartiallyApplyExtensionMethodForByref(finalCalledMethInfo.DisplayName), mMethExpr)) - let objArgTy = tyOfExpr cenv.g objArg - let v, ve = mkCompGenLocal mMethExpr "objectArg" objArgTy - (fun body -> mkCompGenLet mMethExpr v objArg body), [ve] - | _ -> - emptyPreBinder, objArgs - - // Handle adhoc argument conversions - let coerceExpr isOutArg calledArgTy (reflArgInfo: ReflectedArgInfo) callerArgTy m callerArgExpr = - let g = cenv.g - - if isByrefTy g calledArgTy && isRefCellTy g callerArgTy then - None, Expr.Op(TOp.RefAddrGet false, [destRefCellTy g callerArgTy], [callerArgExpr], m) - -#if IMPLICIT_ADDRESS_OF - elif isInByrefTy g calledArgTy && not (isByrefTy cenv.g callerArgTy) then - let wrap, callerArgExprAddress, _readonly, _writeonly = mkExprAddrOfExpr g true false NeverMutates callerArgExpr None m - Some wrap, callerArgExprAddress -#endif - - elif isDelegateTy cenv.g calledArgTy && isFunTy cenv.g callerArgTy then - None, CoerceFromFSharpFuncToDelegate cenv.g cenv.amap cenv.infoReader ad callerArgTy m callerArgExpr calledArgTy - - elif isLinqExpressionTy cenv.g calledArgTy && isDelegateTy cenv.g (destLinqExpressionTy cenv.g calledArgTy) && isFunTy cenv.g callerArgTy then - let delegateTy = destLinqExpressionTy cenv.g calledArgTy - let expr = CoerceFromFSharpFuncToDelegate cenv.g cenv.amap cenv.infoReader ad callerArgTy m callerArgExpr delegateTy - None, mkCallQuoteToLinqLambdaExpression cenv.g m delegateTy (Expr.Quote(expr, ref None, false, m, mkQuotedExprTy cenv.g delegateTy)) - - // auto conversions to quotations (to match auto conversions to LINQ expressions) - elif reflArgInfo.AutoQuote && isQuotedExprTy cenv.g calledArgTy && not (isQuotedExprTy cenv.g callerArgTy) then - match reflArgInfo with - | ReflectedArgInfo.Quote true -> - None, mkCallLiftValueWithDefn cenv.g m calledArgTy callerArgExpr - | ReflectedArgInfo.Quote false -> - None, Expr.Quote(callerArgExpr, ref None, false, m, calledArgTy) - | ReflectedArgInfo.None -> failwith "unreachable" // unreachable due to reflArgInfo.AutoQuote condition - - // Note: out args do not need to be coerced - elif isOutArg then - None, callerArgExpr - - // Note: not all these casts are reported in quotations - else - None, mkCoerceIfNeeded cenv.g calledArgTy callerArgTy callerArgExpr - - // Handle param array and optional arguments - let optArgPreBinder, paramArrayPreBinders, allArgs, outArgExprs, outArgTmpBinds = - - let normalUnnamedArgs = - (finalUnnamedCalledArgs, finalUnnamedCallerArgs) ||> List.map2 (fun called caller -> { NamedArgIdOpt = None; CalledArg=called; CallerArg=caller }) - - let paramArrayPreBinders, paramArrayArgs = - match finalCalledMeth.ParamArrayCalledArgOpt with - | None -> - [], [] - | Some paramArrayCalledArg -> - let paramArrayCalledArgElementType = destArrayTy cenv.g paramArrayCalledArg.CalledArgumentType - - let paramArrayPreBinders, es = - finalParamArrayCallerArgs - |> List.map (fun callerArg -> - let (CallerArg(callerArgTy, m, isOutArg, callerArgExpr)) = callerArg - coerceExpr isOutArg paramArrayCalledArgElementType paramArrayCalledArg.ReflArgInfo callerArgTy m callerArgExpr) - |> List.unzip - - let arg = - [ { NamedArgIdOpt = None - CalledArg=paramArrayCalledArg - CallerArg=CallerArg(paramArrayCalledArg.CalledArgumentType, mMethExpr, false, Expr.Op(TOp.Array, [paramArrayCalledArgElementType], es, mMethExpr)) } ] - paramArrayPreBinders, arg - - // CLEANUP: Move all this code into some isolated file, e.g. "optional.fs" - // - // Handle CallerSide optional arguments. - // - // CallerSide optional arguments are largely for COM interop, e.g. to PIA assemblies for Word etc. - // As a result we follow the VB and C# behavior here. - // - // "1. If the parameter is statically typed as System.Object and does not have a value, then there are four cases: - // a. The parameter is marked with MarshalAs(IUnknown), MarshalAs(Interface), or MarshalAs(IDispatch). In this case we pass null. - // b. Else if the parameter is marked with IUnknownConstantAttribute. In this case we pass new System.Runtime.InteropServices.UnknownWrapper(null) - // c. Else if the parameter is marked with IDispatchConstantAttribute. In this case we pass new System.Runtime.InteropServices.DispatchWrapper(null) - // d. Else, we will pass Missing.Value. - // 2. Otherwise, if there is a value attribute, then emit the default value. - // 3. Otherwise, we emit default(T). - // 4. Finally, we apply conversions from the value to the parameter type. This is where the nullable conversions take place for VB. - // - VB allows you to mark ref parameters as optional. The semantics of this is that we create a temporary - // with type = type of parameter, load the optional value to it, and call the method. - // - VB also allows you to mark arrays with Nothing as the optional value. - // - VB also allows you to pass intrinsic values as optional values to parameters - // typed as Object. What we do in this case is we box the intrinsic value." - // - let optArgs, optArgPreBinder = - (emptyPreBinder, finalUnnamedCalledOptArgs) ||> List.mapFold (fun wrapper calledArg -> - let calledArgTy = calledArg.CalledArgumentType - let wrapper2, expr = - match calledArg.OptArgInfo with - | NotOptional -> - error(InternalError("Unexpected NotOptional", mItem)) - | CallerSide dfltVal -> - let rec build currCalledArgTy currDfltVal = - match currDfltVal with - | MissingValue -> - // Add an I_nop if this is an initonly field to make sure we never recognize it as an lvalue. See mkExprAddrOfExpr. - emptyPreBinder, mkAsmExpr ([ mkNormalLdsfld (fspec_Missing_Value cenv.g); AI_nop ], [], [], [currCalledArgTy], mMethExpr) - | DefaultValue -> - emptyPreBinder, mkDefault(mMethExpr, currCalledArgTy) - | Constant fieldInit -> - match currCalledArgTy with - | NullableTy cenv.g inst when fieldInit <> ILFieldInit.Null -> - let nullableTy = mkILNonGenericBoxedTy(cenv.g.FindSysILTypeRef "System.Nullable`1") - let ctor = mkILCtorMethSpecForTy(nullableTy, [ILType.TypeVar 0us]).MethodRef - let ctorArgs = [Expr.Const(TcFieldInit mMethExpr fieldInit, mMethExpr, inst)] - emptyPreBinder, Expr.Op(TOp.ILCall(false, false, true, true, NormalValUse, false, false, ctor, [inst], [], [currCalledArgTy]), [], ctorArgs, mMethExpr) - | ByrefTy cenv.g inst -> - build inst (PassByRef(inst, currDfltVal)) - | _ -> - match calledArg.CallerInfo, env.eCallerMemberName with - | CallerLineNumber, _ when typeEquiv cenv.g currCalledArgTy cenv.g.int_ty -> - emptyPreBinder, Expr.Const(Const.Int32(mMethExpr.StartLine), mMethExpr, currCalledArgTy) - | CallerFilePath, _ when typeEquiv cenv.g currCalledArgTy cenv.g.string_ty -> - emptyPreBinder, Expr.Const(Const.String(FileSystem.GetFullPathShim(mMethExpr.FileName)), mMethExpr, currCalledArgTy) - | CallerMemberName, Some(callerName) when (typeEquiv cenv.g currCalledArgTy cenv.g.string_ty) -> - emptyPreBinder, Expr.Const(Const.String(callerName), mMethExpr, currCalledArgTy) - | _ -> - emptyPreBinder, Expr.Const(TcFieldInit mMethExpr fieldInit, mMethExpr, currCalledArgTy) - - | WrapperForIDispatch -> - match cenv.g.TryFindSysILTypeRef "System.Runtime.InteropServices.DispatchWrapper" with - | None -> error(Error(FSComp.SR.fscSystemRuntimeInteropServicesIsRequired(), mMethExpr)) - | Some tref -> - let ty = mkILNonGenericBoxedTy tref - let mref = mkILCtorMethSpecForTy(ty, [cenv.g.ilg.typ_Object]).MethodRef - let expr = Expr.Op(TOp.ILCall(false, false, false, true, NormalValUse, false, false, mref, [], [], [cenv.g.obj_ty]), [], [mkDefault(mMethExpr, currCalledArgTy)], mMethExpr) - emptyPreBinder, expr - | WrapperForIUnknown -> - match cenv.g.TryFindSysILTypeRef "System.Runtime.InteropServices.UnknownWrapper" with - | None -> error(Error(FSComp.SR.fscSystemRuntimeInteropServicesIsRequired(), mMethExpr)) - | Some tref -> - let ty = mkILNonGenericBoxedTy tref - let mref = mkILCtorMethSpecForTy(ty, [cenv.g.ilg.typ_Object]).MethodRef - let expr = Expr.Op(TOp.ILCall(false, false, false, true, NormalValUse, false, false, mref, [], [], [cenv.g.obj_ty]), [], [mkDefault(mMethExpr, currCalledArgTy)], mMethExpr) - emptyPreBinder, expr - | PassByRef (ty, dfltVal2) -> - let v, _ = mkCompGenLocal mMethExpr "defaultByrefArg" ty - let wrapper2, rhs = build currCalledArgTy dfltVal2 - (wrapper2 >> mkCompGenLet mMethExpr v rhs), mkValAddr mMethExpr false (mkLocalValRef v) - build calledArgTy dfltVal - | CalleeSide -> - let calledNonOptTy = - if isOptionTy cenv.g calledArgTy then - destOptionTy cenv.g calledArgTy - else - calledArgTy // should be unreachable - - match calledArg.CallerInfo, env.eCallerMemberName with - | CallerLineNumber, _ when typeEquiv cenv.g calledNonOptTy cenv.g.int_ty -> - let lineExpr = Expr.Const(Const.Int32(mMethExpr.StartLine), mMethExpr, calledNonOptTy) - emptyPreBinder, mkUnionCaseExpr(mkSomeCase cenv.g, [calledNonOptTy], [lineExpr], mMethExpr) - | CallerFilePath, _ when typeEquiv cenv.g calledNonOptTy cenv.g.string_ty -> - let filePathExpr = Expr.Const(Const.String(FileSystem.GetFullPathShim(mMethExpr.FileName)), mMethExpr, calledNonOptTy) - emptyPreBinder, mkUnionCaseExpr(mkSomeCase cenv.g, [calledNonOptTy], [filePathExpr], mMethExpr) - | CallerMemberName, Some(callerName) when typeEquiv cenv.g calledNonOptTy cenv.g.string_ty -> - let memberNameExpr = Expr.Const(Const.String(callerName), mMethExpr, calledNonOptTy) - emptyPreBinder, mkUnionCaseExpr(mkSomeCase cenv.g, [calledNonOptTy], [memberNameExpr], mMethExpr) - | _ -> - emptyPreBinder, mkUnionCaseExpr(mkNoneCase cenv.g, [calledNonOptTy], [], mMethExpr) - - // Combine the variable allocators (if any) - let wrapper = (wrapper >> wrapper2) - let callerArg = CallerArg(calledArgTy, mMethExpr, false, expr) - { NamedArgIdOpt = None; CalledArg = calledArg; CallerArg = callerArg }, wrapper) - - - // Handle optional arguments - let wrapOptionalArg (assignedArg: AssignedCalledArg<_>) = - let (CallerArg(callerArgTy, m, isOptCallerArg, expr)) = assignedArg.CallerArg - match assignedArg.CalledArg.OptArgInfo with - | NotOptional -> - if isOptCallerArg then errorR(Error(FSComp.SR.tcFormalArgumentIsNotOptional(), m)) - assignedArg - | _ -> - let expr = - match assignedArg.CalledArg.OptArgInfo with - | CallerSide _ -> - if isOptCallerArg then - // STRUCT OPTIONS: if we allow struct options as optional arguments then we should take - // the address correctly. - mkUnionCaseFieldGetUnprovenViaExprAddr (expr, mkSomeCase cenv.g, [destOptionTy cenv.g callerArgTy], 0, m) - else - expr - | CalleeSide -> - if isOptCallerArg then - // M(?x=bopt) when M(A) --> M(?x=Some(b.Value)) - expr - else - // M(x=b) when M(A) --> M(?x=Some(b :> A)) - let calledArgTy = assignedArg.CalledArg.CalledArgumentType - if isOptionTy cenv.g calledArgTy then - let calledNonOptTy = destOptionTy cenv.g calledArgTy - mkUnionCaseExpr(mkSomeCase cenv.g, [calledNonOptTy], [mkCoerceIfNeeded cenv.g calledNonOptTy callerArgTy expr], m) - else - expr // should be unreachable - - | _ -> failwith "Unreachable" - { assignedArg with CallerArg=CallerArg((tyOfExpr cenv.g expr), m, isOptCallerArg, expr) } - - let outArgsAndExprs, outArgTmpBinds = - finalUnnamedCalledOutArgs |> List.map (fun calledArg -> - let calledArgTy = calledArg.CalledArgumentType - let outArgTy = destByrefTy cenv.g calledArgTy - let outv, outArgExpr = mkMutableCompGenLocal mMethExpr PrettyNaming.outArgCompilerGeneratedName outArgTy // mutable! - let expr = mkDefault(mMethExpr, outArgTy) - let callerArg = CallerArg(calledArgTy, mMethExpr, false, mkValAddr mMethExpr false (mkLocalValRef outv)) - let outArg = { NamedArgIdOpt=None;CalledArg=calledArg;CallerArg=callerArg } - (outArg, outArgExpr), mkCompGenBind outv expr) - |> List.unzip - - let outArgs, outArgExprs = List.unzip outArgsAndExprs - - let allArgs = - List.map wrapOptionalArg normalUnnamedArgs @ - List.map wrapOptionalArg finalAssignedNamedArgs @ - paramArrayArgs @ - optArgs @ - outArgs - - let allArgs = - allArgs |> List.sortBy (fun x -> x.Position) - - optArgPreBinder, paramArrayPreBinders, allArgs, outArgExprs, outArgTmpBinds - - let coerce (assignedArg: AssignedCalledArg<_>) = - let isOutArg = assignedArg.CalledArg.IsOutArg - let reflArgInfo = assignedArg.CalledArg.ReflArgInfo - let calledArgTy = assignedArg.CalledArg.CalledArgumentType - let (CallerArg(callerArgTy, m, _, e)) = assignedArg.CallerArg - - coerceExpr isOutArg calledArgTy reflArgInfo callerArgTy m e + let objArgPreBinder, objArgs, allArgsPreBinders, allArgs, allArgsCoerced, optArgPreBinder, paramArrayPreBinders, outArgExprs, outArgTmpBinds = + AdjustCallerArgs TcFieldInit env.eCallerMemberName cenv.infoReader ad finalCalledMeth objArgs lambdaVars mItem mMethExpr // Record the resolution of the named argument for the Language Service allArgs |> List.iter (fun assignedArg -> match assignedArg.NamedArgIdOpt with | None -> () | Some id -> - let item = Item.ArgName (defaultArg assignedArg.CalledArg.NameOpt id, assignedArg.CalledArg.CalledArgumentType, Some(ArgumentContainer.Method(finalCalledMethInfo))) - CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, ad)) + let item = Item.ArgName (defaultArg assignedArg.CalledArg.NameOpt id, assignedArg.CalledArg.CalledArgumentType, Some(ArgumentContainer.Method finalCalledMethInfo)) + CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, ad)) - let allArgsPreBinders, allArgsCoerced = List.map coerce allArgs |> List.unzip - // Make the call expression - let expr, exprty = + /// STEP 6. Build the call expression, then adjust for byref-returns, out-parameters-as-tuples, post-hoc property assignments, methods-as-first-class-value, + /// + + let callExpr0, exprty = BuildPossiblyConditionalMethodCall cenv env mut mMethExpr isProp finalCalledMethInfo isSuperInit finalCalledMethInst objArgs allArgsCoerced // Handle byref returns - let expr = + let callExpr1 = // byref-typed returns get implicitly dereferenced - let vty = tyOfExpr cenv.g expr + let vty = tyOfExpr cenv.g callExpr0 if isByrefTy cenv.g vty then - let v, _ = mkCompGenLocal mMethExpr "byrefReturn" vty - mkCompGenLet mMethExpr v expr (mkAddrGet mMethExpr (mkLocalValRef v)) + mkDerefAddrExpr mMethExpr callExpr0 mMethExpr vty else - expr + callExpr0 // Bind "out" parameters as part of the result tuple - let expr, exprty = + let callExpr2, exprty = + let expr = callExpr1 if isNil outArgTmpBinds then expr, exprty else let outArgTys = outArgExprs |> List.map (tyOfExpr cenv.g) - let expr = if isUnitTy cenv.g exprty then mkCompGenSequential mMethExpr expr (mkRefTupled cenv.g mMethExpr outArgExprs outArgTys) - else mkRefTupled cenv.g mMethExpr (expr :: outArgExprs) (exprty :: outArgTys) + let expr = + if isUnitTy cenv.g exprty then + mkCompGenSequential mMethExpr expr (mkRefTupled cenv.g mMethExpr outArgExprs outArgTys) + else + mkRefTupled cenv.g mMethExpr (expr :: outArgExprs) (exprty :: outArgTys) let expr = mkLetsBind mMethExpr outArgTmpBinds expr expr, tyOfExpr cenv.g expr // Handle post-hoc property assignments - let setterExprPrebinders, expr = - if isCheckingAttributeCall then - [], expr - elif isNil finalAssignedItemSetters then - [], expr - else - // This holds the result of the call - let objv, objExpr = mkMutableCompGenLocal mMethExpr "returnVal" exprty // mutable in case it's a struct - // This expression mutates the properties on the result of the call - let setterExprPrebinders, propSetExpr = - (mkUnit cenv.g mMethExpr, finalAssignedItemSetters) ||> List.mapFold (fun acc (AssignedItemSetter(id, setter, CallerArg(callerArgTy, m, isOptCallerArg, argExpr))) -> - if isOptCallerArg then error(Error(FSComp.SR.tcInvalidOptionalAssignmentToPropertyOrField(), m)) - - let argExprPrebinder, action, defnItem = - match setter with - | AssignedPropSetter (pinfo, pminfo, pminst) -> - MethInfoChecks cenv.g cenv.amap true None [objExpr] ad m pminfo - let calledArgTy = List.head (List.head (pminfo.GetParamTypes(cenv.amap, m, pminst))) - let argExprPrebinder, argExpr = coerceExpr false calledArgTy ReflectedArgInfo.None callerArgTy m argExpr - let mut = (if isStructTy cenv.g (tyOfExpr cenv.g objExpr) then DefinitelyMutates else PossiblyMutates) - let action = BuildPossiblyConditionalMethodCall cenv env mut m true pminfo NormalValUse pminst [objExpr] [argExpr] |> fst - argExprPrebinder, action, Item.Property (pinfo.PropertyName, [pinfo]) - - | AssignedILFieldSetter finfo -> - // Get or set instance IL field - ILFieldInstanceChecks cenv.g cenv.amap ad m finfo - let calledArgTy = finfo.FieldType (cenv.amap, m) - let argExprPrebinder, argExpr = coerceExpr false calledArgTy ReflectedArgInfo.None callerArgTy m argExpr - let action = BuildILFieldSet cenv.g m objExpr finfo argExpr - argExprPrebinder, action, Item.ILField finfo - - | AssignedRecdFieldSetter rfinfo -> - RecdFieldInstanceChecks cenv.g cenv.amap ad m rfinfo - let calledArgTy = rfinfo.FieldType - CheckRecdFieldMutation m denv rfinfo - let argExprPrebinder, argExpr = coerceExpr false calledArgTy ReflectedArgInfo.None callerArgTy m argExpr - let action = BuildRecdFieldSet cenv.g m objExpr rfinfo argExpr - argExprPrebinder, action, Item.RecdField rfinfo - - // Record the resolution for the Language Service - let item = Item.SetterArg (id, defnItem) - CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, ad) - - argExprPrebinder, mkCompGenSequential m acc action) - - // now put them together - let expr = mkCompGenLet mMethExpr objv expr (mkCompGenSequential mMethExpr propSetExpr objExpr) - setterExprPrebinders, expr - - // Build the lambda expression if any - let expr = + let setterExprPrebinders, callExpr3 = + let expr = callExpr2 + if isCheckingAttributeCall then + [], expr + elif isNil finalAssignedItemSetters then + [], expr + else + // This holds the result of the call + let objv, objExpr = mkMutableCompGenLocal mMethExpr "returnVal" exprty // mutable in case it's a struct + + // Build the expression that mutates the properties on the result of the call + let setterExprPrebinders, propSetExpr = + (mkUnit cenv.g mMethExpr, finalAssignedItemSetters) ||> List.mapFold (fun acc assignedItemSetter -> + let argExprPrebinder, action, m = TcSetterArgExpr cenv env denv objExpr ad assignedItemSetter + argExprPrebinder, mkCompGenSequential m acc action) + + // now put them together + let expr = mkCompGenLet mMethExpr objv expr (mkCompGenSequential mMethExpr propSetExpr objExpr) + setterExprPrebinders, expr + + // Build the lambda expression if any, if the method is used as a first-class value + let callExpr4 = + let expr = callExpr3 match lambdaVars with | None -> expr | Some curriedLambdaVars -> @@ -10269,7 +10691,8 @@ and TcMethodApplication | _ -> mkMultiLambda mMethExpr vs (expr, tyOfExpr cenv.g expr) List.foldBack mkLambda curriedLambdaVars expr - let expr, tpenv = + let callExpr5, tpenv = + let expr = callExpr4 match unnamedDelayedCallerArgExprOpt with | Some synArgExpr -> match lambdaVars with @@ -10282,15 +10705,53 @@ and TcMethodApplication expr, tpenv // Apply the PreBinders, if any - let expr = (expr, setterExprPrebinders) ||> List.fold (fun expr argPreBinder -> match argPreBinder with None -> expr | Some f -> f expr) - let expr = (expr, paramArrayPreBinders) ||> List.fold (fun expr argPreBinder -> match argPreBinder with None -> expr | Some f -> f expr) - let expr = (expr, allArgsPreBinders) ||> List.fold (fun expr argPreBinder -> match argPreBinder with None -> expr | Some f -> f expr) + let callExpr6 = + let expr = callExpr5 + let expr = (expr, setterExprPrebinders) ||> List.fold (fun expr argPreBinder -> match argPreBinder with None -> expr | Some f -> f expr) + let expr = (expr, paramArrayPreBinders) ||> List.fold (fun expr argPreBinder -> match argPreBinder with None -> expr | Some f -> f expr) + let expr = (expr, allArgsPreBinders) ||> List.fold (fun expr argPreBinder -> match argPreBinder with None -> expr | Some f -> f expr) - let expr = optArgPreBinder expr - let expr = objArgPreBinder expr + let expr = optArgPreBinder expr + let expr = objArgPreBinder expr + expr - (expr, finalAttributeAssignedNamedItems, delayed), tpenv + (callExpr6, finalAttributeAssignedNamedItems, delayed), tpenv +and TcSetterArgExpr cenv env denv objExpr ad (AssignedItemSetter(id, setter, CallerArg(callerArgTy, m, isOptCallerArg, argExpr))) = + if isOptCallerArg then error(Error(FSComp.SR.tcInvalidOptionalAssignmentToPropertyOrField(), m)) + + let argExprPrebinder, action, defnItem = + match setter with + | AssignedPropSetter (pinfo, pminfo, pminst) -> + MethInfoChecks cenv.g cenv.amap true None [objExpr] ad m pminfo + let calledArgTy = List.head (List.head (pminfo.GetParamTypes(cenv.amap, m, pminst))) + let argExprPrebinder, argExpr = MethodCalls.AdjustCallerArgExprForCoercions cenv.g cenv.amap cenv.infoReader ad false calledArgTy ReflectedArgInfo.None callerArgTy m argExpr + let mut = (if isStructTy cenv.g (tyOfExpr cenv.g objExpr) then DefinitelyMutates else PossiblyMutates) + let action = BuildPossiblyConditionalMethodCall cenv env mut m true pminfo NormalValUse pminst [objExpr] [argExpr] |> fst + argExprPrebinder, action, Item.Property (pinfo.PropertyName, [pinfo]) + + | AssignedILFieldSetter finfo -> + // Get or set instance IL field + ILFieldInstanceChecks cenv.g cenv.amap ad m finfo + let calledArgTy = finfo.FieldType (cenv.amap, m) + let argExprPrebinder, argExpr = MethodCalls.AdjustCallerArgExprForCoercions cenv.g cenv.amap cenv.infoReader ad false calledArgTy ReflectedArgInfo.None callerArgTy m argExpr + let action = BuildILFieldSet cenv.g m objExpr finfo argExpr + argExprPrebinder, action, Item.ILField finfo + + | AssignedRecdFieldSetter rfinfo -> + RecdFieldInstanceChecks cenv.g cenv.amap ad m rfinfo + let calledArgTy = rfinfo.FieldType + CheckRecdFieldMutation m denv rfinfo + let argExprPrebinder, argExpr = MethodCalls.AdjustCallerArgExprForCoercions cenv.g cenv.amap cenv.infoReader ad false calledArgTy ReflectedArgInfo.None callerArgTy m argExpr + let action = BuildRecdFieldSet cenv.g m objExpr rfinfo argExpr + argExprPrebinder, action, Item.RecdField rfinfo + + // Record the resolution for the Language Service + let item = Item.SetterArg (id, defnItem) + CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, ad) + + argExprPrebinder, action, m + and TcUnnamedMethodArgs cenv env lambdaPropagationInfo tpenv args = List.mapiFoldSquared (TcUnnamedMethodArg cenv env) (lambdaPropagationInfo, tpenv) args @@ -10393,7 +10854,7 @@ and bindLetRec (binds: Bindings) m e = if isNil binds then e else - Expr.LetRec (binds, e, m, NewFreeVarsCache()) + Expr.LetRec (binds, e, m, Construct.NewFreeVarsCache()) /// Check for duplicate bindings in simple recursive patterns and CheckRecursiveBindingIds binds = @@ -10418,7 +10879,7 @@ and TcLinearExprs bodyChecker cenv env overallTy tpenv isCompExpr expr cont = let env = ShrinkContext env m e2.Range // tailcall TcLinearExprs bodyChecker cenv env overallTy tpenv isCompExpr e2 (fun (e2', tpenv) -> - cont (Expr.Sequential(e1', e2', NormalSeq, sp, m), tpenv)) + cont (Expr.Sequential (e1', e2', NormalSeq, sp, m), tpenv)) | SynExpr.LetOrUse (isRec, isUse, binds, body, m) when not (isUse && isCompExpr) -> if isRec then @@ -10457,15 +10918,15 @@ and TcLinearExprs bodyChecker cenv env overallTy tpenv isCompExpr expr cont = match synElseExprOpt with | None -> let elseExpr = mkUnit cenv.g mIfToThen - let spElse = SuppressSequencePointAtTarget // the fake 'unit' value gets exactly the same range as spIfToThen - let overallExpr = primMkCond spIfToThen SequencePointAtTarget spElse m overallTy boolExpr thenExpr elseExpr + let spElse = DebugPointForTarget.No // the fake 'unit' value gets exactly the same range as spIfToThen + let overallExpr = primMkCond spIfToThen DebugPointForTarget.Yes spElse m overallTy boolExpr thenExpr elseExpr cont (overallExpr, tpenv) | Some synElseExpr -> let env = { env with eContextInfo = ContextInfo.ElseBranchResult synElseExpr.Range } // tailcall TcLinearExprs bodyChecker cenv env overallTy tpenv isCompExpr synElseExpr (fun (elseExpr, tpenv) -> - let resExpr = primMkCond spIfToThen SequencePointAtTarget SequencePointAtTarget m overallTy boolExpr thenExpr elseExpr + let resExpr = primMkCond spIfToThen DebugPointForTarget.Yes DebugPointForTarget.Yes m overallTy boolExpr thenExpr elseExpr cont (resExpr, tpenv)) | _ -> @@ -10480,7 +10941,7 @@ and TcAndPatternCompileMatchClauses mExpr matchm actionOnFailure cenv inputExprO and TcMatchPattern cenv inputTy env tpenv (pat: SynPat, optWhenExpr) = let m = pat.Range let patf', (tpenv, names, _) = TcPat WarnOnUpperCase cenv env None (ValInline.Optional, permitInferTypars, noArgOrRetAttribs, false, None, false) (tpenv, Map.empty, Set.empty) inputTy pat - let envinner, values, vspecMap = MakeAndPublishSimpleVals cenv env m names false + let envinner, values, vspecMap = MakeAndPublishSimpleValsForMergedScope cenv env m names let optWhenExpr', tpenv = match optWhenExpr with | Some whenExpr -> @@ -10491,8 +10952,8 @@ and TcMatchPattern cenv inputTy env tpenv (pat: SynPat, optWhenExpr) = patf' (TcPatPhase2Input (values, true)), optWhenExpr', NameMap.range vspecMap, envinner, tpenv and TcMatchClauses cenv inputTy resultTy env tpenv clauses = - let first = ref true - let isFirst() = if !first then first := false; true else false + let mutable first = true + let isFirst() = if first then first <- false; true else false List.mapFold (fun clause -> TcMatchClause cenv inputTy resultTy env (isFirst()) clause) tpenv clauses and TcMatchClause cenv inputTy resultTy env isFirst tpenv (Clause(pat, optWhenExpr, e, patm, spTgt)) = @@ -10520,7 +10981,7 @@ and mkConvToNativeInt (g: TcGlobals) e m = Expr.Op (TOp.ILAsm ([ AI_conv ILBasic /// Fix up the r.h.s. of a 'use x = fixed expr' and TcAndBuildFixedExpr cenv env (overallPatTy, fixedExpr, overallExprTy, mBinding) = - warning(PossibleUnverifiableCode(mBinding)) + warning(PossibleUnverifiableCode mBinding) match overallExprTy with | ty when isByrefTy cenv.g ty -> let okByRef = @@ -10528,7 +10989,7 @@ and TcAndBuildFixedExpr cenv env (overallPatTy, fixedExpr, overallExprTy, mBindi | Expr.Op (op, tyargs, args, _) -> match op, tyargs, args with | TOp.ValFieldGetAddr (rfref, _), _, [_] -> not rfref.Tycon.IsStructOrEnumTycon - | TOp.ILAsm ([ I_ldflda (fspec)], _), _, _ -> fspec.DeclaringType.Boxity = ILBoxity.AsObject + | TOp.ILAsm ([ I_ldflda fspec], _), _, _ -> fspec.DeclaringType.Boxity = ILBoxity.AsObject | TOp.ILAsm ([ I_ldelema _], _), _, _ -> true | TOp.RefAddrGet _, _, _ -> true | _ -> false @@ -10606,15 +11067,15 @@ and TcNormalizedBinding declKind (cenv: cenv) env tpenv overallTy safeThisValOpt | ExpressionBinding, _, _ -> envinner.eCallerMemberName | _, _, SynPat.Named(_, name, _, _, _) -> match memberFlagsOpt with - | Some(memberFlags) -> + | Some memberFlags -> match memberFlags.MemberKind with - | MemberKind.PropertyGet | MemberKind.PropertySet | MemberKind.PropertyGetSet -> Some(name.idText.Substring(4)) + | MemberKind.PropertyGet | MemberKind.PropertySet | MemberKind.PropertyGetSet -> Some(name.idText.Substring 4) | MemberKind.ClassConstructor -> Some(".ctor") | MemberKind.Constructor -> Some(".ctor") | _ -> Some(name.idText) | _ -> Some(name.idText) - | ClassLetBinding(false), DoBinding, _ -> Some(".ctor") - | ClassLetBinding(true), DoBinding, _ -> Some(".cctor") + | ClassLetBinding false, DoBinding, _ -> Some(".ctor") + | ClassLetBinding true, DoBinding, _ -> Some(".cctor") | ModuleOrMemberBinding, StandaloneExpression, _ -> Some(".cctor") | _, _, _ -> envinner.eCallerMemberName @@ -10643,7 +11104,7 @@ and TcNormalizedBinding declKind (cenv: cenv) env tpenv overallTy safeThisValOpt spatsL |> List.map (SynInfo.InferSynArgInfoFromSimplePats >> List.map (SynInfo.AttribsOfArgData >> TcAttrs AttributeTargets.Parameter)) let retAttribs = match rtyOpt with - | Some (SynBindingReturnInfo(_, _, retAttrs)) -> TcAttrs AttributeTargets.ReturnValue retAttrs + | Some (SynBindingReturnInfo(_, _, Attributes retAttrs)) -> TcAttrs AttributeTargets.ReturnValue retAttrs | None -> [] let argAndRetAttribs = ArgAndRetAttribs(argAttribs, retAttribs) @@ -10652,7 +11113,7 @@ and TcNormalizedBinding declKind (cenv: cenv) env tpenv overallTy safeThisValOpt errorR(Error(FSComp.SR.tcDefaultValueAttributeRequiresVal(), mBinding)) let isThreadStatic = isThreadOrContextStatic cenv.g valAttribs - if isThreadStatic then errorR(DeprecatedThreadStaticBindingWarning(mBinding)) + if isThreadStatic then errorR(DeprecatedThreadStaticBindingWarning mBinding) if isVolatile then match declKind with @@ -10701,7 +11162,7 @@ and TcNormalizedBinding declKind (cenv: cenv) env tpenv overallTy safeThisValOpt // Check the pattern of the l.h.s. of the binding let tcPatPhase2, (tpenv, nameToPrelimValSchemeMap, _) = - TcPat AllIdsOK cenv envinner (Some(partialValReprInfo)) (inlineFlag, flex, argAndRetAttribs, isMutable, vis, compgen) (tpenv, NameMap.empty, Set.empty) overallPatTy pat + TcPat AllIdsOK cenv envinner (Some partialValReprInfo) (inlineFlag, flex, argAndRetAttribs, isMutable, vis, compgen) (tpenv, NameMap.empty, Set.empty) overallPatTy pat // Add active pattern result names to the environment @@ -10722,7 +11183,7 @@ and TcNormalizedBinding declKind (cenv: cenv) env tpenv overallTy safeThisValOpt apinfo.ActiveTagsWithRanges |> List.iteri (fun i (_tag, tagRange) -> let item = Item.ActivePatternResult(apinfo, cenv.g.unit_ty, i, tagRange) - CallNameResolutionSink cenv.tcSink (tagRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Binding, env.DisplayEnv, env.eAccessRights)) + CallNameResolutionSink cenv.tcSink (tagRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Binding, env.AccessRights)) { envinner with eNameResEnv = AddActivePatternResultTagsToNameEnv apinfo envinner.eNameResEnv ty m } | None -> @@ -10782,7 +11243,7 @@ and TcLiteral cenv overallTy env tpenv (attrs, synLiteralValExpr) = if hasLiteralAttr then let literalValExpr, _ = TcExpr cenv overallTy env tpenv synLiteralValExpr match EvalLiteralExprOrAttribArg cenv.g literalValExpr with - | Expr.Const(c, _, ty) -> + | Expr.Const (c, _, ty) -> if c = Const.Zero && isStructTy cenv.g ty then warning(Error(FSComp.SR.tcIllegalStructTypeForConstantExpression(), synLiteralValExpr.Range)) false, None @@ -10844,7 +11305,7 @@ and TcAttribute canFail cenv (env: TcEnv) attrTgt (synAttr: SynAttribute) = let tycon = (typath @ [tyid]) let ad = env.eAccessRights match ResolveTypeLongIdent cenv.tcSink cenv.nameResolver ItemOccurence.UseInAttribute OpenQualified env.eNameResEnv ad tycon TypeNameResolutionStaticArgsInfo.DefiniteEmpty PermitDirectReferenceToGeneratedType.No with - | Exception err -> raze(err) + | Exception err -> raze err | _ -> success(TcTypeAndRecover cenv NoNewTypars CheckCxs ItemOccurence.UseInAttribute env tpenv (SynType.App(SynType.LongIdent(LongIdentWithDots(tycon, [])), None, [], [], None, false, mAttr)) ) ForceRaise ((try1 (tyid.idText + "Attribute")) |> ResultOrException.otherwise (fun () -> (try1 tyid.idText))) @@ -10881,11 +11342,11 @@ and TcAttribute canFail cenv (env: TcEnv) attrTgt (synAttr: SynAttribute) = (validOnDefault, inheritedDefault) else match (TryFindFSharpAttribute cenv.g cenv.g.attrib_AttributeUsageAttribute tcref.Attribs) with - | Some(Attrib(_, _, [ AttribInt32Arg(validOn) ], _, _, _, _)) -> + | Some(Attrib(_, _, [ AttribInt32Arg validOn ], _, _, _, _)) -> (validOn, inheritedDefault) - | Some(Attrib(_, _, [ AttribInt32Arg(validOn) + | Some(Attrib(_, _, [ AttribInt32Arg validOn AttribBoolArg(_allowMultiple) - AttribBoolArg(inherited)], _, _, _, _)) -> + AttribBoolArg inherited], _, _, _, _)) -> (validOn, inherited) | Some _ -> warning(Error(FSComp.SR.tcUnexpectedConditionInImportedAssembly(), mAttr)) @@ -10959,22 +11420,22 @@ and TcAttribute canFail cenv (env: TcEnv) attrTgt (synAttr: SynAttribute) = errorR(Error(FSComp.SR.tcPropertyOrFieldNotFoundInAttribute(), m)) id.idText, false, cenv.g.unit_ty let propNameItem = Item.SetterArg(id, setterItem) - CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, propNameItem, propNameItem, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, ad) + CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, propNameItem, emptyTyparInst, ItemOccurence.Use, ad) AddCxTypeMustSubsumeType ContextInfo.NoContext env.DisplayEnv cenv.css m NoTrace argty argtyv AttribNamedArg(nm, argty, isProp, mkAttribExpr callerArgExpr)) match expr with - | Expr.Op(TOp.ILCall(_, _, valu, _, _, _, _, ilMethRef, [], [], _rtys), [], args, m) -> + | Expr.Op (TOp.ILCall (_, _, valu, _, _, _, _, ilMethRef, [], [], _rtys), [], args, m) -> if valu then error (Error(FSComp.SR.tcCustomAttributeMustBeReferenceType(), m)) if args.Length <> ilMethRef.ArgTypes.Length then error (Error(FSComp.SR.tcCustomAttributeArgumentMismatch(), m)) let args = args |> List.map mkAttribExpr - Attrib(tcref, ILAttrib(ilMethRef), args, namedAttribArgMap, isAppliedToGetterOrSetter, Some constrainedTgts, m) + Attrib(tcref, ILAttrib ilMethRef, args, namedAttribArgMap, isAppliedToGetterOrSetter, Some constrainedTgts, m) - | Expr.App((InnerExprPat(ExprValWithPossibleTypeInst(vref, _, _, _))), _, _, args, _) -> - let args = args |> List.collect (function Expr.Const(Const.Unit, _, _) -> [] | expr -> tryDestRefTupleExpr expr) |> List.map mkAttribExpr - Attrib(tcref, FSAttrib(vref), args, namedAttribArgMap, isAppliedToGetterOrSetter, Some constrainedTgts, mAttr) + | Expr.App ((InnerExprPat(ExprValWithPossibleTypeInst(vref, _, _, _))), _, _, args, _) -> + let args = args |> List.collect (function Expr.Const (Const.Unit, _, _) -> [] | expr -> tryDestRefTupleExpr expr) |> List.map mkAttribExpr + Attrib(tcref, FSAttrib vref, args, namedAttribArgMap, isAppliedToGetterOrSetter, Some constrainedTgts, mAttr) | _ -> error (Error(FSComp.SR.tcCustomAttributeMustInvokeConstructor(), mAttr)) @@ -11027,7 +11488,7 @@ and TcLetBinding cenv isUse env containerInfo declKind tpenv (synBinds, synBinds // Canonicalize constraints prior to generalization let denv = env.DisplayEnv - GeneralizationHelpers.CanonicalizePartialInferenceProblem (cenv, denv, synBindsRange) + ConstraintSolver.CanonicalizePartialInferenceProblem cenv.css denv synBindsRange (checkedBinds |> List.collect (fun tbinfo -> let (CheckedBindingInfo(_, _, _, _, flex, _, _, _, tauTy, _, _, _, _, _)) = tbinfo let (ExplicitTyparInfo(_, declaredTypars, _)) = flex @@ -11052,7 +11513,7 @@ and TcLetBinding cenv isUse env containerInfo declKind tpenv (synBinds, synBinds [] else let freeInEnv = lazyFreeInEnv.Force() - let canConstrain = GeneralizationHelpers.CanGeneralizeConstrainedTyparsForDecl(declKind) + let canConstrain = GeneralizationHelpers.CanGeneralizeConstrainedTyparsForDecl declKind GeneralizationHelpers.ComputeAndGeneralizeGenericTypars (cenv, denv, m, freeInEnv, canInferTypars, canConstrain, inlineFlag, Some rhsExpr, allDeclaredTypars, maxInferredTypars, tauTy, false) @@ -11075,7 +11536,7 @@ and TcLetBinding cenv isUse env containerInfo declKind tpenv (synBinds, synBinds // Don't introduce temporary or 'let' for 'match against wild' or 'match against unit' | (TPat_wild _ | TPat_const (Const.Unit, _)) when not isUse && not isFixed && isNil generalizedTypars -> - let mkSequentialBind (tm, tmty) = (mkSequential SequencePointsAtSeq m rhsExpr tm, tmty) + let mkSequentialBind (tm, tmty) = (mkSequential DebugPointAtSequential.Both m rhsExpr tm, tmty) (buildExpr >> mkSequentialBind, env, tpenv) | _ -> @@ -11116,7 +11577,7 @@ and TcLetBinding cenv isUse env containerInfo declKind tpenv (synBinds, synBinds // Add the compilation of the pattern to the bodyExpr we get from mkCleanup let mkPatBind (bodyExpr, bodyExprTy) = let valsDefinedByMatching = ListSet.remove valEq patternInputTmp allValsDefinedByPattern - let clauses = [TClause(checkedPat2, None, TTarget(valsDefinedByMatching, bodyExpr, SuppressSequencePointAtTarget), m)] + let clauses = [TClause(checkedPat2, None, TTarget(valsDefinedByMatching, bodyExpr, DebugPointForTarget.No), m)] let matchx = CompilePatternForMatch cenv env m m true ThrowIncompleteMatchException (patternInputTmp, generalizedTypars, Some rhsExpr) clauses tauTy bodyExprTy let matchx = if (DeclKind.ConvertToLinearBindings declKind) then LinearizeTopMatch cenv.g altActualParent matchx else matchx matchx, bodyExprTy @@ -11127,7 +11588,7 @@ and TcLetBinding cenv isUse env containerInfo declKind tpenv (synBinds, synBinds (allValsDefinedByPattern, (bodyExpr, bodyExprTy)) ||> List.foldBack (fun v (bodyExpr, bodyExprTy) -> AddCxTypeMustSubsumeType ContextInfo.NoContext denv cenv.css v.Range NoTrace cenv.g.system_IDisposable_ty v.Type let cleanupE = BuildDisposableCleanup cenv env m v - mkTryFinally cenv.g (bodyExpr, cleanupE, m, bodyExprTy, SequencePointInBodyOfTry, NoSequencePointAtFinally), bodyExprTy) + mkTryFinally cenv.g (bodyExpr, cleanupE, m, bodyExprTy, DebugPointAtTry.Body, DebugPointAtFinally.No), bodyExprTy) else (bodyExpr, bodyExprTy) @@ -11140,7 +11601,7 @@ and TcLetBinding cenv isUse env containerInfo declKind tpenv (synBinds, synBinds /// RECAP: /// The LHS of let-bindings are patterns. /// These patterns could fail, e.g. "let Some x = ...". -/// So letbindings could contain a fork at a match construct, with one branch being the match failure. +/// So let bindings could contain a fork at a match construct, with one branch being the match failure. /// If bindings are linearised, then this fork is pushed to the RHS. /// In this case, the let bindings type check to a sequence of bindings. and TcLetBindings cenv env containerInfo declKind tpenv (binds, bindsm, scopem) = @@ -11162,7 +11623,7 @@ and CheckMemberFlags optIntfSlotTy newslotsOK overridesOK memberFlags m = if overridesOK = ErrorOnOverrides && memberFlags.MemberKind = MemberKind.Constructor then errorR(Error(FSComp.SR.tcConstructorsIllegalInAugmentation(), m)) if overridesOK = WarnOnOverrides && memberFlags.IsOverrideOrExplicitImpl && Option.isNone optIntfSlotTy then - warning(OverrideInIntrinsicAugmentation(m)) + warning(OverrideInIntrinsicAugmentation m) if overridesOK = ErrorOnOverrides && memberFlags.IsOverrideOrExplicitImpl then error(Error(FSComp.SR.tcMethodOverridesIllegalHere(), m)) @@ -11210,7 +11671,7 @@ and ApplyAbstractSlotInference (cenv: cenv) (envinner: TcEnv) (bindingTy, m, syn | Some (ty, abstractSlots) -> // The interface type is in terms of the type's type parameters. // We need a signature in terms of the values' type parameters. - ty, Some(abstractSlots) + ty, Some abstractSlots | None -> tcrefObjTy, None @@ -11247,7 +11708,7 @@ and ApplyAbstractSlotInference (cenv: cenv) (envinner: TcEnv) (bindingTy, m, syn |> Seq.map (sprintf "%s %s" System.Environment.NewLine) |> String.concat "" - errorR(Error(FSComp.SR.tcOverrideArityMismatch(details), memberId.idRange)) + errorR(Error(FSComp.SR.tcOverrideArityMismatch details, memberId.idRange)) [] | _ -> [] // check that method to override is sealed is located at CheckOverridesAreAllUsedOnce (typrelns.fs) // We hit this case when it is ambiguous which abstract method is being implemented. @@ -11367,7 +11828,7 @@ and CheckForNonAbstractInterface declKind tcref memberFlags m = error(Error(FSComp.SR.tcConcreteMembersIllegalInInterface(), m)) //------------------------------------------------------------------------- -// TcLetrec - AnalyzeAndMakeAndPublishRecursiveValue(s) +// TcLetrec - AnalyzeAndMakeAndPublishRecursiveValue s //------------------------------------------------------------------------ and AnalyzeRecursiveStaticMemberOrValDecl @@ -11383,7 +11844,7 @@ and AnalyzeRecursiveStaticMemberOrValDecl let vis = CombineVisibilityAttribs vis1 vis2 mBinding // Check if we're defining a member, in which case generate the internal unique - // name for the member and the information about which type it is agumenting + // name for the member and the information about which type it is augmenting match tcrefContainerInfo, memberFlagsOpt with | (Some(MemberOrValContainerInfo(tcref, optIntfSlotTy, baseValOpt, _safeInitInfo, declaredTyconTypars)), Some memberFlags) -> @@ -11437,7 +11898,7 @@ and AnalyzeRecursiveStaticMemberOrValDecl let isExtrinsic = (declKind = ExtrinsicExtensionBinding) MakeMemberDataAndMangledNameForMemberVal(cenv.g, tcref, isExtrinsic, bindingAttribs, [], memberFlags, valSynInfo, id, false) - envinner, tpenv, id, None, Some(memberInfo), vis, vis2, safeThisValOpt, enclosingDeclaredTypars, baseValOpt, flex, bindingRhs, declaredTypars + envinner, tpenv, id, None, Some memberInfo, vis, vis2, safeThisValOpt, enclosingDeclaredTypars, baseValOpt, flex, bindingRhs, declaredTypars // non-member bindings. How easy. | _ -> @@ -11495,7 +11956,7 @@ and AnalyzeRecursiveInstanceMemberDecl // each member that may use it. let baseValOpt = match GetSuperTypeOfType cenv.g cenv.amap mBinding objTy with - | Some(superTy) -> MakeAndPublishBaseVal cenv envinner (match baseValOpt with None -> None | Some v -> Some v.Id) superTy + | Some superTy -> MakeAndPublishBaseVal cenv envinner (match baseValOpt with None -> None | Some v -> Some v.Id) superTy | None -> None let memberInfo = MakeMemberDataAndMangledNameForMemberVal(cenv.g, tcref, isExtrinsic, bindingAttribs, optInferredImplSlotTys, memberFlags, valSynInfo, memberId, false) @@ -11511,7 +11972,11 @@ and AnalyzeRecursiveInstanceMemberDecl | _ -> error(Error(FSComp.SR.tcRecursiveBindingsWithMembersMustBeDirectAugmentation(), mBinding)) -and AnalyzeRecursiveDecl (cenv, envinner, tpenv, declKind, synTyparDecls, declaredTypars, thisIdOpt, valSynInfo, flex, newslotsOK, overridesOK, vis1, declPattern, bindingAttribs, tcrefContainerInfo, memberFlagsOpt, ty, bindingRhs, mBinding) = +and AnalyzeRecursiveDecl (cenv, envinner, tpenv, declKind, synTyparDecls, declaredTypars, + thisIdOpt, valSynInfo, flex, newslotsOK, overridesOK, vis1, + declPattern, bindingAttribs, tcrefContainerInfo, + memberFlagsOpt, ty, bindingRhs, mBinding) = + let rec analyzeRecursiveDeclPat tpenv p = match p with | SynPat.FromParseError(pat', _) -> analyzeRecursiveDeclPat tpenv pat' @@ -11603,7 +12068,7 @@ and AnalyzeAndMakeAndPublishRecursiveValue overridesOK isGeneratedEventVal cenv let isComplete = ComputeIsComplete enclosingDeclaredTypars declaredTypars ty // NOTE: The type scheme here is normally not 'complete'!!!! The type is more or less just a type variable at this point. - // NOTE: toparity, type and typars get fixed-up after inference + // NOTE: top arity, type and typars get fixed-up after inference let prelimTyscheme = TypeScheme(enclosingDeclaredTypars@declaredTypars, ty) let partialValReprInfo = TranslateTopValSynInfo mBinding (TcAttributes cenv envinner) valSynInfo let topValInfo = UseSyntacticArity declKind prelimTyscheme partialValReprInfo @@ -11622,15 +12087,14 @@ and AnalyzeAndMakeAndPublishRecursiveValue overridesOK isGeneratedEventVal cenv List.concat extraBindings, List.concat extraValues, tpenv, recBindIdx // Create the value - let vspec = MakeAndPublishVal cenv envinner (altActualParent, false, declKind, ValInRecScope(isComplete), prelimValScheme, bindingAttribs, bindingXmlDoc, konst, isGeneratedEventVal) + let vspec = MakeAndPublishVal cenv envinner (altActualParent, false, declKind, ValInRecScope isComplete, prelimValScheme, bindingAttribs, bindingXmlDoc, konst, isGeneratedEventVal) // Suppress hover tip for "get" and "set" at property definitions, where toolId <> bindingId match toolIdOpt with - | Some tid when not tid.idRange.IsSynthetic && tid.idRange <> bindingId.idRange -> + | Some tid when not tid.idRange.IsSynthetic && not (Range.equals tid.idRange bindingId.idRange) -> let item = Item.Value (mkLocalValRef vspec) - CallNameResolutionSink cenv.tcSink (tid.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.RelatedText, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (tid.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.RelatedText, env.eAccessRights) | _ -> () - let mangledId = ident(vspec.LogicalName, vspec.Range) // Reconstitute the binding with the unique name @@ -11652,7 +12116,7 @@ and AnalyzeAndMakeAndPublishRecursiveValue overridesOK isGeneratedEventVal cenv { SyntacticBinding = revisedBinding RecBindingInfo = rbinfo } - ((primaryBinding::extraBindings), (vspec::extraValues)), (tpenv, recBindIdx) + ((primaryBinding :: extraBindings), (vspec :: extraValues)), (tpenv, recBindIdx) and AnalyzeAndMakeAndPublishRecursiveValues overridesOK cenv env tpenv binds = @@ -11746,7 +12210,7 @@ and TcLetrecBinding uncheckedRecBindsTable.Remove rbind.RecBindingInfo.Val.Stamp // Add one binding to the candidates eligible for generalization - let preGeneralizationRecBinds = (preGeneralizationRecBind::preGeneralizationRecBinds) + let preGeneralizationRecBinds = (preGeneralizationRecBind :: preGeneralizationRecBinds) // Incrementally generalize as many bindings as we can TcIncrementalLetRecGeneralization cenv scopem (envNonRec, generalizedRecBinds, preGeneralizationRecBinds, tpenv, uncheckedRecBindsTable) @@ -11780,7 +12244,7 @@ and TcIncrementalLetRecGeneralization cenv scopem // - This table is usually much smaller than the number of remaining forward declarations ? e.g. in the pathological case you mentioned below this table is size 1. // - If a forward declaration does not have an entry in this table then its type can't involve any inference variables from the declarations we have already checked. // - So by scanning the domain of this table we can reduce the complexity down to something like O(n * average-number-of-forward-calls). - // - For a fully connected programs or programs where every forward declaration is subject to a forward call, this would be quadratic. However we do not expect callgraphs to be like this in practice + // - For a fully connected programs or programs where every forward declaration is subject to a forward call, this would be quadratic. However we do not expect call graphs to be like this in practice // // Hence we use the recursive-uses table to guide the process of scraping forward references for frozen types // If the is no entry in the recursive use table then a forward binding has never been used and @@ -11903,7 +12367,7 @@ and TcIncrementalLetRecGeneralization cenv scopem else let supportForBindings = newGeneralizableBindings |> List.collect (TcLetrecComputeSupportForBinding cenv) - GeneralizationHelpers.CanonicalizePartialInferenceProblem (cenv, denv, scopem) supportForBindings + ConstraintSolver.CanonicalizePartialInferenceProblem cenv.css denv scopem supportForBindings let generalizedTyparsL = newGeneralizableBindings |> List.map (TcLetrecComputeAndGeneralizeGenericTyparsForBinding cenv denv freeInEnv) @@ -11952,7 +12416,7 @@ and TcLetrecComputeAndGeneralizeGenericTyparsForBinding cenv denv freeInEnv (pgr let maxInferredTypars = freeInTypeLeftToRight cenv.g false tau let canGeneralizeConstrained = GeneralizationHelpers.CanGeneralizeConstrainedTyparsForDecl rbinfo.DeclKind - let generalizedTypars = GeneralizationHelpers.ComputeAndGeneralizeGenericTypars (cenv, denv, m, freeInEnv, canInferTypars, canGeneralizeConstrained, inlineFlag, Some(expr), allDeclaredTypars, maxInferredTypars, tau, isCtor) + let generalizedTypars = GeneralizationHelpers.ComputeAndGeneralizeGenericTypars (cenv, denv, m, freeInEnv, canInferTypars, canGeneralizeConstrained, inlineFlag, Some expr, allDeclaredTypars, maxInferredTypars, tau, isCtor) generalizedTypars /// Compute the type variables which may have member constraints that need to be canonicalized prior to generalization @@ -11977,7 +12441,7 @@ and TcLetrecGeneralizeBinding cenv denv generalizedTypars (pgrbind: PreGeneraliz let _, tau = vspec.TypeScheme - let pvalscheme1 = PrelimValScheme1(vspec.Id, flex, tau, Some(partialValReprInfo), memberInfoOpt, false, inlineFlag, NormalVal, argAttribs, vis, compgen) + let pvalscheme1 = PrelimValScheme1(vspec.Id, flex, tau, Some partialValReprInfo, memberInfoOpt, false, inlineFlag, NormalVal, argAttribs, vis, compgen) let pvalscheme2 = GeneralizeVal cenv denv enclosingDeclaredTypars generalizedTypars pvalscheme1 let valscheme = UseCombinedArity cenv.g declKind expr pvalscheme2 @@ -12147,8 +12611,8 @@ and TcLetrec overridesOK cenv env tpenv (binds, bindsm, scopem) = let results = EliminateInitializationGraphs - (fun _ -> failwith "unreachable 2 - no type definitions in recursivve group") - (fun _ _ -> failwith "unreachable 3 - no type definitions in recursivve group") + (fun _ -> failwith "unreachable 2 - no type definitions in recursive group") + (fun _ _ -> failwith "unreachable 3 - no type definitions in recursive group") id (fun morpher oldBinds -> morpher oldBinds) cenv.g mustHaveArity env.DisplayEnv [MutRecShape.Lets bindsWithoutLaziness] bindsm @@ -12169,7 +12633,7 @@ and TcLetrec overridesOK cenv env tpenv (binds, bindsm, scopem) = let TcAndPublishValSpec (cenv, env, containerInfo: ContainerInfo, declKind, memFlagsOpt, tpenv, valSpfn) = - let (ValSpfn (synAttrs, _, SynValTyparDecls (synTypars, synCanInferTypars, _), _, _, isInline, mutableFlag, doc, vis, literalExprOpt, m)) = valSpfn + let (ValSpfn (Attributes synAttrs, _, SynValTyparDecls (synTypars, synCanInferTypars, _), _, _, isInline, mutableFlag, doc, vis, literalExprOpt, m)) = valSpfn GeneralizationHelpers.CheckDeclaredTyparsPermitted(memFlagsOpt, synTypars, m) let canInferTypars = GeneralizationHelpers.ComputeCanInferExtraGeneralizableTypars (containerInfo.ParentRef, synCanInferTypars, memFlagsOpt) @@ -12194,15 +12658,18 @@ let TcAndPublishValSpec (cenv, env, containerInfo: ContainerInfo, declKind, memF let flex = ExplicitTyparInfo(declaredTypars, declaredTypars, synCanInferTypars) - let generalizedTypars = GeneralizationHelpers.ComputeAndGeneralizeGenericTypars(cenv, denv, id.idRange, emptyFreeTypars, canInferTypars, CanGeneralizeConstrainedTypars, inlineFlag, None, allDeclaredTypars, freeInType, ty, false) + let generalizedTypars = + GeneralizationHelpers.ComputeAndGeneralizeGenericTypars(cenv, denv, id.idRange, + emptyFreeTypars, canInferTypars, CanGeneralizeConstrainedTypars, inlineFlag, + None, allDeclaredTypars, freeInType, ty, false) - let valscheme1 = PrelimValScheme1(id, flex, ty, Some(partialValReprInfo), memberInfoOpt, mutableFlag, inlineFlag, NormalVal, noArgOrRetAttribs, vis, false) + let valscheme1 = PrelimValScheme1(id, flex, ty, Some partialValReprInfo, memberInfoOpt, mutableFlag, inlineFlag, NormalVal, noArgOrRetAttribs, vis, false) let valscheme2 = GeneralizeVal cenv denv enclosingDeclaredTypars generalizedTypars valscheme1 let tpenv = HideUnscopedTypars generalizedTypars tpenv - let valscheme = BuildValScheme declKind (Some(partialValReprInfo)) valscheme2 + let valscheme = BuildValScheme declKind (Some partialValReprInfo) valscheme2 let konst = match literalExprOpt with @@ -12232,7 +12699,7 @@ exception NotUpperCaseConstructor of range let CheckNamespaceModuleOrTypeName (g: TcGlobals) (id: Ident) = // type names '[]' etc. are used in fslib - if not g.compilingFslib && id.idText.IndexOfAny(IllegalCharactersInTypeAndNamespaceNames) <> -1 then + if not g.compilingFslib && id.idText.IndexOfAny IllegalCharactersInTypeAndNamespaceNames <> -1 then errorR(Error(FSComp.SR.tcInvalidNamespaceModuleTypeUnionName(), id.idRange)) let CheckDuplicates (idf: _ -> Ident) k elems = @@ -12255,7 +12722,7 @@ module TcRecdUnionAndEnumDeclarations = begin let MakeRecdFieldSpec _cenv env parent (isStatic, konst, ty', attrsForProperty, attrsForField, id, nameGenerated, isMutable, vol, xmldoc, vis, m) = let vis, _ = ComputeAccessAndCompPath env None m vis None parent let vis = CombineReprAccess parent vis - NewRecdField isStatic konst id nameGenerated ty' isMutable vol attrsForProperty attrsForField xmldoc vis false + Construct.NewRecdField isStatic konst id nameGenerated ty' isMutable vol attrsForProperty attrsForField xmldoc vis false let TcFieldDecl cenv env parent isIncrClass tpenv (isStatic, synAttrs, id, nameGenerated, ty, isMutable, xmldoc, vis, m) = let attrs, _ = TcAttributesWithPossibleTargets false cenv env AttributeTargets.FieldDecl synAttrs @@ -12285,21 +12752,14 @@ module TcRecdUnionAndEnumDeclarations = begin rfspec - let TcAnonFieldDecl cenv env parent tpenv nm (Field(attribs, isStatic, idOpt, ty, isMutable, xmldoc, vis, m)) = + let TcAnonFieldDecl cenv env parent tpenv nm (Field(Attributes attribs, isStatic, idOpt, ty, isMutable, xmldoc, vis, m)) = let id = (match idOpt with None -> mkSynId m nm | Some id -> id) - let f = TcFieldDecl cenv env parent false tpenv (isStatic, attribs, id, idOpt.IsNone, ty, isMutable, xmldoc.ToXmlDoc(), vis, m) - match idOpt with - | None -> () - | Some id -> - let item = Item.ArgName(id, f.FormalType, None) - CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Binding, env.DisplayEnv, env.AccessRights) - f + TcFieldDecl cenv env parent false tpenv (isStatic, attribs, id, idOpt.IsNone, ty, isMutable, xmldoc.ToXmlDoc(), vis, m) - - let TcNamedFieldDecl cenv env parent isIncrClass tpenv (Field(attribs, isStatic, id, ty, isMutable, xmldoc, vis, m)) = + let TcNamedFieldDecl cenv env parent isIncrClass tpenv (Field(Attributes attribs, isStatic, id, ty, isMutable, xmldoc, vis, m)) = match id with | None -> error (Error(FSComp.SR.tcFieldRequiresName(), m)) - | Some(id) -> TcFieldDecl cenv env parent isIncrClass tpenv (isStatic, attribs, id, false, ty, isMutable, xmldoc.ToXmlDoc(), vis, m) + | Some id -> TcFieldDecl cenv env parent isIncrClass tpenv (isStatic, attribs, id, false, ty, isMutable, xmldoc.ToXmlDoc(), vis, m) let TcNamedFieldDecls cenv env parent isIncrClass tpenv fields = fields |> List.map (TcNamedFieldDecl cenv env parent isIncrClass tpenv) @@ -12321,38 +12781,39 @@ module TcRecdUnionAndEnumDeclarations = begin let ValidateFieldNames (synFields: SynField list, tastFields: RecdField list) = let seen = Dictionary() for (sf, f) in List.zip synFields tastFields do -#if FABLE_COMPILER - let ok, synField = seen.TryGetValue(f.Name) - if ok then -#else - let mutable synField = Unchecked.defaultof<_> - if seen.TryGetValue(f.Name, &synField) then -#endif + match seen.TryGetValue f.Name with + | true, synField -> match sf, synField with - | Field(_, _, Some(id), _, _, _, _, _), Field(_, _, Some(_), _, _, _, _, _) -> + | Field(_, _, Some id, _, _, _, _, _), Field(_, _, Some(_), _, _, _, _, _) -> error(Error(FSComp.SR.tcFieldNameIsUsedModeThanOnce(id.idText), id.idRange)) - | Field(_, _, Some(id), _, _, _, _, _), Field(_, _, None, _, _, _, _, _) - | Field(_, _, None, _, _, _, _, _), Field(_, _, Some(id), _, _, _, _, _) -> + | Field(_, _, Some id, _, _, _, _, _), Field(_, _, None, _, _, _, _, _) + | Field(_, _, None, _, _, _, _, _), Field(_, _, Some id, _, _, _, _, _) -> error(Error(FSComp.SR.tcFieldNameConflictsWithGeneratedNameForAnonymousField(id.idText), id.idRange)) | _ -> assert false - else + | _ -> seen.Add(f.Name, sf) - let TcUnionCaseDecl cenv env parent thisTy tpenv (UnionCase (synAttrs, id, args, xmldoc, vis, m)) = + let TcUnionCaseDecl cenv env parent thisTy thisTyInst tpenv (UnionCase(Attributes synAttrs, id, args, xmldoc, vis, m)) = let attrs = TcAttributes cenv env AttributeTargets.UnionCaseDecl synAttrs // the attributes of a union case decl get attached to the generated "static factory" method let vis, _ = ComputeAccessAndCompPath env None m vis None parent let vis = CombineReprAccess parent vis CheckUnionCaseName cenv id - let mkName nFields i = if nFields <= 1 then "Item" else "Item"+string (i+1) let rfields, recordTy = match args with | UnionCaseFields flds -> let nFields = flds.Length - let rfields = flds |> List.mapi (fun i fld -> TcAnonFieldDecl cenv env parent tpenv (mkName nFields i) fld) - ValidateFieldNames(flds, rfields) + let rfields = flds |> List.mapi (fun i (Field (idOpt = idOpt) as fld) -> + match idOpt, parent with + | Some fieldId, Parent tcref -> + let item = Item.UnionCaseField (UnionCaseInfo (thisTyInst, UnionCaseRef (tcref, id.idText)), i) + CallNameResolutionSink cenv.tcSink (fieldId.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Binding, env.AccessRights) + | _ -> () + TcAnonFieldDecl cenv env parent tpenv (mkUnionCaseFieldName nFields i) fld) + ValidateFieldNames(flds, rfields) + rfields, thisTy | UnionCaseFullType (ty, arity) -> let ty', _ = TcTypeAndRecover cenv NoNewTypars CheckCxs ItemOccurence.UseInType env tpenv ty @@ -12363,19 +12824,18 @@ module TcRecdUnionAndEnumDeclarations = begin let nFields = argTys.Length let rfields = argTys |> List.mapi (fun i (argty, argInfo) -> - let id = (match argInfo.Name with Some id -> id | None -> mkSynId m (mkName nFields i)) + let id = (match argInfo.Name with Some id -> id | None -> mkSynId m (mkUnionCaseFieldName nFields i)) MakeRecdFieldSpec cenv env parent (false, None, argty, [], [], id, argInfo.Name.IsNone, false, false, XmlDoc.Empty, None, m)) if not (typeEquiv cenv.g recordTy thisTy) then error(Error(FSComp.SR.tcReturnTypesForUnionMustBeSameAsType(), m)) rfields, recordTy - NewUnionCase id rfields recordTy attrs (xmldoc.ToXmlDoc()) vis - + Construct.NewUnionCase id rfields recordTy attrs (xmldoc.ToXmlDoc()) vis - let TcUnionCaseDecls cenv env parent (thisTy: TType) tpenv unionCases = - let unionCases' = unionCases |> List.map (TcUnionCaseDecl cenv env parent thisTy tpenv) + let TcUnionCaseDecls cenv env parent (thisTy: TType) thisTyInst tpenv unionCases = + let unionCases' = unionCases |> List.map (TcUnionCaseDecl cenv env parent thisTy thisTyInst tpenv) unionCases' |> CheckDuplicates (fun uc -> uc.Id) "union case" - let TcEnumDecl cenv env parent thisTy fieldTy (EnumCase (synAttrs, id, v, xmldoc, m)) = + let TcEnumDecl cenv env parent thisTy fieldTy (EnumCase(Attributes synAttrs, id, v, xmldoc, m)) = let attrs = TcAttributes cenv env AttributeTargets.Field synAttrs match v with | SynConst.Bytes _ @@ -12386,7 +12846,7 @@ module TcRecdUnionAndEnumDeclarations = begin let vis, _ = ComputeAccessAndCompPath env None m None None parent let vis = CombineReprAccess parent vis if id.idText = "value__" then errorR(Error(FSComp.SR.tcNotValidEnumCaseName(), id.idRange)) - NewRecdField true (Some v) id false thisTy false false [] attrs (xmldoc.ToXmlDoc()) vis false + Construct.NewRecdField true (Some v) id false thisTy false false [] attrs (xmldoc.ToXmlDoc()) vis false let TcEnumDecls cenv env parent thisTy enumCases = let fieldTy = NewInferenceType () @@ -12418,7 +12878,7 @@ let TcAndPublishMemberSpec cenv env containerInfo declKind tpenv memb = [], tpenv -let TcTyconMemberSpecs cenv env containerInfo declKind tpenv (augSpfn: SynMemberSigs) = +let TcTyconMemberSpecs cenv env containerInfo declKind tpenv augSpfn = let members, tpenv = List.mapFold (TcAndPublishMemberSpec cenv env containerInfo declKind) tpenv augSpfn List.concat members, tpenv @@ -12427,18 +12887,21 @@ let TcTyconMemberSpecs cenv env containerInfo declKind tpenv (augSpfn: SynMember // Bind 'open' declarations //------------------------------------------------------------------------- -let TcModuleOrNamespaceLidAndPermitAutoResolve tcSink env amap (longId: Ident list) = +let TcOpenLidAndPermitAutoResolve tcSink env amap (longId : Ident list) = let ad = env.eAccessRights match longId with - | [] -> Result [] - | id::rest -> + | [] -> [] + | id :: rest -> let m = longId |> List.map (fun id -> id.idRange) |> List.reduce unionRanges - match ResolveLongIndentAsModuleOrNamespace tcSink ResultCollectionSettings.AllResults amap m true OpenQualified env.eNameResEnv ad id rest true with - | Result res -> Result res - | Exception err -> raze err + match ResolveLongIndentAsModuleOrNamespaceOrStaticClass tcSink ResultCollectionSettings.AllResults amap m true true OpenQualified env.eNameResEnv ad id rest true with + | Result res -> res + | Exception err -> + errorR(err); [] let TcOpenDecl tcSink (g: TcGlobals) amap m scopem env (longId: Ident list) = - let modrefs = ForceRaise (TcModuleOrNamespaceLidAndPermitAutoResolve tcSink env amap longId) + match TcOpenLidAndPermitAutoResolve tcSink env amap longId with + | [] -> env + | modrefs -> // validate opened namespace names for id in longId do @@ -12451,7 +12914,7 @@ let TcOpenDecl tcSink (g: TcGlobals) amap m scopem env (longId: Ident list) = let p = match p with | [] -> [] - | (h, _):: t -> if h.StartsWithOrdinal(FsiDynamicModulePrefix) then t else p + | (h, _) :: t -> if h.StartsWithOrdinal FsiDynamicModulePrefix then t else p // See https://fslang.uservoice.com/forums/245727-f-language/suggestions/6107641-make-microsoft-prefix-optional-when-using-core-f let isFSharpCoreSpecialCase = @@ -12488,7 +12951,7 @@ let TcOpenDecl tcSink (g: TcGlobals) amap m scopem env (longId: Ident list) = modrefs |> List.iter (fun modref -> CheckEntityAttributes g modref m |> CommitOperationResult) let openDecl = OpenDeclaration.Create (longId, modrefs, scopem, false) - let env = OpenModulesOrNamespaces tcSink g amap scopem false env modrefs openDecl + let env = OpenEntities tcSink g amap scopem false env modrefs openDecl env @@ -12499,7 +12962,7 @@ module IncrClassChecking = /// Represents a single group of bindings in a class with an implicit constructor type IncrClassBindingGroup = - | IncrClassBindingGroup of Tast.Binding list * (*isStatic:*) bool* (*recursive:*) bool + | IncrClassBindingGroup of Binding list * (*isStatic:*) bool* (*recursive:*) bool | IncrClassDo of Expr * (*isStatic:*) bool /// Typechecked info for implicit constructor and it's arguments @@ -12509,7 +12972,7 @@ module IncrClassChecking = TyconRef: TyconRef /// The type parameters allocated for the implicit instance constructor. - /// These may be equated with other (WillBeRigid) type parameters through equirecursive inference, and so + /// These may be equated with other (WillBeRigid) type parameters through equi-recursive inference, and so /// should always be renormalized/canonicalized when used. InstanceCtorDeclaredTypars: Typars @@ -12551,7 +13014,7 @@ module IncrClassChecking = /// Check and elaborate the "left hand side" of the implicit class construction /// syntax. - let TcImplictCtorLhs_Phase2A(cenv, env, tpenv, tcref: TyconRef, vis, attrs, spats, thisIdOpt, baseValOpt: Val option, safeInitInfo, m, copyOfTyconTypars, objTy, thisTy) = + let TcImplicitCtorLhs_Phase2A(cenv, env, tpenv, tcref: TyconRef, vis, attrs, spats, thisIdOpt, baseValOpt: Val option, safeInitInfo, m, copyOfTyconTypars, objTy, thisTy) = let baseValOpt = match GetSuperTypeOfType cenv.g cenv.amap m objTy with @@ -12566,7 +13029,7 @@ module IncrClassChecking = let ctorArgNames, (_, names, _) = TcSimplePatsOfUnknownType cenv true CheckCxs env tpenv (SynSimplePats.SimplePats (spats, m)) // Create the values with the given names - let _, vspecs = MakeSimpleVals cenv env names + let _, vspecs = MakeAndPublishSimpleVals cenv env names if tcref.IsStructOrEnumTycon && isNil spats then errorR (ParameterlessStructCtor(tcref.Range)) @@ -12595,8 +13058,8 @@ module IncrClassChecking = let prelimTyschemeG = TypeScheme(copyOfTyconTypars, ctorTy) let isComplete = ComputeIsComplete copyOfTyconTypars [] ctorTy let topValInfo = InferGenericArityFromTyScheme prelimTyschemeG partialValReprInfo - let ctorValScheme = ValScheme(id, prelimTyschemeG, Some(topValInfo), Some(memberInfo), false, ValInline.Never, NormalVal, vis, false, true, false, false) - let ctorVal = MakeAndPublishVal cenv env (Parent(tcref), false, ModuleOrMemberBinding, ValInRecScope(isComplete), ctorValScheme, attribs, XmlDoc.Empty, None, false) + let ctorValScheme = ValScheme(id, prelimTyschemeG, Some topValInfo, Some memberInfo, false, ValInline.Never, NormalVal, vis, false, true, false, false) + let ctorVal = MakeAndPublishVal cenv env (Parent tcref, false, ModuleOrMemberBinding, ValInRecScope isComplete, ctorValScheme, attribs, XmlDoc.Empty, None, false) ctorValScheme, ctorVal // We only generate the cctor on demand, because we don't need it if there are no cctor actions. @@ -12614,16 +13077,16 @@ module IncrClassChecking = let partialValReprInfo = TranslateTopValSynInfo m (TcAttributes cenv env) valSynData let prelimTyschemeG = TypeScheme(copyOfTyconTypars, cctorTy) let topValInfo = InferGenericArityFromTyScheme prelimTyschemeG partialValReprInfo - let cctorValScheme = ValScheme(id, prelimTyschemeG, Some(topValInfo), Some(memberInfo), false, ValInline.Never, NormalVal, Some SynAccess.Private, false, true, false, false) + let cctorValScheme = ValScheme(id, prelimTyschemeG, Some topValInfo, Some memberInfo, false, ValInline.Never, NormalVal, Some SynAccess.Private, false, true, false, false) - let cctorVal = MakeAndPublishVal cenv env (Parent(tcref), false, ModuleOrMemberBinding, ValNotInRecScope, cctorValScheme, [(* no attributes*)], XmlDoc.Empty, None, false) + let cctorVal = MakeAndPublishVal cenv env (Parent tcref, false, ModuleOrMemberBinding, ValNotInRecScope, cctorValScheme, [(* no attributes*)], XmlDoc.Empty, None, false) cctorArgs, cctorVal, cctorValScheme) let thisVal = // --- Create this for use inside constructor let thisId = ident ("this", m) - let thisValScheme = ValScheme(thisId, NonGenericTypeScheme(thisTy), None, None, false, ValInline.Never, CtorThisVal, None, true, false, false, false) - let thisVal = MakeAndPublishVal cenv env (ParentNone, false, ClassLetBinding(false), ValNotInRecScope, thisValScheme, [], XmlDoc.Empty, None, false) + let thisValScheme = ValScheme(thisId, NonGenericTypeScheme thisTy, None, None, false, ValInline.Never, CtorThisVal, None, true, false, false, false) + let thisVal = MakeAndPublishVal cenv env (ParentNone, false, ClassLetBinding false, ValNotInRecScope, thisValScheme, [], XmlDoc.Empty, None, false) thisVal {TyconRef = tcref @@ -12656,7 +13119,7 @@ module IncrClassChecking = let taccess = TAccess [cpath] let isVolatile = HasFSharpAttribute g g.attrib_VolatileFieldAttribute v.Attribs - NewRecdField isStatic None id false ty v.IsMutable isVolatile [(*no property attributes*)] v.Attribs v.XmlDoc taccess (*compiler generated:*)true + Construct.NewRecdField isStatic None id false ty v.IsMutable isVolatile [] v.Attribs v.XmlDoc taccess true /// Indicates how is a 'let' bound value in a class with implicit construction is represented in /// the TAST ultimately produced by type checking. @@ -12728,7 +13191,7 @@ module IncrClassChecking = ctorInfo.NameGenerator.FreshCompilerGeneratedName (v.LogicalName, v.Range) else v.LogicalName - nm, takenFieldNames.Add(nm) + nm, takenFieldNames.Add nm let reportIfUnused() = if not v.HasBeenReferenced && not v.IsCompiledAsTopLevel && not (v.DisplayName.StartsWithOrdinal("_")) && not v.IsCompilerGenerated then @@ -12748,7 +13211,7 @@ module IncrClassChecking = if v.IsMutable || relevantForcedFieldVars.Contains v || tcref.IsStructOrEnumTycon then //dprintfn "Representing %s as a field %s" v.LogicalName name - let rfref = RFRef(tcref, name) + let rfref = RecdFieldRef(tcref, name) reportIfUnused() InField (isStatic, localRep.ValReprs.Count, rfref) else @@ -12778,16 +13241,16 @@ module IncrClassChecking = else let tauTy = ctorInfo.InstanceCtorThisVal.Type --> v.TauType let (ValReprInfo(tpNames, args, ret)) = topValInfo - let topValInfo = ValReprInfo(tpNames, ValReprInfo.selfMetadata::args, ret) + let topValInfo = ValReprInfo(tpNames, ValReprInfo.selfMetadata :: args, ret) tauTy, topValInfo // Add the enclosing type parameters on to the function let topValInfo = let (ValReprInfo(tpNames, args, ret)) = topValInfo - ValReprInfo(tpNames@ValReprInfo.InferTyparInfo(copyOfTyconTypars), args, ret) + ValReprInfo(tpNames@ValReprInfo.InferTyparInfo copyOfTyconTypars, args, ret) let prelimTyschemeG = TypeScheme(copyOfTyconTypars@tps, memberTauTy) - let memberValScheme = ValScheme(id, prelimTyschemeG, Some(topValInfo), Some(memberInfo), false, ValInline.Never, NormalVal, None, true (* isCompilerGenerated *), true (* isIncrClass *), false, false) - let methodVal = MakeAndPublishVal cenv env (Parent(tcref), false, ModuleOrMemberBinding, ValNotInRecScope, memberValScheme, v.Attribs, XmlDoc.Empty, None, false) + let memberValScheme = ValScheme(id, prelimTyschemeG, Some topValInfo, Some memberInfo, false, ValInline.Never, NormalVal, None, true (* isCompilerGenerated *), true (* isIncrClass *), false, false) + let methodVal = MakeAndPublishVal cenv env (Parent tcref, false, ModuleOrMemberBinding, ValNotInRecScope, memberValScheme, v.Attribs, XmlDoc.Empty, None, false) reportIfUnused() InMethod(isStatic, methodVal, topValInfo) @@ -12806,7 +13269,7 @@ module IncrClassChecking = {localRep with ValsWithRepresentation = Zset.add v localRep.ValsWithRepresentation} member localRep.IsValWithRepresentation (v: Val) = - localRep.ValsWithRepresentation.Contains(v) + localRep.ValsWithRepresentation.Contains v member localRep.IsValRepresentedAsLocalVar (v: Val) = match localRep.LookupRepr v with @@ -12814,8 +13277,8 @@ module IncrClassChecking = | _ -> false member localRep.IsValRepresentedAsMethod (v: Val) = - localRep.IsValWithRepresentation(v) && - match localRep.LookupRepr(v) with + localRep.IsValWithRepresentation v && + match localRep.LookupRepr v with | InMethod _ -> true | _ -> false @@ -12826,13 +13289,13 @@ module IncrClassChecking = match localRep.LookupRepr v, thisValOpt with | InVar _, _ -> exprForVal m v - | InField(false, _idx, rfref), Some(thisVal) -> + | InField(false, _idx, rfref), Some thisVal -> let thise = exprForVal m thisVal - mkRecdFieldGetViaExprAddr(thise, rfref, tinst, m) + mkRecdFieldGetViaExprAddr (thise, rfref, tinst, m) | InField(false, _idx, _rfref), None -> error(InternalError("Unexpected missing 'this' variable in MakeValueLookup", m)) | InField(true, idx, rfref), _ -> - let expr = mkStaticRecdFieldGet(rfref, tinst, m) + let expr = mkStaticRecdFieldGet (rfref, tinst, m) MakeCheckSafeInit g tinst safeStaticInitInfo (mkInt g m idx) expr | InMethod(isStatic, methodVal, topValInfo), _ -> @@ -12851,7 +13314,7 @@ module IncrClassChecking = member localRep.MakeValueAssign thisValOpt tinst safeStaticInitInfo v expr m = let g = localRep.RepInfoTcGlobals match localRep.LookupRepr v, thisValOpt with - | InField(false, _, rfref), Some(thisVal) -> + | InField(false, _, rfref), Some thisVal -> let thise = exprForVal m thisVal mkRecdFieldSetViaExprAddr(thise, rfref, tinst, expr, m) | InField(false, _, _rfref), None -> @@ -12867,7 +13330,7 @@ module IncrClassChecking = member localRep.MakeValueGetAddress readonly thisValOpt tinst safeStaticInitInfo v m = let g = localRep.RepInfoTcGlobals match localRep.LookupRepr v, thisValOpt with - | InField(false, _, rfref), Some(thisVal) -> + | InField(false, _, rfref), Some thisVal -> let thise = exprForVal m thisVal mkRecdFieldGetAddrViaExprAddr(readonly, thise, rfref, tinst, m) | InField(false, _, _rfref), None -> @@ -12904,7 +13367,7 @@ module IncrClassChecking = | SafeInitField (_, fld) -> yield fld | NoSafeInitInfo -> () ] - let recdFields = MakeRecdFieldsTable (rfspecs @ tcref.AllFieldsAsList) + let recdFields = Construct.MakeRecdFieldsTable (rfspecs @ tcref.AllFieldsAsList) // Mutate the entity_tycon_repr to publish the fields tcref.Deref.entity_tycon_repr <- TFSharpObjectRepr { tcref.FSharpObjectModelTypeInfo with fsobjmodel_rfields = recdFields} @@ -12926,10 +13389,10 @@ module IncrClassChecking = // Rewrite references to applied let-bound-functions-compiled-as-methods // Rewrite references to applied recursive let-bound-functions-compiled-as-methods // Rewrite references to applied recursive generic let-bound-functions-compiled-as-methods - | Expr.App(Expr.Val (ValDeref v, _, _), _, tyargs, args, m) - | Expr.App(Expr.Link {contents = Expr.Val (ValDeref v, _, _) }, _, tyargs, args, m) - | Expr.App(Expr.Link {contents = Expr.App(Expr.Val (ValDeref v, _, _), _, tyargs, [], _) }, _, [], args, m) - when localRep.IsValRepresentedAsMethod(v) && not (cenv.recUses.ContainsKey v) -> + | Expr.App (Expr.Val (ValDeref v, _, _), _, tyargs, args, m) + | Expr.App (Expr.Link {contents = Expr.Val (ValDeref v, _, _) }, _, tyargs, args, m) + | Expr.App (Expr.Link {contents = Expr.App (Expr.Val (ValDeref v, _, _), _, tyargs, [], _) }, _, [], args, m) + when localRep.IsValRepresentedAsMethod v && not (cenv.recUses.ContainsKey v) -> let expr = localRep.MakeValueLookup thisValOpt thisTyInst safeStaticInitInfo v tyargs m let args = args |> List.map rw @@ -12937,27 +13400,27 @@ module IncrClassChecking = // Rewrite references to values stored as fields and first class uses of method values | Expr.Val (ValDeref v, _, m) - when localRep.IsValWithRepresentation(v) -> + when localRep.IsValWithRepresentation v -> //dprintfn "Found use of %s" v.LogicalName Some (localRep.MakeValueLookup thisValOpt thisTyInst safeStaticInitInfo v [] m) // Rewrite assignments to mutable values stored as fields - | Expr.Op(TOp.LValueOp (LSet, ValDeref v), [], [arg], m) - when localRep.IsValWithRepresentation(v) -> + | Expr.Op (TOp.LValueOp (LSet, ValDeref v), [], [arg], m) + when localRep.IsValWithRepresentation v -> let arg = rw arg Some (localRep.MakeValueAssign thisValOpt thisTyInst safeStaticInitInfo v arg m) // Rewrite taking the address of mutable values stored as fields - | Expr.Op(TOp.LValueOp (LAddrOf readonly, ValDeref v), [], [], m) - when localRep.IsValWithRepresentation(v) -> + | Expr.Op (TOp.LValueOp (LAddrOf readonly, ValDeref v), [], [], m) + when localRep.IsValWithRepresentation v -> Some (localRep.MakeValueGetAddress readonly thisValOpt thisTyInst safeStaticInitInfo v m) | _ -> None - Tastops.RewriteExpr { PreIntercept = Some FixupExprNode - PostTransform = (fun _ -> None) - PreInterceptBinding = None - IsUnderQuotations=true } expr + RewriteExpr { PreIntercept = Some FixupExprNode + PostTransform = (fun _ -> None) + PreInterceptBinding = None + IsUnderQuotations=true } expr type IncrClassConstructionBindingsPhase2C = @@ -12985,12 +13448,13 @@ module IncrClassChecking = let denv = env.DisplayEnv + let g = cenv.g let thisVal = ctorInfo.InstanceCtorThisVal let m = thisVal.Range let ctorDeclaredTypars = ctorInfo.GetNormalizedInstanceCtorDeclaredTypars cenv denv m - ctorDeclaredTypars |> List.iter (SetTyparRigid cenv.g env.DisplayEnv m) + ctorDeclaredTypars |> List.iter (SetTyparRigid g env.DisplayEnv m) // Reconstitute the type with the correct quantified type variables. ctorInfo.InstanceCtorVal.SetType (mkForallTyIfNeeded ctorDeclaredTypars ctorInfo.InstanceCtorVal.TauType) @@ -13070,10 +13534,10 @@ module IncrClassChecking = | InMethod(isStatic, methodVal, _) -> let _, chooseTps, tauExpr, tauTy, m = match rhsExpr with - | Expr.TyChoose(chooseTps, b, _) -> [], chooseTps, b, (tyOfExpr cenv.g b), m - | Expr.TyLambda (_, tps, Expr.TyChoose(chooseTps, b, _), m, returnTy) -> tps, chooseTps, b, returnTy, m + | Expr.TyChoose (chooseTps, b, _) -> [], chooseTps, b, (tyOfExpr g b), m + | Expr.TyLambda (_, tps, Expr.TyChoose (chooseTps, b, _), m, returnTy) -> tps, chooseTps, b, returnTy, m | Expr.TyLambda (_, tps, b, m, returnTy) -> tps, [], b, returnTy, m - | e -> [], [], e, (tyOfExpr cenv.g e), e.Range + | e -> [], [], e, (tyOfExpr g e), e.Range let chooseTps = chooseTps @ (ListSet.subtract typarEq freeChoiceTypars methodVal.Typars) @@ -13083,7 +13547,7 @@ module IncrClassChecking = tauExpr, tauTy else let e = mkLambda m thisVal (tauExpr, tauTy) - e, tyOfExpr cenv.g e + e, tyOfExpr g e // Replace the type parameters that used to be on the rhs with // the full set of type parameters including the type parameters of the enclosing class @@ -13102,15 +13566,15 @@ module IncrClassChecking = match spBind, rhsExpr with // Don't generate big sequence points for functions in classes | _, (Expr.Lambda _ | Expr.TyLambda _) -> v.Range - | SequencePointAtBinding m, _ -> m + | DebugPointAtBinding m, _ -> m | _ -> v.Range let assignExpr = reps.MakeValueAssign (Some thisVal) thisTyInst NoSafeInitInfo v rhsExpr m let adjustSafeInitFieldExprOpt = if isStatic then match safeStaticInitInfo with | SafeInitField (rfref, _) -> - let setExpr = mkStaticRecdFieldSet (rfref, thisTyInst, mkInt cenv.g m idx, m) - let setExpr = reps.FixupIncrClassExprPhase2C cenv (Some(thisVal)) NoSafeInitInfo thisTyInst setExpr + let setExpr = mkStaticRecdFieldSet (rfref, thisTyInst, mkInt g m idx, m) + let setExpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) NoSafeInitInfo thisTyInst setExpr Some setExpr | NoSafeInitInfo -> None @@ -13119,7 +13583,7 @@ module IncrClassChecking = (isPriorToSuperInit, (fun e -> let e = match adjustSafeInitFieldExprOpt with None -> e | Some ae -> mkCompGenSequential m ae e - mkSequential SequencePointsAtSeq m assignExpr e)), [] + mkSequential DebugPointAtSequential.Both m assignExpr e)), [] /// Work out the implicit construction side effects of a 'let', 'let rec' or 'do' /// binding in the implicit class construction sequence @@ -13132,12 +13596,12 @@ module IncrClassChecking = // Note: the recursive calls are made via members on the object // or via access to fields. This means the recursive loop is "broken", // and we can collapse to sequential bindings - let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ValNowWithRepresentation bind.Var) // inscope before + let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ValNowWithRepresentation bind.Var) // in scope before let actions, methodBinds = binds |> List.map (TransBind reps) |> List.unzip // since can occur in RHS of own defns actions, reps, methodBinds else let actions, methodBinds = binds |> List.map (TransBind reps) |> List.unzip - let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ValNowWithRepresentation bind.Var) // inscope after + let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ValNowWithRepresentation bind.Var) // in scope after actions, reps, methodBinds let methodBinds = List.concat methodBinds if isStatic then @@ -13146,8 +13610,8 @@ module IncrClassChecking = ([], actions, methodBinds), reps | IncrClassDo (doExpr, isStatic) -> - let doExpr = reps.FixupIncrClassExprPhase2C cenv (Some(thisVal)) safeStaticInitInfo thisTyInst doExpr - let binder = (fun e -> mkSequential SequencePointsAtSeq doExpr.Range doExpr e) + let doExpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) safeStaticInitInfo thisTyInst doExpr + let binder = (fun e -> mkSequential DebugPointAtSequential.Both doExpr.Range doExpr e) let isPriorToSuperInit = false if isStatic then ([(isPriorToSuperInit, binder)], [], []), reps @@ -13165,9 +13629,9 @@ module IncrClassChecking = [ match ctorInfo.InstanceCtorSafeThisValOpt with | None -> () | Some v -> - let setExpr = mkRefCellSet cenv.g m ctorInfo.InstanceCtorThisVal.Type (exprForVal m v) (exprForVal m ctorInfo.InstanceCtorThisVal) - let setExpr = reps.FixupIncrClassExprPhase2C cenv (Some(thisVal)) safeStaticInitInfo thisTyInst setExpr - let binder = (fun e -> mkSequential SequencePointsAtSeq setExpr.Range setExpr e) + let setExpr = mkRefCellSet g m ctorInfo.InstanceCtorThisVal.Type (exprForVal m v) (exprForVal m ctorInfo.InstanceCtorThisVal) + let setExpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) safeStaticInitInfo thisTyInst setExpr + let binder = (fun e -> mkSequential DebugPointAtSequential.Both setExpr.Range setExpr e) let isPriorToSuperInit = false yield (isPriorToSuperInit, binder) ] @@ -13179,9 +13643,9 @@ module IncrClassChecking = let binders = [ match ctorInfo.InstanceCtorSafeInitInfo with | SafeInitField (rfref, _) -> - let setExpr = mkRecdFieldSetViaExprAddr (exprForVal m thisVal, rfref, thisTyInst, mkOne cenv.g m, m) - let setExpr = reps.FixupIncrClassExprPhase2C cenv (Some(thisVal)) safeStaticInitInfo thisTyInst setExpr - let binder = (fun e -> mkSequential SequencePointsAtSeq setExpr.Range setExpr e) + let setExpr = mkRecdFieldSetViaExprAddr (exprForVal m thisVal, rfref, thisTyInst, mkOne g m, m) + let setExpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) safeStaticInitInfo thisTyInst setExpr + let binder = (fun e -> mkSequential DebugPointAtSequential.Both setExpr.Range setExpr e) let isPriorToSuperInit = false yield (isPriorToSuperInit, binder) | NoSafeInitInfo -> @@ -13198,11 +13662,11 @@ module IncrClassChecking = let takenFieldNames = [ for b in memberBinds do - yield b.Var.CompiledName + yield b.Var.CompiledName cenv.g.CompilerGlobalState yield b.Var.DisplayName yield b.Var.CoreDisplayName yield b.Var.LogicalName ] - let reps = IncrClassReprInfo.Empty(cenv.g, takenFieldNames) + let reps = IncrClassReprInfo.Empty(g, takenFieldNames) // Bind the IsArg(true) representations of the object constructor arguments and assign them to fields // if they escape to the members. We do this by running the instance bindings 'let x = x' through TransTrueDec @@ -13233,7 +13697,7 @@ module IncrClassChecking = let ctorInitActionsPre, ctorInitActionsPost = ctorInitActions |> List.partition (fun (isPriorToSuperInit, _) -> isPriorToSuperInit) // This is the return result - let ctorBody = mkUnit cenv.g m + let ctorBody = mkUnit g m // Add . // That is, add any that come prior to the super init constructor call, @@ -13249,7 +13713,7 @@ module IncrClassChecking = // // As a result, the most natural way to implement this would be to simply capture arg0 if needed // and access all variables via that. This would be done by rewriting the inheritsExpr as follows: - // let inheritsExpr = reps.FixupIncrClassExprPhase2C (Some(thisVal)) thisTyInst inheritsExpr + // let inheritsExpr = reps.FixupIncrClassExprPhase2C (Some thisVal) thisTyInst inheritsExpr // However, the rules of IL mean we are not actually allowed to capture arg0 // and store it as a closure field before the base class constructor is called. // @@ -13259,23 +13723,23 @@ module IncrClassChecking = // (c) rely on the fact that there are no 'let' bindings prior to the inherits expr. let inheritsExpr = match ctorInfo.InstanceCtorSafeThisValOpt with - | Some v when not (reps.IsValRepresentedAsLocalVar (v)) -> + | Some v when not (reps.IsValRepresentedAsLocalVar v) -> // Rewrite the expression to convert it to a load of a field if needed. // We are allowed to load fields from our own object even though we haven't called // the super class constructor yet. - let ldexpr = reps.FixupIncrClassExprPhase2C cenv (Some(thisVal)) safeStaticInitInfo thisTyInst (exprForVal m v) + let ldexpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) safeStaticInitInfo thisTyInst (exprForVal m v) mkInvisibleLet m v ldexpr inheritsExpr | _ -> inheritsExpr - let spAtSuperInit = (if inheritsIsVisible then SequencePointsAtSeq else SuppressSequencePointOnExprOfSequential) + let spAtSuperInit = (if inheritsIsVisible then DebugPointAtSequential.Both else DebugPointAtSequential.StmtOnly) mkSequential spAtSuperInit m inheritsExpr ctorBody // Add the normal let ctorBody = List.foldBack (fun (_, binder) acc -> binder acc) ctorInitActionsPre ctorBody // Add the final wrapping to make this into a method - let ctorBody = mkMemberLambdas m [] (Some(thisVal)) ctorInfo.InstanceCtorBaseValOpt [ctorInfo.InstanceCtorArgs] (ctorBody, cenv.g.unit_ty) + let ctorBody = mkMemberLambdas m [] (Some thisVal) ctorInfo.InstanceCtorBaseValOpt [ctorInfo.InstanceCtorArgs] (ctorBody, g.unit_ty) ctorBody @@ -13284,13 +13748,13 @@ module IncrClassChecking = match cctorInitActions with | [] -> None | _ -> - let cctorInitAction = List.foldBack (fun (_, binder) acc -> binder acc) cctorInitActions (mkUnit cenv.g m) + let cctorInitAction = List.foldBack (fun (_, binder) acc -> binder acc) cctorInitActions (mkUnit g m) let m = thisVal.Range let cctorArgs, cctorVal, _ = ctorInfo.StaticCtorValInfo.Force() // Reconstitute the type of the implicit class constructor with the correct quantified type variables. cctorVal.SetType (mkForallTyIfNeeded ctorDeclaredTypars cctorVal.TauType) - let cctorBody = mkMemberLambdas m [] None None [cctorArgs] (cctorInitAction, cenv.g.unit_ty) - Some(cctorBody) + let cctorBody = mkMemberLambdas m [] None None [cctorArgs] (cctorInitAction, g.unit_ty) + Some cctorBody ctorBody, cctorBodyOpt, methodBinds, reps @@ -13319,7 +13783,7 @@ module MutRecBindingChecking = /// A set of value or function definitions in an incremental class /// /// Phase2AIncrClassBindings (tcref, letBinds, isStatic, isRec, m) - | Phase2AIncrClassBindings of TyconRef * Ast.SynBinding list * bool * bool * range + | Phase2AIncrClassBindings of TyconRef * SynBinding list * bool * bool * range /// A 'member' definition in a class | Phase2AMember of PreCheckingRecursiveBinding #if OPEN_IN_TYPE_DECLARATIONS @@ -13340,7 +13804,7 @@ module MutRecBindingChecking = /// Represents one element in a type definition, after the second phase type TyconBindingPhase2B = - | Phase2BIncrClassCtor of IncrClassCtorLhs * Tast.Binding option + | Phase2BIncrClassCtor of IncrClassCtorLhs * Binding option | Phase2BInherit of Expr * Val option /// A set of value of function definitions in a class definition with an implicit constructor. | Phase2BIncrClassBindings of IncrClassBindingGroup list @@ -13359,7 +13823,7 @@ module MutRecBindingChecking = /// Represents one element in a type definition, after the third phase type TyconBindingPhase2C = - | Phase2CIncrClassCtor of IncrClassCtorLhs * Tast.Binding option + | Phase2CIncrClassCtor of IncrClassCtorLhs * Binding option | Phase2CInherit of Expr * Val option | Phase2CIncrClassBindings of IncrClassBindingGroup list | Phase2CMember of PreInitializationGraphEliminationBinding @@ -13376,6 +13840,7 @@ module MutRecBindingChecking = // Phase2A: create member prelimRecValues for "recursive" items, i.e. ctor val and member vals // Phase2A: also processes their arg patterns - collecting type assertions let TcMutRecBindings_Phase2A_CreateRecursiveValuesAndCheckArgumentPatterns cenv tpenv (envMutRec, mutRecDefns: MutRecDefnsPhase2Info) = + let g = cenv.g // The basic iteration over the declarations in a single type definition // State: @@ -13406,16 +13871,16 @@ module MutRecBindingChecking = // Class members can access protected members of the implemented type // Class members can access private members in the ty let isExtrinsic = (declKind = ExtrinsicExtensionBinding) - let initalEnvForTycon = MakeInnerEnvForTyconRef envForDecls tcref isExtrinsic + let initialEnvForTycon = MakeInnerEnvForTyconRef envForDecls tcref isExtrinsic // Re-add the type constructor to make it take precedence for record label field resolutions // This does not apply to extension members: in those cases the relationship between the record labels // and the type is too extruded let envForTycon = if isExtrinsic then - initalEnvForTycon + initialEnvForTycon else - AddLocalTyconRefs true cenv.g cenv.amap tcref.Range [tcref] initalEnvForTycon + AddLocalTyconRefs true g cenv.amap tcref.Range [tcref] initialEnvForTycon // Make fresh version of the class type for type checking the members and lets * let _, copyOfTyconTypars, _, objTy, thisTy = FreshenObjectArgType cenv tcref.Range TyparRigidity.WillBeRigid tcref isExtrinsic declaredTyconTypars @@ -13439,12 +13904,12 @@ module MutRecBindingChecking = error(Error(FSComp.SR.tcEnumerationsMayNotHaveMembers(), (trimRangeToLine m))) match classMemberDef, containerInfo with - | SynMemberDefn.ImplicitCtor (vis, attrs, spats, thisIdOpt, m), ContainerInfo(_, Some(MemberOrValContainerInfo(tcref, _, baseValOpt, safeInitInfo, _))) -> + | SynMemberDefn.ImplicitCtor (vis, Attributes attrs, SynSimplePats.SimplePats(spats, _), thisIdOpt, m), ContainerInfo(_, Some(MemberOrValContainerInfo(tcref, _, baseValOpt, safeInitInfo, _))) -> if tcref.TypeOrMeasureKind = TyparKind.Measure then error(Error(FSComp.SR.tcMeasureDeclarationsRequireStaticMembers(), m)) // Phase2A: make incrClassCtorLhs - ctorv, thisVal etc, type depends on argty(s) - let incrClassCtorLhs = TcImplictCtorLhs_Phase2A(cenv, envForTycon, tpenv, tcref, vis, attrs, spats, thisIdOpt, baseValOpt, safeInitInfo, m, copyOfTyconTypars, objTy, thisTy) + let incrClassCtorLhs = TcImplicitCtorLhs_Phase2A(cenv, envForTycon, tpenv, tcref, vis, attrs, spats, thisIdOpt, baseValOpt, safeInitInfo, m, copyOfTyconTypars, objTy, thisTy) // Phase2A: Add copyOfTyconTypars from incrClassCtorLhs - or from tcref let envForTycon = AddDeclaredTypars CheckForDuplicateTypars incrClassCtorLhs.InstanceCtorDeclaredTypars envForTycon let innerState = (Some incrClassCtorLhs, envForTycon, tpenv, recBindIdx, uncheckedBindsRev) @@ -13497,7 +13962,7 @@ module MutRecBindingChecking = | MemberKind.Constructor -> error(Error(FSComp.SR.tcMeasureDeclarationsRequireStaticMembersNotConstructors(), m)) | _ -> () let rbind = NormalizedRecBindingDefn(containerInfo, newslotsOK, declKind, bind) - let overridesOK = DeclKind.CanOverrideOrImplement(declKind) + let overridesOK = DeclKind.CanOverrideOrImplement declKind let (binds, _values), (tpenv, recBindIdx) = AnalyzeAndMakeAndPublishRecursiveValue overridesOK false cenv envForTycon (tpenv, recBindIdx) rbind let cbinds = [ for rbind in binds -> Phase2AMember rbind ] @@ -13556,6 +14021,7 @@ module MutRecBindingChecking = /// Phase2B: check each of the bindings, convert from ast to tast and collects type assertions. /// Also generalize incrementally. let TcMutRecBindings_Phase2B_TypeCheckAndIncrementalGeneralization cenv tpenv envInitial (envMutRec, defnsAs: MutRecDefnsPhase2AData, uncheckedRecBinds: PreCheckingRecursiveBinding list, scopem) : MutRecDefnsPhase2BData * _ * _ = + let g = cenv.g let (defnsBs: MutRecDefnsPhase2BData), (tpenv, generalizedRecBinds, preGeneralizationRecBinds, _, _) = @@ -13610,7 +14076,7 @@ module MutRecBindingChecking = let isExtrinsic = (declKind = ExtrinsicExtensionBinding) let envForTycon = MakeInnerEnvForTyconRef envForDecls tcref isExtrinsic - let envForTycon = if isExtrinsic then envForTycon else AddLocalTyconRefs true cenv.g cenv.amap tcref.Range [tcref] envForTycon + let envForTycon = if isExtrinsic then envForTycon else AddLocalTyconRefs true g cenv.amap tcref.Range [tcref] envForTycon // Set up the environment so use-before-definition warnings are given, at least // until we reach a Phase2AIncrClassCtorJustAfterSuperInit. let envForTycon = { envForTycon with eCtorInfo = Some (InitialImplicitCtorInfo()) } @@ -13651,8 +14117,13 @@ 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 envInstance tpenv synBaseTy - let baseTy = baseTy |> convertToTypeWithMetadataIfPossible cenv.g - let inheritsExpr, tpenv = TcNewExpr cenv envInstance tpenv baseTy (Some synBaseTy.Range) true arg m + let baseTy = baseTy |> convertToTypeWithMetadataIfPossible g + let inheritsExpr, tpenv = + try + TcNewExpr cenv envInstance tpenv baseTy (Some synBaseTy.Range) true arg m + with e -> + errorRecovery e m + mkUnit g m, tpenv let envInstance = match baseValOpt with Some baseVal -> AddLocalVal cenv.tcSink scopem baseVal envInstance | None -> envInstance let envNonRec = match baseValOpt with Some baseVal -> AddLocalVal cenv.tcSink scopem baseVal envNonRec | None -> envNonRec let innerState = (tpenv, envInstance, envStatic, envNonRec, generalizedRecBinds, preGeneralizationRecBinds, uncheckedRecBindsTable) @@ -13665,14 +14136,14 @@ module MutRecBindingChecking = if isRec then // Type check local recursive binding - let binds = binds |> List.map (fun bind -> RecDefnBindingInfo(ExprContainerInfo, NoNewSlots, ClassLetBinding(isStatic), bind)) + let binds = binds |> List.map (fun bind -> RecDefnBindingInfo(ExprContainerInfo, NoNewSlots, ClassLetBinding isStatic, bind)) let binds, env, tpenv = TcLetrec ErrorOnOverrides cenv envForBinding tpenv (binds, scopem(*bindsm*), scopem) let bindRs = [IncrClassBindingGroup(binds, isStatic, true)] binds, bindRs, env, tpenv else // Type check local binding - let binds, env, tpenv = TcLetBindings cenv envForBinding ExprContainerInfo (ClassLetBinding(isStatic)) tpenv (binds, bindsm, scopem) + let binds, env, tpenv = TcLetBindings cenv envForBinding ExprContainerInfo (ClassLetBinding isStatic) tpenv (binds, bindsm, scopem) let binds, bindRs = binds |> List.map (function @@ -13686,7 +14157,7 @@ module MutRecBindingChecking = // Check to see that local bindings and members don't have the same name and check some other adhoc conditions for bind in binds do - if not isStatic && HasFSharpAttributeOpt cenv.g cenv.g.attrib_DllImportAttribute bind.Var.Attribs then + if not isStatic && HasFSharpAttributeOpt g g.attrib_DllImportAttribute bind.Var.Attribs then errorR(Error(FSComp.SR.tcDllImportNotAllowed(), bind.Var.Range)) let nm = bind.Var.DisplayName @@ -13695,7 +14166,7 @@ module MutRecBindingChecking = match TryFindIntrinsicMethInfo cenv.infoReader bind.Var.Range ad nm ty, TryFindPropInfo cenv.infoReader bind.Var.Range ad nm ty with | [], [] -> () - | _ -> errorR (Error(FSComp.SR.tcMemberAndLocalClassBindingHaveSameName(nm), bind.Var.Range)) + | _ -> errorR (Error(FSComp.SR.tcMemberAndLocalClassBindingHaveSameName nm, bind.Var.Range)) // Also add static entries to the envInstance if necessary let envInstance = (if isStatic then (binds, envInstance) ||> List.foldBack (fun b e -> AddLocalVal cenv.tcSink scopem b.Var e) else env) @@ -13714,8 +14185,8 @@ module MutRecBindingChecking = #if OPEN_IN_TYPE_DECLARATIONS | Phase2AOpen(mp, m) -> - let envInstance = TcOpenDecl cenv.tcSink cenv.g cenv.amap m scopem envInstance mp - let envStatic = TcOpenDecl cenv.tcSink cenv.g cenv.amap m scopem envStatic mp + let envInstance = TcOpenDecl cenv.tcSink g cenv.amap m scopem envInstance mp + let envStatic = TcOpenDecl cenv.tcSink g cenv.amap m scopem envStatic mp let innerState = (tpenv, envInstance, envStatic, envNonRec, generalizedRecBinds, preGeneralizationRecBinds, uncheckedRecBindsTable) Phase2BOpen, innerState #endif @@ -13766,6 +14237,8 @@ module MutRecBindingChecking = // Choose type scheme implicit constructors and adjust their recursive types. // Fixup recursive references to members. let TcMutRecBindings_Phase2C_FixupRecursiveReferences cenv (denv, defnsBs: MutRecDefnsPhase2BData, generalizedTyparsForRecursiveBlock: Typar list, generalizedRecBinds: PostGeneralizationRecursiveBinding list, scopem) = + let g = cenv.g + // Build an index ---> binding map let generalizedBindingsMap = generalizedRecBinds |> List.map (fun pgrbind -> (pgrbind.RecBindingInfo.Index, pgrbind)) |> Map.ofList @@ -13781,7 +14254,7 @@ module MutRecBindingChecking = match defnB with | Phase2BIncrClassCtor (incrClassCtorLhs, safeThisValBindOpt) -> let valscheme = incrClassCtorLhs.InstanceCtorValScheme - let valscheme = ChooseCanonicalValSchemeAfterInference cenv.g denv valscheme scopem + let valscheme = ChooseCanonicalValSchemeAfterInference g denv valscheme scopem AdjustRecType cenv incrClassCtorLhs.InstanceCtorVal valscheme Phase2CIncrClassCtor (incrClassCtorLhs, safeThisValBindOpt) @@ -13817,6 +14290,7 @@ module MutRecBindingChecking = // --- Extract method bindings from let-bindings // --- Extract bindings for implicit constructors let TcMutRecBindings_Phase2D_ExtractImplicitFieldAndMethodBindings cenv envMutRec tpenv (denv, generalizedTyparsForRecursiveBlock, defnsCs: MutRecDefnsPhase2CData) = + let g = cenv.g // let (fixupValueExprBinds, methodBinds) = (envMutRec, defnsCs) ||> MutRecShapes.mapTyconsWithEnv (fun envForDecls (TyconBindingsPhase2C(tyconOpt, tcref, defnCs)) -> @@ -13842,7 +14316,7 @@ module MutRecBindingChecking = // // REVIEW: consider allowing an optimization switch to turn off these checks - let needsSafeStaticInit = not cenv.g.compilingFslib + let needsSafeStaticInit = not g.compilingFslib // We only need safe static init checks if there are some static field bindings (actually, we look for non-method bindings) let hasStaticBindings = @@ -13855,7 +14329,7 @@ module MutRecBindingChecking = | _ -> false) if needsSafeStaticInit && hasStaticBindings then - let rfield = MakeSafeInitField cenv.g envForDecls tcref.Range true + let rfield = MakeSafeInitField g envForDecls tcref.Range true SafeInitField(mkRecdFieldRef tcref rfield.Name, rfield) else NoSafeInitInfo @@ -13872,9 +14346,9 @@ module MutRecBindingChecking = | _ -> if tcref.IsStructOrEnumTycon then - mkUnit cenv.g tcref.Range, false, None, defnCs + mkUnit g tcref.Range, false, None, defnCs else - let inheritsExpr, _ = TcNewExpr cenv envForDecls tpenv cenv.g.obj_ty None true (SynExpr.Const(SynConst.Unit, tcref.Range)) tcref.Range + let inheritsExpr, _ = TcNewExpr cenv envForDecls tpenv g.obj_ty None true (SynExpr.Const (SynConst.Unit, tcref.Range)) tcref.Range inheritsExpr, false, None, defnCs let envForTycon = MakeInnerEnvForTyconRef envForDecls tcref false @@ -13902,7 +14376,7 @@ module MutRecBindingChecking = let localDecs = [ for localDec in localDecs do match localDec with - | Phase2CIncrClassBindings(binds) -> yield Phase2CBindings binds + | Phase2CIncrClassBindings binds -> yield Phase2CBindings binds | Phase2CIncrClassCtorJustAfterSuperInit -> yield Phase2CCtorJustAfterSuperInit | Phase2CIncrClassCtorJustAfterLastLet -> yield Phase2CCtorJustAfterLastLet | _ -> () ] @@ -13912,15 +14386,15 @@ module MutRecBindingChecking = // Generate the (value, expr) pairs for the implicit // object constructor and implicit static initializer let ctorValueExprBindings = - [ (let ctorValueExprBinding = TBind(incrClassCtorLhs.InstanceCtorVal, ctorBodyLambdaExpr, NoSequencePointAtStickyBinding) + [ (let ctorValueExprBinding = TBind(incrClassCtorLhs.InstanceCtorVal, ctorBodyLambdaExpr, NoDebugPointAtStickyBinding) let rbind = { ValScheme = incrClassCtorLhs.InstanceCtorValScheme ; Binding = ctorValueExprBinding } FixupLetrecBind cenv envForDecls.DisplayEnv generalizedTyparsForRecursiveBlock rbind) ] @ ( match cctorBodyLambdaExprOpt with | None -> [] - | Some(cctorBodyLambdaExpr) -> + | Some cctorBodyLambdaExpr -> [ (let _, cctorVal, cctorValScheme = incrClassCtorLhs.StaticCtorValInfo.Force() - let cctorValueExprBinding = TBind(cctorVal, cctorBodyLambdaExpr, NoSequencePointAtStickyBinding) + let cctorValueExprBinding = TBind(cctorVal, cctorBodyLambdaExpr, NoDebugPointAtStickyBinding) let rbind = { ValScheme = cctorValScheme; Binding = cctorValueExprBinding } FixupLetrecBind cenv envForDecls.DisplayEnv generalizedTyparsForRecursiveBlock rbind) ] ) @@ -13957,7 +14431,7 @@ module MutRecBindingChecking = let resolved = match p with | [] -> Result [] - | id::rest -> ResolveLongIndentAsModuleOrNamespace cenv.tcSink ResultCollectionSettings.AllResults cenv.amap m true OpenQualified env.eNameResEnv ad id rest false + | id :: rest -> ResolveLongIndentAsModuleOrNamespaceOrStaticClass cenv.tcSink ResultCollectionSettings.AllResults cenv.amap m false true OpenQualified env.eNameResEnv ad id rest false let mvvs = ForceRaise resolved if isNil mvvs then env else let modrefs = mvvs |> List.map p23 @@ -13993,7 +14467,7 @@ module MutRecBindingChecking = let tycons = decls |> List.choose (function MutRecShape.Tycon d -> getTyconOpt d | _ -> None) let mspecs = decls |> List.choose (function MutRecShape.Module (MutRecDefnsPhase2DataForModule (_, mspec), _) -> Some mspec | _ -> None) let moduleAbbrevs = decls |> List.choose (function MutRecShape.ModuleAbbrev (MutRecDataForModuleAbbrev (id, mp, m)) -> Some (id, mp, m) | _ -> None) - let opens = decls |> List.choose (function MutRecShape.Open (MutRecDataForOpen (mp, m)) -> Some (mp, m) | _ -> None) + let opens = decls |> List.choose (function MutRecShape.Open (MutRecDataForOpen (mp, m, moduleRange)) -> Some (mp, m, moduleRange) | _ -> None) let lets = decls |> List.collect (function MutRecShape.Lets binds -> getVals binds | _ -> []) let exns = tycons |> List.filter (fun (tycon: Tycon) -> tycon.IsExceptionDecl) @@ -14019,7 +14493,7 @@ module MutRecBindingChecking = // Add the modules being defined let envForDecls = (envForDecls, mspecs) ||> List.fold ((if report then AddLocalSubModuleAndReport cenv.tcSink scopem else AddLocalSubModule) cenv.g cenv.amap m) // Process the 'open' declarations - let envForDecls = (envForDecls, opens) ||> List.fold (fun env (mp, m) -> TcOpenDecl cenv.tcSink cenv.g cenv.amap m scopem env mp) + let envForDecls = (envForDecls, opens) ||> List.fold (fun env (mp, m, moduleRange) -> TcOpenDecl cenv.tcSink cenv.g cenv.amap m moduleRange env mp) // Add the type definitions being defined let envForDecls = (if report then AddLocalTyconsAndReport cenv.tcSink scopem else AddLocalTycons) cenv.g cenv.amap m tycons envForDecls // Add the exception definitions being defined @@ -14068,7 +14542,7 @@ module MutRecBindingChecking = decls |> MutRecShapes.topTycons |> List.collect (fun (TyconBindingsPhase2A(_, _, _, _, _, _, defnAs)) -> [ for defnB in defnAs do match defnB with - | Phase2AIncrClassCtor (incrClassCtorLhs) -> yield incrClassCtorLhs.InstanceCtorVal + | Phase2AIncrClassCtor incrClassCtorLhs -> yield incrClassCtorLhs.InstanceCtorVal | _ -> () ]) let envForDeclsUpdated = @@ -14167,12 +14641,13 @@ module MutRecBindingChecking = /// Check and generalize the interface implementations, members, 'let' definitions in a mutually recursive group of definitions. let TcMutRecDefns_Phase2 cenv envInitial bindsm scopem mutRecNSInfo (envMutRec: TcEnv) (mutRecDefns: MutRecDefnsPhase2Data) = + let g = cenv.g let interfacesFromTypeDefn envForTycon tyconMembersData = let (MutRecDefnsPhase2DataForTycon(_, _, declKind, tcref, _, _, declaredTyconTypars, members, _, _, _)) = tyconMembersData - let overridesOK = DeclKind.CanOverrideOrImplement(declKind) + let overridesOK = DeclKind.CanOverrideOrImplement declKind members |> List.collect (function | SynMemberDefn.Interface(ity, defnOpt, _) -> - let _, ty = if tcref.Deref.IsExceptionDecl then [], cenv.g.exn_ty else generalizeTyconRef tcref + let _, ty = if tcref.Deref.IsExceptionDecl then [], g.exn_ty else generalizeTyconRef tcref let m = ity.Range if tcref.IsTypeAbbrev then error(Error(FSComp.SR.tcTypeAbbreviationsCannotHaveInterfaceDeclaration(), m)) if tcref.IsEnumTycon then error(Error(FSComp.SR.tcEnumerationsCannotHaveInterfaceDeclaration(), m)) @@ -14180,22 +14655,22 @@ let TcMutRecDefns_Phase2 cenv envInitial bindsm scopem mutRecNSInfo (envMutRec: let ity' = let envinner = AddDeclaredTypars CheckForDuplicateTypars declaredTyconTypars envForTycon TcTypeAndRecover cenv NoNewTypars CheckCxs ItemOccurence.UseInType envinner emptyUnscopedTyparEnv ity |> fst - if not (isInterfaceTy cenv.g ity') then errorR(Error(FSComp.SR.tcTypeIsNotInterfaceType0(), ity.Range)) + if not (isInterfaceTy g ity') then errorR(Error(FSComp.SR.tcTypeIsNotInterfaceType0(), ity.Range)) - if not (tcref.HasInterface cenv.g ity') then + if not (tcref.HasInterface g ity') then error(Error(FSComp.SR.tcAllImplementedInterfacesShouldBeDeclared(), ity.Range)) - if (typeEquiv cenv.g ity' cenv.g.mk_IComparable_ty && Option.isSome tcref.GeneratedCompareToValues) || - (typeEquiv cenv.g ity' cenv.g.mk_IStructuralComparable_ty && Option.isSome tcref.GeneratedCompareToWithComparerValues) || - (typeEquiv cenv.g ity' ((mkAppTy cenv.g.system_GenericIComparable_tcref [ty])) && Option.isSome tcref.GeneratedCompareToValues) || - (typeEquiv cenv.g ity' ((mkAppTy cenv.g.system_GenericIEquatable_tcref [ty])) && Option.isSome tcref.GeneratedHashAndEqualsWithComparerValues) || - (typeEquiv cenv.g ity' cenv.g.mk_IStructuralEquatable_ty && Option.isSome tcref.GeneratedHashAndEqualsWithComparerValues) then + if (typeEquiv g ity' g.mk_IComparable_ty && Option.isSome tcref.GeneratedCompareToValues) || + (typeEquiv g ity' g.mk_IStructuralComparable_ty && Option.isSome tcref.GeneratedCompareToWithComparerValues) || + (typeEquiv g ity' ((mkAppTy g.system_GenericIComparable_tcref [ty])) && Option.isSome tcref.GeneratedCompareToValues) || + (typeEquiv g ity' ((mkAppTy g.system_GenericIEquatable_tcref [ty])) && Option.isSome tcref.GeneratedHashAndEqualsWithComparerValues) || + (typeEquiv g ity' g.mk_IStructuralEquatable_ty && Option.isSome tcref.GeneratedHashAndEqualsWithComparerValues) then errorR(Error(FSComp.SR.tcDefaultImplementationForInterfaceHasAlreadyBeenAdded(), ity.Range)) if overridesOK = WarnOnOverrides then warning(IntfImplInIntrinsicAugmentation(ity.Range)) if overridesOK = ErrorOnOverrides then errorR(IntfImplInExtrinsicAugmentation(ity.Range)) match defnOpt with - | Some(defn) -> [ (ity', defn, m) ] + | Some defn -> [ (ity', defn, m) ] | _-> [] | _ -> []) @@ -14256,10 +14731,19 @@ let TcMutRecDefns_Phase2 cenv envInitial bindsm scopem mutRecNSInfo (envMutRec: let binds: MutRecDefnsPhase2Info = (envMutRec, mutRecDefns) ||> MutRecShapes.mapTyconsWithEnv (fun envForDecls tyconData -> let (MutRecDefnsPhase2DataForTycon(tyconOpt, _, declKind, tcref, _, _, declaredTyconTypars, _, _, _, fixupFinalAttrs)) = tyconData + let envForDecls = + // This allows to implement protected interface methods if it's a DIM. + // Does not need to be hidden behind a lang version as it needs to be possible to + // implement protected interface methods in lower F# versions regardless if it's a DIM or not. + match tyconOpt with + | Some _ when declKind = DeclKind.ModuleOrMemberBinding -> + MakeInnerEnvForTyconRef envForDecls tcref false + | _ -> + envForDecls let obinds = tyconBindingsOfTypeDefn tyconData let ibinds = let intfTypes = interfacesFromTypeDefn envForDecls tyconData - let slotImplSets = DispatchSlotChecking.GetSlotImplSets cenv.infoReader envForDecls.DisplayEnv false (List.map (fun (ity, _, m) -> (ity, m)) intfTypes) + let slotImplSets = DispatchSlotChecking.GetSlotImplSets cenv.infoReader envForDecls.DisplayEnv envForDecls.AccessRights false (List.map (fun (ity, _, m) -> (ity, m)) intfTypes) (intfTypes, slotImplSets) ||> List.map2 (interfaceMembersFromTypeDefn tyconData) |> List.concat MutRecDefnsPhase2InfoForTycon(tyconOpt, tcref, declaredTyconTypars, declKind, obinds @ ibinds, fixupFinalAttrs)) @@ -14274,22 +14758,23 @@ let TcMutRecDefns_Phase2 cenv envInitial bindsm scopem mutRecNSInfo (envMutRec: module AddAugmentationDeclarations = let tcaugHasNominalInterface g (tcaug: TyconAugmentation) tcref = tcaug.tcaug_interfaces |> List.exists (fun (x, _, _) -> - match tryDestAppTy g x with + match tryTcrefOfAppTy g x with | ValueSome tcref2 when tyconRefEq g tcref2 tcref -> true | _ -> false) let AddGenericCompareDeclarations cenv (env: TcEnv) (scSet: Set) (tycon: Tycon) = - if AugmentWithHashCompare.TyconIsCandidateForAugmentationWithCompare cenv.g tycon && scSet.Contains tycon.Stamp then + let g = cenv.g + if AugmentWithHashCompare.TyconIsCandidateForAugmentationWithCompare g tycon && scSet.Contains tycon.Stamp then let tcref = mkLocalTyconRef tycon let tcaug = tycon.TypeContents - let _, ty = if tcref.Deref.IsExceptionDecl then [], cenv.g.exn_ty else generalizeTyconRef tcref + let _, ty = if tcref.Deref.IsExceptionDecl then [], g.exn_ty else generalizeTyconRef tcref let m = tycon.Range - let genericIComparableTy = mkAppTy cenv.g.system_GenericIComparable_tcref [ty] + let genericIComparableTy = mkAppTy g.system_GenericIComparable_tcref [ty] - let hasExplicitIComparable = tycon.HasInterface cenv.g cenv.g.mk_IComparable_ty - let hasExplicitGenericIComparable = tcaugHasNominalInterface cenv.g tcaug cenv.g.system_GenericIComparable_tcref - let hasExplicitIStructuralComparable = tycon.HasInterface cenv.g cenv.g.mk_IStructuralComparable_ty + let hasExplicitIComparable = tycon.HasInterface g g.mk_IComparable_ty + let hasExplicitGenericIComparable = tcaugHasNominalInterface g tcaug g.system_GenericIComparable_tcref + let hasExplicitIStructuralComparable = tycon.HasInterface g g.mk_IStructuralComparable_ty if hasExplicitIComparable then errorR(Error(FSComp.SR.tcImplementsIComparableExplicitly(tycon.DisplayName), m)) @@ -14299,12 +14784,12 @@ module AddAugmentationDeclarations = elif hasExplicitIStructuralComparable then errorR(Error(FSComp.SR.tcImplementsIStructuralComparableExplicitly(tycon.DisplayName), m)) else - let hasExplicitGenericIComparable = tycon.HasInterface cenv.g genericIComparableTy - let cvspec1, cvspec2 = AugmentWithHashCompare.MakeValsForCompareAugmentation cenv.g tcref - let cvspec3 = AugmentWithHashCompare.MakeValsForCompareWithComparerAugmentation cenv.g tcref + let hasExplicitGenericIComparable = tycon.HasInterface g genericIComparableTy + let cvspec1, cvspec2 = AugmentWithHashCompare.MakeValsForCompareAugmentation g tcref + let cvspec3 = AugmentWithHashCompare.MakeValsForCompareWithComparerAugmentation g tcref - PublishInterface cenv env.DisplayEnv tcref m true cenv.g.mk_IStructuralComparable_ty - PublishInterface cenv env.DisplayEnv tcref m true cenv.g.mk_IComparable_ty + PublishInterface cenv env.DisplayEnv tcref m true g.mk_IStructuralComparable_ty + PublishInterface cenv env.DisplayEnv tcref m true g.mk_IComparable_ty if not tycon.IsExceptionDecl && not hasExplicitGenericIComparable then PublishInterface cenv env.DisplayEnv tcref m true genericIComparableTy tcaug.SetCompare (mkLocalValRef cvspec1, mkLocalValRef cvspec2) @@ -14316,18 +14801,19 @@ module AddAugmentationDeclarations = let AddGenericEqualityWithComparerDeclarations cenv (env: TcEnv) (seSet: Set) (tycon: Tycon) = - if AugmentWithHashCompare.TyconIsCandidateForAugmentationWithEquals cenv.g tycon && seSet.Contains tycon.Stamp then + let g = cenv.g + if AugmentWithHashCompare.TyconIsCandidateForAugmentationWithEquals g tycon && seSet.Contains tycon.Stamp then let tcref = mkLocalTyconRef tycon let tcaug = tycon.TypeContents let m = tycon.Range - let hasExplicitIStructuralEquatable = tycon.HasInterface cenv.g cenv.g.mk_IStructuralEquatable_ty + let hasExplicitIStructuralEquatable = tycon.HasInterface g g.mk_IStructuralEquatable_ty if hasExplicitIStructuralEquatable then errorR(Error(FSComp.SR.tcImplementsIStructuralEquatableExplicitly(tycon.DisplayName), m)) else - let evspec1, evspec2, evspec3 = AugmentWithHashCompare.MakeValsForEqualityWithComparerAugmentation cenv.g tcref - PublishInterface cenv env.DisplayEnv tcref m true cenv.g.mk_IStructuralEquatable_ty + let evspec1, evspec2, evspec3 = AugmentWithHashCompare.MakeValsForEqualityWithComparerAugmentation g tcref + PublishInterface cenv env.DisplayEnv tcref m true g.mk_IStructuralEquatable_ty tcaug.SetHashAndEqualsWith (mkLocalValRef evspec1, mkLocalValRef evspec2, mkLocalValRef evspec3) PublishValueDefn cenv env ModuleOrMemberBinding evspec1 PublishValueDefn cenv env ModuleOrMemberBinding evspec2 @@ -14364,15 +14850,16 @@ module AddAugmentationDeclarations = // We can only add the Equals override after we've done the augmentation because we have to wait until // tycon.HasOverride can give correct results let AddGenericEqualityBindings cenv (env: TcEnv) tycon = - if AugmentWithHashCompare.TyconIsCandidateForAugmentationWithEquals cenv.g tycon then + let g = cenv.g + if AugmentWithHashCompare.TyconIsCandidateForAugmentationWithEquals g tycon then let tcref = mkLocalTyconRef tycon let tcaug = tycon.TypeContents - let _, ty = if tcref.Deref.IsExceptionDecl then [], cenv.g.exn_ty else generalizeTyconRef tcref + let _, ty = if tcref.Deref.IsExceptionDecl then [], g.exn_ty else generalizeTyconRef tcref let m = tycon.Range // Note: tycon.HasOverride only gives correct results after we've done the type augmentation - let hasExplicitObjectEqualsOverride = tycon.HasOverride cenv.g "Equals" [cenv.g.obj_ty] - let hasExplicitGenericIEquatable = tcaugHasNominalInterface cenv.g tcaug cenv.g.system_GenericIEquatable_tcref + let hasExplicitObjectEqualsOverride = tycon.HasOverride g "Equals" [g.obj_ty] + let hasExplicitGenericIEquatable = tcaugHasNominalInterface g tcaug g.system_GenericIEquatable_tcref if hasExplicitGenericIEquatable then errorR(Error(FSComp.SR.tcImplementsIEquatableExplicitly(tycon.DisplayName), m)) @@ -14382,13 +14869,13 @@ module AddAugmentationDeclarations = if not hasExplicitObjectEqualsOverride && Option.isSome tycon.GeneratedHashAndEqualsWithComparerValues then - let vspec1, vspec2 = AugmentWithHashCompare.MakeValsForEqualsAugmentation cenv.g tcref + let vspec1, vspec2 = AugmentWithHashCompare.MakeValsForEqualsAugmentation g tcref tcaug.SetEquals (mkLocalValRef vspec1, mkLocalValRef vspec2) if not tycon.IsExceptionDecl then - PublishInterface cenv env.DisplayEnv tcref m true (mkAppTy cenv.g.system_GenericIEquatable_tcref [ty]) + PublishInterface cenv env.DisplayEnv tcref m true (mkAppTy g.system_GenericIEquatable_tcref [ty]) PublishValueDefn cenv env ModuleOrMemberBinding vspec1 PublishValueDefn cenv env ModuleOrMemberBinding vspec2 - AugmentWithHashCompare.MakeBindingsForEqualsAugmentation cenv.g tycon + AugmentWithHashCompare.MakeBindingsForEqualsAugmentation g tycon else [] else [] @@ -14410,12 +14897,12 @@ module TyconConstraintInference = yield tycon.Stamp ] // Initially, don't assume that the equality relation is dependent on any type variables - let initialAsssumedTypars = Set.empty + let initialAssumedTypars = Set.empty // Repeatedly eliminate structural type definitions whose structural component types no longer support // comparison. On the way record type variables which are support the comparison relation. let rec loop (assumedTycons: Set) (assumedTypars: Set) = - let assumedTyparsAcc = ref assumedTypars + let mutable assumedTyparsAcc = assumedTypars // Checks if a field type supports the 'comparison' constraint based on the assumptions about the type constructors // and type parameters. @@ -14431,7 +14918,7 @@ module TyconConstraintInference = // Within structural types, type parameters can be optimistically assumed to have comparison // We record the ones for which we have made this assumption. elif tycon.TyparsNoRange |> List.exists (fun tp2 -> typarRefEq tp tp2) then - assumedTyparsAcc := (!assumedTyparsAcc).Add(tp.Stamp) + assumedTyparsAcc <- assumedTyparsAcc.Add(tp.Stamp) true else @@ -14481,7 +14968,7 @@ module TyconConstraintInference = // If the type was excluded, say why if not res then match TryFindFSharpBoolAttribute g g.attrib_StructuralComparisonAttribute tycon.Attribs with - | Some(true) -> + | Some true -> match structuralTypes |> List.tryFind (fst >> checkIfFieldTypeSupportsComparison tycon >> not) with | None -> assert false @@ -14491,7 +14978,7 @@ module TyconConstraintInference = errorR(Error(FSComp.SR.tcStructuralComparisonNotSatisfied1(tycon.DisplayName, NicePrint.prettyStringOfTy denv ty), tycon.Range)) else errorR(Error(FSComp.SR.tcStructuralComparisonNotSatisfied2(tycon.DisplayName, NicePrint.prettyStringOfTy denv ty), tycon.Range)) - | Some(false) -> + | Some false -> () | None -> @@ -14511,12 +14998,12 @@ module TyconConstraintInference = res) - if newSet = assumedTycons && assumedTypars = !assumedTyparsAcc then - newSet, !assumedTyparsAcc + if newSet = assumedTycons && assumedTypars = assumedTyparsAcc then + newSet, assumedTyparsAcc else - loop newSet !assumedTyparsAcc + loop newSet assumedTyparsAcc - let uneliminatedTycons, assumedTyparsActual = loop initialAssumedTycons initialAsssumedTypars + let uneliminatedTycons, assumedTyparsActual = loop initialAssumedTycons initialAssumedTypars // OK, we're done, Record the results for the type variable which provide the support for tyconStamp in uneliminatedTycons do @@ -14546,7 +15033,7 @@ module TyconConstraintInference = // Repeatedly eliminate structural type definitions whose structural component types no longer support // equality. On the way add type variables which are support the equality relation let rec loop (assumedTycons: Set) (assumedTypars: Set) = - let assumedTyparsAcc = ref assumedTypars + let mutable assumedTyparsAcc = assumedTypars // Checks if a field type supports the 'equality' constraint based on the assumptions about the type constructors // and type parameters. @@ -14557,10 +15044,10 @@ module TyconConstraintInference = if tp.Constraints |> List.exists (function TyparConstraint.SupportsEquality _ -> true | _ -> false) then true - // Within structural types, type parameters can be optimistically assumed to have ewquality + // Within structural types, type parameters can be optimistically assumed to have equality // We record the ones for which we have made this assumption. elif tycon.Typars(tycon.Range) |> List.exists (fun tp2 -> typarRefEq tp tp2) then - assumedTyparsAcc := (!assumedTyparsAcc).Add(tp.Stamp) + assumedTyparsAcc <- assumedTyparsAcc.Add(tp.Stamp) true else false @@ -14623,7 +15110,7 @@ module TyconConstraintInference = errorR(Error(FSComp.SR.tcStructuralEqualityNotSatisfied2(tycon.DisplayName, NicePrint.prettyStringOfTy denv ty), tycon.Range)) else () - | Some(false) -> + | Some false -> () | None -> if AugmentWithHashCompare.TyconIsCandidateForAugmentationWithEquals cenv.g tycon then @@ -14640,10 +15127,10 @@ module TyconConstraintInference = res) - if newSet = assumedTycons && assumedTypars = !assumedTyparsAcc then - newSet, !assumedTyparsAcc + if newSet = assumedTycons && assumedTypars = assumedTyparsAcc then + newSet, assumedTyparsAcc else - loop newSet !assumedTyparsAcc + loop newSet assumedTyparsAcc let uneliminatedTycons, assumedTyparsActual = loop initialAssumedTycons initialAssumedTypars @@ -14674,7 +15161,7 @@ let CheckForDuplicateConcreteType env nm m = let CheckForDuplicateModule env nm m = let curr = GetCurrAccumulatedModuleOrNamespaceType env - if curr.ModulesAndNamespacesByDemangledName.ContainsKey(nm) then + if curr.ModulesAndNamespacesByDemangledName.ContainsKey nm then errorR (Duplicate(FSComp.SR.tcTypeOrModule(), nm, m)) @@ -14685,21 +15172,33 @@ let CheckForDuplicateModule env nm m = /// Check 'exception' declarations in implementations and signatures module TcExceptionDeclarations = - let TcExnDefnCore_Phase1A cenv env parent (SynExceptionDefnRepr(synAttrs, UnionCase(_, id, _, _, _, _), _, doc, vis, m)) = + let TcExnDefnCore_Phase1A cenv env parent (SynExceptionDefnRepr(Attributes synAttrs, UnionCase(_, id, _, _, _, _), _, doc, vis, m)) = let attrs = TcAttributes cenv env AttributeTargets.ExnDecl synAttrs - if not (String.isUpper id.idText) then errorR(NotUpperCaseConstructor(m)) + if not (String.isUpper id.idText) then errorR(NotUpperCaseConstructor m) let vis, cpath = ComputeAccessAndCompPath env None m vis None parent let vis = TcRecdUnionAndEnumDeclarations.CombineReprAccess parent vis CheckForDuplicateConcreteType env (id.idText + "Exception") id.idRange CheckForDuplicateConcreteType env id.idText id.idRange - NewExn cpath id vis (TExnFresh (MakeRecdFieldsTable [])) attrs (doc.ToXmlDoc()) + let repr = TExnFresh (Construct.MakeRecdFieldsTable []) + Construct.NewExn cpath id vis repr attrs (doc.ToXmlDoc()) let TcExnDefnCore_Phase1G_EstablishRepresentation cenv env parent (exnc: Entity) (SynExceptionDefnRepr(_, UnionCase(_, _, args, _, _, _), reprIdOpt, _, _, m)) = + let g = cenv.g let args = match args with (UnionCaseFields args) -> args | _ -> error(Error(FSComp.SR.tcExplicitTypeSpecificationCannotBeUsedForExceptionConstructors(), m)) let ad = env.eAccessRights let id = exnc.Id - let args' = List.mapi (fun i fdef -> TcRecdUnionAndEnumDeclarations.TcAnonFieldDecl cenv env parent emptyUnscopedTyparEnv ("Data" + string i) fdef) args + let args' = + args |> List.mapi (fun i (Field (idOpt = idOpt) as fdef) -> + match idOpt with + | Some fieldId -> + let tcref = mkLocalTyconRef exnc + let thisTypInst, _ = generalizeTyconRef tcref + let item = Item.RecdField (RecdFieldInfo (thisTypInst, RecdFieldRef (tcref, fieldId.idText))) + CallNameResolutionSink cenv.tcSink (fieldId.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Binding, env.AccessRights) + | _ -> () + + TcRecdUnionAndEnumDeclarations.TcAnonFieldDecl cenv env parent emptyUnscopedTyparEnv (mkExceptionFieldName i) fdef) TcRecdUnionAndEnumDeclarations.ValidateFieldNames(args, args') let repr = match reprIdOpt with @@ -14722,7 +15221,7 @@ module TcExceptionDeclarations = match candidates with | [minfo] -> match minfo.ApparentEnclosingType with - | AppTy cenv.g (tcref, _) as ety when (TypeDefinitelySubsumesTypeNoCoercion 0 cenv.g cenv.amap m cenv.g.exn_ty ety) -> + | AppTy g (tcref, _) as ety when (TypeDefinitelySubsumesTypeNoCoercion 0 g cenv.amap m g.exn_ty ety) -> let tref = tcref.CompiledRepresentationForNamedType TExnAsmRepr tref | _ -> @@ -14732,12 +15231,12 @@ module TcExceptionDeclarations = | _ -> error (Error(FSComp.SR.tcNotAnException(), m)) | None -> - TExnFresh (MakeRecdFieldsTable args') + TExnFresh (Construct.MakeRecdFieldsTable args') exnc.SetExceptionInfo repr let item = Item.ExnCase(mkLocalTyconRef exnc) - CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Binding, env.DisplayEnv, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Binding, env.eAccessRights) args' let private TcExnDefnCore cenv env parent synExnDefnRepr = @@ -14860,7 +15359,7 @@ module EstablishTypeDefinitionCores = let private GetStructuralElementsOfTyconDefn cenv env tpenv (MutRecDefnsPhase1DataForTycon(_, synTyconRepr, _, _, _, _)) tycon = let thisTyconRef = mkLocalTyconRef tycon let m = tycon.Range - let env = AddDeclaredTypars CheckForDuplicateTypars (tycon.Typars(m)) env + let env = AddDeclaredTypars CheckForDuplicateTypars (tycon.Typars m) env let env = MakeInnerEnvForTyconRef env thisTyconRef false [ match synTyconRepr with | SynTypeDefnSimpleRepr.None _ -> () @@ -14890,7 +15389,7 @@ module EstablishTypeDefinitionCores = match implicitCtorSynPats with | None -> () | Some spats -> - let ctorArgNames, (_, names, _) = TcSimplePatsOfUnknownType cenv true NoCheckCxs env tpenv (SynSimplePats.SimplePats (spats, m)) + let ctorArgNames, (_, names, _) = TcSimplePatsOfUnknownType cenv true NoCheckCxs env tpenv spats for arg in ctorArgNames do let ty = names.[arg].Type let m = names.[arg].Ident.idRange @@ -14949,7 +15448,7 @@ module EstablishTypeDefinitionCores = |> set let TcTyconDefnCore_Phase1A_BuildInitialModule cenv envInitial parent typeNames compInfo decls = - let (ComponentInfo(attribs, _parms, _constraints, longPath, xml, _, vis, im)) = compInfo + let (ComponentInfo(Attributes attribs, _parms, _constraints, longPath, xml, _, vis, im)) = compInfo let id = ComputeModuleName longPath let modAttrs = TcAttributes cenv envInitial AttributeTargets.ModuleDecl attribs let modKind = ComputeModuleOrNamespaceKind cenv.g true typeNames modAttrs id.idText @@ -14963,7 +15462,8 @@ module EstablishTypeDefinitionCores = CheckNamespaceModuleOrTypeName cenv.g id let envForDecls, mtypeAcc = MakeInnerEnv envInitial id modKind - let mspec = NewModuleOrNamespace (Some envInitial.eCompPath) vis id (xml.ToXmlDoc()) modAttrs (MaybeLazy.Strict (NewEmptyModuleOrNamespaceType modKind)) + let mty = Construct.NewEmptyModuleOrNamespaceType modKind + let mspec = Construct.NewModuleOrNamespace (Some envInitial.eCompPath) vis id (xml.ToXmlDoc()) modAttrs (MaybeLazy.Strict mty) let innerParent = Parent (mkLocalModRef mspec) let innerTypeNames = TypeNamesInMutRecDecls cenv envForDecls decls MutRecDefnsPhase2DataForModule (mtypeAcc, mspec), (innerParent, innerTypeNames, envForDecls) @@ -15004,9 +15504,11 @@ module EstablishTypeDefinitionCores = let visOfRepr, _ = ComputeAccessAndCompPath env None id.idRange synVisOfRepr None parent let visOfRepr = combineAccess vis visOfRepr // If we supported nested types and modules then additions would be needed here - let lmtyp = MaybeLazy.Strict (NewEmptyModuleOrNamespaceType ModuleOrType) + let lmtyp = MaybeLazy.Strict (Construct.NewEmptyModuleOrNamespaceType ModuleOrType) - NewTycon(cpath, id.idText, id.idRange, vis, visOfRepr, TyparKind.Type, LazyWithContext.NotLazy checkedTypars, doc.ToXmlDoc(), preferPostfix, preEstablishedHasDefaultCtor, hasSelfReferentialCtor, lmtyp) + Construct.NewTycon + (cpath, id.idText, id.idRange, vis, visOfRepr, TyparKind.Type, LazyWithContext.NotLazy checkedTypars, + doc.ToXmlDoc(), preferPostfix, preEstablishedHasDefaultCtor, hasSelfReferentialCtor, lmtyp) //------------------------------------------------------------------------- /// Establishing type definitions: early phase: work out the basic kind of the type definition @@ -15020,7 +15522,7 @@ module EstablishTypeDefinitionCores = /// synTyconInfo: Syntactic AST for the name, attributes etc. of the type constructor /// synTyconRepr: Syntactic AST for the RHS of the type definition let private TcTyconDefnCore_Phase1B_EstablishBasicKind cenv inSig envinner (MutRecDefnsPhase1DataForTycon(synTyconInfo, synTyconRepr, _, _, _, _)) (tycon: Tycon) = - let (ComponentInfo(synAttrs, typars, _, _, _, _, _, _)) = synTyconInfo + let (ComponentInfo(Attributes synAttrs, typars, _, _, _, _, _, _)) = synTyconInfo let m = tycon.Range let id = tycon.Id @@ -15056,18 +15558,20 @@ module EstablishTypeDefinitionCores = if not inSig && not hasMeasureAttr then errorR(Error(FSComp.SR.tcTypeRequiresDefinition(), m)) if hasMeasureAttr then - TFSharpObjectRepr { fsobjmodel_kind=TTyconClass - fsobjmodel_vslots=[] - fsobjmodel_rfields=MakeRecdFieldsTable [] } + TFSharpObjectRepr { fsobjmodel_kind = TTyconClass + fsobjmodel_vslots = [] + fsobjmodel_rfields = Construct.MakeRecdFieldsTable [] } else TNoRepr | TyconCoreAbbrevThatIsReallyAUnion (hasMeasureAttr, envinner, id) (_, m) | SynTypeDefnSimpleRepr.Union (_, _, m) -> + // Run InferTyconKind to raise errors on inconsistent attribute sets InferTyconKind cenv.g (TyconUnion, attrs, [], [], inSig, true, m) |> ignore + // Note: the table of union cases is initially empty - MakeUnionRepr [] + Construct.MakeUnionRepr [] | SynTypeDefnSimpleRepr.TypeAbbrev _ -> // Run InferTyconKind to raise errors on inconsistent attribute sets @@ -15080,10 +15584,12 @@ module EstablishTypeDefinitionCores = TAsmRepr s | SynTypeDefnSimpleRepr.Record (_, _, m) -> + // Run InferTyconKind to raise errors on inconsistent attribute sets InferTyconKind cenv.g (TyconRecord, attrs, [], [], inSig, true, m) |> ignore + // Note: the table of record fields is initially empty - TRecdRepr (MakeRecdFieldsTable []) + TRecdRepr (Construct.MakeRecdFieldsTable []) | SynTypeDefnSimpleRepr.General (kind, _, slotsigs, fields, isConcrete, _, _, _) -> let kind = InferTyconKind cenv.g (kind, attrs, slotsigs, fields, inSig, isConcrete, m) @@ -15099,16 +15605,20 @@ module EstablishTypeDefinitionCores = | TyconStruct -> TTyconStruct | _ -> error(InternalError("should have inferred tycon kind", m)) - let repr = { fsobjmodel_kind=kind - fsobjmodel_vslots=[] - fsobjmodel_rfields=MakeRecdFieldsTable [] } + let repr = + { fsobjmodel_kind = kind + fsobjmodel_vslots = [] + fsobjmodel_rfields = Construct.MakeRecdFieldsTable [] } + TFSharpObjectRepr repr | SynTypeDefnSimpleRepr.Enum _ -> let kind = TTyconEnum - let repr = { fsobjmodel_kind=kind - fsobjmodel_vslots=[] - fsobjmodel_rfields=MakeRecdFieldsTable [] } + let repr = + { fsobjmodel_kind = kind + fsobjmodel_vslots = [] + fsobjmodel_rfields = Construct.MakeRecdFieldsTable [] } + TFSharpObjectRepr repr // OK, now fill in the (partially computed) type representation @@ -15206,10 +15716,10 @@ module EstablishTypeDefinitionCores = let isSuppressRelocate = cenv.g.isInteractive || isForcedSuppressRelocate // Adjust the representation of the container type - let repr = Construct.NewProvidedTyconRepr(resolutionEnvironment, theRootTypeWithRemapping, - Import.ImportProvidedType cenv.amap m, - isSuppressRelocate, - m=m) + let repr = + Construct.NewProvidedTyconRepr(resolutionEnvironment, theRootTypeWithRemapping, + Import.ImportProvidedType cenv.amap m, + isSuppressRelocate, m) tycon.entity_tycon_repr <- repr // Record the details so we can map System.Type --> TyconRef let ilOrigRootTypeRef = GetOriginalILTypeRefOfProvidedType (theRootTypeWithRemapping, m) @@ -15244,8 +15754,8 @@ module EstablishTypeDefinitionCores = let nestedTycon = Construct.NewProvidedTycon(resolutionEnvironment, st, Import.ImportProvidedType cenv.amap m, isSuppressRelocate, - m=m, cpath=cpath, access = access) - eref.ModuleOrNamespaceType.AddProvidedTypeEntity(nestedTycon) + m=m, cpath=cpath, access=access) + eref.ModuleOrNamespaceType.AddProvidedTypeEntity nestedTycon let nestedTyRef = eref.NestedTyconRef nestedTycon let ilOrigTypeRef = GetOriginalILTypeRefOfProvidedType (st, m) @@ -15325,7 +15835,7 @@ module EstablishTypeDefinitionCores = let hasMeasureAttr = HasFSharpAttribute cenv.g cenv.g.attrib_MeasureAttribute attrs let hasMeasureableAttr = HasFSharpAttribute cenv.g cenv.g.attrib_MeasureableAttribute attrs - let envinner = AddDeclaredTypars CheckForDuplicateTypars (tycon.Typars(m)) envinner + let envinner = AddDeclaredTypars CheckForDuplicateTypars (tycon.Typars m) envinner let envinner = MakeInnerEnvForTyconRef envinner thisTyconRef false match synTyconRepr with @@ -15361,7 +15871,7 @@ module EstablishTypeDefinitionCores = if not firstPass then let ftyvs = freeInTypeLeftToRight cenv.g false ty - let typars = tycon.Typars(m) + let typars = tycon.Typars m if ftyvs.Length <> typars.Length then errorR(Deprecated(FSComp.SR.tcTypeAbbreviationHasTypeParametersMissingOnType(), tycon.Range)) @@ -15373,7 +15883,7 @@ module EstablishTypeDefinitionCores = with e -> errorRecovery e m - // Third phase: check and publish the supr types. Run twice, once before constraints are established + // Third phase: check and publish the super types. Run twice, once before constraints are established // and once after let private TcTyconDefnCore_Phase1D_Phase1F_EstablishSuperTypesAndInterfaceTypes cenv tpenv inSig pass (envMutRec, mutRecDefns: MutRecShape<(_ * (Tycon * (Attribs * _)) option), _, _, _, _> list) = let checkCxs = if (pass = SecondPass) then CheckCxs else NoCheckCxs @@ -15387,7 +15897,7 @@ module EstablishTypeDefinitionCores = let (MutRecDefnsPhase1DataForTycon(_, synTyconRepr, explicitImplements, _, _, _)) = typeDefCore let m = tycon.Range let tcref = mkLocalTyconRef tycon - let envinner = AddDeclaredTypars CheckForDuplicateTypars (tycon.Typars(m)) envinner + let envinner = AddDeclaredTypars CheckForDuplicateTypars (tycon.Typars m) envinner let envinner = MakeInnerEnvForTyconRef envinner tcref false let implementedTys, _ = List.mapFold (mapFoldFst (TcTypeAndRecover cenv NoNewTypars checkCxs ItemOccurence.UseInType envinner)) tpenv explicitImplements @@ -15485,6 +15995,7 @@ module EstablishTypeDefinitionCores = /// Establish the fields, dispatch slots and union cases of a type let private TcTyconDefnCore_Phase1G_EstablishRepresentation cenv envinner tpenv inSig (MutRecDefnsPhase1DataForTycon(_, synTyconRepr, _, _, _, _)) (tycon: Tycon) (attrs: Attribs) = + let g = cenv.g let m = tycon.Range try let id = tycon.Id @@ -15492,22 +16003,22 @@ module EstablishTypeDefinitionCores = let innerParent = Parent thisTyconRef let thisTyInst, thisTy = generalizeTyconRef thisTyconRef - let hasAbstractAttr = HasFSharpAttribute cenv.g cenv.g.attrib_AbstractClassAttribute attrs + let hasAbstractAttr = HasFSharpAttribute g g.attrib_AbstractClassAttribute attrs let hasSealedAttr = // The special case is needed for 'unit' because the 'Sealed' attribute is not yet available when this type is defined. - if cenv.g.compilingFslib && id.idText = "Unit" then + if g.compilingFslib && id.idText = "Unit" then Some true else - TryFindFSharpBoolAttribute cenv.g cenv.g.attrib_SealedAttribute attrs - let hasMeasureAttr = HasFSharpAttribute cenv.g cenv.g.attrib_MeasureAttribute attrs + TryFindFSharpBoolAttribute g g.attrib_SealedAttribute attrs + let hasMeasureAttr = HasFSharpAttribute g g.attrib_MeasureAttribute attrs // REVIEW: for hasMeasureableAttr we need to be stricter about checking these - // are only used on exactly the right kinds of type definitions and not inconjunction with other attributes. - let hasMeasureableAttr = HasFSharpAttribute cenv.g cenv.g.attrib_MeasureableAttribute attrs - let hasCLIMutable = HasFSharpAttribute cenv.g cenv.g.attrib_CLIMutableAttribute attrs + // are only used on exactly the right kinds of type definitions and not in conjunction with other attributes. + let hasMeasureableAttr = HasFSharpAttribute g g.attrib_MeasureableAttribute attrs + let hasCLIMutable = HasFSharpAttribute g g.attrib_CLIMutableAttribute attrs - let structLayoutAttr = TryFindFSharpInt32Attribute cenv.g cenv.g.attrib_StructLayoutAttribute attrs - let hasAllowNullLiteralAttr = TryFindFSharpBoolAttribute cenv.g cenv.g.attrib_AllowNullLiteralAttribute attrs = Some(true) + let structLayoutAttr = TryFindFSharpInt32Attribute g g.attrib_StructLayoutAttribute attrs + let hasAllowNullLiteralAttr = TryFindFSharpBoolAttribute g g.attrib_AllowNullLiteralAttribute attrs = Some true if hasAbstractAttr then tycon.TypeContents.tcaug_abstract <- true @@ -15522,26 +16033,26 @@ module EstablishTypeDefinitionCores = let allowNullLiteralAttributeCheck() = if hasAllowNullLiteralAttr then - tycon.TypeContents.tcaug_super |> Option.iter (fun ty -> if not (TypeNullIsExtraValue cenv.g m ty) then errorR (Error(FSComp.SR.tcAllowNullTypesMayOnlyInheritFromAllowNullTypes(), m))) - tycon.ImmediateInterfaceTypesOfFSharpTycon |> List.iter (fun ty -> if not (TypeNullIsExtraValue cenv.g m ty) then errorR (Error(FSComp.SR.tcAllowNullTypesMayOnlyInheritFromAllowNullTypes(), m))) + tycon.TypeContents.tcaug_super |> Option.iter (fun ty -> if not (TypeNullIsExtraValue g m ty) then errorR (Error(FSComp.SR.tcAllowNullTypesMayOnlyInheritFromAllowNullTypes(), m))) + tycon.ImmediateInterfaceTypesOfFSharpTycon |> List.iter (fun ty -> if not (TypeNullIsExtraValue g m ty) then errorR (Error(FSComp.SR.tcAllowNullTypesMayOnlyInheritFromAllowNullTypes(), m))) - let structLayoutAttributeCheck(allowed) = + let structLayoutAttributeCheck allowed = let explicitKind = int32 System.Runtime.InteropServices.LayoutKind.Explicit match structLayoutAttr with | Some kind -> if allowed then if kind = explicitKind then - warning(PossibleUnverifiableCode(m)) + warning(PossibleUnverifiableCode m) elif List.isEmpty (thisTyconRef.Typars m) then errorR (Error(FSComp.SR.tcOnlyStructsCanHaveStructLayout(), m)) else errorR (Error(FSComp.SR.tcGenericTypesCannotHaveStructLayout(), m)) | None -> () - let hiddenReprChecks(hasRepr) = - structLayoutAttributeCheck(false) - if hasSealedAttr = Some(false) || (hasRepr && hasSealedAttr <> Some(true) && not (id.idText = "Unit" && cenv.g.compilingFslib) ) then + let hiddenReprChecks hasRepr = + structLayoutAttributeCheck false + if hasSealedAttr = Some false || (hasRepr && hasSealedAttr <> Some true && not (id.idText = "Unit" && g.compilingFslib) ) then errorR(Error(FSComp.SR.tcRepresentationOfTypeHiddenBySignature(), m)) if hasAbstractAttr then errorR (Error(FSComp.SR.tcOnlyClassesCanHaveAbstract(), m)) @@ -15552,8 +16063,8 @@ module EstablishTypeDefinitionCores = let noCLIMutableAttributeCheck() = if hasCLIMutable then errorR (Error(FSComp.SR.tcThisTypeMayNotHaveACLIMutableAttribute(), m)) - let noSealedAttributeCheck(k) = - if hasSealedAttr = Some(true) then errorR (Error(k(), m)) + let noSealedAttributeCheck k = + if hasSealedAttr = Some true then errorR (Error(k(), m)) let noFieldsCheck(fields': RecdField list) = match fields' with @@ -15561,7 +16072,7 @@ module EstablishTypeDefinitionCores = | _ -> () - let envinner = AddDeclaredTypars CheckForDuplicateTypars (tycon.Typars(m)) envinner + let envinner = AddDeclaredTypars CheckForDuplicateTypars (tycon.Typars m) envinner let envinner = MakeInnerEnvForTyconRef envinner thisTyconRef false @@ -15576,7 +16087,7 @@ module EstablishTypeDefinitionCores = let nenv' = AddFakeNameToNameEnv fspec.Name nenv (Item.RecdField info) // Name resolution gives better info for tooltips let item = FreshenRecdFieldRef cenv.nameResolver m (thisTyconRef.MakeNestedRecdFieldRef fspec) - CallNameResolutionSink cenv.tcSink (fspec.Range, nenv, item, item, emptyTyparInst, ItemOccurence.Binding, envinner.DisplayEnv, ad) + CallNameResolutionSink cenv.tcSink (fspec.Range, nenv, item, emptyTyparInst, ItemOccurence.Binding, ad) // Environment is needed for completions CallEnvSink cenv.tcSink (fspec.Range, nenv', ad) @@ -15589,7 +16100,7 @@ module EstablishTypeDefinitionCores = let nenv' = AddFakeNameToNameEnv unionCase.Id.idText nenv (Item.UnionCase(info, false)) // Report to both - as in previous function let item = Item.UnionCase(info, false) - CallNameResolutionSink cenv.tcSink (unionCase.Range, nenv, item, item, emptyTyparInst, ItemOccurence.Binding, envinner.DisplayEnv, ad) + CallNameResolutionSink cenv.tcSink (unionCase.Range, nenv, item, emptyTyparInst, ItemOccurence.Binding, ad) CallEnvSink cenv.tcSink (unionCase.Id.idRange, nenv', ad) let typeRepr, baseValOpt, safeInitInfo = @@ -15601,12 +16112,12 @@ module EstablishTypeDefinitionCores = TNoRepr, None, NoSafeInitInfo | SynTypeDefnSimpleRepr.None _ -> - hiddenReprChecks(false) + hiddenReprChecks false noAllowNullLiteralAttributeCheck() if hasMeasureAttr then let repr = TFSharpObjectRepr { fsobjmodel_kind=TTyconClass fsobjmodel_vslots=[] - fsobjmodel_rfields= MakeRecdFieldsTable [] } + fsobjmodel_rfields= Construct.MakeRecdFieldsTable [] } repr, None, NoSafeInitInfo else TNoRepr, None, NoSafeInitInfo @@ -15617,18 +16128,18 @@ module EstablishTypeDefinitionCores = // "type x = | A" can always be used instead. | TyconCoreAbbrevThatIsReallyAUnion (hasMeasureAttr, envinner, id) (unionCaseName, _) -> - structLayoutAttributeCheck(false) + structLayoutAttributeCheck false noAllowNullLiteralAttributeCheck() TcRecdUnionAndEnumDeclarations.CheckUnionCaseName cenv unionCaseName - let unionCase = NewUnionCase unionCaseName [] thisTy [] XmlDoc.Empty tycon.Accessibility + let unionCase = Construct.NewUnionCase unionCaseName [] thisTy [] XmlDoc.Empty tycon.Accessibility writeFakeUnionCtorsToSink [ unionCase ] - MakeUnionRepr [ unionCase ], None, NoSafeInitInfo + Construct.MakeUnionRepr [ unionCase ], None, NoSafeInitInfo - | SynTypeDefnSimpleRepr.TypeAbbrev(ParserDetail.ThereWereSignificantParseErrorsSoDoNotTypecheckThisNode, _rhsType, _) -> + | SynTypeDefnSimpleRepr.TypeAbbrev(ParserDetail.ErrorRecovery, _rhsType, _) -> TNoRepr, None, NoSafeInitInfo | SynTypeDefnSimpleRepr.TypeAbbrev(ParserDetail.Ok, rhsType, _) -> - if hasSealedAttr = Some(true) then + if hasSealedAttr = Some true then errorR (Error(FSComp.SR.tcAbbreviatedTypesCannotBeSealed(), m)) noAbstractClassAttributeCheck() noAllowNullLiteralAttributeCheck() @@ -15649,8 +16160,8 @@ module EstablishTypeDefinitionCores = noSealedAttributeCheck FSComp.SR.tcTypesAreAlwaysSealedDU noAbstractClassAttributeCheck() noAllowNullLiteralAttributeCheck() - structLayoutAttributeCheck(false) - let unionCases = TcRecdUnionAndEnumDeclarations.TcUnionCaseDecls cenv envinner innerParent thisTy tpenv unionCases + structLayoutAttributeCheck false + let unionCases = TcRecdUnionAndEnumDeclarations.TcUnionCaseDecls cenv envinner innerParent thisTy thisTyInst tpenv unionCases if tycon.IsStructRecordOrUnionTycon && unionCases.Length > 1 then let fieldNames = [ for uc in unionCases do for ft in uc.FieldTable.TrueInstanceFieldsAsList do yield ft.Name ] @@ -15658,25 +16169,25 @@ module EstablishTypeDefinitionCores = errorR(Error(FSComp.SR.tcStructUnionMultiCaseDistinctFields(), m)) writeFakeUnionCtorsToSink unionCases - MakeUnionRepr unionCases, None, NoSafeInitInfo + Construct.MakeUnionRepr unionCases, None, NoSafeInitInfo | SynTypeDefnSimpleRepr.Record (_, fields, _) -> noMeasureAttributeCheck() noSealedAttributeCheck FSComp.SR.tcTypesAreAlwaysSealedRecord noAbstractClassAttributeCheck() noAllowNullLiteralAttributeCheck() - structLayoutAttributeCheck(true) // these are allowed for records + structLayoutAttributeCheck true // these are allowed for records let recdFields = TcRecdUnionAndEnumDeclarations.TcNamedFieldDecls cenv envinner innerParent false tpenv fields recdFields |> CheckDuplicates (fun f -> f.Id) "field" |> ignore writeFakeRecordFieldsToSink recdFields - TRecdRepr (MakeRecdFieldsTable recdFields), None, NoSafeInitInfo + TRecdRepr (Construct.MakeRecdFieldsTable recdFields), None, NoSafeInitInfo | SynTypeDefnSimpleRepr.LibraryOnlyILAssembly (s, _) -> noCLIMutableAttributeCheck() noMeasureAttributeCheck() noSealedAttributeCheck FSComp.SR.tcTypesAreAlwaysSealedAssemblyCode noAllowNullLiteralAttributeCheck() - structLayoutAttributeCheck(false) + structLayoutAttributeCheck false noAbstractClassAttributeCheck() TAsmRepr s, None, NoSafeInitInfo @@ -15689,22 +16200,22 @@ module EstablishTypeDefinitionCores = () | Some spats -> if tycon.IsFSharpStructOrEnumTycon then - let ctorArgNames, (_, names, _) = TcSimplePatsOfUnknownType cenv true CheckCxs envinner tpenv (SynSimplePats.SimplePats (spats, m)) + let ctorArgNames, (_, names, _) = TcSimplePatsOfUnknownType cenv true CheckCxs envinner tpenv spats for arg in ctorArgNames do let ty = names.[arg].Type let id = names.[arg].Ident let taccess = TAccess [envinner.eAccessPath] - yield NewRecdField false None id false ty false false [(*no property attributes*)] [(*no field attributes *)] XmlDoc.Empty taccess (*compiler generated:*)true ] + yield Construct.NewRecdField false None id false ty false false [] [] XmlDoc.Empty taccess true ] (userFields @ implicitStructFields) |> CheckDuplicates (fun f -> f.Id) "field" |> ignore writeFakeRecordFieldsToSink userFields let superTy = tycon.TypeContents.tcaug_super - let containerInfo = TyconContainerInfo(innerParent, thisTyconRef, thisTyconRef.Typars(m), NoSafeInitInfo) - let kind = InferTyconKind cenv.g (kind, attrs, slotsigs, fields, inSig, isConcrete, m) + let containerInfo = TyconContainerInfo(innerParent, thisTyconRef, thisTyconRef.Typars m, NoSafeInitInfo) + let kind = InferTyconKind g (kind, attrs, slotsigs, fields, inSig, isConcrete, m) match kind with | TyconHiddenRepr -> - hiddenReprChecks(true) + hiddenReprChecks true noAllowNullLiteralAttributeCheck() TNoRepr, None, NoSafeInitInfo | _ -> @@ -15713,9 +16224,9 @@ module EstablishTypeDefinitionCores = // until "isSealedTy" and "isClassTy" give reliable results. superTy |> Option.iter (fun ty -> let m = match inherits with | [] -> m | ((_, m, _) :: _) -> m - if isSealedTy cenv.g ty then + if isSealedTy g ty then errorR(Error(FSComp.SR.tcCannotInheritFromSealedType(), m)) - elif not (isClassTy cenv.g ty) then + elif not (isClassTy g ty) then errorR(Error(FSComp.SR.tcCannotInheritFromInterfaceType(), m))) let kind = @@ -15727,16 +16238,16 @@ module EstablishTypeDefinitionCores = noAllowNullLiteralAttributeCheck() if not (isNil slotsigs) then errorR (Error(FSComp.SR.tcStructTypesCannotContainAbstractMembers(), m)) - structLayoutAttributeCheck(true) + structLayoutAttributeCheck true TTyconStruct | TyconInterface -> - if hasSealedAttr = Some(true) then errorR (Error(FSComp.SR.tcInterfaceTypesCannotBeSealed(), m)) + if hasSealedAttr = Some true then errorR (Error(FSComp.SR.tcInterfaceTypesCannotBeSealed(), m)) noCLIMutableAttributeCheck() - structLayoutAttributeCheck(false) + structLayoutAttributeCheck false noAbstractClassAttributeCheck() allowNullLiteralAttributeCheck() - noFieldsCheck(userFields) + noFieldsCheck userFields TTyconInterface | TyconClass -> noCLIMutableAttributeCheck() @@ -15746,15 +16257,15 @@ module EstablishTypeDefinitionCores = | TyconDelegate (ty, arity) -> noCLIMutableAttributeCheck() noSealedAttributeCheck FSComp.SR.tcTypesAreAlwaysSealedDelegate - structLayoutAttributeCheck(false) + structLayoutAttributeCheck false noAllowNullLiteralAttributeCheck() noAbstractClassAttributeCheck() - noFieldsCheck(userFields) + noFieldsCheck userFields let ty', _ = TcTypeAndRecover cenv NoNewTypars CheckCxs ItemOccurence.UseInType envinner tpenv ty - let _, curriedArgInfos, returnTy, _ = GetTopValTypeInCompiledForm cenv.g (arity |> TranslateTopValSynInfo m (TcAttributes cenv envinner) |> TranslatePartialArity []) ty' m + let _, curriedArgInfos, returnTy, _ = GetTopValTypeInCompiledForm g (arity |> TranslateTopValSynInfo m (TcAttributes cenv envinner) |> TranslatePartialArity []) ty' m if curriedArgInfos.Length < 1 then error(Error(FSComp.SR.tcInvalidDelegateSpecification(), m)) if curriedArgInfos.Length > 1 then error(Error(FSComp.SR.tcDelegatesCannotBeCurried(), m)) - let ttps = thisTyconRef.Typars(m) + let ttps = thisTyconRef.Typars m let fparams = curriedArgInfos.Head |> List.map MakeSlotParam TTyconDelegate (MakeSlotSig("Invoke", thisTy, ttps, [], [fparams], returnTy)) | _ -> @@ -15775,7 +16286,7 @@ module EstablishTypeDefinitionCores = | ((_, m, baseIdOpt) :: _) -> match baseIdOpt with | None -> Some(ident("base", m)) - | Some id -> Some(id) + | Some id -> Some id let abstractSlots = [ for (valSpfn, memberFlags) in slotsigs do @@ -15791,28 +16302,29 @@ module EstablishTypeDefinitionCores = for slot in slots do yield mkLocalValRef slot ] - let baseValOpt = MakeAndPublishBaseVal cenv envinner baseIdOpt (superOfTycon cenv.g tycon) + let baseValOpt = MakeAndPublishBaseVal cenv envinner baseIdOpt (superOfTycon g tycon) let safeInitInfo = ComputeInstanceSafeInitInfo cenv envinner thisTyconRef.Range thisTy let safeInitFields = match safeInitInfo with SafeInitField (_, fld) -> [fld] | NoSafeInitInfo -> [] let repr = TFSharpObjectRepr - { fsobjmodel_kind=kind - fsobjmodel_vslots= abstractSlots - fsobjmodel_rfields=MakeRecdFieldsTable (userFields @ implicitStructFields @ safeInitFields) } + { fsobjmodel_kind = kind + fsobjmodel_vslots = abstractSlots + fsobjmodel_rfields = Construct.MakeRecdFieldsTable (userFields @ implicitStructFields @ safeInitFields) } repr, baseValOpt, safeInitInfo | SynTypeDefnSimpleRepr.Enum (decls, m) -> let fieldTy, fields' = TcRecdUnionAndEnumDeclarations.TcEnumDecls cenv envinner innerParent thisTy decls let kind = TTyconEnum - structLayoutAttributeCheck(false) + structLayoutAttributeCheck false noCLIMutableAttributeCheck() noSealedAttributeCheck FSComp.SR.tcTypesAreAlwaysSealedEnum noAllowNullLiteralAttributeCheck() - let vfld = NewRecdField false None (ident("value__", m)) false fieldTy false false [] [] XmlDoc.Empty taccessPublic true + let vid = ident("value__", m) + let vfld = Construct.NewRecdField false None vid false fieldTy false false [] [] XmlDoc.Empty taccessPublic true - let legitEnumTypes = [ cenv.g.int32_ty; cenv.g.int16_ty; cenv.g.sbyte_ty; cenv.g.int64_ty; cenv.g.char_ty; cenv.g.bool_ty; cenv.g.uint32_ty; cenv.g.uint16_ty; cenv.g.byte_ty; cenv.g.uint64_ty ] - if not (ListSet.contains (typeEquiv cenv.g) fieldTy legitEnumTypes) then + let legitEnumTypes = [ g.int32_ty; g.int16_ty; g.sbyte_ty; g.int64_ty; g.char_ty; g.bool_ty; g.uint32_ty; g.uint16_ty; g.byte_ty; g.uint64_ty ] + if not (ListSet.contains (typeEquiv g) fieldTy legitEnumTypes) then errorR(Error(FSComp.SR.tcInvalidTypeForLiteralEnumeration(), m)) writeFakeRecordFieldsToSink fields' @@ -15820,18 +16332,18 @@ module EstablishTypeDefinitionCores = TFSharpObjectRepr { fsobjmodel_kind=kind fsobjmodel_vslots=[] - fsobjmodel_rfields= MakeRecdFieldsTable (vfld :: fields') } + fsobjmodel_rfields= Construct.MakeRecdFieldsTable (vfld :: fields') } repr, None, NoSafeInitInfo tycon.entity_tycon_repr <- typeRepr // We check this just after establishing the representation - if TyconHasUseNullAsTrueValueAttribute cenv.g tycon && not (CanHaveUseNullAsTrueValueAttribute cenv.g tycon) then + if TyconHasUseNullAsTrueValueAttribute g tycon && not (CanHaveUseNullAsTrueValueAttribute g tycon) then errorR(Error(FSComp.SR.tcInvalidUseNullAsTrueValue(), m)) // validate ConditionalAttribute, should it be applied (it's only valid on a type if the type is an attribute type) - match attrs |> List.tryFind (IsMatchingFSharpAttribute cenv.g cenv.g.attrib_ConditionalAttribute) with + match attrs |> List.tryFind (IsMatchingFSharpAttribute g g.attrib_ConditionalAttribute) with | Some _ -> - if not(ExistsInEntireHierarchyOfType (fun t -> typeEquiv cenv.g t (mkAppTy cenv.g.tcref_System_Attribute [])) cenv.g cenv.amap m AllowMultiIntfInstantiations.Yes thisTy) then + if not(ExistsInEntireHierarchyOfType (fun t -> typeEquiv g t (mkAppTy g.tcref_System_Attribute [])) g cenv.amap m AllowMultiIntfInstantiations.Yes thisTy) then errorR(Error(FSComp.SR.tcConditionalAttributeUsage(), m)) | _ -> () @@ -15849,7 +16361,7 @@ module EstablishTypeDefinitionCores = match stripTyparEqns ty with | TType_anon (_,l) | TType_tuple (_, l) -> accInAbbrevTypes l acc - | TType_ucase (UCRef(tc, _), tinst) + | TType_ucase (UnionCaseRef(tc, _), tinst) | TType_app (tc, tinst) -> let tycon2 = tc.Deref let acc = accInAbbrevTypes tinst acc @@ -15901,6 +16413,7 @@ module EstablishTypeDefinitionCores = /// Check that a set of type definitions is free of inheritance cycles let TcTyconDefnCore_CheckForCyclicStructsAndInheritance cenv tycons = + let g = cenv.g // Overview: // Given several tycons now being defined (the "initial" tycons). // Look for cycles in inheritance and struct-field-containment. @@ -15942,10 +16455,10 @@ module EstablishTypeDefinitionCores = if ListSet.contains (===) tycon2 tycons && // note: only add if tycon2 is initial not (List.exists (fun (tc, tc2) -> tc === tycon && tc2 === tycon2) acc) // note: only add if (tycon, tycon2) not already an edge then - (tycon, tycon2)::acc + (tycon, tycon2) :: acc else acc // note: all edges added are (tycon, _) let insertEdgeToType ty acc = - match tryDestAppTy cenv.g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref -> insertEdgeToTycon tcref.Deref acc | _ -> @@ -15969,9 +16482,9 @@ module EstablishTypeDefinitionCores = fspec.IsStatic && (structTycon === tycon2) && (structTyInst, tinst2) ||> List.lengthsEqAndForall2 (fun ty1 ty2 -> - match tryDestTyparTy cenv.g ty1 with + match tryDestTyparTy g ty1 with | ValueSome destTypar1 -> - match tryDestTyparTy cenv.g ty2 with + match tryDestTyparTy g ty2 with | ValueSome destTypar2 -> typarEq destTypar1 destTypar2 | _ -> false | _ -> false) @@ -15988,7 +16501,7 @@ module EstablishTypeDefinitionCores = // collect edges from the fields of a given struct type. and accStructFields includeStaticFields ty (structTycon: Tycon) tinst (doneTypes, acc) = - if List.exists (typeEquiv cenv.g ty) doneTypes then + if List.exists (typeEquiv g ty) doneTypes then // This type (type instance) has been seen before, so no need to collect the same edges again (and avoid loops!) doneTypes, acc else @@ -16018,7 +16531,7 @@ module EstablishTypeDefinitionCores = let acc = // Note: only the nominal type counts - let super = superOfTycon cenv.g tycon + let super = superOfTycon g tycon insertEdgeToType super acc let acc = // Note: only the nominal type counts @@ -16041,7 +16554,7 @@ module EstablishTypeDefinitionCores = | (typeDefCore, _, _), Some (tycon: Tycon) -> let (MutRecDefnsPhase1DataForTycon(synTyconInfo, _, _, _, _, _)) = typeDefCore let (ComponentInfo(_, _, synTyconConstraints, _, _, _, _, _)) = synTyconInfo - let envForTycon = AddDeclaredTypars CheckForDuplicateTypars (tycon.Typars(m)) envForDecls + let envForTycon = AddDeclaredTypars CheckForDuplicateTypars (tycon.Typars m) envForDecls let thisTyconRef = mkLocalTyconRef tycon let envForTycon = MakeInnerEnvForTyconRef envForTycon thisTyconRef false try TcTyparConstraints cenv NoNewTypars checkCxs ItemOccurence.UseInType envForTycon tpenv synTyconConstraints |> ignore @@ -16050,7 +16563,7 @@ module EstablishTypeDefinitionCores = let TcMutRecDefns_Phase1 mkLetInfo cenv envInitial parent typeNames inSig tpenv m scopem mutRecNSInfo (mutRecDefns: MutRecShapes) = - + let g = cenv.g // Phase1A - build Entity for type definitions, exception definitions and module definitions. // Also for abbreviations of any of these. Augmentations are skipped in this phase. let withEntities = @@ -16155,7 +16668,7 @@ module EstablishTypeDefinitionCores = // No inferred constraints allowed on declared typars (envMutRecPrelim, withEnvs) ||> MutRecShapes.iterTyconsWithEnv (fun envForDecls (_, tyconOpt) -> - tyconOpt |> Option.iter (fun tycon -> tycon.Typars(m) |> List.iter (SetTyparRigid cenv.g envForDecls.DisplayEnv m))) + tyconOpt |> Option.iter (fun tycon -> tycon.Typars m |> List.iter (SetTyparRigid g envForDecls.DisplayEnv m))) // Phase1E. OK, now recheck the abbreviations, super/interface and explicit constraints types (this time checking constraints) (envMutRecPrelim, withAttrs) ||> MutRecShapes.iterTyconsWithEnv (fun envForDecls (origInfo, tyconAndAttrsOpt) -> @@ -16207,7 +16720,8 @@ module TcDeclarations = /// Given a type definition, compute whether its members form an extension of an existing type, and if so if it is an /// intrinsic or extrinsic extension - let private ComputeTyconDeclKind tyconOpt isAtOriginalTyconDefn cenv envForDecls inSig m (synTypars: SynTyparDecl list) synTyparCxs longPath = + let private ComputeTyconDeclKind cenv envForDecls tyconOpt isAtOriginalTyconDefn inSig m (synTypars: SynTyparDecl list) synTyparCxs longPath = + let g = cenv.g let ad = envForDecls.eAccessRights let tcref = @@ -16235,7 +16749,7 @@ module TcDeclarations = tcref.Deref.IsFSharpDelegateTycon || tcref.Deref.IsFSharpEnumTycon - let reqTypars = tcref.Typars(m) + let reqTypars = tcref.Typars m // Member definitions are intrinsic (added directly to the type) if: // a) For interfaces, only if it is in the original defn. @@ -16252,20 +16766,20 @@ module TcDeclarations = | _ -> //false // There is a special case we allow when compiling FSharp.Core.dll which permits interface implementations across namespace fragments - cenv.g.compilingFslib && tcref.LogicalName.StartsWithOrdinal("Tuple`") + g.compilingFslib && tcref.LogicalName.StartsWithOrdinal("Tuple`") let nReqTypars = reqTypars.Length let declaredTypars = TcTyparDecls cenv envForDecls synTypars let envForTycon = AddDeclaredTypars CheckForDuplicateTypars declaredTypars envForDecls let _tpenv = TcTyparConstraints cenv NoNewTypars CheckCxs ItemOccurence.UseInType envForTycon emptyUnscopedTyparEnv synTyparCxs - declaredTypars |> List.iter (SetTyparRigid cenv.g envForDecls.DisplayEnv m) + declaredTypars |> List.iter (SetTyparRigid g envForDecls.DisplayEnv m) if isInSameModuleOrNamespace && not isInterfaceOrDelegateOrEnum then // For historical reasons we only give a warning for incorrect type parameters on intrinsic extensions if nReqTypars <> synTypars.Length then warning(Error(FSComp.SR.tcDeclaredTypeParametersForExtensionDoNotMatchOriginal(tcref.DisplayNameWithStaticParametersAndUnderscoreTypars), m)) - if not (typarsAEquiv cenv.g TypeEquivEnv.Empty reqTypars declaredTypars) then + if not (typarsAEquiv g TypeEquivEnv.Empty reqTypars declaredTypars) then warning(Error(FSComp.SR.tcDeclaredTypeParametersForExtensionDoNotMatchOriginal(tcref.DisplayNameWithStaticParametersAndUnderscoreTypars), m)) // Note we return 'reqTypars' for intrinsic extensions since we may only have given warnings IntrinsicExtensionBinding, reqTypars @@ -16274,7 +16788,7 @@ module TcDeclarations = errorR(Error(FSComp.SR.tcMembersThatExtendInterfaceMustBePlacedInSeparateModule(), tcref.Range)) if nReqTypars <> synTypars.Length then error(Error(FSComp.SR.tcDeclaredTypeParametersForExtensionDoNotMatchOriginal(tcref.DisplayNameWithStaticParametersAndUnderscoreTypars), m)) - if not (typarsAEquiv cenv.g TypeEquivEnv.Empty reqTypars declaredTypars) then + if not (typarsAEquiv g TypeEquivEnv.Empty reqTypars declaredTypars) then errorR(Error(FSComp.SR.tcDeclaredTypeParametersForExtensionDoNotMatchOriginal(tcref.DisplayNameWithStaticParametersAndUnderscoreTypars), m)) ExtrinsicExtensionBinding, declaredTypars @@ -16310,11 +16824,11 @@ module TcDeclarations = // atMostOne inherit. let private CheckMembersForm ds = match ds with - | d::ds when isImplicitCtor d -> + | d :: ds when isImplicitCtor d -> // Implicit construction let ds = match ds with - | d::ds when isImplicitInherit d -> ds // skip inherit call if it comes next + | d :: ds when isImplicitInherit d -> ds // skip inherit call if it comes next | _ -> ds // Skip over 'let' and 'do' bindings @@ -16362,13 +16876,14 @@ module TcDeclarations = match trepr with | SynTypeDefnRepr.ObjectModel(kind, cspec, m) -> CheckMembersForm cspec - let fields = cspec |> List.choose (function SynMemberDefn.ValField (f, _) -> Some(f) | _ -> None) + let fields = cspec |> List.choose (function SynMemberDefn.ValField (f, _) -> Some f | _ -> None) let implements2 = cspec |> List.choose (function SynMemberDefn.Interface (ty, _, _) -> Some(ty, ty.Range) | _ -> None) - let inherits = cspec |> List.choose (function - | SynMemberDefn.Inherit (ty, idOpt, m) -> Some(ty, m, idOpt) - | SynMemberDefn.ImplicitInherit (ty, _, idOpt, m) -> Some(ty, m, idOpt) - | _ -> None) - //let nestedTycons = cspec |> List.choose (function SynMemberDefn.NestedType (x, _, _) -> Some(x) | _ -> None) + let inherits = + cspec |> List.choose (function + | SynMemberDefn.Inherit (ty, idOpt, m) -> Some(ty, m, idOpt) + | SynMemberDefn.ImplicitInherit (ty, _, idOpt, m) -> Some(ty, m, idOpt) + | _ -> None) + //let nestedTycons = cspec |> List.choose (function SynMemberDefn.NestedType (x, _, _) -> Some x | _ -> None) let slotsigs = cspec |> List.choose (function SynMemberDefn.AbstractSlot (x, y, _) -> Some(x, y) | _ -> None) let members = @@ -16388,22 +16903,23 @@ module TcDeclarations = | SynMemberDefn.Inherit _ | SynMemberDefn.AbstractSlot _ -> false) - // Convert autoproperties to let bindings in the pre-list + // Convert auto properties to let bindings in the pre-list let rec preAutoProps memb = match memb with - | SynMemberDefn.AutoProperty (attribs, isStatic, id, tyOpt, propKind, _, xmlDoc, _access, synExpr, _mGetSet, mWholeAutoProp) -> + | SynMemberDefn.AutoProperty(Attributes attribs, isStatic, id, tyOpt, propKind, _, xmlDoc, _access, synExpr, _mGetSet, 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) let mLetPortion = synExpr.Range let fldId = ident (CompilerGeneratedName id.idText, mLetPortion) - let headPat = SynPat.LongIdent (LongIdentWithDots([fldId], []), None, Some noInferredTypars, SynConstructorArgs.Pats [], None, mLetPortion) + let headPat = SynPat.LongIdent (LongIdentWithDots([fldId], []), None, Some noInferredTypars, SynArgPats.Pats [], None, mLetPortion) let retInfo = match tyOpt with None -> None | Some ty -> Some (SynReturnInfo((ty, SynInfo.unnamedRetVal), ty.Range)) let isMutable = match propKind with | MemberKind.PropertySet | MemberKind.PropertyGetSet -> true | _ -> false - let binding = mkSynBinding (xmlDoc, headPat) (None, false, isMutable, mLetPortion, NoSequencePointAtInvisibleBinding, retInfo, synExpr, synExpr.Range, [], attribs, None) + let attribs = mkAttributeList attribs mWholeAutoProp + let binding = mkSynBinding (xmlDoc, headPat) (None, false, isMutable, mLetPortion, NoDebugPointAtInvisibleBinding, retInfo, synExpr, synExpr.Range, [], attribs, None) [(SynMemberDefn.LetBindings ([binding], isStatic, false, mWholeAutoProp))] @@ -16414,16 +16930,16 @@ module TcDeclarations = | SynMemberDefn.ImplicitInherit _ -> [memb] | _ -> [] - // Convert autoproperties to member bindings in the post-list + // Convert auto properties to member bindings in the post-list let rec postAutoProps memb = match memb with - | SynMemberDefn.AutoProperty (attribs, isStatic, id, tyOpt, propKind, memberFlags, xmlDoc, access, _synExpr, mGetSetOpt, _mWholeAutoProp) -> + | SynMemberDefn.AutoProperty(Attributes attribs, isStatic, id, tyOpt, propKind, memberFlags, xmlDoc, access, _synExpr, mGetSetOpt, _mWholeAutoProp) -> let mMemberPortion = id.idRange // Only the keep the non-field-targeted attributes let attribs = attribs |> List.filter (fun a -> match a.Target with Some t when t.idText = "field" -> false | _ -> true) let fldId = ident (CompilerGeneratedName id.idText, mMemberPortion) let headPatIds = if isStatic then [id] else [ident ("__", mMemberPortion);id] - let headPat = SynPat.LongIdent (LongIdentWithDots(headPatIds, []), None, Some noInferredTypars, SynConstructorArgs.Pats [], None, mMemberPortion) + let headPat = SynPat.LongIdent (LongIdentWithDots(headPatIds, []), None, Some noInferredTypars, SynArgPats.Pats [], None, mMemberPortion) match propKind, mGetSetOpt with | MemberKind.PropertySet, Some m -> errorR(Error(FSComp.SR.parsMutableOnAutoPropertyShouldBeGetSetNotJustSet(), m)) @@ -16437,7 +16953,8 @@ module TcDeclarations = let getter = let rhsExpr = SynExpr.Ident fldId let retInfo = match tyOpt with None -> None | Some ty -> Some (SynReturnInfo((ty, SynInfo.unnamedRetVal), ty.Range)) - let binding = mkSynBinding (xmlDoc, headPat) (access, false, false, mMemberPortion, NoSequencePointAtInvisibleBinding, retInfo, rhsExpr, rhsExpr.Range, [], attribs, Some (memberFlags MemberKind.Member)) + let attribs = mkAttributeList attribs mMemberPortion + let binding = mkSynBinding (xmlDoc, headPat) (access, false, false, mMemberPortion, NoDebugPointAtInvisibleBinding, retInfo, rhsExpr, rhsExpr.Range, [], attribs, Some (memberFlags MemberKind.Member)) SynMemberDefn.Member (binding, mMemberPortion) yield getter | _ -> () @@ -16447,10 +16964,10 @@ module TcDeclarations = | MemberKind.PropertyGetSet -> let setter = let vId = ident("v", mMemberPortion) - let headPat = SynPat.LongIdent (LongIdentWithDots(headPatIds, []), None, Some noInferredTypars, SynConstructorArgs.Pats [mkSynPatVar None vId], None, mMemberPortion) + let headPat = SynPat.LongIdent (LongIdentWithDots(headPatIds, []), None, Some noInferredTypars, SynArgPats.Pats [mkSynPatVar None vId], None, mMemberPortion) let rhsExpr = mkSynAssign (SynExpr.Ident fldId) (SynExpr.Ident vId) //let retInfo = match tyOpt with None -> None | Some ty -> Some (SynReturnInfo((ty, SynInfo.unnamedRetVal), ty.Range)) - let binding = mkSynBinding (xmlDoc, headPat) (access, false, false, mMemberPortion, NoSequencePointAtInvisibleBinding, None, rhsExpr, rhsExpr.Range, [], [], Some (memberFlags MemberKind.PropertySet)) + let binding = mkSynBinding (xmlDoc, headPat) (access, false, false, mMemberPortion, NoDebugPointAtInvisibleBinding, None, rhsExpr, rhsExpr.Range, [], [], Some (memberFlags MemberKind.PropertySet)) SynMemberDefn.Member (binding, mMemberPortion) yield setter | _ -> ()] @@ -16490,16 +17007,16 @@ module TcDeclarations = let implicitCtorSynPats = members |> List.tryPick (function - | SynMemberDefn.ImplicitCtor (_, _, spats, _, _) -> Some spats + | SynMemberDefn.ImplicitCtor (_, _, (SynSimplePats.SimplePats _ as spats), _, _) -> Some spats | _ -> None) // An ugly bit of code to pre-determine if a type has a nullary constructor, prior to establishing the // members of the type let preEstablishedHasDefaultCtor = members |> List.exists (function - | SynMemberDefn.Member(Binding(_, _, _, _, _, _, SynValData(Some memberFlags, _, _), SynPatForConstructorDecl(SynPatForNullaryArgs), _, _, _, _), _) -> + | SynMemberDefn.Member(Binding(_, _, _, _, _, _, SynValData(Some memberFlags, _, _), SynPatForConstructorDecl SynPatForNullaryArgs, _, _, _, _), _) -> memberFlags.MemberKind=MemberKind.Constructor - | SynMemberDefn.ImplicitCtor (_, _, spats, _, _) -> isNil spats + | SynMemberDefn.ImplicitCtor (_, _, SynSimplePats.SimplePats(spats, _), _, _) -> isNil spats | _ -> false) let repr = SynTypeDefnSimpleRepr.General(kind, inherits, slotsigs, fields, isConcrete, isIncrClass, implicitCtorSynPats, m) let isAtOriginalTyconDefn = not (isAugmentationTyconDefnRepr repr) @@ -16513,7 +17030,7 @@ module TcDeclarations = let core = MutRecDefnsPhase1DataForTycon(synTyconInfo, repr, implements1, false, false, isAtOriginalTyconDefn) core, members @ extraMembers - | SynTypeDefnRepr.Exception(r) -> + | SynTypeDefnRepr.Exception r -> let isAtOriginalTyconDefn = true let core = MutRecDefnsPhase1DataForTycon(synTyconInfo, SynTypeDefnSimpleRepr.Exception r, implements1, false, false, isAtOriginalTyconDefn) core, extraMembers @@ -16540,7 +17057,7 @@ module TcDeclarations = let (MutRecDefnsPhase1DataForTycon(synTyconInfo, _, _, _, _, isAtOriginalTyconDefn)) = typeDefnCore let tyDeclRange = synTyconInfo.Range let (ComponentInfo(_, typars, cs, longPath, _, _, _, _)) = synTyconInfo - let declKind, tcref, declaredTyconTypars = ComputeTyconDeclKind tyconOpt isAtOriginalTyconDefn cenv envForDecls false tyDeclRange typars cs longPath + let declKind, tcref, declaredTyconTypars = ComputeTyconDeclKind cenv envForDecls tyconOpt isAtOriginalTyconDefn false tyDeclRange typars cs longPath let newslotsOK = (if isAtOriginalTyconDefn && tcref.IsFSharpObjectModelTycon then NewSlotsOK else NoNewSlots) if (declKind = ExtrinsicExtensionBinding) && isByrefTyconRef cenv.g tcref then @@ -16549,6 +17066,11 @@ module TcDeclarations = if not (isNil members) && tcref.IsTypeAbbrev then errorR(Error(FSComp.SR.tcTypeAbbreviationsCannotHaveAugmentations(), tyDeclRange)) + let (ComponentInfo (attributes, _, _, _, _, _, _, _)) = synTyconInfo + if not (List.isEmpty attributes) && (declKind = ExtrinsicExtensionBinding || declKind = IntrinsicExtensionBinding) then + let attributeRange = (List.head attributes).Range + error(Error(FSComp.SR.tcAugmentationsCannotHaveAttributes(), attributeRange)) + MutRecDefnsPhase2DataForTycon(tyconOpt, innerParent, declKind, tcref, baseValOpt, safeInitInfo, declaredTyconTypars, members, tyDeclRange, newslotsOK, fixupFinalAttrs)) // By now we've established the full contents of type definitions apart from their @@ -16601,10 +17123,10 @@ module TcDeclarations = match trepr with | SynTypeDefnSigRepr.ObjectModel(kind, cspec, m) -> - let fields = cspec |> List.choose (function SynMemberSig.ValField (f, _) -> Some(f) | _ -> None) + let fields = cspec |> List.choose (function SynMemberSig.ValField (f, _) -> Some f | _ -> None) let implements2 = cspec |> List.choose (function SynMemberSig.Interface (ty, m) -> Some(ty, m) | _ -> None) let inherits = cspec |> List.choose (function SynMemberSig.Inherit (ty, _) -> Some(ty, m, None) | _ -> None) - //let nestedTycons = cspec |> List.choose (function SynMemberSig.NestedType (x, _) -> Some(x) | _ -> None) + //let nestedTycons = cspec |> List.choose (function SynMemberSig.NestedType (x, _) -> Some x | _ -> None) let slotsigs = cspec |> List.choose (function SynMemberSig.Member (v, fl, _) when fl.IsDispatchSlot -> Some(v, fl) | _ -> None) let members = cspec |> List.filter (function | SynMemberSig.Interface _ -> true @@ -16643,7 +17165,7 @@ module TcDeclarations = let tyconCore = MutRecDefnsPhase1DataForTycon (synTyconInfo, r, implements1, false, false, isAtOriginalTyconDefn) tyconCore, (synTyconInfo, extraMembers) - | SynTypeDefnSigRepr.Exception(r) -> + | SynTypeDefnSigRepr.Exception r -> let isAtOriginalTyconDefn = true let core = MutRecDefnsPhase1DataForTycon(synTyconInfo, SynTypeDefnSimpleRepr.Exception r, implements1, false, false, isAtOriginalTyconDefn) core, (synTyconInfo, extraMembers) @@ -16661,7 +17183,7 @@ module TcDeclarations = let tpenv = emptyUnscopedTyparEnv let (MutRecDefnsPhase1DataForTycon (_, _, _, _, _, isAtOriginalTyconDefn)) = tyconCore let (ComponentInfo(_, typars, cs, longPath, _, _, _, m)) = synTyconInfo - let declKind, tcref, declaredTyconTypars = ComputeTyconDeclKind tyconOpt isAtOriginalTyconDefn cenv envForDecls true m typars cs longPath + let declKind, tcref, declaredTyconTypars = ComputeTyconDeclKind cenv envForDecls tyconOpt isAtOriginalTyconDefn true m typars cs longPath let envForTycon = AddDeclaredTypars CheckForDuplicateTypars declaredTyconTypars envForDecls let envForTycon = MakeInnerEnvForTyconRef envForTycon tcref (declKind = ExtrinsicExtensionBinding) @@ -16679,7 +17201,10 @@ module TcDeclarations = /// Bind a collection of mutually recursive declarations in a signature file let TcMutRecSignatureDecls cenv envInitial parent typeNames tpenv m scopem mutRecNSInfo (mutRecSigs: MutRecSigsInitialData) = let mutRecSigsAfterSplit = mutRecSigs |> MutRecShapes.mapTycons SplitTyconSignature - let _tycons, envMutRec, mutRecDefnsAfterCore = EstablishTypeDefinitionCores.TcMutRecDefns_Phase1 (fun containerInfo valDecl -> (containerInfo, valDecl)) cenv envInitial parent typeNames true tpenv m scopem mutRecNSInfo mutRecSigsAfterSplit + let _tycons, envMutRec, mutRecDefnsAfterCore = + EstablishTypeDefinitionCores.TcMutRecDefns_Phase1 + (fun containerInfo valDecl -> (containerInfo, valDecl)) + cenv envInitial parent typeNames true tpenv m scopem mutRecNSInfo mutRecSigsAfterSplit // Updates the types of the modules to contain the contents so far, which now includes values and members MutRecBindingChecking.TcMutRecDefns_UpdateModuleContents mutRecNSInfo mutRecDefnsAfterCore @@ -16735,13 +17260,13 @@ let rec TcSignatureElementNonMutRec cenv parent typeNames endm (env: TcEnv) synS match parent with | ParentNone -> error(NumberedError(FSComp.SR.tcNamespaceCannotContainValues(), vspec.RangeOfId)) | Parent p -> p - let containerInfo = ModuleOrNamespaceContainerInfo(parentModule) + let containerInfo = ModuleOrNamespaceContainerInfo parentModule let idvs, _ = TcAndPublishValSpec (cenv, env, containerInfo, ModuleOrMemberBinding, None, emptyUnscopedTyparEnv, vspec) let scopem = unionRanges m endm let env = List.foldBack (AddLocalVal cenv.tcSink scopem) idvs env return env - | SynModuleSigDecl.NestedModule(ComponentInfo(attribs, _parms, _constraints, longPath, xml, _, vis, im) as compInfo, isRec, mdefs, m) -> + | SynModuleSigDecl.NestedModule(ComponentInfo(Attributes attribs, _parms, _constraints, longPath, xml, _, vis, im) as compInfo, isRec, mdefs, m) -> if isRec then // Treat 'module rec M = ...' as a single mutually recursive definition group 'module M = ...' let modDecl = SynModuleSigDecl.NestedModule(compInfo, false, mdefs, m) @@ -16759,7 +17284,8 @@ let rec TcSignatureElementNonMutRec cenv parent typeNames endm (env: TcEnv) synS // Now typecheck the signature, accumulating and then recording the submodule description. let id = ident (modName, id.idRange) - let mspec = NewModuleOrNamespace (Some env.eCompPath) vis id (xml.ToXmlDoc()) attribs (MaybeLazy.Strict (NewEmptyModuleOrNamespaceType modKind)) + let mty = Construct.NewEmptyModuleOrNamespaceType modKind + let mspec = Construct.NewModuleOrNamespace (Some env.eCompPath) vis id (xml.ToXmlDoc()) attribs (MaybeLazy.Strict mty) let! (mtyp, _) = TcModuleOrNamespaceSignatureElementsNonMutRec cenv (Parent (mkLocalModRef mspec)) env (id, modKind, mdefs, m, xml) @@ -16774,7 +17300,7 @@ let rec TcSignatureElementNonMutRec cenv parent typeNames endm (env: TcEnv) synS let resolved = match p with | [] -> Result [] - | id::rest -> ResolveLongIndentAsModuleOrNamespace cenv.tcSink ResultCollectionSettings.AllResults cenv.amap m true OpenQualified env.eNameResEnv ad id rest false + | id :: rest -> ResolveLongIndentAsModuleOrNamespaceOrStaticClass cenv.tcSink ResultCollectionSettings.AllResults cenv.amap m false true OpenQualified env.eNameResEnv ad id rest false let mvvs = ForceRaise resolved let scopem = unionRanges m endm let unfilteredModrefs = mvvs |> List.map p23 @@ -16824,7 +17350,7 @@ let rec TcSignatureElementNonMutRec cenv parent typeNames endm (env: TcEnv) synS mspecNSs |> List.iter (fun mspec -> let modref = mkLocalModRef mspec let item = Item.ModuleOrNamespaces [modref] - CallNameResolutionSink cenv.tcSink (mspec.Range, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Binding, env.DisplayEnv, env.eAccessRights)) + CallNameResolutionSink cenv.tcSink (mspec.Range, env.NameEnv, item, emptyTyparInst, ItemOccurence.Binding, env.eAccessRights)) // For 'namespace rec' and 'module rec' we add the thing being defined let envNS = if isRec then AddLocalRootModuleOrNamespace cenv.tcSink cenv.g cenv.amap m envNS mtypRoot else envNS @@ -16879,13 +17405,13 @@ and TcSignatureElementsNonMutRec cenv parent typeNames endm env defs = return! Eventually.fold (TcSignatureElementNonMutRec cenv parent typeNames endm) env defs } -and TcSignatureElementsMutRec cenv parent typeNames endm mutRecNSInfo envInitial (defs: SynModuleSigDecl list) = +and TcSignatureElementsMutRec cenv parent typeNames m mutRecNSInfo envInitial (defs: SynModuleSigDecl list) = eventually { - let m = match defs with [] -> endm | _ -> defs |> List.map (fun d -> d.Range) |> List.reduce unionRanges - let scopem = (defs, endm) ||> List.foldBack (fun h m -> unionRanges h.Range m) + let m = match defs with [] -> m | _ -> defs |> List.map (fun d -> d.Range) |> List.reduce unionRanges + let scopem = (defs, m) ||> List.foldBack (fun h m -> unionRanges h.Range m) let mutRecDefns = - let rec loop isNamespace defs: MutRecSigsInitialData = + let rec loop isNamespace moduleRange defs: MutRecSigsInitialData = ((true, true), defs) ||> List.collectFold (fun (openOk, moduleAbbrevOk) def -> match def with | SynModuleSigDecl.Types (typeSpecs, _) -> @@ -16894,7 +17420,7 @@ and TcSignatureElementsMutRec cenv parent typeNames endm mutRecNSInfo envInitial | SynModuleSigDecl.Open (lid, m) -> if not openOk then errorR(Error(FSComp.SR.tcOpenFirstInMutRec(), m)) - let decls = [ MutRecShape.Open (MutRecDataForOpen(lid, m)) ] + let decls = [ MutRecShape.Open (MutRecDataForOpen(lid, m, moduleRange)) ] decls, (openOk, moduleAbbrevOk) | SynModuleSigDecl.Exception (SynExceptionSig(exnRepr, members, _), _) -> @@ -16905,12 +17431,12 @@ and TcSignatureElementsMutRec cenv parent typeNames endm mutRecNSInfo envInitial | SynModuleSigDecl.Val (vspec, _) -> if isNamespace then error(NumberedError(FSComp.SR.tcNamespaceCannotContainValues(), vspec.RangeOfId)) - let decls = [ MutRecShape.Lets(vspec) ] + let decls = [ MutRecShape.Lets vspec ] decls, (false, false) - | SynModuleSigDecl.NestedModule(compInfo, isRec, synDefs, _) -> + | SynModuleSigDecl.NestedModule(compInfo, isRec, synDefs, moduleRange) -> if isRec then warning(Error(FSComp.SR.tcRecImplied(), compInfo.Range)) - let mutRecDefs = loop false synDefs + let mutRecDefs = loop false moduleRange synDefs let decls = [MutRecShape.Module (compInfo, mutRecDefs)] decls, (false, false) @@ -16926,7 +17452,7 @@ and TcSignatureElementsMutRec cenv parent typeNames endm mutRecNSInfo envInitial error(Error(FSComp.SR.tcUnsupportedMutRecDecl(), def.Range))) |> fst - loop (match parent with ParentNone -> true | Parent _ -> false) defs + loop (match parent with ParentNone -> true | Parent _ -> false) m defs return TcDeclarations.TcMutRecSignatureDecls cenv envInitial parent typeNames emptyUnscopedTyparEnv m scopem mutRecNSInfo mutRecDefns } @@ -17034,7 +17560,7 @@ let rec TcModuleOrNamespaceElementNonMutRec (cenv: cenv) parent typeNames scopem return (id, []), env, env | Parent parentModule -> - let containerInfo = ModuleOrNamespaceContainerInfo(parentModule) + let containerInfo = ModuleOrNamespaceContainerInfo parentModule if letrec then let scopem = unionRanges m scopem let binds = binds |> List.map (fun bind -> RecDefnBindingInfo(containerInfo, NoNewSlots, ModuleOrMemberBinding, bind)) @@ -17046,7 +17572,7 @@ let rec TcModuleOrNamespaceElementNonMutRec (cenv: cenv) parent typeNames scopem | SynModuleDecl.DoExpr _ -> return! failwith "unreachable" - | SynModuleDecl.Attributes (synAttrs, _) -> + | SynModuleDecl.Attributes (Attributes synAttrs, _) -> let attrs, _ = TcAttributesWithPossibleTargets false cenv env AttributeTargets.Top synAttrs return ((fun e -> e), attrs), env, env @@ -17061,7 +17587,7 @@ let rec TcModuleOrNamespaceElementNonMutRec (cenv: cenv) parent typeNames scopem let modDecl = SynModuleDecl.NestedModule(compInfo, false, mdefs, isContinuingModule, m) return! TcModuleOrNamespaceElementsMutRec cenv parent typeNames m env None [modDecl] else - let (ComponentInfo(attribs, _parms, _constraints, longPath, xml, _, vis, im)) = compInfo + let (ComponentInfo(Attributes attribs, _parms, _constraints, longPath, xml, _, vis, im)) = compInfo let id = ComputeModuleName longPath let modAttrs = TcAttributes cenv env AttributeTargets.ModuleDecl attribs @@ -17080,7 +17606,8 @@ let rec TcModuleOrNamespaceElementNonMutRec (cenv: cenv) parent typeNames scopem // Create the new module specification to hold the accumulated results of the type of the module // Also record this in the environment as the accumulator - let mspec = NewModuleOrNamespace (Some env.eCompPath) vis id (xml.ToXmlDoc()) modAttrs (MaybeLazy.Strict (NewEmptyModuleOrNamespaceType modKind)) + let mty = Construct.NewEmptyModuleOrNamespaceType modKind + let mspec = Construct.NewModuleOrNamespace (Some env.eCompPath) vis id (xml.ToXmlDoc()) modAttrs (MaybeLazy.Strict mty) // Now typecheck. let! mexpr, topAttrsNew, envAtEnd = TcModuleOrNamespaceElements cenv (Parent (mkLocalModRef mspec)) endm envForModule xml None mdefs @@ -17105,7 +17632,7 @@ let rec TcModuleOrNamespaceElementNonMutRec (cenv: cenv) parent typeNames scopem | SynModuleDecl.NamespaceFragment(SynModuleOrNamespace(longId, isRec, kind, defs, xml, attribs, vis, m)) -> - if !progress then dprintn ("Typecheck implementation " + textOfLid longId) + if progress then dprintn ("Typecheck implementation " + textOfLid longId) let endm = m.EndRange do for id in longId do @@ -17135,7 +17662,7 @@ let rec TcModuleOrNamespaceElementNonMutRec (cenv: cenv) parent typeNames scopem mspecNSs |> List.iter (fun mspec -> let modref = mkLocalModRef mspec let item = Item.ModuleOrNamespaces [modref] - CallNameResolutionSink cenv.tcSink (mspec.Range, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Binding, env.DisplayEnv, env.eAccessRights)) + CallNameResolutionSink cenv.tcSink (mspec.Range, env.NameEnv, item, emptyTyparInst, ItemOccurence.Binding, env.eAccessRights)) // For 'namespace rec' and 'module rec' we add the thing being defined let envNS = if isRec then AddLocalRootModuleOrNamespace cenv.tcSink cenv.g cenv.amap m envNS mtypRoot else envNS @@ -17192,14 +17719,14 @@ and TcModuleOrNamespaceElementsNonMutRec cenv parent typeNames endm (defsSoFar, } /// The mutually recursive case for a sequence of declarations (and nested modules) -and TcModuleOrNamespaceElementsMutRec cenv parent typeNames endm envInitial mutRecNSInfo (defs: SynModuleDecl list) = +and TcModuleOrNamespaceElementsMutRec cenv parent typeNames m envInitial mutRecNSInfo (defs: SynModuleDecl list) = eventually { - let m = match defs with [] -> endm | _ -> defs |> List.map (fun d -> d.Range) |> List.reduce unionRanges - let scopem = (defs, endm) ||> List.foldBack (fun h m -> unionRanges h.Range m) + let m = match defs with [] -> m | _ -> defs |> List.map (fun d -> d.Range) |> List.reduce unionRanges + let scopem = (defs, m) ||> List.foldBack (fun h m -> unionRanges h.Range m) - let (mutRecDefns, (_, _, synAttrs)) = - let rec loop isNamespace attrs defs: (MutRecDefnsInitialData * _) = + let (mutRecDefns, (_, _, Attributes synAttrs)) = + let rec loop isNamespace moduleRange attrs defs: (MutRecDefnsInitialData * _) = ((true, true, attrs), defs) ||> List.collectFold (fun (openOk, moduleAbbrevOk, attrs) def -> match ElimModuleDoBinding def with @@ -17216,15 +17743,15 @@ and TcModuleOrNamespaceElementsMutRec cenv parent typeNames endm envInitial mutR else List.map (List.singleton >> MutRecShape.Lets) binds binds, (false, false, attrs) - | SynModuleDecl.NestedModule(compInfo, isRec, synDefs, _isContinuingModule, _) -> + | SynModuleDecl.NestedModule(compInfo, isRec, synDefs, _isContinuingModule, moduleRange) -> if isRec then warning(Error(FSComp.SR.tcRecImplied(), compInfo.Range)) - let mutRecDefs, (_, _, attrs) = loop false attrs synDefs + let mutRecDefs, (_, _, attrs) = loop false moduleRange attrs synDefs let decls = [MutRecShape.Module (compInfo, mutRecDefs)] decls, (false, false, attrs) | SynModuleDecl.Open (LongIdentWithDots(lid, _), m) -> if not openOk then errorR(Error(FSComp.SR.tcOpenFirstInMutRec(), m)) - let decls = [ MutRecShape.Open (MutRecDataForOpen(lid, m)) ] + let decls = [ MutRecShape.Open (MutRecDataForOpen(lid, m, moduleRange)) ] decls, (openOk, moduleAbbrevOk, attrs) | SynModuleDecl.Exception (SynExceptionDefn(repr, members, _), _m) -> @@ -17248,7 +17775,7 @@ and TcModuleOrNamespaceElementsMutRec cenv parent typeNames endm envInitial mutR | (SynModuleDecl.NamespaceFragment _ as d) -> error(Error(FSComp.SR.tcUnsupportedMutRecDecl(), d.Range))) - loop (match parent with ParentNone -> true | Parent _ -> false) [] defs + loop (match parent with ParentNone -> true | Parent _ -> false) m [] defs let tpenv = emptyUnscopedTyparEnv let mutRecDefnsChecked, envAfter = TcDeclarations.TcMutRecDefinitions cenv envInitial parent typeNames tpenv m scopem mutRecNSInfo mutRecDefns @@ -17328,7 +17855,7 @@ let ApplyAssemblyLevelAutoOpenAttributeToTcEnv g amap (ccu: CcuThunk) scopem env | ValueNone -> warn() | ValueSome _ -> let openDecl = OpenDeclaration.Create ([], [modref], scopem, false) - OpenModulesOrNamespaces TcResultsSink.NoSink g amap scopem root env [modref] openDecl + OpenEntities TcResultsSink.NoSink g amap scopem root env [modref] openDecl // Add the CCU and apply the "AutoOpen" attributes let AddCcuToTcEnv(g, amap, scopem, env, assemblyName, ccu, autoOpens, internalsVisible) = @@ -17389,27 +17916,15 @@ let ApplyDefaults cenv g denvAtEnd m mexpr extraAttribs = try let unsolved = FSharp.Compiler.FindUnsolved.UnsolvedTyparsOfModuleDef g cenv.amap denvAtEnd (mexpr, extraAttribs) - GeneralizationHelpers.CanonicalizePartialInferenceProblem (cenv, denvAtEnd, m) unsolved + ConstraintSolver.CanonicalizePartialInferenceProblem cenv.css denvAtEnd m unsolved - let applyDefaults priority = - unsolved |> List.iter (fun tp -> + // The priority order comes from the order of declaration of the defaults in FSharp.Core. + for priority = 10 downto 0 do + unsolved |> List.iter (fun tp -> if not tp.IsSolved then // Apply the first default. If we're defaulting one type variable to another then // the defaults will be propagated to the new type variable. - tp.Constraints |> List.iter (fun tpc -> - match tpc with - | TyparConstraint.DefaultsTo(priority2, ty2, m) when priority2 = priority -> - let ty1 = mkTyparTy tp - if not tp.IsSolved && not (typeEquiv cenv.g ty1 ty2) then - let csenv = MakeConstraintSolverEnv ContextInfo.NoContext cenv.css m denvAtEnd - TryD (fun () -> ConstraintSolver.SolveTyparEqualsType csenv 0 m NoTrace ty1 ty2) - (fun e -> solveTypAsError cenv denvAtEnd m ty1 - ErrorD(ErrorFromApplyingDefault(g, denvAtEnd, tp, ty2, e, m))) - |> RaiseOperationResult - | _ -> ())) - - for priority = 10 downto 0 do - applyDefaults priority + ConstraintSolver.ApplyTyparDefaultAtPriority denvAtEnd cenv.css priority tp) // OK, now apply defaults for any unsolved HeadTypeStaticReq unsolved |> List.iter (fun tp -> @@ -17488,14 +18003,14 @@ let TypeCheckOneImplFile (g, niceNameGen, amap, topCcu, checkForErrors, conditionalDefines, tcSink, isInternalTestSpanStackReferring) env (rootSigOpt: ModuleOrNamespaceType option) - (ParsedImplFileInput(_, isScript, qualNameOfFile, scopedPragmas, _, implFileFrags, isLastCompiland)) = + (ParsedImplFileInput (_, isScript, qualNameOfFile, scopedPragmas, _, implFileFrags, isLastCompiland)) = eventually { let cenv = cenv.Create (g, isScript, niceNameGen, amap, topCcu, false, Option.isSome rootSigOpt, conditionalDefines, tcSink, (LightweightTcValForUsingInBuildMethodCall g), isInternalTestSpanStackReferring) let envinner, mtypeAcc = MakeInitialEnv env - let defs = [ for x in implFileFrags -> SynModuleDecl.NamespaceFragment(x) ] + let defs = [ for x in implFileFrags -> SynModuleDecl.NamespaceFragment x ] let! mexpr, topAttrs, envAtEnd = TcModuleOrNamespaceElements cenv ParentNone qualNameOfFile.Range envinner PreXmlDocEmpty None defs let implFileTypePriorToSig = !mtypeAcc @@ -17570,7 +18085,7 @@ let TypeCheckOneImplFile // Warn on version attributes. topAttrs.assemblyAttrs |> List.iter (function - | Attrib(tref, _, [ AttribExpr(Expr.Const (Const.String(version), range, _), _) ], _, _, _, _) -> + | Attrib(tref, _, [ AttribExpr(Expr.Const (Const.String version, range, _), _) ], _, _, _, _) -> let attrName = tref.CompiledRepresentationForNamedType.FullName let isValid() = try IL.parseILVersion version |> ignore; true @@ -17582,7 +18097,7 @@ let TypeCheckOneImplFile | _ -> () | _ -> ()) - let implFile = TImplFile(qualNameOfFile, scopedPragmas, implFileExprAfterSig, hasExplicitEntryPoint, isScript, anonRecdTypes) + let implFile = TImplFile (qualNameOfFile, scopedPragmas, implFileExprAfterSig, hasExplicitEntryPoint, isScript, anonRecdTypes) return (topAttrs, implFile, implFileTypePriorToSig, envAtEnd, cenv.createsGeneratedProvidedTypes) } @@ -17590,12 +18105,12 @@ let TypeCheckOneImplFile /// Check an entire signature file -let TypeCheckOneSigFile (g, niceNameGen, amap, topCcu, checkForErrors, conditionalDefines, tcSink, isInternalTestSpanStackReferring) tcEnv (ParsedSigFileInput(_, qualNameOfFile, _, _, sigFileFrags)) = +let TypeCheckOneSigFile (g, niceNameGen, amap, topCcu, checkForErrors, conditionalDefines, tcSink, isInternalTestSpanStackReferring) tcEnv (ParsedSigFileInput (_, qualNameOfFile, _, _, sigFileFrags)) = eventually { let cenv = cenv.Create (g, false, niceNameGen, amap, topCcu, true, false, conditionalDefines, tcSink, (LightweightTcValForUsingInBuildMethodCall g), isInternalTestSpanStackReferring) let envinner, mtypeAcc = MakeInitialEnv tcEnv - let specs = [ for x in sigFileFrags -> SynModuleSigDecl.NamespaceFragment(x) ] + let specs = [ for x in sigFileFrags -> SynModuleSigDecl.NamespaceFragment x ] let! tcEnv = TcSignatureElements cenv ParentNone qualNameOfFile.Range envinner PreXmlDocEmpty None specs let sigFileType = !mtypeAcc diff --git a/src/fcs-fable/src/fsharp/TypeChecker.fsi b/src/fcs-fable/src/fsharp/TypeChecker.fsi index 09856e0489..d18adc7629 100644 --- a/src/fcs-fable/src/fsharp/TypeChecker.fsi +++ b/src/fcs-fable/src/fsharp/TypeChecker.fsi @@ -6,15 +6,14 @@ open FSharp.Compiler open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AccessibilityLogic -open FSharp.Compiler.Ast -open FSharp.Compiler.Range -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.Infos open FSharp.Compiler.Import +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree open FSharp.Compiler.TcGlobals - -open System.Collections.Generic +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps [] type TcEnv = @@ -41,9 +40,9 @@ val CombineTopAttrs : TopAttribs -> TopAttribs -> TopAttribs val TypeCheckOneImplFile : TcGlobals * NiceNameGenerator * ImportMap * CcuThunk * (unit -> bool) * ConditionalDefines option * NameResolution.TcResultsSink * bool -> TcEnv - -> Tast.ModuleOrNamespaceType option + -> ModuleOrNamespaceType option -> ParsedImplFileInput - -> Eventually + -> Eventually val TypeCheckOneSigFile : TcGlobals * NiceNameGenerator * ImportMap * CcuThunk * (unit -> bool) * ConditionalDefines option * NameResolution.TcResultsSink * bool @@ -60,7 +59,7 @@ exception BakedInMemberConstraintName of string * range exception FunctionExpected of DisplayEnv * TType * range exception NotAFunction of DisplayEnv * TType * range * range exception NotAFunctionButIndexer of DisplayEnv * TType * string option * range * range -exception Recursion of DisplayEnv * Ast.Ident * TType * TType * range +exception Recursion of DisplayEnv * Ident * TType * TType * range exception RecursiveUseCheckedAtRuntime of DisplayEnv * ValRef * range exception LetRecEvaluatedOutOfOrder of DisplayEnv * ValRef * ValRef * range exception LetRecCheckedAtRuntime of range @@ -77,7 +76,7 @@ exception UnitTypeExpectedWithPossiblePropertySetter of DisplayEnv * TType * str exception UnitTypeExpectedWithPossibleAssignment of DisplayEnv * TType * bool * string * range exception FunctionValueUnexpected of DisplayEnv * TType * range exception UnionPatternsBindDifferentNames of range -exception VarBoundTwice of Ast.Ident +exception VarBoundTwice of Ident exception ValueRestriction of DisplayEnv * bool * Val * Typar * range exception ValNotMutable of DisplayEnv * ValRef * range exception ValNotLocal of DisplayEnv * ValRef * range @@ -104,6 +103,6 @@ exception StandardOperatorRedefinitionWarning of string * range exception ParameterlessStructCtor of range exception InvalidInternalsVisibleToAssemblyName of (*badName*)string * (*fileName option*) string option -val TcFieldInit : range -> ILFieldInit -> Tast.Const +val TcFieldInit : range -> ILFieldInit -> Const val LightweightTcValForUsingInBuildMethodCall : g : TcGlobals -> vref:ValRef -> vrefFlags : ValUseFlag -> vrefTypeInst : TTypes -> m : range -> Expr * TType \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/TypeRelations.fs b/src/fcs-fable/src/fsharp/TypeRelations.fs index 05c016d3cf..efd82d277d 100755 --- a/src/fcs-fable/src/fsharp/TypeRelations.fs +++ b/src/fcs-fable/src/fsharp/TypeRelations.fs @@ -7,14 +7,14 @@ module internal FSharp.Compiler.TypeRelations open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals open FSharp.Compiler.Infos -open FSharp.Compiler.PrettyNaming /// Implements a :> b without coercion based on finalized (no type variable) types -// QUERY: This relation is approximate and not part of the language specification. +// Note: This relation is approximate and not part of the language specification. // // Some appropriate uses: // patcompile.fs: IsDiscrimSubsumedBy (approximate warning for redundancy of 'isinst' patterns) @@ -25,37 +25,24 @@ open FSharp.Compiler.PrettyNaming let rec TypeDefinitelySubsumesTypeNoCoercion ndeep g amap m ty1 ty2 = if ndeep > 100 then error(InternalError("recursive class hierarchy (detected in TypeDefinitelySubsumesTypeNoCoercion), ty1 = " + (DebugPrint.showType ty1), m)) if ty1 === ty2 then true - // QUERY : quadratic elif typeEquiv g ty1 ty2 then true else let ty1 = stripTyEqns g ty1 let ty2 = stripTyEqns g ty2 - match ty1, ty2 with - | TType_app (tc1, l1), TType_app (tc2, l2) when tyconRefEq g tc1 tc2 -> - List.lengthsEqAndForall2 (typeEquiv g) l1 l2 - | TType_ucase (tc1, l1), TType_ucase (tc2, l2) when g.unionCaseRefEq tc1 tc2 -> - List.lengthsEqAndForall2 (typeEquiv g) l1 l2 - | TType_tuple (tupInfo1, l1), TType_tuple (tupInfo2, l2) -> - evalTupInfoIsStruct tupInfo1 = evalTupInfoIsStruct tupInfo2 && - List.lengthsEqAndForall2 (typeEquiv g) l1 l2 - | TType_fun (d1, r1), TType_fun (d2, r2) -> - typeEquiv g d1 d2 && typeEquiv g r1 r2 - | TType_measure measure1, TType_measure measure2 -> - measureEquiv g measure1 measure2 - | _ -> - (typeEquiv g ty1 g.obj_ty && isRefTy g ty2) || (* F# reference types are subtypes of type 'obj' *) - (isAppTy g ty2 && - isRefTy g ty2 && - - ((match GetSuperTypeOfType g amap m ty2 with - | None -> false - | Some ty -> TypeDefinitelySubsumesTypeNoCoercion (ndeep+1) g amap m ty1 ty) || - - (isInterfaceTy g ty1 && - ty2 |> GetImmediateInterfacesOfType SkipUnrefInterfaces.Yes g amap m - |> List.exists (TypeDefinitelySubsumesTypeNoCoercion (ndeep+1) g amap m ty1)))) + // F# reference types are subtypes of type 'obj' + (typeEquiv g ty1 g.obj_ty && isRefTy g ty2) || + // Follow the supertype chain + (isAppTy g ty2 && + isRefTy g ty2 && + ((match GetSuperTypeOfType g amap m ty2 with + | None -> false + | Some ty -> TypeDefinitelySubsumesTypeNoCoercion (ndeep+1) g amap m ty1 ty) || + // Follow the interface hierarchy + (isInterfaceTy g ty1 && + ty2 |> GetImmediateInterfacesOfType SkipUnrefInterfaces.Yes g amap m + |> List.exists (TypeDefinitelySubsumesTypeNoCoercion (ndeep+1) g amap m ty1)))) type CanCoerce = CanCoerce | NoCoerce @@ -66,18 +53,28 @@ let rec TypesFeasiblyEquiv ndeep g amap m ty1 ty2 = let ty1 = stripTyEqns g ty1 let ty2 = stripTyEqns g ty2 match ty1, ty2 with - // QUERY: should these be false for non-equal rigid typars? warn-if-not-rigid typars? | TType_var _, _ | _, TType_var _ -> true + | TType_app (tc1, l1), TType_app (tc2, l2) when tyconRefEq g tc1 tc2 -> List.lengthsEqAndForall2 (TypesFeasiblyEquiv ndeep g amap m) l1 l2 + + | TType_anon (anonInfo1, l1),TType_anon (anonInfo2, l2) -> + (evalTupInfoIsStruct anonInfo1.TupInfo = evalTupInfoIsStruct anonInfo2.TupInfo) && + (match anonInfo1.Assembly, anonInfo2.Assembly with ccu1, ccu2 -> ccuEq ccu1 ccu2) && + (anonInfo1.SortedNames = anonInfo2.SortedNames) && + List.lengthsEqAndForall2 (TypesFeasiblyEquiv ndeep g amap m) l1 l2 + | TType_tuple (tupInfo1, l1), TType_tuple (tupInfo2, l2) -> evalTupInfoIsStruct tupInfo1 = evalTupInfoIsStruct tupInfo2 && List.lengthsEqAndForall2 (TypesFeasiblyEquiv ndeep g amap m) l1 l2 + | TType_fun (d1, r1), TType_fun (d2, r2) -> (TypesFeasiblyEquiv ndeep g amap m) d1 d2 && (TypesFeasiblyEquiv ndeep g amap m) r1 r2 + | TType_measure _, TType_measure _ -> true + | _ -> false @@ -88,18 +85,18 @@ let rec TypeFeasiblySubsumesType ndeep g amap m ty1 canCoerce ty2 = let ty1 = stripTyEqns g ty1 let ty2 = stripTyEqns g ty2 match ty1, ty2 with - // QUERY: should these be false for non-equal rigid typars? warn-if-not-rigid typars? | TType_var _, _ | _, TType_var _ -> true | TType_app (tc1, l1), TType_app (tc2, l2) when tyconRefEq g tc1 tc2 -> List.lengthsEqAndForall2 (TypesFeasiblyEquiv ndeep g amap m) l1 l2 - | TType_tuple (tupInfo1, l1), TType_tuple (tupInfo2, l2) -> - evalTupInfoIsStruct tupInfo1 = evalTupInfoIsStruct tupInfo2 && - List.lengthsEqAndForall2 (TypesFeasiblyEquiv ndeep g amap m) l1 l2 - | TType_fun (d1, r1), TType_fun (d2, r2) -> - (TypesFeasiblyEquiv ndeep g amap m) d1 d2 && (TypesFeasiblyEquiv ndeep g amap m) r1 r2 + + | TType_tuple _, TType_tuple _ + | TType_anon _, TType_anon _ + | TType_fun _, TType_fun _ -> TypesFeasiblyEquiv ndeep g amap m ty1 ty2 + | TType_measure _, TType_measure _ -> true + | _ -> // F# reference types are subtypes of type 'obj' (isObjTy g ty1 && (canCoerce = CanCoerce || isRefTy g ty2)) @@ -137,7 +134,7 @@ let ChooseTyparSolutionAndRange (g: TcGlobals) amap (tp:Typar) = match tpc with | TyparConstraint.CoercesTo(x, m) -> join m x, m - | TyparConstraint.MayResolveMember(TTrait(_, _, _, _, _, _), m) -> + | TyparConstraint.MayResolveMember(_traitInfo, m) -> maxSoFar, m | TyparConstraint.SimpleChoice(_, m) -> errorR(Error(FSComp.SR.typrelCannotResolveAmbiguityInPrintf(), m)) @@ -201,7 +198,7 @@ let IterativelySubstituteTyparSolutions g tps solutions = let ChooseTyparSolutionsForFreeChoiceTypars g amap e = match e with - | Expr.TyChoose(tps, e1, _m) -> + | Expr.TyChoose (tps, e1, _m) -> /// Only make choices for variables that are actually used in the expression let ftvs = (freeInExpr CollectTyparsNoCaching e1).FreeTyvars.FreeTypars diff --git a/src/fcs-fable/src/fsharp/tast.fs b/src/fcs-fable/src/fsharp/TypedTree.fs similarity index 77% rename from src/fcs-fable/src/fsharp/tast.fs rename to src/fcs-fable/src/fsharp/TypedTree.fs index f195a7a94a..ec084c61c3 100644 --- a/src/fcs-fable/src/fsharp/tast.fs +++ b/src/fcs-fable/src/fsharp/TypedTree.fs @@ -1,70 +1,42 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -//------------------------------------------------------------------------- -// Defines the typed abstract syntax trees used throughout the F# compiler. -//------------------------------------------------------------------------- - -module internal FSharp.Compiler.Tast +/// Defines the typed abstract syntax intermediate representation used throughout the F# compiler. +module internal rec FSharp.Compiler.TypedTree open System open System.Collections.Generic open System.Diagnostics open System.Reflection + open Internal.Utilities + +open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Extensions.ILX.Types - -open FSharp.Compiler -open FSharp.Compiler.Range -open FSharp.Compiler.Ast +open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Lib open FSharp.Compiler.PrettyNaming open FSharp.Compiler.QuotationPickler -open Microsoft.FSharp.Core.Printf +open FSharp.Compiler.Range open FSharp.Compiler.Rational +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.XmlDoc +open FSharp.Core.Printf #if !NO_EXTENSIONTYPING open FSharp.Compiler.ExtensionTyping -open Microsoft.FSharp.Core.CompilerServices -#endif - -/// Unique name generator for stamps attached to lambdas and object expressions -type Unique = int64 - -//++GLOBAL MUTABLE STATE (concurrency-safe) -#if FABLE_COMPILER -let newUnique = let i = ref 0L in fun () -> i := !i + 1L; !i -#else -let newUnique = let i = ref 0L in fun () -> System.Threading.Interlocked.Increment(i) +open FSharp.Core.CompilerServices #endif type Stamp = int64 -/// Unique name generator for stamps attached to to val_specs, tycon_specs etc. -//++GLOBAL MUTABLE STATE (concurrency-safe) -#if FABLE_COMPILER -let newStamp = let i = ref 0L in fun () -> i := !i + 1L; !i -#else -let newStamp = let i = ref 0L in fun () -> System.Threading.Interlocked.Increment(i) -#endif - -/// A global generator of compiler generated names -// ++GLOBAL MUTABLE STATE (concurrency safe by locking inside NiceNameGenerator) -let globalNng = NiceNameGenerator() - -/// A global generator of stable compiler generated names -// ++GLOBAL MUTABLE STATE (concurrency safe by locking inside StableNiceNameGenerator) -let globalStableNameGenerator = StableNiceNameGenerator () - type StampMap<'T> = Map -//------------------------------------------------------------------------- -// Flags - [] type ValInline = @@ -132,133 +104,137 @@ type ValFlags(flags: int64) = new (recValInfo, baseOrThis, isCompGen, inlineInfo, isMutable, isModuleOrMemberBinding, isExtensionMember, isIncrClassSpecialMember, isTyFunc, allowTypeInst, isGeneratedEventVal) = let flags = (match baseOrThis with - | BaseVal -> 0b0000000000000000000L - | CtorThisVal -> 0b0000000000000000010L - | NormalVal -> 0b0000000000000000100L - | MemberThisVal -> 0b0000000000000000110L) ||| - (if isCompGen then 0b0000000000000001000L - else 0b00000000000000000000L) ||| + | BaseVal -> 0b00000000000000000000L + | CtorThisVal -> 0b00000000000000000010L + | NormalVal -> 0b00000000000000000100L + | MemberThisVal -> 0b00000000000000000110L) ||| + (if isCompGen then 0b00000000000000001000L + else 0b000000000000000000000L) ||| (match inlineInfo with - | ValInline.PseudoVal -> 0b0000000000000000000L - | ValInline.Always -> 0b0000000000000010000L - | ValInline.Optional -> 0b0000000000000100000L - | ValInline.Never -> 0b0000000000000110000L) ||| + | ValInline.PseudoVal -> 0b00000000000000000000L + | ValInline.Always -> 0b00000000000000010000L + | ValInline.Optional -> 0b00000000000000100000L + | ValInline.Never -> 0b00000000000000110000L) ||| (match isMutable with - | Immutable -> 0b0000000000000000000L - | Mutable -> 0b0000000000001000000L) ||| + | Immutable -> 0b00000000000000000000L + | Mutable -> 0b00000000000001000000L) ||| (match isModuleOrMemberBinding with - | false -> 0b0000000000000000000L - | true -> 0b0000000000010000000L) ||| + | false -> 0b00000000000000000000L + | true -> 0b00000000000010000000L) ||| (match isExtensionMember with - | false -> 0b0000000000000000000L - | true -> 0b0000000000100000000L) ||| + | false -> 0b00000000000000000000L + | true -> 0b00000000000100000000L) ||| (match isIncrClassSpecialMember with - | false -> 0b0000000000000000000L - | true -> 0b0000000001000000000L) ||| + | false -> 0b00000000000000000000L + | true -> 0b00000000001000000000L) ||| (match isTyFunc with - | false -> 0b0000000000000000000L - | true -> 0b0000000010000000000L) ||| + | false -> 0b00000000000000000000L + | true -> 0b00000000010000000000L) ||| (match recValInfo with - | ValNotInRecScope -> 0b0000000000000000000L - | ValInRecScope true -> 0b0000000100000000000L - | ValInRecScope false -> 0b0000001000000000000L) ||| + | ValNotInRecScope -> 0b00000000000000000000L + | ValInRecScope true -> 0b00000000100000000000L + | ValInRecScope false -> 0b00000001000000000000L) ||| (match allowTypeInst with - | false -> 0b0000000000000000000L - | true -> 0b0000100000000000000L) ||| + | false -> 0b00000000000000000000L + | true -> 0b00000100000000000000L) ||| (match isGeneratedEventVal with - | false -> 0b0000000000000000000L - | true -> 0b0100000000000000000L) + | false -> 0b00000000000000000000L + | true -> 0b00100000000000000000L) - ValFlags(flags) + ValFlags flags member x.BaseOrThisInfo = - match (flags &&& 0b0000000000000000110L) with - | 0b0000000000000000000L -> BaseVal - | 0b0000000000000000010L -> CtorThisVal - | 0b0000000000000000100L -> NormalVal - | 0b0000000000000000110L -> MemberThisVal + match (flags &&& 0b00000000000000000110L) with + | 0b00000000000000000000L -> BaseVal + | 0b00000000000000000010L -> CtorThisVal + | 0b00000000000000000100L -> NormalVal + | 0b00000000000000000110L -> MemberThisVal | _ -> failwith "unreachable" - member x.IsCompilerGenerated = (flags &&& 0b0000000000000001000L) <> 0x0L + member x.IsCompilerGenerated = (flags &&& 0b00000000000000001000L) <> 0x0L - member x.SetIsCompilerGenerated(isCompGen) = - let flags = (flags &&& ~~~0b0000000000000001000L) ||| + member x.SetIsCompilerGenerated isCompGen = + let flags = (flags &&& ~~~0b00000000000000001000L) ||| (match isCompGen with - | false -> 0b0000000000000000000L - | true -> 0b0000000000000001000L) - ValFlags(flags) + | false -> 0b00000000000000000000L + | true -> 0b00000000000000001000L) + ValFlags flags member x.InlineInfo = - match (flags &&& 0b0000000000000110000L) with - | 0b0000000000000000000L -> ValInline.PseudoVal - | 0b0000000000000010000L -> ValInline.Always - | 0b0000000000000100000L -> ValInline.Optional - | 0b0000000000000110000L -> ValInline.Never + match (flags &&& 0b00000000000000110000L) with + | 0b00000000000000000000L -> ValInline.PseudoVal + | 0b00000000000000010000L -> ValInline.Always + | 0b00000000000000100000L -> ValInline.Optional + | 0b00000000000000110000L -> ValInline.Never | _ -> failwith "unreachable" member x.MutabilityInfo = - match (flags &&& 0b0000000000001000000L) with - | 0b0000000000000000000L -> Immutable - | 0b0000000000001000000L -> Mutable + match (flags &&& 0b00000000000001000000L) with + | 0b00000000000000000000L -> Immutable + | 0b00000000000001000000L -> Mutable | _ -> failwith "unreachable" member x.IsMemberOrModuleBinding = - match (flags &&& 0b0000000000010000000L) with - | 0b0000000000000000000L -> false - | 0b0000000000010000000L -> true + match (flags &&& 0b00000000000010000000L) with + | 0b00000000000000000000L -> false + | 0b00000000000010000000L -> true | _ -> failwith "unreachable" - member x.WithIsMemberOrModuleBinding = ValFlags(flags ||| 0b0000000000010000000L) + member x.WithIsMemberOrModuleBinding = ValFlags(flags ||| 0b00000000000010000000L) - member x.IsExtensionMember = (flags &&& 0b0000000000100000000L) <> 0L + member x.IsExtensionMember = (flags &&& 0b00000000000100000000L) <> 0L - member x.IsIncrClassSpecialMember = (flags &&& 0b0000000001000000000L) <> 0L + member x.IsIncrClassSpecialMember = (flags &&& 0b00000000001000000000L) <> 0L - member x.IsTypeFunction = (flags &&& 0b0000000010000000000L) <> 0L + member x.IsTypeFunction = (flags &&& 0b00000000010000000000L) <> 0L - member x.RecursiveValInfo = match (flags &&& 0b0000001100000000000L) with - | 0b0000000000000000000L -> ValNotInRecScope - | 0b0000000100000000000L -> ValInRecScope(true) - | 0b0000001000000000000L -> ValInRecScope(false) + member x.RecursiveValInfo = match (flags &&& 0b00000001100000000000L) with + | 0b00000000000000000000L -> ValNotInRecScope + | 0b00000000100000000000L -> ValInRecScope true + | 0b00000001000000000000L -> ValInRecScope false | _ -> failwith "unreachable" - member x.WithRecursiveValInfo(recValInfo) = + member x.WithRecursiveValInfo recValInfo = let flags = - (flags &&& ~~~0b0000001100000000000L) ||| + (flags &&& ~~~0b00000001100000000000L) ||| (match recValInfo with - | ValNotInRecScope -> 0b0000000000000000000L - | ValInRecScope(true) -> 0b0000000100000000000L - | ValInRecScope(false) -> 0b0000001000000000000L) - ValFlags(flags) + | ValNotInRecScope -> 0b00000000000000000000L + | ValInRecScope true -> 0b00000000100000000000L + | ValInRecScope false -> 0b00000001000000000000L) + ValFlags flags + + member x.MakesNoCriticalTailcalls = (flags &&& 0b00000010000000000000L) <> 0L + + member x.WithMakesNoCriticalTailcalls = ValFlags(flags ||| 0b00000010000000000000L) - member x.MakesNoCriticalTailcalls = (flags &&& 0b0000010000000000000L) <> 0L + member x.PermitsExplicitTypeInstantiation = (flags &&& 0b00000100000000000000L) <> 0L - member x.WithMakesNoCriticalTailcalls = ValFlags(flags ||| 0b0000010000000000000L) + member x.HasBeenReferenced = (flags &&& 0b00001000000000000000L) <> 0L - member x.PermitsExplicitTypeInstantiation = (flags &&& 0b0000100000000000000L) <> 0L + member x.WithHasBeenReferenced = ValFlags(flags ||| 0b00001000000000000000L) - member x.HasBeenReferenced = (flags &&& 0b0001000000000000000L) <> 0L + member x.IsCompiledAsStaticPropertyWithoutField = (flags &&& 0b00010000000000000000L) <> 0L - member x.WithHasBeenReferenced = ValFlags(flags ||| 0b0001000000000000000L) + member x.WithIsCompiledAsStaticPropertyWithoutField = ValFlags(flags ||| 0b00010000000000000000L) - member x.IsCompiledAsStaticPropertyWithoutField = (flags &&& 0b0010000000000000000L) <> 0L + member x.IsGeneratedEventVal = (flags &&& 0b00100000000000000000L) <> 0L - member x.WithIsCompiledAsStaticPropertyWithoutField = ValFlags(flags ||| 0b0010000000000000000L) + member x.IsFixed = (flags &&& 0b01000000000000000000L) <> 0L - member x.IsGeneratedEventVal = (flags &&& 0b0100000000000000000L) <> 0L + member x.WithIsFixed = ValFlags(flags ||| 0b01000000000000000000L) - member x.IsFixed = (flags &&& 0b1000000000000000000L) <> 0L + member x.IgnoresByrefScope = (flags &&& 0b10000000000000000000L) <> 0L - member x.WithIsFixed = ValFlags(flags ||| 0b1000000000000000000L) + member x.WithIgnoresByrefScope = ValFlags(flags ||| 0b10000000000000000000L) /// Get the flags as included in the F# binary metadata member x.PickledBits = @@ -266,7 +242,7 @@ type ValFlags(flags: int64) = // Clear the IsCompiledAsStaticPropertyWithoutField, only used to determine whether to use a true field for a value, and to eliminate the optimization info for observable bindings // Clear the HasBeenReferenced, only used to report "unreferenced variable" warnings and to help collect 'it' values in FSI.EXE // Clear the IsGeneratedEventVal, since there's no use in propagating specialname information for generated add/remove event vals - (flags &&& ~~~0b0011001100000000000L) + (flags &&& ~~~0b10011001100000000000L) /// Represents the kind of a type parameter [] @@ -277,21 +253,21 @@ type TyparKind = | Measure member x.AttrName = - match x with - | TyparKind.Type -> ValueNone - | TyparKind.Measure -> ValueSome "Measure" + match x with + | TyparKind.Type -> ValueNone + | TyparKind.Measure -> ValueSome "Measure" //[] //member x.DebugText = x.ToString() override x.ToString() = - match x with - | TyparKind.Type -> "type" - | TyparKind.Measure -> "measure" + match x with + | TyparKind.Type -> "type" + | TyparKind.Measure -> "measure" -[] /// Indicates if the type variable can be solved or given new constraints. The status of a type variable /// evolves towards being either rigid or solved. +[] type TyparRigidity = /// Indicates the type parameter can't be solved @@ -395,7 +371,7 @@ type TyparFlags(flags: int32) = member x.IsCompatFlex = (flags &&& 0b00010000000000000) <> 0x0 - member x.WithCompatFlex(b) = + member x.WithCompatFlex b = if b then TyparFlags(flags ||| 0b00010000000000000) else @@ -439,61 +415,59 @@ type EntityFlags(flags: int64) = /// These two bits represents the on-demand analysis about whether the entity has the IsByRefLike attribute member x.TryIsByRefLike = (flags &&& 0b000000011000000L) |> function - | 0b000000011000000L -> Some true - | 0b000000010000000L -> Some false - | _ -> None + | 0b000000011000000L -> ValueSome true + | 0b000000010000000L -> ValueSome false + | _ -> ValueNone /// Adjust the on-demand analysis about whether the entity has the IsByRefLike attribute - member x.WithIsByRefLike(flag) = + member x.WithIsByRefLike flag = let flags = (flags &&& ~~~0b000000011000000L) ||| (match flag with | true -> 0b000000011000000L | false -> 0b000000010000000L) - EntityFlags(flags) + EntityFlags flags - /// These two bits represents the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct + /// These two bits represents the on-demand analysis about whether the entity has the IsReadOnly attribute member x.TryIsReadOnly = (flags &&& 0b000001100000000L) |> function - | 0b000001100000000L -> Some true - | 0b000001000000000L -> Some false - | _ -> None + | 0b000001100000000L -> ValueSome true + | 0b000001000000000L -> ValueSome false + | _ -> ValueNone - /// Adjust the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct - member x.WithIsReadOnly(flag) = + /// Adjust the on-demand analysis about whether the entity has the IsReadOnly attribute + member x.WithIsReadOnly flag = let flags = (flags &&& ~~~0b000001100000000L) ||| (match flag with | true -> 0b000001100000000L | false -> 0b000001000000000L) - EntityFlags(flags) + EntityFlags flags - /// Get the flags as included in the F# binary metadata - member x.PickledBits = (flags &&& ~~~0b000001111000100L) + /// These two bits represents the on-demand analysis about whether the entity is assumed to be a readonly struct + member x.TryIsAssumedReadOnly = (flags &&& 0b000110000000000L) + |> function + | 0b000110000000000L -> ValueSome true + | 0b000100000000000L -> ValueSome false + | _ -> ValueNone + /// Adjust the on-demand analysis about whether the entity is assumed to be a readonly struct + member x.WithIsAssumedReadOnly flag = + let flags = + (flags &&& ~~~0b000110000000000L) ||| + (match flag with + | true -> 0b000110000000000L + | false -> 0b000100000000000L) + EntityFlags flags -#if DEBUG && !FABLE_COMPILER -assert (sizeof = 8) -assert (sizeof = 8) -assert (sizeof = 4) -#endif + /// Get the flags as included in the F# binary metadata + member x.PickledBits = (flags &&& ~~~0b000111111000100L) -let unassignedTyparName = "?" -exception UndefinedName of int * (* error func that expects identifier name *)(string -> string) * Ident * ErrorLogger.Suggestions -exception InternalUndefinedItemRef of (string * string * string -> int * string) * string * string * string -let KeyTyconByDemangledNameAndArity nm (typars: _ list) x = - KeyValuePair(NameArityPair(DemangleGenericTypeName nm, typars.Length), x) +exception UndefinedName of int * (string -> string) * Ident * ErrorLogger.Suggestions -/// Generic types can be accessed either by 'List' or 'List`1'. This lists both keys. The second form should really be deprecated. -let KeyTyconByAccessNames nm x = - match TryDemangleGenericNameAndPos nm with - | ValueSome pos -> - let dnm = DemangleGenericTypeNameWithPos pos nm - [| KeyValuePair(nm, x); KeyValuePair(dnm, x) |] - | _ -> - [| KeyValuePair(nm, x) |] +exception InternalUndefinedItemRef of (string * string * string -> int * string) * string * string * string type ModuleOrNamespaceKind = @@ -506,31 +480,12 @@ type ModuleOrNamespaceKind = /// Indicates that a 'module' is really a namespace | Namespace -let getNameOfScopeRef sref = - match sref with - | ILScopeRef.Local -> "" - | ILScopeRef.Module mref -> mref.Name - | ILScopeRef.Assembly aref -> aref.Name - -#if !NO_EXTENSIONTYPING -let ComputeDefinitionLocationOfProvidedItem (p: Tainted<#IProvidedCustomAttributeProvider>) = - let attrs = p.PUntaintNoFailure(fun x -> x.GetDefinitionLocationAttribute(p.TypeProvider.PUntaintNoFailure(id))) - match attrs with - | None | Some (null, _, _) -> None - | Some (filePath, line, column) -> - // Coordinates from type provider are 1-based for lines and columns - // Coordinates internally in the F# compiler are 1-based for lines and 0-based for columns - let pos = Range.mkPos line (max 0 (column - 1)) - Range.mkRange filePath pos pos |> Some - -#endif - /// A public path records where a construct lives within the global namespace /// of a CCU. type PublicPath = | PubPath of string[] member x.EnclosingPath = - let (PubPath(pp)) = x + let (PubPath pp) = x assert (pp.Length >= 1) pp.[0..pp.Length-2] @@ -562,8 +517,6 @@ type CompilationPath = | FSharpModuleWithSuffix -> String.dropSuffix nm FSharpModuleSuffix | _ -> nm - - [] type EntityOptionalData = { @@ -596,7 +549,7 @@ type EntityOptionalData = /// Indicates how visible is the entity is. // MUTABILITY: only for unpickle linkage - mutable entity_accessiblity: Accessibility + mutable entity_accessibility: Accessibility /// Field used when the 'tycon' is really an exception definition // @@ -609,10 +562,11 @@ type EntityOptionalData = override x.ToString() = "EntityOptionalData(...)" -and /// Represents a type definition, exception definition, module definition or namespace definition. - [] - Entity = - { /// The declared type parameters of the type +/// Represents a type definition, exception definition, module definition or namespace definition. +[] +type Entity = + { + /// The declared type parameters of the type // MUTABILITY; used only during creation and remapping of tycons mutable entity_typars: LazyWithContext @@ -674,7 +628,7 @@ and /// Represents a type definition, exception definition, module definition or entity_xmldocsig = "" entity_tycon_abbrev = None entity_tycon_repr_accessibility = TAccess [] - entity_accessiblity = TAccess [] + entity_accessibility = TAccess [] entity_exn_info = TExnNone } /// The name of the namespace, module or type, possibly with mangling, e.g. List`1, List or FailureException @@ -691,19 +645,22 @@ and /// Represents a type definition, exception definition, module definition or | Some optData -> optData.entity_compiled_name | _ -> None - member x.SetCompiledName(name) = + member x.SetCompiledName name = match x.entity_opt_data with | Some optData -> optData.entity_compiled_name <- name | _ -> x.entity_opt_data <- Some { Entity.NewEmptyEntityOptData() with entity_compiled_name = name } /// The display name of the namespace, module or type, e.g. List instead of List`1, and no static parameters - member x.DisplayName = x.GetDisplayName(false, false) + member x.DisplayName = x.GetDisplayName() + + /// The display name of the namespace, module or type with <'T, 'U, 'V> added for generic types, plus static parameters if any + member x.DisplayNameWithStaticParametersAndTypars = x.GetDisplayName(withStaticParameters=true, withTypars=true, withUnderscoreTypars=false) /// The display name of the namespace, module or type with <_, _, _> added for generic types, plus static parameters if any - member x.DisplayNameWithStaticParametersAndUnderscoreTypars = x.GetDisplayName(true, true) + member x.DisplayNameWithStaticParametersAndUnderscoreTypars = x.GetDisplayName(withStaticParameters=true, withTypars=false, withUnderscoreTypars=true) /// The display name of the namespace, module or type, e.g. List instead of List`1, including static parameters if any - member x.DisplayNameWithStaticParameters = x.GetDisplayName(true, false) + member x.DisplayNameWithStaticParameters = x.GetDisplayName(withStaticParameters=true, withTypars=false, withUnderscoreTypars=false) #if !NO_EXTENSIONTYPING member x.IsStaticInstantiationTycon = @@ -712,15 +669,20 @@ and /// Represents a type definition, exception definition, module definition or args.Length > 0 #endif - member x.GetDisplayName(withStaticParameters, withUnderscoreTypars) = + member x.GetDisplayName(?withStaticParameters, ?withTypars, ?withUnderscoreTypars) = + let withStaticParameters = defaultArg withStaticParameters false + let withTypars = defaultArg withTypars false + let withUnderscoreTypars = defaultArg withUnderscoreTypars false let nm = x.LogicalName + let getName () = match x.TyparsNoRange with | [] -> nm | tps -> let nm = DemangleGenericTypeName nm - if withUnderscoreTypars && not (List.isEmpty tps) then - nm + "<" + String.concat "," (Array.create tps.Length "_") + ">" + if (withUnderscoreTypars || withTypars) && not (List.isEmpty tps) then + let typearNames = tps |> List.map (fun typar -> if withUnderscoreTypars then "_" else typar.Name) + nm + "<" + String.concat "," typearNames + ">" else nm @@ -744,7 +706,7 @@ and /// Represents a type definition, exception definition, module definition or #if !NO_EXTENSIONTYPING match x.TypeReprInfo with | TProvidedTypeExtensionPoint info -> - match ComputeDefinitionLocationOfProvidedItem info.ProvidedType with + match Construct.ComputeDefinitionLocationOfProvidedItem info.ProvidedType with | Some range -> range | None -> x.entity_range | _ -> @@ -783,7 +745,7 @@ and /// Represents a type definition, exception definition, module definition or member x.XmlDoc = #if !NO_EXTENSIONTYPING match x.TypeReprInfo with - | TProvidedTypeExtensionPoint info -> XmlDoc (info.ProvidedType.PUntaintNoFailure(fun st -> (st :> IProvidedCustomAttributeProvider).GetXmlDocAttributes(info.ProvidedType.TypeProvider.PUntaintNoFailure(id)))) + | TProvidedTypeExtensionPoint info -> XmlDoc (info.ProvidedType.PUntaintNoFailure(fun st -> (st :> IProvidedCustomAttributeProvider).GetXmlDocAttributes(info.ProvidedType.TypeProvider.PUntaintNoFailure id))) | _ -> #endif match x.entity_opt_data with @@ -849,7 +811,7 @@ and /// Represents a type definition, exception definition, module definition or member x.Typars m = x.entity_typars.Force m /// Get the type parameters for an entity that is a type declaration, otherwise return the empty list. - member x.TyparsNoRange = x.Typars x.Range + member x.TyparsNoRange: Typars = x.Typars x.Range /// Get the type abbreviated by this type definition, if it is an F# type abbreviation definition member x.TypeAbbrev = @@ -880,7 +842,7 @@ and /// Represents a type definition, exception definition, module definition or /// Get the value representing the accessibility of an F# type definition or module. member x.Accessibility = match x.entity_opt_data with - | Some optData -> optData.entity_accessiblity + | Some optData -> optData.entity_accessibility | _ -> TAccess [] /// Indicates the type prefers the "tycon" syntax for display etc. @@ -1045,7 +1007,7 @@ and /// Represents a type definition, exception definition, module definition or entity_xmldocsig = tg.entity_xmldocsig entity_tycon_abbrev = tg.entity_tycon_abbrev entity_tycon_repr_accessibility = tg.entity_tycon_repr_accessibility - entity_accessiblity = tg.entity_accessiblity + entity_accessibility = tg.entity_accessibility entity_exn_info = tg.entity_exn_info } | None -> () @@ -1081,12 +1043,18 @@ and /// Represents a type definition, exception definition, module definition or /// Set the on-demand analysis about whether the entity has the IsByRefLike attribute member x.SetIsByRefLike b = x.entity_flags <- x.entity_flags.WithIsByRefLike b - /// These two bits represents the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct + /// These two bits represents the on-demand analysis about whether the entity has the IsReadOnly attribute member x.TryIsReadOnly = x.entity_flags.TryIsReadOnly - /// Set the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct + /// Set the on-demand analysis about whether the entity has the IsReadOnly attribute member x.SetIsReadOnly b = x.entity_flags <- x.entity_flags.WithIsReadOnly b + /// These two bits represents the on-demand analysis about whether the entity is assumed to be a readonly struct + member x.TryIsAssumedReadOnly = x.entity_flags.TryIsAssumedReadOnly + + /// Set the on-demand analysis about whether the entity is assumed to be a readonly struct + member x.SetIsAssumedReadOnly b = x.entity_flags <- x.entity_flags.WithIsAssumedReadOnly b + /// Indicates if this is an F# type definition whose r.h.s. is known to be some kind of F# object model definition member x.IsFSharpObjectModelTycon = match x.TypeReprInfo with | TFSharpObjectRepr _ -> true | _ -> false @@ -1224,14 +1192,14 @@ and /// Represents a type definition, exception definition, module definition or let ilTypeRefForCompilationPath (CompPath(sref, p)) item = let rec top racc p = match p with - | [] -> ILTypeRef.Create(sref, [], textOfPath (List.rev (item::racc))) - | (h, istype)::t -> - match istype with + | [] -> ILTypeRef.Create(sref, [], textOfPath (List.rev (item :: racc))) + | (h, isType) :: t -> + match isType with | FSharpModuleWithSuffix | ModuleOrType -> - let outerTypeName = (textOfPath (List.rev (h::racc))) + let outerTypeName = (textOfPath (List.rev (h :: racc))) ILTypeRef.Create(sref, (outerTypeName :: List.map (fun (nm, _) -> nm) t), item) | _ -> - top (h::racc) t + top (h :: racc) t top [] p @@ -1279,30 +1247,50 @@ and /// Represents a type definition, exception definition, module definition or override x.ToString() = x.LogicalName -and [] MaybeLazy<'T> = - | Strict of 'T - | Lazy of Lazy<'T> +type EntityData = Entity - member this.Value: 'T = - match this with - | Strict x -> x - | Lazy x -> x.Value - - member this.Force() : 'T = - match this with - | Strict x -> x - | Lazy x -> x.Force() - -and EntityData = Entity - -and ParentRef = +/// Represents the parent entity of a type definition, if any +type ParentRef = | Parent of EntityRef | ParentNone -and - [] - TyconAugmentation = - { /// This is the value implementing the auto-generated comparison +/// Specifies the compiled representations of type and exception definitions. Basically +/// just an ILTypeRef. Computed and cached by later phases. Stored in +/// type and exception definitions. Not pickled. Store an optional ILType object for +/// non-generic types. +[] +type CompiledTypeRepr = + + /// An AbstractIL type representation that is just the name of a type. + /// + /// CompiledTypeRepr.ILAsmNamed (ilTypeRef, ilBoxity, ilTypeOpt) + /// + /// The ilTypeOpt is present for non-generic types. It is an ILType corresponding to the first two elements of the case. This + /// prevents reallocation of the ILType each time we need to generate it. For generic types, it is None. + | ILAsmNamed of + ILTypeRef * + ILBoxity * + ILType option + + /// An AbstractIL type representation that may include type variables + // This case is only used for types defined in the F# library by their translation to ILASM types, e.g. + // type ``[]``<'T> = (# "!0[]" #) + // type ``[, ]``<'T> = (# "!0[0 ..., 0 ...]" #) + // type ``[, , ]``<'T> = (# "!0[0 ..., 0 ..., 0 ...]" #) + // type byref<'T> = (# "!0&" #) + // type nativeptr<'T when 'T: unmanaged> = (# "native int" #) + // type ilsigptr<'T> = (# "!0*" #) + | ILAsmOpen of ILType + + [] + member x.DebugText = x.ToString() + + override x.ToString() = "CompiledTypeRepr(...)" + +[] +type TyconAugmentation = + { + /// This is the value implementing the auto-generated comparison /// semantics if any. It is not present if the type defines its own implementation /// of IComparable or if the type doesn't implement IComparable implicitly. mutable tcaug_compare: (ValRef * ValRef) option @@ -1375,10 +1363,9 @@ and override x.ToString() = "TyconAugmentation(...)" -and - [] - /// The information for the contents of a type. Also used for a provided namespace. - TyconRepresentation = +/// The information for the contents of a type. Also used for a provided namespace. +[] +type TyconRepresentation = /// Indicates the type is a class, struct, enum, delegate or interface | TFSharpObjectRepr of TyconObjModelData @@ -1425,11 +1412,9 @@ and override x.ToString() = sprintf "%+A" x -and - [] - /// TILObjectReprData(scope, nesting, definition) - TILObjectReprData = - | TILObjectReprData of ILScopeRef * ILTypeDef list * ILTypeDef +[] +type TILObjectReprData = + | TILObjectReprData of scope: ILScopeRef * nesting: ILTypeDef list * definition: ILTypeDef [] member x.DebugText = x.ToString() @@ -1438,12 +1423,12 @@ and #if !NO_EXTENSIONTYPING -and - [] - - /// The information kept about a provided type - TProvidedTypeInfo = - { /// The parameters given to the provider that provided to this type. + +/// The information kept about a provided type +[] +type TProvidedTypeInfo = + { + /// The parameters given to the provider that provided to this type. ResolutionEnvironment: ExtensionTyping.ResolutionEnvironment /// The underlying System.Type (wrapped as a ProvidedType to make sure we don't call random things on @@ -1462,7 +1447,10 @@ and IsSealed: bool /// A flag read eagerly from the provided type and used to compute basic properties of the type definition. - IsInterface: bool + IsAbstract: bool + + /// A flag read eagerly from the provided type and used to compute basic properties of the type definition. + IsInterface: bool /// A flag read eagerly from the provided type and used to compute basic properties of the type definition. IsStructOrEnum: bool @@ -1482,10 +1470,13 @@ and IsErased: bool /// Indicates the type is generated, but type-relocation is suppressed - IsSuppressRelocate: bool } + IsSuppressRelocate: bool + } + /// Indicates if the provided type is generated, i.e. not erased member info.IsGenerated = not info.IsErased + /// Gets the base type of an erased provided type member info.BaseTypeForErased (m, objTy) = if info.IsErased then info.LazyBaseType.Force (m, objTy) else failwith "expect erased type" @@ -1493,12 +1484,11 @@ and [] member x.DebugText = x.ToString() - override x.ToString() = "TProvidedTypeInfo(...)" + override _.ToString() = "TProvidedTypeInfo(...)" #endif -and - TyconObjModelKind = +type TyconObjModelKind = /// Indicates the type is a class (also used for units-of-measure) | TTyconClass @@ -1514,47 +1504,57 @@ and /// Indicates the type is an enumeration | TTyconEnum + /// Indicates if the type definition is a value type member x.IsValueType = match x with | TTyconClass | TTyconInterface | TTyconDelegate _ -> false | TTyconStruct | TTyconEnum -> true -and - [] - TyconObjModelData = - { /// Indicates whether the type declaration is a class, interface, enum, delegate or struct +/// Represents member values and class fields relating to the F# object model +[] +type TyconObjModelData = + { + /// Indicates whether the type declaration is a class, interface, enum, delegate or struct fsobjmodel_kind: TyconObjModelKind /// The declared abstract slots of the class, interface or struct fsobjmodel_vslots: ValRef list /// The fields of the class, struct or enum - fsobjmodel_rfields: TyconRecdFields } + fsobjmodel_rfields: TyconRecdFields + } [] member x.DebugText = x.ToString() override x.ToString() = "TyconObjModelData(...)" -and - [] - TyconRecdFields = - { /// The fields of the record, in declaration order. +/// Represents record fields in an F# type definition +[] +type TyconRecdFields = + { + /// The fields of the record, in declaration order. FieldsByIndex: RecdField[] /// The fields of the record, indexed by name. - FieldsByName: NameMap } + FieldsByName: NameMap + } + /// Get a field by index member x.FieldByIndex n = if n >= 0 && n < x.FieldsByIndex.Length then x.FieldsByIndex.[n] else failwith "FieldByIndex" - member x.FieldByName n = x.FieldsByName.TryFind(n) + /// Get a field by name + member x.FieldByName nm = x.FieldsByName.TryFind nm + /// Get all the fields as a list member x.AllFieldsAsList = x.FieldsByIndex |> Array.toList + /// Get all non-compiler-generated fields as a list member x.TrueFieldsAsList = x.AllFieldsAsList |> List.filter (fun f -> not f.IsCompilerGenerated) + /// Get all non-compiler-generated instance fields as a list member x.TrueInstanceFieldsAsList = x.AllFieldsAsList |> List.filter (fun f -> not f.IsStatic && not f.IsCompilerGenerated) [] @@ -1562,18 +1562,23 @@ and override x.ToString() = "TyconRecdFields(...)" -and - [] - TyconUnionCases = - { /// The cases of the discriminated union, in declaration order. +/// Represents union cases in an F# type definition +[] +type TyconUnionCases = + { + /// The cases of the discriminated union, in declaration order. CasesByIndex: UnionCase[] + /// The cases of the discriminated union, indexed by name. CasesByName: NameMap } + + /// Get a union case by index member x.GetUnionCaseByIndex n = if n >= 0 && n < x.CasesByIndex.Length then x.CasesByIndex.[n] else invalidArg "n" "GetUnionCaseByIndex" + /// Get the union cases as a list member x.UnionCasesAsList = x.CasesByIndex |> Array.toList [] @@ -1581,15 +1586,18 @@ and override x.ToString() = "TyconUnionCases(...)" -and - [] - TyconUnionData = - { /// The cases contained in the discriminated union. +/// Represents the union cases and related information in an F# type definition +[] +type TyconUnionData = + { + /// The cases contained in the discriminated union. CasesTable: TyconUnionCases + /// The ILX data structure representing the discriminated union. CompiledRepresentation: IlxUnionRef cache } + /// Get the union cases as a list member x.UnionCasesAsList = x.CasesTable.CasesByIndex |> Array.toList [] @@ -1597,10 +1605,11 @@ and override x.ToString() = "TyconUnionData(...)" -and - [] - UnionCase = - { /// Data carried by the case. +/// Represents a union case in an F# type definition +[] +type UnionCase = + { + /// Data carried by the case. FieldTable: TyconRecdFields /// Return type constructed by the case. Normally exactly the type of the enclosing type, sometimes an abbreviation of it @@ -1625,35 +1634,47 @@ and /// Attributes, attached to the generated static method to make instances of the case // MUTABILITY: used when propagating signature attributes into the implementation. - mutable Attribs: Attribs } + mutable Attribs: Attribs + } + /// Get the declaration location of the union case member uc.Range = uc.Id.idRange + /// Get the definition location of the union case member uc.DefinitionRange = match uc.OtherRangeOpt with | Some (m, true) -> m | _ -> uc.Range + /// Get the signature location of the union case member uc.SigRange = match uc.OtherRangeOpt with | Some (m, false) -> m | _ -> uc.Range + /// Get the display name of the union case member uc.DisplayName = uc.Id.idText - /// Name of the case in generated IL code. + /// Get the name of the case in generated IL code. member uc.CompiledName = let idText = uc.Id.idText if idText = opNameCons then "Cons" elif idText = opNameNil then "Empty" else idText + /// Get the full array of fields of the union case member uc.RecdFieldsArray = uc.FieldTable.FieldsByIndex + /// Get the full list of fields of the union case member uc.RecdFields = uc.FieldTable.FieldsByIndex |> Array.toList + /// Get a field of the union case by name member uc.GetFieldByName nm = uc.FieldTable.FieldByName nm + /// Get a field of the union case by position + member uc.GetFieldByIndex n = uc.FieldTable.FieldByIndex n + + /// Indicates if the union case has no fields member uc.IsNullary = (uc.FieldTable.FieldsByIndex.Length = 0) [] @@ -1661,12 +1682,12 @@ and override x.ToString() = "UnionCase(" + x.DisplayName + ")" -and - /// This may represent a "field" in either a struct, class, record or union - /// It is normally compiled to a property. - [] - RecdField = - { /// Is the field declared mutable in F#? +/// Represents a class, struct or record field in an F# type definition. +/// This may represent a "field" in either a struct, class, record or union. +[] +type RecdField = + { + /// Is the field declared mutable in F#? rfield_mutable: bool /// Documentation for the field @@ -1720,14 +1741,16 @@ and /// Attributes attached to generated field member v.FieldAttribs = v.rfield_fattribs - /// Declaration-location of the field + /// Get the declaration location of the field member v.Range = v.rfield_id.idRange + /// Get the definition location of the field member v.DefinitionRange = match v.rfield_other_range with | Some (m, true) -> m | _ -> v.Range + /// Get the signature location of the field member v.SigRange = match v.rfield_other_range with | Some (m, false) -> m @@ -1760,7 +1783,7 @@ and /// Get or set the XML documentation signature for the field member v.XmlDocSig with get() = v.rfield_xmldocsig - and set(x) = v.rfield_xmldocsig <- x + and set x = v.rfield_xmldocsig <- x /// The default initialization info, for static literals member v.LiteralValue = @@ -1781,9 +1804,10 @@ and override x.ToString() = x.Name -and - [] - ExceptionInfo = +/// Represents the implementation of an F# exception definition. +[] +type ExceptionInfo = + /// Indicates that an exception is an abbreviation for the given exception | TExnAbbrevRepr of TyconRef @@ -1802,8 +1826,9 @@ and override x.ToString() = sprintf "%+A" x -and [] - ModuleOrNamespaceType(kind: ModuleOrNamespaceKind, vals: QueueList, entities: QueueList) = +/// Represents the contents of of a module of namespace +[] +type ModuleOrNamespaceType(kind: ModuleOrNamespaceKind, vals: QueueList, entities: QueueList) = /// Mutation used during compilation of FSharp.Core.dll let mutable entities = entities @@ -1834,19 +1859,19 @@ and [] let allValsByLogicalNameCache: NameMap option ref = ref None /// Namespace or module-compiled-as-type? - member mtyp.ModuleOrNamespaceKind = kind + member _.ModuleOrNamespaceKind = kind /// Values, including members in F# types in this module-or-namespace-fragment. - member mtyp.AllValsAndMembers = vals + member _.AllValsAndMembers = vals /// Type, mapping mangled name to Tycon, e.g. //// "Dictionary`2" --> Tycon //// "ListModule" --> Tycon with module info //// "FooException" --> Tycon with exception info - member mtyp.AllEntities = entities + member _.AllEntities = entities /// Mutation used during compilation of FSharp.Core.dll - member mtyp.AddModuleOrNamespaceByMutation(modul: ModuleOrNamespace) = + member _.AddModuleOrNamespaceByMutation(modul: ModuleOrNamespace) = entities <- QueueList.appendOne entities modul modulesByDemangledNameCache := None allEntitiesByMangledNameCache := None @@ -1862,49 +1887,49 @@ and [] #endif /// Return a new module or namespace type with an entity added. - member mtyp.AddEntity(tycon: Tycon) = + member _.AddEntity(tycon: Tycon) = ModuleOrNamespaceType(kind, vals, entities.AppendOne tycon) /// Return a new module or namespace type with a value added. - member mtyp.AddVal(vspec: Val) = + member _.AddVal(vspec: Val) = ModuleOrNamespaceType(kind, vals.AppendOne vspec, entities) /// Get a table of the active patterns defined in this module. - member mtyp.ActivePatternElemRefLookupTable = activePatternElemRefCache + member _.ActivePatternElemRefLookupTable = activePatternElemRefCache /// Get a list of types defined within this module, namespace or type. - member mtyp.TypeDefinitions = entities |> Seq.filter (fun x -> not x.IsExceptionDecl && not x.IsModuleOrNamespace) |> Seq.toList + member _.TypeDefinitions = entities |> Seq.filter (fun x -> not x.IsExceptionDecl && not x.IsModuleOrNamespace) |> Seq.toList /// Get a list of F# exception definitions defined within this module, namespace or type. - member mtyp.ExceptionDefinitions = entities |> Seq.filter (fun x -> x.IsExceptionDecl) |> Seq.toList + member _.ExceptionDefinitions = entities |> Seq.filter (fun x -> x.IsExceptionDecl) |> Seq.toList /// Get a list of module and namespace definitions defined within this module, namespace or type. - member mtyp.ModuleAndNamespaceDefinitions = entities |> Seq.filter (fun x -> x.IsModuleOrNamespace) |> Seq.toList + member _.ModuleAndNamespaceDefinitions = entities |> Seq.filter (fun x -> x.IsModuleOrNamespace) |> Seq.toList /// Get a list of type and exception definitions defined within this module, namespace or type. - member mtyp.TypeAndExceptionDefinitions = entities |> Seq.filter (fun x -> not x.IsModuleOrNamespace) |> Seq.toList + member _.TypeAndExceptionDefinitions = entities |> Seq.filter (fun x -> not x.IsModuleOrNamespace) |> Seq.toList /// Get a table of types defined within this module, namespace or type. The /// table is indexed by both name and generic arity. This means that for generic /// types "List`1", the entry (List, 1) will be present. member mtyp.TypesByDemangledNameAndArity m = cacheOptRef tyconsByDemangledNameAndArityCache (fun () -> - LayeredMap.Empty.AddAndMarkAsCollapsible( mtyp.TypeAndExceptionDefinitions |> List.map (fun (tc: Tycon) -> KeyTyconByDemangledNameAndArity tc.LogicalName (tc.Typars m) tc) |> List.toArray)) + LayeredMap.Empty.AddAndMarkAsCollapsible( mtyp.TypeAndExceptionDefinitions |> List.map (fun (tc: Tycon) -> Construct.KeyTyconByDemangledNameAndArity tc.LogicalName (tc.Typars m) tc) |> List.toArray)) /// Get a table of types defined within this module, namespace or type. The /// table is indexed by both name and, for generic types, also by mangled name. member mtyp.TypesByAccessNames = cacheOptRef tyconsByAccessNamesCache (fun () -> - LayeredMultiMap.Empty.AddAndMarkAsCollapsible (mtyp.TypeAndExceptionDefinitions |> List.toArray |> Array.collect (fun (tc: Tycon) -> KeyTyconByAccessNames tc.LogicalName tc))) + LayeredMultiMap.Empty.AddAndMarkAsCollapsible (mtyp.TypeAndExceptionDefinitions |> List.toArray |> Array.collect (fun (tc: Tycon) -> Construct.KeyTyconByAccessNames tc.LogicalName tc))) - // REVIEW: we can remove this lookup and use AllEntitiedByMangledName instead? + // REVIEW: we can remove this lookup and use AllEntitiesByMangledName instead? member mtyp.TypesByMangledName = let addTyconByMangledName (x: Tycon) tab = NameMap.add x.LogicalName x tab cacheOptRef tyconsByMangledNameCache (fun () -> List.foldBack addTyconByMangledName mtyp.TypeAndExceptionDefinitions Map.empty) /// Get a table of entities indexed by both logical and compiled names - member mtyp.AllEntitiesByCompiledAndLogicalMangledNames: NameMap = + member _.AllEntitiesByCompiledAndLogicalMangledNames: NameMap = let addEntityByMangledName (x: Entity) tab = let name1 = x.LogicalName let name2 = x.CompiledName @@ -1916,13 +1941,13 @@ and [] QueueList.foldBack addEntityByMangledName entities Map.empty) /// Get a table of entities indexed by both logical name - member mtyp.AllEntitiesByLogicalMangledName: NameMap = + member _.AllEntitiesByLogicalMangledName: NameMap = let addEntityByMangledName (x: Entity) tab = NameMap.add x.LogicalName x tab QueueList.foldBack addEntityByMangledName entities Map.empty /// Get a table of values and members indexed by partial linkage key, which includes name, the mangled name of the parent type (if any), /// and the method argument count (if any). - member mtyp.AllValsAndMembersByPartialLinkageKey = + member _.AllValsAndMembersByPartialLinkageKey = let addValByMangledName (x: Val) tab = if x.IsCompiledAsTopLevel then let key = x.GetLinkagePartialKey() @@ -1942,7 +1967,7 @@ and [] |> ValueOptionInternal.ofOption /// Get a table of values indexed by logical name - member mtyp.AllValsByLogicalName = + member _.AllValsByLogicalName = let addValByName (x: Val) tab = // Note: names may occur twice prior to raising errors about this in PostTypeCheckSemanticChecks // Earlier ones take precedence since we report errors about the later ones @@ -1954,7 +1979,7 @@ and [] QueueList.foldBack addValByName vals Map.empty) /// Compute a table of values and members indexed by logical name. - member mtyp.AllValsAndMembersByLogicalNameUncached = + member _.AllValsAndMembersByLogicalNameUncached = let addValByName (x: Val) tab = if not x.IsCompilerGenerated then MultiMap.add x.LogicalName x tab @@ -1969,7 +1994,7 @@ and [] List.foldBack add mtyp.ExceptionDefinitions Map.empty) /// Get a table of nested module and namespace fragments indexed by demangled name (so 'ListModule' becomes 'List') - member mtyp.ModulesAndNamespacesByDemangledName = + member _.ModulesAndNamespacesByDemangledName = let add (entity: Entity) acc = if entity.IsModuleOrNamespace then NameMap.add entity.DemangledModuleOrNamespaceName entity acc @@ -1978,131 +2003,20 @@ and [] QueueList.foldBack add entities Map.empty) [] - member x.DebugText = x.ToString() - - override x.ToString() = "ModuleOrNamespaceType(...)" - -and ModuleOrNamespace = Entity -and Tycon = Entity - -/// A set of static methods for constructing types. -and Construct = - - static member NewModuleOrNamespaceType mkind tycons vals = - ModuleOrNamespaceType(mkind, QueueList.ofList vals, QueueList.ofList tycons) - - static member NewEmptyModuleOrNamespaceType mkind = - Construct.NewModuleOrNamespaceType mkind [] [] - -#if !NO_EXTENSIONTYPING - - static member NewProvidedTyconRepr(resolutionEnvironment, st: Tainted, importProvidedType, isSuppressRelocate, m) = - - let isErased = st.PUntaint((fun st -> st.IsErased), m) - - let lazyBaseTy = - LazyWithContext.Create - ((fun (m, objTy) -> - let baseSystemTy = st.PApplyOption((fun st -> match st.BaseType with null -> None | ty -> Some ty), m) - match baseSystemTy with - | None -> objTy - | Some t -> importProvidedType t), - ErrorLogger.findOriginalException) + member mtyp.DebugText = mtyp.ToString() - TProvidedTypeExtensionPoint - { ResolutionEnvironment=resolutionEnvironment - ProvidedType=st - LazyBaseType=lazyBaseTy - UnderlyingTypeOfEnum = (fun () -> importProvidedType (st.PApply((fun st -> st.GetEnumUnderlyingType()), m))) - IsDelegate = (fun () -> st.PUntaint((fun st -> - let baseType = st.BaseType - match baseType with - | null -> false - | x when x.IsGenericType -> false - | x when x.DeclaringType <> null -> false - | x -> x.FullName = "System.Delegate" || x.FullName = "System.MulticastDelegate"), m)) - IsEnum = st.PUntaint((fun st -> st.IsEnum), m) - IsStructOrEnum = st.PUntaint((fun st -> st.IsValueType || st.IsEnum), m) - IsInterface = st.PUntaint((fun st -> st.IsInterface), m) - IsSealed = st.PUntaint((fun st -> st.IsSealed), m) - IsClass = st.PUntaint((fun st -> st.IsClass), m) - IsErased = isErased - IsSuppressRelocate = isSuppressRelocate } - - static member NewProvidedTycon(resolutionEnvironment, st: Tainted, importProvidedType, isSuppressRelocate, m, ?access, ?cpath) = - let stamp = newStamp() - let name = st.PUntaint((fun st -> st.Name), m) - let id = ident (name, m) - let kind = - let isMeasure = - st.PApplyWithProvider((fun (st, provider) -> - let findAttrib (ty: System.Type) (a: CustomAttributeData) = (a.Constructor.DeclaringType.FullName = ty.FullName) - let ty = st.RawSystemType - ignore provider - ty.CustomAttributes - |> Seq.exists (findAttrib typeof)), m) - .PUntaintNoFailure(fun x -> x) - if isMeasure then TyparKind.Measure else TyparKind.Type - - let access = - match access with - | Some a -> a - | None -> TAccess [] - let cpath = - match cpath with - | None -> - let ilScopeRef = st.TypeProviderAssemblyRef - let enclosingName = ExtensionTyping.GetFSharpPathToProvidedType(st, m) - CompPath(ilScopeRef, enclosingName |> List.map(fun id->id, ModuleOrNamespaceKind.Namespace)) - | Some p -> p - let pubpath = cpath.NestedPublicPath id + override _.ToString() = "ModuleOrNamespaceType(...)" - let repr = Construct.NewProvidedTyconRepr(resolutionEnvironment, st, importProvidedType, isSuppressRelocate, m) +/// Represents a module or namespace definition in the typed AST +type ModuleOrNamespace = Entity - Tycon.New "tycon" - { entity_stamp=stamp - entity_logical_name=name - entity_range=m - entity_flags=EntityFlags(usesPrefixDisplay=false, isModuleOrNamespace=false, preEstablishedHasDefaultCtor=false, hasSelfReferentialCtor=false, isStructRecordOrUnionType=false) - entity_attribs=[] // fetched on demand via est.fs API - entity_typars= LazyWithContext.NotLazy [] - entity_tycon_repr = repr - entity_tycon_tcaug=TyconAugmentation.Create() - entity_modul_contents = MaybeLazy.Lazy (lazy new ModuleOrNamespaceType(Namespace, QueueList.ofList [], QueueList.ofList [])) - // Generated types get internal accessibility - entity_pubpath = Some pubpath - entity_cpath = Some cpath - entity_il_repr_cache = newCache() - entity_opt_data = - match kind, access with - | TyparKind.Type, TAccess [] -> None - | _ -> Some { Entity.NewEmptyEntityOptData() with entity_kind = kind; entity_accessiblity = access } } -#endif +/// Represents a type or exception definition in the typed AST +type Tycon = Entity - static member NewModuleOrNamespace cpath access (id: Ident) xml attribs mtype = - let stamp = newStamp() - // Put the module suffix on if needed - Tycon.New "mspec" - { entity_logical_name=id.idText - entity_range = id.idRange - entity_stamp=stamp - entity_modul_contents = mtype - entity_flags=EntityFlags(usesPrefixDisplay=false, isModuleOrNamespace=true, preEstablishedHasDefaultCtor=false, hasSelfReferentialCtor=false, isStructRecordOrUnionType=false) - entity_typars=LazyWithContext.NotLazy [] - entity_tycon_repr = TNoRepr - entity_tycon_tcaug=TyconAugmentation.Create() - entity_pubpath=cpath |> Option.map (fun (cp: CompilationPath) -> cp.NestedPublicPath id) - entity_cpath=cpath - entity_attribs=attribs - entity_il_repr_cache = newCache() - entity_opt_data = - match xml, access with - | XmlDoc [||], TAccess [] -> None - | _ -> Some { Entity.NewEmptyEntityOptData() with entity_xmldoc = xml; entity_tycon_repr_accessibility = access; entity_accessiblity = access } } +/// Represents the constraint on access for a construct +[] +type Accessibility = -and - [] - Accessibility = /// Indicates the construct can only be accessed from any code in the given type constructor, module or assembly. [] indicates global scope. | TAccess of CompilationPath list @@ -2111,18 +2025,19 @@ and override x.ToString() = "Accessibility(...)" -and - [] - TyparOptionalData = +/// Represents less-frequently-required data about a type parameter of type inference variable +[] +type TyparOptionalData = { /// MUTABILITY: we set the names of generalized inference type parameters to make the look nice for IL code generation + /// The storage for the IL name for the type parameter. mutable typar_il_name: string option - /// The documentation for the type parameter. Empty for type inference variables. + /// The documentation for the type parameter. Empty for inference variables. /// MUTABILITY: for linking when unpickling mutable typar_xmldoc: XmlDoc - /// The inferred constraints for the type inference variable + /// The inferred constraints for the type parameter or inference variable. mutable typar_constraints: TyparConstraint list /// The declared attributes of the type parameter. Empty for type inference variables. @@ -2134,24 +2049,20 @@ and override __.ToString() = sprintf "TyparOptionalData(...)" -and TyparData = Typar - -and - [] - /// A declared generic type/measure parameter, or a type/measure inference variable. - Typar = - // Backing data for type parameters and type inference variables - // - // where the "common" settings are - // kind=TyparKind.Type, rigid=TyparRigidity.Flexible, id=compgen_id, staticReq=NoStaticReq, isCompGen=true, isFromError=false, - // dynamicReq=TyparDynamicReq.No, attribs=[], eqDep=false, compDep=false +type TyparData = Typar - { /// MUTABILITY: we set the names of generalized inference type parameters to make the look nice for IL code generation +/// A declared generic type/measure parameter, or a type/measure inference variable. +[] +type Typar = + { + /// MUTABILITY: we set the names of generalized inference type parameters to make the look nice for IL code generation + /// The identifier for the type parameter mutable typar_id: Ident + /// The flag data for the type parameter mutable typar_flags: TyparFlags - /// The unique stamp of the typar blob. + /// The unique stamp of the type parameter /// MUTABILITY: for linking when unpickling mutable typar_stamp: Stamp @@ -2161,7 +2072,9 @@ and /// A cached TAST type used when this type variable is used as type. mutable typar_astype: TType - mutable typar_opt_data: TyparOptionalData option } + /// The optional data for the type parameter + mutable typar_opt_data: TyparOptionalData option + } /// The name of the type parameter member x.Name = x.typar_id.idText @@ -2210,7 +2123,7 @@ and member x.IsCompatFlex = x.typar_flags.IsCompatFlex /// Set whether this type parameter is a compat-flex type parameter (i.e. where "expr :> tp" only emits an optional warning) - member x.SetIsCompatFlex(b) = x.typar_flags <- x.typar_flags.WithCompatFlex(b) + member x.SetIsCompatFlex b = x.typar_flags <- x.typar_flags.WithCompatFlex b /// Indicates whether a type variable can be instantiated by types or units-of-measure. member x.Kind = x.typar_flags.Kind @@ -2218,12 +2131,13 @@ and /// Indicates whether a type variable is erased in compiled .NET IL code, i.e. whether it is a unit-of-measure variable member x.IsErased = match x.Kind with TyparKind.Type -> false | _ -> true - /// The declared attributes of the type parameter. Empty for type inference variables and parameters from .NET + /// The declared attributes of the type parameter. Empty for type inference variables and parameters from .NET. member x.Attribs = match x.typar_opt_data with | Some optData -> optData.typar_attribs | _ -> [] + /// Set the attributes on the type parameter member x.SetAttribs attribs = match attribs, x.typar_opt_data with | [], None -> () @@ -2232,16 +2146,19 @@ and | _, Some optData -> optData.typar_attribs <- attribs | _ -> x.typar_opt_data <- Some { typar_il_name = None; typar_xmldoc = XmlDoc.Empty; typar_constraints = []; typar_attribs = attribs } + /// Get the XML documetnation for the type parameter member x.XmlDoc = match x.typar_opt_data with | Some optData -> optData.typar_xmldoc | _ -> XmlDoc.Empty + /// Get the IL name of the type parameter member x.ILName = match x.typar_opt_data with | Some optData -> optData.typar_il_name | _ -> None + /// Set the IL name of the type parameter member x.SetILName il_name = match x.typar_opt_data with | Some optData -> optData.typar_il_name <- il_name @@ -2259,7 +2176,6 @@ and | _, Some optData -> optData.typar_constraints <- cs | _ -> x.typar_opt_data <- Some { typar_il_name = None; typar_xmldoc = XmlDoc.Empty; typar_constraints = cs; typar_attribs = [] } - /// Creates a type variable that contains empty data, and is not yet linked. Only used during unpickling of F# metadata. static member NewUnlinked() : Typar = { typar_id = Unchecked.defaultof<_> @@ -2329,48 +2245,49 @@ and override x.ToString() = x.Name -and - [] - TyparConstraint = - /// Indicates a constraint that a type is a subtype of the given type +/// Represents a constraint on a type parameter or type +[] +type TyparConstraint = + + /// A constraint that a type is a subtype of the given type | CoercesTo of TType * range - /// Indicates a default value for an inference type variable should it be neither generalized nor solved + /// A constraint for a default value for an inference type variable should it be neither generalized nor solved | DefaultsTo of int * TType * range - /// Indicates a constraint that a type has a 'null' value + /// A constraint that a type has a 'null' value | SupportsNull of range - /// Indicates a constraint that a type has a member with the given signature - | MayResolveMember of TraitConstraintInfo * range + /// A constraint that a type has a member with the given signature + | MayResolveMember of TraitConstraintInfo * range - /// Indicates a constraint that a type is a non-Nullable value type + /// A constraint that a type is a non-Nullable value type /// These are part of .NET's model of generic constraints, and in order to /// generate verifiable code we must attach them to F# generalized type variables as well. | IsNonNullableStruct of range - /// Indicates a constraint that a type is a reference type + /// A constraint that a type is a reference type | IsReferenceType of range - /// Indicates a constraint that a type is a simple choice between one of the given ground types. Only arises from 'printf' format strings. See format.fs + /// A constraint that a type is a simple choice between one of the given ground types. Only arises from 'printf' format strings. See format.fs | SimpleChoice of TTypes * range - /// Indicates a constraint that a type has a parameterless constructor + /// A constraint that a type has a parameterless constructor | RequiresDefaultConstructor of range - /// Indicates a constraint that a type is an enum with the given underlying + /// A constraint that a type is an enum with the given underlying | IsEnum of TType * range - /// Indicates a constraint that a type implements IComparable, with special rules for some known structural container types + /// A constraint that a type implements IComparable, with special rules for some known structural container types | SupportsComparison of range - /// Indicates a constraint that a type does not have the Equality(false) attribute, or is not a structural type with this attribute, with special rules for some known structural container types + /// A constraint that a type does not have the Equality(false) attribute, or is not a structural type with this attribute, with special rules for some known structural container types | SupportsEquality of range - /// Indicates a constraint that a type is a delegate from the given tuple of args to the given return type + /// A constraint that a type is a delegate from the given tuple of args to the given return type | IsDelegate of TType * TType * range - /// Indicates a constraint that a type is .NET unmanaged type + /// A constraint that a type is .NET unmanaged type | IsUnmanaged of range // %+A formatting is used, so this is not needed @@ -2379,20 +2296,20 @@ and override x.ToString() = sprintf "%+A" x -/// The specification of a member constraint that must be solved -and - [] - TraitConstraintInfo = +/// Represents the specification of a member constraint that must be solved +[] +type TraitConstraintInfo = - /// TTrait(tys, nm, memFlags, argtys, rty, colution) - /// /// Indicates the signature of a member constraint. Contains a mutable solution cell /// to store the inferred solution of the constraint. - | TTrait of TTypes * string * MemberFlags * TTypes * TType option * TraitConstraintSln option ref + | TTrait of tys: TTypes * memberName: string * _memFlags: MemberFlags * argTys: TTypes * returnTy: TType option * solution: TraitConstraintSln option ref /// Get the member name associated with the member constraint. member x.MemberName = (let (TTrait(_, nm, _, _, _, _)) = x in nm) + /// Get the argument types required of a member in order to solve the constraint + member x.ArgumentTypes = (let (TTrait(_, _, _, argtys, _, _)) = x in argtys) + /// Get the return type recorded in the member constraint. member x.ReturnType = (let (TTrait(_, _, _, _, ty, _)) = x in ty) @@ -2406,10 +2323,9 @@ and override x.ToString() = "TTrait(" + x.MemberName + ")" -and - [] - /// Indicates the solution of a member constraint during inference. - TraitConstraintSln = +/// Represents the solution of a member constraint during inference. +[] +type TraitConstraintSln = /// FSMethSln(ty, vref, minst) /// @@ -2439,7 +2355,7 @@ and /// minst -- the generic method instantiation | ILMethSln of TType * ILTypeRef option * ILMethodRef * TypeInst - /// ClosedExprSln(expr) + /// ClosedExprSln expr /// /// Indicates a trait is solved by an erased provided expression | ClosedExprSln of Expr @@ -2454,9 +2370,10 @@ and override x.ToString() = sprintf "%+A" x /// The partial information used to index the methods of all those in a ModuleOrNamespace. -and [] - ValLinkagePartialKey = - { /// The name of the type with which the member is associated. None for non-member values. +[] +type ValLinkagePartialKey = + { + /// The name of the type with which the member is associated. None for non-member values. MemberParentMangledName: string option /// Indicates if the member is an override. @@ -2466,7 +2383,8 @@ and [] LogicalName: string /// Indicates the total argument count of the member. - TotalArgCount: int } + TotalArgCount: int + } [] member x.DebugText = x.ToString() @@ -2475,9 +2393,8 @@ and [] /// The full information used to identify a specific overloaded method /// amongst all those in a ModuleOrNamespace. -and - [< (* NoEquality; NoComparison; *) StructuredFormatDisplay("{DebugText}")>] - ValLinkageFullKey(partialKey: ValLinkagePartialKey, typeForLinkage: TType option) = +[] +type ValLinkageFullKey(partialKey: ValLinkagePartialKey, typeForLinkage: TType option) = /// The partial information used to index the value in a ModuleOrNamespace. member x.PartialKey = partialKey @@ -2490,9 +2407,8 @@ and override x.ToString() = "ValLinkageFullKey(" + partialKey.LogicalName + ")" -and - [] - ValOptionalData = +[] +type ValOptionalData = { /// MUTABILITY: for unpickle linkage mutable val_compiled_name: string option @@ -2548,10 +2464,11 @@ and override x.ToString() = "ValOptionalData(...)" -and ValData = Val -and [] - Val = - { +type ValData = Val + +[] +type Val = + { /// Mutable for unpickle linkage mutable val_logical_name: string @@ -2563,12 +2480,12 @@ and [] /// Mutable for unpickle linkage mutable val_stamp: Stamp - /// See vflags section further below for encoding/decodings here + /// See vflags section further below for encoding/decodings here mutable val_flags: ValFlags - - mutable val_opt_data: ValOptionalData option } - static member NewEmptyValOptData() = + mutable val_opt_data: ValOptionalData option } + + static member NewEmptyValOptData() = { val_compiled_name = None val_other_range = None val_const = None @@ -2706,19 +2623,19 @@ and [] /// Indicates if this is an F#-defined 'new' constructor member member x.IsConstructor = match x.MemberInfo with - | Some(memberInfo) when not x.IsExtensionMember && (memberInfo.MemberFlags.MemberKind = MemberKind.Constructor) -> true + | Some memberInfo when not x.IsExtensionMember && (memberInfo.MemberFlags.MemberKind = MemberKind.Constructor) -> true | _ -> false /// Indicates if this is a compiler-generated class constructor member member x.IsClassConstructor = match x.MemberInfo with - | Some(memberInfo) when not x.IsExtensionMember && (memberInfo.MemberFlags.MemberKind = MemberKind.ClassConstructor) -> true + | Some memberInfo when not x.IsExtensionMember && (memberInfo.MemberFlags.MemberKind = MemberKind.ClassConstructor) -> true | _ -> false /// Indicates if this value was a member declared 'override' or an implementation of an interface slot member x.IsOverrideOrExplicitImpl = match x.MemberInfo with - | Some(memberInfo) when memberInfo.MemberFlags.IsOverrideOrExplicitImpl -> true + | Some memberInfo when memberInfo.MemberFlags.IsOverrideOrExplicitImpl -> true | _ -> false /// Indicates if this is declared 'mutable' @@ -2738,6 +2655,9 @@ and [] /// Indicates if the value is pinned/fixed member x.IsFixed = x.val_flags.IsFixed + /// Indicates if the value will ignore byref scoping rules + member x.IgnoresByrefScope = x.val_flags.IgnoresByrefScope + /// Indicates if this value allows the use of an explicit type instantiation (i.e. does it itself have explicit type arguments, /// or does it have a signature?) member x.PermitsExplicitTypeInstantiation = x.val_flags.PermitsExplicitTypeInstantiation @@ -2786,7 +2706,7 @@ and [] match x.val_opt_data with | Some optData -> optData.val_xmldocsig | _ -> String.Empty - and set(v) = + and set v = match x.val_opt_data with | Some optData -> optData.val_xmldocsig <- v | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_xmldocsig = v } @@ -2853,7 +2773,7 @@ and [] /// Indicates if this member is an F#-defined dispatch slot. member x.IsDispatchSlot = match x.MemberInfo with - | Some(membInfo) -> membInfo.MemberFlags.IsDispatchSlot + | Some membInfo -> membInfo.MemberFlags.IsDispatchSlot | _ -> false /// Get the type of the value including any generic type parameters @@ -2896,7 +2816,7 @@ and [] /// - If this is an implementation of an abstract slot then this may be a mangled name /// - If this is an extension member then this will be a mangled name /// - If this is an operator then this is 'op_Addition' - member x.CompiledName = + member x.CompiledName (compilerGlobalState:CompilerGlobalState option) = let givenName = match x.val_opt_data with | Some { val_compiled_name = Some n } -> n @@ -2915,10 +2835,10 @@ and [] // let dt = System.DateTime.Now - System.DateTime.Now // IsMemberOrModuleBinding = false, IsCompiledAsTopLevel = true, IsMember = false, CompilerGenerated=true // // However we don't need this for CompilerGenerated members such as the implementations of IComparable - if x.IsCompiledAsTopLevel && not x.IsMember && (x.IsCompilerGenerated || not x.IsMemberOrModuleBinding) then - globalStableNameGenerator.GetUniqueCompilerGeneratedName(givenName, x.Range, x.Stamp) - else - givenName + match compilerGlobalState with + | Some state when x.IsCompiledAsTopLevel && not x.IsMember && (x.IsCompilerGenerated || not x.IsMemberOrModuleBinding) -> + state.StableNameGenerator.GetUniqueCompilerGeneratedName(givenName, x.Range, x.Stamp) + | _ -> givenName /// The name of the property. /// - If this is a property then this is 'Foo' @@ -2961,6 +2881,8 @@ and [] member x.SetIsFixed() = x.val_flags <- x.val_flags.WithIsFixed + member x.SetIgnoresByrefScope() = x.val_flags <- x.val_flags.WithIgnoresByrefScope + member x.SetValReprInfo info = match x.val_opt_data with | Some optData -> optData.val_repr_info <- info @@ -3041,11 +2963,11 @@ and [] override x.ToString() = x.LogicalName -and - /// Represents the extra information stored for a member - [] - ValMemberInfo = - { /// The parent type. For an extension member this is the type being extended +/// Represents the extra information stored for a member +[] +type ValMemberInfo = + { + /// The parent type. For an extension member this is the type being extended ApparentEnclosingEntity: TyconRef /// Updated with the full implemented slotsig after interface implementation relation is checked @@ -3054,21 +2976,23 @@ and /// Gets updated with 'true' if an abstract slot is implemented in the file being typechecked. Internal only. mutable IsImplemented: bool - MemberFlags: MemberFlags } + MemberFlags: MemberFlags + } [] member x.DebugText = x.ToString() override x.ToString() = "ValMemberInfo(...)" -and - [] - NonLocalValOrMemberRef = - { /// A reference to the entity containing the value or member. This will always be a non-local reference +[] +type NonLocalValOrMemberRef = + { + /// A reference to the entity containing the value or member. This will always be a non-local reference EnclosingEntity: EntityRef /// The name of the value, or the full signature of the member - ItemKey: ValLinkageFullKey } + ItemKey: ValLinkageFullKey + } /// Get the thunk for the assembly referred to member x.Ccu = x.EnclosingEntity.nlr.Ccu @@ -3083,9 +3007,10 @@ and /// For debugging override x.ToString() = x.EnclosingEntity.nlr.ToString() + "::" + x.ItemKey.PartialKey.LogicalName -and - [] - ValPublicPath = +/// Represents the path information for a reference to a value or member in another assembly, disassociated +/// from any particular reference. +[] +type ValPublicPath = | ValPubPath of PublicPath * ValLinkageFullKey [] @@ -3093,10 +3018,9 @@ and override __.ToString() = sprintf "ValPubPath(...)" -/// Index into the namespace/module structure of a particular CCU -and - [] - NonLocalEntityRef = +/// Represents an index into the namespace/module structure of an assembly +[] +type NonLocalEntityRef = | NonLocalEntityRef of CcuThunk * string[] /// Try to find the entity corresponding to the given path in the given CCU @@ -3129,8 +3053,8 @@ and | Tainted.Null -> ValueNone | st -> let newEntity = Construct.NewProvidedTycon(resolutionEnvironment, st, ccu.ImportProvidedType, false, m) - parentEntity.ModuleOrNamespaceType.AddProvidedTypeEntity(newEntity) - if i = path.Length-1 then ValueSome(newEntity) + parentEntity.ModuleOrNamespaceType.AddProvidedTypeEntity newEntity + if i = path.Length-1 then ValueSome newEntity else tryResolveNestedTypeOf(newEntity, resolutionEnvironment, st, i+1) tryResolveNestedTypeOf(entity, resolutionEnvironment, st, i) @@ -3172,7 +3096,7 @@ and let rec injectNamespacesFromIToJ (entity: Entity) k = if k = j then let newEntity = Construct.NewProvidedTycon(resolutionEnvironment, st, ccu.ImportProvidedType, false, m) - entity.ModuleOrNamespaceType.AddProvidedTypeEntity(newEntity) + entity.ModuleOrNamespaceType.AddProvidedTypeEntity newEntity newEntity else let cpath = entity.CompilationPath.NestedCompPath entity.LogicalName ModuleOrNamespaceKind.Namespace @@ -3181,7 +3105,7 @@ and (Some cpath) (TAccess []) (ident(path.[k], m)) XmlDoc.Empty [] (MaybeLazy.Strict (Construct.NewEmptyModuleOrNamespaceType Namespace)) - entity.ModuleOrNamespaceType.AddModuleOrNamespaceByMutation(newEntity) + entity.ModuleOrNamespaceType.AddModuleOrNamespaceByMutation newEntity injectNamespacesFromIToJ newEntity (k+1) let newEntity = injectNamespacesFromIToJ entity i @@ -3203,10 +3127,10 @@ and #endif /// Try to link a non-local entity reference to an actual entity - member nleref.TryDeref(canError) = + member nleref.TryDeref canError = let (NonLocalEntityRef(ccu, path)) = nleref if canError then - ccu.EnsureDerefable(path) + ccu.EnsureDerefable path if ccu.IsUnresolvedReference then ValueNone else @@ -3268,24 +3192,28 @@ and override x.ToString() = x.DisplayName -and - [] - EntityRef = - { /// Indicates a reference to something bound in this CCU +[] +type EntityRef = + { + /// Indicates a reference to something bound in this CCU mutable binding: NonNullSlot + /// Indicates a reference to something bound in another CCU - nlr: NonLocalEntityRef } + nlr: NonLocalEntityRef + } + /// Indicates if the reference is a local reference member x.IsLocalRef = match box x.nlr with null -> true | _ -> false + /// Indicates if the reference has been resolved member x.IsResolved = match box x.binding with null -> false | _ -> true - member x.PrivateTarget = x.binding - + /// The resolved target of the reference member x.ResolvedTarget = x.binding - member private tcr.Resolve(canError) = - let res = tcr.nlr.TryDeref(canError) + /// Resolve the reference + member private tcr.Resolve canError = + let res = tcr.nlr.TryDeref canError match res with | ValueSome r -> tcr.binding <- nullableSlotFull r @@ -3340,6 +3268,9 @@ and /// The display name of the namespace, module or type, e.g. List instead of List`1, not including static parameters member x.DisplayName = x.Deref.DisplayName + /// The display name of the namespace, module or type with <'T, 'U, 'V> added for generic types, including static parameters + member x.DisplayNameWithStaticParametersAndTypars = x.Deref.DisplayNameWithStaticParametersAndTypars + /// The display name of the namespace, module or type with <_, _, _> added for generic types, including static parameters member x.DisplayNameWithStaticParametersAndUnderscoreTypars = x.Deref.DisplayNameWithStaticParametersAndUnderscoreTypars @@ -3475,7 +3406,6 @@ and /// Get a list of all instance fields for F#-defined record, struct and class fields in this type definition. /// including hidden fields from the compilation of implicit class constructions. - // NOTE: This method doesn't perform particularly well, and is over-used, but doesn't seem to appear on performance traces member x.AllInstanceFieldsAsList = x.Deref.AllInstanceFieldsAsList /// Get a field by index in definition order @@ -3564,12 +3494,18 @@ and /// Set the on-demand analysis about whether the entity has the IsByRefLike attribute member x.SetIsByRefLike b = x.Deref.SetIsByRefLike b - /// The on-demand analysis about whether the entity has the IsByRefLike attribute + /// The on-demand analysis about whether the entity has the IsReadOnly attribute member x.TryIsReadOnly = x.Deref.TryIsReadOnly - /// Set the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct + /// Set the on-demand analysis about whether the entity has the IsReadOnly attribute member x.SetIsReadOnly b = x.Deref.SetIsReadOnly b + /// The on-demand analysis about whether the entity is assumed to be a readonly struct + member x.TryIsAssumedReadOnly = x.Deref.TryIsAssumedReadOnly + + /// Set the on-demand analysis about whether the entity is assumed to be a readonly struct + member x.SetIsAssumedReadOnly b = x.Deref.SetIsAssumedReadOnly b + /// Indicates if this is an F# type definition whose r.h.s. definition is unknown (i.e. a traditional ML 'abstract' type in a signature, /// which in F# is called a 'unknown representation' type). member x.IsHiddenReprTycon = x.Deref.IsHiddenReprTycon @@ -3607,9 +3543,9 @@ and member x.AllFieldAsRefList = x.AllFieldsAsList |> List.map x.MakeNestedRecdFieldRef - member x.MakeNestedRecdFieldRef (rf: RecdField) = RFRef (x, rf.Name) + member x.MakeNestedRecdFieldRef (rf: RecdField) = RecdFieldRef (x, rf.Name) - member x.MakeNestedUnionCaseRef (uc: UnionCase) = UCRef (x, uc.Id.idText) + member x.MakeNestedUnionCaseRef (uc: UnionCase) = UnionCaseRef (x, uc.Id.idText) [] member x.DebugText = x.ToString() @@ -3620,27 +3556,27 @@ and else x.nlr.DisplayName +/// Represents a module-or-namespace reference in the typed abstract syntax. +type ModuleOrNamespaceRef = EntityRef -/// note: ModuleOrNamespaceRef and TyconRef are type equivalent -and ModuleOrNamespaceRef = EntityRef - -and TyconRef = EntityRef +/// Represents a type definition reference in the typed abstract syntax. +type TyconRef = EntityRef /// References are either local or nonlocal -and - [] - ValRef = - { /// Indicates a reference to something bound in this CCU +[] +type ValRef = + { + /// Indicates a reference to something bound in this CCU mutable binding: NonNullSlot + /// Indicates a reference to something bound in another CCU - nlr: NonLocalValOrMemberRef } + nlr: NonLocalValOrMemberRef + } member x.IsLocalRef = obj.ReferenceEquals(x.nlr, null) member x.IsResolved = not (obj.ReferenceEquals(x.binding, null)) - member x.PrivateTarget = x.binding - member x.ResolvedTarget = x.binding /// Dereference the ValRef to a Val. @@ -3847,16 +3783,15 @@ and else x.nlr.ToString() /// Represents a reference to a case of a union type -and - [] - UnionCaseRef = - | UCRef of TyconRef * string +[] +type UnionCaseRef = + | UnionCaseRef of TyconRef * string /// Get a reference to the type containing this union case - member x.TyconRef = let (UCRef(tcref, _)) = x in tcref + member x.TyconRef = let (UnionCaseRef(tcref, _)) = x in tcref /// Get the name of this union case - member x.CaseName = let (UCRef(_, nm)) = x in nm + member x.CaseName = let (UnionCaseRef(_, nm)) = x in nm /// Get the Entity for the type containing this union case member x.Tycon = x.TyconRef.Deref @@ -3907,23 +3842,22 @@ and override x.ToString() = x.CaseName /// Represents a reference to a field in a record, class or struct -and - [] - RecdFieldRef = - | RFRef of TyconRef * string +[] +type RecdFieldRef = + | RecdFieldRef of TyconRef * string /// Get a reference to the type containing this union case - member x.TyconRef = let (RFRef(tcref, _)) = x in tcref + member x.TyconRef = let (RecdFieldRef(tcref, _)) = x in tcref /// Get the name off the field - member x.FieldName = let (RFRef(_, id)) = x in id + member x.FieldName = let (RecdFieldRef(_, id)) = x in id /// Get the Entity for the type containing this union case member x.Tycon = x.TyconRef.Deref /// Dereference the reference member x.RecdField = - let (RFRef(tcref, id)) = x + let (RecdFieldRef(tcref, id)) = x match tcref.GetFieldByName id with | Some res -> res | None -> error(InternalError(sprintf "field %s not found in type %s" id tcref.LogicalName, tcref.Range)) @@ -3946,7 +3880,7 @@ and member x.SigRange = x.RecdField.SigRange member x.Index = - let (RFRef(tcref, id)) = x + let (RecdFieldRef(tcref, id)) = x try // REVIEW: this could be faster, e.g. by storing the index in the NameMap tcref.AllFieldsArray |> Array.findIndex (fun rfspec -> rfspec.Name = id) @@ -3958,10 +3892,9 @@ and override x.ToString() = x.FieldName -and - /// The algebra of types - [] - TType = +/// Represents a type in the typed abstract syntax +[] +type TType = /// TType_forall(typars, bodyTy). /// @@ -4041,16 +3974,25 @@ and | Some _ -> tp.DisplayName + " (solved)" | TType_measure ms -> ms.ToString() -and TypeInst = TType list +type TypeInst = TType list -and TTypes = TType list -and [] AnonRecdTypeInfo = - // Mutability for pickling/unpickling only - { mutable Assembly: CcuThunk - mutable TupInfo: TupInfo - mutable SortedIds: Ident[] - mutable Stamp: Stamp - mutable SortedNames: string[] } +type TTypes = TType list + +/// Represents the information identifying an anonymous record +[] +type AnonRecdTypeInfo = + { + // Mutability for pickling/unpickling only + mutable Assembly: CcuThunk + + mutable TupInfo: TupInfo + + mutable SortedIds: Ident[] + + mutable Stamp: Stamp + + mutable SortedNames: string[] + } /// Create an AnonRecdTypeInfo from the basic data static member Create(ccu: CcuThunk, tupInfo, ids: Ident[]) = @@ -4068,7 +4010,7 @@ and [] AnonRecdTypeInfo = /// Get the ILTypeRef for the generated type implied by the anonymous type member x.ILTypeRef = - let ilTypeName = sprintf "<>f__AnonymousType%s%u`%d'" (match x.TupInfo with TupInfo.Const b -> if b then "1000" else "") (uint32 x.Stamp) x.SortedIds.Length + let ilTypeName = sprintf "<>f__AnonymousType%s%u`%d" (match x.TupInfo with TupInfo.Const b -> if b then "1000" else "") (uint32 x.Stamp) x.SortedIds.Length mkILTyRef(x.Assembly.ILScopeRef, ilTypeName) static member NewUnlinked() : AnonRecdTypeInfo = @@ -4088,13 +4030,15 @@ and [] AnonRecdTypeInfo = member x.IsLinked = (match x.SortedIds with null -> true | _ -> false) -and [] TupInfo = +[] +type TupInfo = /// Some constant, e.g. true or false for tupInfo | Const of bool -and - [] - Measure = +/// Represents a unit of measure in the typed AST +[] +type Measure = + /// A variable unit-of-measure | Var of Typar @@ -4119,256 +4063,10 @@ and override x.ToString() = sprintf "%+A" x -and - [] - CcuData = - { /// Holds the filename for the DLL, if any - FileName: string option - - /// Holds the data indicating how this assembly/module is referenced from the code being compiled. - ILScopeRef: ILScopeRef - - /// A unique stamp for this DLL - Stamp: Stamp - - /// The fully qualified assembly reference string to refer to this assembly. This is persisted in quotations - QualifiedName: string option - - /// A hint as to where does the code for the CCU live (e.g what was the tcConfig.implicitIncludeDir at compilation time for this DLL?) - SourceCodeDirectory: string - - /// Indicates that this DLL was compiled using the F# compiler and has F# metadata - IsFSharp: bool - -#if !NO_EXTENSIONTYPING - /// Is the CCu an assembly injected by a type provider - IsProviderGenerated: bool - - /// Triggered when the contents of the CCU are invalidated - InvalidateEvent: IEvent - - /// A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality - /// logic in tastops.fs - ImportProvidedType: Tainted -> TType - -#endif - /// Indicates that this DLL uses pre-F#-4.0 quotation literals somewhere. This is used to implement a restriction on static linking - mutable UsesFSharp20PlusQuotations: bool - - /// A handle to the full specification of the contents of the module contained in this ccu - // NOTE: may contain transient state during typechecking - mutable Contents: ModuleOrNamespace - - /// A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality - /// logic in tastops.fs - TryGetILModuleDef: (unit -> ILModuleDef option) - - /// A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality - /// logic in tastops.fs - MemberSignatureEquality: (TType -> TType -> bool) - - /// The table of .NET CLI type forwarders for this assembly - TypeForwarders: CcuTypeForwarderTable } - - [] - member x.DebugText = x.ToString() - - override x.ToString() = sprintf "CcuData(%A)" x.FileName - -/// Represents a table of .NET CLI type forwarders for an assembly -and CcuTypeForwarderTable = Map> - -and CcuReference = string // ILAssemblyRef - - -/// A relinkable handle to the contents of a compilation unit. Relinking is performed by mutation. -// -/// A compilation unit is, more or less, the new material created in one -/// invocation of the compiler. Due to static linking assemblies may hold more -/// than one compilation unit (i.e. when two assemblies are merged into a compilation -/// the resulting assembly will contain 3 CUs). Compilation units are also created for referenced -/// .NET assemblies. -/// -/// References to items such as type constructors are via -/// cross-compilation-unit thunks, which directly reference the data structures that define -/// these modules. Thus, when saving out values to disk we only wish -/// to save out the "current" part of the term graph. When reading values -/// back in we "fixup" the links to previously referenced modules. -/// -/// All non-local accesses to the data structures are mediated -/// by ccu-thunks. Ultimately, a ccu-thunk is either a (named) element of -/// the data structure, or it is a delayed fixup, i.e. an invalid dangling -/// reference that has not had an appropriate fixup applied. -and - [] - CcuThunk = - { mutable target: CcuData - - /// ccu.orphanfixup is true when a reference is missing in the transitive closure of static references that - /// may potentially be required for the metadata of referenced DLLs. It is set to true if the "loader" - /// used in the F# metadata-deserializer or the .NET metadata reader returns a failing value (e.g. None). - /// Note: When used from Visual Studio, the loader will not automatically chase down transitively referenced DLLs - they - /// must be in the explicit references in the project. - mutable orphanfixup: bool - - name: CcuReference } - - member ccu.Deref = - if isNull (ccu.target :> obj) || ccu.orphanfixup then - raise(UnresolvedReferenceNoRange ccu.name) - ccu.target - - member ccu.IsUnresolvedReference = isNull (ccu.target :> obj) || ccu.orphanfixup - - /// Ensure the ccu is derefable in advance. Supply a path to attach to any resulting error message. - member ccu.EnsureDerefable(requiringPath: string[]) = - if ccu.IsUnresolvedReference then - let path = System.String.Join(".", requiringPath) - raise(UnresolvedPathReferenceNoRange(ccu.name, path)) - - /// Indicates that this DLL uses F# 2.0+ quotation literals somewhere. This is used to implement a restriction on static linking. - member ccu.UsesFSharp20PlusQuotations - with get() = ccu.Deref.UsesFSharp20PlusQuotations - and set v = ccu.Deref.UsesFSharp20PlusQuotations <- v - - member ccu.AssemblyName = ccu.name - - /// Holds the data indicating how this assembly/module is referenced from the code being compiled. - member ccu.ILScopeRef = ccu.Deref.ILScopeRef - - /// A unique stamp for this DLL - member ccu.Stamp = ccu.Deref.Stamp - - /// Holds the filename for the DLL, if any - member ccu.FileName = ccu.Deref.FileName - - /// Try to get the .NET Assembly, if known. May not be present for `IsFSharp` for in-memory cross-project references - member ccu.TryGetILModuleDef() = ccu.Deref.TryGetILModuleDef() - -#if !NO_EXTENSIONTYPING - /// Is the CCu an EST injected assembly - member ccu.IsProviderGenerated = ccu.Deref.IsProviderGenerated - - /// Used to make 'forward' calls into the loader during linking - member ccu.ImportProvidedType ty: TType = ccu.Deref.ImportProvidedType ty - -#endif - - /// The fully qualified assembly reference string to refer to this assembly. This is persisted in quotations - member ccu.QualifiedName = ccu.Deref.QualifiedName - - /// A hint as to where does the code for the CCU live (e.g what was the tcConfig.implicitIncludeDir at compilation time for this DLL?) - member ccu.SourceCodeDirectory = ccu.Deref.SourceCodeDirectory - - /// Indicates that this DLL was compiled using the F# compiler and has F# metadata - member ccu.IsFSharp = ccu.Deref.IsFSharp - - /// A handle to the full specification of the contents of the module contained in this ccu - // NOTE: may contain transient state during typechecking - member ccu.Contents = ccu.Deref.Contents - - /// The table of type forwarders for this assembly - member ccu.TypeForwarders: Map> = ccu.Deref.TypeForwarders - - /// The table of modules and namespaces at the "root" of the assembly - member ccu.RootModulesAndNamespaces = ccu.Contents.ModuleOrNamespaceType.ModuleAndNamespaceDefinitions - - /// The table of type definitions at the "root" of the assembly - member ccu.RootTypeAndExceptionDefinitions = ccu.Contents.ModuleOrNamespaceType.TypeAndExceptionDefinitions - - /// Create a CCU with the given name and contents - static member Create(nm, x) = - { target = x - orphanfixup = false - name = nm } - - /// Create a CCU with the given name but where the contents have not yet been specified - static member CreateDelayed(nm) = - { target = Unchecked.defaultof<_> - orphanfixup = false - name = nm } - - /// Fixup a CCU to have the given contents - member x.Fixup(avail: CcuThunk) = - - match box x.target with - | null -> () - | _ -> - // In the IDE we tolerate a double-fixup of FSHarp.Core when editing the FSharp.Core project itself - if x.AssemblyName <> "FSharp.Core" then - errorR(Failure("internal error: Fixup: the ccu thunk for assembly "+x.AssemblyName+" not delayed!")) - - assert (avail.AssemblyName = x.AssemblyName) - x.target <- - match box avail.target with - | null -> error(Failure("internal error: ccu thunk '"+avail.name+"' not fixed up!")) - | _ -> avail.target - - /// Fixup a CCU to record it as "orphaned", i.e. not available - member x.FixupOrphaned() = - match box x.target with - | null -> x.orphanfixup<-true - | _ -> errorR(Failure("internal error: FixupOrphaned: the ccu thunk for assembly "+x.AssemblyName+" not delayed!")) - - /// Try to resolve a path into the CCU by referencing the .NET/CLI type forwarder table of the CCU - member ccu.TryForward(nlpath: string[], item: string) : EntityRef option = - ccu.EnsureDerefable(nlpath) - let key = nlpath, item - match ccu.TypeForwarders.TryGetValue key with - | true, entity -> Some(entity.Force()) - | _ -> None - //printfn "trying to forward %A::%s from ccu '%s', res = '%A'" p n ccu.AssemblyName res.IsSome - - /// Used to make forward calls into the type/assembly loader when comparing member signatures during linking - member ccu.MemberSignatureEquality(ty1: TType, ty2: TType) = - ccu.Deref.MemberSignatureEquality ty1 ty2 - - [] - member x.DebugText = x.ToString() - - override ccu.ToString() = ccu.AssemblyName - -/// The result of attempting to resolve an assembly name to a full ccu. -/// UnresolvedCcu will contain the name of the assembly that could not be resolved. -and - [] - CcuResolutionResult = - - | ResolvedCcu of CcuThunk - - | UnresolvedCcu of string - - [] - member x.DebugText = x.ToString() - - override x.ToString() = match x with ResolvedCcu ccu -> ccu.ToString() | UnresolvedCcu s -> "unresolved " + s - -/// Represents the information saved in the assembly signature data resource for an F# assembly -and - [] - PickledCcuInfo = - { mspec: ModuleOrNamespace - - compileTimeWorkingDir: string - - usesQuotations: bool } - - [] - member x.DebugText = x.ToString() - - override __.ToString() = "PickledCcuInfo(...)" - - - -//--------------------------------------------------------------------------- -// Attributes -//--------------------------------------------------------------------------- - -and Attribs = Attrib list +type Attribs = Attrib list -and - [] - AttribKind = +[] +type AttribKind = /// Indicates an attribute refers to a type defined in an imported .NET assembly | ILAttrib of ILMethodRef @@ -4383,9 +4081,8 @@ and override x.ToString() = sprintf "%+A" x /// Attrib(kind, unnamedArgs, propVal, appliedToAGetterOrSetter, targetsOpt, range) -and - [] - Attrib = +[] +type Attrib = | Attrib of TyconRef * AttribKind * AttribExpr list * AttribNamedArg list * bool * AttributeTargets option * range @@ -4397,9 +4094,8 @@ and override x.ToString() = "attrib" + x.TyconRef.ToString() /// We keep both source expression and evaluated expression around to help intellisense and signature printing -and - [] - AttribExpr = +[] +type AttribExpr = /// AttribExpr(source, evaluated) | AttribExpr of Expr * Expr @@ -4410,9 +4106,8 @@ and override x.ToString() = sprintf "AttribExpr(...)" /// AttribNamedArg(name, type, isField, value) -and - [] - AttribNamedArg = +[] +type AttribNamedArg = | AttribNamedArg of (string*TType*bool*AttribExpr) [] @@ -4421,8 +4116,8 @@ and override x.ToString() = sprintf "AttribNamedArg(...)" /// Constants in expressions -and [] - Const = +[] +type Const = | Bool of bool | SByte of sbyte | Byte of byte @@ -4442,14 +4137,37 @@ and [] | Unit | Zero // null/zero-bit-pattern + [] + member x.DebugText = x.ToString() + + override c.ToString() = + match c with + | Bool b -> (if b then "true" else "false") + | SByte x -> string x + "y" + | Byte x -> string x + "uy" + | Int16 x -> string x + "s" + | UInt16 x -> string x + "us" + | Int32 x -> string x + | UInt32 x -> string x + "u" + | Int64 x -> string x + "L" + | UInt64 x -> string x + "UL" + | IntPtr x -> string x + "n" + | UIntPtr x -> string x + "un" + | Single x -> string x + "f" + | Double x -> string x + | Char x -> "'" + string x + "'" + | String x -> "\"" + x + "\"" + | Decimal x -> string x + "M" + | Unit -> "()" + | Zero -> "Const.Zero" + /// Decision trees. Pattern matching has been compiled down to /// a decision tree by this point. The right-hand-sides (actions) of /// a decision tree by this point. The right-hand-sides (actions) of /// the decision tree are labelled by integers that are unique for that /// particular tree. -and - [] - DecisionTree = +[] +type DecisionTree = /// TDSwitch(input, cases, default, range) /// @@ -4484,9 +4202,8 @@ and override x.ToString() = sprintf "%+A" x /// Represents a test and a subsequent decision tree -and - [] - DecisionTreeCase = +[] +type DecisionTreeCase = | TCase of DecisionTreeTest * DecisionTree /// Get the discriminator associated with the case @@ -4500,9 +4217,8 @@ and override x.ToString() = sprintf "DecisionTreeCase(...)" -and - [] - DecisionTreeTest = +[] +type DecisionTreeTest = /// Test if the input to a decision tree matches the given union case | UnionCase of UnionCaseRef * TypeInst @@ -4531,6 +4247,9 @@ and /// activePatternInfo -- The extracted info for the active pattern. | ActivePatternCase of Expr * TTypes * (ValRef * TypeInst) option * int * ActivePatternInfo + /// Used in error recovery + | Error of range + // %+A formatting is used, so this is not needed //[] //member x.DebugText = x.ToString() @@ -4538,10 +4257,9 @@ and override x.ToString() = sprintf "%+A" x /// A target of a decision tree. Can be thought of as a little function, though is compiled as a local block. -and - [] - DecisionTreeTarget = - | TTarget of Vals * Expr * SequencePointInfoForTarget +[] +type DecisionTreeTarget = + | TTarget of Val list * Expr * DebugPointForTarget [] member x.DebugText = x.ToString() @@ -4549,13 +4267,12 @@ and override x.ToString() = sprintf "DecisionTreeTarget(...)" /// A collection of simultaneous bindings -and Bindings = Binding list +type Bindings = Binding list /// A binding of a variable to an expression, as in a `let` binding or similar -and - [] - Binding = - | TBind of Val * Expr * SequencePointInfoForBinding +[] +type Binding = + | TBind of Val * Expr * DebugPointForBinding /// The value being bound member x.Var = (let (TBind(v, _, _)) = x in v) @@ -4564,18 +4281,17 @@ and member x.Expr = (let (TBind(_, e, _)) = x in e) /// The information about whether to emit a sequence point for the binding - member x.SequencePointInfo = (let (TBind(_, _, sp)) = x in sp) + member x.DebugPoint = (let (TBind(_, _, sp)) = x in sp) [] member x.DebugText = x.ToString() - override x.ToString() = sprintf "TBind(%s, ...)" x.Var.CompiledName + override x.ToString() = sprintf "TBind(%s, ...)" (x.Var.CompiledName None) /// Represents a reference to an active pattern element. The /// integer indicates which choice in the target set is being selected by this item. -and - [] - ActivePatternElemRef = +[] +type ActivePatternElemRef = | APElemRef of ActivePatternInfo * ValRef * int /// Get the full information about the active pattern being referred to @@ -4594,9 +4310,8 @@ and /// Records the "extra information" for a value compiled as a method (rather /// than a closure or a local), including argument names, attributes etc. -and - [] - ValReprInfo = +[] +type ValReprInfo = /// ValReprInfo (numTypars, args, result) | ValReprInfo of TyparReprInfo list * ArgReprInfo list list * ArgReprInfo @@ -4626,9 +4341,9 @@ and let rec loop (args: ArgReprInfo list list) acc = match args with | [] -> acc - | []::t -> loop t acc - | [_]::t -> loop t (acc+1) - | (_::_::h)::t -> loop t (acc + h.Length + 2) + | [] :: t -> loop t acc + | [_] :: t -> loop t (acc+1) + | (_ :: _ :: h) :: t -> loop t (acc + h.Length + 2) loop args 0 [] @@ -4638,15 +4353,17 @@ and /// Records the "extra information" for an argument compiled as a real /// method argument, specifically the argument name and attributes. -and - [] - ArgReprInfo = +[] +type ArgReprInfo = { + /// The attributes for the argument // MUTABILITY: used when propagating signature attributes into the implementation. mutable Attribs: Attribs + /// The name for the argument at this position, if any // MUTABILITY: used when propagating names of parameters from signature into the implementation. - mutable Name: Ident option } + mutable Name: Ident option + } [] member x.DebugText = x.ToString() @@ -4657,105 +4374,179 @@ and /// compiled as "real" IL type parameters, specifically for values with /// ValReprInfo. Any information here is propagated from signature through /// to the compiled code. -and TyparReprInfo = TyparReprInfo of Ident * TyparKind +type TyparReprInfo = TyparReprInfo of Ident * TyparKind -and Typars = Typar list +type Typars = Typar list -and Exprs = Expr list +type Exprs = Expr list -and Vals = Val list +type Vals = Val list -/// The big type of expressions. -and - [] - Expr = +/// Represents an expression in the typed abstract syntax +[] +type Expr = /// A constant expression. - | Const of Const * range * TType + | Const of + value: Const * + range: range * + constType: TType /// Reference a value. The flag is only relevant if the value is an object model member /// and indicates base calls and special uses of object constructors. - | Val of ValRef * ValUseFlag * range + | Val of + valRef: ValRef * + flags: ValUseFlag * + range: range /// Sequence expressions, used for "a;b", "let a = e in b;a" and "a then b" (the last an OO constructor). - | Sequential of Expr * Expr * SequentialOpKind * SequencePointInfoForSeq * range + | Sequential of + expr1: Expr * + expr2: Expr * + kind: SequentialOpKind * + debugPoint: DebugPointAtSequential * + range: range /// Lambda expressions. /// Why multiple vspecs? A Expr.Lambda taking multiple arguments really accepts a tuple. /// But it is in a convenient form to be compile accepting multiple /// arguments, e.g. if compiled as a toplevel static method. - | Lambda of Unique * Val option * Val option * Val list * Expr * range * TType + | Lambda of + unique: Unique * + ctorThisValOpt: Val option * + baseValOpt: Val option * + valParams: Val list * + bodyExpr: Expr * + range: range * + overallType: TType /// Type lambdas. These are used for the r.h.s. of polymorphic 'let' bindings and /// for expressions that implement first-class polymorphic values. - | TyLambda of Unique * Typars * Expr * range * TType + | TyLambda of + unique: Unique * + typeParams: Typars * + bodyExpr: Expr * + range: range * + overallType: TType /// Applications. /// Applications combine type and term applications, and are normalized so /// that sequential applications are combined, so "(f x y)" becomes "f [[x];[y]]". /// The type attached to the function is the formal function type, used to ensure we don't build application /// nodes that over-apply when instantiating at function types. - | App of Expr * TType * TypeInst * Exprs * range + | App of + funcExpr: Expr * + formalType: TType * + typeArgs: TypeInst * + args: Exprs * + range: range /// Bind a recursive set of values. - | LetRec of Bindings * Expr * range * FreeVarsCache + | LetRec of + bindings: Bindings * + bodyExpr: Expr * + range: range * + frees: FreeVarsCache /// Bind a value. - | Let of Binding * Expr * range * FreeVarsCache + | Let of + binding: Binding * + bodyExpr: Expr * + range: range * + frees: FreeVarsCache // Object expressions: A closure that implements an interface or a base type. // The base object type might be a delegate type. | Obj of - unique: Unique * - objTy: TType * (* <-- NOTE: specifies type parameters for base type *) - baseVal: Val option * - ctorCall: Expr * - overrides: ObjExprMethod list * - interfaceImpls: (TType * ObjExprMethod list) list * - range: range + unique: Unique * + objTy: TType * (* <-- NOTE: specifies type parameters for base type *) + baseVal: Val option * + ctorCall: Expr * + overrides: ObjExprMethod list * + interfaceImpls: (TType * ObjExprMethod list) list * + range: range /// Matches are a more complicated form of "let" with multiple possible destinations /// and possibly multiple ways to get to each destination. - /// The first mark is that of the expression being matched, which is used - /// as the mark for all the decision making and binding that happens during the match. - | Match of SequencePointInfoForBinding * range * DecisionTree * DecisionTreeTarget array * range * TType + /// The first range is that of the expression being matched, which is used + /// as the range for all the decision making and binding that happens during the decision tree + /// execution. + | Match of + debugPoint: DebugPointForBinding * + inputRange: range * + decision: DecisionTree * + targets: DecisionTreeTarget array * + fullRange: range * + exprType: TType /// If we statically know some information then in many cases we can use a more optimized expression /// This is primarily used by terms in the standard library, particularly those implementing overloaded /// operators. - | StaticOptimization of StaticOptimization list * Expr * Expr * range + | StaticOptimization of + conditions: StaticOptimization list * + expr: Expr * + alternativeExpr: Expr * + range: range /// An intrinsic applied to some (strictly evaluated) arguments /// A few of intrinsics (TOp_try, TOp.While, TOp.For) expect arguments kept in a normal form involving lambdas - | Op of TOp * TypeInst * Exprs * range + | Op of + op: TOp * + typeArgs: TypeInst * + args: Exprs * + range: range - /// Expr.Quote(quotedExpr, (referencedTypes, spliceTypes, spliceExprs, data) option ref, isFromQueryExpression, fullRange, quotedType) - /// /// Indicates the expression is a quoted expression tree. /// // MUTABILITY: this use of mutability is awkward and perhaps should be removed - | Quote of Expr * (ILTypeRef list * TTypes * Exprs * ExprData) option ref * bool * range * TType + | Quote of + quotedExpr: Expr * + quotationInfo: (ILTypeRef list * TTypes * Exprs * ExprData) option ref * + isFromQueryExpression: bool * + range: range * + quotedType: TType - /// Typechecking residue: Indicates a free choice of typars that arises due to + /// Indicates a free choice of typars that arises due to /// minimization of polymorphism at let-rec bindings. These are /// resolved to a concrete instantiation on subsequent rewrites. - | TyChoose of Typars * Expr * range + | TyChoose of + typeParams: Typars * + bodyExpr: Expr * + range: range - /// Typechecking residue: A Expr.Link occurs for every use of a recursively bound variable. While type-checking + /// An instance of a link node occurs for every use of a recursively bound variable. When type-checking /// the recursive bindings a dummy expression is stored in the mutable reference cell. /// After type checking the bindings this is replaced by a use of the variable, perhaps at an /// appropriate type instantiation. These are immediately eliminated on subsequent rewrites. | Link of Expr ref - // Prefer to use the default formatting of this union type - //[] - //member x.DebugText = x.ToString() - // - //override __.ToString() = "Expr(...)" - -and - [] - TOp = + [] + member expr.DebugText = expr.ToDebugString(3) + + override expr.ToString() = expr.ToDebugString(3) + + member expr.ToDebugString(depth: int) = + if depth = 0 then ".." else + let depth = depth - 1 + match expr with + | Const (c, _, _) -> c.ToString() + | Val (v, _, _) -> v.LogicalName + | Sequential (e1, e2, _, _, _) -> "Sequential(" + e1.ToDebugString(depth) + ", " + e2.ToDebugString(depth) + ")" + | Lambda (_, _, _, vs, body, _, _) -> sprintf "Lambda(%+A, " vs + body.ToDebugString(depth) + ")" + | TyLambda (_, tps, body, _, _) -> sprintf "TyLambda(%+A, " tps + body.ToDebugString(depth) + ")" + | App (f, _, _, args, _) -> "App(" + f.ToDebugString(depth) + ", [" + String.concat ", " (args |> List.map (fun e -> e.ToDebugString(depth))) + "])" + | LetRec _ -> "LetRec(..)" + | Let (bind, body, _, _) -> "Let(" + bind.Var.DisplayName + ", " + bind.Expr.ToDebugString(depth) + ", " + body.ToDebugString(depth) + ")" + | Obj (_, _objTy, _, _, _, _, _) -> "Obj(..)" + | Match (_, _, _dt, _tgs, _, _) -> "Match(..)" + | StaticOptimization (_, _, _, _) -> "StaticOptimization(..)" + | Op (op, _, args, _) -> "Op(" + op.ToString() + ", " + String.concat ", " (args |> List.map (fun e -> e.ToDebugString(depth))) + ")" + | Quote _ -> "Quote(..)" + | TyChoose _ -> "TyChoose(..)" + | Link e -> "Link(" + e.Value.ToDebugString(depth) + ")" + +[] +type TOp = /// An operation representing the creation of a union value of the particular union case | UnionCase of UnionCaseRef @@ -4782,16 +4573,16 @@ and | UInt16s of uint16[] /// An operation representing a lambda-encoded while loop. The special while loop marker is used to mark compilations of 'foreach' expressions - | While of SequencePointInfoForWhileLoop * SpecialWhileLoopMarker + | While of DebugPointAtWhile * SpecialWhileLoopMarker /// An operation representing a lambda-encoded for loop - | For of SequencePointInfoForForLoop * ForLoopStyle (* count up or down? *) + | For of DebugPointAtFor * ForLoopStyle (* count up or down? *) /// An operation representing a lambda-encoded try/catch - | TryCatch of SequencePointInfoForTry * SequencePointInfoForWith + | TryCatch of DebugPointAtTry * DebugPointAtWith /// An operation representing a lambda-encoded try/finally - | TryFinally of SequencePointInfoForTry * SequencePointInfoForFinally + | TryFinally of DebugPointAtTry * DebugPointAtFinally /// Construct a record or object-model value. The ValRef is for self-referential class constructors, otherwise /// it indicates that we're in a constructor and the purpose of the expression is to @@ -4855,7 +4646,7 @@ and | Label of ILCodeLabel /// Pseudo method calls. This is used for overloaded operations like op_Addition. - | TraitCall of TraitConstraintInfo + | TraitCall of TraitConstraintInfo /// Operation nodes representing C-style operations on byrefs and mutable vals (l-values) | LValueOp of LValueOperation * ValRef @@ -4871,35 +4662,70 @@ and /// retTy -- the types of pushed values, if any | ILCall of bool * bool * bool * bool * ValUseFlag * bool * bool * ILMethodRef * TypeInst * TypeInst * TTypes - // Prefer to use the default formatting of this union type - //[] - //member x.DebugText = x.ToString() - // - //override __.ToString() = "TOp(...)" - -/// Indicates the kind of record construction operation. -and RecordConstructionInfo = - /// We're in an explicit constructor. The purpose of the record expression is to - /// fill in the fields of a pre-created but uninitialized object - | RecdExprIsObjInit - - /// Normal record construction - | RecdExpr + [] + member x.DebugText = x.ToString() -/// If this is Some(ty) then it indicates that a .NET 2.0 constrained call is required, with the given type as the + override op.ToString() = + match op with + | UnionCase ucref -> "UnionCase(" + ucref.CaseName + ")" + | ExnConstr ecref -> "ExnConstr(" + ecref.LogicalName + ")" + | Tuple _tupinfo -> "Tuple" + | AnonRecd _anonInfo -> "AnonRecd(..)" + | AnonRecdGet _ -> "AnonRecdGet(..)" + | Array -> "NewArray" + | Bytes _ -> "Bytes(..)" + | UInt16s _ -> "UInt16s(..)" + | While _ -> "While" + | For _ -> "For" + | TryCatch _ -> "TryCatch" + | TryFinally _ -> "TryFinally" + | Recd (_, tcref) -> "Recd(" + tcref.LogicalName + ")" + | ValFieldSet rfref -> "ValFieldSet(" + rfref.FieldName + ")" + | ValFieldGet rfref -> "ValFieldGet(" + rfref.FieldName + ")" + | ValFieldGetAddr (rfref, _) -> "ValFieldGetAddr(" + rfref.FieldName + ",..)" + | UnionCaseTagGet tcref -> "UnionCaseTagGet(" + tcref.LogicalName + ")" + | UnionCaseProof ucref -> "UnionCaseProof(" + ucref.CaseName + ")" + | UnionCaseFieldGet (ucref, _) -> "UnionCaseFieldGet(" + ucref.CaseName + ",..)" + | UnionCaseFieldGetAddr (ucref, _, _) -> "UnionCaseFieldGetAddr(" + ucref.CaseName + ",..)" + | UnionCaseFieldSet (ucref, _) -> "UnionCaseFieldSet(" + ucref.CaseName + ",..)" + | ExnFieldGet (tcref, _) -> "ExnFieldGet(" + tcref.LogicalName + ",..)" + | ExnFieldSet (tcref, _) -> "ExnFieldSet(" + tcref.LogicalName + ",..)" + | TupleFieldGet _ -> "TupleFieldGet(..)" + | ILAsm _ -> "ILAsm(..)" + | RefAddrGet _ -> "RefAddrGet(..)" + | Coerce -> "Coerce" + | Reraise -> "Reraise" + | Return -> "Return" + | Goto n -> "Goto(" + string n + ")" + | Label n -> "Label(" + string n + ")" + | TraitCall info -> "TraitCall(" + info.MemberName + ")" + | LValueOp (op, vref) -> sprintf "%+A(%s)" op vref.LogicalName + | ILCall (_,_,_,_,_,_,_,m,_,_,_) -> "ILCall(" + m.ToString() + ",..)" + +/// Represents the kind of record construction operation. +type RecordConstructionInfo = + + /// We're in an explicit constructor. The purpose of the record expression is to + /// fill in the fields of a pre-created but uninitialized object + | RecdExprIsObjInit + + /// Normal record construction + | RecdExpr + +/// If this is Some ty then it indicates that a .NET 2.0 constrained call is required, with the given type as the /// static type of the object argument. -and ConstrainedCallInfo = TType option +type ConstrainedCallInfo = TType option -/// Indicates the kind of looping operation. -and SpecialWhileLoopMarker = +/// Represents the kind of looping operation. +type SpecialWhileLoopMarker = | NoSpecialWhileLoopMarker /// Marks the compiled form of a 'for ... in ... do ' expression | WhileLoopForCompiledForEachExprMarker -/// Indicates the kind of looping operation. -and ForLoopStyle = +/// Represents the kind of looping operation. +type ForLoopStyle = /// Evaluate start and end once, loop up | FSharpForLoopUp @@ -4910,7 +4736,8 @@ and ForLoopStyle = | CSharpForLoopUp /// Indicates what kind of pointer operation this is. -and LValueOperation = +type LValueOperation = + /// In C syntax this is: &localv | LAddrOf of readonly: bool @@ -4923,8 +4750,8 @@ and LValueOperation = /// In C syntax this is: *localv_ptr = e | LByrefSet -/// Indicates the kind of sequential operation, i.e. "normal" or "to a before returning b" -and SequentialOpKind = +/// Represents the kind of sequential operation, i.e. "normal" or "to a before returning b" +type SequentialOpKind = /// a ; b | NormalSeq @@ -4932,7 +4759,8 @@ and SequentialOpKind = | ThenDoSeq /// Indicates how a value, function or member is being used at a particular usage point. -and ValUseFlag = +type ValUseFlag = + /// Indicates a use of a value represents a call to a method that may require /// a .NET 2.0 constrained call. A constrained call is only used for calls where // the object argument is a value type or generic type, and the call is to a method @@ -4951,19 +4779,20 @@ and ValUseFlag = /// A call to a base method, e.g. 'base.OnPaint(args)' | VSlotDirectCall -/// Indicates the kind of an F# core library static optimization construct -and StaticOptimization = +/// Represents the kind of an F# core library static optimization construct +type StaticOptimization = + /// Indicates the static optimization applies when a type equality holds | TTyconEqualsTycon of TType * TType + /// Indicates the static optimization applies when a type is a struct | TTyconIsStruct of TType /// A representation of a method in an object expression. /// /// TObjExprMethod(slotsig, attribs, methTyparsOfOverridingMethod, methodParams, methodBodyExpr, m) -and - [] - ObjExprMethod = +[] +type ObjExprMethod = | TObjExprMethod of SlotSig * Attribs * Typars * Val list list * Expr * range @@ -4977,22 +4806,32 @@ and /// Represents an abstract method slot, or delegate signature. /// /// TSlotSig(methodName, declaringType, declaringTypeParameters, methodTypeParameters, slotParameters, returnTy) -and - [] - SlotSig = - - | TSlotSig of string * TType * Typars * Typars * SlotParam list list * TType option - +[] +type SlotSig = + | TSlotSig of + methodName: string * + implementedType: TType * + classTypars: Typars * + methodTypars: Typars * + formalParams: SlotParam list list * + formalReturn: TType option + + /// The name of the method member ss.Name = let (TSlotSig(nm, _, _, _, _, _)) = ss in nm + /// The (instantiated) type which the slot is logically a part of member ss.ImplementedType = let (TSlotSig(_, ty, _, _, _, _)) = ss in ty + /// The class type parameters of the slot member ss.ClassTypars = let (TSlotSig(_, _, ctps, _, _, _)) = ss in ctps + /// The method type parameters of the slot member ss.MethodTypars = let (TSlotSig(_, _, _, mtps, _, _)) = ss in mtps + /// The formal parameters of the slot (regardless of the type or method instantiation) member ss.FormalParams = let (TSlotSig(_, _, _, _, ps, _)) = ss in ps + /// The formal return type of the slot (regardless of the type or method instantiation) member ss.FormalReturnType = let (TSlotSig(_, _, _, _, _, rt)) = ss in rt [] @@ -5003,10 +4842,15 @@ and /// Represents a parameter to an abstract method slot. /// /// TSlotParam(nm, ty, inFlag, outFlag, optionalFlag, attribs) -and - [] - SlotParam = - | TSlotParam of string option * TType * bool (* in *) * bool (* out *) * bool (* optional *) * Attribs +[] +type SlotParam = + | TSlotParam of + paramName: string option * + paramType: TType * + isIn: bool * + isOut: bool * + isOptional: bool * + attributes: Attribs member x.Type = let (TSlotParam(_, ty, _, _, _, _)) = x in ty @@ -5018,13 +4862,12 @@ and /// A type for a module-or-namespace-fragment and the actual definition of the module-or-namespace-fragment /// The first ModuleOrNamespaceType is the signature and is a binder. However the bindings are not used in the ModuleOrNamespaceExpr: it is only referenced from the 'outside' /// is for use by FCS only to report the "hidden" contents of the assembly prior to applying the signature. -and - [] - ModuleOrNamespaceExprWithSig = +[] +type ModuleOrNamespaceExprWithSig = | ModuleOrNamespaceExprWithSig of - ModuleOrNamespaceType - * ModuleOrNamespaceExpr - * range + moduleType: ModuleOrNamespaceType * + contents: ModuleOrNamespaceExpr * + range: range member x.Type = let (ModuleOrNamespaceExprWithSig(mtyp, _, _)) = x in mtyp @@ -5034,9 +4877,8 @@ and override x.ToString() = "ModuleOrNamespaceExprWithSig(...)" /// The contents of a module-or-namespace-fragment definition -and - [] - ModuleOrNamespaceExpr = +[] +type ModuleOrNamespaceExpr = /// Indicates the module is a module with a signature | TMAbstract of ModuleOrNamespaceExprWithSig @@ -5059,9 +4901,8 @@ and override x.ToString() = sprintf "%+A" x /// A named module-or-namespace-fragment definition -and - [] - ModuleOrNamespaceBinding = +[] +type ModuleOrNamespaceBinding = | Binding of Binding @@ -5079,22 +4920,19 @@ and /// Represents a complete typechecked implementation file, including its typechecked signature if any. /// -/// TImplFile(qualifiedNameOfFile, pragmas, implementationExpressionWithSignature, hasExplicitEntryPoint, isScript) -and - [] - TypedImplFile = +/// TImplFile (qualifiedNameOfFile, pragmas, implementationExpressionWithSignature, hasExplicitEntryPoint, isScript) +[] +type TypedImplFile = | TImplFile of QualifiedNameOfFile * ScopedPragma list * ModuleOrNamespaceExprWithSig * bool * bool * StampMap [] member x.DebugText = x.ToString() - override x.ToString() = "TImplFile(...)" + override x.ToString() = "TImplFile (...)" /// Represents a complete typechecked assembly, made up of multiple implementation files. -/// -and - [] - TypedAssemblyAfterOptimization = +[] +type TypedAssemblyAfterOptimization = | TypedAssemblyAfterOptimization of (TypedImplFile * (* optimizeDuringCodeGen: *) (Expr -> Expr)) list [] @@ -5102,33 +4940,275 @@ and override x.ToString() = "TypedAssemblyAfterOptimization(...)" -//--------------------------------------------------------------------------- -// Freevars. Computed and cached by later phases (never computed type checking). Cached in terms. Not pickled. -//--------------------------------------------------------------------------- +[] +type CcuData = + { + /// Holds the filename for the DLL, if any + FileName: string option + + /// Holds the data indicating how this assembly/module is referenced from the code being compiled. + ILScopeRef: ILScopeRef + + /// A unique stamp for this DLL + Stamp: Stamp + + /// The fully qualified assembly reference string to refer to this assembly. This is persisted in quotations + QualifiedName: string option + + /// A hint as to where does the code for the CCU live (e.g what was the tcConfig.implicitIncludeDir at compilation time for this DLL?) + SourceCodeDirectory: string + + /// Indicates that this DLL was compiled using the F# compiler and has F# metadata + IsFSharp: bool + +#if !NO_EXTENSIONTYPING + /// Is the CCu an assembly injected by a type provider + IsProviderGenerated: bool + + /// Triggered when the contents of the CCU are invalidated + InvalidateEvent: IEvent + + /// A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality + /// logic in tastops.fs + ImportProvidedType: Tainted -> TType + +#endif + /// Indicates that this DLL uses pre-F#-4.0 quotation literals somewhere. This is used to implement a restriction on static linking + mutable UsesFSharp20PlusQuotations: bool + + /// A handle to the full specification of the contents of the module contained in this ccu + // NOTE: may contain transient state during typechecking + mutable Contents: ModuleOrNamespace + + /// A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality + /// logic in tastops.fs + TryGetILModuleDef: (unit -> ILModuleDef option) + + /// A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality + /// logic in tastops.fs + MemberSignatureEquality: (TType -> TType -> bool) + + /// The table of .NET CLI type forwarders for this assembly + TypeForwarders: CcuTypeForwarderTable } + + [] + member x.DebugText = x.ToString() + + override x.ToString() = sprintf "CcuData(%A)" x.FileName + +/// Represents a table of .NET CLI type forwarders for an assembly +type CcuTypeForwarderTable = Map> + +type CcuReference = string // ILAssemblyRef + +/// A relinkable handle to the contents of a compilation unit. Relinking is performed by mutation. +// +/// A compilation unit is, more or less, the new material created in one +/// invocation of the compiler. Due to static linking assemblies may hold more +/// than one compilation unit (i.e. when two assemblies are merged into a compilation +/// the resulting assembly will contain 3 CUs). Compilation units are also created for referenced +/// .NET assemblies. +/// +/// References to items such as type constructors are via +/// cross-compilation-unit thunks, which directly reference the data structures that define +/// these modules. Thus, when saving out values to disk we only wish +/// to save out the "current" part of the term graph. When reading values +/// back in we "fixup" the links to previously referenced modules. +/// +/// All non-local accesses to the data structures are mediated +/// by ccu-thunks. Ultimately, a ccu-thunk is either a (named) element of +/// the data structure, or it is a delayed fixup, i.e. an invalid dangling +/// reference that has not had an appropriate fixup applied. +[] +type CcuThunk = + + { + mutable target: CcuData + + /// ccu.orphanfixup is true when a reference is missing in the transitive closure of static references that + /// may potentially be required for the metadata of referenced DLLs. It is set to true if the "loader" + /// used in the F# metadata-deserializer or the .NET metadata reader returns a failing value (e.g. None). + /// Note: When used from Visual Studio, the loader will not automatically chase down transitively referenced DLLs - they + /// must be in the explicit references in the project. + mutable orphanfixup: bool + + name: CcuReference + } + + /// Dereference the asssembly reference + member ccu.Deref = + if isNull (ccu.target :> obj) || ccu.orphanfixup then + raise(UnresolvedReferenceNoRange ccu.name) + ccu.target + + /// Indicates if this assembly reference is unresolved + member ccu.IsUnresolvedReference = isNull (ccu.target :> obj) || ccu.orphanfixup + + /// Ensure the ccu is derefable in advance. Supply a path to attach to any resulting error message. + member ccu.EnsureDerefable(requiringPath: string[]) = + if ccu.IsUnresolvedReference then + let path = System.String.Join(".", requiringPath) + raise(UnresolvedPathReferenceNoRange(ccu.name, path)) + + /// Indicates that this DLL uses F# 2.0+ quotation literals somewhere. This is used to implement a restriction on static linking. + member ccu.UsesFSharp20PlusQuotations + with get() = ccu.Deref.UsesFSharp20PlusQuotations + and set v = ccu.Deref.UsesFSharp20PlusQuotations <- v + + /// The short name of the asssembly being referenced + member ccu.AssemblyName = ccu.name + + /// Holds the data indicating how this assembly/module is referenced from the code being compiled. + member ccu.ILScopeRef = ccu.Deref.ILScopeRef + + /// A unique stamp for this assembly + member ccu.Stamp = ccu.Deref.Stamp + + /// Holds the filename for the assembly, if any + member ccu.FileName = ccu.Deref.FileName + + /// Try to get the .NET Assembly, if known. May not be present for `IsFSharp` for + /// in-memory cross-project references + member ccu.TryGetILModuleDef() = ccu.Deref.TryGetILModuleDef() + +#if !NO_EXTENSIONTYPING + /// Is this a provider-injected assembly + member ccu.IsProviderGenerated = ccu.Deref.IsProviderGenerated + + /// Used to make 'forward' calls into the loader during linking + member ccu.ImportProvidedType ty: TType = ccu.Deref.ImportProvidedType ty +#endif + + /// The fully qualified assembly reference string to refer to this assembly. This is persisted in quotations + member ccu.QualifiedName = ccu.Deref.QualifiedName + + /// A hint as to where does the code for the CCU live (e.g what was the tcConfig.implicitIncludeDir at compilation time for this DLL?) + member ccu.SourceCodeDirectory = ccu.Deref.SourceCodeDirectory + + /// Indicates that this DLL was compiled using the F# compiler and has F# metadata + member ccu.IsFSharp = ccu.Deref.IsFSharp + + /// A handle to the full specification of the contents of the module contained in this ccu + // NOTE: may contain transient state during typechecking + member ccu.Contents = ccu.Deref.Contents + + /// The table of type forwarders for this assembly + member ccu.TypeForwarders: Map> = ccu.Deref.TypeForwarders + + /// The table of modules and namespaces at the "root" of the assembly + member ccu.RootModulesAndNamespaces = ccu.Contents.ModuleOrNamespaceType.ModuleAndNamespaceDefinitions + + /// The table of type definitions at the "root" of the assembly + member ccu.RootTypeAndExceptionDefinitions = ccu.Contents.ModuleOrNamespaceType.TypeAndExceptionDefinitions + + /// Create a CCU with the given name and contents + static member Create(nm, x) = + { target = x + orphanfixup = false + name = nm } + + /// Create a CCU with the given name but where the contents have not yet been specified + static member CreateDelayed nm = + { target = Unchecked.defaultof<_> + orphanfixup = false + name = nm } + + /// Fixup a CCU to have the given contents + member x.Fixup(avail: CcuThunk) = + + match box x.target with + | null -> () + | _ -> + // In the IDE we tolerate a double-fixup of FSHarp.Core when editing the FSharp.Core project itself + if x.AssemblyName <> "FSharp.Core" then + errorR(Failure("internal error: Fixup: the ccu thunk for assembly "+x.AssemblyName+" not delayed!")) + + assert (avail.AssemblyName = x.AssemblyName) + x.target <- + match box avail.target with + | null -> error(Failure("internal error: ccu thunk '"+avail.name+"' not fixed up!")) + | _ -> avail.target + + /// Fixup a CCU to record it as "orphaned", i.e. not available + member x.FixupOrphaned() = + match box x.target with + | null -> x.orphanfixup<-true + | _ -> errorR(Failure("internal error: FixupOrphaned: the ccu thunk for assembly "+x.AssemblyName+" not delayed!")) + + /// Try to resolve a path into the CCU by referencing the .NET/CLI type forwarder table of the CCU + member ccu.TryForward(nlpath: string[], item: string) : EntityRef option = + ccu.EnsureDerefable nlpath + let key = nlpath, item + match ccu.TypeForwarders.TryGetValue key with + | true, entity -> Some(entity.Force()) + | _ -> None + + /// Used to make forward calls into the type/assembly loader when comparing member signatures during linking + member ccu.MemberSignatureEquality(ty1: TType, ty2: TType) = + ccu.Deref.MemberSignatureEquality ty1 ty2 + + [] + member x.DebugText = x.ToString() + + override ccu.ToString() = ccu.AssemblyName + +/// The result of attempting to resolve an assembly name to a full ccu. +/// UnresolvedCcu will contain the name of the assembly that could not be resolved. +[] +type CcuResolutionResult = + + | ResolvedCcu of CcuThunk + + | UnresolvedCcu of string + + [] + member x.DebugText = x.ToString() + + override x.ToString() = match x with ResolvedCcu ccu -> ccu.ToString() | UnresolvedCcu s -> "unresolved " + s + +/// Represents the information saved in the assembly signature data resource for an F# assembly +[] +type PickledCcuInfo = + { + mspec: ModuleOrNamespace + + compileTimeWorkingDir: string + + usesQuotations: bool + } + + [] + member x.DebugText = x.ToString() + + override __.ToString() = "PickledCcuInfo(...)" + -/// Represents a set of free local values. -and FreeLocals = Zset +/// Represents a set of free local values. Computed and cached by later phases +/// (never cached type checking). Cached in expressions. Not pickled. +type FreeLocals = Zset -/// Represents a set of free type parameters -and FreeTypars = Zset +/// Represents a set of free type parameters. Computed and cached by later phases +/// (never cached type checking). Cached in expressions. Not pickled. +type FreeTypars = Zset /// Represents a set of 'free' named type definitions. Used to collect the named type definitions referred to -/// from a type or expression. -and FreeTycons = Zset +/// from a type or expression. Computed and cached by later phases (never cached type checking). Cached +/// in expressions. Not pickled. +type FreeTycons = Zset /// Represents a set of 'free' record field definitions. Used to collect the record field definitions referred to /// from an expression. -and FreeRecdFields = Zset +type FreeRecdFields = Zset /// Represents a set of 'free' union cases. Used to collect the union cases referred to from an expression. -and FreeUnionCases = Zset +type FreeUnionCases = Zset /// Represents a set of 'free' type-related elements, including named types, trait solutions, union cases and /// record fields. -and - [] - FreeTyvars = - { /// The summary of locally defined type definitions used in the expression. These may be made private by a signature +[] +type FreeTyvars = + { + /// The summary of locally defined type definitions used in the expression. These may be made private by a signature /// and we have to check various conditions associated with that. FreeTycons: FreeTycons @@ -5137,7 +5217,8 @@ and /// The summary of type parameters used in the expression. These may not escape the enclosing generic construct /// and we have to check various conditions associated with that. - FreeTypars: FreeTypars } + FreeTypars: FreeTypars + } [] member x.DebugText = x.ToString() @@ -5145,13 +5226,13 @@ and override x.ToString() = "FreeTyvars(...)" /// Represents an amortized computation of the free variables in an expression -and FreeVarsCache = FreeVars cache +type FreeVarsCache = FreeVars cache /// Represents the set of free variables in an expression -and - [] - FreeVars = - { /// The summary of locally defined variables used in the expression. These may be hidden at let bindings etc. +[] +type FreeVars = + { + /// The summary of locally defined variables used in the expression. These may be hidden at let bindings etc. /// or made private by a signature or marked 'internal' or 'private', and we have to check various conditions associated with that. FreeLocals: FreeLocals @@ -5183,725 +5264,333 @@ and override x.ToString() = "FreeVars(...)" -/// Specifies the compiled representations of type and exception definitions. Basically -/// just an ILTypeRef. Computed and cached by later phases. Stored in -/// type and exception definitions. Not pickled. Store an optional ILType object for -/// non-generic types. -and - [] - CompiledTypeRepr = - - /// An AbstractIL type representation that is just the name of a type. - /// - /// CompiledTypeRepr.ILAsmNamed (ilTypeRef, ilBoxity, ilTypeOpt) - /// - /// The ilTypeOpt is present for non-generic types. It is an ILType corresponding to the first two elements of the case. This - /// prevents reallocation of the ILType each time we need to generate it. For generic types, it is None. - | ILAsmNamed of - ILTypeRef * - ILBoxity * - ILType option - - /// An AbstractIL type representation that may include type variables - // This case is only used for types defined in the F# library by their translation to ILASM types, e.g. - // type ``[]``<'T> = (# "!0[]" #) - // type ``[, ]``<'T> = (# "!0[0 ..., 0 ...]" #) - // type ``[, , ]``<'T> = (# "!0[0 ..., 0 ..., 0 ...]" #) - // type byref<'T> = (# "!0&" #) - // type nativeptr<'T when 'T: unmanaged> = (# "native int" #) - // type ilsigptr<'T> = (# "!0*" #) - | ILAsmOpen of ILType - - [] - member x.DebugText = x.ToString() - - override x.ToString() = "CompiledTypeRepr(...)" - -//--------------------------------------------------------------------------- -// Basic properties on type definitions -//--------------------------------------------------------------------------- - - -/// Metadata on values (names of arguments etc. -[] -module ValReprInfo = - - let unnamedTopArg1: ArgReprInfo = { Attribs=[]; Name=None } - - let unnamedTopArg = [unnamedTopArg1] - - let unitArgData: ArgReprInfo list list = [[]] - - let unnamedRetVal: ArgReprInfo = { Attribs = []; Name=None } - - let selfMetadata = unnamedTopArg - - let emptyValData = ValReprInfo([], [], unnamedRetVal) - - let InferTyparInfo (tps: Typar list) = tps |> List.map (fun tp -> TyparReprInfo(tp.Id, tp.Kind)) - - let InferArgReprInfo (v: Val) : ArgReprInfo = { Attribs = []; Name= Some v.Id } - - let InferArgReprInfos (vs: Val list list) = ValReprInfo([], List.mapSquared InferArgReprInfo vs, unnamedRetVal) - - let HasNoArgs (ValReprInfo(n, args, _)) = n.IsEmpty && args.IsEmpty - -//--------------------------------------------------------------------------- -// Basic properties via functions (old style) -//--------------------------------------------------------------------------- - -let typeOfVal (v: Val) = v.Type -let typesOfVals (v: Val list) = v |> List.map (fun v -> v.Type) -let nameOfVal (v: Val) = v.LogicalName -let arityOfVal (v: Val) = (match v.ValReprInfo with None -> ValReprInfo.emptyValData | Some arities -> arities) - -let tupInfoRef = TupInfo.Const false -let tupInfoStruct = TupInfo.Const true -let mkTupInfo b = if b then tupInfoStruct else tupInfoRef -let structnessDefault = false -let mkRawRefTupleTy tys = TType_tuple (tupInfoRef, tys) -let mkRawStructTupleTy tys = TType_tuple (tupInfoStruct, tys) - -//--------------------------------------------------------------------------- -// Aggregate operations to help transform the components that -// make up the entire compilation unit -//--------------------------------------------------------------------------- - -let mapTImplFile f (TImplFile(fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes)) = TImplFile(fragName, pragmas, f moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes) -let mapAccImplFile f z (TImplFile(fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes)) = let moduleExpr, z = f z moduleExpr in TImplFile(fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes), z -let foldTImplFile f z (TImplFile(_, _, moduleExpr, _, _, _)) = f z moduleExpr - -//--------------------------------------------------------------------------- -// Equality relations on locally defined things -//--------------------------------------------------------------------------- - -let typarEq (lv1: Typar) (lv2: Typar) = (lv1.Stamp = lv2.Stamp) - -/// Equality on type variables, implemented as reference equality. This should be equivalent to using typarEq. -let typarRefEq (tp1: Typar) (tp2: Typar) = (tp1 === tp2) - - -/// Equality on value specs, implemented as reference equality -let valEq (lv1: Val) (lv2: Val) = (lv1 === lv2) - -/// Equality on CCU references, implemented as reference equality except when unresolved -let ccuEq (mv1: CcuThunk) (mv2: CcuThunk) = - (mv1 === mv2) || - (if mv1.IsUnresolvedReference || mv2.IsUnresolvedReference then - mv1.AssemblyName = mv2.AssemblyName - else - mv1.Contents === mv2.Contents) - -/// For dereferencing in the middle of a pattern -let (|ValDeref|) (vr: ValRef) = vr.Deref - - -//-------------------------------------------------------------------------- -// Make references to TAST items -//-------------------------------------------------------------------------- - -let mkRecdFieldRef tcref f = RFRef(tcref, f) -let mkUnionCaseRef tcref c = UCRef(tcref, c) - - -let ERefLocal x: EntityRef = { binding=x; nlr=Unchecked.defaultof<_> } -let ERefNonLocal x: EntityRef = { binding=Unchecked.defaultof<_>; nlr=x } -let ERefNonLocalPreResolved x xref: EntityRef = { binding=x; nlr=xref } -let (|ERefLocal|ERefNonLocal|) (x: EntityRef) = - match box x.nlr with - | null -> ERefLocal x.binding - | _ -> ERefNonLocal x.nlr - -//-------------------------------------------------------------------------- -// Construct local references -//-------------------------------------------------------------------------- - - -let mkLocalTyconRef x = ERefLocal x -let mkNonLocalEntityRef ccu mp = NonLocalEntityRef(ccu, mp) -let mkNestedNonLocalEntityRef (nleref: NonLocalEntityRef) id = mkNonLocalEntityRef nleref.Ccu (Array.append nleref.Path [| id |]) -let mkNonLocalTyconRef nleref id = ERefNonLocal (mkNestedNonLocalEntityRef nleref id) -let mkNonLocalTyconRefPreResolved x nleref id = ERefNonLocalPreResolved x (mkNestedNonLocalEntityRef nleref id) - -type EntityRef with - - member tcref.NestedTyconRef (x: Entity) = - match tcref with - | ERefLocal _ -> mkLocalTyconRef x - | ERefNonLocal nlr -> mkNonLocalTyconRefPreResolved x nlr x.LogicalName - - member tcref.RecdFieldRefInNestedTycon tycon (id: Ident) = RFRef (tcref.NestedTyconRef tycon, id.idText) - -/// Make a reference to a union case for type in a module or namespace -let mkModuleUnionCaseRef (modref: ModuleOrNamespaceRef) tycon uc = - (modref.NestedTyconRef tycon).MakeNestedUnionCaseRef uc +/// A set of static methods for constructing types. +type Construct() = -let VRefLocal x: ValRef = { binding=x; nlr=Unchecked.defaultof<_> } + static let taccessPublic = TAccess [] + + /// Key a Tycon or TyconRef by demangled name and arity + static member KeyTyconByDemangledNameAndArity<'T> (nm: string) (typars: Typar list) (x: 'T) : KeyValuePair = + KeyValuePair(NameArityPair(DemangleGenericTypeName nm, typars.Length), x) + + /// Key a Tycon or TyconRef by both mangled and demangled name. + /// Generic types can be accessed either by 'List' or 'List`1'. + /// This lists both keys. + static member KeyTyconByAccessNames<'T> (nm: string) (x: 'T) : KeyValuePair[] = + match TryDemangleGenericNameAndPos nm with + | ValueSome pos -> + let dnm = DemangleGenericTypeNameWithPos pos nm + [| KeyValuePair(nm, x); KeyValuePair(dnm, x) |] + | _ -> + [| KeyValuePair(nm, x) |] -let VRefNonLocal x: ValRef = { binding=Unchecked.defaultof<_>; nlr=x } + /// Create a new node for the contents of a module or namespace + static member NewModuleOrNamespaceType mkind tycons vals = + ModuleOrNamespaceType(mkind, QueueList.ofList vals, QueueList.ofList tycons) -let VRefNonLocalPreResolved x xref: ValRef = { binding=x; nlr=xref } + /// Create a new node for an empty module or namespace contents + static member NewEmptyModuleOrNamespaceType mkind = + Construct.NewModuleOrNamespaceType mkind [] [] -let (|VRefLocal|VRefNonLocal|) (x: ValRef) = - match box x.nlr with - | null -> VRefLocal x.binding - | _ -> VRefNonLocal x.nlr +#if !NO_EXTENSIONTYPING -let mkNonLocalValRef mp id = VRefNonLocal {EnclosingEntity = ERefNonLocal mp; ItemKey=id } -let mkNonLocalValRefPreResolved x mp id = VRefNonLocalPreResolved x {EnclosingEntity = ERefNonLocal mp; ItemKey=id } + /// Create a new node for the representation information for a provided type definition + static member NewProvidedTyconRepr(resolutionEnvironment, st: Tainted, importProvidedType, isSuppressRelocate, m) = -let ccuOfValRef vref = - match vref with - | VRefLocal _ -> None - | VRefNonLocal nlr -> Some nlr.Ccu + let isErased = st.PUntaint((fun st -> st.IsErased), m) -let ccuOfTyconRef eref = - match eref with - | ERefLocal _ -> None - | ERefNonLocal nlr -> Some nlr.Ccu + let lazyBaseTy = + LazyWithContext.Create + ((fun (m, objTy) -> + let baseSystemTy = st.PApplyOption((fun st -> match st.BaseType with null -> None | ty -> Some ty), m) + match baseSystemTy with + | None -> objTy + | Some t -> importProvidedType t), + ErrorLogger.findOriginalException) -//-------------------------------------------------------------------------- -// Type parameters and inference unknowns -//------------------------------------------------------------------------- + TProvidedTypeExtensionPoint + { ResolutionEnvironment=resolutionEnvironment + ProvidedType=st + LazyBaseType=lazyBaseTy + UnderlyingTypeOfEnum = (fun () -> importProvidedType (st.PApply((fun st -> st.GetEnumUnderlyingType()), m))) + IsDelegate = (fun () -> st.PUntaint((fun st -> + let baseType = st.BaseType + match baseType with + | null -> false + | x when x.IsGenericType -> false + | x when x.DeclaringType <> null -> false + | x -> x.FullName = "System.Delegate" || x.FullName = "System.MulticastDelegate"), m)) + IsEnum = st.PUntaint((fun st -> st.IsEnum), m) + IsStructOrEnum = st.PUntaint((fun st -> st.IsValueType || st.IsEnum), m) + IsInterface = st.PUntaint((fun st -> st.IsInterface), m) + IsSealed = st.PUntaint((fun st -> st.IsSealed), m) + IsAbstract = st.PUntaint((fun st -> st.IsAbstract), m) + IsClass = st.PUntaint((fun st -> st.IsClass), m) + IsErased = isErased + IsSuppressRelocate = isSuppressRelocate } -let mkTyparTy (tp: Typar) = - match tp.Kind with - | TyparKind.Type -> tp.AsType - | TyparKind.Measure -> TType_measure (Measure.Var tp) + /// Create a new entity node for a provided type definition + static member NewProvidedTycon(resolutionEnvironment, st: Tainted, importProvidedType, isSuppressRelocate, m, ?access, ?cpath) = + let stamp = newStamp() + let name = st.PUntaint((fun st -> st.Name), m) + let id = ident (name, m) + let kind = + let isMeasure = + st.PApplyWithProvider((fun (st, provider) -> + ignore provider + st.IsMeasure), m) + .PUntaintNoFailure(fun x -> x) + if isMeasure then TyparKind.Measure else TyparKind.Type -let copyTypar (tp: Typar) = - let optData = tp.typar_opt_data |> Option.map (fun tg -> { typar_il_name = tg.typar_il_name; typar_xmldoc = tg.typar_xmldoc; typar_constraints = tg.typar_constraints; typar_attribs = tg.typar_attribs }) - Typar.New { typar_id = tp.typar_id - typar_flags = tp.typar_flags - typar_stamp = newStamp() - typar_solution = tp.typar_solution - typar_astype = Unchecked.defaultof<_> - // Be careful to clone the mutable optional data too - typar_opt_data = optData } + let access = + match access with + | Some a -> a + | None -> TAccess [] + let cpath = + match cpath with + | None -> + let ilScopeRef = st.TypeProviderAssemblyRef + let enclosingName = ExtensionTyping.GetFSharpPathToProvidedType(st, m) + CompPath(ilScopeRef, enclosingName |> List.map(fun id->id, ModuleOrNamespaceKind.Namespace)) + | Some p -> p + let pubpath = cpath.NestedPublicPath id -let copyTypars tps = List.map copyTypar tps + let repr = Construct.NewProvidedTyconRepr(resolutionEnvironment, st, importProvidedType, isSuppressRelocate, m) -//-------------------------------------------------------------------------- -// Inference variables -//-------------------------------------------------------------------------- - -let tryShortcutSolvedUnitPar canShortcut (r: Typar) = - if r.Kind = TyparKind.Type then failwith "tryShortcutSolvedUnitPar: kind=type" - match r.Solution with - | Some (TType_measure unt) -> - if canShortcut then - match unt with - | Measure.Var r2 -> - match r2.Solution with - | None -> () - | Some _ as soln -> - r.typar_solution <- soln - | _ -> () - unt - | _ -> - failwith "tryShortcutSolvedUnitPar: unsolved" - -let rec stripUnitEqnsAux canShortcut unt = - match unt with - | Measure.Var r when r.IsSolved -> stripUnitEqnsAux canShortcut (tryShortcutSolvedUnitPar canShortcut r) - | _ -> unt - -let rec stripTyparEqnsAux canShortcut ty = - match ty with - | TType_var r -> - match r.Solution with - | Some soln -> - if canShortcut then - match soln with - // We avoid shortcutting when there are additional constraints on the type variable we're trying to cut out - // This is only because IterType likes to walk _all_ the constraints _everywhere_ in a type, including - // those attached to _solved_ type variables. In an ideal world this would never be needed - see the notes - // on IterType. - | TType_var r2 when r2.Constraints.IsEmpty -> - match r2.Solution with - | None -> () - | Some _ as soln2 -> - r.typar_solution <- soln2 - | _ -> () - stripTyparEqnsAux canShortcut soln - | None -> - ty - | TType_measure unt -> - TType_measure (stripUnitEqnsAux canShortcut unt) - | _ -> ty - -let stripTyparEqns ty = stripTyparEqnsAux false ty -let stripUnitEqns unt = stripUnitEqnsAux false unt - -//--------------------------------------------------------------------------- -// These make local/non-local references to values according to whether -// the item is globally stable ("published") or not. -//--------------------------------------------------------------------------- - -let mkLocalValRef (v: Val) = VRefLocal v -let mkLocalModRef (v: ModuleOrNamespace) = ERefLocal v -let mkLocalEntityRef (v: Entity) = ERefLocal v - -let mkNonLocalCcuRootEntityRef ccu (x: Entity) = mkNonLocalTyconRefPreResolved x (mkNonLocalEntityRef ccu [| |]) x.LogicalName - -let mkNestedValRef (cref: EntityRef) (v: Val) : ValRef = - match cref with - | ERefLocal _ -> mkLocalValRef v - | ERefNonLocal nlr -> - let key = v.GetLinkageFullKey() - mkNonLocalValRefPreResolved v nlr key - -/// From Ref_private to Ref_nonlocal when exporting data. -let rescopePubPathToParent viewedCcu (PubPath(p)) = NonLocalEntityRef(viewedCcu, p.[0..p.Length-2]) - -/// From Ref_private to Ref_nonlocal when exporting data. -let rescopePubPath viewedCcu (PubPath(p)) = NonLocalEntityRef(viewedCcu, p) - -//--------------------------------------------------------------------------- -// Equality between TAST items. -//--------------------------------------------------------------------------- - -let valRefInThisAssembly compilingFslib (x: ValRef) = - match x with - | VRefLocal _ -> true - | VRefNonLocal _ -> compilingFslib - -let tyconRefUsesLocalXmlDoc compilingFslib (x: TyconRef) = - match x with - | ERefLocal _ -> true - | ERefNonLocal _ -> -#if !NO_EXTENSIONTYPING - match x.TypeReprInfo with - | TProvidedTypeExtensionPoint _ -> true - | _ -> + Tycon.New "tycon" + { entity_stamp=stamp + entity_logical_name=name + entity_range=m + entity_flags=EntityFlags(usesPrefixDisplay=false, isModuleOrNamespace=false, preEstablishedHasDefaultCtor=false, hasSelfReferentialCtor=false, isStructRecordOrUnionType=false) + entity_attribs=[] // fetched on demand via est.fs API + entity_typars= LazyWithContext.NotLazy [] + entity_tycon_repr = repr + entity_tycon_tcaug=TyconAugmentation.Create() + entity_modul_contents = MaybeLazy.Lazy (lazy new ModuleOrNamespaceType(Namespace, QueueList.ofList [], QueueList.ofList [])) + // Generated types get internal accessibility + entity_pubpath = Some pubpath + entity_cpath = Some cpath + entity_il_repr_cache = newCache() + entity_opt_data = + match kind, access with + | TyparKind.Type, TAccess [] -> None + | _ -> Some { Entity.NewEmptyEntityOptData() with + entity_kind = kind + entity_accessibility = access } } #endif - compilingFslib - -let entityRefInThisAssembly compilingFslib (x: EntityRef) = - match x with - | ERefLocal _ -> true - | ERefNonLocal _ -> compilingFslib - -let arrayPathEq (y1: string[]) (y2: string[]) = - let len1 = y1.Length - let len2 = y2.Length - (len1 = len2) && - (let rec loop i = (i >= len1) || (y1.[i] = y2.[i] && loop (i+1)) - loop 0) - -let nonLocalRefEq (NonLocalEntityRef(x1, y1) as smr1) (NonLocalEntityRef(x2, y2) as smr2) = - smr1 === smr2 || (ccuEq x1 x2 && arrayPathEq y1 y2) - -/// This predicate tests if non-local resolution paths are definitely known to resolve -/// to different entities. All references with different named paths always resolve to -/// different entities. Two references with the same named paths may resolve to the same -/// entities even if they reference through different CCUs, because one reference -/// may be forwarded to another via a .NET TypeForwarder. -let nonLocalRefDefinitelyNotEq (NonLocalEntityRef(_, y1)) (NonLocalEntityRef(_, y2)) = - not (arrayPathEq y1 y2) - -let pubPathEq (PubPath path1) (PubPath path2) = arrayPathEq path1 path2 - -let fslibRefEq (nlr1: NonLocalEntityRef) (PubPath(path2)) = - arrayPathEq nlr1.Path path2 - -// Compare two EntityRef's for equality when compiling fslib (FSharp.Core.dll) -// -// Compiler-internal references to items in fslib are Ref_nonlocals even when compiling fslib. -// This breaks certain invariants that hold elsewhere, because they dereference to point to -// Entity's from signatures rather than Entity's from implementations. This means backup, alternative -// equality comparison techniques are needed when compiling fslib itself. -let fslibEntityRefEq fslibCcu (eref1: EntityRef) (eref2: EntityRef) = - match eref1, eref2 with - | (ERefNonLocal nlr1, ERefLocal x2) - | (ERefLocal x2, ERefNonLocal nlr1) -> - ccuEq nlr1.Ccu fslibCcu && - match x2.PublicPath with - | Some pp2 -> fslibRefEq nlr1 pp2 - | None -> false - | (ERefLocal e1, ERefLocal e2) -> - match e1.PublicPath, e2.PublicPath with - | Some pp1, Some pp2 -> pubPathEq pp1 pp2 - | _ -> false - | _ -> false - - -// Compare two ValRef's for equality when compiling fslib (FSharp.Core.dll) -// -// Compiler-internal references to items in fslib are Ref_nonlocals even when compiling fslib. -// This breaks certain invariants that hold elsewhere, because they dereference to point to -// Val's from signatures rather than Val's from implementations. This means backup, alternative -// equality comparison techniques are needed when compiling fslib itself. -let fslibValRefEq fslibCcu vref1 vref2 = - match vref1, vref2 with - | (VRefNonLocal nlr1, VRefLocal x2) - | (VRefLocal x2, VRefNonLocal nlr1) -> - ccuEq nlr1.Ccu fslibCcu && - match x2.PublicPath with - | Some (ValPubPath(pp2, nm2)) -> - // Note: this next line is just comparing the values by name, and not even the partial linkage data - // This relies on the fact that the compiler doesn't use any references to - // entities in fslib that are overloaded, or, if they are overloaded, then value identity - // is not significant - nlr1.ItemKey.PartialKey = nm2.PartialKey && - fslibRefEq nlr1.EnclosingEntity.nlr pp2 - | _ -> - false - // Note: I suspect this private-to-private reference comparison is not needed - | (VRefLocal e1, VRefLocal e2) -> - match e1.PublicPath, e2.PublicPath with - | Some (ValPubPath(pp1, nm1)), Some (ValPubPath(pp2, nm2)) -> - pubPathEq pp1 pp2 && - (nm1 = nm2) - | _ -> false - | _ -> false - -/// Primitive routine to compare two EntityRef's for equality -/// This takes into account the possibility that they may have type forwarders -let primEntityRefEq compilingFslib fslibCcu (x: EntityRef) (y: EntityRef) = - x === y || - - if x.IsResolved && y.IsResolved && not compilingFslib then - x.ResolvedTarget === y.ResolvedTarget - elif not x.IsLocalRef && not y.IsLocalRef && - (// Two tcrefs with identical paths are always equal - nonLocalRefEq x.nlr y.nlr || - // The tcrefs may have forwarders. If they may possibly be equal then resolve them to get their canonical references - // and compare those using pointer equality. - (not (nonLocalRefDefinitelyNotEq x.nlr y.nlr) && - match x.TryDeref with - | ValueSome v1 -> match y.TryDeref with ValueSome v2 -> v1 === v2 | _ -> false - | _ -> match y.TryDeref with ValueNone -> true | _ -> false)) then - true - else - compilingFslib && fslibEntityRefEq fslibCcu x y - -/// Primitive routine to compare two UnionCaseRef's for equality -let primUnionCaseRefEq compilingFslib fslibCcu (UCRef(tcr1, c1) as uc1) (UCRef(tcr2, c2) as uc2) = - uc1 === uc2 || (primEntityRefEq compilingFslib fslibCcu tcr1 tcr2 && c1 = c2) - -/// Primitive routine to compare two ValRef's for equality. On the whole value identity is not particularly -/// significant in F#. However it is significant for -/// (a) Active Patterns -/// (b) detecting uses of "special known values" from FSharp.Core.dll, such as 'seq' -/// and quotation splicing -/// -/// Note this routine doesn't take type forwarding into account -let primValRefEq compilingFslib fslibCcu (x: ValRef) (y: ValRef) = - x === y || - if (x.IsResolved && y.IsResolved && x.ResolvedTarget === y.ResolvedTarget) || - (x.IsLocalRef && y.IsLocalRef && valEq x.PrivateTarget y.PrivateTarget) then - true - else - (// Use TryDeref to guard against the platforms/times when certain F# language features aren't available, - // e.g. CompactFramework doesn't have support for quotations. - match x.TryDeref with - | ValueSome v1 -> match y.TryDeref with ValueSome v2 -> v1 === v2 | _ -> false - | _ -> match y.TryDeref with ValueNone -> true | _ -> false) - || (if compilingFslib then fslibValRefEq fslibCcu x y else false) - -//--------------------------------------------------------------------------- -// pubpath/cpath mess -//--------------------------------------------------------------------------- - -let fullCompPathOfModuleOrNamespace (m: ModuleOrNamespace) = - let (CompPath(scoref, cpath)) = m.CompilationPath - CompPath(scoref, cpath@[(m.LogicalName, m.ModuleOrNamespaceType.ModuleOrNamespaceKind)]) - -// Can cpath2 be accessed given a right to access cpath1. That is, is cpath2 a nested type or namespace of cpath1. Note order of arguments. -let inline canAccessCompPathFrom (CompPath(scoref1, cpath1)) (CompPath(scoref2, cpath2)) = - let rec loop p1 p2 = - match p1, p2 with - | (a1, k1)::rest1, (a2, k2)::rest2 -> (a1=a2) && (k1=k2) && loop rest1 rest2 - | [], _ -> true - | _ -> false // cpath1 is longer - loop cpath1 cpath2 && - (scoref1 = scoref2) - -let canAccessFromOneOf cpaths cpathTest = - cpaths |> List.exists (fun cpath -> canAccessCompPathFrom cpath cpathTest) - -let canAccessFrom (TAccess x) cpath = - x |> List.forall (fun cpath1 -> canAccessCompPathFrom cpath1 cpath) - -let canAccessFromEverywhere (TAccess x) = x.IsEmpty -let canAccessFromSomewhere (TAccess _) = true -let isLessAccessible (TAccess aa) (TAccess bb) = - not (aa |> List.forall(fun a -> bb |> List.exists (fun b -> canAccessCompPathFrom a b))) - -/// Given (newPath, oldPath) replace oldPath by newPath in the TAccess. -let accessSubstPaths (newPath, oldPath) (TAccess paths) = - let subst cpath = if cpath=oldPath then newPath else cpath - TAccess (List.map subst paths) - -let compPathOfCcu (ccu: CcuThunk) = CompPath(ccu.ILScopeRef, []) -let taccessPublic = TAccess [] -let taccessPrivate accessPath = TAccess [accessPath] -let compPathInternal = CompPath(ILScopeRef.Local, []) -let taccessInternal = TAccess [compPathInternal] -let combineAccess (TAccess a1) (TAccess a2) = TAccess(a1@a2) - -//--------------------------------------------------------------------------- -// Construct TAST nodes -//--------------------------------------------------------------------------- - -let NewFreeVarsCache() = newCache () - -let MakeUnionCasesTable ucs: TyconUnionCases = - { CasesByIndex = Array.ofList ucs - CasesByName = NameMap.ofKeyedList (fun uc -> uc.DisplayName) ucs } - -let MakeRecdFieldsTable ucs: TyconRecdFields = - { FieldsByIndex = Array.ofList ucs - FieldsByName = ucs |> NameMap.ofKeyedList (fun rfld -> rfld.Name) } - - -let MakeUnionCases ucs: TyconUnionData = - { CasesTable=MakeUnionCasesTable ucs - CompiledRepresentation=newCache() } - -let MakeUnionRepr ucs = TUnionRepr (MakeUnionCases ucs) - -let NewTypar (kind, rigid, Typar(id, staticReq, isCompGen), isFromError, dynamicReq, attribs, eqDep, compDep) = - Typar.New - { typar_id = id - typar_stamp = newStamp() - typar_flags= TyparFlags(kind, rigid, isFromError, isCompGen, staticReq, dynamicReq, eqDep, compDep) - typar_solution = None - typar_astype = Unchecked.defaultof<_> - typar_opt_data = - match attribs with - | [] -> None - | _ -> Some { typar_il_name = None; typar_xmldoc = XmlDoc.Empty; typar_constraints = []; typar_attribs = attribs } } - -let NewRigidTypar nm m = NewTypar (TyparKind.Type, TyparRigidity.Rigid, Typar(mkSynId m nm, NoStaticReq, true), false, TyparDynamicReq.Yes, [], false, false) - -let NewUnionCase id tys rty attribs docOption access: UnionCase = - { Id=id - XmlDoc=docOption - XmlDocSig="" - Accessibility=access - FieldTable = MakeRecdFieldsTable tys - ReturnType = rty - Attribs=attribs - OtherRangeOpt = None } - -let NewModuleOrNamespaceType mkind tycons vals = - ModuleOrNamespaceType(mkind, QueueList.ofList vals, QueueList.ofList tycons) - -let NewEmptyModuleOrNamespaceType mkind = NewModuleOrNamespaceType mkind [] [] - -/// Create a new TAST Entity node for an F# exception definition -let NewExn cpath (id: Ident) access repr attribs doc = - Tycon.New "exnc" - { entity_stamp=newStamp() - entity_attribs=attribs - entity_logical_name=id.idText - entity_range=id.idRange - entity_tycon_tcaug=TyconAugmentation.Create() - entity_pubpath=cpath |> Option.map (fun (cp: CompilationPath) -> cp.NestedPublicPath id) - entity_modul_contents = MaybeLazy.Strict (NewEmptyModuleOrNamespaceType ModuleOrType) - entity_cpath= cpath - entity_typars=LazyWithContext.NotLazy [] - entity_tycon_repr = TNoRepr - entity_flags=EntityFlags(usesPrefixDisplay=false, isModuleOrNamespace=false, preEstablishedHasDefaultCtor=false, hasSelfReferentialCtor=false, isStructRecordOrUnionType=false) - entity_il_repr_cache= newCache() - entity_opt_data = - match doc, access, repr with - | XmlDoc [||], TAccess [], TExnNone -> None - | _ -> Some { Entity.NewEmptyEntityOptData() with entity_xmldoc = doc; entity_accessiblity = access; entity_tycon_repr_accessibility = access; entity_exn_info = repr } } - -/// Create a new TAST RecdField node for an F# class, struct or record field -let NewRecdField stat konst id nameGenerated ty isMutable isVolatile pattribs fattribs docOption access secret = - { rfield_mutable=isMutable - rfield_pattribs=pattribs - rfield_fattribs=fattribs - rfield_type=ty - rfield_static=stat - rfield_volatile=isVolatile - rfield_const=konst - rfield_access = access - rfield_secret = secret - rfield_xmldoc = docOption - rfield_xmldocsig = "" - rfield_id=id - rfield_name_generated = nameGenerated - rfield_other_range = None } - -let NewTycon (cpath, nm, m, access, reprAccess, kind, typars, docOption, usesPrefixDisplay, preEstablishedHasDefaultCtor, hasSelfReferentialCtor, mtyp) = - let stamp = newStamp() - Tycon.New "tycon" - { entity_stamp=stamp - entity_logical_name=nm - entity_range=m - entity_flags=EntityFlags(usesPrefixDisplay=usesPrefixDisplay, isModuleOrNamespace=false, preEstablishedHasDefaultCtor=preEstablishedHasDefaultCtor, hasSelfReferentialCtor=hasSelfReferentialCtor, isStructRecordOrUnionType=false) - entity_attribs=[] // fixed up after - entity_typars=typars - entity_tycon_repr = TNoRepr - entity_tycon_tcaug=TyconAugmentation.Create() - entity_modul_contents = mtyp - entity_pubpath=cpath |> Option.map (fun (cp: CompilationPath) -> cp.NestedPublicPath (mkSynId m nm)) - entity_cpath = cpath - entity_il_repr_cache = newCache() - entity_opt_data = - match kind, docOption, reprAccess, access with - | TyparKind.Type, XmlDoc [||], TAccess [], TAccess [] -> None - | _ -> Some { Entity.NewEmptyEntityOptData() with entity_kind = kind; entity_xmldoc = docOption; entity_tycon_repr_accessibility = reprAccess; entity_accessiblity=access } } - - -let NewILTycon nlpath (nm, m) tps (scoref: ILScopeRef, enc, tdef: ILTypeDef) mtyp = - - // NOTE: hasSelfReferentialCtor=false is an assumption about mscorlib - let hasSelfReferentialCtor = tdef.IsClass && (not scoref.IsAssemblyRef && scoref.AssemblyRef.Name = "mscorlib") - let tycon = NewTycon(nlpath, nm, m, taccessPublic, taccessPublic, TyparKind.Type, tps, XmlDoc.Empty, true, false, hasSelfReferentialCtor, mtyp) - - tycon.entity_tycon_repr <- TILObjectRepr (TILObjectReprData (scoref, enc, tdef)) - tycon.TypeContents.tcaug_closed <- true - tycon - -exception Duplicate of string * string * range -exception NameClash of string * string * string * range * string * string * range -exception FullAbstraction of string * range - -let NewModuleOrNamespace cpath access (id: Ident) xml attribs mtype = - Construct.NewModuleOrNamespace cpath access id xml attribs mtype - -/// Create a new Val object -let NewVal - (logicalName: string, m: range, compiledName, ty, isMutable, isCompGen, arity, access, - recValInfo, specialRepr, baseOrThis, attribs, inlineInfo, doc, isModuleOrMemberBinding, - isExtensionMember, isIncrClassSpecialMember, isTyFunc, allowTypeInst, isGeneratedEventVal, - konst, actualParent) : Val = - - let stamp = newStamp() - Val.New - { val_stamp = stamp - val_logical_name = logicalName - val_range = m - val_flags = ValFlags(recValInfo, baseOrThis, isCompGen, inlineInfo, isMutable, isModuleOrMemberBinding, isExtensionMember, isIncrClassSpecialMember, isTyFunc, allowTypeInst, isGeneratedEventVal) - val_type = ty - val_opt_data = - match compiledName, arity, konst, access, doc, specialRepr, actualParent, attribs with - | None, None, None, TAccess [], XmlDoc [||], None, ParentNone, [] -> None - | _ -> - Some { Val.NewEmptyValOptData() with - val_compiled_name = (match compiledName with Some v when v <> logicalName -> compiledName | _ -> None) - val_repr_info = arity - val_const = konst - val_access = access - val_xmldoc = doc - val_member_info = specialRepr - val_declaring_entity = actualParent - val_attribs = attribs } - } - - -/// Create the new contents of an overall assembly -let NewCcuContents sref m nm mty = - NewModuleOrNamespace (Some(CompPath(sref, []))) taccessPublic (ident(nm, m)) XmlDoc.Empty [] (MaybeLazy.Strict mty) - + /// Create a new entity node for a module or namespace + static member NewModuleOrNamespace cpath access (id: Ident) xml attribs mtype = + let stamp = newStamp() + // Put the module suffix on if needed + Tycon.New "mspec" + { entity_logical_name=id.idText + entity_range = id.idRange + entity_stamp=stamp + entity_modul_contents = mtype + entity_flags=EntityFlags(usesPrefixDisplay=false, isModuleOrNamespace=true, preEstablishedHasDefaultCtor=false, hasSelfReferentialCtor=false, isStructRecordOrUnionType=false) + entity_typars=LazyWithContext.NotLazy [] + entity_tycon_repr = TNoRepr + entity_tycon_tcaug=TyconAugmentation.Create() + entity_pubpath=cpath |> Option.map (fun (cp: CompilationPath) -> cp.NestedPublicPath id) + entity_cpath=cpath + entity_attribs=attribs + entity_il_repr_cache = newCache() + entity_opt_data = + match xml, access with + | XmlDoc [||], TAccess [] -> None + | _ -> Some { Entity.NewEmptyEntityOptData() with + entity_xmldoc = xml + entity_tycon_repr_accessibility = access + entity_accessibility = access } } + + /// Create a new unfilled cache for free variable calculations + static member NewFreeVarsCache() = newCache () + + /// Create the field tables for a record or class type + static member MakeRecdFieldsTable ucs: TyconRecdFields = + { FieldsByIndex = Array.ofList ucs + FieldsByName = ucs |> NameMap.ofKeyedList (fun rfld -> rfld.Name) } + + /// Create the union case tables for a union type + static member MakeUnionCases ucs: TyconUnionData = + { CasesTable = + { CasesByIndex = Array.ofList ucs + CasesByName = NameMap.ofKeyedList (fun uc -> uc.DisplayName) ucs } + CompiledRepresentation=newCache() } + + /// Create a node for a union type + static member MakeUnionRepr ucs = TUnionRepr (Construct.MakeUnionCases ucs) + + /// Create a new type parameter node + static member NewTypar (kind, rigid, Typar(id, staticReq, isCompGen), isFromError, dynamicReq, attribs, eqDep, compDep) = + Typar.New + { typar_id = id + typar_stamp = newStamp() + typar_flags= TyparFlags(kind, rigid, isFromError, isCompGen, staticReq, dynamicReq, eqDep, compDep) + typar_solution = None + typar_astype = Unchecked.defaultof<_> + typar_opt_data = + match attribs with + | [] -> None + | _ -> Some { typar_il_name = None; typar_xmldoc = XmlDoc.Empty; typar_constraints = []; typar_attribs = attribs } } + + /// Create a new type parameter node for a declared type parameter + static member NewRigidTypar nm m = + Construct.NewTypar (TyparKind.Type, TyparRigidity.Rigid, Typar(mkSynId m nm, NoStaticReq, true), false, TyparDynamicReq.Yes, [], false, false) + + /// Create a new union case node + static member NewUnionCase id tys rty attribs docOption access: UnionCase = + { Id=id + XmlDoc=docOption + XmlDocSig="" + Accessibility=access + FieldTable = Construct.MakeRecdFieldsTable tys + ReturnType = rty + Attribs=attribs + OtherRangeOpt = None } + + /// Create a new TAST Entity node for an F# exception definition + static member NewExn cpath (id: Ident) access repr attribs doc = + Tycon.New "exnc" + { entity_stamp=newStamp() + entity_attribs=attribs + entity_logical_name=id.idText + entity_range=id.idRange + entity_tycon_tcaug=TyconAugmentation.Create() + entity_pubpath=cpath |> Option.map (fun (cp: CompilationPath) -> cp.NestedPublicPath id) + entity_modul_contents = MaybeLazy.Strict (Construct.NewEmptyModuleOrNamespaceType ModuleOrType) + entity_cpath= cpath + entity_typars=LazyWithContext.NotLazy [] + entity_tycon_repr = TNoRepr + entity_flags=EntityFlags(usesPrefixDisplay=false, isModuleOrNamespace=false, preEstablishedHasDefaultCtor=false, hasSelfReferentialCtor=false, isStructRecordOrUnionType=false) + entity_il_repr_cache= newCache() + entity_opt_data = + match doc, access, repr with + | XmlDoc [||], TAccess [], TExnNone -> None + | _ -> Some { Entity.NewEmptyEntityOptData() with entity_xmldoc = doc; entity_accessibility = access; entity_tycon_repr_accessibility = access; entity_exn_info = repr } } + + /// Create a new TAST RecdField node for an F# class, struct or record field + static member NewRecdField stat konst id nameGenerated ty isMutable isVolatile pattribs fattribs docOption access secret = + { rfield_mutable=isMutable + rfield_pattribs=pattribs + rfield_fattribs=fattribs + rfield_type=ty + rfield_static=stat + rfield_volatile=isVolatile + rfield_const=konst + rfield_access = access + rfield_secret = secret + rfield_xmldoc = docOption + rfield_xmldocsig = "" + rfield_id=id + rfield_name_generated = nameGenerated + rfield_other_range = None } -//-------------------------------------------------------------------------- -// Cloning and adjusting -//-------------------------------------------------------------------------- - -/// Create a tycon based on an existing one using the function 'f'. -/// We require that we be given the new parent for the new tycon. -/// We pass the new tycon to 'f' in case it needs to reparent the -/// contents of the tycon. -let NewModifiedTycon f (orig: Tycon) = - let data = { orig with entity_stamp = newStamp() } - Tycon.New "NewModifiedTycon" (f data) -/// Create a module Tycon based on an existing one using the function 'f'. -/// We require that we be given the parent for the new module. -/// We pass the new module to 'f' in case it needs to reparent the -/// contents of the module. -let NewModifiedModuleOrNamespace f orig = - orig |> NewModifiedTycon (fun d -> - { d with entity_modul_contents = MaybeLazy.Strict (f (d.entity_modul_contents.Force())) }) - -/// Create a Val based on an existing one using the function 'f'. -/// We require that we be given the parent for the new Val. -let NewModifiedVal f (orig: Val) = - let stamp = newStamp() - let data' = f { orig with val_stamp=stamp } - Val.New data' - -let NewClonedModuleOrNamespace orig = NewModifiedModuleOrNamespace (fun mty -> mty) orig -let NewClonedTycon orig = NewModifiedTycon (fun d -> d) orig - -//------------------------------------------------------------------------------ - -/// Combine a list of ModuleOrNamespaceType's making up the description of a CCU. checking there are now -/// duplicate modules etc. -let CombineCcuContentFragments m l = - - /// Combine module types when multiple namespace fragments contribute to the - /// same namespace, making new module specs as we go. - let rec CombineModuleOrNamespaceTypes path m (mty1: ModuleOrNamespaceType) (mty2: ModuleOrNamespaceType) = - match mty1.ModuleOrNamespaceKind, mty2.ModuleOrNamespaceKind with - | Namespace, Namespace -> - let kind = mty1.ModuleOrNamespaceKind - let tab1 = mty1.AllEntitiesByLogicalMangledName - let tab2 = mty2.AllEntitiesByLogicalMangledName - let entities = - [ for e1 in mty1.AllEntities do - match tab2.TryGetValue e1.LogicalName with - | true, e2 -> yield CombineEntites path e1 e2 - | _ -> yield e1 - for e2 in mty2.AllEntities do - match tab1.TryGetValue e2.LogicalName with - | true, _ -> () - | _ -> yield e2 ] - - let vals = QueueList.append mty1.AllValsAndMembers mty2.AllValsAndMembers - - ModuleOrNamespaceType(kind, vals, QueueList.ofList entities) - - | Namespace, _ | _, Namespace -> - error(Error(FSComp.SR.tastNamespaceAndModuleWithSameNameInAssembly(textOfPath path), m)) - - | _-> - error(Error(FSComp.SR.tastTwoModulesWithSameNameInAssembly(textOfPath path), m)) - - and CombineEntites path (entity1: Entity) (entity2: Entity) = - - match entity1.IsModuleOrNamespace, entity2.IsModuleOrNamespace with - | true, true -> - entity1 |> NewModifiedTycon (fun data1 -> - let xml = XmlDoc.Merge entity1.XmlDoc entity2.XmlDoc - { data1 with - entity_attribs = entity1.Attribs @ entity2.Attribs - entity_modul_contents = MaybeLazy.Lazy (lazy (CombineModuleOrNamespaceTypes (path@[entity2.DemangledModuleOrNamespaceName]) entity2.Range entity1.ModuleOrNamespaceType entity2.ModuleOrNamespaceType)) - entity_opt_data = - match data1.entity_opt_data with - | Some optData -> Some { optData with entity_xmldoc = xml } - | _ -> Some { Entity.NewEmptyEntityOptData() with entity_xmldoc = xml } }) - | false, false -> - error(Error(FSComp.SR.tastDuplicateTypeDefinitionInAssembly(entity2.LogicalName, textOfPath path), entity2.Range)) - | _, _ -> - error(Error(FSComp.SR.tastConflictingModuleAndTypeDefinitionInAssembly(entity2.LogicalName, textOfPath path), entity2.Range)) + /// Create a new type definition node + static member NewTycon (cpath, nm, m, access, reprAccess, kind, typars, docOption, usesPrefixDisplay, preEstablishedHasDefaultCtor, hasSelfReferentialCtor, mtyp) = + let stamp = newStamp() + Tycon.New "tycon" + { entity_stamp=stamp + entity_logical_name=nm + entity_range=m + entity_flags=EntityFlags(usesPrefixDisplay=usesPrefixDisplay, isModuleOrNamespace=false, preEstablishedHasDefaultCtor=preEstablishedHasDefaultCtor, hasSelfReferentialCtor=hasSelfReferentialCtor, isStructRecordOrUnionType=false) + entity_attribs=[] // fixed up after + entity_typars=typars + entity_tycon_repr = TNoRepr + entity_tycon_tcaug=TyconAugmentation.Create() + entity_modul_contents = mtyp + entity_pubpath=cpath |> Option.map (fun (cp: CompilationPath) -> cp.NestedPublicPath (mkSynId m nm)) + entity_cpath = cpath + entity_il_repr_cache = newCache() + entity_opt_data = + match kind, docOption, reprAccess, access with + | TyparKind.Type, XmlDoc [||], TAccess [], TAccess [] -> None + | _ -> Some { Entity.NewEmptyEntityOptData() with entity_kind = kind; entity_xmldoc = docOption; entity_tycon_repr_accessibility = reprAccess; entity_accessibility=access } } + + /// Create a new type definition node for a .NET type definition + static member NewILTycon nlpath (nm, m) tps (scoref: ILScopeRef, enc, tdef: ILTypeDef) mtyp = + let tycon = Construct.NewTycon(nlpath, nm, m, taccessPublic, taccessPublic, TyparKind.Type, tps, XmlDoc.Empty, true, false, false, mtyp) + + tycon.entity_tycon_repr <- TILObjectRepr (TILObjectReprData (scoref, enc, tdef)) + tycon.TypeContents.tcaug_closed <- true + tycon + + /// Create a new Val node + static member NewVal + (logicalName: string, m: range, compiledName, ty, isMutable, isCompGen, arity, access, + recValInfo, specialRepr, baseOrThis, attribs, inlineInfo, doc, isModuleOrMemberBinding, + isExtensionMember, isIncrClassSpecialMember, isTyFunc, allowTypeInst, isGeneratedEventVal, + konst, actualParent) : Val = + + let stamp = newStamp() + Val.New { + val_stamp = stamp + val_logical_name = logicalName + val_range = m + val_flags = ValFlags(recValInfo, baseOrThis, isCompGen, inlineInfo, isMutable, isModuleOrMemberBinding, isExtensionMember, isIncrClassSpecialMember, isTyFunc, allowTypeInst, isGeneratedEventVal) + val_type = ty + val_opt_data = + match compiledName, arity, konst, access, doc, specialRepr, actualParent, attribs with + | None, None, None, TAccess [], XmlDoc [||], None, ParentNone, [] -> None + | _ -> + Some { Val.NewEmptyValOptData() with + val_compiled_name = (match compiledName with Some v when v <> logicalName -> compiledName | _ -> None) + val_repr_info = arity + val_const = konst + val_access = access + val_xmldoc = doc + val_member_info = specialRepr + val_declaring_entity = actualParent + val_attribs = attribs } + } + + /// Create the new contents of an overall assembly + static member NewCcuContents sref m nm mty = + Construct.NewModuleOrNamespace (Some(CompPath(sref, []))) taccessPublic (ident(nm, m)) XmlDoc.Empty [] (MaybeLazy.Strict mty) + + /// Create a tycon based on an existing one using the function 'f'. + /// We require that we be given the new parent for the new tycon. + /// We pass the new tycon to 'f' in case it needs to reparent the + /// contents of the tycon. + static member NewModifiedTycon f (orig: Tycon) = + let data = { orig with entity_stamp = newStamp() } + Tycon.New "NewModifiedTycon" (f data) - and CombineModuleOrNamespaceTypeList path m l = - match l with - | h :: t -> List.fold (CombineModuleOrNamespaceTypes path m) h t - | _ -> failwith "CombineModuleOrNamespaceTypeList" - - CombineModuleOrNamespaceTypeList [] m l - -//-------------------------------------------------------------------------- -// Resource format for pickled data -//-------------------------------------------------------------------------- + /// Create a module Tycon based on an existing one using the function 'f'. + /// We require that we be given the parent for the new module. + /// We pass the new module to 'f' in case it needs to reparent the + /// contents of the module. + static member NewModifiedModuleOrNamespace f orig = + orig |> Construct.NewModifiedTycon (fun d -> + { d with entity_modul_contents = MaybeLazy.Strict (f (d.entity_modul_contents.Force())) }) + + /// Create a Val based on an existing one using the function 'f'. + /// We require that we be given the parent for the new Val. + static member NewModifiedVal f (orig: Val) = + let stamp = newStamp() + let data' = f { orig with val_stamp=stamp } + Val.New data' -let FSharpOptimizationDataResourceName = "FSharpOptimizationData." -let FSharpSignatureDataResourceName = "FSharpSignatureData." -// For historical reasons, we use a different resource name for FSharp.Core, so older F# compilers -// don't complain when they see the resource. The prefix of these names must not be 'FSharpOptimizationData' -// or 'FSharpSignatureData' -let FSharpOptimizationDataResourceName2 = "FSharpOptimizationInfo." -let FSharpSignatureDataResourceName2 = "FSharpSignatureInfo." + /// Create a new module or namespace node by cloning an existing one + static member NewClonedModuleOrNamespace orig = + Construct.NewModifiedModuleOrNamespace (fun mty -> mty) orig + /// Create a new type definition node by cloning an existing one + static member NewClonedTycon orig = + Construct.NewModifiedTycon (fun d -> d) orig +#if !NO_EXTENSIONTYPING + /// Compute the definition location of a provided item + static member ComputeDefinitionLocationOfProvidedItem<'T when 'T :> IProvidedCustomAttributeProvider> (p: Tainted<'T>) : range option = + let attrs = p.PUntaintNoFailure(fun x -> x.GetDefinitionLocationAttribute(p.TypeProvider.PUntaintNoFailure id)) + match attrs with + | None | Some (null, _, _) -> None + | Some (filePath, line, column) -> + // Coordinates from type provider are 1-based for lines and columns + // Coordinates internally in the F# compiler are 1-based for lines and 0-based for columns + let pos = Range.mkPos line (max 0 (column - 1)) + Range.mkRange filePath pos pos |> Some +#endif diff --git a/src/fcs-fable/src/fsharp/TypedTreeBasics.fs b/src/fcs-fable/src/fsharp/TypedTreeBasics.fs new file mode 100644 index 0000000000..7f35d57a86 --- /dev/null +++ b/src/fcs-fable/src/fsharp/TypedTreeBasics.fs @@ -0,0 +1,470 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +//------------------------------------------------------------------------- +// Defines the typed abstract syntax trees used throughout the F# compiler. +//------------------------------------------------------------------------- + +module internal FSharp.Compiler.TypedTreeBasics + +open FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.CompilerGlobalState +open FSharp.Compiler.Lib +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TypedTree + +#if DEBUG +assert (sizeof = 8) +assert (sizeof = 8) +assert (sizeof = 4) +#endif + +let getNameOfScopeRef sref = + match sref with + | ILScopeRef.Local -> "" + | ILScopeRef.Module mref -> mref.Name + | ILScopeRef.Assembly aref -> aref.Name + | ILScopeRef.PrimaryAssembly -> "" + +/// Metadata on values (names of arguments etc. +module ValReprInfo = + + let unnamedTopArg1: ArgReprInfo = { Attribs=[]; Name=None } + + let unnamedTopArg = [unnamedTopArg1] + + let unitArgData: ArgReprInfo list list = [[]] + + let unnamedRetVal: ArgReprInfo = { Attribs = []; Name=None } + + let selfMetadata = unnamedTopArg + + let emptyValData = ValReprInfo([], [], unnamedRetVal) + + let InferTyparInfo (tps: Typar list) = tps |> List.map (fun tp -> TyparReprInfo(tp.Id, tp.Kind)) + + let InferArgReprInfo (v: Val) : ArgReprInfo = { Attribs = []; Name= Some v.Id } + + let InferArgReprInfos (vs: Val list list) = ValReprInfo([], List.mapSquared InferArgReprInfo vs, unnamedRetVal) + + let HasNoArgs (ValReprInfo(n, args, _)) = n.IsEmpty && args.IsEmpty + +//--------------------------------------------------------------------------- +// Basic properties via functions (old style) +//--------------------------------------------------------------------------- + +let typeOfVal (v: Val) = v.Type + +let typesOfVals (v: Val list) = v |> List.map (fun v -> v.Type) + +let nameOfVal (v: Val) = v.LogicalName + +let arityOfVal (v: Val) = (match v.ValReprInfo with None -> ValReprInfo.emptyValData | Some arities -> arities) + +let tupInfoRef = TupInfo.Const false + +let tupInfoStruct = TupInfo.Const true + +let mkTupInfo b = if b then tupInfoStruct else tupInfoRef + +let structnessDefault = false + +let mkRawRefTupleTy tys = TType_tuple (tupInfoRef, tys) + +let mkRawStructTupleTy tys = TType_tuple (tupInfoStruct, tys) + +//--------------------------------------------------------------------------- +// Aggregate operations to help transform the components that +// make up the entire compilation unit +//--------------------------------------------------------------------------- + +let mapTImplFile f (TImplFile (fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes)) = + TImplFile (fragName, pragmas, f moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes) + +let mapAccImplFile f z (TImplFile (fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes)) = + let moduleExpr, z = f z moduleExpr + TImplFile (fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes), z + +let foldTImplFile f z (TImplFile (_, _, moduleExpr, _, _, _)) = f z moduleExpr + +//--------------------------------------------------------------------------- +// Equality relations on locally defined things +//--------------------------------------------------------------------------- + +let typarEq (lv1: Typar) (lv2: Typar) = (lv1.Stamp = lv2.Stamp) + +/// Equality on type variables, implemented as reference equality. This should be equivalent to using typarEq. +let typarRefEq (tp1: Typar) (tp2: Typar) = (tp1 === tp2) + + +/// Equality on value specs, implemented as reference equality +let valEq (lv1: Val) (lv2: Val) = (lv1 === lv2) + +/// Equality on CCU references, implemented as reference equality except when unresolved +let ccuEq (mv1: CcuThunk) (mv2: CcuThunk) = + (mv1 === mv2) || + (if mv1.IsUnresolvedReference || mv2.IsUnresolvedReference then + mv1.AssemblyName = mv2.AssemblyName + else + mv1.Contents === mv2.Contents) + +/// For dereferencing in the middle of a pattern +let (|ValDeref|) (vr: ValRef) = vr.Deref + +//-------------------------------------------------------------------------- +// Make references to TAST items +//-------------------------------------------------------------------------- + +let mkRecdFieldRef tcref f = RecdFieldRef(tcref, f) + +let mkUnionCaseRef tcref c = UnionCaseRef(tcref, c) + +let ERefLocal x: EntityRef = { binding=x; nlr=Unchecked.defaultof<_> } + +let ERefNonLocal x: EntityRef = { binding=Unchecked.defaultof<_>; nlr=x } + +let ERefNonLocalPreResolved x xref: EntityRef = { binding=x; nlr=xref } + +let (|ERefLocal|ERefNonLocal|) (x: EntityRef) = + match box x.nlr with + | null -> ERefLocal x.binding + | _ -> ERefNonLocal x.nlr + +//-------------------------------------------------------------------------- +// Construct local references +//-------------------------------------------------------------------------- + +let mkLocalTyconRef x = ERefLocal x + +let mkNonLocalEntityRef ccu mp = NonLocalEntityRef(ccu, mp) + +let mkNestedNonLocalEntityRef (nleref: NonLocalEntityRef) id = + mkNonLocalEntityRef nleref.Ccu (Array.append nleref.Path [| id |]) + +let mkNonLocalTyconRef nleref id = ERefNonLocal (mkNestedNonLocalEntityRef nleref id) + +let mkNonLocalTyconRefPreResolved x nleref id = + ERefNonLocalPreResolved x (mkNestedNonLocalEntityRef nleref id) + +type EntityRef with + + member tcref.NestedTyconRef (x: Entity) = + match tcref with + | ERefLocal _ -> mkLocalTyconRef x + | ERefNonLocal nlr -> mkNonLocalTyconRefPreResolved x nlr x.LogicalName + + member tcref.RecdFieldRefInNestedTycon tycon (id: Ident) = RecdFieldRef (tcref.NestedTyconRef tycon, id.idText) + +/// Make a reference to a union case for type in a module or namespace +let mkModuleUnionCaseRef (modref: ModuleOrNamespaceRef) tycon uc = + (modref.NestedTyconRef tycon).MakeNestedUnionCaseRef uc + +let VRefLocal x: ValRef = { binding=x; nlr=Unchecked.defaultof<_> } + +let VRefNonLocal x: ValRef = { binding=Unchecked.defaultof<_>; nlr=x } + +let VRefNonLocalPreResolved x xref: ValRef = { binding=x; nlr=xref } + +let (|VRefLocal|VRefNonLocal|) (x: ValRef) = + match box x.nlr with + | null -> VRefLocal x.binding + | _ -> VRefNonLocal x.nlr + +let mkNonLocalValRef mp id = VRefNonLocal {EnclosingEntity = ERefNonLocal mp; ItemKey=id } +let mkNonLocalValRefPreResolved x mp id = VRefNonLocalPreResolved x {EnclosingEntity = ERefNonLocal mp; ItemKey=id } + +let ccuOfValRef vref = + match vref with + | VRefLocal _ -> None + | VRefNonLocal nlr -> Some nlr.Ccu + +let ccuOfTyconRef eref = + match eref with + | ERefLocal _ -> None + | ERefNonLocal nlr -> Some nlr.Ccu + +//-------------------------------------------------------------------------- +// Type parameters and inference unknowns +//------------------------------------------------------------------------- + +let mkTyparTy (tp: Typar) = + match tp.Kind with + | TyparKind.Type -> tp.AsType + | TyparKind.Measure -> TType_measure (Measure.Var tp) + +let copyTypar (tp: Typar) = + let optData = tp.typar_opt_data |> Option.map (fun tg -> { typar_il_name = tg.typar_il_name; typar_xmldoc = tg.typar_xmldoc; typar_constraints = tg.typar_constraints; typar_attribs = tg.typar_attribs }) + Typar.New { typar_id = tp.typar_id + typar_flags = tp.typar_flags + typar_stamp = newStamp() + typar_solution = tp.typar_solution + typar_astype = Unchecked.defaultof<_> + // Be careful to clone the mutable optional data too + typar_opt_data = optData } + +let copyTypars tps = List.map copyTypar tps + +//-------------------------------------------------------------------------- +// Inference variables +//-------------------------------------------------------------------------- + +let tryShortcutSolvedUnitPar canShortcut (r: Typar) = + if r.Kind = TyparKind.Type then failwith "tryShortcutSolvedUnitPar: kind=type" + match r.Solution with + | Some (TType_measure unt) -> + if canShortcut then + match unt with + | Measure.Var r2 -> + match r2.Solution with + | None -> () + | Some _ as soln -> + r.typar_solution <- soln + | _ -> () + unt + | _ -> + failwith "tryShortcutSolvedUnitPar: unsolved" + +let rec stripUnitEqnsAux canShortcut unt = + match unt with + | Measure.Var r when r.IsSolved -> stripUnitEqnsAux canShortcut (tryShortcutSolvedUnitPar canShortcut r) + | _ -> unt + +let rec stripTyparEqnsAux canShortcut ty = + match ty with + | TType_var r -> + match r.Solution with + | Some soln -> + if canShortcut then + match soln with + // We avoid shortcutting when there are additional constraints on the type variable we're trying to cut out + // This is only because IterType likes to walk _all_ the constraints _everywhere_ in a type, including + // those attached to _solved_ type variables. In an ideal world this would never be needed - see the notes + // on IterType. + | TType_var r2 when r2.Constraints.IsEmpty -> + match r2.Solution with + | None -> () + | Some _ as soln2 -> + r.typar_solution <- soln2 + | _ -> () + stripTyparEqnsAux canShortcut soln + | None -> + ty + | TType_measure unt -> + TType_measure (stripUnitEqnsAux canShortcut unt) + | _ -> ty + +let stripTyparEqns ty = stripTyparEqnsAux false ty + +let stripUnitEqns unt = stripUnitEqnsAux false unt + +//--------------------------------------------------------------------------- +// These make local/non-local references to values according to whether +// the item is globally stable ("published") or not. +//--------------------------------------------------------------------------- + +let mkLocalValRef (v: Val) = VRefLocal v +let mkLocalModRef (v: ModuleOrNamespace) = ERefLocal v +let mkLocalEntityRef (v: Entity) = ERefLocal v + +let mkNonLocalCcuRootEntityRef ccu (x: Entity) = mkNonLocalTyconRefPreResolved x (mkNonLocalEntityRef ccu [| |]) x.LogicalName + +let mkNestedValRef (cref: EntityRef) (v: Val) : ValRef = + match cref with + | ERefLocal _ -> mkLocalValRef v + | ERefNonLocal nlr -> + let key = v.GetLinkageFullKey() + mkNonLocalValRefPreResolved v nlr key + +/// From Ref_private to Ref_nonlocal when exporting data. +let rescopePubPathToParent viewedCcu (PubPath p) = NonLocalEntityRef(viewedCcu, p.[0..p.Length-2]) + +/// From Ref_private to Ref_nonlocal when exporting data. +let rescopePubPath viewedCcu (PubPath p) = NonLocalEntityRef(viewedCcu, p) + +//--------------------------------------------------------------------------- +// Equality between TAST items. +//--------------------------------------------------------------------------- + +let valRefInThisAssembly compilingFslib (x: ValRef) = + match x with + | VRefLocal _ -> true + | VRefNonLocal _ -> compilingFslib + +let tyconRefUsesLocalXmlDoc compilingFslib (x: TyconRef) = + match x with + | ERefLocal _ -> true + | ERefNonLocal _ -> +#if !NO_EXTENSIONTYPING + match x.TypeReprInfo with + | TProvidedTypeExtensionPoint _ -> true + | _ -> +#endif + compilingFslib + +let entityRefInThisAssembly compilingFslib (x: EntityRef) = + match x with + | ERefLocal _ -> true + | ERefNonLocal _ -> compilingFslib + +let arrayPathEq (y1: string[]) (y2: string[]) = + let len1 = y1.Length + let len2 = y2.Length + (len1 = len2) && + (let rec loop i = (i >= len1) || (y1.[i] = y2.[i] && loop (i+1)) + loop 0) + +let nonLocalRefEq (NonLocalEntityRef(x1, y1) as smr1) (NonLocalEntityRef(x2, y2) as smr2) = + smr1 === smr2 || (ccuEq x1 x2 && arrayPathEq y1 y2) + +/// This predicate tests if non-local resolution paths are definitely known to resolve +/// to different entities. All references with different named paths always resolve to +/// different entities. Two references with the same named paths may resolve to the same +/// entities even if they reference through different CCUs, because one reference +/// may be forwarded to another via a .NET TypeForwarder. +let nonLocalRefDefinitelyNotEq (NonLocalEntityRef(_, y1)) (NonLocalEntityRef(_, y2)) = + not (arrayPathEq y1 y2) + +let pubPathEq (PubPath path1) (PubPath path2) = arrayPathEq path1 path2 + +let fslibRefEq (nlr1: NonLocalEntityRef) (PubPath path2) = + arrayPathEq nlr1.Path path2 + +// Compare two EntityRef's for equality when compiling fslib (FSharp.Core.dll) +// +// Compiler-internal references to items in fslib are Ref_nonlocals even when compiling fslib. +// This breaks certain invariants that hold elsewhere, because they dereference to point to +// Entity's from signatures rather than Entity's from implementations. This means backup, alternative +// equality comparison techniques are needed when compiling fslib itself. +let fslibEntityRefEq fslibCcu (eref1: EntityRef) (eref2: EntityRef) = + match eref1, eref2 with + | (ERefNonLocal nlr1, ERefLocal x2) + | (ERefLocal x2, ERefNonLocal nlr1) -> + ccuEq nlr1.Ccu fslibCcu && + match x2.PublicPath with + | Some pp2 -> fslibRefEq nlr1 pp2 + | None -> false + | (ERefLocal e1, ERefLocal e2) -> + match e1.PublicPath, e2.PublicPath with + | Some pp1, Some pp2 -> pubPathEq pp1 pp2 + | _ -> false + | _ -> false + +// Compare two ValRef's for equality when compiling fslib (FSharp.Core.dll) +// +// Compiler-internal references to items in fslib are Ref_nonlocals even when compiling fslib. +// This breaks certain invariants that hold elsewhere, because they dereference to point to +// Val's from signatures rather than Val's from implementations. This means backup, alternative +// equality comparison techniques are needed when compiling fslib itself. +let fslibValRefEq fslibCcu vref1 vref2 = + match vref1, vref2 with + | (VRefNonLocal nlr1, VRefLocal x2) + | (VRefLocal x2, VRefNonLocal nlr1) -> + ccuEq nlr1.Ccu fslibCcu && + match x2.PublicPath with + | Some (ValPubPath(pp2, nm2)) -> + // Note: this next line is just comparing the values by name, and not even the partial linkage data + // This relies on the fact that the compiler doesn't use any references to + // entities in fslib that are overloaded, or, if they are overloaded, then value identity + // is not significant + nlr1.ItemKey.PartialKey = nm2.PartialKey && + fslibRefEq nlr1.EnclosingEntity.nlr pp2 + | _ -> + false + // Note: I suspect this private-to-private reference comparison is not needed + | (VRefLocal e1, VRefLocal e2) -> + match e1.PublicPath, e2.PublicPath with + | Some (ValPubPath(pp1, nm1)), Some (ValPubPath(pp2, nm2)) -> + pubPathEq pp1 pp2 && + (nm1 = nm2) + | _ -> false + | _ -> false + +/// Primitive routine to compare two EntityRef's for equality +/// This takes into account the possibility that they may have type forwarders +let primEntityRefEq compilingFslib fslibCcu (x: EntityRef) (y: EntityRef) = + x === y || + + if x.IsResolved && y.IsResolved && not compilingFslib then + x.ResolvedTarget === y.ResolvedTarget + elif not x.IsLocalRef && not y.IsLocalRef && + (// Two tcrefs with identical paths are always equal + nonLocalRefEq x.nlr y.nlr || + // The tcrefs may have forwarders. If they may possibly be equal then resolve them to get their canonical references + // and compare those using pointer equality. + (not (nonLocalRefDefinitelyNotEq x.nlr y.nlr) && + match x.TryDeref with + | ValueSome v1 -> match y.TryDeref with ValueSome v2 -> v1 === v2 | _ -> false + | _ -> match y.TryDeref with ValueNone -> true | _ -> false)) then + true + else + compilingFslib && fslibEntityRefEq fslibCcu x y + +/// Primitive routine to compare two UnionCaseRef's for equality +let primUnionCaseRefEq compilingFslib fslibCcu (UnionCaseRef(tcr1, c1) as uc1) (UnionCaseRef(tcr2, c2) as uc2) = + uc1 === uc2 || (primEntityRefEq compilingFslib fslibCcu tcr1 tcr2 && c1 = c2) + +/// Primitive routine to compare two ValRef's for equality. On the whole value identity is not particularly +/// significant in F#. However it is significant for +/// (a) Active Patterns +/// (b) detecting uses of "special known values" from FSharp.Core.dll, such as 'seq' +/// and quotation splicing +/// +/// Note this routine doesn't take type forwarding into account +let primValRefEq compilingFslib fslibCcu (x: ValRef) (y: ValRef) = + x === y || + if (x.IsResolved && y.IsResolved && x.ResolvedTarget === y.ResolvedTarget) || + (x.IsLocalRef && y.IsLocalRef && valEq x.ResolvedTarget y.ResolvedTarget) then + true + else + (// Use TryDeref to guard against the platforms/times when certain F# language features aren't available, + // e.g. CompactFramework doesn't have support for quotations. + match x.TryDeref with + | ValueSome v1 -> match y.TryDeref with ValueSome v2 -> v1 === v2 | _ -> false + | _ -> match y.TryDeref with ValueNone -> true | _ -> false) + || (if compilingFslib then fslibValRefEq fslibCcu x y else false) + +//--------------------------------------------------------------------------- +// pubpath/cpath mess +//--------------------------------------------------------------------------- + +let fullCompPathOfModuleOrNamespace (m: ModuleOrNamespace) = + let (CompPath(scoref, cpath)) = m.CompilationPath + CompPath(scoref, cpath@[(m.LogicalName, m.ModuleOrNamespaceType.ModuleOrNamespaceKind)]) + +// Can cpath2 be accessed given a right to access cpath1. That is, is cpath2 a nested type or namespace of cpath1. Note order of arguments. +let inline canAccessCompPathFrom (CompPath(scoref1, cpath1)) (CompPath(scoref2, cpath2)) = + let rec loop p1 p2 = + match p1, p2 with + | (a1, k1) :: rest1, (a2, k2) :: rest2 -> (a1=a2) && (k1=k2) && loop rest1 rest2 + | [], _ -> true + | _ -> false // cpath1 is longer + loop cpath1 cpath2 && + (scoref1 = scoref2) + +let canAccessFromOneOf cpaths cpathTest = + cpaths |> List.exists (fun cpath -> canAccessCompPathFrom cpath cpathTest) + +let canAccessFrom (TAccess x) cpath = + x |> List.forall (fun cpath1 -> canAccessCompPathFrom cpath1 cpath) + +let canAccessFromEverywhere (TAccess x) = x.IsEmpty +let canAccessFromSomewhere (TAccess _) = true +let isLessAccessible (TAccess aa) (TAccess bb) = + not (aa |> List.forall(fun a -> bb |> List.exists (fun b -> canAccessCompPathFrom a b))) + +/// Given (newPath, oldPath) replace oldPath by newPath in the TAccess. +let accessSubstPaths (newPath, oldPath) (TAccess paths) = + let subst cpath = if cpath=oldPath then newPath else cpath + TAccess (List.map subst paths) + +let compPathOfCcu (ccu: CcuThunk) = CompPath(ccu.ILScopeRef, []) +let taccessPublic = TAccess [] +let taccessPrivate accessPath = TAccess [accessPath] +let compPathInternal = CompPath(ILScopeRef.Local, []) +let taccessInternal = TAccess [compPathInternal] +let combineAccess (TAccess a1) (TAccess a2) = TAccess(a1@a2) + +exception Duplicate of string * string * range +exception NameClash of string * string * string * range * string * string * range + diff --git a/src/fcs-fable/src/fsharp/TastOps.fs b/src/fcs-fable/src/fsharp/TypedTreeOps.fs similarity index 89% rename from src/fcs-fable/src/fsharp/TastOps.fs rename to src/fcs-fable/src/fsharp/TypedTreeOps.fs index cb5050592d..89329bc2ba 100644 --- a/src/fcs-fable/src/fsharp/TastOps.fs +++ b/src/fcs-fable/src/fsharp/TypedTreeOps.fs @@ -1,27 +1,33 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. /// Defines derived expression manipulation and construction functions. -module internal FSharp.Compiler.Tastops +module internal FSharp.Compiler.TypedTreeOps open System.Collections.Generic open Internal.Utilities + +open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler.AbstractIL.Diagnostics open FSharp.Compiler.AbstractIL.Extensions.ILX open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler -open FSharp.Compiler.Range -open FSharp.Compiler.Rational -open FSharp.Compiler.Ast +open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Tast -open FSharp.Compiler.AbstractIL.Diagnostics -open FSharp.Compiler.Lib -open FSharp.Compiler.TcGlobals +open FSharp.Compiler.Features open FSharp.Compiler.Layout open FSharp.Compiler.Layout.TaggedTextOps +open FSharp.Compiler.Lib open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.Range +open FSharp.Compiler.Rational +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.XmlDoc #if !NO_EXTENSIONTYPING open FSharp.Compiler.ExtensionTyping #endif @@ -94,8 +100,14 @@ let emptyTyparInst = ([]: TyparInst) [] type Remap = { tpinst: TyparInst + + /// Values to remap valRemap: ValRemap + + /// TyconRefs to remap tyconRefRemap: TyconRefRemap + + /// Remove existing trait solutions? removeTraitSolutions: bool } let emptyRemap = @@ -122,7 +134,7 @@ let isRemapEmpty remap = let rec instTyparRef tpinst ty tp = match tpinst with | [] -> ty - | (tp', ty'):: t -> + | (tp', ty') :: t -> if typarEq tp tp' then ty' else instTyparRef t ty tp @@ -132,7 +144,7 @@ let instMeasureTyparRef tpinst unt (tp: Typar) = let rec loop tpinst = match tpinst with | [] -> unt - | (tp', ty'):: t -> + | (tp', ty') :: t -> if typarEq tp tp' then match ty' with | TType_measure unt -> unt @@ -147,8 +159,8 @@ let remapTyconRef (tcmap: TyconRefMap<_>) tcref = | Some tcref -> tcref | None -> tcref -let remapUnionCaseRef tcmap (UCRef(tcref, nm)) = UCRef(remapTyconRef tcmap tcref, nm) -let remapRecdFieldRef tcmap (RFRef(tcref, nm)) = RFRef(remapTyconRef tcmap tcref, nm) +let remapUnionCaseRef tcmap (UnionCaseRef(tcref, nm)) = UnionCaseRef(remapTyconRef tcmap tcref, nm) +let remapRecdFieldRef tcmap (RecdFieldRef(tcref, nm)) = RecdFieldRef(remapTyconRef tcmap tcref, nm) let mkTyparInst (typars: Typars) tyargs = #if CHECKED @@ -176,10 +188,10 @@ let rec remapTypeAux (tyenv: Remap) (ty: TType) = if tinst === tinst' then ty else TType_app (tcref, tinst') - | TType_ucase (UCRef(tcref, n), tinst) -> + | TType_ucase (UnionCaseRef(tcref, n), tinst) -> match tyenv.tyconRefRemap.TryFind tcref with - | Some tcref' -> TType_ucase (UCRef(tcref', n), remapTypesAux tyenv tinst) - | None -> TType_ucase (UCRef(tcref, n), remapTypesAux tyenv tinst) + | Some tcref' -> TType_ucase (UnionCaseRef(tcref', n), remapTypesAux tyenv tinst) + | None -> TType_ucase (UnionCaseRef(tcref, n), remapTypesAux tyenv tinst) | TType_anon (anonInfo, l) as ty -> let tupInfo' = remapTupInfoAux tyenv anonInfo.TupInfo @@ -241,19 +253,21 @@ and remapTyparConstraintsAux tyenv cs = Some(TyparConstraint.CoercesTo (remapTypeAux tyenv ty, m)) | TyparConstraint.MayResolveMember(traitInfo, m) -> Some(TyparConstraint.MayResolveMember (remapTraitAux tyenv traitInfo, m)) - | TyparConstraint.DefaultsTo(priority, ty, m) -> Some(TyparConstraint.DefaultsTo(priority, remapTypeAux tyenv ty, m)) + | TyparConstraint.DefaultsTo(priority, ty, m) -> + Some(TyparConstraint.DefaultsTo(priority, remapTypeAux tyenv ty, m)) | TyparConstraint.IsEnum(uty, m) -> Some(TyparConstraint.IsEnum(remapTypeAux tyenv uty, m)) | TyparConstraint.IsDelegate(uty1, uty2, m) -> Some(TyparConstraint.IsDelegate(remapTypeAux tyenv uty1, remapTypeAux tyenv uty2, m)) - | TyparConstraint.SimpleChoice(tys, m) -> Some(TyparConstraint.SimpleChoice(remapTypesAux tyenv tys, m)) + | TyparConstraint.SimpleChoice(tys, m) -> + Some(TyparConstraint.SimpleChoice(remapTypesAux tyenv tys, m)) | TyparConstraint.SupportsComparison _ | TyparConstraint.SupportsEquality _ | TyparConstraint.SupportsNull _ | TyparConstraint.IsUnmanaged _ | TyparConstraint.IsNonNullableStruct _ | TyparConstraint.IsReferenceType _ - | TyparConstraint.RequiresDefaultConstructor _ -> Some(x)) + | TyparConstraint.RequiresDefaultConstructor _ -> Some x) and remapTraitAux tyenv (TTrait(tys, nm, mf, argtys, rty, slnCell)) = let slnCell = @@ -396,7 +410,7 @@ let mkTyconInst (tycon: Tycon) tinst = mkTyparInst tycon.TyparsNoRange tinst let mkTyconRefInst (tcref: TyconRef) tinst = mkTyconInst tcref.Deref tinst //--------------------------------------------------------------------------- -// Basic equalites +// Basic equalities //--------------------------------------------------------------------------- let tyconRefEq (g: TcGlobals) tcref1 tcref2 = primEntityRefEq g.compilingFslib g.fslibCcu tcref1 tcref2 @@ -456,7 +470,7 @@ let rec MeasureVarExponent tp unt = let ListMeasureVarOccs unt = let rec gather acc unt = match stripUnitEqnsFromMeasure unt with - | Measure.Var tp -> if List.exists (typarEq tp) acc then acc else tp:: acc + | Measure.Var tp -> if List.exists (typarEq tp) acc then acc else tp :: acc | Measure.Prod(unt1, unt2) -> gather (gather acc unt1) unt2 | Measure.RationalPower(unt', _) -> gather acc unt' | Measure.Inv unt' -> gather acc unt' @@ -471,7 +485,7 @@ let ListMeasureVarOccsWithNonZeroExponents untexpr = if List.exists (fun (tp', _) -> typarEq tp tp') acc then acc else let e = MeasureVarExponent tp untexpr - if e = ZeroRational then acc else (tp, e):: acc + if e = ZeroRational then acc else (tp, e) :: acc | Measure.Prod(unt1, unt2) -> gather (gather acc unt1) unt2 | Measure.Inv unt' -> gather acc unt' | Measure.RationalPower(unt', _) -> gather acc unt' @@ -485,7 +499,7 @@ let ListMeasureConOccsWithNonZeroExponents g eraseAbbrevs untexpr = | Measure.Con c -> if List.exists (fun (c', _) -> tyconRefEq g c c') acc then acc else let e = MeasureExprConExponent g eraseAbbrevs c untexpr - if e = ZeroRational then acc else (c, e):: acc + if e = ZeroRational then acc else (c, e) :: acc | Measure.Prod(unt1, unt2) -> gather (gather acc unt1) unt2 | Measure.Inv unt' -> gather acc unt' | Measure.RationalPower(unt', _) -> gather acc unt' @@ -497,7 +511,7 @@ let ListMeasureConOccsWithNonZeroExponents g eraseAbbrevs untexpr = let ListMeasureConOccsAfterRemapping g r unt = let rec gather acc unt = match stripUnitEqnsFromMeasure unt with - | Measure.Con c -> if List.exists (tyconRefEq g (r c)) acc then acc else r c:: acc + | Measure.Con c -> if List.exists (tyconRefEq g (r c)) acc then acc else r c :: acc | Measure.Prod(unt1, unt2) -> gather (gather acc unt1) unt2 | Measure.RationalPower(unt', _) -> gather acc unt' | Measure.Inv unt' -> gather acc unt' @@ -521,7 +535,7 @@ let MeasureProdOpt m1 m2 = let ProdMeasures ms = match ms with | [] -> Measure.One - | m:: ms -> List.foldBack MeasureProdOpt ms m + | m :: ms -> List.foldBack MeasureProdOpt ms m let isDimensionless g tyarg = match stripTyparEqns tyarg with @@ -610,7 +624,7 @@ let mkByrefTyWithInference (g: TcGlobals) ty1 ty2 = let mkArrayTy (g: TcGlobals) rank ty m = if rank < 1 || rank > 32 then - errorR(Error(FSComp.SR.tastopsMaxArrayThirtyTwo(rank), m)) + errorR(Error(FSComp.SR.tastopsMaxArrayThirtyTwo rank, m)) TType_app (g.il_arr_tcr_map.[3], [ty]) else TType_app (g.il_arr_tcr_map.[rank - 1], [ty]) @@ -720,7 +734,7 @@ let rec stripTyEqnsA g canShortcut ty = | Some abbrevTy -> stripTyEqnsA g canShortcut (applyTyconAbbrev abbrevTy tycon tinst) | None -> - // This is the point where we get to add additional coditional normalizing equations + // This is the point where we get to add additional conditional normalizing equations // into the type system. Such power! // // Add the equation byref<'T> = byref<'T, ByRefKinds.InOut> for when using sufficient FSharp.Core @@ -817,7 +831,7 @@ let tcrefOfAppTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> let argsOfAppTy g ty = ty |> stripTyEqns g |> (function TType_app(_, tinst) -> tinst | _ -> []) let tryDestTyparTy g ty = ty |> stripTyEqns g |> (function TType_var v -> ValueSome v | _ -> ValueNone) let tryDestFunTy g ty = ty |> stripTyEqns g |> (function TType_fun (tyv, tau) -> ValueSome(tyv, tau) | _ -> ValueNone) -let tryDestAppTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> ValueSome tcref | _ -> ValueNone) +let tryTcrefOfAppTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> ValueSome tcref | _ -> ValueNone) let tryDestAnonRecdTy g ty = ty |> stripTyEqns g |> (function TType_anon (anonInfo, tys) -> ValueSome (anonInfo, tys) | _ -> ValueNone) let tryAnyParTy g ty = ty |> stripTyEqns g |> (function TType_var v -> ValueSome v | TType_measure unt when isUnitParMeasure g unt -> ValueSome(destUnitParMeasure g unt) | _ -> ValueNone) @@ -839,16 +853,6 @@ let tryNiceEntityRefOfTyOption ty = | TType_app (tcref, _) -> Some tcref | TType_measure (Measure.Con tcref) -> Some tcref | _ -> None - -let (|NullableTy|_|) g ty = - match tryAppTy g ty with - | ValueSome (tcref, [tyarg]) when tyconRefEq g tcref g.system_Nullable_tcref -> Some tyarg - | _ -> None - -let (|StripNullableTy|) g ty = - match tryAppTy g ty with - | ValueSome (tcref, [tyarg]) when tyconRefEq g tcref g.system_Nullable_tcref -> tyarg - | _ -> ty let mkInstForAppTy g ty = match tryAppTy g ty with @@ -898,7 +902,9 @@ type TypeEquivEnv with static member FromEquivTypars tps1 tps2 = TypeEquivEnv.Empty.BindEquivTypars tps1 tps2 -let rec traitsAEquivAux erasureFlag g aenv (TTrait(tys1, nm, mf1, argtys, rty, _)) (TTrait(tys2, nm2, mf2, argtys2, rty2, _)) = +let rec traitsAEquivAux erasureFlag g aenv traitInfo1 traitInfo2 = + let (TTrait(tys1, nm, mf1, argtys, rty, _)) = traitInfo1 + let (TTrait(tys2, nm2, mf2, argtys2, rty2, _)) = traitInfo2 mf1 = mf2 && nm = nm2 && ListSet.equals (typeAEquivAux erasureFlag g aenv) tys1 tys2 && @@ -918,7 +924,7 @@ and typarConstraintsAEquivAux erasureFlag g aenv tpc1 tpc2 = TyparConstraint.CoercesTo(fcty, _) -> typeAEquivAux erasureFlag g aenv acty fcty - | TyparConstraint.MayResolveMember(trait1, _), + | TyparConstraint.MayResolveMember(trait1, _), TyparConstraint.MayResolveMember(trait2, _) -> traitsAEquivAux erasureFlag g aenv trait1 trait2 @@ -973,7 +979,7 @@ and typeAEquivAux erasureFlag g aenv ty1 ty2 = | TType_app (tc1, b1), TType_app (tc2, b2) -> tcrefAEquiv g aenv tc1 tc2 && typesAEquivAux erasureFlag g aenv b1 b2 - | TType_ucase (UCRef(tc1, n1), b1), TType_ucase (UCRef(tc2, n2), b2) -> + | TType_ucase (UnionCaseRef(tc1, n1), b1), TType_ucase (UnionCaseRef(tc2, n2), b2) -> n1=n2 && tcrefAEquiv g aenv tc1 tc2 && typesAEquivAux erasureFlag g aenv b1 b2 @@ -1058,14 +1064,14 @@ let valOrder = { new IComparer with member __.Compare(v1, v2) = compare v1. let tyconOrder = { new IComparer with member __.Compare(tc1, tc2) = compare tc1.Stamp tc2.Stamp } let recdFieldRefOrder = { new IComparer with - member __.Compare(RFRef(tcref1, nm1), RFRef(tcref2, nm2)) = + member __.Compare(RecdFieldRef(tcref1, nm1), RecdFieldRef(tcref2, nm2)) = let c = tyconOrder.Compare (tcref1.Deref, tcref2.Deref) if c <> 0 then c else compare nm1 nm2 } let unionCaseRefOrder = { new IComparer with - member __.Compare(UCRef(tcref1, nm1), UCRef(tcref2, nm2)) = + member __.Compare(UnionCaseRef(tcref1, nm1), UnionCaseRef(tcref2, nm2)) = let c = tyconOrder.Compare (tcref1.Deref, tcref2.Deref) if c <> 0 then c else compare nm1 nm2 } @@ -1105,13 +1111,15 @@ let ensureCcuHasModuleOrNamespaceAtPath (ccu: CcuThunk) path (CompPath(_, cpath) let rec loop prior_cpath (path: Ident list) cpath (modul: ModuleOrNamespace) = let mtype = modul.ModuleOrNamespaceType match path, cpath with - | (hpath:: tpath), ((_, mkind):: tcpath) -> + | (hpath :: tpath), ((_, mkind) :: tcpath) -> let modName = hpath.idText if not (Map.containsKey modName mtype.AllEntitiesByCompiledAndLogicalMangledNames) then - let smodul = NewModuleOrNamespace (Some(CompPath(scoref, prior_cpath))) taccessPublic hpath xml [] (MaybeLazy.Strict (NewEmptyModuleOrNamespaceType mkind)) - mtype.AddModuleOrNamespaceByMutation(smodul) + let mty = Construct.NewEmptyModuleOrNamespaceType mkind + let cpath = CompPath(scoref, prior_cpath) + let smodul = Construct.NewModuleOrNamespace (Some cpath) taccessPublic hpath xml [] (MaybeLazy.Strict mty) + mtype.AddModuleOrNamespaceByMutation smodul let modul = Map.find modName mtype.AllEntitiesByCompiledAndLogicalMangledNames - loop (prior_cpath@[(modName, Namespace)]) tpath tcpath modul + loop (prior_cpath @ [(modName, Namespace)]) tpath tcpath modul | _ -> () @@ -1140,10 +1148,10 @@ let tryDestRefTupleExpr e = match e with Expr.Op (TOp.Tuple tupInfo, _, es, _) w let rec rangeOfExpr x = match x with | Expr.Val (_, _, m) | Expr.Op (_, _, _, m) | Expr.Const (_, m, _) | Expr.Quote (_, _, _, m, _) - | Expr.Obj (_, _, _, _, _, _, m) | Expr.App(_, _, _, _, m) | Expr.Sequential (_, _, _, _, m) + | Expr.Obj (_, _, _, _, _, _, m) | Expr.App (_, _, _, _, m) | Expr.Sequential (_, _, _, _, m) | Expr.StaticOptimization (_, _, _, m) | Expr.Lambda (_, _, _, _, _, m, _) | Expr.TyLambda (_, _, _, m, _)| Expr.TyChoose (_, _, m) | Expr.LetRec (_, _, m, _) | Expr.Let (_, _, m, _) | Expr.Match (_, _, _, _, m, _) -> m - | Expr.Link(eref) -> rangeOfExpr (!eref) + | Expr.Link eref -> rangeOfExpr (!eref) type Expr with member x.Range = rangeOfExpr x @@ -1158,7 +1166,7 @@ let primMkMatch(spBind, exprm, tree, targets, matchm, ty) = Expr.Match (spBind, type MatchBuilder(spBind, inpRange: Range.range) = let targets = new ResizeArray<_>(10) - member x.AddTarget(tg) = + member x.AddTarget tg = let n = targets.Count targets.Add tg n @@ -1169,7 +1177,7 @@ type MatchBuilder(spBind, inpRange: Range.range) = member x.Close(dtree, m, ty) = primMkMatch (spBind, inpRange, dtree, targets.ToArray(), m, ty) -let mkBoolSwitch m g t e = TDSwitch(g, [TCase(DecisionTreeTest.Const(Const.Bool(true)), t)], Some e, m) +let mkBoolSwitch m g t e = TDSwitch(g, [TCase(DecisionTreeTest.Const(Const.Bool true), t)], Some e, m) let primMkCond spBind spTarget1 spTarget2 m ty e1 e2 e3 = let mbuilder = new MatchBuilder(spBind, m) @@ -1183,10 +1191,10 @@ let mkCond spBind spTarget m ty e1 e2 e3 = primMkCond spBind spTarget spTarget m // Primitive constructors //--------------------------------------------------------------------------- -let exprForValRef m vref = Expr.Val(vref, NormalValUse, m) +let exprForValRef m vref = Expr.Val (vref, NormalValUse, m) let exprForVal m v = exprForValRef m (mkLocalValRef v) let mkLocalAux m s ty mut compgen = - let thisv = NewVal(s, m, None, ty, mut, compgen, None, taccessPublic, ValNotInRecScope, None, NormalVal, [], ValInline.Optional, XmlDoc.Empty, false, false, false, false, false, false, None, ParentNone) + let thisv = Construct.NewVal(s, m, None, ty, mut, compgen, None, taccessPublic, ValNotInRecScope, None, NormalVal, [], ValInline.Optional, XmlDoc.Empty, false, false, false, false, false, false, None, ParentNone) thisv, exprForVal m thisv let mkLocal m s ty = mkLocalAux m s ty Immutable false @@ -1220,7 +1228,7 @@ let mkMemberLambdas m tps ctorThisValOpt baseValOpt vsl (b, rty) = | _ -> match vsl with | [] -> error(InternalError("mk_basev_multi_lambdas_core: can't attach a basev to a non-lambda expression", m)) - | h:: t -> + | h :: t -> let b, rty = mkMultiLambdasCore m t (b, rty) (rebuildLambda m ctorThisValOpt baseValOpt h (b, rty), (typeOfLambdaArg m h --> rty)) mkTypeLambda m tps expr @@ -1230,25 +1238,29 @@ let mkMultiLambdaBind v letSeqPtOpt m tps vsl (b, rty) = let mkBind seqPtOpt v e = TBind(v, e, seqPtOpt) -let mkLetBind m bind body = Expr.Let(bind, body, m, NewFreeVarsCache()) +let mkLetBind m bind body = Expr.Let (bind, body, m, Construct.NewFreeVarsCache()) let mkLetsBind m binds body = List.foldBack (mkLetBind m) binds body let mkLetsFromBindings m binds body = List.foldBack (mkLetBind m) binds body let mkLet seqPtOpt m v x body = mkLetBind m (mkBind seqPtOpt v x) body /// Make sticky bindings that are compiler generated (though the variables may not be - e.g. they may be lambda arguments in a beta reduction) -let mkCompGenBind v e = TBind(v, e, NoSequencePointAtStickyBinding) +let mkCompGenBind v e = TBind(v, e, NoDebugPointAtStickyBinding) let mkCompGenBinds (vs: Val list) (es: Expr list) = List.map2 mkCompGenBind vs es let mkCompGenLet m v x body = mkLetBind m (mkCompGenBind v x) body let mkCompGenLets m vs xs body = mkLetsBind m (mkCompGenBinds vs xs) body let mkCompGenLetsFromBindings m vs xs body = mkLetsFromBindings m (mkCompGenBinds vs xs) body -let mkInvisibleBind v e = TBind(v, e, NoSequencePointAtInvisibleBinding) +let mkInvisibleBind v e = TBind(v, e, NoDebugPointAtInvisibleBinding) let mkInvisibleBinds (vs: Val list) (es: Expr list) = List.map2 mkInvisibleBind vs es let mkInvisibleLet m v x body = mkLetBind m (mkInvisibleBind v x) body let mkInvisibleLets m vs xs body = mkLetsBind m (mkInvisibleBinds vs xs) body let mkInvisibleLetsFromBindings m vs xs body = mkLetsFromBindings m (mkInvisibleBinds vs xs) body -let mkLetRecBinds m binds body = if isNil binds then body else Expr.LetRec(binds, body, m, NewFreeVarsCache()) +let mkLetRecBinds m binds body = + if isNil binds then + body + else + Expr.LetRec (binds, body, m, Construct.NewFreeVarsCache()) //------------------------------------------------------------------------- // Type schemes... @@ -1297,53 +1309,54 @@ let isBeingGeneralized tp typeScheme = // Build conditional expressions... //------------------------------------------------------------------------- -let mkLazyAnd (g: TcGlobals) m e1 e2 = mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.bool_ty e1 e2 (Expr.Const(Const.Bool false, m, g.bool_ty)) -let mkLazyOr (g: TcGlobals) m e1 e2 = mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.bool_ty e1 (Expr.Const(Const.Bool true, m, g.bool_ty)) e2 +let mkLazyAnd (g: TcGlobals) m e1 e2 = mkCond NoDebugPointAtStickyBinding DebugPointForTarget.No m g.bool_ty e1 e2 (Expr.Const (Const.Bool false, m, g.bool_ty)) +let mkLazyOr (g: TcGlobals) m e1 e2 = mkCond NoDebugPointAtStickyBinding DebugPointForTarget.No m g.bool_ty e1 (Expr.Const (Const.Bool true, m, g.bool_ty)) e2 let mkCoerceExpr(e, to_ty, m, from_ty) = Expr.Op (TOp.Coerce, [to_ty;from_ty], [e], m) -let mkAsmExpr(code, tinst, args, rettys, m) = Expr.Op (TOp.ILAsm(code, rettys), tinst, args, m) +let mkAsmExpr (code, tinst, args, rettys, m) = Expr.Op (TOp.ILAsm (code, rettys), tinst, args, m) let mkUnionCaseExpr(uc, tinst, args, m) = Expr.Op (TOp.UnionCase uc, tinst, args, m) let mkExnExpr(uc, args, m) = Expr.Op (TOp.ExnConstr uc, [], args, m) -let mkTupleFieldGetViaExprAddr(tupInfo, e, tinst, i, m) = Expr.Op (TOp.TupleFieldGet(tupInfo, i), tinst, [e], m) -let mkAnonRecdFieldGetViaExprAddr(anonInfo, e, tinst, i, m) = Expr.Op (TOp.AnonRecdGet(anonInfo, i), tinst, [e], m) +let mkTupleFieldGetViaExprAddr(tupInfo, e, tinst, i, m) = Expr.Op (TOp.TupleFieldGet (tupInfo, i), tinst, [e], m) +let mkAnonRecdFieldGetViaExprAddr(anonInfo, e, tinst, i, m) = Expr.Op (TOp.AnonRecdGet (anonInfo, i), tinst, [e], m) -let mkRecdFieldGetViaExprAddr(e, fref, tinst, m) = Expr.Op (TOp.ValFieldGet(fref), tinst, [e], m) -let mkRecdFieldGetAddrViaExprAddr(readonly, e, fref, tinst, m) = Expr.Op (TOp.ValFieldGetAddr(fref, readonly), tinst, [e], m) +let mkRecdFieldGetViaExprAddr (e, fref, tinst, m) = Expr.Op (TOp.ValFieldGet fref, tinst, [e], m) +let mkRecdFieldGetAddrViaExprAddr(readonly, e, fref, tinst, m) = Expr.Op (TOp.ValFieldGetAddr (fref, readonly), tinst, [e], m) -let mkStaticRecdFieldGetAddr(readonly, fref, tinst, m) = Expr.Op (TOp.ValFieldGetAddr(fref, readonly), tinst, [], m) -let mkStaticRecdFieldGet(fref, tinst, m) = Expr.Op (TOp.ValFieldGet(fref), tinst, [], m) -let mkStaticRecdFieldSet(fref, tinst, e, m) = Expr.Op (TOp.ValFieldSet(fref), tinst, [e], m) +let mkStaticRecdFieldGetAddr(readonly, fref, tinst, m) = Expr.Op (TOp.ValFieldGetAddr (fref, readonly), tinst, [], m) +let mkStaticRecdFieldGet (fref, tinst, m) = Expr.Op (TOp.ValFieldGet fref, tinst, [], m) +let mkStaticRecdFieldSet(fref, tinst, e, m) = Expr.Op (TOp.ValFieldSet fref, tinst, [e], m) let mkArrayElemAddress g (readonly, ilInstrReadOnlyAnnotation, isNativePtr, shape, elemTy, exprs, m) = Expr.Op (TOp.ILAsm ([IL.I_ldelema(ilInstrReadOnlyAnnotation, isNativePtr, shape, mkILTyvarTy 0us)], [mkByrefTyWithFlag g readonly elemTy]), [elemTy], exprs, m) -let mkRecdFieldSetViaExprAddr (e1, fref, tinst, e2, m) = Expr.Op (TOp.ValFieldSet(fref), tinst, [e1;e2], m) +let mkRecdFieldSetViaExprAddr (e1, fref, tinst, e2, m) = Expr.Op (TOp.ValFieldSet fref, tinst, [e1;e2], m) -let mkUnionCaseTagGetViaExprAddr (e1, cref, tinst, m) = Expr.Op (TOp.UnionCaseTagGet(cref), tinst, [e1], m) +let mkUnionCaseTagGetViaExprAddr (e1, cref, tinst, m) = Expr.Op (TOp.UnionCaseTagGet cref, tinst, [e1], m) /// Make a 'TOp.UnionCaseProof' expression, which proves a union value is over a particular case (used only for ref-unions, not struct-unions) -let mkUnionCaseProof (e1, cref: UnionCaseRef, tinst, m) = if cref.Tycon.IsStructOrEnumTycon then e1 else Expr.Op (TOp.UnionCaseProof(cref), tinst, [e1], m) +let mkUnionCaseProof (e1, cref: UnionCaseRef, tinst, m) = if cref.Tycon.IsStructOrEnumTycon then e1 else Expr.Op (TOp.UnionCaseProof cref, tinst, [e1], m) /// Build a 'TOp.UnionCaseFieldGet' expression for something we've already determined to be a particular union case. For ref-unions, /// the input expression has 'TType_ucase', which is an F# compiler internal "type" corresponding to the union case. For struct-unions, /// the input should be the address of the expression. -let mkUnionCaseFieldGetProvenViaExprAddr (e1, cref, tinst, j, m) = Expr.Op (TOp.UnionCaseFieldGet(cref, j), tinst, [e1], m) +let mkUnionCaseFieldGetProvenViaExprAddr (e1, cref, tinst, j, m) = Expr.Op (TOp.UnionCaseFieldGet (cref, j), tinst, [e1], m) /// Build a 'TOp.UnionCaseFieldGetAddr' expression for a field of a union when we've already determined the value to be a particular union case. For ref-unions, /// the input expression has 'TType_ucase', which is an F# compiler internal "type" corresponding to the union case. For struct-unions, /// the input should be the address of the expression. -let mkUnionCaseFieldGetAddrProvenViaExprAddr (readonly, e1, cref, tinst, j, m) = Expr.Op (TOp.UnionCaseFieldGetAddr(cref, j, readonly), tinst, [e1], m) +let mkUnionCaseFieldGetAddrProvenViaExprAddr (readonly, e1, cref, tinst, j, m) = Expr.Op (TOp.UnionCaseFieldGetAddr (cref, j, readonly), tinst, [e1], m) /// Build a 'get' expression for something we've already determined to be a particular union case, but where /// the static type of the input is not yet proven to be that particular union case. This requires a type /// cast to 'prove' the condition. -let mkUnionCaseFieldGetUnprovenViaExprAddr (e1, cref, tinst, j, m) = mkUnionCaseFieldGetProvenViaExprAddr(mkUnionCaseProof(e1, cref, tinst, m), cref, tinst, j, m) +let mkUnionCaseFieldGetUnprovenViaExprAddr (e1, cref, tinst, j, m) = mkUnionCaseFieldGetProvenViaExprAddr (mkUnionCaseProof(e1, cref, tinst, m), cref, tinst, j, m) + +let mkUnionCaseFieldSet (e1, cref, tinst, j, e2, m) = Expr.Op (TOp.UnionCaseFieldSet (cref, j), tinst, [e1;e2], m) -let mkUnionCaseFieldSet (e1, cref, tinst, j, e2, m) = Expr.Op (TOp.UnionCaseFieldSet(cref, j), tinst, [e1;e2], m) +let mkExnCaseFieldGet (e1, ecref, j, m) = Expr.Op (TOp.ExnFieldGet (ecref, j), [], [e1], m) -let mkExnCaseFieldGet (e1, ecref, j, m) = Expr.Op (TOp.ExnFieldGet(ecref, j), [], [e1], m) -let mkExnCaseFieldSet (e1, ecref, j, e2, m) = Expr.Op (TOp.ExnFieldSet(ecref, j), [], [e1;e2], m) +let mkExnCaseFieldSet (e1, ecref, j, e2, m) = Expr.Op (TOp.ExnFieldSet (ecref, j), [], [e1;e2], m) let mkDummyLambda (g: TcGlobals) (e: Expr, ety) = let m = e.Range @@ -1356,12 +1369,12 @@ let mkFor (g: TcGlobals) (spFor, v, e1, dir, e2, e3: Expr, m) = Expr.Op (TOp.For (spFor, dir), [], [mkDummyLambda g (e1, g.int_ty) ;mkDummyLambda g (e2, g.int_ty);mkLambda e3.Range v (e3, g.unit_ty)], m) let mkTryWith g (e1, vf, ef: Expr, vh, eh: Expr, m, ty, spTry, spWith) = - Expr.Op (TOp.TryCatch(spTry, spWith), [ty], [mkDummyLambda g (e1, ty);mkLambda ef.Range vf (ef, ty);mkLambda eh.Range vh (eh, ty)], m) + Expr.Op (TOp.TryCatch (spTry, spWith), [ty], [mkDummyLambda g (e1, ty);mkLambda ef.Range vf (ef, ty);mkLambda eh.Range vh (eh, ty)], m) let mkTryFinally (g: TcGlobals) (e1, e2, m, ty, spTry, spFinally) = - Expr.Op (TOp.TryFinally(spTry, spFinally), [ty], [mkDummyLambda g (e1, ty);mkDummyLambda g (e2, g.unit_ty)], m) + Expr.Op (TOp.TryFinally (spTry, spFinally), [ty], [mkDummyLambda g (e1, ty);mkDummyLambda g (e2, g.unit_ty)], m) -let mkDefault (m, ty) = Expr.Const(Const.Zero, m, ty) +let mkDefault (m, ty) = Expr.Const (Const.Zero, m, ty) let mkValSet m v e = Expr.Op (TOp.LValueOp (LSet, v), [], [e], m) let mkAddrSet m v e = Expr.Op (TOp.LValueOp (LByrefSet, v), [], [e], m) @@ -1481,7 +1494,7 @@ let actualTyOfRecdFieldRef (fref: RecdFieldRef) tinst = actualTyOfRecdFieldForTycon fref.Tycon tinst fref.RecdField let actualTyOfUnionFieldRef (fref: UnionCaseRef) n tinst = - actualTyOfRecdFieldForTycon fref.Tycon tinst (fref.FieldByIndex(n)) + actualTyOfRecdFieldForTycon fref.Tycon tinst (fref.FieldByIndex n) //--------------------------------------------------------------------------- @@ -1502,7 +1515,7 @@ let rec stripFunTy g ty = if isFunTy g ty then let (d, r) = destFunTy g ty let more, rty = stripFunTy g r - d:: more, rty + d :: more, rty else [], ty let applyForallTy g ty tyargs = @@ -1530,7 +1543,7 @@ let rec stripFunTyN g n ty = assert (n >= 0) if n > 0 && isFunTy g ty then let (d, r) = destFunTy g ty - let more, rty = stripFunTyN g (n-1) r in d:: more, rty + let more, rty = stripFunTyN g (n-1) r in d :: more, rty else [], ty @@ -1706,17 +1719,17 @@ let isFSharpObjModelRefTy g ty = | TTyconStruct | TTyconEnum -> false let isFSharpClassTy g ty = - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref -> tcref.Deref.IsFSharpClassTycon | _ -> false let isFSharpStructTy g ty = - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref -> tcref.Deref.IsFSharpStructOrEnumTycon | _ -> false let isFSharpInterfaceTy g ty = - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref -> tcref.Deref.IsFSharpInterfaceTycon | _ -> false @@ -1727,7 +1740,7 @@ let isDelegateTy g ty = #endif | ILTypeMetadata (TILObjectReprData(_, _, td)) -> td.IsDelegate | FSharpOrArrayOrByrefOrTupleOrExnTypeMetadata -> - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref -> tcref.Deref.IsFSharpDelegateTycon | _ -> false @@ -1748,20 +1761,23 @@ let isClassTy g ty = | FSharpOrArrayOrByrefOrTupleOrExnTypeMetadata -> isFSharpClassTy g ty let isStructOrEnumTyconTy g ty = - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref -> tcref.Deref.IsStructOrEnumTycon | _ -> false let isStructRecordOrUnionTyconTy g ty = - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref -> tcref.Deref.IsStructRecordOrUnionTycon | _ -> false +let isStructTyconRef (tcref: TyconRef) = + let tycon = tcref.Deref + tycon.IsStructRecordOrUnionTycon || tycon.IsStructOrEnumTycon + let isStructTy g ty = - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref -> - let tycon = tcref.Deref - tycon.IsStructRecordOrUnionTycon || tycon.IsStructOrEnumTycon + isStructTyconRef tcref | _ -> isStructAnonRecdTy g ty || isStructTupleTy g ty @@ -1775,7 +1791,8 @@ let isRefTy g ty = isFunTy g ty || isReprHiddenTy g ty || isFSharpObjModelRefTy g ty || - isUnitTy g ty + isUnitTy g ty || + (isAnonRecdTy g ty && not (isStructAnonRecdTy g ty)) ) // ECMA C# LANGUAGE SPECIFICATION, 27.2 @@ -1789,7 +1806,7 @@ let isRefTy g ty = // [Note: Constructed types and type-parameters are never unmanaged-types. end note] let rec isUnmanagedTy g ty = let ty = stripTyEqnsAndMeasureEqns g ty - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref -> let isEq tcref2 = tyconRefEq g tcref tcref2 if isEq g.nativeptr_tcr || isEq g.nativeint_tcr || @@ -1821,7 +1838,7 @@ let isInterfaceTycon x = let isInterfaceTyconRef (tcref: TyconRef) = isInterfaceTycon tcref.Deref let isEnumTy g ty = - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueNone -> false | ValueSome tcref -> tcref.IsEnumTycon @@ -2002,7 +2019,7 @@ let accFreeLocalTycon opts x acc = let accFreeTycon opts (tcref: TyconRef) acc = if not opts.includeLocalTycons then acc - elif tcref.IsLocalRef then accFreeLocalTycon opts tcref.PrivateTarget acc + elif tcref.IsLocalRef then accFreeLocalTycon opts tcref.ResolvedTarget acc else acc let rec boundTypars opts tps acc = @@ -2058,7 +2075,7 @@ and accFreeLocalValInTraitSln _opts v fvs = and accFreeValRefInTraitSln opts (vref: ValRef) fvs = if vref.IsLocalRef then - accFreeLocalValInTraitSln opts vref.PrivateTarget fvs + accFreeLocalValInTraitSln opts vref.ResolvedTarget fvs else // non-local values do not contain free variables fvs @@ -2080,7 +2097,7 @@ and accFreeInType opts ty acc = | [] -> acc // optimization to avoid unneeded call | [h] -> accFreeInType opts h acc // optimization to avoid unneeded call | _ -> accFreeInTypes opts tinst acc - | TType_ucase (UCRef(tc, _), tinst) -> accFreeInTypes opts tinst (accFreeTycon opts tc acc) + | TType_ucase (UnionCaseRef(tc, _), tinst) -> accFreeInTypes opts tinst (accFreeTycon opts tc acc) | TType_fun (d, r) -> accFreeInType opts d (accFreeInType opts r acc) | TType_var r -> accFreeTyparRef opts r acc | TType_forall (tps, r) -> unionFreeTyvars (boundTypars opts tps (freeInType opts r)) acc @@ -2227,7 +2244,7 @@ let GetMemberTypeInFSharpForm g memberFlags arities ty m = | [] -> errorR(InternalError("value does not have a valid member type", m)) argInfos - | _:: t -> t + | _ :: t -> t else argInfos tps, argInfos, rty, retInfo @@ -2406,7 +2423,7 @@ type TyparConstraintsWithTypars = (Typar * TyparConstraint) list module PrettyTypes = let newPrettyTypar (tp: Typar) nm = - NewTypar (tp.Kind, tp.Rigidity, Typar(ident(nm, tp.Range), tp.StaticReq, false), false, TyparDynamicReq.Yes, [], false, false) + Construct.NewTypar (tp.Kind, tp.Rigidity, Typar(ident(nm, tp.Range), tp.StaticReq, false), false, TyparDynamicReq.Yes, [], false, false) let NewPrettyTypars renaming tps names = let niceTypars = List.map2 newPrettyTypar tps names @@ -2428,16 +2445,16 @@ module PrettyTypes = let rec choose (tps: Typar list) (typeIndex, measureIndex) acc = match tps with | [] -> List.rev acc - | tp:: tps -> + | tp :: tps -> // Use a particular name, possibly after incrementing indexes let useThisName (nm, typeIndex, measureIndex) = - choose tps (typeIndex, measureIndex) (nm:: acc) + choose tps (typeIndex, measureIndex) (nm :: acc) // Give up, try again with incremented indexes let tryAgain (typeIndex, measureIndex) = - choose (tp:: tps) (typeIndex, measureIndex) acc + choose (tp :: tps) (typeIndex, measureIndex) acc let tryName (nm, typeIndex, measureIndex) f = if List.contains nm alreadyInUse then @@ -2484,8 +2501,6 @@ module PrettyTypes = computeKeep keep (tp :: change) rest let keep, change = computeKeep [] [] ftps - // change |> List.iter (fun tp -> dprintf "change typar: %s %s %d\n" tp.Name (tp.DisplayName) (stamp_of_typar tp)) - // keep |> List.iter (fun tp -> dprintf "keep typar: %s %s %d\n" tp.Name (tp.DisplayName) (stamp_of_typar tp)) let alreadyInUse = keep |> List.map (fun x -> x.Name) let names = PrettyTyparNames (fun x -> List.memq x change) alreadyInUse ftps @@ -2499,7 +2514,6 @@ module PrettyTypes = let tauThings = mapTys getTauStayTau things let prettyThings = mapTys (instType renaming) tauThings - // niceTypars |> List.iter (fun tp -> dprintf "nice typar: %d\n" (stamp_of_typar tp)); * let tpconstraints = niceTypars |> List.collect (fun tpnice -> List.map (fun tpc -> tpnice, tpc) tpnice.Constraints) prettyThings, tpconstraints @@ -2507,6 +2521,11 @@ module PrettyTypes = let PrettifyType g x = PrettifyThings g id id x let PrettifyTypePair g x = PrettifyThings g (fun f -> foldPair (f, f)) (fun f -> mapPair (f, f)) x let PrettifyTypes g x = PrettifyThings g List.fold List.map x + + let PrettifyDiscriminantAndTypePairs g x = + let tys, cxs = (PrettifyThings g List.fold List.map (x |> List.map snd)) + List.zip (List.map fst x) tys, cxs + let PrettifyCurriedTypes g x = PrettifyThings g (fun f -> List.fold (List.fold f)) List.mapSquared x let PrettifyCurriedSigTypes g x = PrettifyThings g (fun f -> foldPair (List.fold (List.fold f), f)) (fun f -> mapPair (List.mapSquared f, f)) x @@ -2662,7 +2681,7 @@ type DisplayEnv = contextAccessibility: Accessibility generatedValueLayout : (Val -> layout option) } - member x.SetOpenPaths(paths) = + member x.SetOpenPaths paths = { x with openTopPathsSorted = (lazy (paths |> List.sortWith (fun p1 p2 -> -(compare p1 p2)))) openTopPathsRaw = paths @@ -2718,8 +2737,8 @@ let fullNameOfParentOfPubPathAsLayout pp = | PubPath([| _ |]) -> ValueNone | pp -> ValueSome(layoutOfPath (Array.toList pp.EnclosingPath)) -let fullNameOfPubPath (PubPath(p)) = textOfPath p -let fullNameOfPubPathAsLayout (PubPath(p)) = layoutOfPath (Array.toList p) +let fullNameOfPubPath (PubPath p) = textOfPath p +let fullNameOfPubPathAsLayout (PubPath p) = layoutOfPath (Array.toList p) let fullNameOfParentOfNonLocalEntityRef (nlr: NonLocalEntityRef) = if nlr.Path.Length < 2 then ValueNone @@ -2840,13 +2859,13 @@ let qualifiedMangledNameOfTyconRef tcref nm = let rec firstEq p1 p2 = match p1 with | [] -> true - | h1:: t1 -> + | h1 :: t1 -> match p2 with - | h2:: t2 -> h1 = h2 && firstEq t1 t2 + | h2 :: t2 -> h1 = h2 && firstEq t1 t2 | _ -> false let rec firstRem p1 p2 = - match p1 with [] -> p2 | _:: t1 -> firstRem t1 (List.tail p2) + match p1 with [] -> p2 | _ :: t1 -> firstRem t1 (List.tail p2) let trimPathByDisplayEnv denv path = let findOpenedNamespace openedPath = @@ -2902,15 +2921,15 @@ let IsMatchingFSharpAttributeOpt g attrOpt (Attrib(tcref2, _, _, _, _, _, _)) = let (|ExtractAttribNamedArg|_|) nm args = args |> List.tryPick (function (AttribNamedArg(nm2, _, _, v)) when nm = nm2 -> Some v | _ -> None) -let (|AttribInt32Arg|_|) = function AttribExpr(_, Expr.Const (Const.Int32(n), _, _)) -> Some(n) | _ -> None -let (|AttribInt16Arg|_|) = function AttribExpr(_, Expr.Const (Const.Int16(n), _, _)) -> Some(n) | _ -> None -let (|AttribBoolArg|_|) = function AttribExpr(_, Expr.Const (Const.Bool(n), _, _)) -> Some(n) | _ -> None -let (|AttribStringArg|_|) = function AttribExpr(_, Expr.Const (Const.String(n), _, _)) -> Some(n) | _ -> None +let (|AttribInt32Arg|_|) = function AttribExpr(_, Expr.Const (Const.Int32 n, _, _)) -> Some n | _ -> None +let (|AttribInt16Arg|_|) = function AttribExpr(_, Expr.Const (Const.Int16 n, _, _)) -> Some n | _ -> None +let (|AttribBoolArg|_|) = function AttribExpr(_, Expr.Const (Const.Bool n, _, _)) -> Some n | _ -> None +let (|AttribStringArg|_|) = function AttribExpr(_, Expr.Const (Const.String n, _, _)) -> Some n | _ -> None let TryFindFSharpBoolAttributeWithDefault dflt g nm attrs = match TryFindFSharpAttribute g nm attrs with - | Some(Attrib(_, _, [ ], _, _, _, _)) -> Some(dflt) - | Some(Attrib(_, _, [ AttribBoolArg(b) ], _, _, _, _)) -> Some(b) + | Some(Attrib(_, _, [ ], _, _, _, _)) -> Some dflt + | Some(Attrib(_, _, [ AttribBoolArg b ], _, _, _, _)) -> Some b | _ -> None let TryFindFSharpBoolAttribute g nm attrs = TryFindFSharpBoolAttributeWithDefault true g nm attrs @@ -2918,12 +2937,12 @@ let TryFindFSharpBoolAttributeAssumeFalse g nm attrs = TryFindFSharpBoolAttribut let TryFindFSharpInt32Attribute g nm attrs = match TryFindFSharpAttribute g nm attrs with - | Some(Attrib(_, _, [ AttribInt32Arg(b) ], _, _, _, _)) -> Some b + | Some(Attrib(_, _, [ AttribInt32Arg b ], _, _, _, _)) -> Some b | _ -> None let TryFindFSharpStringAttribute g nm attrs = match TryFindFSharpAttribute g nm attrs with - | Some(Attrib(_, _, [ AttribStringArg(b) ], _, _, _, _)) -> Some b + | Some(Attrib(_, _, [ AttribStringArg b ], _, _, _, _)) -> Some b | _ -> None let TryFindILAttribute (AttribInfo (atref, _)) attrs = @@ -2944,7 +2963,7 @@ let TryBindTyconRefAttribute g (m: range) (AttribInfo (atref, _) as args) (tcref #if !NO_EXTENSIONTYPING | ProvidedTypeMetadata info -> let provAttribs = info.ProvidedType.PApply((fun a -> (a :> IProvidedCustomAttributeProvider)), m) - match provAttribs.PUntaint((fun a -> a.GetAttributeConstructorArgs(provAttribs.TypeProvider.PUntaintNoFailure(id), atref.FullName)), m) with + match provAttribs.PUntaint((fun a -> a.GetAttributeConstructorArgs(provAttribs.TypeProvider.PUntaintNoFailure id, atref.FullName)), m) with | Some args -> f3 args | None -> None #endif @@ -2961,7 +2980,7 @@ let TryFindTyconRefBoolAttribute g m attribSpec tcref = TryBindTyconRefAttribute g m attribSpec tcref (function | ([ ], _) -> Some true - | ([ILAttribElem.Bool (v) ], _) -> Some v + | ([ILAttribElem.Bool v ], _) -> Some v | _ -> None) (function | (Attrib(_, _, [ ], _, _, _, _)) -> Some true @@ -2975,7 +2994,7 @@ let TryFindTyconRefBoolAttribute g m attribSpec tcref = let TryFindAttributeUsageAttribute g m tcref = TryBindTyconRefAttribute g m g.attrib_AttributeUsageAttribute tcref (fun (_, named) -> named |> List.tryPick (function ("AllowMultiple", _, _, ILAttribElem.Bool res) -> Some res | _ -> None)) - (fun (Attrib(_, _, _, named, _, _, _)) -> named |> List.tryPick (function AttribNamedArg("AllowMultiple", _, _, AttribBoolArg(res) ) -> Some res | _ -> None)) + (fun (Attrib(_, _, _, named, _, _, _)) -> named |> List.tryPick (function AttribNamedArg("AllowMultiple", _, _, AttribBoolArg res ) -> Some res | _ -> None)) (fun (_, named) -> named |> List.tryPick (function ("AllowMultiple", Some ((:? bool as res) : obj)) -> Some res | _ -> None)) @@ -2984,8 +3003,8 @@ let TryFindAttributeUsageAttribute g m tcref = /// This is used to detect the 'DefaultMemberAttribute' and 'ConditionalAttribute' attributes (on type definitions) let TryFindTyconRefStringAttribute g m attribSpec tcref = TryBindTyconRefAttribute g m attribSpec tcref - (function ([ILAttribElem.String (Some(msg)) ], _) -> Some msg | _ -> None) - (function (Attrib(_, _, [ AttribStringArg(msg) ], _, _, _, _)) -> Some msg | _ -> None) + (function ([ILAttribElem.String (Some msg) ], _) -> Some msg | _ -> None) + (function (Attrib(_, _, [ AttribStringArg msg ], _, _, _, _)) -> Some msg | _ -> None) (function ([ Some ((:? string as msg) : obj) ], _) -> Some msg | _ -> None) /// Check if a type definition has a specific attribute @@ -3009,11 +3028,11 @@ let isByrefTyconRef (g: TcGlobals) (tcref: TyconRef) = let isByrefLikeTyconRef (g: TcGlobals) m (tcref: TyconRef) = tcref.CanDeref && match tcref.TryIsByRefLike with - | Some res -> res - | None -> + | ValueSome res -> res + | _ -> let res = isByrefTyconRef g tcref || - TyconRefHasAttribute g m g.attrib_IsByRefLikeAttribute tcref + (isStructTyconRef tcref && TyconRefHasAttribute g m g.attrib_IsByRefLikeAttribute tcref) tcref.SetIsByRefLike res res @@ -3022,11 +3041,45 @@ let isSpanLikeTyconRef g m tcref = not (isByrefTyconRef g tcref) let isByrefLikeTy g m ty = - ty |> stripTyEqns g |> (function TType_app(tcref, _) -> isByrefLikeTyconRef g m tcref | _ -> false) + ty |> stripTyEqns g |> (function TType_app(tcref, _) -> isByrefLikeTyconRef g m tcref | _ -> false) let isSpanLikeTy g m ty = isByrefLikeTy g m ty && - not (isByrefTy g ty) + not (isByrefTy g ty) + +let isSpanTyconRef g m tcref = + isByrefLikeTyconRef g m tcref && + tcref.CompiledRepresentationForNamedType.BasicQualifiedName = "System.Span`1" + +let isSpanTy g m ty = + ty |> stripTyEqns g |> (function TType_app(tcref, _) -> isSpanTyconRef g m tcref | _ -> false) + +let rec tryDestSpanTy g m ty = + match tryAppTy g ty with + | ValueSome(tcref, [ty]) when isSpanTyconRef g m tcref -> ValueSome(struct(tcref, ty)) + | _ -> ValueNone + +let destSpanTy g m ty = + match tryDestSpanTy g m ty with + | ValueSome(struct(tcref, ty)) -> struct(tcref, ty) + | _ -> failwith "destSpanTy" + +let isReadOnlySpanTyconRef g m tcref = + isByrefLikeTyconRef g m tcref && + tcref.CompiledRepresentationForNamedType.BasicQualifiedName = "System.ReadOnlySpan`1" + +let isReadOnlySpanTy g m ty = + ty |> stripTyEqns g |> (function TType_app(tcref, _) -> isReadOnlySpanTyconRef g m tcref | _ -> false) + +let tryDestReadOnlySpanTy g m ty = + match tryAppTy g ty with + | ValueSome(tcref, [ty]) when isReadOnlySpanTyconRef g m tcref -> ValueSome(struct(tcref, ty)) + | _ -> ValueNone + +let destReadOnlySpanTy g m ty = + match tryDestReadOnlySpanTy g m ty with + | ValueSome(struct(tcref, ty)) -> struct(tcref, ty) + | _ -> failwith "destReadOnlySpanTy" //------------------------------------------------------------------------- // List and reference types... @@ -3048,7 +3101,7 @@ let destNativePtrTy g ty = | _ -> failwith "destNativePtrTy: not a native ptr type" let isRefCellTy g ty = - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueNone -> false | ValueSome tcref -> tyconRefEq g g.refcell_tcr_canon tcref @@ -3070,10 +3123,12 @@ let mkPrintfFormatTy (g: TcGlobals) aty bty cty dty ety = TType_app(g.format_tcr let mkOptionTy (g: TcGlobals) ty = TType_app (g.option_tcr_nice, [ty]) +let mkNullableTy (g: TcGlobals) ty = TType_app (g.system_Nullable_tcref, [ty]) + let mkListTy (g: TcGlobals) ty = TType_app (g.list_tcr_nice, [ty]) let isOptionTy (g: TcGlobals) ty = - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueNone -> false | ValueSome tcref -> tyconRefEq g g.option_tcr_canon tcref @@ -3087,8 +3142,33 @@ let destOptionTy g ty = | ValueSome ty -> ty | ValueNone -> failwith "destOptionTy: not an option type" +let isNullableTy (g: TcGlobals) ty = + match tryTcrefOfAppTy g ty with + | ValueNone -> false + | ValueSome tcref -> tyconRefEq g g.system_Nullable_tcref tcref + +let tryDestNullableTy g ty = + match argsOfAppTy g ty with + | [ty1] when isNullableTy g ty -> ValueSome ty1 + | _ -> ValueNone + +let destNullableTy g ty = + match tryDestNullableTy g ty with + | ValueSome ty -> ty + | ValueNone -> failwith "destNullableTy: not a Nullable type" + +let (|NullableTy|_|) g ty = + match tryAppTy g ty with + | ValueSome (tcref, [tyarg]) when tyconRefEq g tcref g.system_Nullable_tcref -> Some tyarg + | _ -> None + +let (|StripNullableTy|) g ty = + match tryDestNullableTy g ty with + | ValueSome tyarg -> tyarg + | _ -> ty + let isLinqExpressionTy g ty = - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueNone -> false | ValueSome tcref -> tyconRefEq g g.system_LinqExpression_tcref tcref @@ -3103,8 +3183,15 @@ let destLinqExpressionTy g ty = | None -> failwith "destLinqExpressionTy: not an expression type" let mkNoneCase (g: TcGlobals) = mkUnionCaseRef g.option_tcr_canon "None" + let mkSomeCase (g: TcGlobals) = mkUnionCaseRef g.option_tcr_canon "Some" +let mkSome g ty arg m = mkUnionCaseExpr(mkSomeCase g, [ty], [arg], m) + +let mkNone g ty m = mkUnionCaseExpr(mkNoneCase g, [ty], [], m) + +let mkOptionGetValueUnprovenViaAddr g expr ty m = mkUnionCaseFieldGetUnprovenViaExprAddr (expr, mkSomeCase g, [ty], 0, m) + type ValRef with member vref.IsDispatchSlot = match vref.MemberInfo with @@ -3113,12 +3200,12 @@ type ValRef with let (|UnopExpr|_|) _g expr = match expr with - | Expr.App(Expr.Val(vref, _, _), _, _, [arg1], _) -> Some (vref, arg1) + | Expr.App (Expr.Val (vref, _, _), _, _, [arg1], _) -> Some (vref, arg1) | _ -> None let (|BinopExpr|_|) _g expr = match expr with - | Expr.App(Expr.Val(vref, _, _), _, _, [arg1;arg2], _) -> Some (vref, arg1, arg2) + | Expr.App (Expr.Val (vref, _, _), _, _, [arg1;arg2], _) -> Some (vref, arg1, arg2) | _ -> None let (|SpecificUnopExpr|_|) g vrefReqd expr = @@ -3145,7 +3232,7 @@ let (|AttribBitwiseOrExpr|_|) g expr = // is defined. These get through type checking because enums implicitly support the '|||' operator through // the automatic resolution of undefined operators (see tc.fs, Item.ImplicitOp). This then compiles as an // application of a lambda to two arguments. We recognize this pattern here - | Expr.App(Expr.Lambda _, _, _, [arg1;arg2], _) when g.compilingFslib -> + | Expr.App (Expr.Lambda _, _, _, [arg1;arg2], _) when g.compilingFslib -> Some(arg1, arg2) | _ -> None @@ -3164,6 +3251,11 @@ let isSizeOfValRef g vref = // There is an internal version of typeof defined in prim-types.fs that needs to be detected || (g.compilingFslib && vref.LogicalName = "sizeof") +let isNameOfValRef g vref = + valRefEq g vref g.nameof_vref + // There is an internal version of nameof defined in prim-types.fs that needs to be detected + || (g.compilingFslib && vref.LogicalName = "nameof") + let isTypeDefOfValRef g vref = valRefEq g vref g.typedefof_vref // There is an internal version of typedefof defined in prim-types.fs that needs to be detected @@ -3171,28 +3263,37 @@ let isTypeDefOfValRef g vref = let (|UncheckedDefaultOfExpr|_|) g expr = match expr with - | Expr.App(Expr.Val(vref, _, _), _, [ty], [], _) when isUncheckedDefaultOfValRef g vref -> Some ty + | Expr.App (Expr.Val (vref, _, _), _, [ty], [], _) when isUncheckedDefaultOfValRef g vref -> Some ty | _ -> None let (|TypeOfExpr|_|) g expr = match expr with - | Expr.App(Expr.Val(vref, _, _), _, [ty], [], _) when isTypeOfValRef g vref -> Some ty + | Expr.App (Expr.Val (vref, _, _), _, [ty], [], _) when isTypeOfValRef g vref -> Some ty | _ -> None let (|SizeOfExpr|_|) g expr = match expr with - | Expr.App(Expr.Val(vref, _, _), _, [ty], [], _) when isSizeOfValRef g vref -> Some ty + | Expr.App (Expr.Val (vref, _, _), _, [ty], [], _) when isSizeOfValRef g vref -> Some ty | _ -> None let (|TypeDefOfExpr|_|) g expr = match expr with - | Expr.App(Expr.Val(vref, _, _), _, [ty], [], _) when isTypeDefOfValRef g vref -> Some ty + | Expr.App (Expr.Val (vref, _, _), _, [ty], [], _) when isTypeDefOfValRef g vref -> Some ty + | _ -> None + +let (|NameOfExpr|_|) g expr = + match expr with + | Expr.App(Expr.Val(vref,_,_),_,[ty],[],_) when isNameOfValRef g vref -> Some ty + | _ -> None + +let (|SeqExpr|_|) g expr = + match expr with + | Expr.App(Expr.Val(vref,_,_),_,_,_,_) when valRefEq g vref g.seq_vref -> Some() | _ -> None //-------------------------------------------------------------------------- // DEBUG layout //--------------------------------------------------------------------------- - module DebugPrint = let layoutRanges = ref false @@ -3264,7 +3365,7 @@ module DebugPrint = match stripTyparEqns ty with | TType_forall (typars, rty) -> (leftL (tagText "!") ^^ layoutTyparDecls typars --- auxTypeL env rty) |> wrap - | TType_ucase (UCRef(tcref, _), tinst) + | TType_ucase (UnionCaseRef(tcref, _), tinst) | TType_app (tcref, tinst) -> let prefix = tcref.IsPrefixDisplay let tcL = layoutTyconRef tcref @@ -3276,7 +3377,7 @@ module DebugPrint = | TType_measure unt -> #if DEBUG leftL (tagText "{") ^^ - (match !global_g with + (match global_g with | None -> wordL (tagText "") | Some g -> let sortVars (vs:(Typar * Rational) list) = vs |> List.sortBy (fun (v, _) -> v.DisplayName) @@ -3319,7 +3420,7 @@ module DebugPrint = let varL = tpL |> stampL typar.Stamp match Zmap.tryFind typar env.inplaceConstraints with - | Some (typarConstraintTy) -> + | Some typarConstraintTy -> if Zset.contains typar env.singletons then leftL (tagText "#") ^^ auxTyparConstraintTypL env typarConstraintTy else @@ -3335,7 +3436,7 @@ module DebugPrint = and auxTraitL env (ttrait: TraitConstraintInfo) = #if DEBUG let (TTrait(tys, nm, memFlags, argtys, rty, _)) = ttrait - match !global_g with + match global_g with | None -> wordL (tagText "") | Some g -> let rty = GetFSharpViewOfReturnType g rty @@ -3426,14 +3527,13 @@ module DebugPrint = | ILAttrib ilmeth -> wordL (tagText ilmeth.Name) | FSAttrib vref -> valRefL vref) ^^ rightL (tagText ">]") - + let layoutAttribs attribs = aboveListL (List.map layoutAttrib attribs) let arityInfoL (ValReprInfo (tpNames, _, _) as tvd) = let ns = tvd.AritiesOfArgs in leftL (tagText "arity<") ^^ intL tpNames.Length ^^ sepL (tagText ">[") ^^ commaListL (List.map intL ns) ^^ rightL (tagText "]") - let valL (v: Val) = let vsL = wordL (tagText (DecompileOpName v.LogicalName)) |> stampL v.Stamp let vsL = vsL -- layoutAttribs (v.Attribs) @@ -3456,7 +3556,7 @@ module DebugPrint = let slotSigL (slotsig: SlotSig) = #if DEBUG let (TSlotSig(nm, ty, tps1, tps2, pms, rty)) = slotsig - match !global_g with + match global_g with | None -> wordL(tagText "") | Some g -> let rty = GetFSharpViewOfReturnType g rty @@ -3469,18 +3569,18 @@ module DebugPrint = wordL(tagText "slotsig") #endif - let rec memberL (v: Val) (membInfo: ValMemberInfo) = + let rec memberL (g:TcGlobals) (v: Val) (membInfo: ValMemberInfo) = aboveListL - [ wordL(tagText "compiled_name! = ") ^^ wordL (tagText v.CompiledName) + [ wordL(tagText "compiled_name! = ") ^^ wordL (tagText (v.CompiledName g.CompilerGlobalState)) wordL(tagText "membInfo-slotsig! = ") ^^ listL slotSigL membInfo.ImplementedSlotSigs ] - and valAtBindL v = + and valAtBindL g v = let vL = valL v let mutL = (if v.IsMutable then wordL(tagText "mutable") ++ vL else vL) mutL --- aboveListL [ yield wordL(tagText ":") ^^ typeL v.Type - match v.MemberInfo with None -> () | Some mem_info -> yield wordL(tagText "!") ^^ memberL v mem_info + match v.MemberInfo with None -> () | Some mem_info -> yield wordL(tagText "!") ^^ memberL g v mem_info match v.ValReprInfo with None -> () | Some arity_info -> yield wordL(tagText "#") ^^ arityInfoL arity_info] let unionCaseRefL (ucr: UnionCaseRef) = wordL (tagText ucr.CaseName) @@ -3506,12 +3606,12 @@ module DebugPrint = | Const.UIntPtr x -> (x |> string)+"un" | Const.Single d -> (let s = d.ToString("g12", System.Globalization.CultureInfo.InvariantCulture) - if String.forall (fun c -> System.Char.IsDigit(c) || c = '-') s + if String.forall (fun c -> System.Char.IsDigit c || c = '-') s then s + ".0" else s) + "f" | Const.Double d -> let s = d.ToString("g12", System.Globalization.CultureInfo.InvariantCulture) - if String.forall (fun c -> System.Char.IsDigit(c) || c = '-') s + if String.forall (fun c -> System.Char.IsDigit c || c = '-') s then s + ".0" else s | Const.Char c -> "'" + c.ToString() + "'" @@ -3521,9 +3621,9 @@ module DebugPrint = | Const.Zero -> "default" wordL (tagText str) - let rec tyconL (tycon: Tycon) = - if tycon.IsModuleOrNamespace then entityL tycon else - + let rec tyconL g (tycon: Tycon) = + if tycon.IsModuleOrNamespace then entityL g tycon else + let lhsL = wordL (tagText (match tycon.TypeOrMeasureKind with TyparKind.Measure -> "[] type" | TyparKind.Type -> "type")) ^^ wordL (tagText tycon.DisplayName) ^^ layoutTyparDecls tycon.TyparsNoRange let lhsL = lhsL --- layoutAttribs tycon.Attribs let memberLs = @@ -3543,7 +3643,7 @@ module DebugPrint = emptyL else let iimplsLs = iimpls |> List.map (fun (ty, _, _) -> wordL(tagText "interface") --- typeL ty) - let adhocLs = adhoc |> List.map (fun vref -> valAtBindL vref.Deref) + let adhocLs = adhoc |> List.map (fun vref -> valAtBindL g vref.Deref) (wordL(tagText "with") @@-- aboveListL (iimplsLs @ adhocLs)) @@ wordL(tagText "end") let layoutUnionCaseArgTypes argtys = sepListL (wordL(tagText "*")) (List.map typeL argtys) @@ -3590,7 +3690,7 @@ module DebugPrint = let vsprs = tycon.MembersOfFSharpTyconSorted |> List.filter (fun v -> v.IsDispatchSlot) - |> List.map (fun vref -> valAtBindL vref.Deref) + |> List.map (fun vref -> valAtBindL g vref.Deref) let vals = tycon.TrueFieldsAsList |> List.map (fun f -> (if f.IsStatic then wordL(tagText "static") else emptyL) ^^ wordL(tagText "val") ^^ layoutRecdField f) let alldecls = inherits @ vsprs @ vals let emptyMeasure = match tycon.TypeOrMeasureKind with TyparKind.Measure -> isNil alldecls | _ -> false @@ -3616,25 +3716,29 @@ module DebugPrint = (lhsL ^^ wordL(tagText "=")) @@-- rhsL reprL - and bindingL (TBind(v, repr, _)) = - valAtBindL v --- (wordL(tagText "=") ^^ exprL repr) + and bindingL g (TBind(v, repr, _)) = + (valAtBindL g v ^^ wordL(tagText "=")) @@-- exprL g repr - and exprL expr = exprWrapL false expr + and exprL g expr = exprWrapL g false expr - and atomL expr = exprWrapL true expr // true means bracket if needed to be atomic expr + and atomL g expr = exprWrapL g true expr // true means bracket if needed to be atomic expr - and letRecL binds bodyL = + and letRecL g binds bodyL = let eqnsL = binds - |> List.mapHeadTail (fun bind -> wordL(tagText "rec") ^^ bindingL bind ^^ wordL(tagText "in")) - (fun bind -> wordL(tagText "and") ^^ bindingL bind ^^ wordL(tagText "in")) + |> List.mapHeadTail (fun bind -> wordL(tagText "rec") ^^ bindingL g bind ^^ wordL(tagText "in")) + (fun bind -> wordL(tagText "and") ^^ bindingL g bind ^^ wordL(tagText "in")) (aboveListL eqnsL @@ bodyL) - and letL bind bodyL = - let eqnL = wordL(tagText "let") ^^ bindingL bind ^^ wordL(tagText "in") + and letL g bind bodyL = + let eqnL = wordL(tagText "let") ^^ bindingL g bind (eqnL @@ bodyL) - and exprWrapL isAtomic expr = + and exprWrapL g isAtomic expr = + let atomL args = atomL g args + let exprL expr = exprL g expr + let valAtBindL v = valAtBindL g v + let targetL targets = targetL g targets let wrap = bracketIfL isAtomic // wrap iff require atomic expr let lay = match expr with @@ -3652,34 +3756,34 @@ module DebugPrint = | Expr.Sequential (expr1, expr2, flag, _, _) -> let flag = match flag with - | NormalSeq -> "; (*Seq*)" - | ThenDoSeq -> "; (*ThenDo*)" + | NormalSeq -> ";" + | ThenDoSeq -> "; ThenDo" ((exprL expr1 ^^ rightL (tagText flag)) @@ exprL expr2) |> wrap - | Expr.Lambda(_, _, baseValOpt, argvs, body, _, _) -> + | Expr.Lambda (_, _, baseValOpt, argvs, body, _, _) -> let formalsL = spaceListL (List.map valAtBindL argvs) in let bindingL = match baseValOpt with | None -> wordL(tagText "lam") ^^ formalsL ^^ rightL(tagText ".") | Some basev -> wordL(tagText "lam") ^^ (leftL(tagText "base=") ^^ valAtBindL basev) --- formalsL ^^ rightL(tagText ".") in (bindingL ++ exprL body) |> wrap - | Expr.TyLambda(_, argtyvs, body, _, _) -> + | Expr.TyLambda (_, argtyvs, body, _, _) -> ((wordL(tagText "LAM") ^^ spaceListL (List.map typarL argtyvs) ^^ rightL(tagText ".")) ++ exprL body) |> wrap - | Expr.TyChoose(argtyvs, body, _) -> + | Expr.TyChoose (argtyvs, body, _) -> ((wordL(tagText "CHOOSE") ^^ spaceListL (List.map typarL argtyvs) ^^ rightL(tagText ".")) ++ exprL body) |> wrap | Expr.App (f, _, tys, argtys, _) -> let flayout = atomL f - appL flayout tys argtys |> wrap + appL g flayout tys argtys |> wrap | Expr.LetRec (binds, body, _, _) -> - letRecL binds (exprL body) |> wrap + letRecL g binds (exprL body) |> wrap | Expr.Let (bind, body, _, _) -> - letL bind (exprL body) |> wrap + letL g bind (exprL body) |> wrap | Expr.Link rX -> (wordL(tagText "RecLink") --- atomL (!rX)) |> wrap | Expr.Match (_, _, dtree, targets, _, _) -> - leftL(tagText "[") ^^ (decisionTreeL dtree @@ aboveListL (List.mapi targetL (targets |> Array.toList)) ^^ rightL(tagText "]")) - | Expr.Op (TOp.UnionCase (c), _, args, _) -> + leftL(tagText "[") ^^ (decisionTreeL g dtree @@ aboveListL (List.mapi targetL (targets |> Array.toList)) ^^ rightL(tagText "]")) + | Expr.Op (TOp.UnionCase c, _, args, _) -> (unionCaseRefL c ++ spaceListL (List.map atomL args)) |> wrap - | Expr.Op (TOp.ExnConstr (ecref), _, args, _) -> + | Expr.Op (TOp.ExnConstr ecref, _, args, _) -> wordL (tagText ecref.LogicalName) ^^ bracketL (commaListL (List.map atomL args)) | Expr.Op (TOp.Tuple _, _, xs, _) -> tupleL (List.map exprL xs) @@ -3720,7 +3824,7 @@ module DebugPrint = | Expr.Op (TOp.ILAsm (a, tys), tyargs, args, _) -> let instrs = a |> List.map (sprintf "%+A" >> tagText >> wordL) |> spaceListL // %+A has + since instrs are from an "internal" type let instrs = leftL(tagText "(#") ^^ instrs ^^ rightL(tagText "#)") - (appL instrs tyargs args --- + (appL g instrs tyargs args --- wordL(tagText ":") ^^ spaceListL (List.map typeAtomL tys)) |> wrap | Expr.Op (TOp.LValueOp (lvop, vr), _, args, _) -> (lvalopL lvop ^^ valRefL vr --- bracketL (commaListL (List.map atomL args))) |> wrap @@ -3728,22 +3832,22 @@ module DebugPrint = let meth = ilMethRef.Name wordL(tagText "ILCall") ^^ aboveListL - [ wordL(tagText "meth ") --- wordL (tagText ilMethRef.DeclaringTypeRef.FullName) ^^ sepL(tagText ".") ^^ wordL (tagText meth) - wordL(tagText "tinst ") --- listL typeL tinst - wordL(tagText "minst ") --- listL typeL minst - wordL(tagText "tyargs") --- listL typeL tyargs - wordL(tagText "args ") --- listL exprL args ] + [ yield wordL (tagText ilMethRef.DeclaringTypeRef.FullName) ^^ sepL(tagText ".") ^^ wordL (tagText meth) + if not tinst.IsEmpty then yield wordL(tagText "tinst ") --- listL typeL tinst + if not minst.IsEmpty then yield wordL (tagText "minst ") --- listL typeL minst + if not tyargs.IsEmpty then yield wordL (tagText "tyargs") --- listL typeL tyargs + if not args.IsEmpty then yield listL exprL args ] |> wrap | Expr.Op (TOp.Array, [_], xs, _) -> leftL(tagText "[|") ^^ commaListL (List.map exprL xs) ^^ rightL(tagText "|]") - | Expr.Op (TOp.While _, [], [x1;x2], _) -> - wordL(tagText "while") ^^ exprL x1 ^^ wordL(tagText "do") ^^ exprL x2 ^^ rightL(tagText "}") - | Expr.Op (TOp.For _, [], [x1;x2;x3], _) -> + | Expr.Op (TOp.While _, [], [Expr.Lambda (_, _, _, [_], x1, _, _);Expr.Lambda (_, _, _, [_], x2, _, _)], _) -> + (wordL(tagText "while") ^^ exprL x1 ^^ wordL(tagText "do")) @@-- exprL x2 + | Expr.Op (TOp.For _, [], [Expr.Lambda (_, _, _, [_], x1, _, _);Expr.Lambda (_, _, _, [_], x2, _, _);Expr.Lambda (_, _, _, [_], x3, _, _)], _) -> wordL(tagText "for") ^^ aboveListL [(exprL x1 ^^ wordL(tagText "to") ^^ exprL x2 ^^ wordL(tagText "do")); exprL x3 ] ^^ rightL(tagText "done") - | Expr.Op (TOp.TryCatch _, [_], [x1;x2], _) -> - wordL(tagText "try") ^^ exprL x1 ^^ wordL(tagText "with") ^^ exprL x2 ^^ rightL(tagText "}") - | Expr.Op (TOp.TryFinally _, [_], [x1;x2], _) -> - wordL(tagText "try") ^^ exprL x1 ^^ wordL(tagText "finally") ^^ exprL x2 ^^ rightL(tagText "}") + | Expr.Op (TOp.TryCatch _, [_], [Expr.Lambda (_, _, _, [_], x1, _, _);Expr.Lambda (_, _, _, [_], xf, _, _);Expr.Lambda (_, _, _, [_], xh, _, _)], _) -> + (wordL (tagText "try") @@-- exprL x1) @@ (wordL(tagText "with-filter") @@-- exprL xf) @@ (wordL(tagText "with") @@-- exprL xh) + | Expr.Op (TOp.TryFinally _, [_], [Expr.Lambda (_, _, _, [_], x1, _, _);Expr.Lambda (_, _, _, [_], x2, _, _)], _) -> + (wordL (tagText "try") @@-- exprL x1) @@ (wordL(tagText "finally") @@-- exprL x2) | Expr.Op (TOp.Bytes _, _, _, _) -> wordL(tagText "bytes++") | Expr.Op (TOp.UInt16s _, _, _, _) -> wordL(tagText "uint16++") @@ -3753,15 +3857,21 @@ module DebugPrint = | Expr.Op (TOp.ExnFieldSet _, _tyargs, _args, _) -> wordL(tagText "TOp.ExnFieldSet...") | Expr.Op (TOp.TryFinally _, _tyargs, _args, _) -> wordL(tagText "TOp.TryFinally...") | Expr.Op (TOp.TryCatch _, _tyargs, _args, _) -> wordL(tagText "TOp.TryCatch...") + | Expr.Op (TOp.Goto l, _tys, args, _) -> wordL(tagText ("Expr.Goto " + string l)) ^^ bracketL (commaListL (List.map atomL args)) + | Expr.Op (TOp.Label l, _tys, args, _) -> wordL(tagText ("Expr.Label " + string l)) ^^ bracketL (commaListL (List.map atomL args)) | Expr.Op (_, _tys, args, _) -> wordL(tagText "Expr.Op ...") ^^ bracketL (commaListL (List.map atomL args)) | Expr.Quote (a, _, _, _, _) -> leftL(tagText "<@") ^^ atomL a ^^ rightL(tagText "@>") | Expr.Obj (_lambdaId, ty, basev, ccall, overrides, iimpls, _) -> - wordL(tagText "OBJ:") ^^ - aboveListL [typeL ty - exprL ccall - optionL valAtBindL basev - aboveListL (List.map overrideL overrides) - aboveListL (List.map iimplL iimpls)] + (leftL (tagText "{") + @@-- + ((wordL(tagText "new ") ++ typeL ty) + @@-- + aboveListL [exprL ccall + optionL valAtBindL basev + aboveListL (List.map (tmethodL g) overrides) + aboveListL (List.map (iimplL g) iimpls)])) + @@ + rightL (tagText "}") | Expr.StaticOptimization (_tcs, csx, x, _) -> (wordL(tagText "opt") @@- (exprL x)) @@-- @@ -3772,92 +3882,94 @@ module DebugPrint = then leftL(tagText "{") ^^ (rangeL expr.Range ^^ rightL(tagText ":")) ++ lay ^^ rightL(tagText "}") else lay - and implFilesL implFiles = - aboveListL (List.map implFileL implFiles) + and implFilesL g implFiles = + aboveListL (List.map (implFileL g) implFiles) - and appL flayout tys args = + and appL g flayout tys args = let z = flayout - let z = z ^^ instL typeL tys - let z = z --- sepL(tagText "`") --- (spaceListL (List.map atomL args)) + let z = if tys.Length > 0 then z ^^ instL typeL tys else z + let z = if args.Length > 0 then z --- spaceListL (List.map (atomL g) args) else z z - - and implFileL (TImplFile(_, _, mexpr, _, _, _)) = - aboveListL [(wordL(tagText "top implementation ")) @@-- mexprL mexpr] - and mexprL x = + and implFileL g (TImplFile (_, _, mexpr, _, _, _)) = + aboveListL [(wordL(tagText "top implementation ")) @@-- mexprL g mexpr] + + and mexprL g x = match x with - | ModuleOrNamespaceExprWithSig(mtyp, defs, _) -> mdefL defs @@- (wordL(tagText ":") @@- entityTypeL mtyp) + | ModuleOrNamespaceExprWithSig(mtyp, defs, _) -> mdefL g defs @@- (wordL(tagText ":") @@- entityTypeL g mtyp) - and mdefsL defs = wordL(tagText "Module Defs") @@-- aboveListL(List.map mdefL defs) + and mdefsL g defs = + wordL(tagText "Module Defs") @@-- aboveListL(List.map (mdefL g) defs) - and mdefL x = - match x with - | TMDefRec(_, tycons, mbinds, _) -> aboveListL ((tycons |> List.map tyconL) @ List.map mbindL mbinds) - | TMDefLet(bind, _) -> letL bind emptyL - | TMDefDo(e, _) -> exprL e - | TMDefs defs -> mdefsL defs - | TMAbstract mexpr -> mexprL mexpr - - and mbindL x = - match x with - | ModuleOrNamespaceBinding.Binding bind -> letL bind emptyL + and mdefL g x = + match x with + | TMDefRec(_, tycons, mbinds, _) -> aboveListL ((tycons |> List.map (tyconL g)) @ (mbinds |> List.map (mbindL g))) + | TMDefLet(bind, _) -> letL g bind emptyL + | TMDefDo(e, _) -> exprL g e + | TMDefs defs -> mdefsL g defs + | TMAbstract mexpr -> mexprL g mexpr + + and mbindL g x = + match x with + | ModuleOrNamespaceBinding.Binding bind -> letL g bind emptyL | ModuleOrNamespaceBinding.Module(mspec, rhs) -> - (wordL (tagText (if mspec.IsNamespace then "namespace" else "module")) ^^ (wordL (tagText mspec.DemangledModuleOrNamespaceName) |> stampL mspec.Stamp)) @@-- mdefL rhs + (wordL (tagText (if mspec.IsNamespace then "namespace" else "module")) ^^ (wordL (tagText mspec.DemangledModuleOrNamespaceName) |> stampL mspec.Stamp)) @@-- mdefL g rhs - and entityTypeL (mtyp: ModuleOrNamespaceType) = + and entityTypeL g (mtyp: ModuleOrNamespaceType) = aboveListL [jlistL typeOfValL mtyp.AllValsAndMembers - jlistL tyconL mtyp.AllEntities;] + jlistL (tyconL g) mtyp.AllEntities] - and entityL (ms: ModuleOrNamespace) = + and entityL g (ms: ModuleOrNamespace) = let header = wordL(tagText "module") ^^ (wordL (tagText ms.DemangledModuleOrNamespaceName) |> stampL ms.Stamp) ^^ wordL(tagText ":") let footer = wordL(tagText "end") - let body = entityTypeL ms.ModuleOrNamespaceType + let body = entityTypeL g ms.ModuleOrNamespaceType (header @@-- body) @@ footer - and ccuL (ccu: CcuThunk) = entityL ccu.Contents + and ccuL g (ccu: CcuThunk) = entityL g ccu.Contents - and decisionTreeL x = + and decisionTreeL g x = match x with | TDBind (bind, body) -> - let bind = wordL(tagText "let") ^^ bindingL bind ^^ wordL(tagText "in") - (bind @@ decisionTreeL body) + let bind = wordL(tagText "let") ^^ bindingL g bind + (bind @@ decisionTreeL g body) | TDSuccess (args, n) -> - wordL(tagText "Success") ^^ leftL(tagText "T") ^^ intL n ^^ tupleL (args |> List.map exprL) - | TDSwitch (test, dcases, dflt, _) -> - (wordL(tagText "Switch") --- exprL test) @@-- - (aboveListL (List.map dcaseL dcases) @@ + wordL(tagText "Success") ^^ leftL(tagText "T") ^^ intL n ^^ tupleL (args |> List.map (exprL g)) + | TDSwitch (test, dcases, dflt, _) -> + (wordL(tagText "Switch") --- exprL g test) @@-- + (aboveListL (List.map (dcaseL g) dcases) @@ match dflt with | None -> emptyL - | Some dtree -> wordL(tagText "dflt:") --- decisionTreeL dtree) + | Some dtree -> wordL(tagText "dflt:") --- decisionTreeL g dtree) - and dcaseL (TCase (test, dtree)) = (dtestL test ^^ wordL(tagText "//")) --- decisionTreeL dtree + and dcaseL g (TCase (test, dtree)) = (dtestL g test ^^ wordL(tagText "//")) --- decisionTreeL g dtree - and dtestL x = + and dtestL g x = match x with | (DecisionTreeTest.UnionCase (c, tinst)) -> wordL(tagText "is") ^^ unionCaseRefL c ^^ instL typeL tinst | (DecisionTreeTest.ArrayLength (n, ty)) -> wordL(tagText "length") ^^ intL n ^^ typeL ty | (DecisionTreeTest.Const c) -> wordL(tagText "is") ^^ constL c | (DecisionTreeTest.IsNull ) -> wordL(tagText "isnull") | (DecisionTreeTest.IsInst (_, ty)) -> wordL(tagText "isinst") ^^ typeL ty - | (DecisionTreeTest.ActivePatternCase (exp, _, _, _, _)) -> wordL(tagText "query") ^^ exprL exp + | (DecisionTreeTest.ActivePatternCase (exp, _, _, _, _)) -> wordL(tagText "query") ^^ exprL g exp + | (DecisionTreeTest.Error _) -> wordL (tagText "error recovery") - and targetL i (TTarget (argvs, body, _)) = leftL(tagText "T") ^^ intL i ^^ tupleL (flatValsL argvs) ^^ rightL(tagText ":") --- exprL body + and targetL g i (TTarget (argvs, body, _)) = + leftL(tagText "T") ^^ intL i ^^ tupleL (flatValsL argvs) ^^ rightL(tagText ":") --- exprL g body and flatValsL vs = vs |> List.map valL - and tmethodL (TObjExprMethod(TSlotSig(nm, _, _, _, _, _), _, tps, vs, e, _)) = - (wordL(tagText "TObjExprMethod") --- (wordL (tagText nm)) ^^ wordL(tagText "=")) -- - (wordL(tagText "METH-LAM") --- angleBracketListL (List.map typarL tps) ^^ rightL(tagText ".")) --- - (wordL(tagText "meth-lam") --- tupleL (List.map (List.map valAtBindL >> tupleL) vs) ^^ rightL(tagText ".")) --- - (atomL e) + and tmethodL g (TObjExprMethod(TSlotSig(nm, _, _, _, _, _), _, tps, vs, e, _)) = + ((wordL(tagText "TObjExprMethod") --- (wordL (tagText nm)) ^^ wordL(tagText "=")) -- + (angleBracketListL (List.map typarL tps) ^^ rightL(tagText ".")) --- + (tupleL (List.map (List.map (valAtBindL g) >> tupleL) vs) ^^ rightL(tagText "."))) + @@-- + (atomL g e) - and overrideL tmeth = wordL(tagText "with") ^^ tmethodL tmeth - - and iimplL (ty, tmeths) = wordL(tagText "impl") ^^ aboveListL (typeL ty :: List.map tmethodL tmeths) + and iimplL g (ty, tmeths) = wordL(tagText "impl") ^^ aboveListL (typeL ty :: List.map (tmethodL g) tmeths) let showType x = Layout.showL (typeL x) - let showExpr x = Layout.showL (exprL x) + let showExpr g x = Layout.showL (exprL g x) let traitL x = auxTraitL SimplifyTypes.typeSimplificationInfo0 x @@ -3868,18 +3980,18 @@ module DebugPrint = //-------------------------------------------------------------------------- let wrapModuleOrNamespaceType id cpath mtyp = - NewModuleOrNamespace (Some cpath) taccessPublic id XmlDoc.Empty [] (MaybeLazy.Strict mtyp) + Construct.NewModuleOrNamespace (Some cpath) taccessPublic id XmlDoc.Empty [] (MaybeLazy.Strict mtyp) let wrapModuleOrNamespaceTypeInNamespace id cpath mtyp = let mspec = wrapModuleOrNamespaceType id cpath mtyp - NewModuleOrNamespaceType Namespace [ mspec ] [], mspec + Construct.NewModuleOrNamespaceType Namespace [ mspec ] [], mspec let wrapModuleOrNamespaceExprInNamespace (id: Ident) cpath mexpr = - let mspec = wrapModuleOrNamespaceType id cpath (NewEmptyModuleOrNamespaceType Namespace) + let mspec = wrapModuleOrNamespaceType id cpath (Construct.NewEmptyModuleOrNamespaceType Namespace) TMDefRec (false, [], [ModuleOrNamespaceBinding.Module(mspec, mexpr)], id.idRange) // cleanup: make this a property -let SigTypeOfImplFile (TImplFile(_, _, mexpr, _, _, _)) = mexpr.Type +let SigTypeOfImplFile (TImplFile (_, _, mexpr, _, _, _)) = mexpr.Type //-------------------------------------------------------------------------- // Data structures representing what gets hidden and what gets remapped (i.e. renamed or alpha-converted) @@ -3992,7 +4104,6 @@ let accValRemap g aenv (msigty: ModuleOrNamespaceType) (implVal: Val) (mrpi, mhi let vref = mkLocalValRef implVal match sigValOpt with | None -> - if verbose then dprintf "accValRemap, hide = %s#%d\n" implVal.LogicalName implVal.Stamp let mhi = { mhi with HiddenVals = Zset.add implVal mhi.HiddenVals } (mrpi, mhi) | Some (sigVal: Val) -> @@ -4002,7 +4113,7 @@ let accValRemap g aenv (msigty: ModuleOrNamespaceType) (implVal: Val) (mrpi, mhi let getCorrespondingSigTy nm (msigty: ModuleOrNamespaceType) = match NameMap.tryFind nm msigty.AllEntitiesByCompiledAndLogicalMangledNames with - | None -> NewEmptyModuleOrNamespaceType ModuleOrType + | None -> Construct.NewEmptyModuleOrNamespaceType ModuleOrType | Some sigsubmodul -> sigsubmodul.ModuleOrNamespaceType let rec accEntityRemapFromModuleOrNamespaceType (mty: ModuleOrNamespaceType) (msigty: ModuleOrNamespaceType) acc = @@ -4016,7 +4127,6 @@ let rec accValRemapFromModuleOrNamespaceType g aenv (mty: ModuleOrNamespaceType) acc let ComputeRemappingFromInferredSignatureToExplicitSignature g mty msigty = - // dprintf "ComputeRemappingFromInferredSignatureToExplicitSignature, \nmty = %s\nmmsigty=%s\n" (showL(entityTypeL mty)) (showL(entityTypeL msigty)) let ((mrpi, _) as entityRemap) = accEntityRemapFromModuleOrNamespaceType mty msigty (SignatureRepackageInfo.Empty, SignatureHidingInfo.Empty) let aenv = mrpi.ImplToSigMapping let valAndEntityRemap = accValRemapFromModuleOrNamespaceType g aenv mty msigty entityRemap @@ -4077,7 +4187,6 @@ and accValRemapFromModuleOrNamespaceBind g aenv msigty x acc = and accValRemapFromModuleOrNamespaceDefs g aenv msigty mdefs acc = List.foldBack (accValRemapFromModuleOrNamespace g aenv msigty) mdefs acc let ComputeRemappingFromImplementationToSignature g mdef msigty = - //if verbose then dprintf "ComputeRemappingFromImplementationToSignature, \nmdefs = %s\nmsigty=%s\n" (showL(DebugPrint.mdefL mdef)) (showL(DebugPrint.entityTypeL msigty)) let ((mrpi, _) as entityRemap) = accEntityRemapFromModuleOrNamespace msigty mdef (SignatureRepackageInfo.Empty, SignatureHidingInfo.Empty) let aenv = mrpi.ImplToSigMapping @@ -4133,16 +4242,14 @@ let rec accModuleOrNamespaceHidingInfoAtAssemblyBoundary mty acc = acc let ComputeHidingInfoAtAssemblyBoundary mty acc = -// dprintf "ComputeRemappingFromInferredSignatureToExplicitSignature, \nmty = %s\nmmsigty=%s\n" (showL(entityTypeL mty)) (showL(entityTypeL msigty)) accModuleOrNamespaceHidingInfoAtAssemblyBoundary mty acc //-------------------------------------------------------------------------- // Compute instances of the above for mexpr -> mty //-------------------------------------------------------------------------- -let IsHidden setF accessF remapF debugF = +let IsHidden setF accessF remapF = let rec check mrmi x = - if verbose then dprintf "IsHidden %s ??\n" (showL (debugF x)) // Internal/private? not (canAccessFromEverywhere (accessF x)) || (match mrmi with @@ -4153,14 +4260,15 @@ let IsHidden setF accessF remapF debugF = // Recurse... check rest (remapF rpi x)) fun mrmi x -> - let res = check mrmi x - if verbose then dprintf "IsHidden, #mrmi = %d, %s = %b\n" mrmi.Length (showL (debugF x)) res - res - -let IsHiddenTycon mrmi x = IsHidden (fun mhi -> mhi.HiddenTycons) (fun tc -> tc.Accessibility) (fun rpi x -> (remapTyconRef rpi.tyconRefRemap (mkLocalTyconRef x)).Deref) DebugPrint.tyconL mrmi x -let IsHiddenTyconRepr mrmi x = IsHidden (fun mhi -> mhi.HiddenTyconReprs) (fun v -> v.TypeReprAccessibility) (fun rpi x -> (remapTyconRef rpi.tyconRefRemap (mkLocalTyconRef x)).Deref) DebugPrint.tyconL mrmi x -let IsHiddenVal mrmi x = IsHidden (fun mhi -> mhi.HiddenVals) (fun v -> v.Accessibility) (fun rpi x -> (remapValRef rpi (mkLocalValRef x)).Deref) DebugPrint.valL mrmi x -let IsHiddenRecdField mrmi x = IsHidden (fun mhi -> mhi.HiddenRecdFields) (fun rfref -> rfref.RecdField.Accessibility) (fun rpi x -> remapRecdFieldRef rpi.tyconRefRemap x) DebugPrint.recdFieldRefL mrmi x + check mrmi x + +let IsHiddenTycon mrmi x = IsHidden (fun mhi -> mhi.HiddenTycons) (fun tc -> tc.Accessibility) (fun rpi x -> (remapTyconRef rpi.tyconRefRemap (mkLocalTyconRef x)).Deref) mrmi x + +let IsHiddenTyconRepr mrmi x = IsHidden (fun mhi -> mhi.HiddenTyconReprs) (fun v -> v.TypeReprAccessibility) (fun rpi x -> (remapTyconRef rpi.tyconRefRemap (mkLocalTyconRef x)).Deref) mrmi x + +let IsHiddenVal mrmi x = IsHidden (fun mhi -> mhi.HiddenVals) (fun v -> v.Accessibility) (fun rpi x -> (remapValRef rpi (mkLocalValRef x)).Deref) mrmi x + +let IsHiddenRecdField mrmi x = IsHidden (fun mhi -> mhi.HiddenRecdFields) (fun rfref -> rfref.RecdField.Accessibility) (fun rpi x -> remapRecdFieldRef rpi.tyconRefRemap x) mrmi x //-------------------------------------------------------------------------- // Generic operations on module types @@ -4189,14 +4297,14 @@ let isPublicTycon (tcref: Tycon) = (tcref.Accessibility = taccessPublic) let freeVarsAllPublic fvs = // Are any non-public items used in the expr (which corresponded to the fvs)? // Recall, taccess occurs in: - // EntityData has ReprAccessibility and Accessiblity + // EntityData has ReprAccessibility and Accessibility // UnionCase has Accessibility // RecdField has Accessibility // ValData has Accessibility // The freevars and FreeTyvars collect local constructs. // Here, we test that all those constructs are public. // - // CODEREVIEW: + // CODE REVIEW: // What about non-local vals. This fix assumes non-local vals must be public. OK? Zset.forall isPublicVal fvs.FreeLocals && Zset.forall isPublicUnionCase fvs.FreeUnionCases && @@ -4295,6 +4403,10 @@ let bindLhs opts (bind: Binding) fvs = boundLocalVal opts bind.Var fvs let freeVarsCacheCompute opts cache f = if opts.canCache then cached cache f else f() +let tryGetFreeVarsCacheValue opts cache = + if opts.canCache then tryGetCacheValue cache + else ValueNone + let rec accBindRhs opts (TBind(_, repr, _)) acc = accFreeInExpr opts repr acc and accFreeInSwitchCases opts csl dflt (acc: FreeVars) = @@ -4314,6 +4426,7 @@ and accFreeInTest (opts: FreeVarOptions) discrim acc = accFreeInExpr opts exp (accFreeVarsInTys opts tys (Option.foldBack (fun (vref, tinst) acc -> accFreeValRef opts vref (accFreeVarsInTys opts tinst acc)) activePatIdentity acc)) + | DecisionTreeTest.Error _ -> acc and accFreeInDecisionTree opts x (acc: FreeVars) = match x with @@ -4370,7 +4483,7 @@ and accFreeRecdFieldRef opts rfref fvs = and accFreeExnRef _exnc fvs = fvs // Note: this exnc (TyconRef) should be collected the surround types, e.g. tinst of Expr.Op and accFreeValRef opts (vref: ValRef) fvs = match vref.IsLocalRef with - | true -> accFreeLocalVal opts vref.PrivateTarget fvs + | true -> accFreeLocalVal opts vref.ResolvedTarget fvs // non-local values do not contain free variables | _ -> fvs @@ -4392,13 +4505,16 @@ and accFreeInExpr (opts: FreeVarOptions) x acc = and accFreeInExprLinear (opts: FreeVarOptions) x acc contf = // for nested let-bindings, we need to continue after the whole let-binding is processed match x with - | Expr.Let (bind, e, _, cache) -> - let contf = contf << (fun free -> - unionFreeVars (freeVarsCacheCompute opts cache (fun () -> bindLhs opts bind (accBindRhs opts bind free))) acc ) - accFreeInExprLinear opts e emptyFreeVars contf + | Expr.Let (bind, e, _, cache) -> + match tryGetFreeVarsCacheValue opts cache with + | ValueSome free -> contf (unionFreeVars free acc) + | _ -> + accFreeInExprLinear opts e emptyFreeVars (contf << (fun free -> + unionFreeVars (freeVarsCacheCompute opts cache (fun () -> bindLhs opts bind (accBindRhs opts bind free))) acc + )) | _ -> - // No longer linear expr - accFreeInExpr opts x acc |> contf + // No longer linear expr + contf (accFreeInExpr opts x acc) and accFreeInExprNonLinear opts x acc = match x with @@ -4450,13 +4566,13 @@ and accFreeInExprNonLinear opts x acc = | Expr.Quote (ast, {contents=None}, _, _, ty) -> accFreeInExpr opts ast (accFreeVarsInTy opts ty acc) - | Expr.App(f0, f0ty, tyargs, args, _) -> + | Expr.App (f0, f0ty, tyargs, args, _) -> accFreeVarsInTy opts f0ty (accFreeInExpr opts f0 (accFreeVarsInTys opts tyargs (accFreeInExprs opts args acc))) - | Expr.Link(eref) -> accFreeInExpr opts !eref acc + | Expr.Link eref -> accFreeInExpr opts !eref acc | Expr.Sequential (expr1, expr2, _, _, _) -> let acc = accFreeInExpr opts expr1 acc @@ -4544,7 +4660,7 @@ and accFreeInOp opts op acc = | TOp.Reraise -> accUsesRethrow true acc - | TOp.TraitCall(TTrait(tys, _, _, argtys, rty, sln)) -> + | TOp.TraitCall (TTrait(tys, _, _, argtys, rty, sln)) -> Option.foldBack (accFreeVarsInTraitSln opts) sln.Value (accFreeVarsInTys opts tys (accFreeVarsInTys opts argtys @@ -4574,7 +4690,7 @@ and accFreeInExprs opts (exprs: Exprs) acc = | [h]-> // tailcall - e.g. Cons(x, Cons(x2, .......Cons(x1000000, Nil))) and [| x1; .... ; x1000000 |] accFreeInExpr opts h acc - | h:: t -> + | h :: t -> let acc = accFreeInExpr opts h acc accFreeInExprs opts t acc @@ -4635,7 +4751,7 @@ let rec stripLambdaN n expr = let tryStripLambdaN n expr = match expr with - | Expr.Lambda(_, None, None, _, _, _, _) -> + | Expr.Lambda (_, None, None, _, _, _, _) -> let argvsl, bodyExpr, remaining = stripLambdaN n expr if remaining = 0 then Some (argvsl, bodyExpr) else None @@ -4778,14 +4894,14 @@ let decideStaticOptimizationConstraint g c = checkTypes a b | TTyconIsStruct a -> let a = normalizeEnumTy g (stripTyEqnsAndMeasureEqns g a) - match tryDestAppTy g a with + match tryTcrefOfAppTy g a with | ValueSome tcref1 -> if tcref1.IsStructOrEnumTycon then StaticOptimizationAnswer.Yes else StaticOptimizationAnswer.No | ValueNone -> StaticOptimizationAnswer.Unknown let rec DecideStaticOptimizations g cs = match cs with | [] -> StaticOptimizationAnswer.Yes - | h:: t -> + | h :: t -> let d = decideStaticOptimizationConstraint g h if d = StaticOptimizationAnswer.No then StaticOptimizationAnswer.No elif d = StaticOptimizationAnswer.Yes then DecideStaticOptimizations g t @@ -4795,7 +4911,7 @@ let mkStaticOptimizationExpr g (cs, e1, e2, m) = let d = DecideStaticOptimizations g cs in if d = StaticOptimizationAnswer.No then e2 elif d = StaticOptimizationAnswer.Yes then e1 - else Expr.StaticOptimization(cs, e1, e2, m) + else Expr.StaticOptimization (cs, e1, e2, m) //-------------------------------------------------------------------------- // Copy expressions, including new names for locally bound values. @@ -4894,7 +5010,7 @@ and mapImmediateValsAndTycons ft fv (x: ModuleOrNamespaceType) = and copyVal compgen (v: Val) = match compgen with | OnlyCloneExprVals when v.IsMemberOrModuleBinding -> v - | _ -> v |> NewModifiedVal id + | _ -> v |> Construct.NewModifiedVal id and fixupValData g compgen tmenv (v2: Val) = // only fixup if we copy the value @@ -4942,11 +5058,11 @@ and remapExpr (g: TcGlobals) (compgen: ValCopyFlag) (tmenv: Remap) expr = | Expr.TyChoose (tps, b, m) -> let tps', tmenvinner = tmenvCopyRemapAndBindTypars (remapAttribs g tmenv) tmenv tps - Expr.TyChoose(tps', remapExpr g compgen tmenvinner b, m) + Expr.TyChoose (tps', remapExpr g compgen tmenvinner b, m) | Expr.LetRec (binds, e, m, _) -> let binds', tmenvinner = copyAndRemapAndBindBindings g compgen tmenv binds - Expr.LetRec (binds', remapExpr g compgen tmenvinner e, m, NewFreeVarsCache()) + Expr.LetRec (binds', remapExpr g compgen tmenvinner e, m, Construct.NewFreeVarsCache()) | Expr.Match (spBind, exprm, pt, targets, m, ty) -> primMkMatch (spBind, exprm, remapDecisionTree g compgen tmenv pt, @@ -4986,7 +5102,7 @@ and remapExpr (g: TcGlobals) (compgen: ValCopyFlag) (tmenv: Remap) expr = let tinst = remapTypes tmenv tinst let arg = remapExpr g compgen tmenv arg let tmp, _ = mkMutableCompGenLocal m "copyOfStruct" (actualTyOfRecdFieldRef rfref tinst) - mkCompGenLet m tmp (mkRecdFieldGetViaExprAddr(arg, rfref, tinst, m)) (mkValAddr m readonly (mkLocalValRef tmp)) + mkCompGenLet m tmp (mkRecdFieldGetViaExprAddr (arg, rfref, tinst, m)) (mkValAddr m readonly (mkLocalValRef tmp)) | Expr.Op (TOp.UnionCaseFieldGetAddr (uref, cidx, readonly), tinst, [arg], m) when not (uref.FieldByIndex(cidx).IsMutable) && @@ -4995,7 +5111,7 @@ and remapExpr (g: TcGlobals) (compgen: ValCopyFlag) (tmenv: Remap) expr = let tinst = remapTypes tmenv tinst let arg = remapExpr g compgen tmenv arg let tmp, _ = mkMutableCompGenLocal m "copyOfStruct" (actualTyOfUnionFieldRef uref cidx tinst) - mkCompGenLet m tmp (mkUnionCaseFieldGetProvenViaExprAddr(arg, uref, tinst, cidx, m)) (mkValAddr m readonly (mkLocalValRef tmp)) + mkCompGenLet m tmp (mkUnionCaseFieldGetProvenViaExprAddr (arg, uref, tinst, cidx, m)) (mkValAddr m readonly (mkLocalValRef tmp)) | Expr.Op (op, tinst, args, m) -> let op' = remapOp tmenv op @@ -5004,15 +5120,15 @@ and remapExpr (g: TcGlobals) (compgen: ValCopyFlag) (tmenv: Remap) expr = if op === op' && tinst === tinst' && args === args' then expr else Expr.Op (op', tinst', args', m) - | Expr.App(e1, e1ty, tyargs, args, m) -> + | Expr.App (e1, e1ty, tyargs, args, m) -> let e1' = remapExpr g compgen tmenv e1 let e1ty' = remapPossibleForallTy g tmenv e1ty let tyargs' = remapTypes tmenv tyargs let args' = remapExprs g compgen tmenv args if e1 === e1' && e1ty === e1ty' && tyargs === tyargs' && args === args' then expr - else Expr.App(e1', e1ty', tyargs', args', m) + else Expr.App (e1', e1ty', tyargs', args', m) - | Expr.Link(eref) -> + | Expr.Link eref -> remapExpr g compgen tmenv !eref | Expr.StaticOptimization (cs, e2, e3, m) -> @@ -5066,28 +5182,28 @@ and remapLinearExpr g compgen tmenv expr contf = and remapConstraint tyenv c = match c with | TTyconEqualsTycon(ty1, ty2) -> TTyconEqualsTycon(remapType tyenv ty1, remapType tyenv ty2) - | TTyconIsStruct(ty1) -> TTyconIsStruct(remapType tyenv ty1) + | TTyconIsStruct ty1 -> TTyconIsStruct(remapType tyenv ty1) and remapOp tmenv op = match op with - | TOp.Recd (ctor, tcref) -> TOp.Recd(ctor, remapTyconRef tmenv.tyconRefRemap tcref) - | TOp.UnionCaseTagGet tcref -> TOp.UnionCaseTagGet(remapTyconRef tmenv.tyconRefRemap tcref) - | TOp.UnionCase ucref -> TOp.UnionCase(remapUnionCaseRef tmenv.tyconRefRemap ucref) - | TOp.UnionCaseProof ucref -> TOp.UnionCaseProof(remapUnionCaseRef tmenv.tyconRefRemap ucref) - | TOp.ExnConstr ec -> TOp.ExnConstr(remapTyconRef tmenv.tyconRefRemap ec) - | TOp.ExnFieldGet (ec, n) -> TOp.ExnFieldGet(remapTyconRef tmenv.tyconRefRemap ec, n) - | TOp.ExnFieldSet (ec, n) -> TOp.ExnFieldSet(remapTyconRef tmenv.tyconRefRemap ec, n) - | TOp.ValFieldSet rfref -> TOp.ValFieldSet(remapRecdFieldRef tmenv.tyconRefRemap rfref) - | TOp.ValFieldGet rfref -> TOp.ValFieldGet(remapRecdFieldRef tmenv.tyconRefRemap rfref) - | TOp.ValFieldGetAddr (rfref, readonly) -> TOp.ValFieldGetAddr(remapRecdFieldRef tmenv.tyconRefRemap rfref, readonly) - | TOp.UnionCaseFieldGet (ucref, n) -> TOp.UnionCaseFieldGet(remapUnionCaseRef tmenv.tyconRefRemap ucref, n) - | TOp.UnionCaseFieldGetAddr (ucref, n, readonly) -> TOp.UnionCaseFieldGetAddr(remapUnionCaseRef tmenv.tyconRefRemap ucref, n, readonly) - | TOp.UnionCaseFieldSet (ucref, n) -> TOp.UnionCaseFieldSet(remapUnionCaseRef tmenv.tyconRefRemap ucref, n) + | TOp.Recd (ctor, tcref) -> TOp.Recd (ctor, remapTyconRef tmenv.tyconRefRemap tcref) + | TOp.UnionCaseTagGet tcref -> TOp.UnionCaseTagGet (remapTyconRef tmenv.tyconRefRemap tcref) + | TOp.UnionCase ucref -> TOp.UnionCase (remapUnionCaseRef tmenv.tyconRefRemap ucref) + | TOp.UnionCaseProof ucref -> TOp.UnionCaseProof (remapUnionCaseRef tmenv.tyconRefRemap ucref) + | TOp.ExnConstr ec -> TOp.ExnConstr (remapTyconRef tmenv.tyconRefRemap ec) + | TOp.ExnFieldGet (ec, n) -> TOp.ExnFieldGet (remapTyconRef tmenv.tyconRefRemap ec, n) + | TOp.ExnFieldSet (ec, n) -> TOp.ExnFieldSet (remapTyconRef tmenv.tyconRefRemap ec, n) + | TOp.ValFieldSet rfref -> TOp.ValFieldSet (remapRecdFieldRef tmenv.tyconRefRemap rfref) + | TOp.ValFieldGet rfref -> TOp.ValFieldGet (remapRecdFieldRef tmenv.tyconRefRemap rfref) + | TOp.ValFieldGetAddr (rfref, readonly) -> TOp.ValFieldGetAddr (remapRecdFieldRef tmenv.tyconRefRemap rfref, readonly) + | TOp.UnionCaseFieldGet (ucref, n) -> TOp.UnionCaseFieldGet (remapUnionCaseRef tmenv.tyconRefRemap ucref, n) + | TOp.UnionCaseFieldGetAddr (ucref, n, readonly) -> TOp.UnionCaseFieldGetAddr (remapUnionCaseRef tmenv.tyconRefRemap ucref, n, readonly) + | TOp.UnionCaseFieldSet (ucref, n) -> TOp.UnionCaseFieldSet (remapUnionCaseRef tmenv.tyconRefRemap ucref, n) | TOp.ILAsm (instrs, tys) -> let tys2 = remapTypes tmenv tys if tys === tys2 then op else TOp.ILAsm (instrs, tys2) - | TOp.TraitCall traitInfo -> TOp.TraitCall(remapTraitAux tmenv traitInfo) + | TOp.TraitCall traitInfo -> TOp.TraitCall (remapTraitAux tmenv traitInfo) | TOp.LValueOp (kind, lvr) -> TOp.LValueOp (kind, remapValRef tmenv lvr) | TOp.ILCall (isVirtCall, isProtectedCall, valu, isNewObjCall, valUseFlags, isProperty, noTailCall, ilMethRef, enclTypeArgs, methTypeArgs, tys) -> TOp.ILCall (isVirtCall, isProtectedCall, valu, isNewObjCall, remapValFlags tmenv valUseFlags, @@ -5117,6 +5233,7 @@ and remapDecisionTree g compgen tmenv x = | DecisionTreeTest.IsInst (srcty, tgty) -> DecisionTreeTest.IsInst (remapType tmenv srcty, remapType tmenv tgty) | DecisionTreeTest.IsNull -> DecisionTreeTest.IsNull | DecisionTreeTest.ActivePatternCase _ -> failwith "DecisionTreeTest.ActivePatternCase should only be used during pattern match compilation" + | DecisionTreeTest.Error _ -> failwith "DecisionTreeTest.Error should only be used during pattern match compilation" TCase(test', remapDecisionTree g compgen tmenv y)) csl, Option.map (remapDecisionTree g compgen tmenv) dflt, m) @@ -5156,7 +5273,7 @@ and remapRecdField g tmenv x = rfield_fattribs = x.rfield_fattribs |> remapAttribs g tmenv } and remapRecdFields g tmenv (x: TyconRecdFields) = - x.AllFieldsAsList |> List.map (remapRecdField g tmenv) |> MakeRecdFieldsTable + x.AllFieldsAsList |> List.map (remapRecdField g tmenv) |> Construct.MakeRecdFieldsTable and remapUnionCase g tmenv (x: UnionCase) = { x with @@ -5165,7 +5282,7 @@ and remapUnionCase g tmenv (x: UnionCase) = Attribs = x.Attribs |> remapAttribs g tmenv } and remapUnionCases g tmenv (x: TyconUnionData) = - x.UnionCasesAsList |> List.map (remapUnionCase g tmenv) |> MakeUnionCases + x.UnionCasesAsList |> List.map (remapUnionCase g tmenv) |> Construct.MakeUnionCases and remapFsObjData g tmenv x = { x with @@ -5236,16 +5353,16 @@ and copyAndRemapAndBindModTy g compgen tmenv mty = let _, _, tmenvinner = copyAndRemapAndBindTyconsAndVals g compgen tmenv tycons vs remapModTy g compgen tmenvinner mty, tmenvinner -and remapModTy _g _compgen tmenv mty = - mapImmediateValsAndTycons (renameTycon tmenv) (renameVal tmenv) mty +and remapModTy g _compgen tmenv mty = + mapImmediateValsAndTycons (renameTycon g tmenv) (renameVal tmenv) mty -and renameTycon tyenv x = +and renameTycon g tyenv x = let tcref = - try + try let res = tyenv.tyconRefRemap.[mkLocalTyconRef x] res with :? KeyNotFoundException -> - errorR(InternalError("couldn't remap internal tycon " + showL(DebugPrint.tyconL x), x.Range)) + errorR(InternalError("couldn't remap internal tycon " + showL(DebugPrint.tyconL g x), x.Range)) mkLocalTyconRef x tcref.Deref @@ -5257,7 +5374,7 @@ and renameVal tmenv x = and copyTycon compgen (tycon: Tycon) = match compgen with | OnlyCloneExprVals -> tycon - | _ -> NewClonedTycon tycon + | _ -> Construct.NewClonedTycon tycon /// This operates over a whole nested collection of tycons and vals simultaneously *) and copyAndRemapAndBindTyconsAndVals g compgen tmenv tycons vs = @@ -5281,17 +5398,17 @@ and copyAndRemapAndBindTyconsAndVals g compgen tmenv tycons vs = mkLocalValRef v vref.Deref - let lookupTycon tycon = + let lookupTycon g tycon = let tcref = try let res = tmenvinner.tyconRefRemap.[mkLocalTyconRef tycon] res with :? KeyNotFoundException -> - errorR(InternalError("couldn't remap internal tycon " + showL(DebugPrint.tyconL tycon), tycon.Range)) + errorR(InternalError("couldn't remap internal tycon " + showL(DebugPrint.tyconL g tycon), tycon.Range)) mkLocalTyconRef tycon tcref.Deref - - (tycons, tycons') ||> List.iter2 (fun tcd tcd' -> + (tycons, tycons') ||> List.iter2 (fun tcd tcd' -> + let lookupTycon tycon = lookupTycon g tycon let tps', tmenvinner2 = tmenvCopyRemapAndBindTypars (remapAttribs g tmenvinner) tmenvinner (tcd.entity_typars.Force(tcd.entity_range)) tcd'.entity_typars <- LazyWithContext.NotLazy tps' tcd'.entity_attribs <- tcd.entity_attribs |> remapAttribs g tmenvinner2 @@ -5373,7 +5490,7 @@ and remapAndRenameModDef g compgen tmenv mdef = match mdef with | TMDefRec(isRec, tycons, mbinds, m) -> // Abstract (virtual) vslots in the tycons at TMDefRec nodes are binders. They also need to be copied and renamed. - let tycons = tycons |> List.map (renameTycon tmenv) + let tycons = tycons |> List.map (renameTycon g tmenv) let mbinds = mbinds |> List.map (remapAndRenameModBind g compgen tmenv) TMDefRec(isRec, tycons, mbinds, m) | TMDefLet(bind, m) -> @@ -5397,7 +5514,7 @@ and remapAndRenameModBind g compgen tmenv x = let bind2 = remapAndRenameBind g compgen tmenv bind v2 ModuleOrNamespaceBinding.Binding bind2 | ModuleOrNamespaceBinding.Module(mspec, def) -> - let mspec = renameTycon tmenv mspec + let mspec = renameTycon g tmenv mspec let def = remapAndRenameModDef g compgen tmenv def ModuleOrNamespaceBinding.Module(mspec, def) @@ -5435,8 +5552,8 @@ let rec remarkExpr m x = Expr.Let (remarkBind m bind, remarkExpr m e, m, fvs) | Expr.Match (_, _, pt, targets, _, ty) -> - let targetsR = targets |> Array.map (fun (TTarget(vs, e, _)) -> TTarget(vs, remarkExpr m e, SuppressSequencePointAtTarget)) - primMkMatch (NoSequencePointAtInvisibleBinding, m, remarkDecisionTree m pt, targetsR, m, ty) + let targetsR = targets |> Array.map (fun (TTarget(vs, e, _)) -> TTarget(vs, remarkExpr m e, DebugPointForTarget.No)) + primMkMatch (NoDebugPointAtInvisibleBinding, m, remarkDecisionTree m pt, targetsR, m, ty) | Expr.Val (x, valUseFlags, _) -> Expr.Val (x, valUseFlags, m) @@ -5452,21 +5569,21 @@ let rec remarkExpr m x = | Expr.Op (op, tinst, args, _) -> let op = match op with - | TOp.TryFinally(_, _) -> TOp.TryFinally(NoSequencePointAtTry, NoSequencePointAtFinally) - | TOp.TryCatch(_, _) -> TOp.TryCatch(NoSequencePointAtTry, NoSequencePointAtWith) + | TOp.TryFinally (_, _) -> TOp.TryFinally (DebugPointAtTry.No, DebugPointAtFinally.No) + | TOp.TryCatch (_, _) -> TOp.TryCatch (DebugPointAtTry.No, DebugPointAtWith.No) | _ -> op Expr.Op (op, tinst, remarkExprs m args, m) - | Expr.Link (eref) -> + | Expr.Link eref -> // Preserve identity of fixup nodes during remarkExpr eref := remarkExpr m !eref x - | Expr.App(e1, e1ty, tyargs, args, _) -> - Expr.App(remarkExpr m e1, e1ty, tyargs, remarkExprs m args, m) + | Expr.App (e1, e1ty, tyargs, args, _) -> + Expr.App (remarkExpr m e1, e1ty, tyargs, remarkExprs m args, m) | Expr.Sequential (e1, e2, dir, _, _) -> - Expr.Sequential (remarkExpr m e1, remarkExpr m e2, dir, SuppressSequencePointOnExprOfSequential, m) + Expr.Sequential (remarkExpr m e1, remarkExpr m e2, dir, DebugPointAtSequential.StmtOnly, m) | Expr.StaticOptimization (eqns, e2, e3, _) -> Expr.StaticOptimization (eqns, remarkExpr m e2, remarkExpr m e3, m) @@ -5497,7 +5614,7 @@ and remarkBinds m binds = List.map (remarkBind m) binds // This very deliberately drops the sequence points since this is used when adjusting the marks for inlined expressions and remarkBind m (TBind(v, repr, _)) = - TBind(v, remarkExpr m repr, NoSequencePointAtStickyBinding) + TBind(v, remarkExpr m repr, NoDebugPointAtStickyBinding) //-------------------------------------------------------------------------- // Mutability analysis @@ -5584,48 +5701,48 @@ let mkByteArrayTy (g: TcGlobals) = mkArrayType g g.byte_ty let rec tyOfExpr g e = match e with - | Expr.App(_, fty, tyargs, args, _) -> applyTys g fty (tyargs, args) + | Expr.App (_, fty, tyargs, args, _) -> applyTys g fty (tyargs, args) | Expr.Obj (_, ty, _, _, _, _, _) | Expr.Match (_, _, _, _, _, ty) - | Expr.Quote(_, _, _, _, ty) - | Expr.Const(_, _, ty) -> (ty) - | Expr.Val(vref, _, _) -> vref.Type - | Expr.Sequential(a, b, k, _, _) -> tyOfExpr g (match k with NormalSeq -> b | ThenDoSeq -> a) - | Expr.Lambda(_, _, _, vs, _, _, rty) -> (mkRefTupledVarsTy g vs --> rty) - | Expr.TyLambda(_, tyvs, _, _, rty) -> (tyvs +-> rty) - | Expr.Let(_, e, _, _) - | Expr.TyChoose(_, e, _) + | Expr.Quote (_, _, _, _, ty) + | Expr.Const (_, _, ty) -> (ty) + | Expr.Val (vref, _, _) -> vref.Type + | Expr.Sequential (a, b, k, _, _) -> tyOfExpr g (match k with NormalSeq -> b | ThenDoSeq -> a) + | Expr.Lambda (_, _, _, vs, _, _, rty) -> (mkRefTupledVarsTy g vs --> rty) + | Expr.TyLambda (_, tyvs, _, _, rty) -> (tyvs +-> rty) + | Expr.Let (_, e, _, _) + | Expr.TyChoose (_, e, _) | Expr.Link { contents=e} | Expr.StaticOptimization (_, _, e, _) - | Expr.LetRec(_, e, _, _) -> tyOfExpr g e + | Expr.LetRec (_, e, _, _) -> tyOfExpr g e | Expr.Op (op, tinst, _, _) -> match op with | TOp.Coerce -> (match tinst with [to_ty;_fromTy] -> to_ty | _ -> failwith "bad TOp.Coerce node") - | (TOp.ILCall (_, _, _, _, _, _, _, _, _, _, rtys) | TOp.ILAsm(_, rtys)) -> (match rtys with [h] -> h | _ -> g.unit_ty) + | (TOp.ILCall (_, _, _, _, _, _, _, _, _, _, rtys) | TOp.ILAsm (_, rtys)) -> (match rtys with [h] -> h | _ -> g.unit_ty) | TOp.UnionCase uc -> actualResultTyOfUnionCase tinst uc | TOp.UnionCaseProof uc -> mkProvenUnionCaseTy uc tinst | TOp.Recd (_, tcref) -> mkAppTy tcref tinst | TOp.ExnConstr _ -> g.exn_ty | TOp.Bytes _ -> mkByteArrayTy g | TOp.UInt16s _ -> mkArrayType g g.uint16_ty - | TOp.AnonRecdGet(_, i) -> List.item i tinst - | TOp.TupleFieldGet(_, i) -> List.item i tinst + | TOp.AnonRecdGet (_, i) -> List.item i tinst + | TOp.TupleFieldGet (_, i) -> List.item i tinst | TOp.Tuple tupInfo -> mkAnyTupledTy g tupInfo tinst | TOp.AnonRecd anonInfo -> mkAnyAnonRecdTy g anonInfo tinst | (TOp.For _ | TOp.While _) -> g.unit_ty | TOp.Array -> (match tinst with [ty] -> mkArrayType g ty | _ -> failwith "bad TOp.Array node") | (TOp.TryCatch _ | TOp.TryFinally _) -> (match tinst with [ty] -> ty | _ -> failwith "bad TOp_try node") - | TOp.ValFieldGetAddr(fref, readonly) -> mkByrefTyWithFlag g readonly (actualTyOfRecdFieldRef fref tinst) - | TOp.ValFieldGet(fref) -> actualTyOfRecdFieldRef fref tinst + | TOp.ValFieldGetAddr (fref, readonly) -> mkByrefTyWithFlag g readonly (actualTyOfRecdFieldRef fref tinst) + | TOp.ValFieldGet fref -> actualTyOfRecdFieldRef fref tinst | (TOp.ValFieldSet _ | TOp.UnionCaseFieldSet _ | TOp.ExnFieldSet _ | TOp.LValueOp ((LSet | LByrefSet), _)) ->g.unit_ty | TOp.UnionCaseTagGet _ -> g.int_ty - | TOp.UnionCaseFieldGetAddr(cref, j, readonly) -> mkByrefTyWithFlag g readonly (actualTyOfRecdField (mkTyconRefInst cref.TyconRef tinst) (cref.FieldByIndex j)) - | TOp.UnionCaseFieldGet(cref, j) -> actualTyOfRecdField (mkTyconRefInst cref.TyconRef tinst) (cref.FieldByIndex j) - | TOp.ExnFieldGet(ecref, j) -> recdFieldTyOfExnDefRefByIdx ecref j + | TOp.UnionCaseFieldGetAddr (cref, j, readonly) -> mkByrefTyWithFlag g readonly (actualTyOfRecdField (mkTyconRefInst cref.TyconRef tinst) (cref.FieldByIndex j)) + | TOp.UnionCaseFieldGet (cref, j) -> actualTyOfRecdField (mkTyconRefInst cref.TyconRef tinst) (cref.FieldByIndex j) + | TOp.ExnFieldGet (ecref, j) -> recdFieldTyOfExnDefRefByIdx ecref j | TOp.LValueOp (LByrefGet, v) -> destByrefTy g v.Type | TOp.LValueOp (LAddrOf readonly, v) -> mkByrefTyWithFlag g readonly v.Type | TOp.RefAddrGet readonly -> (match tinst with [ty] -> mkByrefTyWithFlag g readonly ty | _ -> failwith "bad TOp.RefAddrGet node") - | TOp.TraitCall (TTrait(_, _, _, _, ty, _)) -> GetFSharpViewOfReturnType g ty + | TOp.TraitCall traitInfo -> GetFSharpViewOfReturnType g traitInfo.ReturnType | TOp.Reraise -> (match tinst with [rtn_ty] -> rtn_ty | _ -> failwith "bad TOp.Reraise node") | TOp.Goto _ | TOp.Label _ | TOp.Return -> //assert false @@ -5638,7 +5755,7 @@ let rec tyOfExpr g e = //--------------------------------------------------------------------------- let primMkApp (f, fty) tyargs argsl m = - Expr.App(f, fty, tyargs, argsl, m) + Expr.App (f, fty, tyargs, argsl, m) // Check for the funky where a generic type instantiation at function type causes a generic function // to appear to accept more arguments than it really does, e.g. "id id 1", where the first "id" is @@ -5655,7 +5772,7 @@ let isExpansiveUnderInstantiation g fty0 tyargs pargs argsl = | _ :: t -> not (isFunTy g fty) || loop (rangeOfFunTy g fty) t loop fty1 argsl) -let rec mkExprApplAux g f fty argsl m = +let rec mkExprAppAux g f fty argsl m = match argsl with | [] -> f | _ -> @@ -5663,11 +5780,11 @@ let rec mkExprApplAux g f fty argsl m = // // Combine the term application with a term application, but only when f' is an under-applied value of known arity match f with - | Expr.App(f', fty', tyargs, pargs, m2) + | Expr.App (f', fty', tyargs, pargs, m2) when (isNil pargs || (match stripExpr f' with - | Expr.Val(v, _, _) -> + | Expr.Val (v, _, _) -> match v.ValReprInfo with | Some info -> info.NumCurriedArgs > pargs.Length | None -> false @@ -5690,7 +5807,7 @@ let rec mkAppsAux g f fty tyargsl argsl m = let arfty = applyForallTy g fty tyargs mkAppsAux g (primMkApp (f, fty) tyargs [] m) arfty rest argsl m | [] -> - mkExprApplAux g f fty argsl m + mkExprAppAux g f fty argsl m let mkApps g ((f, fty), tyargsl, argl, m) = mkAppsAux g f fty tyargsl argl m @@ -5705,7 +5822,7 @@ let rec accTargetsOfDecisionTree tree acc = | TDSwitch (_, cases, dflt, _) -> List.foldBack (fun (c: DecisionTreeCase) -> accTargetsOfDecisionTree c.CaseTree) cases (Option.foldBack accTargetsOfDecisionTree dflt acc) - | TDSuccess (_, i) -> i:: acc + | TDSuccess (_, i) -> i :: acc | TDBind (_, rest) -> accTargetsOfDecisionTree rest acc let rec mapTargetsOfDecisionTree f tree = @@ -5772,7 +5889,7 @@ let foldLinearBindingTargetsOfMatch tree (targets: _[]) = | TDSuccess (es, i) -> branchesToTargets.[i] <- (List.rev accBinds, es) :: branchesToTargets.[i] | TDBind (bind, rest) -> - accumulateTipsOfDecisionTree (bind:: accBinds) rest + accumulateTipsOfDecisionTree (bind :: accBinds) rest // Compute the targets that can only be reached one way accumulateTipsOfDecisionTree [] tree @@ -5848,34 +5965,56 @@ let mkAndSimplifyMatch spBind exprm matchm ty tree targets = //------------------------------------------------------------------------- type Mutates = AddressOfOp | DefinitelyMutates | PossiblyMutates | NeverMutates -exception DefensiveCopyWarning of string * range +exception DefensiveCopyWarning of string * range let isRecdOrStructTyconRefAssumedImmutable (g: TcGlobals) (tcref: TyconRef) = tcref.CanDeref && not (isRecdOrUnionOrStructTyconRefDefinitelyMutable tcref) || - tyconRefEq g tcref g.decimal_tcr || + tyconRefEq g tcref g.decimal_tcr || tyconRefEq g tcref g.date_tcr -let isRecdOrStructTyconRefReadOnly (g: TcGlobals) m (tcref: TyconRef) = +let isTyconRefReadOnly g m (tcref: TyconRef) = tcref.CanDeref && - match tcref.TryIsReadOnly with - | Some res -> res - | None -> - let isImmutable = isRecdOrStructTyconRefAssumedImmutable g tcref - let hasAttrib = TyconRefHasAttribute g m g.attrib_IsReadOnlyAttribute tcref - let res = isImmutable || hasAttrib - tcref.SetIsReadOnly res + if + match tcref.TryIsReadOnly with + | ValueSome res -> res + | _ -> + let res = TyconRefHasAttribute g m g.attrib_IsReadOnlyAttribute tcref + tcref.SetIsReadOnly res + res + then true + else tcref.IsEnumTycon + +let isTyconRefAssumedReadOnly g (tcref: TyconRef) = + tcref.CanDeref && + match tcref.TryIsAssumedReadOnly with + | ValueSome res -> res + | _ -> + let res = isRecdOrStructTyconRefAssumedImmutable g tcref + tcref.SetIsAssumedReadOnly res res -let isRecdOrStructTyReadOnly (g: TcGlobals) m ty = - match tryDestAppTy g ty with +let isRecdOrStructTyconRefReadOnlyAux g m isInref (tcref: TyconRef) = + if isInref && tcref.IsILStructOrEnumTycon then + isTyconRefReadOnly g m tcref + else + isTyconRefReadOnly g m tcref || isTyconRefAssumedReadOnly g tcref + +let isRecdOrStructTyconRefReadOnly g m tcref = + isRecdOrStructTyconRefReadOnlyAux g m false tcref + +let isRecdOrStructTyReadOnlyAux (g: TcGlobals) m isInref ty = + match tryTcrefOfAppTy g ty with | ValueNone -> false - | ValueSome tcref -> isRecdOrStructTyconRefReadOnly g m tcref + | ValueSome tcref -> isRecdOrStructTyconRefReadOnlyAux g m isInref tcref -let CanTakeAddressOf g m ty mut = +let isRecdOrStructTyReadOnly g m ty = + isRecdOrStructTyReadOnlyAux g m false ty + +let CanTakeAddressOf g m isInref ty mut = match mut with | NeverMutates -> true - | PossiblyMutates -> isRecdOrStructTyReadOnly g m ty + | PossiblyMutates -> isRecdOrStructTyReadOnlyAux g m isInref ty | DefinitelyMutates -> false | AddressOfOp -> true // you can take the address but you might get a (readonly) inref as a result @@ -5903,7 +6042,7 @@ let CanTakeAddressOfImmutableVal (g: TcGlobals) m (vref: ValRef) mut = // || valRefInThisAssembly g.compilingFslib vref // This is because we don't actually guarantee to generate static backing fields for all values like these, e.g. simple constants "let x = 1". // We always generate a static property but there is no field to take an address of - CanTakeAddressOf g m vref.Type mut + CanTakeAddressOf g m false vref.Type mut let MustTakeAddressOfVal (g: TcGlobals) (vref: ValRef) = vref.IsMutable && @@ -5915,7 +6054,7 @@ let MustTakeAddressOfByrefGet (g: TcGlobals) (vref: ValRef) = let CanTakeAddressOfByrefGet (g: TcGlobals) (vref: ValRef) mut = isInByrefTy g vref.Type && - CanTakeAddressOf g vref.Range (destByrefTy g vref.Type) mut + CanTakeAddressOf g vref.Range true (destByrefTy g vref.Type) mut let MustTakeAddressOfRecdField (rfref: RecdField) = // Static mutable fields must be private, hence we don't have to take their address @@ -5928,20 +6067,34 @@ let CanTakeAddressOfRecdFieldRef (g: TcGlobals) m (rfref: RecdFieldRef) tinst mu // We only do this if the field is defined in this assembly because we can't take addresses across assemblies for immutable fields entityRefInThisAssembly g.compilingFslib rfref.TyconRef && not rfref.RecdField.IsMutable && - CanTakeAddressOf g m (actualTyOfRecdFieldRef rfref tinst) mut + CanTakeAddressOf g m false (actualTyOfRecdFieldRef rfref tinst) mut let CanTakeAddressOfUnionFieldRef (g: TcGlobals) m (uref: UnionCaseRef) cidx tinst mut = // We only do this if the field is defined in this assembly because we can't take addresses across assemblies for immutable fields entityRefInThisAssembly g.compilingFslib uref.TyconRef && let rfref = uref.FieldByIndex cidx not rfref.IsMutable && - CanTakeAddressOf g m (actualTyOfUnionFieldRef uref cidx tinst) mut + CanTakeAddressOf g m false (actualTyOfUnionFieldRef uref cidx tinst) mut + +let mkDerefAddrExpr mAddrGet expr mExpr exprTy = + let v, _ = mkCompGenLocal mAddrGet "byrefReturn" exprTy + mkCompGenLet mExpr v expr (mkAddrGet mAddrGet (mkLocalValRef v)) /// Make the address-of expression and return a wrapper that adds any allocated locals at an appropriate scope. /// Also return a flag that indicates if the resulting pointer is a not a pointer where writing is allowed and will /// have intended effect (i.e. is a readonly pointer and/or a defensive copy). let rec mkExprAddrOfExprAux g mustTakeAddress useReadonlyForGenericArrayAddress mut expr addrExprVal m = if mustTakeAddress then + let isNativePtr = + match addrExprVal with + | Some vf -> valRefEq g vf g.addrof2_vref + | _ -> false + + // If we are taking the native address using "&&" to get a nativeptr, disallow if it's readonly. + let checkTakeNativeAddress readonly = + if isNativePtr && readonly then + error(Error(FSComp.SR.tastValueMustBeMutable(), m)) + match expr with // LVALUE of "*x" where "x" is byref is just the byref itself | Expr.Op (TOp.LValueOp (LByrefGet, vref), _, [], m) when MustTakeAddressOfByrefGet g vref || CanTakeAddressOfByrefGet g vref mut -> @@ -5951,9 +6104,10 @@ let rec mkExprAddrOfExprAux g mustTakeAddress useReadonlyForGenericArrayAddress // LVALUE of "x" where "x" is mutable local, mutable intra-assembly module/static binding, or operation doesn't mutate. // Note: we can always take the address of mutable intra-assembly values - | Expr.Val(vref, _, m) when MustTakeAddressOfVal g vref || CanTakeAddressOfImmutableVal g m vref mut -> + | Expr.Val (vref, _, m) when MustTakeAddressOfVal g vref || CanTakeAddressOfImmutableVal g m vref mut -> let readonly = not (MustTakeAddressOfVal g vref) let writeonly = false + checkTakeNativeAddress readonly None, mkValAddr m readonly vref, readonly, writeonly // LVALUE of "e.f" where "f" is an instance F# field or record field. @@ -5972,11 +6126,11 @@ let rec mkExprAddrOfExprAux g mustTakeAddress useReadonlyForGenericArrayAddress None, mkStaticRecdFieldGetAddr(readonly, rfref, tinst, m), readonly, writeonly // LVALUE of "e.f" where "f" is an F# union field. - | Expr.Op (TOp.UnionCaseFieldGet (uref, cidx), tinst, [objExpr], m) when MustTakeAddressOfRecdField (uref.FieldByIndex(cidx)) || CanTakeAddressOfUnionFieldRef g m uref cidx tinst mut -> + | Expr.Op (TOp.UnionCaseFieldGet (uref, cidx), tinst, [objExpr], m) when MustTakeAddressOfRecdField (uref.FieldByIndex cidx) || CanTakeAddressOfUnionFieldRef g m uref cidx tinst mut -> let objTy = tyOfExpr g objExpr let takeAddrOfObjExpr = isStructTy g objTy // It seems this will always be false - the address will already have been taken let wrap, expra, readonly, writeonly = mkExprAddrOfExprAux g takeAddrOfObjExpr false mut objExpr None m - let readonly = readonly || isInByrefTy g objTy || not (MustTakeAddressOfRecdField (uref.FieldByIndex(cidx))) + let readonly = readonly || isInByrefTy g objTy || not (MustTakeAddressOfRecdField (uref.FieldByIndex cidx)) let writeonly = writeonly || isOutByrefTy g objTy wrap, mkUnionCaseFieldGetAddrProvenViaExprAddr(readonly, expra, uref, tinst, cidx, m), readonly, writeonly @@ -5984,48 +6138,39 @@ let rec mkExprAddrOfExprAux g mustTakeAddress useReadonlyForGenericArrayAddress | Expr.Op (TOp.ILAsm ([IL.I_ldsfld(_vol, fspec)], [ty2]), tinst, [], m) -> let readonly = false // we never consider taking the address of a .NET static field to give an inref pointer let writeonly = false - None, Expr.Op (TOp.ILAsm ([IL.I_ldsflda(fspec)], [mkByrefTy g ty2]), tinst, [], m), readonly, writeonly + None, Expr.Op (TOp.ILAsm ([IL.I_ldsflda fspec], [mkByrefTy g ty2]), tinst, [], m), readonly, writeonly // LVALUE of "e.f" where "f" is a .NET instance field. - | Expr.Op (TOp.ILAsm ([IL.I_ldfld(_align, _vol, fspec)], [ty2]), tinst, [objExpr], m) -> + | Expr.Op (TOp.ILAsm ([IL.I_ldfld (_align, _vol, fspec)], [ty2]), tinst, [objExpr], m) -> let objTy = tyOfExpr g objExpr let takeAddrOfObjExpr = isStructTy g objTy // It seems this will always be false - the address will already have been taken // we never consider taking the address of an .NET instance field to give an inref pointer, unless the object pointer is an inref pointer let wrap, expra, readonly, writeonly = mkExprAddrOfExprAux g takeAddrOfObjExpr false mut objExpr None m let readonly = readonly || isInByrefTy g objTy let writeonly = writeonly || isOutByrefTy g objTy - wrap, Expr.Op (TOp.ILAsm ([IL.I_ldflda(fspec)], [mkByrefTyWithFlag g readonly ty2]), tinst, [expra], m), readonly, writeonly + wrap, Expr.Op (TOp.ILAsm ([IL.I_ldflda fspec], [mkByrefTyWithFlag g readonly ty2]), tinst, [expra], m), readonly, writeonly // LVALUE of "e.[n]" where e is an array of structs - | Expr.App(Expr.Val(vf, _, _), _, [elemTy], [aexpr;nexpr], _) when (valRefEq g vf g.array_get_vref) -> - + | Expr.App (Expr.Val (vf, _, _), _, [elemTy], [aexpr;nexpr], _) when (valRefEq g vf g.array_get_vref) -> + let readonly = false // array address is never forced to be readonly let writeonly = false let shape = ILArrayShape.SingleDimensional let ilInstrReadOnlyAnnotation = if isTyparTy g elemTy && useReadonlyForGenericArrayAddress then ReadonlyAddress else NormalAddress - let isNativePtr = - match addrExprVal with - | Some(vf) -> valRefEq g vf g.addrof2_vref - | _ -> false None, mkArrayElemAddress g (readonly, ilInstrReadOnlyAnnotation, isNativePtr, shape, elemTy, [aexpr; nexpr], m), readonly, writeonly // LVALUE of "e.[n1, n2]", "e.[n1, n2, n3]", "e.[n1, n2, n3, n4]" where e is an array of structs - | Expr.App(Expr.Val(vref, _, _), _, [elemTy], (aexpr:: args), _) + | Expr.App (Expr.Val (vref, _, _), _, [elemTy], (aexpr :: args), _) when (valRefEq g vref g.array2D_get_vref || valRefEq g vref g.array3D_get_vref || valRefEq g vref g.array4D_get_vref) -> let readonly = false // array address is never forced to be readonly let writeonly = false let shape = ILArrayShape.FromRank args.Length let ilInstrReadOnlyAnnotation = if isTyparTy g elemTy && useReadonlyForGenericArrayAddress then ReadonlyAddress else NormalAddress - let isNativePtr = - match addrExprVal with - | Some(vf) -> valRefEq g vf g.addrof2_vref - | _ -> false - - None, mkArrayElemAddress g (readonly, ilInstrReadOnlyAnnotation, isNativePtr, shape, elemTy, (aexpr:: args), m), readonly, writeonly + None, mkArrayElemAddress g (readonly, ilInstrReadOnlyAnnotation, isNativePtr, shape, elemTy, (aexpr :: args), m), readonly, writeonly // LVALUE: "&meth(args)" where meth has a byref or inref return. Includes "&span.[idx]". - | Expr.Let(TBind(vref, e, _), Expr.Op(TOp.LValueOp (LByrefGet, vref2), _, _, _), _, _) + | Expr.Let (TBind(vref, e, _), Expr.Op (TOp.LValueOp (LByrefGet, vref2), _, _, _), _, _) when (valRefEq g (mkLocalValRef vref) vref2) && (MustTakeAddressOfByrefGet g vref2 || CanTakeAddressOfByrefGet g vref2 mut) -> let ty = tyOfExpr g e @@ -6034,11 +6179,11 @@ let rec mkExprAddrOfExprAux g mustTakeAddress useReadonlyForGenericArrayAddress None, e, readonly, writeonly // Give a nice error message for address-of-byref - | Expr.Val(vref, _, m) when isByrefTy g vref.Type -> + | Expr.Val (vref, _, m) when isByrefTy g vref.Type -> error(Error(FSComp.SR.tastUnexpectedByRef(), m)) // Give a nice error message for DefinitelyMutates of address-of on mutable values in other assemblies - | Expr.Val(vref, _, m) when (mut = DefinitelyMutates || mut = AddressOfOp) && vref.IsMutable -> + | Expr.Val (vref, _, m) when (mut = DefinitelyMutates || mut = AddressOfOp) && vref.IsMutable -> error(Error(FSComp.SR.tastInvalidAddressOfMutableAcrossAssemblyBoundary(), m)) // Give a nice error message for AddressOfOp on immutable values @@ -6073,8 +6218,12 @@ let rec mkExprAddrOfExprAux g mustTakeAddress useReadonlyForGenericArrayAddress // Take a defensive copy let tmp, _ = match mut with - | NeverMutates -> mkCompGenLocal m "copyOfStruct" ty + | NeverMutates -> mkCompGenLocal m "copyOfStruct" ty | _ -> mkMutableCompGenLocal m "copyOfStruct" ty + + // This local is special in that it ignore byref scoping rules. + tmp.SetIgnoresByrefScope() + let readonly = true let writeonly = false Some (tmp, expr), (mkValAddr m readonly (mkLocalValRef tmp)), readonly, writeonly @@ -6098,14 +6247,14 @@ let mkAnonRecdFieldGet g (anonInfo: AnonRecdTypeInfo, e, tinst, i, m) = let mkRecdFieldGet g (e, fref: RecdFieldRef, tinst, m) = assert (not (isByrefTy g (tyOfExpr g e))) let wrap, e', _readonly, _writeonly = mkExprAddrOfExpr g fref.Tycon.IsStructOrEnumTycon false NeverMutates e None m - wrap (mkRecdFieldGetViaExprAddr(e', fref, tinst, m)) + wrap (mkRecdFieldGetViaExprAddr (e', fref, tinst, m)) let mkUnionCaseFieldGetUnproven g (e, cref: UnionCaseRef, tinst, j, m) = assert (not (isByrefTy g (tyOfExpr g e))) let wrap, e', _readonly, _writeonly = mkExprAddrOfExpr g cref.Tycon.IsStructOrEnumTycon false NeverMutates e None m wrap (mkUnionCaseFieldGetUnprovenViaExprAddr (e', cref, tinst, j, m)) -let mkArray (argty, args, m) = Expr.Op(TOp.Array, [argty], args, m) +let mkArray (argty, args, m) = Expr.Op (TOp.Array, [argty], args, m) //--------------------------------------------------------------------------- // Compute fixups for letrec's. @@ -6140,14 +6289,14 @@ let rec IterateRecursiveFixups g (selfv: Val option) rvs ((access: Expr), set) e errorR(Error(FSComp.SR.tastRecursiveValuesMayNotBeInConstructionOfTuple(), m)) e))) - | Expr.Op (TOp.UnionCase (c), tinst, args, m) -> + | Expr.Op (TOp.UnionCase c, tinst, args, m) -> args |> List.iteri (fun n -> IterateRecursiveFixups g None rvs (mkUnionCaseFieldGetUnprovenViaExprAddr (access, c, tinst, n, m), (fun e -> // NICE: it would be better to do this check in the type checker let tcref = c.TyconRef - if not (c.FieldByIndex(n)).IsMutable && not (entityRefInThisAssembly g.compilingFslib tcref) then + if not (c.FieldByIndex n).IsMutable && not (entityRefInThisAssembly g.compilingFslib tcref) then errorR(Error(FSComp.SR.tastRecursiveValuesMayNotAppearInConstructionOfType(tcref.LogicalName), m)) mkUnionCaseFieldSet (access, c, tinst, n, e, m)))) @@ -6155,7 +6304,7 @@ let rec IterateRecursiveFixups g (selfv: Val option) rvs ((access: Expr), set) e (tcref.TrueInstanceFieldsAsRefList, args) ||> List.iter2 (fun fref arg -> let fspec = fref.RecdField IterateRecursiveFixups g None rvs - (mkRecdFieldGetViaExprAddr(access, fref, tinst, m), + (mkRecdFieldGetViaExprAddr (access, fref, tinst, m), (fun e -> // NICE: it would be better to do this check in the type checker if not fspec.IsMutable && not (entityRefInThisAssembly g.compilingFslib tcref) then @@ -6239,13 +6388,13 @@ type ExprFolders<'State> (folders: ExprFolder<'State>) = let z = exprF z x0 exprF z x1 - | Expr.Lambda(_lambdaId, _ctorThisValOpt, _baseValOpt, _argvs, body, _m, _rty) -> + | Expr.Lambda (_lambdaId, _ctorThisValOpt, _baseValOpt, _argvs, body, _m, _rty) -> exprF z body - | Expr.TyLambda(_lambdaId, _argtyvs, body, _m, _rty) -> + | Expr.TyLambda (_lambdaId, _argtyvs, body, _m, _rty) -> exprF z body - | Expr.TyChoose(_, body, _) -> + | Expr.TyChoose (_, body, _) -> exprF z body | Expr.App (f, _fty, _tys, argtys, _) -> @@ -6268,11 +6417,11 @@ type ExprFolders<'State> (folders: ExprFolder<'State>) = // tailcall targetF z targets.[targets.Length - 1] - | Expr.Quote(e, {contents=Some(_typeDefs, _argTypes, argExprs, _)}, _, _, _) -> + | Expr.Quote (e, {contents=Some(_typeDefs, _argTypes, argExprs, _)}, _, _, _) -> let z = exprF z e exprsF z argExprs - | Expr.Quote(e, {contents=None}, _, _m, _) -> + | Expr.Quote (e, {contents=None}, _, _m, _) -> exprF z e | Expr.Obj (_n, _typ, _basev, basecall, overrides, iimpls, _m) -> @@ -6364,33 +6513,33 @@ let FoldImplFile folders state implFile = ExprFolders(folders).FoldImplFile stat //------------------------------------------------------------------------- let ExprStats x = - let count = ref 0 - let folders = {ExprFolder0 with exprIntercept = (fun _ noInterceptF z x -> (count := !count + 1; noInterceptF z x))} + let mutable count = 0 + let folders = {ExprFolder0 with exprIntercept = (fun _ noInterceptF z x -> (count <- count + 1; noInterceptF z x))} let () = FoldExpr folders () x - string !count + " TExpr nodes" + string count + " TExpr nodes" #endif //------------------------------------------------------------------------- // Make expressions //------------------------------------------------------------------------- -let mkString (g: TcGlobals) m n = Expr.Const(Const.String n, m, g.string_ty) +let mkString (g: TcGlobals) m n = Expr.Const (Const.String n, m, g.string_ty) -let mkBool (g: TcGlobals) m b = Expr.Const(Const.Bool b, m, g.bool_ty) +let mkBool (g: TcGlobals) m b = Expr.Const (Const.Bool b, m, g.bool_ty) -let mkByte (g: TcGlobals) m b = Expr.Const(Const.Byte b, m, g.byte_ty) +let mkByte (g: TcGlobals) m b = Expr.Const (Const.Byte b, m, g.byte_ty) -let mkUInt16 (g: TcGlobals) m b = Expr.Const(Const.UInt16 b, m, g.uint16_ty) +let mkUInt16 (g: TcGlobals) m b = Expr.Const (Const.UInt16 b, m, g.uint16_ty) let mkTrue g m = mkBool g m true let mkFalse g m = mkBool g m false -let mkUnit (g: TcGlobals) m = Expr.Const(Const.Unit, m, g.unit_ty) +let mkUnit (g: TcGlobals) m = Expr.Const (Const.Unit, m, g.unit_ty) -let mkInt32 (g: TcGlobals) m n = Expr.Const(Const.Int32 n, m, g.int32_ty) +let mkInt32 (g: TcGlobals) m n = Expr.Const (Const.Int32 n, m, g.int32_ty) -let mkInt g m n = mkInt32 g m (n) +let mkInt g m n = mkInt32 g m n let mkZero g m = mkInt g m 0 @@ -6400,10 +6549,10 @@ let mkTwo g m = mkInt g m 2 let mkMinusOne g m = mkInt g m (-1) -let destInt32 = function Expr.Const(Const.Int32 n, _, _) -> Some n | _ -> None +let destInt32 = function Expr.Const (Const.Int32 n, _, _) -> Some n | _ -> None let isIDelegateEventType g ty = - match tryDestAppTy g ty with + match tryTcrefOfAppTy g ty with | ValueSome tcref -> tyconRefEq g g.fslib_IDelegateEvent_tcr tcref | _ -> false @@ -6422,17 +6571,17 @@ let mkIObserverType (g: TcGlobals) ty1 = TType_app (g.tcref_IObserver, [ty1]) let mkRefCellContentsRef (g: TcGlobals) = mkRecdFieldRef g.refcell_tcr_canon "contents" -let mkSequential spSeq m e1 e2 = Expr.Sequential(e1, e2, NormalSeq, spSeq, m) +let mkSequential spSeq m e1 e2 = Expr.Sequential (e1, e2, NormalSeq, spSeq, m) -let mkCompGenSequential m e1 e2 = mkSequential SuppressSequencePointOnExprOfSequential m e1 e2 +let mkCompGenSequential m e1 e2 = mkSequential DebugPointAtSequential.StmtOnly m e1 e2 let rec mkSequentials spSeq g m es = match es with | [e] -> e - | e:: es -> mkSequential spSeq m e (mkSequentials spSeq g m es) + | e :: es -> mkSequential spSeq m e (mkSequentials spSeq g m es) | [] -> mkUnit g m -let mkGetArg0 m ty = mkAsmExpr( [ mkLdarg0 ], [], [], [ty], m) +let mkGetArg0 m ty = mkAsmExpr ( [ mkLdarg0 ], [], [], [ty], m) //------------------------------------------------------------------------- // Tuples... @@ -6450,8 +6599,6 @@ let mkRefTupledNoTypes g m args = mkRefTupled g m args (List.map (tyOfExpr g) ar let mkRefTupledVars g m vs = mkRefTupled g m (List.map (exprForVal m) vs) (typesOfVals vs) -let mkAnonRecd (_g: TcGlobals) m anonInfo es tys = Expr.Op (TOp.AnonRecd (anonInfo),tys,es,m) - //-------------------------------------------------------------------------- // Permute expressions //-------------------------------------------------------------------------- @@ -6512,21 +6659,35 @@ let permuteExprList (sigma: int[]) (exprs: Expr list) (ty: TType list) (names: s /// let sigma = Array.map #Index () /// However the presence of static fields means .Index may index into a non-compact set of instance field indexes. /// We still need to sort by index. -let mkRecordExpr g (lnk, tcref, tinst, rfrefs: RecdFieldRef list, args, m) = +let mkRecordExpr g (lnk, tcref, tinst, unsortedRecdFields: RecdFieldRef list, unsortedFieldExprs, m) = // Remove any abbreviations let tcref, tinst = destAppTy g (mkAppTy tcref tinst) - let rfrefsArray = rfrefs |> List.indexed |> Array.ofList - rfrefsArray |> Array.sortInPlaceBy (fun (_, r) -> r.Index) - let sigma = Array.create rfrefsArray.Length -1 - Array.iteri (fun j (i, _) -> - if sigma.[i] <> -1 then error(InternalError("bad permutation", m)) - sigma.[i] <- j) rfrefsArray + let sortedRecdFields = unsortedRecdFields |> List.indexed |> Array.ofList |> Array.sortBy (fun (_, r) -> r.Index) + let sigma = Array.create sortedRecdFields.Length -1 + sortedRecdFields |> Array.iteri (fun sortedIdx (unsortedIdx, _) -> + if sigma.[unsortedIdx] <> -1 then error(InternalError("bad permutation", m)) + sigma.[unsortedIdx] <- sortedIdx) + + let unsortedArgTys = unsortedRecdFields |> List.map (fun rfref -> actualTyOfRecdFieldRef rfref tinst) + let unsortedArgNames = unsortedRecdFields |> List.map (fun rfref -> rfref.FieldName) + let unsortedArgBinds, sortedArgExprs = permuteExprList sigma unsortedFieldExprs unsortedArgTys unsortedArgNames + let core = Expr.Op (TOp.Recd (lnk, tcref), tinst, sortedArgExprs, m) + mkLetsBind m unsortedArgBinds core + +let mkAnonRecd (_g: TcGlobals) m (anonInfo: AnonRecdTypeInfo) (unsortedIds: Ident[]) (unsortedFieldExprs: Expr list) unsortedArgTys = + let sortedRecdFields = unsortedFieldExprs |> List.indexed |> Array.ofList |> Array.sortBy (fun (i,_) -> unsortedIds.[i].idText) + let sortedArgTys = unsortedArgTys |> List.indexed |> List.sortBy (fun (i,_) -> unsortedIds.[i].idText) |> List.map snd + + let sigma = Array.create sortedRecdFields.Length -1 + sortedRecdFields |> Array.iteri (fun sortedIdx (unsortedIdx, _) -> + if sigma.[unsortedIdx] <> -1 then error(InternalError("bad permutation", m)) + sigma.[unsortedIdx] <- sortedIdx) - let argTys = List.map (fun rfref -> actualTyOfRecdFieldRef rfref tinst) rfrefs - let names = rfrefs |> List.map (fun rfref -> rfref.FieldName) - let binds, args = permuteExprList sigma args argTys names - mkLetsBind m binds (Expr.Op (TOp.Recd(lnk, tcref), tinst, args, m)) + let unsortedArgNames = unsortedIds |> Array.toList |> List.map (fun id -> id.idText) + let unsortedArgBinds, sortedArgExprs = permuteExprList sigma unsortedFieldExprs unsortedArgTys unsortedArgNames + let core = Expr.Op (TOp.AnonRecd anonInfo, sortedArgTys, sortedArgExprs, m) + mkLetsBind m unsortedArgBinds core //------------------------------------------------------------------------- // List builders @@ -6542,7 +6703,7 @@ let mkNil (g: TcGlobals) m ty = mkUnionCaseExpr (g.nil_ucref, [ty], [], m) let mkCons (g: TcGlobals) ty h t = mkUnionCaseExpr (g.cons_ucref, [ty], [h;t], unionRanges h.Range t.Range) -let mkCompGenLocalAndInvisbleBind g nm m e = +let mkCompGenLocalAndInvisibleBind g nm m e = let locv, loce = mkCompGenLocal m nm (tyOfExpr g e) locv, loce, mkInvisibleBind locv e @@ -6587,7 +6748,6 @@ let mkInitializeArrayMethSpec (g: TcGlobals) = let mkInvalidCastExnNewobj (g: TcGlobals) = mkNormalNewobj (mkILCtorMethSpecForTy (mkILNonGenericBoxedTy (g.FindSysILTypeRef "System.InvalidCastException"), [])) - let typedExprForIntrinsic _g m (IntrinsicValRef(_, _, _, ty, _) as i) = let vref = ValRefForIntrinsic i exprForValRef m vref, ty @@ -6759,7 +6919,7 @@ let mkCallNewFormat (g: TcGlobals) m aty bty cty dty ety e1 = mkApps g (typedExp let TryEliminateDesugaredConstants g m c = match c with | Const.Decimal d -> - match System.Decimal.GetBits(d) with + match System.Decimal.GetBits d with | [| lo;med;hi; signExp |] -> let scale = (min (((signExp &&& 0xFF0000) >>> 16) &&& 0xFF) 28) |> byte let isNegative = (signExp &&& 0x80000000) <> 0 @@ -6840,10 +7000,10 @@ let mkCallLiftValueWithDefn g m qty e1 = match vref.TryDeref with | ValueSome _ -> let copyOfExpr = copyExpr g ValCopyFlag.CloneAll e1 - let quoteOfCopyOfExpr = Expr.Quote(copyOfExpr, ref None, false, m, qty) + let quoteOfCopyOfExpr = Expr.Quote (copyOfExpr, ref None, false, m, qty) mkApps g (typedExprForIntrinsic g m g.lift_value_with_defn_info, [[ty]], [mkRefTupledNoTypes g m [e1; quoteOfCopyOfExpr]], m) | ValueNone -> - Expr.Quote(e1, ref None, false, m, qty) + Expr.Quote (e1, ref None, false, m, qty) let mkCallCheckThis g m ty e1 = mkApps g (typedExprForIntrinsic g m g.check_this_info, [[ty]], [e1], m) @@ -6857,6 +7017,12 @@ let mkCallFailStaticInit g m = let mkCallQuoteToLinqLambdaExpression g m ty e1 = mkApps g (typedExprForIntrinsic g m g.quote_to_linq_lambda_info, [[ty]], [e1], m) +let mkOptionToNullable g m ty e1 = + mkApps g (typedExprForIntrinsic g m g.option_toNullable_info, [[ty]], [e1], m) + +let mkOptionDefaultValue g m ty e1 e2 = + mkApps g (typedExprForIntrinsic g m g.option_defaultValue_info, [[ty]], [e1; e2], m) + let mkLazyDelayed g m ty f = mkApps g (typedExprForIntrinsic g m g.lazy_create_info, [[ty]], [ f ], m) let mkLazyForce g m ty e = mkApps g (typedExprForIntrinsic g m g.lazy_force_info, [[ty]], [ e; mkUnit g m ], m) @@ -6867,24 +7033,23 @@ let mkGetStringChar = mkGetString let mkGetStringLength g m e = let mspec = mspec_String_Length g - /// ILCall(useCallvirt, isProtected, valu, newobj, valUseFlags, isProp, noTailCall, mref, actualTypeInst, actualMethInst, retTy) - Expr.Op(TOp.ILCall(false, false, false, false, ValUseFlag.NormalValUse, true, false, mspec.MethodRef, [], [], [g.int32_ty]), [], [e], m) + Expr.Op (TOp.ILCall (false, false, false, false, ValUseFlag.NormalValUse, true, false, mspec.MethodRef, [], [], [g.int32_ty]), [], [e], m) let mkStaticCall_String_Concat2 g m arg1 arg2 = let mspec = mspec_String_Concat2 g - Expr.Op(TOp.ILCall(false, false, false, false, ValUseFlag.NormalValUse, false, false, mspec.MethodRef, [], [], [g.string_ty]), [], [arg1; arg2], m) + Expr.Op (TOp.ILCall (false, false, false, false, ValUseFlag.NormalValUse, false, false, mspec.MethodRef, [], [], [g.string_ty]), [], [arg1; arg2], m) let mkStaticCall_String_Concat3 g m arg1 arg2 arg3 = let mspec = mspec_String_Concat3 g - Expr.Op(TOp.ILCall(false, false, false, false, ValUseFlag.NormalValUse, false, false, mspec.MethodRef, [], [], [g.string_ty]), [], [arg1; arg2; arg3], m) + Expr.Op (TOp.ILCall (false, false, false, false, ValUseFlag.NormalValUse, false, false, mspec.MethodRef, [], [], [g.string_ty]), [], [arg1; arg2; arg3], m) let mkStaticCall_String_Concat4 g m arg1 arg2 arg3 arg4 = let mspec = mspec_String_Concat4 g - Expr.Op(TOp.ILCall(false, false, false, false, ValUseFlag.NormalValUse, false, false, mspec.MethodRef, [], [], [g.string_ty]), [], [arg1; arg2; arg3; arg4], m) + Expr.Op (TOp.ILCall (false, false, false, false, ValUseFlag.NormalValUse, false, false, mspec.MethodRef, [], [], [g.string_ty]), [], [arg1; arg2; arg3; arg4], m) let mkStaticCall_String_Concat_Array g m arg = let mspec = mspec_String_Concat_Array g - Expr.Op(TOp.ILCall(false, false, false, false, ValUseFlag.NormalValUse, false, false, mspec.MethodRef, [], [], [g.string_ty]), [], [arg], m) + Expr.Op (TOp.ILCall (false, false, false, false, ValUseFlag.NormalValUse, false, false, mspec.MethodRef, [], [], [g.string_ty]), [], [arg], m) // Quotations can't contain any IL. // As a result, we aim to get rid of all IL generation in the typechecker and pattern match @@ -6892,9 +7057,9 @@ let mkStaticCall_String_Concat_Array g m arg = // Hence each of the following are marked with places where they are generated. // Generated by the optimizer and the encoding of 'for' loops -let mkDecr (g: TcGlobals) m e = mkAsmExpr([ IL.AI_sub ], [], [e; mkOne g m], [g.int_ty], m) +let mkDecr (g: TcGlobals) m e = mkAsmExpr ([ IL.AI_sub ], [], [e; mkOne g m], [g.int_ty], m) -let mkIncr (g: TcGlobals) m e = mkAsmExpr([ IL.AI_add ], [], [mkOne g m; e], [g.int_ty], m) +let mkIncr (g: TcGlobals) m e = mkAsmExpr ([ IL.AI_add ], [], [mkOne g m; e], [g.int_ty], m) // Generated by the pattern match compiler and the optimizer for // 1. array patterns @@ -6915,18 +7080,20 @@ let mkILAsmClt (g: TcGlobals) m e1 e2 = mkAsmExpr ([ IL.AI_clt ], [], [e1; e2], // This is generated in the initialization of the "ctorv" field in the typechecker's compilation of // an implicit class construction. -let mkNull m ty = Expr.Const(Const.Zero, m, ty) +let mkNull m ty = Expr.Const (Const.Zero, m, ty) let mkThrow m ty e = mkAsmExpr ([ IL.I_throw ], [], [e], [ty], m) let destThrow = function - | Expr.Op (TOp.ILAsm([IL.I_throw], [ty2]), [], [e], m) -> Some (m, ty2, e) + | Expr.Op (TOp.ILAsm ([IL.I_throw], [ty2]), [], [e], m) -> Some (m, ty2, e) | _ -> None let isThrow x = Option.isSome (destThrow x) // reraise - parsed as library call - internally represented as op form. -let mkReraiseLibCall (g: TcGlobals) ty m = let ve, vt = typedExprForIntrinsic g m g.reraise_info in Expr.App(ve, vt, [ty], [mkUnit g m], m) +let mkReraiseLibCall (g: TcGlobals) ty m = + let ve, vt = typedExprForIntrinsic g m g.reraise_info + Expr.App (ve, vt, [ty], [mkUnit g m], m) let mkReraise m returnTy = Expr.Op (TOp.Reraise, [returnTy], [], m) (* could suppress unitArg *) @@ -6947,7 +7114,7 @@ let tref_SourceConstructFlags (g: TcGlobals) = mkILTyRef (g.fslibCcu.ILScopeRef, let mkCompilationMappingAttrPrim (g: TcGlobals) k nums = mkILCustomAttribute g.ilg (tref_CompilationMappingAttr g, ((mkILNonGenericValueTy (tref_SourceConstructFlags g)) :: (nums |> List.map (fun _ -> g.ilg.typ_Int32))), - ((k :: nums) |> List.map (fun n -> ILAttribElem.Int32(n))), + ((k :: nums) |> List.map (fun n -> ILAttribElem.Int32 n)), []) let mkCompilationMappingAttr g kind = mkCompilationMappingAttrPrim g kind [] @@ -6958,7 +7125,7 @@ let mkCompilationMappingAttrWithVariantNumAndSeqNum g kind varNum seqNum = mkCom let mkCompilationArgumentCountsAttr (g: TcGlobals) nums = mkILCustomAttribute g.ilg (tref_CompilationArgumentCountsAttr g, [ mkILArr1DTy g.ilg.typ_Int32 ], - [ILAttribElem.Array (g.ilg.typ_Int32, List.map (fun n -> ILAttribElem.Int32(n)) nums)], + [ILAttribElem.Array (g.ilg.typ_Int32, List.map (fun n -> ILAttribElem.Int32 n) nums)], []) let mkCompilationSourceNameAttr (g: TcGlobals) n = @@ -6985,8 +7152,8 @@ let TryDecodeTypeProviderAssemblyAttr ilg (cattr: ILAttribute) = if isTypeProviderAssemblyAttr cattr then let parms, _args = decodeILAttribData ilg cattr match parms with // The first parameter to the attribute is the name of the assembly with the compiler extensions. - | (ILAttribElem.String (Some assemblyName))::_ -> Some assemblyName - | (ILAttribElem.String None)::_ -> Some null + | (ILAttribElem.String (Some assemblyName)) :: _ -> Some assemblyName + | (ILAttribElem.String None) :: _ -> Some null | [] -> Some null | _ -> None else @@ -7004,13 +7171,13 @@ let tnames_SignatureDataVersionAttr = splitILTypeName tname_SignatureDataVersion let tref_SignatureDataVersionAttr () = mkILTyRef(IlxSettings.ilxFsharpCoreLibScopeRef (), tname_SignatureDataVersionAttr) -let mkSignatureDataVersionAttr (g: TcGlobals) ((v1, v2, v3, _) : ILVersionInfo) = +let mkSignatureDataVersionAttr (g: TcGlobals) (version: ILVersionInfo) = mkILCustomAttribute g.ilg (tref_SignatureDataVersionAttr(), [g.ilg.typ_Int32;g.ilg.typ_Int32;g.ilg.typ_Int32], - [ILAttribElem.Int32 (int32 v1) - ILAttribElem.Int32 (int32 v2) - ILAttribElem.Int32 (int32 v3)], []) + [ILAttribElem.Int32 (int32 version.Major) + ILAttribElem.Int32 (int32 version.Minor) + ILAttribElem.Int32 (int32 version.Build)], []) let tname_AutoOpenAttr = FSharpLib.Core + ".AutoOpenAttribute" @@ -7040,17 +7207,17 @@ let TryFindInternalsVisibleToAttr ilg cattr = else None -let IsMatchingSignatureDataVersionAttr ilg ((v1, v2, v3, _) : ILVersionInfo) cattr = +let IsMatchingSignatureDataVersionAttr ilg (version: ILVersionInfo) cattr = IsSignatureDataVersionAttr cattr && match decodeILAttribData ilg cattr with - | [ILAttribElem.Int32 u1; ILAttribElem.Int32 u2;ILAttribElem.Int32 u3 ], _ -> - (v1 = uint16 u1) && (v2 = uint16 u2) && (v3 = uint16 u3) + | [ILAttribElem.Int32 u1; ILAttribElem.Int32 u2;ILAttribElem.Int32 u3 ], _ -> + (version.Major = uint16 u1) && (version.Minor = uint16 u2) && (version.Build = uint16 u3) | _ -> warning(Failure(FSComp.SR.tastUnexpectedDecodeOfInterfaceDataVersionAttribute())) false let mkCompilerGeneratedAttr (g: TcGlobals) n = - mkILCustomAttribute g.ilg (tref_CompilationMappingAttr g, [mkILNonGenericValueTy (tref_SourceConstructFlags g)], [ILAttribElem.Int32(n)], []) + mkILCustomAttribute g.ilg (tref_CompilationMappingAttr g, [mkILNonGenericValueTy (tref_SourceConstructFlags g)], [ILAttribElem.Int32 n], []) //-------------------------------------------------------------------------- // tupled lambda --> method/function with a given topValInfo specification. @@ -7095,7 +7262,7 @@ let AdjustArityOfLambdaBody g arity (vs: Val list) body = let MultiLambdaToTupledLambda g vs body = match vs with - | [] -> failwith "MultiLambdaToTupledLambda: expected some argments" + | [] -> failwith "MultiLambdaToTupledLambda: expected some arguments" | [v] -> v, body | vs -> let tupledv, untupler = untupledToRefTupled g vs @@ -7108,7 +7275,7 @@ let (|RefTuple|_|) expr = let MultiLambdaToTupledLambdaIfNeeded g (vs, arg) body = match vs, arg with - | [], _ -> failwith "MultiLambdaToTupledLambda: expected some argments" + | [], _ -> failwith "MultiLambdaToTupledLambda: expected some arguments" | [v], _ -> [(v, arg)], body | vs, RefTuple args when args.Length = vs.Length -> List.zip vs args, body | vs, _ -> @@ -7125,7 +7292,7 @@ let MultiLambdaToTupledLambdaIfNeeded g (vs, arg) body = let rec MakeApplicationAndBetaReduceAux g (f, fty, tyargsl: TType list list, argsl: Expr list, m) = match f with - | Expr.Let(bind, body, mlet, _) -> + | Expr.Let (bind, body, mlet, _) -> // Lift bindings out, i.e. (let x = e in f) y --> let x = e in f y // This increases the scope of 'x', which I don't like as it mucks with debugging // scopes of variables, but this is an important optimization, especially when the '|>' @@ -7139,7 +7306,7 @@ let rec MakeApplicationAndBetaReduceAux g (f, fty, tyargsl: TType list list, arg | tyargs :: rest -> // Bind type parameters by immediate substitution match f with - | Expr.TyLambda(_, tyvs, body, _, bodyty) when tyvs.Length = List.length tyargs -> + | Expr.TyLambda (_, tyvs, body, _, bodyty) when tyvs.Length = List.length tyargs -> let tpenv = bindTypars tyvs tyargs emptyTyparInst let body = remarkExpr m (instExpr g tpenv body) let bodyty' = instType tpenv bodyty @@ -7169,7 +7336,7 @@ let rec MakeApplicationAndBetaReduceAux g (f, fty, tyargsl: TType list list, arg let argvs2, args2 = List.unzip (List.concat pairs) mkLetsBind m (mkCompGenBinds argvs2 args2) body | _ -> - mkExprApplAux g f fty argsl m + mkExprAppAux g f fty argsl m | [] -> f @@ -7200,7 +7367,7 @@ let AdjustValForExpectedArity g m (vref: ValRef) flags topValInfo = let tpenv = bindTypars tps tyargs' emptyTyparInst let rty' = instType tpenv rty let vsl = MakeArgsForTopArgs g m argtysl tpenv - let call = MakeApplicationAndBetaReduce g (Expr.Val(vref, flags, m), vref.Type, [tyargs'], (List.map (mkRefTupledVars g m) vsl), m) + let call = MakeApplicationAndBetaReduce g (Expr.Val (vref, flags, m), vref.Type, [tyargs'], (List.map (mkRefTupledVars g m) vsl), m) let tauexpr, tauty = List.foldBack (fun vs (e, ty) -> mkMultiLambda m vs (e, ty), (mkRefTupledVarsTy g vs --> ty)) @@ -7519,7 +7686,7 @@ let NormalizeAndAdjustPossibleSubsumptionExprs g inputExpr = let expr, args = // AdjustPossibleSubsumptionExpr can take into account an application match stripExpr inputExpr with - | Expr.App(f, _fty, [], args, _) -> + | Expr.App (f, _fty, [], args, _) -> f, args | _ -> @@ -7532,7 +7699,7 @@ let NormalizeAndAdjustPossibleSubsumptionExprs g inputExpr = expr' | Some (expr', args') -> //printfn "adjusted...." - Expr.App(expr', tyOfExpr g expr', [], args', inputExpr.Range) + Expr.App (expr', tyOfExpr g expr', [], args', inputExpr.Range) //--------------------------------------------------------------------------- @@ -7574,12 +7741,11 @@ let LinearizeTopMatchAux g parent (spBind, m, tree, targets, m2, ty) = match tys with | [] -> failwith "itemsProj: no items?" | [_] -> x (* no projection needed *) - | tys -> Expr.Op (TOp.TupleFieldGet(tupInfoRef, i), tys, [x], m) + | tys -> Expr.Op (TOp.TupleFieldGet (tupInfoRef, i), tys, [x], m) let isThrowingTarget = function TTarget(_, x, _) -> isThrow x if 1 + List.count isThrowingTarget targetsL = targetsL.Length then - (* Have failing targets and ONE successful one, so linearize *) - let (TTarget (vs, rhs, spTarget)) = Option.get (List.tryFind (isThrowingTarget >> not) targetsL) - (* note - old code here used copy value to generate locals - this was not right *) + // Have failing targets and ONE successful one, so linearize + let (TTarget (vs, rhs, spTarget)) = List.find (isThrowingTarget >> not) targetsL let fvs = vs |> List.map (fun v -> fst(mkLocal v.Range v.LogicalName v.Type)) (* fresh *) let vtys = vs |> List.map (fun v -> v.Type) let tmpTy = mkRefTupledVarsTy g vs @@ -7640,7 +7806,6 @@ let typarEnc _g (gtpsType, gtpsMethod) typar = "``0" let rec typeEnc g (gtpsType, gtpsMethod) ty = - if verbose then dprintf "--> typeEnc" let stripped = stripTyEqnsAndMeasureEqns g ty match stripped with | TType_forall _ -> @@ -7657,7 +7822,7 @@ let rec typeEnc g (gtpsType, gtpsMethod) ty = | _ -> failwith "impossible: rankOfArrayTyconRef: unsupported array rank" typeEnc g (gtpsType, gtpsMethod) (List.head tinst) + arraySuffix - | TType_ucase (UCRef(tcref, _), tinst) + | TType_ucase (UnionCaseRef(tcref, _), tinst) | TType_app (tcref, tinst) -> if tyconRefEq g g.byref_tcr tcref then typeEnc g (gtpsType, gtpsMethod) (List.head tinst) + "@" @@ -7706,7 +7871,7 @@ let XmlDocArgsEnc g (gtpsType, gtpsMethod) argTs = let buildAccessPath (cp: CompilationPath option) = match cp with - | Some(cp) -> + | Some cp -> let ap = cp.AccessPath |> List.map fst |> List.toArray System.String.Join(".", ap) | None -> "Extension Type" @@ -7727,7 +7892,7 @@ let XmlDocSigOfVal g path (v: Val) = match membInfo.MemberFlags.MemberKind with | MemberKind.ClassConstructor | MemberKind.Constructor -> "M:", "#ctor" - | MemberKind.Member -> "M:", v.CompiledName + | MemberKind.Member -> "M:", v.CompiledName g.CompilerGlobalState | MemberKind.PropertyGetSet | MemberKind.PropertySet | MemberKind.PropertyGet -> "P:", v.PropertyName @@ -7741,7 +7906,7 @@ let XmlDocSigOfVal g path (v: Val) = // Regular F# values and extension members let w = arityOfVal v let tps, argInfos, _, _ = GetTopValTypeInCompiledForm g w v.Type v.Range - let name = v.CompiledName + let name = v.CompiledName g.CompilerGlobalState let prefix = if w.NumCurriedArgs = 0 && isNil tps then "P:" else "M:" @@ -7780,7 +7945,7 @@ let enum_CompilationRepresentationAttribute_PermitNull = 0b0000000000001000 let HasUseNullAsTrueValueAttribute g attribs = match TryFindFSharpInt32Attribute g g.attrib_CompilationRepresentationAttribute attribs with - | Some(flags) -> ((flags &&& enum_CompilationRepresentationAttribute_PermitNull) <> 0) + | Some flags -> ((flags &&& enum_CompilationRepresentationAttribute_PermitNull) <> 0) | _ -> false let TyconHasUseNullAsTrueValueAttribute g (tycon: Tycon) = HasUseNullAsTrueValueAttribute g tycon.Attribs @@ -7816,15 +7981,15 @@ let TypeNullNever g ty = let TypeNullIsExtraValue g m ty = if isILReferenceTy g ty || isDelegateTy g ty then // Putting AllowNullLiteralAttribute(false) on an IL or provided type means 'null' can't be used with that type - not (match tryDestAppTy g ty with ValueSome tcref -> TryFindTyconRefBoolAttribute g m g.attrib_AllowNullLiteralAttribute tcref = Some false | _ -> false) + not (match tryTcrefOfAppTy g ty with ValueSome tcref -> TryFindTyconRefBoolAttribute g m g.attrib_AllowNullLiteralAttribute tcref = Some false | _ -> false) elif TypeNullNever g ty then false else // Putting AllowNullLiteralAttribute(true) on an F# type means 'null' can be used with that type - match tryDestAppTy g ty with ValueSome tcref -> TryFindTyconRefBoolAttribute g m g.attrib_AllowNullLiteralAttribute tcref = Some true | _ -> false + match tryTcrefOfAppTy g ty with ValueSome tcref -> TryFindTyconRefBoolAttribute g m g.attrib_AllowNullLiteralAttribute tcref = Some true | _ -> false let TypeNullIsTrueValue g ty = - (match tryDestAppTy g ty with + (match tryTcrefOfAppTy g ty with | ValueSome tcref -> IsUnionTypeWithNullAsTrueValue g tcref.Deref | _ -> false) || (isUnitTy g ty) @@ -7847,7 +8012,7 @@ let rec TypeHasDefaultValue g m ty = // Note this includes fields implied by the use of the implicit class construction syntax tcref.AllInstanceFieldsAsList // We can ignore fields with the DefaultValue(false) attribute - |> List.filter (fun fld -> not (TryFindFSharpBoolAttribute g g.attrib_DefaultValueAttribute fld.FieldAttribs = Some(false))) + |> List.filter (fun fld -> not (TryFindFSharpBoolAttribute g g.attrib_DefaultValueAttribute fld.FieldAttribs = Some false)) flds |> List.forall (actualTyOfRecdField (mkTyconRefInst tcref tinst) >> TypeHasDefaultValue g m) elif isStructTupleTy g ty then @@ -7912,17 +8077,17 @@ let mkIsInstConditional g m tgty vinpe v e2 e3 = if canUseTypeTestFast g tgty then - let mbuilder = new MatchBuilder(NoSequencePointAtInvisibleBinding, m) - let tg2 = mbuilder.AddResultTarget(e2, SuppressSequencePointAtTarget) - let tg3 = mbuilder.AddResultTarget(e3, SuppressSequencePointAtTarget) + let mbuilder = new MatchBuilder(NoDebugPointAtInvisibleBinding, m) + let tg2 = mbuilder.AddResultTarget(e2, DebugPointForTarget.No) + let tg3 = mbuilder.AddResultTarget(e3, DebugPointForTarget.No) let dtree = TDSwitch(exprForVal m v, [TCase(DecisionTreeTest.IsNull, tg3)], Some tg2, m) let expr = mbuilder.Close(dtree, m, tyOfExpr g e2) mkCompGenLet m v (mkIsInst tgty vinpe m) expr else - let mbuilder = new MatchBuilder(NoSequencePointAtInvisibleBinding, m) - let tg2 = TDSuccess([mkCallUnbox g m tgty vinpe], mbuilder.AddTarget(TTarget([v], e2, SuppressSequencePointAtTarget))) - let tg3 = mbuilder.AddResultTarget(e3, SuppressSequencePointAtTarget) + let mbuilder = new MatchBuilder(NoDebugPointAtInvisibleBinding, m) + let tg2 = TDSuccess([mkCallUnbox g m tgty vinpe], mbuilder.AddTarget(TTarget([v], e2, DebugPointForTarget.No))) + let tg3 = mbuilder.AddResultTarget(e3, DebugPointForTarget.No) let dtree = TDSwitch(vinpe, [TCase(DecisionTreeTest.IsInst(tyOfExpr g vinpe, tgty), tg2)], Some tg3, m) let expr = mbuilder.Close(dtree, m, tyOfExpr g e2) expr @@ -7933,20 +8098,20 @@ let mkIsInstConditional g m tgty vinpe v e2 e3 = // 1. The compilation of array patterns in the pattern match compiler // 2. The compilation of string patterns in the pattern match compiler let mkNullTest g m e1 e2 e3 = - let mbuilder = new MatchBuilder(NoSequencePointAtInvisibleBinding, m) - let tg2 = mbuilder.AddResultTarget(e2, SuppressSequencePointAtTarget) - let tg3 = mbuilder.AddResultTarget(e3, SuppressSequencePointAtTarget) + let mbuilder = new MatchBuilder(NoDebugPointAtInvisibleBinding, m) + let tg2 = mbuilder.AddResultTarget(e2, DebugPointForTarget.No) + let tg3 = mbuilder.AddResultTarget(e3, DebugPointForTarget.No) let dtree = TDSwitch(e1, [TCase(DecisionTreeTest.IsNull, tg3)], Some tg2, m) let expr = mbuilder.Close(dtree, m, tyOfExpr g e2) expr let mkNonNullTest (g: TcGlobals) m e = mkAsmExpr ([ IL.AI_ldnull ; IL.AI_cgt_un ], [], [e], [g.bool_ty], m) -let mkNonNullCond g m ty e1 e2 e3 = mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m ty (mkNonNullTest g m e1) e2 e3 -let mkIfThen (g: TcGlobals) m e1 e2 = mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.unit_ty e1 e2 (mkUnit g m) +let mkNonNullCond g m ty e1 e2 e3 = mkCond NoDebugPointAtStickyBinding DebugPointForTarget.No m ty (mkNonNullTest g m e1) e2 e3 +let mkIfThen (g: TcGlobals) m e1 e2 = mkCond NoDebugPointAtStickyBinding DebugPointForTarget.No m g.unit_ty e1 e2 (mkUnit g m) let ModuleNameIsMangled g attrs = match TryFindFSharpInt32Attribute g g.attrib_CompilationRepresentationAttribute attrs with - | Some(flags) -> ((flags &&& enum_CompilationRepresentationAttribute_ModuleSuffix) <> 0) + | Some flags -> ((flags &&& enum_CompilationRepresentationAttribute_ModuleSuffix) <> 0) | _ -> false let CompileAsEvent g attrs = HasFSharpAttribute g g.attrib_CLIEventAttribute attrs @@ -7962,7 +8127,7 @@ let MemberIsCompiledAsInstance g parent isExtensionMember (membInfo: ValMemberIn // Otherwise check attributes to see if there is an explicit instance or explicit static flag let explicitInstance, explicitStatic = match TryFindFSharpInt32Attribute g g.attrib_CompilationRepresentationAttribute attrs with - | Some(flags) -> + | Some flags -> ((flags &&& enum_CompilationRepresentationAttribute_Instance) <> 0), ((flags &&& enum_CompilationRepresentationAttribute_Static) <> 0) | _ -> false, false @@ -7995,11 +8160,11 @@ let isComInteropTy g ty = let tcref = tcrefOfAppTy g ty match g.attrib_ComImportAttribute with | None -> false - | Some attr -> TryFindFSharpBoolAttribute g attr tcref.Attribs = Some(true) + | Some attr -> TryFindFSharpBoolAttribute g attr tcref.Attribs = Some true let ValSpecIsCompiledAsInstance g (v: Val) = match v.MemberInfo with - | Some(membInfo) -> + | Some membInfo -> // Note it doesn't matter if we pass 'v.TopValDeclaringEntity' or 'v.MemberApparentEntity' here. // These only differ if the value is an extension member, and in that case MemberIsCompiledAsInstance always returns // false anyway @@ -8015,7 +8180,7 @@ let ValRefIsCompiledAsInstanceMember g (vref: ValRef) = ValSpecIsCompiledAsInsta let GetMemberCallInfo g (vref: ValRef, vFlags) = match vref.MemberInfo with - | Some(membInfo) when not vref.IsExtensionMember -> + | Some membInfo when not vref.IsExtensionMember -> let numEnclTypeArgs = vref.MemberApparentEntity.TyparsNoRange.Length let virtualCall = (membInfo.MemberFlags.IsOverrideOrExplicitImpl || @@ -8149,24 +8314,24 @@ and preRewriteExpr env expr = and postRewriteExpr env expr = match env.PostTransform expr with | None -> expr - | Some expr -> expr + | Some expr2 -> expr2 and rewriteExprStructure env expr = match expr with | Expr.Const _ | Expr.Val _ -> expr - | Expr.App(f0, f0ty, tyargs, args, m) -> + | Expr.App (f0, f0ty, tyargs, args, m) -> let f0' = RewriteExpr env f0 let args' = rewriteExprs env args if f0 === f0' && args === args' then expr - else Expr.App(f0', f0ty, tyargs, args', m) + else Expr.App (f0', f0ty, tyargs, args', m) - | Expr.Quote(ast, {contents=Some(typeDefs, argTypes, argExprs, data)}, isFromQueryExpression, m, ty) -> - Expr.Quote((if env.IsUnderQuotations then RewriteExpr env ast else ast), {contents=Some(typeDefs, argTypes, rewriteExprs env argExprs, data)}, isFromQueryExpression, m, ty) + | Expr.Quote (ast, {contents=Some(typeDefs, argTypes, argExprs, data)}, isFromQueryExpression, m, ty) -> + Expr.Quote ((if env.IsUnderQuotations then RewriteExpr env ast else ast), {contents=Some(typeDefs, argTypes, rewriteExprs env argExprs, data)}, isFromQueryExpression, m, ty) - | Expr.Quote(ast, {contents=None}, isFromQueryExpression, m, ty) -> - Expr.Quote((if env.IsUnderQuotations then RewriteExpr env ast else ast), {contents=None}, isFromQueryExpression, m, ty) + | Expr.Quote (ast, {contents=None}, isFromQueryExpression, m, ty) -> + Expr.Quote ((if env.IsUnderQuotations then RewriteExpr env ast else ast), {contents=None}, isFromQueryExpression, m, ty) | Expr.Obj (_, ty, basev, basecall, overrides, iimpls, m) -> mkObjExpr(ty, basev, RewriteExpr env basecall, List.map (rewriteObjExprOverride env) overrides, @@ -8179,23 +8344,23 @@ and rewriteExprStructure env expr = if args === args' then expr else Expr.Op (c, tyargs, args', m) - | Expr.Lambda(_lambdaId, ctorThisValOpt, baseValOpt, argvs, body, m, rty) -> + | Expr.Lambda (_lambdaId, ctorThisValOpt, baseValOpt, argvs, body, m, rty) -> let body = RewriteExpr env body rebuildLambda m ctorThisValOpt baseValOpt argvs (body, rty) - | Expr.TyLambda(_lambdaId, argtyvs, body, m, rty) -> + | Expr.TyLambda (_lambdaId, argtyvs, body, m, rty) -> let body = RewriteExpr env body mkTypeLambda m argtyvs (body, rty) - | Expr.Match(spBind, exprm, dtree, targets, m, ty) -> - let dtree' = rewriteDecisionTree env dtree + | Expr.Match (spBind, exprm, dtree, targets, m, ty) -> + let dtree' = RewriteDecisionTree env dtree let targets' = rewriteTargets env targets mkAndSimplifyMatch spBind exprm m ty dtree' targets' | Expr.LetRec (binds, e, m, _) -> let binds = rewriteBinds env binds let e' = RewriteExpr env e - Expr.LetRec(binds, e', m, NewFreeVarsCache()) + Expr.LetRec (binds, e', m, Construct.NewFreeVarsCache()) | Expr.Let _ -> failwith "unreachable - linear let" @@ -8204,10 +8369,10 @@ and rewriteExprStructure env expr = | Expr.StaticOptimization (constraints, e2, e3, m) -> let e2' = RewriteExpr env e2 let e3' = RewriteExpr env e3 - Expr.StaticOptimization(constraints, e2', e3', m) + Expr.StaticOptimization (constraints, e2', e3', m) | Expr.TyChoose (a, b, m) -> - Expr.TyChoose(a, RewriteExpr env b, m) + Expr.TyChoose (a, RewriteExpr env b, m) and rewriteLinearExpr env expr contf = // schedule a rewrite on the way back up by adding to the continuation @@ -8227,7 +8392,7 @@ and rewriteLinearExpr env expr contf = // tailcall rewriteLinearExpr env expr2 (contf << (fun expr2' -> if expr1 === expr1' && expr2 === expr2' then expr - else Expr.Sequential(expr1', expr2', dir, spSeq, m))) + else Expr.Sequential (expr1', expr2', dir, spSeq, m))) | LinearOpExpr (op, tyargs, argsFront, argLast, m) -> let argsFront' = rewriteExprs env argsFront @@ -8237,7 +8402,7 @@ and rewriteLinearExpr env expr contf = else rebuildLinearOpExpr (op, tyargs, argsFront', argLast', m))) | LinearMatchExpr (spBind, exprm, dtree, tg1, expr2, sp2, m2, ty) -> - let dtree = rewriteDecisionTree env dtree + let dtree = RewriteDecisionTree env dtree let tg1' = rewriteTarget env tg1 // tailcall rewriteLinearExpr env expr2 (contf << (fun expr2' -> @@ -8250,7 +8415,7 @@ and rewriteExprs env exprs = List.mapq (RewriteExpr env) exprs and rewriteFlatExprs env exprs = List.mapq (RewriteExpr env) exprs -and rewriteDecisionTree env x = +and RewriteDecisionTree env x = match x with | TDSuccess (es, n) -> let es' = rewriteFlatExprs env es @@ -8259,24 +8424,26 @@ and rewriteDecisionTree env x = | TDSwitch (e, cases, dflt, m) -> let e' = RewriteExpr env e - let cases' = List.map (fun (TCase(discrim, e)) -> TCase(discrim, rewriteDecisionTree env e)) cases - let dflt' = Option.map (rewriteDecisionTree env) dflt + let cases' = List.map (fun (TCase(discrim, e)) -> TCase(discrim, RewriteDecisionTree env e)) cases + let dflt' = Option.map (RewriteDecisionTree env) dflt TDSwitch (e', cases', dflt', m) | TDBind (bind, body) -> let bind' = rewriteBind env bind - let body = rewriteDecisionTree env body + let body = RewriteDecisionTree env body TDBind (bind', body) -and rewriteTarget env (TTarget(vs, e, spTarget)) = TTarget(vs, RewriteExpr env e, spTarget) +and rewriteTarget env (TTarget(vs, e, spTarget)) = + TTarget(vs, RewriteExpr env e, spTarget) -and rewriteTargets env targets = List.map (rewriteTarget env) (Array.toList targets) +and rewriteTargets env targets = + List.map (rewriteTarget env) (Array.toList targets) and rewriteObjExprOverride env (TObjExprMethod(slotsig, attribs, tps, vs, e, m)) = - TObjExprMethod(slotsig, attribs, tps, vs, RewriteExpr env e, m) + TObjExprMethod(slotsig, attribs, tps, vs, RewriteExpr env e, m) and rewriteObjExprInterfaceImpl env (ty, overrides) = - (ty, List.map (rewriteObjExprOverride env) overrides) + (ty, List.map (rewriteObjExprOverride env) overrides) and rewriteModuleOrNamespaceExpr env x = match x with @@ -8370,11 +8537,11 @@ let rec remapEntityDataToNonLocal g tmenv (d: Entity) = | _ -> None } and remapTyconToNonLocal g tmenv x = - x |> NewModifiedTycon (remapEntityDataToNonLocal g tmenv) + x |> Construct.NewModifiedTycon (remapEntityDataToNonLocal g tmenv) and remapValToNonLocal g tmenv inp = // creates a new stamp - inp |> NewModifiedVal (remapValData g tmenv) + inp |> Construct.NewModifiedVal (remapValData g tmenv) let ApplyExportRemappingToEntity g tmenv x = remapTyconToNonLocal g tmenv x @@ -8391,7 +8558,7 @@ let isCompiledConstraint cx = // Is a value a first-class polymorphic value with .NET constraints? // Used to turn off TLR and method splitting -let IsGenericValWithGenericContraints g (v: Val) = +let IsGenericValWithGenericConstraints g (v: Val) = isForallTy g v.Type && v.Type |> destForallTy g |> fst |> List.exists (fun tp -> List.exists isCompiledConstraint tp.Constraints) @@ -8470,9 +8637,9 @@ let IsSimpleSyntacticConstantExpr g inputExpr = valRefEq g vref g.bitwise_or_vref) && (not (typeEquiv g (tyOfExpr g arg1) g.string_ty) && not (typeEquiv g (tyOfExpr g arg1) g.decimal_ty) ) -> checkExpr vrefs arg1 && checkExpr vrefs arg2 - | Expr.Val(vref, _, _) -> vref.Deref.IsCompiledAsStaticPropertyWithoutField || vrefs.Contains vref.Stamp - | Expr.Match(_, _, dtree, targets, _, _) -> checkDecisionTree vrefs dtree && targets |> Array.forall (checkDecisionTreeTarget vrefs) - | Expr.Let(b, e, _, _) -> checkExpr vrefs b.Expr && checkExpr (vrefs.Add b.Var.Stamp) e + | Expr.Val (vref, _, _) -> vref.Deref.IsCompiledAsStaticPropertyWithoutField || vrefs.Contains vref.Stamp + | Expr.Match (_, _, dtree, targets, _, _) -> checkDecisionTree vrefs dtree && targets |> Array.forall (checkDecisionTreeTarget vrefs) + | Expr.Let (b, e, _, _) -> checkExpr vrefs b.Expr && checkExpr (vrefs.Add b.Var.Stamp) e // Detect standard constants | Expr.TyChoose (_, b, _) -> checkExpr vrefs b | Expr.Const _ @@ -8480,6 +8647,7 @@ let IsSimpleSyntacticConstantExpr g inputExpr = | UncheckedDefaultOfExpr g _ | SizeOfExpr g _ | TypeOfExpr g _ -> true + | NameOfExpr g _ when g.langVersion.SupportsFeature LanguageFeature.NameOf -> true // All others are not simple constant expressions | _ -> false @@ -8488,8 +8656,10 @@ let IsSimpleSyntacticConstantExpr g inputExpr = | TDSuccess (es, _n) -> es |> List.forall (checkExpr vrefs) | TDSwitch (e, cases, dflt, _m) -> checkExpr vrefs e && cases |> List.forall (checkDecisionTreeCase vrefs) && dflt |> Option.forall (checkDecisionTree vrefs) | TDBind (bind, body) -> checkExpr vrefs bind.Expr && checkDecisionTree (vrefs.Add bind.Var.Stamp) body + and checkDecisionTreeCase vrefs (TCase(discrim, dtree)) = (match discrim with DecisionTreeTest.Const _c -> true | _ -> false) && checkDecisionTree vrefs dtree + and checkDecisionTreeTarget vrefs (TTarget(vs, e, _)) = let vrefs = ((vrefs, vs) ||> List.fold (fun s v -> s.Add v.Stamp)) checkExpr vrefs e @@ -8501,14 +8671,14 @@ let EvalArithBinOp (opInt8, opInt16, opInt32, opInt64, opUInt8, opUInt16, opUInt let m = unionRanges arg1.Range arg2.Range try match arg1, arg2 with - | Expr.Const(Const.Int32 x1, _, ty), Expr.Const(Const.Int32 x2, _, _) -> Expr.Const(Const.Int32 (opInt32 x1 x2), m, ty) - | Expr.Const(Const.SByte x1, _, ty), Expr.Const(Const.SByte x2, _, _) -> Expr.Const(Const.SByte (opInt8 x1 x2), m, ty) - | Expr.Const(Const.Int16 x1, _, ty), Expr.Const(Const.Int16 x2, _, _) -> Expr.Const(Const.Int16 (opInt16 x1 x2), m, ty) - | Expr.Const(Const.Int64 x1, _, ty), Expr.Const(Const.Int64 x2, _, _) -> Expr.Const(Const.Int64 (opInt64 x1 x2), m, ty) - | Expr.Const(Const.Byte x1, _, ty), Expr.Const(Const.Byte x2, _, _) -> Expr.Const(Const.Byte (opUInt8 x1 x2), m, ty) - | Expr.Const(Const.UInt16 x1, _, ty), Expr.Const(Const.UInt16 x2, _, _) -> Expr.Const(Const.UInt16 (opUInt16 x1 x2), m, ty) - | Expr.Const(Const.UInt32 x1, _, ty), Expr.Const(Const.UInt32 x2, _, _) -> Expr.Const(Const.UInt32 (opUInt32 x1 x2), m, ty) - | Expr.Const(Const.UInt64 x1, _, ty), Expr.Const(Const.UInt64 x2, _, _) -> Expr.Const(Const.UInt64 (opUInt64 x1 x2), m, ty) + | Expr.Const (Const.Int32 x1, _, ty), Expr.Const (Const.Int32 x2, _, _) -> Expr.Const (Const.Int32 (opInt32 x1 x2), m, ty) + | Expr.Const (Const.SByte x1, _, ty), Expr.Const (Const.SByte x2, _, _) -> Expr.Const (Const.SByte (opInt8 x1 x2), m, ty) + | Expr.Const (Const.Int16 x1, _, ty), Expr.Const (Const.Int16 x2, _, _) -> Expr.Const (Const.Int16 (opInt16 x1 x2), m, ty) + | Expr.Const (Const.Int64 x1, _, ty), Expr.Const (Const.Int64 x2, _, _) -> Expr.Const (Const.Int64 (opInt64 x1 x2), m, ty) + | Expr.Const (Const.Byte x1, _, ty), Expr.Const (Const.Byte x2, _, _) -> Expr.Const (Const.Byte (opUInt8 x1 x2), m, ty) + | Expr.Const (Const.UInt16 x1, _, ty), Expr.Const (Const.UInt16 x2, _, _) -> Expr.Const (Const.UInt16 (opUInt16 x1 x2), m, ty) + | Expr.Const (Const.UInt32 x1, _, ty), Expr.Const (Const.UInt32 x2, _, _) -> Expr.Const (Const.UInt32 (opUInt32 x1 x2), m, ty) + | Expr.Const (Const.UInt64 x1, _, ty), Expr.Const (Const.UInt64 x2, _, _) -> Expr.Const (Const.UInt64 (opUInt64 x1 x2), m, ty) | _ -> error (Error ( FSComp.SR.tastNotAConstantExpression(), m)) with :? System.OverflowException -> error (Error ( FSComp.SR.tastConstantExpressionOverflow(), m)) @@ -8517,7 +8687,7 @@ let rec EvalAttribArgExpr g x = match x with // Detect standard constants - | Expr.Const(c, m, _) -> + | Expr.Const (c, m, _) -> match c with | Const.Bool _ | Const.Int32 _ @@ -8552,7 +8722,7 @@ let rec EvalAttribArgExpr g x = // At compile-time we check arithmetic let v1, v2 = EvalAttribArgExpr g arg1, EvalAttribArgExpr g arg2 match v1, v2 with - | Expr.Const(Const.String x1, m, ty), Expr.Const(Const.String x2, _, _) -> Expr.Const(Const.String (x1 + x2), m, ty) + | Expr.Const (Const.String x1, m, ty), Expr.Const (Const.String x2, _, _) -> Expr.Const (Const.String (x1 + x2), m, ty) | _ -> #if ALLOW_ARITHMETIC_OPS_IN_LITERAL_EXPRESSIONS_AND_ATTRIBUTE_ARGS EvalArithBinOp (Checked.(+), Checked.(+), Checked.(+), Checked.(+), Checked.(+), Checked.(+), Checked.(+), Checked.(+)) g v1 v2 @@ -8573,7 +8743,7 @@ let rec EvalAttribArgExpr g x = and EvaledAttribExprEquality g e1 e2 = match e1, e2 with - | Expr.Const(c1, _, _), Expr.Const(c2, _, _) -> c1 = c2 + | Expr.Const (c1, _, _), Expr.Const (c2, _, _) -> c1 = c2 | TypeOfExpr g ty1, TypeOfExpr g ty2 -> typeEquiv g ty1 ty2 | TypeDefOfExpr g ty1, TypeDefOfExpr g ty2 -> typeEquiv g ty1 ty2 | _ -> false @@ -8626,7 +8796,7 @@ let GetTypeOfIntrinsicMemberInCompiledForm g (vref: ValRef) = | [] -> errorR(InternalError("value does not have a valid member type", vref.Range)) argInfos - | h::_ -> h :: argInfos + | h :: _ -> h :: argInfos else argInfos tps, argInfos, rty, retInfo @@ -8657,7 +8827,7 @@ let rec mkCompiledTuple g isStruct (argtys, args, m) = | _ -> let a, b, c, d = mkCompiledTuple g isStruct (argtysB, argsB, m) let ty8plus = TType_app(a, b) - let v8plus = Expr.Op (TOp.Tuple(mkTupInfo isStruct), b, c, d) + let v8plus = Expr.Op (TOp.Tuple (mkTupInfo isStruct), b, c, d) ty8plus, v8plus let argtysAB = argtysA @ [ty8] (mkCompiledTupleTyconRef g isStruct (List.length argtysAB), argtysAB, argsA @ [v8], m) @@ -8670,48 +8840,49 @@ let mkILFieldSpecForTupleItem (ty: ILType) n = let mkGetTupleItemN g m n (ty: ILType) isStruct te retty = if isStruct then - mkAsmExpr([mkNormalLdfld (mkILFieldSpecForTupleItem ty n) ], [], [te], [retty], m) + mkAsmExpr ([mkNormalLdfld (mkILFieldSpecForTupleItem ty n) ], [], [te], [retty], m) else - mkAsmExpr([IL.mkNormalCall(mkILMethodSpecForTupleItem g ty n)], [], [te], [retty], m) + mkAsmExpr ([IL.mkNormalCall(mkILMethodSpecForTupleItem g ty n)], [], [te], [retty], m) + /// Match an Int32 constant expression let (|Int32Expr|_|) expr = match expr with - | Expr.Const(Const.Int32 n, _, _) -> Some n + | Expr.Const (Const.Int32 n, _, _) -> Some n | _ -> None /// Match a try-finally expression let (|TryFinally|_|) expr = match expr with - | Expr.Op (TOp.TryFinally _, [_resty], [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [_], e2, _, _)], _) -> Some(e1, e2) + | Expr.Op (TOp.TryFinally _, [_resty], [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [_], e2, _, _)], _) -> Some(e1, e2) | _ -> None // detect ONLY the while loops that result from compiling 'for ... in ... do ...' let (|WhileLoopForCompiledForEachExpr|_|) expr = match expr with - | Expr.Op (TOp.While (_, WhileLoopForCompiledForEachExprMarker), _, [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [_], e2, _, _)], m) -> Some(e1, e2, m) + | Expr.Op (TOp.While (_, WhileLoopForCompiledForEachExprMarker), _, [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [_], e2, _, _)], m) -> Some(e1, e2, m) | _ -> None let (|Let|_|) expr = match expr with - | Expr.Let(TBind(v, e1, sp), e2, _, _) -> Some(v, e1, sp, e2) + | Expr.Let (TBind(v, e1, sp), e2, _, _) -> Some(v, e1, sp, e2) | _ -> None let (|RangeInt32Step|_|) g expr = match expr with // detect 'n .. m' - | Expr.App(Expr.Val(vf, _, _), _, [tyarg], [startExpr;finishExpr], _) + | Expr.App (Expr.Val (vf, _, _), _, [tyarg], [startExpr;finishExpr], _) when valRefEq g vf g.range_op_vref && typeEquiv g tyarg g.int_ty -> Some(startExpr, 1, finishExpr) // detect (RangeInt32 startExpr N finishExpr), the inlined/compiled form of 'n .. m' and 'n .. N .. m' - | Expr.App(Expr.Val(vf, _, _), _, [], [startExpr; Int32Expr n; finishExpr], _) + | Expr.App (Expr.Val (vf, _, _), _, [], [startExpr; Int32Expr n; finishExpr], _) when valRefEq g vf g.range_int32_op_vref -> Some(startExpr, n, finishExpr) | _ -> None let (|GetEnumeratorCall|_|) expr = match expr with - | Expr.Op (TOp.ILCall( _, _, _, _, _, _, _, iLMethodRef, _, _, _), _, [Expr.Val(vref, _, _) | Expr.Op(_, _, [Expr.Val(vref, ValUseFlag.NormalValUse, _)], _) ], _) -> - if iLMethodRef.Name = "GetEnumerator" then Some(vref) + | Expr.Op (TOp.ILCall ( _, _, _, _, _, _, _, iLMethodRef, _, _, _), _, [Expr.Val (vref, _, _) | Expr.Op (_, _, [Expr.Val (vref, ValUseFlag.NormalValUse, _)], _) ], _) -> + if iLMethodRef.Name = "GetEnumerator" then Some vref else None | _ -> None @@ -8733,8 +8904,8 @@ let (|CompiledForEachExpr|_|) g expr = let mBody = bodyExpr.Range let mWholeExpr = expr.Range - let spForLoop, mForLoop = match enumeratorBind with SequencePointAtBinding(spStart) -> SequencePointAtForLoop(spStart), spStart | _ -> NoSequencePointAtForLoop, mEnumExpr - let spWhileLoop = match enumeratorBind with SequencePointAtBinding(spStart) -> SequencePointAtWhileLoop(spStart)| _ -> NoSequencePointAtWhileLoop + let spForLoop, mForLoop = match enumeratorBind with DebugPointAtBinding spStart -> DebugPointAtFor.Yes spStart, spStart | _ -> DebugPointAtFor.No, mEnumExpr + let spWhileLoop = match enumeratorBind with DebugPointAtBinding spStart -> DebugPointAtWhile.Yes spStart| _ -> DebugPointAtWhile.No let enumerableTy = tyOfExpr g enumerableExpr Some (enumerableTy, enumerableExpr, elemVar, bodyExpr, (mEnumExpr, mBody, spForLoop, mForLoop, spWhileLoop, mWholeExpr)) @@ -8815,7 +8986,7 @@ let DetectAndOptimizeForExpression g option expr = let expr = // let mutable current = enumerableExpr - let spBind = (match spForLoop with SequencePointAtForLoop(spStart) -> SequencePointAtBinding(spStart) | NoSequencePointAtForLoop -> NoSequencePointAtStickyBinding) + let spBind = (match spForLoop with DebugPointAtFor.Yes spStart -> DebugPointAtBinding spStart | DebugPointAtFor.No -> NoDebugPointAtStickyBinding) mkLet spBind mEnumExpr currentVar enumerableExpr // let mutable next = current.TailOrNull (mkCompGenLet mForLoop nextVar tailOrNullExpr @@ -8840,10 +9011,9 @@ let BindUnitVars g (mvs: Val list, paramInfos: ArgReprInfo list, body) = match mvs, paramInfos with | [v], [] -> assert isUnitTy g v.Type - [], mkLet NoSequencePointAtInvisibleBinding v.Range v (mkUnit g v.Range) body + [], mkLet NoDebugPointAtInvisibleBinding v.Range v (mkUnit g v.Range) body | _ -> mvs, body - let isThreadOrContextStatic g attrs = HasFSharpAttributeOpt g g.attrib_ThreadStaticAttribute attrs || HasFSharpAttributeOpt g g.attrib_ContextStaticAttribute attrs @@ -8852,4 +9022,110 @@ let mkUnitDelayLambda (g: TcGlobals) m e = let uv, _ = mkCompGenLocal m "unitVar" g.unit_ty mkLambda m uv (e, tyOfExpr g e) +let (|ValApp|_|) g vref expr = + match expr with + // use 'seq { ... }' as an indicator + | Expr.App (Expr.Val (vref2, _, _), _f0ty, tyargs, args, m) when valRefEq g vref vref2 -> Some (tyargs, args, m) + | _ -> None + +let isStaticClass (g:TcGlobals) (x: EntityRef) = + not x.IsModuleOrNamespace && + x.TyparsNoRange.IsEmpty && + ((x.IsILTycon && + x.ILTyconRawMetadata.IsSealed && + x.ILTyconRawMetadata.IsAbstract) +#if !NO_EXTENSIONTYPING + || (x.IsProvided && + match x.TypeReprInfo with + | TProvidedTypeExtensionPoint info -> info.IsSealed && info.IsAbstract + | _ -> false) +#endif + || (not x.IsILTycon +#if !NO_EXTENSIONTYPING + && not x.IsProvided +#endif + && HasFSharpAttribute g g.attrib_AbstractClassAttribute x.Attribs)) && + not (HasFSharpAttribute g g.attrib_RequireQualifiedAccessAttribute x.Attribs) + +/// Combine a list of ModuleOrNamespaceType's making up the description of a CCU. checking there are now +/// duplicate modules etc. +let CombineCcuContentFragments m l = + + /// Combine module types when multiple namespace fragments contribute to the + /// same namespace, making new module specs as we go. + let rec CombineModuleOrNamespaceTypes path m (mty1: ModuleOrNamespaceType) (mty2: ModuleOrNamespaceType) = + match mty1.ModuleOrNamespaceKind, mty2.ModuleOrNamespaceKind with + | Namespace, Namespace -> + let kind = mty1.ModuleOrNamespaceKind + let tab1 = mty1.AllEntitiesByLogicalMangledName + let tab2 = mty2.AllEntitiesByLogicalMangledName + let entities = + [ for e1 in mty1.AllEntities do + match tab2.TryGetValue e1.LogicalName with + | true, e2 -> yield CombineEntities path e1 e2 + | _ -> yield e1 + for e2 in mty2.AllEntities do + match tab1.TryGetValue e2.LogicalName with + | true, _ -> () + | _ -> yield e2 ] + + let vals = QueueList.append mty1.AllValsAndMembers mty2.AllValsAndMembers + + ModuleOrNamespaceType(kind, vals, QueueList.ofList entities) + + | Namespace, _ | _, Namespace -> + error(Error(FSComp.SR.tastNamespaceAndModuleWithSameNameInAssembly(textOfPath path), m)) + + | _-> + error(Error(FSComp.SR.tastTwoModulesWithSameNameInAssembly(textOfPath path), m)) + + and CombineEntities path (entity1: Entity) (entity2: Entity) = + + match entity1.IsModuleOrNamespace, entity2.IsModuleOrNamespace with + | true, true -> + entity1 |> Construct.NewModifiedTycon (fun data1 -> + let xml = XmlDoc.Merge entity1.XmlDoc entity2.XmlDoc + { data1 with + entity_attribs = entity1.Attribs @ entity2.Attribs + entity_modul_contents = MaybeLazy.Lazy (lazy (CombineModuleOrNamespaceTypes (path@[entity2.DemangledModuleOrNamespaceName]) entity2.Range entity1.ModuleOrNamespaceType entity2.ModuleOrNamespaceType)) + entity_opt_data = + match data1.entity_opt_data with + | Some optData -> Some { optData with entity_xmldoc = xml } + | _ -> Some { Entity.NewEmptyEntityOptData() with entity_xmldoc = xml } }) + | false, false -> + error(Error(FSComp.SR.tastDuplicateTypeDefinitionInAssembly(entity2.LogicalName, textOfPath path), entity2.Range)) + | _, _ -> + error(Error(FSComp.SR.tastConflictingModuleAndTypeDefinitionInAssembly(entity2.LogicalName, textOfPath path), entity2.Range)) + + and CombineModuleOrNamespaceTypeList path m l = + match l with + | h :: t -> List.fold (CombineModuleOrNamespaceTypes path m) h t + | _ -> failwith "CombineModuleOrNamespaceTypeList" + + CombineModuleOrNamespaceTypeList [] m l + +let (|WhileExpr|_|) expr = + match expr with + | Expr.Op (TOp.While (sp1, sp2), _, [Expr.Lambda (_, _, _, [_gv], guardExpr, _, _);Expr.Lambda (_, _, _, [_bv], bodyExpr, _, _)], m) -> + Some (sp1, sp2, guardExpr, bodyExpr, m) + | _ -> None + +let (|TryFinallyExpr|_|) expr = + match expr with + | Expr.Op (TOp.TryFinally (sp1, sp2), [ty], [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [_], e2, _, _)], m) -> + Some (sp1, sp2, ty, e1, e2, m) + | _ -> None + +let (|ForLoopExpr|_|) expr = + match expr with + | Expr.Op (TOp.For (sp1, sp2), _, [Expr.Lambda (_, _, _, [_], e1, _, _);Expr.Lambda (_, _, _, [_], e2, _, _);Expr.Lambda (_, _, _, [v], e3, _, _)], m) -> + Some (sp1, sp2, e1, e2, v, e3, m) + | _ -> None + +let (|TryCatchExpr|_|) expr = + match expr with + | Expr.Op (TOp.TryCatch (spTry, spWith), [resTy], [Expr.Lambda (_, _, _, [_], bodyExpr, _, _); Expr.Lambda (_, _, _, [filterVar], filterExpr, _, _); Expr.Lambda (_, _, _, [handlerVar], handlerExpr, _, _)], m) -> + Some (spTry, spWith, resTy, bodyExpr, filterVar, filterExpr, handlerVar, handlerExpr, m) + | _ -> None +let mkLabelled m l e = mkCompGenSequential m (Expr.Op (TOp.Label l, [], [], m)) e diff --git a/src/fcs-fable/src/fsharp/TastOps.fsi b/src/fcs-fable/src/fsharp/TypedTreeOps.fsi old mode 100755 new mode 100644 similarity index 92% rename from src/fcs-fable/src/fsharp/TastOps.fsi rename to src/fcs-fable/src/fsharp/TypedTreeOps.fsi index 6098625122..dce873e1a8 --- a/src/fcs-fable/src/fsharp/TastOps.fsi +++ b/src/fcs-fable/src/fsharp/TypedTreeOps.fsi @@ -1,24 +1,23 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. /// Defines derived expression manipulation and construction functions. -module internal FSharp.Compiler.Tastops +module internal FSharp.Compiler.TypedTreeOps open System.Collections.Generic + open Internal.Utilities + +open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal -open FSharp.Compiler +open FSharp.Compiler.Layout open FSharp.Compiler.Range open FSharp.Compiler.Rational -open FSharp.Compiler.Ast -open FSharp.Compiler.Tast +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TypedTree open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Layout - -//------------------------------------------------------------------------- -// Type equivalence -//------------------------------------------------------------------------- +open FSharp.Compiler.XmlDoc type Erasure = EraseAll | EraseMeasures | EraseNone @@ -31,7 +30,7 @@ val typeEquiv : TcGlobals -> TType -> TType - /// Check the equivalence of two units-of-measure val measureEquiv : TcGlobals -> Measure -> Measure -> bool -/// Reduce a type to its more anonical form subject to an erasure flag, inference equations and abbreviations +/// Reduce a type to its more canonical form subject to an erasure flag, inference equations and abbreviations val stripTyEqnsWrtErasure: Erasure -> TcGlobals -> TType -> TType /// Build a function type @@ -73,13 +72,13 @@ val (|ExprValWithPossibleTypeInst|_|) : Expr -> (ValRef * ValUseFlag * TType lis type MatchBuilder = /// Create a new builder - new : SequencePointInfoForBinding * range -> MatchBuilder + new : DebugPointForBinding * range -> MatchBuilder /// Add a new destination target member AddTarget : DecisionTreeTarget -> int /// Add a new destination target that is an expression result - member AddResultTarget : Expr * SequencePointInfoForTarget -> DecisionTree + member AddResultTarget : Expr * DebugPointForTarget -> DecisionTree /// Finish the targets member CloseTargets : unit -> DecisionTreeTarget list @@ -91,10 +90,10 @@ type MatchBuilder = val mkBoolSwitch : range -> Expr -> DecisionTree -> DecisionTree -> DecisionTree /// Build a conditional expression -val primMkCond : SequencePointInfoForBinding -> SequencePointInfoForTarget -> SequencePointInfoForTarget -> range -> TType -> Expr -> Expr -> Expr -> Expr +val primMkCond : DebugPointForBinding -> DebugPointForTarget -> DebugPointForTarget -> range -> TType -> Expr -> Expr -> Expr -> Expr /// Build a conditional expression -val mkCond : SequencePointInfoForBinding -> SequencePointInfoForTarget -> range -> TType -> Expr -> Expr -> Expr -> Expr +val mkCond : DebugPointForBinding -> DebugPointForTarget -> range -> TType -> Expr -> Expr -> Expr -> Expr /// Build a conditional expression that checks for non-nullness val mkNonNullCond : TcGlobals -> range -> TType -> Expr -> Expr -> Expr -> Expr @@ -120,7 +119,7 @@ val mkMutableCompGenLocal : range -> string -> TType -> Val * Expr /// Make a new mutable compiler-generated local value, 'let' bind it to an expression /// 'invisibly' (no sequence point etc.), and build an expression to reference it -val mkCompGenLocalAndInvisbleBind : TcGlobals -> string -> range -> Expr -> Val * Expr * Binding +val mkCompGenLocalAndInvisibleBind : TcGlobals -> string -> range -> Expr -> Val * Expr * Binding /// Build a lambda expression taking multiple values val mkMultiLambda : range -> Val list -> Expr * TType -> Expr @@ -153,19 +152,19 @@ val mkMultiLambdas : range -> Typars -> Val list list -> Expr * TType -> Expr val mkMemberLambdas : range -> Typars -> Val option -> Val option -> Val list list -> Expr * TType -> Expr /// Build a 'while' loop expression -val mkWhile : TcGlobals -> SequencePointInfoForWhileLoop * SpecialWhileLoopMarker * Expr * Expr * range -> Expr +val mkWhile : TcGlobals -> DebugPointAtWhile * SpecialWhileLoopMarker * Expr * Expr * range -> Expr /// Build a 'for' loop expression -val mkFor : TcGlobals -> SequencePointInfoForForLoop * Val * Expr * ForLoopStyle * Expr * Expr * range -> Expr +val mkFor : TcGlobals -> DebugPointAtFor * Val * Expr * ForLoopStyle * Expr * Expr * range -> Expr /// Build a 'try/with' expression -val mkTryWith : TcGlobals -> Expr * (* filter val *) Val * (* filter expr *) Expr * (* handler val *) Val * (* handler expr *) Expr * range * TType * SequencePointInfoForTry * SequencePointInfoForWith -> Expr +val mkTryWith : TcGlobals -> Expr * (* filter val *) Val * (* filter expr *) Expr * (* handler val *) Val * (* handler expr *) Expr * range * TType * DebugPointAtTry * DebugPointAtWith -> Expr /// Build a 'try/finally' expression -val mkTryFinally: TcGlobals -> Expr * Expr * range * TType * SequencePointInfoForTry * SequencePointInfoForFinally -> Expr +val mkTryFinally: TcGlobals -> Expr * Expr * range * TType * DebugPointAtTry * DebugPointAtFinally -> Expr /// Build a user-level value binding -val mkBind : SequencePointInfoForBinding -> Val -> Expr -> Binding +val mkBind : DebugPointForBinding -> Val -> Expr -> Binding /// Build a user-level let-binding val mkLetBind : range -> Binding -> Expr -> Expr @@ -177,10 +176,10 @@ val mkLetsBind : range -> Binding list -> Expr -> Expr val mkLetsFromBindings : range -> Bindings -> Expr -> Expr /// Build a user-level let expression -val mkLet : SequencePointInfoForBinding -> range -> Val -> Expr -> Expr -> Expr +val mkLet : DebugPointForBinding -> range -> Val -> Expr -> Expr -> Expr /// Make a binding that binds a function value to a lambda taking multiple arguments -val mkMultiLambdaBind : Val -> SequencePointInfoForBinding -> range -> Typars -> Val list list -> Expr * TType -> Binding +val mkMultiLambdaBind : Val -> DebugPointForBinding -> range -> Typars -> Val list list -> Expr * TType -> Binding // Compiler generated bindings may involve a user variable. // Compiler generated bindings may give rise to a sequence point if they are part of @@ -328,10 +327,6 @@ val mkExnCaseFieldSet : Expr * TyconRef * int * Expr /// Make an expression that gets the address of an element in an array val mkArrayElemAddress : TcGlobals -> readonly: bool * ILReadonly * bool * ILArrayShape * TType * Expr list * range -> Expr -//------------------------------------------------------------------------- -// Compiled view of tuples -//------------------------------------------------------------------------- - /// The largest tuple before we start encoding, i.e. 7 val maxTuple : int @@ -369,6 +364,9 @@ exception DefensiveCopyWarning of string * range type Mutates = AddressOfOp | DefinitelyMutates | PossiblyMutates | NeverMutates +/// Helper to create an expression that dereferences an address. +val mkDerefAddrExpr: mAddrGet: range -> expr: Expr -> mExpr: range -> exprTy: TType -> Expr + /// Helper to take the address of an expression val mkExprAddrOfExprAux : TcGlobals -> bool -> bool -> Mutates -> Expr -> ValRef option -> range -> (Val * Expr) option * Expr * bool * bool @@ -550,10 +548,7 @@ val instTyparConstraints : TyparInst -> TyparConstraint list -> TyparConstraint val instTrait : TyparInst -> TraitConstraintInfo -> TraitConstraintInfo -//------------------------------------------------------------------------- -// From typars to types -//------------------------------------------------------------------------- - +/// From typars to types val generalizeTypars : Typars -> TypeInst val generalizeTyconRef : TyconRef -> TTypes * TType @@ -581,10 +576,6 @@ val stripTyEqnsAndMeasureEqns : TcGlobals -> TType -> TType val tryNormalizeMeasureInType : TcGlobals -> TType -> TType -//------------------------------------------------------------------------- -// -//------------------------------------------------------------------------- - /// See through F# exception abbreviations val stripExnEqns : TyconRef -> Tycon @@ -665,7 +656,7 @@ val destAppTy : TcGlobals -> TType -> TyconRef * TypeInst val tcrefOfAppTy : TcGlobals -> TType -> TyconRef -val tryDestAppTy : TcGlobals -> TType -> ValueOption +val tryTcrefOfAppTy : TcGlobals -> TType -> ValueOption val tryDestTyparTy : TcGlobals -> TType -> ValueOption @@ -928,6 +919,11 @@ module PrettyTypes = val PrettifyTypePair : TcGlobals -> TType * TType -> (TType * TType) * TyparConstraintsWithTypars val PrettifyTypes : TcGlobals -> TTypes -> TTypes * TyparConstraintsWithTypars + + /// same as PrettifyTypes, but allows passing the types along with a discriminant value + /// useful to prettify many types that need to be sorted out after prettifying operation + /// took place. + val PrettifyDiscriminantAndTypePairs : TcGlobals -> ('Discriminant * TType) list -> ('Discriminant * TType) list * TyparConstraintsWithTypars val PrettifyInst : TcGlobals -> TyparInst -> TyparInst * TyparConstraintsWithTypars @@ -1147,7 +1143,7 @@ type SignatureRepackageInfo = { /// The list of corresponding values RepackagedVals: (ValRef * ValRef) list - /// The list of corresponding modules, namespacea and type definitions + /// The list of corresponding modules, namespaces and type definitions RepackagedEntities: (TyconRef * TyconRef) list } /// The empty table @@ -1205,18 +1201,18 @@ val MakeExportRemapping : CcuThunk -> ModuleOrNamespace -> Remap val ApplyExportRemappingToEntity : TcGlobals -> Remap -> ModuleOrNamespace -> ModuleOrNamespace /// Determine if a type definition is hidden by a signature -val IsHiddenTycon : (Remap * SignatureHidingInfo) list -> Tycon -> bool +val IsHiddenTycon: (Remap * SignatureHidingInfo) list -> Tycon -> bool /// Determine if the representation of a type definition is hidden by a signature -val IsHiddenTyconRepr : (Remap * SignatureHidingInfo) list -> Tycon -> bool +val IsHiddenTyconRepr: (Remap * SignatureHidingInfo) list -> Tycon -> bool /// Determine if a member, function or value is hidden by a signature -val IsHiddenVal : (Remap * SignatureHidingInfo) list -> Val -> bool +val IsHiddenVal: (Remap * SignatureHidingInfo) list -> Val -> bool /// Determine if a record field is hidden by a signature -val IsHiddenRecdField : (Remap * SignatureHidingInfo) list -> RecdFieldRef -> bool +val IsHiddenRecdField: (Remap * SignatureHidingInfo) list -> RecdFieldRef -> bool -/// Adjust marks in expressions, replacing all marks by thegiven mark. +/// Adjust marks in expressions, replacing all marks by the given mark. /// Used when inlining. val remarkExpr : range -> Expr -> Expr @@ -1247,7 +1243,7 @@ val mkAddrGet : range -> ValRef -> Expr /// &localv val mkValAddr : range -> readonly: bool -> ValRef -> Expr -/// Build an exression representing the read of an instance class or record field. +/// Build an expression representing the read of an instance class or record field. /// First take the address of the record expression if it is a struct. val mkRecdFieldGet : TcGlobals -> Expr * RecdFieldRef * TypeInst * range -> Expr @@ -1256,10 +1252,10 @@ val accTargetsOfDecisionTree : DecisionTree -> int list -> int list /// Make a 'match' expression applying some peep-hole optimizations along the way, e.g to /// pre-decide the branch taken at compile-time. -val mkAndSimplifyMatch : SequencePointInfoForBinding -> range -> range -> TType -> DecisionTree -> DecisionTreeTarget list -> Expr +val mkAndSimplifyMatch : DebugPointForBinding -> range -> range -> TType -> DecisionTree -> DecisionTreeTarget list -> Expr /// Make a 'match' expression without applying any peep-hole optimizations. -val primMkMatch : SequencePointInfoForBinding * range * DecisionTree * DecisionTreeTarget array * range * TType -> Expr +val primMkMatch : DebugPointForBinding * range * DecisionTree * DecisionTreeTarget array * range * TType -> Expr /// Work out what things on the right-han-side of a 'let rec' recursive binding need to be fixed up val IterateRecursiveFixups : @@ -1277,7 +1273,7 @@ val AdjustArityOfLambdaBody : TcGlobals -> int -> Val list -> Expr -> Val list * /// Make an application expression, doing beta reduction by introducing let-bindings val MakeApplicationAndBetaReduce : TcGlobals -> Expr * TType * TypeInst list * Exprs * range -> Expr -/// COmbine two static-resolution requirements on a type parameter +/// Combine two static-resolution requirements on a type parameter val JoinTyparStaticReq : TyparStaticReq -> TyparStaticReq -> TyparStaticReq /// Layout for internal compiler debugging purposes @@ -1290,7 +1286,7 @@ module DebugPrint = val showType : TType -> string /// Convert an expression to a string for debugging purposes - val showExpr : Expr -> string + val showExpr : TcGlobals -> Expr -> string /// Debug layout for a reference to a value val valRefL : ValRef -> layout @@ -1299,7 +1295,7 @@ module DebugPrint = val unionCaseRefL : UnionCaseRef -> layout /// Debug layout for an value definition at its binding site - val valAtBindL : Val -> layout + val valAtBindL : TcGlobals -> Val -> layout /// Debug layout for an integer val intL : int -> layout @@ -1326,31 +1322,31 @@ module DebugPrint = val slotSigL : SlotSig -> layout /// Debug layout for the type signature of a module or namespace definition - val entityTypeL : ModuleOrNamespaceType -> layout + val entityTypeL : TcGlobals -> ModuleOrNamespaceType -> layout /// Debug layout for a module or namespace definition - val entityL : ModuleOrNamespace -> layout + val entityL : TcGlobals -> ModuleOrNamespace -> layout /// Debug layout for the type of a value val typeOfValL : Val -> layout /// Debug layout for a binding of an expression to a value - val bindingL : Binding -> layout + val bindingL : TcGlobals -> Binding -> layout /// Debug layout for an expression - val exprL : Expr -> layout + val exprL : TcGlobals -> Expr -> layout /// Debug layout for a type definition - val tyconL : Tycon -> layout + val tyconL : TcGlobals -> Tycon -> layout /// Debug layout for a decision tree - val decisionTreeL : DecisionTree -> layout + val decisionTreeL : TcGlobals -> DecisionTree -> layout /// Debug layout for an implementation file - val implFileL : TypedImplFile -> layout + val implFileL : TcGlobals -> TypedImplFile -> layout /// Debug layout for a list of implementation files - val implFilesL : TypedImplFile list -> layout + val implFilesL : TcGlobals -> TypedImplFile list -> layout /// Debug layout for class and record fields val recdFieldRefL : RecdFieldRef -> layout @@ -1388,7 +1384,7 @@ val mkVoidPtrTy : TcGlobals -> TType /// Build a single-dimensional array type val mkArrayType : TcGlobals -> TType -> TType -/// Determine is a type is an option type +/// Determine if a type is an option type val isOptionTy : TcGlobals -> TType -> bool /// Take apart an option type @@ -1397,6 +1393,15 @@ val destOptionTy : TcGlobals -> TType -> TType /// Try to take apart an option type val tryDestOptionTy : TcGlobals -> TType -> ValueOption +/// Determine is a type is a System.Nullable type +val isNullableTy : TcGlobals -> TType -> bool + +/// Try to take apart a System.Nullable type +val tryDestNullableTy: TcGlobals -> TType -> ValueOption + +/// Take apart a System.Nullable type +val destNullableTy: TcGlobals -> TType -> TType + /// Determine if a type is a System.Linq.Expression type val isLinqExpressionTy : TcGlobals -> TType -> bool @@ -1469,10 +1474,10 @@ val destListTy : TcGlobals -> TType -> TType /// Build an array type of the given rank val mkArrayTy : TcGlobals -> int -> TType -> range -> TType -/// Check if a type definition is one of the artifical type definitions used for array types of different ranks +/// Check if a type definition is one of the artificial type definitions used for array types of different ranks val isArrayTyconRef : TcGlobals -> TyconRef -> bool -/// Determine the rank of one of the artifical type definitions used for array types +/// Determine the rank of one of the artificial type definitions used for array types val rankOfArrayTyconRef : TcGlobals -> TyconRef -> int /// Determine if a type is the F# unit type @@ -1626,37 +1631,64 @@ val mkLazyForce : TcGlobals -> range -> TType -> Expr -> Expr val mkRefCellContentsRef : TcGlobals -> RecdFieldRef +/// Check if a type is an FSharpRef type val isRefCellTy : TcGlobals -> TType -> bool +/// Get the element type of an FSharpRef type val destRefCellTy : TcGlobals -> TType -> TType +/// Create the FSharpRef type for a given element type val mkRefCellTy : TcGlobals -> TType -> TType +/// Create the IEnumerable (seq) type for a given element type val mkSeqTy : TcGlobals -> TType -> TType +/// Create the IEnumerator type for a given element type val mkIEnumeratorTy : TcGlobals -> TType -> TType +/// Create the list type for a given element type val mkListTy : TcGlobals -> TType -> TType +/// Create the option type for a given element type val mkOptionTy : TcGlobals -> TType -> TType +/// Create the Nullable type for a given element type +val mkNullableTy: TcGlobals -> TType -> TType + +/// Create the union case 'None' for an option type val mkNoneCase : TcGlobals -> UnionCaseRef -val mkSomeCase : TcGlobals -> UnionCaseRef +/// Create the union case 'Some(expr)' for an option type +val mkSomeCase: TcGlobals -> UnionCaseRef +/// Create the expression '[]' for a list type val mkNil : TcGlobals -> range -> TType -> Expr +/// Create the expression 'headExpr :: tailExpr' val mkCons : TcGlobals -> TType -> Expr -> Expr -> Expr +/// Create the expression 'Some(expr)' +val mkSome : TcGlobals -> TType -> Expr -> range -> Expr + +/// Create the expression 'None' for an option-type +val mkNone: TcGlobals -> TType -> range -> Expr + +/// Create the expression 'expr.Value' for an option-typed expression +val mkOptionGetValueUnprovenViaAddr: TcGlobals -> Expr -> TType -> range -> Expr + +val mkOptionToNullable : TcGlobals -> range -> TType -> Expr -> Expr + +val mkOptionDefaultValue: TcGlobals -> range -> TType -> Expr -> Expr -> Expr + //------------------------------------------------------------------------- // Make a few more expressions //------------------------------------------------------------------------- -val mkSequential : SequencePointInfoForSeq -> range -> Expr -> Expr -> Expr +val mkSequential : DebugPointAtSequential -> range -> Expr -> Expr -> Expr val mkCompGenSequential : range -> Expr -> Expr -> Expr -val mkSequentials : SequencePointInfoForSeq -> TcGlobals -> range -> Exprs -> Expr +val mkSequentials : DebugPointAtSequential -> TcGlobals -> range -> Exprs -> Expr val mkRecordExpr : TcGlobals -> RecordConstructionInfo * TyconRef * TypeInst * RecdFieldRef list * Exprs * range -> Expr @@ -2078,6 +2110,18 @@ val isByrefLikeTy : TcGlobals -> range -> TType -> bool /// Check if the type is a byref-like but not a byref. val isSpanLikeTy : TcGlobals -> range -> TType -> bool +val isSpanTy : TcGlobals -> range -> TType -> bool + +val tryDestSpanTy : TcGlobals -> range -> TType -> struct(TyconRef * TType) voption + +val destSpanTy : TcGlobals -> range -> TType -> struct(TyconRef * TType) + +val isReadOnlySpanTy : TcGlobals -> range -> TType -> bool + +val tryDestReadOnlySpanTy : TcGlobals -> range -> TType -> struct(TyconRef * TType) voption + +val destReadOnlySpanTy : TcGlobals -> range -> TType -> struct(TyconRef * TType) + //------------------------------------------------------------------------- // Tuple constructors/destructors //------------------------------------------------------------------------- @@ -2104,7 +2148,7 @@ val mkMethodTy : TcGlobals -> TType list list -> TType -> TType val mkAnyAnonRecdTy : TcGlobals -> AnonRecdTypeInfo -> TType list -> TType -val mkAnonRecd : TcGlobals -> range -> AnonRecdTypeInfo -> Exprs -> TType list -> Expr +val mkAnonRecd : TcGlobals -> range -> AnonRecdTypeInfo -> Ident[] -> Exprs -> TType list -> Expr val AdjustValForExpectedArity : TcGlobals -> range -> ValRef -> ValUseFlag -> ValReprInfo -> Expr * TType @@ -2152,7 +2196,7 @@ val DecideStaticOptimizations : TcGlobals -> StaticOptimization list -> StaticOp val mkStaticOptimizationExpr : TcGlobals -> StaticOptimization list * Expr * Expr * range -> Expr /// Build for loops -val mkFastForLoop : TcGlobals -> SequencePointInfoForForLoop * range * Val * Expr * bool * Expr * Expr -> Expr +val mkFastForLoop : TcGlobals -> DebugPointAtFor * range * Val * Expr * bool * Expr * Expr -> Expr //--------------------------------------------------------------------------- // Active pattern helpers @@ -2190,7 +2234,7 @@ val RewriteExpr : ExprRewritingEnv -> Expr -> Expr val RewriteImplFile : ExprRewritingEnv -> TypedImplFile -> TypedImplFile -val IsGenericValWithGenericContraints: TcGlobals -> Val -> bool +val IsGenericValWithGenericConstraints: TcGlobals -> Val -> bool type Entity with @@ -2215,6 +2259,8 @@ val (|EnumExpr|_|) : TcGlobals -> Expr -> Expr option val (|TypeOfExpr|_|) : TcGlobals -> Expr -> TType option val (|TypeDefOfExpr|_|) : TcGlobals -> Expr -> TType option +val (|NameOfExpr|_|) : TcGlobals -> Expr -> TType option +val (|SeqExpr|_|) : TcGlobals -> Expr -> unit option val EvalLiteralExprOrAttribArg: TcGlobals -> Expr -> Expr @@ -2257,9 +2303,9 @@ val ValIsExplicitImpl : TcGlobals -> Val -> bool val ValRefIsExplicitImpl : TcGlobals -> ValRef -> bool -val (|LinearMatchExpr|_|) : Expr -> (SequencePointInfoForBinding * range * DecisionTree * DecisionTreeTarget * Expr * SequencePointInfoForTarget * range * TType) option +val (|LinearMatchExpr|_|) : Expr -> (DebugPointForBinding * range * DecisionTree * DecisionTreeTarget * Expr * DebugPointForTarget * range * TType) option -val rebuildLinearMatchExpr : (SequencePointInfoForBinding * range * DecisionTree * DecisionTreeTarget * Expr * SequencePointInfoForTarget * range * TType) -> Expr +val rebuildLinearMatchExpr : (DebugPointForBinding * range * DecisionTree * DecisionTreeTarget * Expr * DebugPointForTarget * range * TType) -> Expr val (|LinearOpExpr|_|) : Expr -> (TOp * TypeInst * Expr list * Expr * range) option @@ -2277,3 +2323,24 @@ val isThreadOrContextStatic: TcGlobals -> Attrib list -> bool val mkUnitDelayLambda: TcGlobals -> range -> Expr -> Expr +/// Match expressions that are an application of a particular F# function value +val (|ValApp|_|) : TcGlobals -> ValRef -> Expr -> (TypeInst * Exprs * range) option + +val isStaticClass: g: TcGlobals -> tcref: TyconRef -> bool + +val CombineCcuContentFragments: range -> ModuleOrNamespaceType list -> ModuleOrNamespaceType + +/// Recognise a while expression +val (|WhileExpr|_|): Expr -> (DebugPointAtWhile * SpecialWhileLoopMarker * Expr * Expr * range) option + +/// Recognise a for-loop expression +val (|ForLoopExpr|_|): Expr -> (DebugPointAtFor * ForLoopStyle * Expr * Expr * Val * Expr * range) option + +/// Recognise a try-catch expression +val (|TryCatchExpr|_|): Expr -> (DebugPointAtTry * DebugPointAtWith * TType * Expr * Val * Expr * Val * Expr * range) option + +/// Recognise a try-finally expression +val (|TryFinallyExpr|_|): Expr -> (DebugPointAtTry * DebugPointAtFinally * TType * Expr * Expr * range) option + +/// Add a label to use as the target for a goto +val mkLabelled: range -> ILCodeLabel -> Expr -> Expr diff --git a/src/fcs-fable/src/fsharp/TastPickle.fs b/src/fcs-fable/src/fsharp/TypedTreePickle.fs old mode 100755 new mode 100644 similarity index 91% rename from src/fcs-fable/src/fsharp/TastPickle.fs rename to src/fcs-fable/src/fsharp/TypedTreePickle.fs index b375d22c82..94691a9fb6 --- a/src/fcs-fable/src/fsharp/TastPickle.fs +++ b/src/fcs-fable/src/fsharp/TypedTreePickle.fs @@ -1,25 +1,30 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -module internal FSharp.Compiler.TastPickle +module internal FSharp.Compiler.TypedTreePickle open System.Collections.Generic open System.Text + open Internal.Utilities + open FSharp.Compiler -open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Diagnostics -open FSharp.Compiler.Tastops +open FSharp.Compiler.CompilerGlobalState +open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Lib open FSharp.Compiler.Lib.Bits open FSharp.Compiler.Range open FSharp.Compiler.Rational -open FSharp.Compiler.Ast -open FSharp.Compiler.Tast +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals -open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.XmlDoc let verbose = false @@ -29,7 +34,6 @@ let ffailwith fileName str = System.Diagnostics.Debug.Assert(false, msg) failwith msg - // Fixup pickled data w.r.t. a set of CCU thunks indexed by name [] type PickledDataWithReferences<'rawData> = @@ -47,18 +51,17 @@ type PickledDataWithReferences<'rawData> = x.FixupThunks |> Array.iter(fun reqd-> match loader reqd.AssemblyName with - | Some(loaded) -> reqd.Fixup(loaded) + | Some loaded -> reqd.Fixup loaded | None -> reqd.FixupOrphaned() ) x.RawData - //--------------------------------------------------------------------------- // Basic pickle/unpickle state //--------------------------------------------------------------------------- [] type Table<'T> = - { name: string; + { name: string tbl: Dictionary<'T, int> mutable rows: ResizeArray<'T> mutable count: int } @@ -68,16 +71,12 @@ type Table<'T> = let n = tbl.count tbl.count <- tbl.count + 1 tbl.tbl.[x] <- n - tbl.rows.Add(x) + tbl.rows.Add x n member tbl.FindOrAdd x = -#if FABLE_COMPILER - let ok, res = tbl.tbl.TryGetValue(x) -#else - let mutable res = Unchecked.defaultof<_> - let ok = tbl.tbl.TryGetValue(x, &res) -#endif - if ok then res else tbl.Add x + match tbl.tbl.TryGetValue x with + | true, res -> res + | _ -> tbl.Add x static member Create n = @@ -126,6 +125,7 @@ type WriterState = onlerefs: Table osimpletys: Table oglobals : TcGlobals + mutable isStructThisArgPos : bool ofile : string /// Indicates if we are using in-memory format, where we store XML docs as well oInMem : bool @@ -170,7 +170,9 @@ let ufailwith st str = ffailwith st.ifile str type 'T pickler = 'T -> WriterState -> unit let p_byte b st = st.os.EmitIntAsByte b + let p_bool b st = p_byte (if b then 1 else 0) st + let prim_p_int32 i st = p_byte (b0 i) st p_byte (b1 i) st @@ -201,65 +203,65 @@ let p_used_space1 f st = // leave more space p_space 1 space st -let p_bytes (s:byte[]) st = +let p_bytes (s: byte[]) st = let len = s.Length - p_int32 (len) st + p_int32 len st st.os.EmitBytes s -let p_prim_string (s:string) st = +let p_prim_string (s: string) st = let bytes = Encoding.UTF8.GetBytes s let len = bytes.Length - p_int32 (len) st + p_int32 len st st.os.EmitBytes bytes let p_int c st = p_int32 c st -let p_int8 (i:sbyte) st = p_int32 (int32 i) st -let p_uint8 (i:byte) st = p_byte (int i) st -let p_int16 (i:int16) st = p_int32 (int32 i) st -let p_uint16 (x:uint16) st = p_int32 (int32 x) st -let p_uint32 (x:uint32) st = p_int32 (int32 x) st -let p_int64 (i:int64) st = +let p_int8 (i: sbyte) st = p_int32 (int32 i) st +let p_uint8 (i: byte) st = p_byte (int i) st +let p_int16 (i: int16) st = p_int32 (int32 i) st +let p_uint16 (x: uint16) st = p_int32 (int32 x) st +let p_uint32 (x: uint32) st = p_int32 (int32 x) st +let p_int64 (i: int64) st = p_int32 (int32 (i &&& 0xFFFFFFFFL)) st p_int32 (int32 (i >>> 32)) st -let p_uint64 (x:uint64) st = p_int64 (int64 x) st +let p_uint64 (x: uint64) st = p_int64 (int64 x) st -let bits_of_float32 (x:float32) = System.BitConverter.ToInt32(System.BitConverter.GetBytes(x), 0) -let bits_of_float (x:float) = System.BitConverter.DoubleToInt64Bits(x) +let bits_of_float32 (x: float32) = System.BitConverter.ToInt32(System.BitConverter.GetBytes x, 0) +let bits_of_float (x: float) = System.BitConverter.DoubleToInt64Bits x let p_single i st = p_int32 (bits_of_float32 i) st let p_double i st = p_int64 (bits_of_float i) st let p_ieee64 i st = p_int64 (bits_of_float i) st let p_char i st = p_uint16 (uint16 (int32 i)) st -let inline p_tup2 p1 p2 (a, b) (st:WriterState) = +let inline p_tup2 p1 p2 (a, b) (st: WriterState) = (p1 a st : unit); (p2 b st : unit) -let inline p_tup3 p1 p2 p3 (a, b, c) (st:WriterState) = +let inline p_tup3 p1 p2 p3 (a, b, c) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit) -let inline p_tup4 p1 p2 p3 p4 (a, b, c, d) (st:WriterState) = +let inline p_tup4 p1 p2 p3 p4 (a, b, c, d) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit) -let inline p_tup5 p1 p2 p3 p4 p5 (a, b, c, d, e) (st:WriterState) = +let inline p_tup5 p1 p2 p3 p4 p5 (a, b, c, d, e) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit); (p5 e st : unit) -let inline p_tup6 p1 p2 p3 p4 p5 p6 (a, b, c, d, e, f) (st:WriterState) = +let inline p_tup6 p1 p2 p3 p4 p5 p6 (a, b, c, d, e, f) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit); (p5 e st : unit); (p6 f st : unit) -let inline p_tup7 p1 p2 p3 p4 p5 p6 p7 (a, b, c, d, e, f, x7) (st:WriterState) = +let inline p_tup7 p1 p2 p3 p4 p5 p6 p7 (a, b, c, d, e, f, x7) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit); (p5 e st : unit); (p6 f st : unit); (p7 x7 st : unit) -let inline p_tup8 p1 p2 p3 p4 p5 p6 p7 p8 (a, b, c, d, e, f, x7, x8) (st:WriterState) = +let inline p_tup8 p1 p2 p3 p4 p5 p6 p7 p8 (a, b, c, d, e, f, x7, x8) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit); (p5 e st : unit); (p6 f st : unit); (p7 x7 st : unit); (p8 x8 st : unit) -let inline p_tup9 p1 p2 p3 p4 p5 p6 p7 p8 p9 (a, b, c, d, e, f, x7, x8, x9) (st:WriterState) = +let inline p_tup9 p1 p2 p3 p4 p5 p6 p7 p8 p9 (a, b, c, d, e, f, x7, x8, x9) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit); (p5 e st : unit); (p6 f st : unit); (p7 x7 st : unit); (p8 x8 st : unit); (p9 x9 st : unit) -let inline p_tup10 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 (a, b, c, d, e, f, x7, x8, x9, x10) (st:WriterState) = +let inline p_tup10 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 (a, b, c, d, e, f, x7, x8, x9, x10) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit); (p5 e st : unit); (p6 f st : unit); (p7 x7 st : unit); (p8 x8 st : unit); (p9 x9 st : unit); (p10 x10 st : unit) -let inline p_tup11 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 (a, b, c, d, e, f, x7, x8, x9, x10, x11) (st:WriterState) = +let inline p_tup11 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 (a, b, c, d, e, f, x7, x8, x9, x10, x11) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit); (p5 e st : unit); (p6 f st : unit); (p7 x7 st : unit); (p8 x8 st : unit); (p9 x9 st : unit); (p10 x10 st : unit); (p11 x11 st : unit) let u_byte st = int (st.is.ReadByte()) @@ -288,10 +290,13 @@ let u_int32 st = assert(b0 = 0xFF) prim_u_int32 st -let u_bytes st = +let u_byte_memory st = let n = (u_int32 st) st.is.ReadBytes n +let u_bytes st = + (u_byte_memory st).ToArray() + let u_prim_string st = let len = (u_int32 st) st.is.ReadUtf8String len @@ -308,8 +313,8 @@ let u_int64 st = b1 ||| (b2 <<< 32) let u_uint64 st = uint64 (u_int64 st) -let float32_of_bits (x:int32) = System.BitConverter.ToSingle(System.BitConverter.GetBytes(x), 0) -let float_of_bits (x:int64) = System.BitConverter.Int64BitsToDouble(x) +let float32_of_bits (x: int32) = System.BitConverter.ToSingle(System.BitConverter.GetBytes x, 0) +let float_of_bits (x: int64) = System.BitConverter.Int64BitsToDouble x let u_single st = float32_of_bits (u_int32 st) let u_double st = float_of_bits (u_int64 st) @@ -336,15 +341,15 @@ let u_used_space1 f st = warning(Error(FSComp.SR.pickleUnexpectedNonZero st.ifile, range0)); None -let inline u_tup2 p1 p2 (st:ReaderState) = let a = p1 st in let b = p2 st in (a, b) +let inline u_tup2 p1 p2 (st: ReaderState) = let a = p1 st in let b = p2 st in (a, b) -let inline u_tup3 p1 p2 p3 (st:ReaderState) = +let inline u_tup3 p1 p2 p3 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in (a, b, c) -let inline u_tup4 p1 p2 p3 p4 (st:ReaderState) = +let inline u_tup4 p1 p2 p3 p4 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in (a, b, c, d) -let inline u_tup5 p1 p2 p3 p4 p5 (st:ReaderState) = +let inline u_tup5 p1 p2 p3 p4 p5 (st: ReaderState) = let a = p1 st let b = p2 st let c = p3 st @@ -352,61 +357,61 @@ let inline u_tup5 p1 p2 p3 p4 p5 (st:ReaderState) = let e = p5 st (a, b, c, d, e) -let inline u_tup6 p1 p2 p3 p4 p5 p6 (st:ReaderState) = +let inline u_tup6 p1 p2 p3 p4 p5 p6 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in (a, b, c, d, e, f) -let inline u_tup7 p1 p2 p3 p4 p5 p6 p7 (st:ReaderState) = +let inline u_tup7 p1 p2 p3 p4 p5 p6 p7 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in (a, b, c, d, e, f, x7) -let inline u_tup8 p1 p2 p3 p4 p5 p6 p7 p8 (st:ReaderState) = +let inline u_tup8 p1 p2 p3 p4 p5 p6 p7 p8 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in (a, b, c, d, e, f, x7, x8) -let inline u_tup9 p1 p2 p3 p4 p5 p6 p7 p8 p9 (st:ReaderState) = +let inline u_tup9 p1 p2 p3 p4 p5 p6 p7 p8 p9 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in (a, b, c, d, e, f, x7, x8, x9) -let inline u_tup10 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 (st:ReaderState) = +let inline u_tup10 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in (a, b, c, d, e, f, x7, x8, x9, x10) -let inline u_tup11 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 (st:ReaderState) = +let inline u_tup11 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in let x11 = p11 st in (a, b, c, d, e, f, x7, x8, x9, x10, x11) -let inline u_tup12 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 (st:ReaderState) = +let inline u_tup12 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in let x11 = p11 st in let x12 = p12 st in (a, b, c, d, e, f, x7, x8, x9, x10, x11, x12) -let inline u_tup13 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 (st:ReaderState) = +let inline u_tup13 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in let x11 = p11 st in let x12 = p12 st in let x13 = p13 st in (a, b, c, d, e, f, x7, x8, x9, x10, x11, x12, x13) -let inline u_tup14 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 (st:ReaderState) = +let inline u_tup14 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in let x11 = p11 st in let x12 = p12 st in let x13 = p13 st in let x14 = p14 st in (a, b, c, d, e, f, x7, x8, x9, x10, x11, x12, x13, x14) -let inline u_tup15 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 (st:ReaderState) = +let inline u_tup15 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in let x11 = p11 st in let x12 = p12 st in let x13 = p13 st in let x14 = p14 st in let x15 = p15 st in (a, b, c, d, e, f, x7, x8, x9, x10, x11, x12, x13, x14, x15) -let inline u_tup16 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 p16 (st:ReaderState) = +let inline u_tup16 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 p16 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in let x11 = p11 st in let x12 = p12 st in let x13 = p13 st in let x14 = p14 st in let x15 = p15 st in let x16 = p16 st in (a, b, c, d, e, f, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16) -let inline u_tup17 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 p16 p17 (st:ReaderState) = +let inline u_tup17 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 p16 p17 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in let x11 = p11 st in let x12 = p12 st in let x13 = p13 st in @@ -421,7 +426,7 @@ let inline u_tup17 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 p16 p17 (s // exception Nope // ctxt is for debugging -let p_osgn_ref (_ctxt:string) (outMap : NodeOutTable<_, _>) x st = +let p_osgn_ref (_ctxt: string) (outMap : NodeOutTable<_, _>) x st = let idx = outMap.Table.FindOrAdd (outMap.NodeStamp x) //if ((idx = 0) && outMap.Name = "oentities") then // let msg = @@ -555,12 +560,12 @@ let p_maybe_lazy p (x: MaybeLazy<_>) st = p_lazy_impl p x.Value st let p_hole () = - let h = ref (None : ('T -> WriterState -> unit) option) - (fun f -> h := Some f), (fun x st -> match !h with Some f -> f x st | None -> pfailwith st "p_hole: unfilled hole") + let mutable h = None + (fun f -> h <- Some f), (fun x st -> match h with Some f -> f x st | None -> pfailwith st "p_hole: unfilled hole") let p_hole2 () = - let h = ref (None : ('Arg -> 'T -> WriterState -> unit) option) - (fun f -> h := Some f), (fun arg x st -> match !h with Some f -> f arg x st | None -> pfailwith st "p_hole2: unfilled hole") + let mutable h = None + (fun f -> h <- Some f), (fun arg x st -> match h with Some f -> f arg x st | None -> pfailwith st "p_hole2: unfilled hole") let u_array_core f n st = let res = Array.zeroCreate n @@ -585,8 +590,7 @@ let u_array_ext extraf f st = extraItem, arr let u_list_core f n st = - [ for _ in 1..n do - yield f st ] + List.init n (fun _ -> f st) let u_list f st = let n = u_int st @@ -639,7 +643,7 @@ let u_option f st = // Boobytrap an OSGN node with a force of a lazy load of a bunch of pickled data #if LAZY_UNPICKLE -let wire (x:osgn<_>) (res:Lazy<_>) = +let wire (x: osgn<_>) (res: Lazy<_>) = x.osgnTripWire <- Some(fun () -> res.Force() |> ignore) #endif @@ -666,9 +670,9 @@ let u_lazy u st = lazy (let st = { st with is = st.is.CloneAndSeek idx1 } u st) /// Force the reading of the data as a "tripwire" for each of the OSGN thunks - for i = otyconsIdx1 to otyconsIdx2-1 do wire (st.ientities.Get(i)) res done - for i = ovalsIdx1 to ovalsIdx2-1 do wire (st.ivals.Get(i)) res done - for i = otyparsIdx1 to otyparsIdx2-1 do wire (st.itypars.Get(i)) res done + for i = otyconsIdx1 to otyconsIdx2-1 do wire (st.ientities.Get i) res done + for i = ovalsIdx1 to ovalsIdx2-1 do wire (st.ivals.Get i) res done + for i = otyparsIdx1 to otyparsIdx2-1 do wire (st.itypars.Get i) res done res #else ignore (len, otyconsIdx1, otyconsIdx2, otyparsIdx1, otyparsIdx2, ovalsIdx1, ovalsIdx2) @@ -677,8 +681,8 @@ let u_lazy u st = let u_hole () = - let h = ref (None : 'T unpickler option) - (fun f -> h := Some f), (fun st -> match !h with Some f -> f st | None -> ufailwith st "u_hole: unfilled hole") + let mutable h = None + (fun f -> h <- Some f), (fun st -> match h with Some f -> f st | None -> ufailwith st "u_hole: unfilled hole") //--------------------------------------------------------------------------- // Pickle/unpickle F# interface data @@ -702,7 +706,7 @@ let p_ints = p_list p_int // CCU References // A huge number of these occur in pickled F# data, so make them unique -let encode_ccuref ccuTab (x:CcuThunk) = encode_uniq ccuTab x.AssemblyName +let encode_ccuref ccuTab (x: CcuThunk) = encode_uniq ccuTab x.AssemblyName let decode_ccuref x = x let lookup_ccuref st ccuTab x = lookup_uniq st ccuTab x let u_encoded_ccuref st = @@ -724,7 +728,7 @@ let lookup_pubpath st pubpathTab x = lookup_uniq st pubpathTab x let u_encoded_pubpath = u_array u_int let u_pubpath st = lookup_uniq st st.ipubpaths (u_int st) -let encode_pubpath stringTab pubpathTab (PubPath(a)) = encode_uniq pubpathTab (Array.map (encode_string stringTab) a) +let encode_pubpath stringTab pubpathTab (PubPath a) = encode_uniq pubpathTab (Array.map (encode_string stringTab) a) let p_encoded_pubpath = p_array p_int let p_pubpath x st = p_int (encode_pubpath st.ostrings st.opubpaths x) st @@ -772,17 +776,18 @@ let pickleObjWithDanglingCcus inMem file g scope p x = { os = ByteBuffer.Create 100000 oscope=scope occus= Table<_>.Create "occus" - oentities=NodeOutTable<_, _>.Create((fun (tc:Tycon) -> tc.Stamp), (fun tc -> tc.LogicalName), (fun tc -> tc.Range), (fun osgn -> osgn), "otycons") - otypars=NodeOutTable<_, _>.Create((fun (tp:Typar) -> tp.Stamp), (fun tp -> tp.DisplayName), (fun tp -> tp.Range), (fun osgn -> osgn), "otypars") - ovals=NodeOutTable<_, _>.Create((fun (v:Val) -> v.Stamp), (fun v -> v.LogicalName), (fun v -> v.Range), (fun osgn -> osgn), "ovals") - oanoninfos=NodeOutTable<_, _>.Create((fun (v:AnonRecdTypeInfo) -> v.Stamp), (fun v -> string v.Stamp), (fun _ -> range0), id, "oanoninfos") + oentities=NodeOutTable<_, _>.Create((fun (tc: Tycon) -> tc.Stamp), (fun tc -> tc.LogicalName), (fun tc -> tc.Range), (fun osgn -> osgn), "otycons") + otypars=NodeOutTable<_, _>.Create((fun (tp: Typar) -> tp.Stamp), (fun tp -> tp.DisplayName), (fun tp -> tp.Range), (fun osgn -> osgn), "otypars") + ovals=NodeOutTable<_, _>.Create((fun (v: Val) -> v.Stamp), (fun v -> v.LogicalName), (fun v -> v.Range), (fun osgn -> osgn), "ovals") + oanoninfos=NodeOutTable<_, _>.Create((fun (v: AnonRecdTypeInfo) -> v.Stamp), (fun v -> string v.Stamp), (fun _ -> range0), id, "oanoninfos") ostrings=Table<_>.Create "ostrings" onlerefs=Table<_>.Create "onlerefs" opubpaths=Table<_>.Create "opubpaths" osimpletys=Table<_>.Create "osimpletys" oglobals=g ofile=file - oInMem=inMem } + oInMem=inMem + isStructThisArgPos = false} p x st1 let sizes = st1.oentities.Size, @@ -796,17 +801,18 @@ let pickleObjWithDanglingCcus inMem file g scope p x = { os = ByteBuffer.Create 100000 oscope=scope occus= Table<_>.Create "occus (fake)" - oentities=NodeOutTable<_, _>.Create((fun (tc:Tycon) -> tc.Stamp), (fun tc -> tc.LogicalName), (fun tc -> tc.Range), (fun osgn -> osgn), "otycons") - otypars=NodeOutTable<_, _>.Create((fun (tp:Typar) -> tp.Stamp), (fun tp -> tp.DisplayName), (fun tp -> tp.Range), (fun osgn -> osgn), "otypars") - ovals=NodeOutTable<_, _>.Create((fun (v:Val) -> v.Stamp), (fun v -> v.LogicalName), (fun v -> v.Range), (fun osgn -> osgn), "ovals") - oanoninfos=NodeOutTable<_, _>.Create((fun (v:AnonRecdTypeInfo) -> v.Stamp), (fun v -> string v.Stamp), (fun _ -> range0), id, "oanoninfos") + oentities=NodeOutTable<_, _>.Create((fun (tc: Tycon) -> tc.Stamp), (fun tc -> tc.LogicalName), (fun tc -> tc.Range), (fun osgn -> osgn), "otycons") + otypars=NodeOutTable<_, _>.Create((fun (tp: Typar) -> tp.Stamp), (fun tp -> tp.DisplayName), (fun tp -> tp.Range), (fun osgn -> osgn), "otypars") + ovals=NodeOutTable<_, _>.Create((fun (v: Val) -> v.Stamp), (fun v -> v.LogicalName), (fun v -> v.Range), (fun osgn -> osgn), "ovals") + oanoninfos=NodeOutTable<_, _>.Create((fun (v: AnonRecdTypeInfo) -> v.Stamp), (fun v -> string v.Stamp), (fun _ -> range0), id, "oanoninfos") ostrings=Table<_>.Create "ostrings (fake)" opubpaths=Table<_>.Create "opubpaths (fake)" onlerefs=Table<_>.Create "onlerefs (fake)" osimpletys=Table<_>.Create "osimpletys (fake)" oglobals=g ofile=file - oInMem=inMem } + oInMem=inMem + isStructThisArgPos = false } p_array p_encoded_ccuref ccuNameTab.AsArray st2 // Add a 4th integer indicated by a negative 1st integer let z1 = if nanoninfos > 0 then -ntycons-1 else ntycons @@ -825,7 +831,7 @@ let pickleObjWithDanglingCcus inMem file g scope p x = st2.os.Close() phase2bytes -let check (ilscope:ILScopeRef) (inMap : NodeInTable<_, _>) = +let check (ilscope: ILScopeRef) (inMap : NodeInTable<_, _>) = for i = 0 to inMap.Count - 1 do let n = inMap.Get i if not (inMap.IsLinked n) then @@ -835,7 +841,7 @@ let check (ilscope:ILScopeRef) (inMap : NodeInTable<_, _>) = // an identical copy of the source for the DLL containing the data being unpickled. A message will // then be printed indicating the name of the item. -let unpickleObjWithDanglingCcus file ilscope (iILModule:ILModuleDef option) u (phase2bytes:byte[]) = +let unpickleObjWithDanglingCcus file ilscope (iILModule: ILModuleDef option) u (phase2bytes: ReadOnlyByteMemory) = let st2 = { is = ByteStream.FromBytes (phase2bytes, 0, phase2bytes.Length) iilscope= ilscope @@ -861,7 +867,7 @@ let unpickleObjWithDanglingCcus file ilscope (iILModule:ILModuleDef option) u (p (u_array u_encoded_pubpath) (u_array u_encoded_nleref) (u_array u_encoded_simpletyp) - u_bytes + u_byte_memory st2 let ccuTab = new_itbl "iccus" (Array.map (CcuThunk.CreateDelayed) ccuNameTab) let stringTab = new_itbl "istrings" (Array.map decode_string stringTab) @@ -907,21 +913,23 @@ let p_ILPublicKey x st = | PublicKey b -> p_byte 0 st; p_bytes b st | PublicKeyToken b -> p_byte 1 st; p_bytes b st -let p_ILVersion x st = p_tup4 p_uint16 p_uint16 p_uint16 p_uint16 x st +let p_ILVersion (x: ILVersionInfo) st = p_tup4 p_uint16 p_uint16 p_uint16 p_uint16 (x.Major, x.Minor, x.Build, x.Revision) st -let p_ILModuleRef (x:ILModuleRef) st = +let p_ILModuleRef (x: ILModuleRef) st = p_tup3 p_string p_bool (p_option p_bytes) (x.Name, x.HasMetadata, x.Hash) st -let p_ILAssemblyRef (x:ILAssemblyRef) st = +let p_ILAssemblyRef (x: ILAssemblyRef) st = p_byte 0 st // leave a dummy tag to make room for future encodings of assembly refs p_tup6 p_string (p_option p_bytes) (p_option p_ILPublicKey) p_bool (p_option p_ILVersion) (p_option p_string) ( x.Name, x.Hash, x.PublicKey, x.Retargetable, x.Version, x.Locale) st let p_ILScopeRef x st = match x with - | ILScopeRef.Local -> p_byte 0 st - | ILScopeRef.Module mref -> p_byte 1 st; p_ILModuleRef mref st - | ILScopeRef.Assembly aref -> p_byte 2 st; p_ILAssemblyRef aref st + | ILScopeRef.Local -> p_byte 0 st + | ILScopeRef.Module mref -> p_byte 1 st; p_ILModuleRef mref st + | ILScopeRef.Assembly aref -> p_byte 2 st; p_ILAssemblyRef aref st + // Encode primary assembly as a normal assembly ref + | ILScopeRef.PrimaryAssembly -> p_byte 2 st; p_ILAssemblyRef st.oglobals.ilg.primaryAssemblyRef st let u_ILPublicKey st = let tag = u_byte st @@ -930,7 +938,9 @@ let u_ILPublicKey st = | 1 -> u_bytes st |> PublicKeyToken | _ -> ufailwith st "u_ILPublicKey" -let u_ILVersion st = u_tup4 u_uint16 u_uint16 u_uint16 u_uint16 st +let u_ILVersion st = + let (major, minor, build, revision) = u_tup4 u_uint16 u_uint16 u_uint16 u_uint16 st + ILVersionInfo(major, minor, build, revision) let u_ILModuleRef st = let (a, b, c) = u_tup3 u_string u_bool (u_option u_bytes) st @@ -993,9 +1003,9 @@ and p_ILCallConv (Callconv(x, y)) st = p_tup2 p_ILHasThis p_ILBasicCallConv (x, and p_ILCallSig x st = p_tup3 p_ILCallConv p_ILTypes p_ILType (x.CallingConv, x.ArgTypes, x.ReturnType) st -and p_ILTypeRef (x:ILTypeRef) st = p_tup3 p_ILScopeRef p_strings p_string (x.Scope, x.Enclosing, x.Name) st +and p_ILTypeRef (x: ILTypeRef) st = p_tup3 p_ILScopeRef p_strings p_string (x.Scope, x.Enclosing, x.Name) st -and p_ILTypeSpec (a:ILTypeSpec) st = p_tup2 p_ILTypeRef p_ILTypes (a.TypeRef, a.GenericArgs) st +and p_ILTypeSpec (a: ILTypeSpec) st = p_tup2 p_ILTypeRef p_ILTypes (a.TypeRef, a.GenericArgs) st let u_ILBasicCallConv st = match u_byte st with @@ -1305,16 +1315,32 @@ let u_ILInstr st = // Pickle/unpickle for F# types and module signatures //--------------------------------------------------------------------------- -let p_Map pk pv = p_wrap Map.toList (p_list (p_tup2 pk pv)) +let p_Map_core pk pv xs st = + xs |> Map.iter (fun k v -> pk k st; pv v st) + +let p_Map pk pv x st = + p_int (Map.count x) st + p_Map_core pk pv x st + let p_qlist pv = p_wrap QueueList.toList (p_list pv) let p_namemap p = p_Map p_string p -let u_Map uk uv = u_wrap Map.ofList (u_list (u_tup2 uk uv)) +let u_Map_core uk uv n st = + Map.ofSeq (seq { for _ in 1..n -> (uk st, uv st) }) + +let u_Map uk uv st = + let n = u_int st + u_Map_core uk uv n st + let u_qlist uv = u_wrap QueueList.ofList (u_list uv) let u_namemap u = u_Map u_string u let p_pos (x: pos) st = p_tup2 p_int p_int (x.Line, x.Column) st -let p_range (x: range) st = p_tup3 p_string p_pos p_pos (x.FileName, x.Start, x.End) st + +let p_range (x: range) st = + let fileName = PathMap.apply st.oglobals.pathMap x.FileName + p_tup3 p_string p_pos p_pos (fileName, x.Start, x.End) st + let p_dummy_range : range pickler = fun _x _st -> () let p_ident (x: Ident) st = p_tup2 p_string p_range (x.idText, x.idRange) st let p_xmldoc (XmlDoc x) st = p_array p_string x st @@ -1327,16 +1353,15 @@ let u_dummy_range : range unpickler = fun _st -> range0 let u_ident st = let a = u_string st in let b = u_range st in ident(a, b) let u_xmldoc st = XmlDoc (u_array u_string st) - let p_local_item_ref ctxt tab st = p_osgn_ref ctxt tab st -let p_tcref ctxt (x:EntityRef) st = +let p_tcref ctxt (x: EntityRef) st = match x with | ERefLocal x -> p_byte 0 st; p_local_item_ref ctxt st.oentities x st | ERefNonLocal x -> p_byte 1 st; p_nleref x st -let p_ucref (UCRef(a, b)) st = p_tup2 (p_tcref "ucref") p_string (a, b) st -let p_rfref (RFRef(a, b)) st = p_tup2 (p_tcref "rfref") p_string (a, b) st +let p_ucref (UnionCaseRef(a, b)) st = p_tup2 (p_tcref "ucref") p_string (a, b) st +let p_rfref (RecdFieldRef(a, b)) st = p_tup2 (p_tcref "rfref") p_string (a, b) st let p_tpref x st = p_local_item_ref "typar" st.otypars x st let u_local_item_ref tab st = u_osgn_ref tab st @@ -1348,9 +1373,9 @@ let u_tcref st = | 1 -> u_nleref st |> ERefNonLocal | _ -> ufailwith st "u_item_ref" -let u_ucref st = let a, b = u_tup2 u_tcref u_string st in UCRef(a, b) +let u_ucref st = let a, b = u_tup2 u_tcref u_string st in UnionCaseRef(a, b) -let u_rfref st = let a, b = u_tup2 u_tcref u_string st in RFRef(a, b) +let u_rfref st = let a, b = u_tup2 u_tcref u_string st in RecdFieldRef(a, b) let u_tpref st = u_local_item_ref st.itypars st @@ -1363,13 +1388,13 @@ let p_tys = (p_list p_ty) let fill_p_attribs, p_attribs = p_hole() // In F# 4.5, the type of the "this" pointer for structs is considered to be inref for the purposes of checking the implementation -// of the struct. However for backwards compat reaons we can't serialize this as the type. +// of the struct. However for backwards compat reasons we can't serialize this as the type. let checkForInRefStructThisArg st ty = let g = st.oglobals let _, tauTy = tryDestForallTy g ty isFunTy g tauTy && isFunTy g (rangeOfFunTy g tauTy) && isInByrefTy g (domainOfFunTy g tauTy) -let p_nonlocal_val_ref (nlv:NonLocalValOrMemberRef) st = +let p_nonlocal_val_ref (nlv: NonLocalValOrMemberRef) st = let a = nlv.EnclosingEntity let key = nlv.ItemKey let pkey = key.PartialKey @@ -1629,7 +1654,7 @@ let u_tyar_constraint st = let u_tyar_constraints = (u_list_revi u_tyar_constraint) -let p_tyar_spec_data (x:Typar) st = +let p_tyar_spec_data (x: Typar) st = p_tup5 p_ident p_attribs @@ -1638,7 +1663,7 @@ let p_tyar_spec_data (x:Typar) st = p_xmldoc (x.typar_id, x.Attribs, int64 x.typar_flags.PickledBits, x.Constraints, x.XmlDoc) st -let p_tyar_spec (x:Typar) st = +let p_tyar_spec (x: Typar) st = //Disabled, workaround for bug 2721: if x.Rigidity <> TyparRigidity.Rigid then warning(Error(sprintf "p_tyar_spec: typar#%d is not rigid" x.Stamp, x.Range)) if x.IsFromError then warning(Error((0, "p_tyar_spec: from error"), x.Range)) p_osgn_decl st.otypars p_tyar_spec_data x st @@ -1728,7 +1753,7 @@ let fill_u_Exprs, u_Exprs = u_hole() let fill_u_constraints, u_constraints = u_hole() let fill_u_Vals, u_Vals = u_hole() -let p_ArgReprInfo (x:ArgReprInfo) st = +let p_ArgReprInfo (x: ArgReprInfo) st = p_attribs x.Attribs st p_option p_ident x.Name st @@ -1851,7 +1876,7 @@ and p_recdfield_spec x st = and p_rfield_table x st = p_array p_recdfield_spec (x.FieldsByIndex) st -and p_entity_spec_data (x:Entity) st = +and p_entity_spec_data (x: Entity) st = p_tyar_specs (x.entity_typars.Force(x.entity_range)) st p_string x.entity_logical_name st p_option p_string x.EntityCompiledName st @@ -1924,7 +1949,7 @@ and p_attrib_expr (AttribExpr(e1, e2)) st = and p_attrib_arg (AttribNamedArg(a, b, c, d)) st = p_tup4 p_string p_ty p_bool p_attrib_expr (a, b, c, d) st -and p_member_info (x:ValMemberInfo) st = +and p_member_info (x: ValMemberInfo) st = p_tup4 (p_tcref "member_info") p_MemberFlags (p_list p_slotsig) p_bool (x.ApparentEnclosingEntity, x.MemberFlags, x.ImplementedSlotSigs, x.IsImplemented) st @@ -2003,7 +2028,7 @@ and u_tycon_repr st = (fun _flagBit -> TRecdRepr v) | 1 -> let v = u_list u_unioncase_spec st - (fun _flagBit -> MakeUnionRepr v) + (fun _flagBit -> Construct.MakeUnionRepr v) | 2 -> let v = u_ILType st // This is the F# 3.0 extension to the format used for F# provider-generated types, which record an ILTypeRef in the format @@ -2016,11 +2041,12 @@ and u_tycon_repr st = | None -> TNoRepr | Some iILModule -> try - let rec find acc enclosingTypeNames (tdefs:ILTypeDefs) = + let rec find acc enclosingTypeNames (tdefs: ILTypeDefs) = match enclosingTypeNames with | [] -> List.rev acc, tdefs.FindByName iltref.Name - | h::t -> let nestedTypeDef = tdefs.FindByName h - find (tdefs.FindByName h :: acc) t nestedTypeDef.NestedTypes + | h :: t -> + let nestedTypeDef = tdefs.FindByName h + find (tdefs.FindByName h :: acc) t nestedTypeDef.NestedTypes let nestedILTypeDefs, ilTypeDef = find [] iltref.Enclosing iILModule.TypeDefs TILObjectRepr(TILObjectReprData(st.iilscope, nestedILTypeDefs, ilTypeDef)) with _ -> @@ -2045,6 +2071,7 @@ and u_attribs_ext extraf st = u_list_ext extraf u_attrib st and u_unioncase_spec st = let a = u_rfield_table st let b = u_ty st + // The union case compiled name is now computed from Id field when needed and is not stored in UnionCase record. let _c = u_string st let d = u_ident st @@ -2107,7 +2134,7 @@ and u_recdfield_spec st = rfield_name_generated = false rfield_other_range = None } -and u_rfield_table st = MakeRecdFieldsTable (u_list u_recdfield_spec st) +and u_rfield_table st = Construct.MakeRecdFieldsTable (u_list u_recdfield_spec st) and u_entity_spec_data st : Entity = let x1, x2a, x2b, x2c, x3, (x4a, x4b), x6, x7f, x8, x9, _x10, x10b, x11, x12, x13, x14, x15 = @@ -2142,7 +2169,7 @@ and u_entity_spec_data st : Entity = entity_attribs=x6 entity_tycon_repr=x7 entity_tycon_tcaug=x9 - entity_flags=EntityFlags(x11) + entity_flags=EntityFlags x11 entity_cpath=x12 entity_modul_contents=MaybeLazy.Lazy x13 entity_il_repr_cache=newCache() @@ -2156,7 +2183,7 @@ and u_entity_spec_data st : Entity = entity_xmldoc= defaultArg x15 XmlDoc.Empty entity_xmldocsig = System.String.Empty entity_tycon_abbrev = x8 - entity_accessiblity = x4a + entity_accessibility = x4a entity_tycon_repr_accessibility = x4b entity_exn_info = x14 } } @@ -2281,7 +2308,7 @@ and u_ValData st = val_range = (match x1a with None -> range0 | Some(a, _) -> a) val_type = x2 val_stamp = newStamp() - val_flags = ValFlags(x4) + val_flags = ValFlags x4 val_opt_data = match x1z, x1a, x10, x14, x13, x15, x8, x13b, x12, x9 with | None, None, None, None, TAccess [], None, None, ParentNone, "", [] -> None @@ -2334,7 +2361,7 @@ and p_const x st = | Const.String s -> p_byte 14 st; p_string s st | Const.Unit -> p_byte 15 st | Const.Zero -> p_byte 16 st - | Const.Decimal s -> p_byte 17 st; p_array p_int32 (System.Decimal.GetBits(s)) st + | Const.Decimal s -> p_byte 17 st; p_array p_int32 (System.Decimal.GetBits s) st and u_const st = let tag = u_byte st @@ -2356,7 +2383,7 @@ and u_const st = | 14 -> u_string st |> Const.String | 15 -> Const.Unit | 16 -> Const.Zero - | 17 -> u_array u_int32 st |> (fun bits -> Const.Decimal (new System.Decimal(bits))) + | 17 -> u_array u_int32 st |> (fun bits -> Const.Decimal (System.Decimal bits)) | _ -> ufailwith st "u_const" @@ -2375,7 +2402,8 @@ and p_dtree_discrim x st = | DecisionTreeTest.IsNull -> p_byte 2 st | DecisionTreeTest.IsInst (srcty, tgty) -> p_byte 3 st; p_ty srcty st; p_ty tgty st | DecisionTreeTest.ArrayLength (n, ty) -> p_byte 4 st; p_tup2 p_int p_ty (n, ty) st - | DecisionTreeTest.ActivePatternCase _ -> pfailwith st "DecisionTreeTest.ActivePatternCase: only used during pattern match compilation" + | DecisionTreeTest.ActivePatternCase _ -> pfailwith st "DecisionTreeTest.ActivePatternCase: only used during pattern match compilation" + | DecisionTreeTest.Error _ -> pfailwith st "DecisionTreeTest.Error: only used during pattern match compilation" and p_target (TTarget(a, b, _)) st = p_tup2 p_Vals p_expr (a, b) st and p_bind (TBind(a, b, _)) st = p_tup2 p_Val p_expr (a, b) st @@ -2408,9 +2436,9 @@ and u_dtree_discrim st = | 4 -> u_tup2 u_int u_ty st |> DecisionTreeTest.ArrayLength | _ -> ufailwith st "u_dtree_discrim" -and u_target st = let a, b = u_tup2 u_Vals u_expr st in (TTarget(a, b, SuppressSequencePointAtTarget)) +and u_target st = let a, b = u_tup2 u_Vals u_expr st in (TTarget(a, b, DebugPointForTarget.No)) -and u_bind st = let a = u_Val st in let b = u_expr st in TBind(a, b, NoSequencePointAtStickyBinding) +and u_bind st = let a = u_Val st in let b = u_expr st in TBind(a, b, NoDebugPointAtStickyBinding) and u_lval_op_kind st = match u_byte st with @@ -2431,9 +2459,9 @@ and p_op x st = else p_byte 2 st | TOp.Recd (a, b) -> p_byte 3 st; p_tup2 p_recdInfo (p_tcref "recd op") (a, b) st - | TOp.ValFieldSet (a) -> p_byte 4 st; p_rfref a st - | TOp.ValFieldGet (a) -> p_byte 5 st; p_rfref a st - | TOp.UnionCaseTagGet (a) -> p_byte 6 st; p_tcref "cnstr op" a st + | TOp.ValFieldSet a -> p_byte 4 st; p_rfref a st + | TOp.ValFieldGet a -> p_byte 5 st; p_rfref a st + | TOp.UnionCaseTagGet a -> p_byte 6 st; p_tcref "cnstr op" a st | TOp.UnionCaseFieldGet (a, b) -> p_byte 7 st; p_tup2 p_ucref p_int (a, b) st | TOp.UnionCaseFieldSet (a, b) -> p_byte 8 st; p_tup2 p_ucref p_int (a, b) st | TOp.ExnFieldGet (a, b) -> p_byte 9 st; p_tup2 (p_tcref "exn op") p_int (a, b) st @@ -2445,15 +2473,15 @@ and p_op x st = p_byte 11 st; p_int a st | TOp.ILAsm (a, b) -> p_byte 12 st; p_tup2 (p_list p_ILInstr) p_tys (a, b) st | TOp.RefAddrGet _ -> p_byte 13 st - | TOp.UnionCaseProof (a) -> p_byte 14 st; p_ucref a st + | TOp.UnionCaseProof a -> p_byte 14 st; p_ucref a st | TOp.Coerce -> p_byte 15 st - | TOp.TraitCall (b) -> p_byte 16 st; p_trait b st + | TOp.TraitCall b -> p_byte 16 st; p_trait b st | TOp.LValueOp (a, b) -> p_byte 17 st; p_tup2 p_lval_op_kind (p_vref "lval") (a, b) st | TOp.ILCall (a1, a2, a3, a4, a5, a7, a8, a9, b, c, d) -> p_byte 18 st; p_tup11 p_bool p_bool p_bool p_bool p_vrefFlags p_bool p_bool p_ILMethodRef p_tys p_tys p_tys (a1, a2, a3, a4, a5, a7, a8, a9, b, c, d) st | TOp.Array -> p_byte 19 st | TOp.While _ -> p_byte 20 st - | TOp.For(_, dir) -> p_byte 21 st; p_int (match dir with FSharpForLoopUp -> 0 | CSharpForLoopUp -> 1 | FSharpForLoopDown -> 2) st + | TOp.For (_, dir) -> p_byte 21 st; p_int (match dir with FSharpForLoopUp -> 0 | CSharpForLoopUp -> 1 | FSharpForLoopDown -> 2) st | TOp.Bytes bytes -> p_byte 22 st; p_bytes bytes st | TOp.TryCatch _ -> p_byte 23 st | TOp.TryFinally _ -> p_byte 24 st @@ -2517,12 +2545,12 @@ and u_op st = let d = u_tys st TOp.ILCall (a1, a2, a3, a4, a5, a7, a8, a9, b, c, d) | 19 -> TOp.Array - | 20 -> TOp.While (NoSequencePointAtWhileLoop, NoSpecialWhileLoopMarker) + | 20 -> TOp.While (DebugPointAtWhile.No, NoSpecialWhileLoopMarker) | 21 -> let dir = match u_int st with 0 -> FSharpForLoopUp | 1 -> CSharpForLoopUp | 2 -> FSharpForLoopDown | _ -> failwith "unknown for loop" - TOp.For (NoSequencePointAtForLoop, dir) + TOp.For (DebugPointAtFor.No, dir) | 22 -> TOp.Bytes (u_bytes st) - | 23 -> TOp.TryCatch(NoSequencePointAtTry, NoSequencePointAtWith) - | 24 -> TOp.TryFinally(NoSequencePointAtTry, NoSequencePointAtFinally) + | 23 -> TOp.TryCatch (DebugPointAtTry.No, DebugPointAtWith.No) + | 24 -> TOp.TryFinally (DebugPointAtTry.No, DebugPointAtFinally.No) | 25 -> let a = u_rfref st TOp.ValFieldGetAddr (a, false) | 26 -> TOp.UInt16s (u_array u_uint16 st) @@ -2534,7 +2562,7 @@ and u_op st = | 30 -> let a = u_int st TOp.TupleFieldGet (tupInfoStruct, a) | 31 -> let info = u_anonInfo st - TOp.AnonRecd (info) + TOp.AnonRecd info | 32 -> let info = u_anonInfo st let n = u_int st TOp.AnonRecdGet (info, n) @@ -2545,7 +2573,7 @@ and p_expr expr st = | Expr.Link e -> p_expr !e st | Expr.Const (x, m, ty) -> p_byte 0 st; p_tup3 p_const p_dummy_range p_ty (x, m, ty) st | Expr.Val (a, b, m) -> p_byte 1 st; p_tup3 (p_vref "val") p_vrefFlags p_dummy_range (a, b, m) st - | Expr.Op(a, b, c, d) -> p_byte 2 st; p_tup4 p_op p_tys p_Exprs p_dummy_range (a, b, c, d) st + | Expr.Op (a, b, c, d) -> p_byte 2 st; p_tup4 p_op p_tys p_Exprs p_dummy_range (a, b, c, d) st | Expr.Sequential (a, b, c, _, d) -> p_byte 3 st; p_tup4 p_expr p_expr p_int p_dummy_range (a, b, (match c with NormalSeq -> 0 | ThenDoSeq -> 1), d) st | Expr.Lambda (_, a1, b0, b1, c, d, e) -> p_byte 4 st; p_tup6 (p_option p_Val) (p_option p_Val) p_Vals p_expr p_dummy_range p_ty (a1, b0, b1, c, d, e) st | Expr.TyLambda (_, b, c, d, e) -> p_byte 5 st; p_tup4 p_tyar_specs p_expr p_dummy_range p_ty (b, c, d, e) st @@ -2553,10 +2581,10 @@ and p_expr expr st = | Expr.LetRec (a, b, c, _) -> p_byte 7 st; p_tup3 p_binds p_expr p_dummy_range (a, b, c) st | Expr.Let (a, b, c, _) -> p_byte 8 st; p_tup3 p_bind p_expr p_dummy_range (a, b, c) st | Expr.Match (_, a, b, c, d, e) -> p_byte 9 st; p_tup5 p_dummy_range p_dtree p_targets p_dummy_range p_ty (a, b, c, d, e) st - | Expr.Obj(_, b, c, d, e, f, g) -> p_byte 10 st; p_tup6 p_ty (p_option p_Val) p_expr p_methods p_intfs p_dummy_range (b, c, d, e, f, g) st - | Expr.StaticOptimization(a, b, c, d) -> p_byte 11 st; p_tup4 p_constraints p_expr p_expr p_dummy_range (a, b, c, d) st + | Expr.Obj (_, b, c, d, e, f, g) -> p_byte 10 st; p_tup6 p_ty (p_option p_Val) p_expr p_methods p_intfs p_dummy_range (b, c, d, e, f, g) st + | Expr.StaticOptimization (a, b, c, d) -> p_byte 11 st; p_tup4 p_constraints p_expr p_expr p_dummy_range (a, b, c, d) st | Expr.TyChoose (a, b, c) -> p_byte 12 st; p_tup3 p_tyar_specs p_expr p_dummy_range (a, b, c) st - | Expr.Quote(ast, _, _, m, ty) -> p_byte 13 st; p_tup3 p_expr p_dummy_range p_ty (ast, m, ty) st + | Expr.Quote (ast, _, _, m, ty) -> p_byte 13 st; p_tup3 p_expr p_dummy_range p_ty (ast, m, ty) st and u_expr st = let tag = u_byte st @@ -2578,7 +2606,7 @@ and u_expr st = let b = u_expr st let c = u_int st let d = u_dummy_range st - Expr.Sequential (a, b, (match c with 0 -> NormalSeq | 1 -> ThenDoSeq | _ -> ufailwith st "specialSeqFlag"), SuppressSequencePointOnExprOfSequential, d) + Expr.Sequential (a, b, (match c with 0 -> NormalSeq | 1 -> ThenDoSeq | _ -> ufailwith st "specialSeqFlag"), DebugPointAtSequential.StmtOnly, d) | 4 -> let a0 = u_option u_Val st let b0 = u_option u_Val st let b1 = u_Vals st @@ -2600,17 +2628,17 @@ and u_expr st = | 7 -> let a = u_binds st let b = u_expr st let c = u_dummy_range st - Expr.LetRec (a, b, c, NewFreeVarsCache()) + Expr.LetRec (a, b, c, Construct.NewFreeVarsCache()) | 8 -> let a = u_bind st let b = u_expr st let c = u_dummy_range st - Expr.Let (a, b, c, NewFreeVarsCache()) + Expr.Let (a, b, c, Construct.NewFreeVarsCache()) | 9 -> let a = u_dummy_range st let b = u_dtree st let c = u_targets st let d = u_dummy_range st let e = u_ty st - Expr.Match (NoSequencePointAtStickyBinding, a, b, c, d, e) + Expr.Match (NoDebugPointAtStickyBinding, a, b, c, d, e) | 10 -> let b = u_ty st let c = (u_option u_Val) st let d = u_expr st @@ -2636,7 +2664,7 @@ and u_expr st = and p_static_optimization_constraint x st = match x with | TTyconEqualsTycon (a, b) -> p_byte 0 st; p_tup2 p_ty p_ty (a, b) st - | TTyconIsStruct(a) -> p_byte 1 st; p_ty a st + | TTyconIsStruct a -> p_byte 1 st; p_ty a st and p_slotparam (TSlotParam (a, b, c, d, e, f)) st = p_tup6 (p_option p_string) p_ty p_bool p_bool p_bool p_attribs (a, b, c, d, e, f) st and p_slotsig (TSlotSig (a, b, c, d, e, f)) st = p_tup6 p_string p_ty p_tyar_specs p_tyar_specs (p_list (p_list p_slotparam)) (p_option p_ty) (a, b, c, d, e, f) st diff --git a/src/fcs-fable/src/fsharp/TastPickle.fsi b/src/fcs-fable/src/fsharp/TypedTreePickle.fsi similarity index 94% rename from src/fcs-fable/src/fsharp/TastPickle.fsi rename to src/fcs-fable/src/fsharp/TypedTreePickle.fsi index 9f1000580a..b5d1547430 100644 --- a/src/fcs-fable/src/fsharp/TastPickle.fsi +++ b/src/fcs-fable/src/fsharp/TypedTreePickle.fsi @@ -1,24 +1,24 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. /// Defines the framework for serializing and de-serializing TAST data structures as binary blobs for the F# metadata format. -module internal FSharp.Compiler.TastPickle +module internal FSharp.Compiler.TypedTreePickle -open Internal.Utilities -open FSharp.Compiler -open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.Tast +open FSharp.Compiler.TypedTree open FSharp.Compiler.TcGlobals /// Represents deserialized data with a dangling set of CCU fixup thunks indexed by name [] type PickledDataWithReferences<'RawData> = - { /// The data that uses a collection of CcuThunks internally + { + /// The data that uses a collection of CcuThunks internally RawData: 'RawData + /// The assumptions that need to be fixed up - FixupThunks: CcuThunk [] } + FixupThunks: CcuThunk [] + } member Fixup : (CcuReference -> CcuThunk) -> 'RawData /// Like Fixup but loader may return None, in which case there is no fixup. @@ -142,7 +142,7 @@ val internal u_ty : unpickler val internal unpickleCcuInfo : ReaderState -> PickledCcuInfo /// Deserialize an arbitrary object which may have holes referring to other compilation units -val internal unpickleObjWithDanglingCcus : file:string -> viewedScope:ILScopeRef -> ilModule:ILModuleDef option -> ('T unpickler) -> byte[] -> PickledDataWithReferences<'T> +val internal unpickleObjWithDanglingCcus : file:string -> viewedScope:ILScopeRef -> ilModule:ILModuleDef option -> ('T unpickler) -> ReadOnlyByteMemory -> PickledDataWithReferences<'T> diff --git a/src/fcs-fable/src/fsharp/UnicodeLexing.fs b/src/fcs-fable/src/fsharp/UnicodeLexing.fs old mode 100755 new mode 100644 index 9250ebed81..5c98662604 --- a/src/fcs-fable/src/fsharp/UnicodeLexing.fs +++ b/src/fcs-fable/src/fsharp/UnicodeLexing.fs @@ -6,68 +6,35 @@ module internal FSharp.Compiler.UnicodeLexing // Functions for Unicode char-based lexing (new code). // -open FSharp.Compiler.AbstractIL.Internal.Library -open Internal.Utilities -open System.IO - +open System.IO open Internal.Utilities.Text.Lexing type Lexbuf = LexBuffer -let StringAsLexbuf = - Lexbuf.FromString - -let FunctionAsLexbuf = - Lexbuf.FromFunction - -#if !FABLE_COMPILER +let StringAsLexbuf (supportsFeature, s: string) = +#if FABLE_COMPILER + LexBuffer.FromString (supportsFeature, s) +#else + LexBuffer.FromChars (supportsFeature, s.ToCharArray()) +#endif -// The choice of 60 retries times 50 ms is not arbitrary. The NTFS FILETIME structure -// uses 2 second resolution for LastWriteTime. We retry long enough to surpass this threshold -// plus 1 second. Once past the threshold the incremental builder will be able to retry asynchronously based -// on plain old timestamp checking. -// -// The sleep time of 50ms is chosen so that we can respond to the user more quickly for Intellisense operations. -// -// This is not run on the UI thread for VS but it is on a thread that must be stopped before Intellisense -// can return any result except for pending. -let retryDelayMilliseconds = 50 -let numRetries = 60 +let FunctionAsLexbuf (supportsFeature, bufferFiller) = + LexBuffer.FromFunction(supportsFeature, bufferFiller) -/// Standard utility to create a Unicode LexBuffer -/// -/// One small annoyance is that LexBuffers and not IDisposable. This means -/// we can't just return the LexBuffer object, since the file it wraps wouldn't -/// get closed when we're finished with the LexBuffer. Hence we return the stream, -/// the reader and the LexBuffer. The caller should dispose the first two when done. -let UnicodeFileAsLexbuf (filename,codePage : int option, retryLocked:bool) : Lexbuf = - // Retry multiple times since other processes may be writing to this file. - let rec getSource retryNumber = - try - // Use the .NET functionality to auto-detect the unicode encoding - use stream = FileSystem.FileStreamReadShim(filename) - use reader = - match codePage with - | None -> new StreamReader(stream,true) - | Some n -> new StreamReader(stream,System.Text.Encoding.GetEncoding(n)) - reader.ReadToEnd() - with - // We can get here if the file is locked--like when VS is saving a file--we don't have direct - // access to the HRESULT to see that this is EONOACCESS. - | :? System.IO.IOException as err when retryLocked && err.GetType() = typeof -> - // This second check is to make sure the exception is exactly IOException and none of these for example: - // DirectoryNotFoundException - // EndOfStreamException - // FileNotFoundException - // FileLoadException - // PathTooLongException - if retryNumber < numRetries then - System.Threading.Thread.Sleep (retryDelayMilliseconds) - getSource (retryNumber + 1) - else - reraise() - let source = getSource 0 - let lexbuf = LexBuffer<_>.FromString (source) - lexbuf +let SourceTextAsLexbuf (supportsFeature, sourceText) = + LexBuffer.FromSourceText(supportsFeature, sourceText) -#endif \ No newline at end of file +#if !FABLE_COMPILER +let StreamReaderAsLexbuf (supportsFeature, reader: StreamReader) = + let mutable isFinished = false + FunctionAsLexbuf (supportsFeature, fun (chars, start, length) -> + if isFinished then 0 + else + let nBytesRead = reader.Read(chars, start, length) + if nBytesRead = 0 then + isFinished <- true + 0 + else + nBytesRead + ) +#endif diff --git a/src/fcs-fable/src/fsharp/UnicodeLexing.fsi b/src/fcs-fable/src/fsharp/UnicodeLexing.fsi old mode 100755 new mode 100644 index d1ef6dd832..dcb48d1ed9 --- a/src/fcs-fable/src/fsharp/UnicodeLexing.fsi +++ b/src/fcs-fable/src/fsharp/UnicodeLexing.fsi @@ -2,13 +2,20 @@ module internal FSharp.Compiler.UnicodeLexing -open Microsoft.FSharp.Text +open System.IO +open FSharp.Compiler.Features +open FSharp.Compiler.Text open Internal.Utilities.Text.Lexing type Lexbuf = LexBuffer -val internal StringAsLexbuf : string -> Lexbuf -val public FunctionAsLexbuf : (LexBufferChar[] * int * int -> int) -> Lexbuf + +val internal StringAsLexbuf: (LanguageFeature -> bool) * string -> Lexbuf + +val public FunctionAsLexbuf: (LanguageFeature -> bool) * (LexBufferChar[] * int * int -> int) -> Lexbuf + +val public SourceTextAsLexbuf: (LanguageFeature -> bool) * ISourceText -> Lexbuf #if !FABLE_COMPILER -val public UnicodeFileAsLexbuf :string * int option * (*retryLocked*) bool -> Lexbuf -#endif \ No newline at end of file +/// Will not dispose of the stream reader. +val public StreamReaderAsLexbuf: (LanguageFeature -> bool) * StreamReader -> Lexbuf +#endif diff --git a/src/fcs-fable/XmlAdapters.fs b/src/fcs-fable/src/fsharp/XmlAdapters.fs similarity index 60% rename from src/fcs-fable/XmlAdapters.fs rename to src/fcs-fable/src/fsharp/XmlAdapters.fs index 78809b64a2..2e04733fc1 100644 --- a/src/fcs-fable/XmlAdapters.fs +++ b/src/fcs-fable/src/fsharp/XmlAdapters.fs @@ -1,11 +1,11 @@ -//------------------------------------------------------------------------ -// From reshapedreflection.fs -//------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. namespace Microsoft.FSharp.Core -module XmlAdapters = +//Replacement for: System.Security.SecurityElement.Escape(line) All platforms +module internal XmlAdapters = let s_escapeChars = [| '<'; '>'; '\"'; '\''; '&' |] + let getEscapeSequence c = match c with | '<' -> "<" @@ -14,4 +14,6 @@ module XmlAdapters = | '\'' -> "'" | '&' -> "&" | _ as ch -> ch.ToString() + let escape str = String.collect getEscapeSequence str + diff --git a/src/fcs-fable/src/fsharp/XmlDoc.fs b/src/fcs-fable/src/fsharp/XmlDoc.fs new file mode 100644 index 0000000000..5748ed5990 --- /dev/null +++ b/src/fcs-fable/src/fsharp/XmlDoc.fs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +module public FSharp.Compiler.XmlDoc + +open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.Range + +/// Represents the final form of collected XmlDoc lines +type XmlDoc = + | XmlDoc of string[] + + static member Empty = XmlDocStatics.Empty + + member x.NonEmpty = (let (XmlDoc lines) = x in lines.Length <> 0) + + static member Merge (XmlDoc lines) (XmlDoc lines') = XmlDoc (Array.append lines lines') + + /// This code runs for .XML generation and thus influences cross-project xmldoc tooltips; for within-project tooltips, + /// see XmlDocumentation.fs in the language service + static member Process (XmlDoc lines) = + let rec processLines (lines: string list) = + match lines with + | [] -> [] + | (lineA :: rest) as lines -> + let lineAT = lineA.TrimStart([|' '|]) + if lineAT = "" then processLines rest + else if lineAT.StartsWithOrdinal("<") then lines + else [""] @ + (lines |> List.map (fun line -> Microsoft.FSharp.Core.XmlAdapters.escape line)) @ + [""] + + let lines = processLines (Array.toList lines) + if isNil lines then XmlDoc.Empty + else XmlDoc (Array.ofList lines) + +// Discriminated unions can't contain statics, so we use a separate type +and XmlDocStatics() = + + static let empty = XmlDoc[| |] + + static member Empty = empty + +/// Used to collect XML documentation during lexing and parsing. +type XmlDocCollector() = + let mutable savedLines = new ResizeArray<(string * pos)>() + let mutable savedGrabPoints = new ResizeArray() + let posCompare p1 p2 = if posGeq p1 p2 then 1 else if posEq p1 p2 then 0 else -1 + let savedGrabPointsAsArray = + lazy (savedGrabPoints.ToArray() |> Array.sortWith posCompare) + + let savedLinesAsArray = + lazy (savedLines.ToArray() |> Array.sortWith (fun (_, p1) (_, p2) -> posCompare p1 p2)) + + let check() = + // can't add more XmlDoc elements to XmlDocCollector after extracting first XmlDoc from the overall results + assert (not savedLinesAsArray.IsValueCreated) + + member x.AddGrabPoint pos = + check() + savedGrabPoints.Add pos + + member x.AddXmlDocLine(line, pos) = + check() + savedLines.Add(line, pos) + + member x.LinesBefore grabPointPos = + try + let lines = savedLinesAsArray.Force() + let grabPoints = savedGrabPointsAsArray.Force() + let firstLineIndexAfterGrabPoint = Array.findFirstIndexWhereTrue lines (fun (_, pos) -> posGeq pos grabPointPos) + let grabPointIndex = Array.findFirstIndexWhereTrue grabPoints (fun pos -> posGeq pos grabPointPos) + assert (posEq grabPoints.[grabPointIndex] grabPointPos) + let firstLineIndexAfterPrevGrabPoint = + if grabPointIndex = 0 then + 0 + else + let prevGrabPointPos = grabPoints.[grabPointIndex-1] + Array.findFirstIndexWhereTrue lines (fun (_, pos) -> posGeq pos prevGrabPointPos) + + let lines = lines.[firstLineIndexAfterPrevGrabPoint..firstLineIndexAfterGrabPoint-1] |> Array.rev + if lines.Length = 0 then + [| |] + else + let firstLineNumber = (snd lines.[0]).Line + lines + |> Array.mapi (fun i x -> firstLineNumber - i, x) + |> Array.takeWhile (fun (sequencedLineNumber, (_, pos)) -> sequencedLineNumber = pos.Line) + |> Array.map (fun (_, (lineStr, _)) -> lineStr) + |> Array.rev + with e -> + //printfn "unexpected error in LinesBefore:\n%s" (e.ToString()) + [| |] + +/// Represents the XmlDoc fragments as collected from the lexer during parsing +type PreXmlDoc = + | PreXmlMerge of PreXmlDoc * PreXmlDoc + | PreXmlDoc of pos * XmlDocCollector + | PreXmlDocEmpty + + member x.ToXmlDoc() = + match x with + | PreXmlMerge(a, b) -> XmlDoc.Merge (a.ToXmlDoc()) (b.ToXmlDoc()) + | PreXmlDocEmpty -> XmlDoc.Empty + | PreXmlDoc (pos, collector) -> + let lines = collector.LinesBefore pos + if lines.Length = 0 then XmlDoc.Empty + else XmlDoc lines + + static member CreateFromGrabPoint(collector: XmlDocCollector, grabPointPos) = + collector.AddGrabPoint grabPointPos + PreXmlDoc(grabPointPos, collector) + + static member Empty = PreXmlDocEmpty + + static member Merge a b = PreXmlMerge (a, b) + diff --git a/src/fcs-fable/src/fsharp/ast.fs b/src/fcs-fable/src/fsharp/ast.fs deleted file mode 100644 index a5068dae2d..0000000000 --- a/src/fcs-fable/src/fsharp/ast.fs +++ /dev/null @@ -1,2629 +0,0 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. - -module public FSharp.Compiler.Ast - -open System.Collections.Generic -open Internal.Utilities.Text.Lexing -open Internal.Utilities.Text.Parsing -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.IL -open FSharp.Compiler.AbstractIL.Internal -open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler -open FSharp.Compiler.UnicodeLexing -open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.PrettyNaming -open FSharp.Compiler.Range - -/// The prefix of the names used for the fake namespace path added to all dynamic code entries in FSI.EXE -let FsiDynamicModulePrefix = "FSI_" - -[] -module FSharpLib = - let Root = "Microsoft.FSharp" - let RootPath = IL.splitNamespace Root - let Core = Root + ".Core" - let CorePath = IL.splitNamespace Core - - -[] -module CustomOperations = - [] - let Into = "into" - -//------------------------------------------------------------------------ -// XML doc pre-processing -//----------------------------------------------------------------------- - - -/// Used to collect XML documentation during lexing and parsing. -type XmlDocCollector() = - let mutable savedLines = new ResizeArray<(string * pos)>() - let mutable savedGrabPoints = new ResizeArray() - let posCompare p1 p2 = if posGeq p1 p2 then 1 else if posEq p1 p2 then 0 else -1 - let savedGrabPointsAsArray = - lazy (savedGrabPoints.ToArray() |> Array.sortWith posCompare) - - let savedLinesAsArray = - lazy (savedLines.ToArray() |> Array.sortWith (fun (_, p1) (_, p2) -> posCompare p1 p2)) - - let check() = - assert (not savedLinesAsArray.IsValueCreated && "can't add more XmlDoc elements to XmlDocCollector after extracting first XmlDoc from the overall results" <> "") - - member x.AddGrabPoint(pos) = - check() - savedGrabPoints.Add pos - - member x.AddXmlDocLine(line, pos) = - check() - savedLines.Add(line, pos) - - member x.LinesBefore(grabPointPos) = - try - let lines = savedLinesAsArray.Force() - let grabPoints = savedGrabPointsAsArray.Force() - let firstLineIndexAfterGrabPoint = Array.findFirstIndexWhereTrue lines (fun (_, pos) -> posGeq pos grabPointPos) - let grabPointIndex = Array.findFirstIndexWhereTrue grabPoints (fun pos -> posGeq pos grabPointPos) - assert (posEq grabPoints.[grabPointIndex] grabPointPos) - let firstLineIndexAfterPrevGrabPoint = - if grabPointIndex = 0 then - 0 - else - let prevGrabPointPos = grabPoints.[grabPointIndex-1] - Array.findFirstIndexWhereTrue lines (fun (_, pos) -> posGeq pos prevGrabPointPos) - //printfn "#lines = %d, firstLineIndexAfterPrevGrabPoint = %d, firstLineIndexAfterGrabPoint = %d" lines.Length firstLineIndexAfterPrevGrabPoint firstLineIndexAfterGrabPoint - - let lines = lines.[firstLineIndexAfterPrevGrabPoint..firstLineIndexAfterGrabPoint-1] |> Array.rev - if lines.Length = 0 then - [| |] - else - let firstLineNumber = (snd lines.[0]).Line - lines - |> Array.mapi (fun i x -> firstLineNumber - i, x) - |> Array.takeWhile (fun (sequencedLineNumber, (_, pos)) -> sequencedLineNumber = pos.Line) - |> Array.map (fun (_, (lineStr, _)) -> lineStr) - |> Array.rev - with e -> - //printfn "unexpected error in LinesBefore:\n%s" (e.ToString()) - [| |] - -type XmlDoc = - | XmlDoc of string[] - - static member Empty = XmlDocStatics.Empty - - member x.NonEmpty = (let (XmlDoc lines) = x in lines.Length <> 0) - - static member Merge (XmlDoc lines) (XmlDoc lines') = XmlDoc (Array.append lines lines') - - /// This code runs for .XML generation and thus influences cross-project xmldoc tooltips; for within-project tooltips, - /// see XmlDocumentation.fs in the language service - static member Process (XmlDoc lines) = - let rec processLines (lines: string list) = - match lines with - | [] -> [] - | (lineA:: rest) as lines -> - let lineAT = lineA.TrimStart([|' '|]) - if lineAT = "" then processLines rest - else if lineAT.StartsWithOrdinal("<") then lines - else [""] @ - (lines |> List.map (fun line -> Microsoft.FSharp.Core.XmlAdapters.escape(line))) @ - [""] - - let lines = processLines (Array.toList lines) - if isNil lines then XmlDoc.Empty - else XmlDoc (Array.ofList lines) - -// Discriminated unions can't contain statics, so we use a separate type -and XmlDocStatics() = - - static let empty = XmlDoc[| |] - - static member Empty = empty - -type PreXmlDoc = - | PreXmlMerge of PreXmlDoc * PreXmlDoc - | PreXmlDoc of pos * XmlDocCollector - | PreXmlDocEmpty - - member x.ToXmlDoc() = - match x with - | PreXmlMerge(a, b) -> XmlDoc.Merge (a.ToXmlDoc()) (b.ToXmlDoc()) - | PreXmlDocEmpty -> XmlDoc.Empty - | PreXmlDoc (pos, collector) -> - let lines = collector.LinesBefore pos - if lines.Length = 0 then XmlDoc.Empty - else XmlDoc lines - - static member CreateFromGrabPoint(collector: XmlDocCollector, grabPointPos) = - collector.AddGrabPoint grabPointPos - PreXmlDoc(grabPointPos, collector) - - static member Empty = PreXmlDocEmpty - - static member Merge a b = PreXmlMerge (a, b) - -type ParserDetail = - | Ok - | ThereWereSignificantParseErrorsSoDoNotTypecheckThisNode // would cause spurious/misleading diagnostics - -//------------------------------------------------------------------------ -// AST: identifiers and long identifiers -//----------------------------------------------------------------------- - -// PERFORMANCE: consider making this a struct. -[] -[] -[] -type Ident (text: string, range: range) = - member x.idText = text - member x.idRange = range - override x.ToString() = text - -type LongIdent = Ident list - -type LongIdentWithDots = - /// LongIdentWithDots(lid, dotms) - /// Typically dotms.Length = lid.Length-1, but they may be same if (incomplete) code ends in a dot, e.g. "Foo.Bar." - /// The dots mostly matter for parsing, and are typically ignored by the typechecker, but - /// if dotms.Length = lid.Length, then the parser must have reported an error, so the typechecker is allowed - /// more freedom about typechecking these expressions. - /// LongIdent can be empty list - it is used to denote that name of some AST element is absent (i.e. empty type name in inherit) - | LongIdentWithDots of id: LongIdent * dotms: range list - - member this.Range = - match this with - | LongIdentWithDots([], _) -> failwith "rangeOfLidwd" - | LongIdentWithDots([id], []) -> id.idRange - | LongIdentWithDots([id], [m]) -> unionRanges id.idRange m - | LongIdentWithDots(h::t, []) -> unionRanges h.idRange (List.last t).idRange - | LongIdentWithDots(h::t, dotms) -> unionRanges h.idRange (List.last t).idRange |> unionRanges (List.last dotms) - - member this.Lid = match this with LongIdentWithDots(lid, _) -> lid - - member this.ThereIsAnExtraDotAtTheEnd = match this with LongIdentWithDots(lid, dots) -> lid.Length = dots.Length - - member this.RangeSansAnyExtraDot = - match this with - | LongIdentWithDots([], _) -> failwith "rangeOfLidwd" - | LongIdentWithDots([id], _) -> id.idRange - | LongIdentWithDots(h::t, dotms) -> - let nonExtraDots = if dotms.Length = t.Length then dotms else List.truncate t.Length dotms - unionRanges h.idRange (List.last t).idRange |> unionRanges (List.last nonExtraDots) - -//------------------------------------------------------------------------ -// AST: the grammar of implicitly scoped type parameters -//----------------------------------------------------------------------- - -type TyparStaticReq = - | NoStaticReq - | HeadTypeStaticReq - -[] -type SynTypar = - | Typar of ident: Ident * staticReq: TyparStaticReq * isCompGen: bool - - member this.Range = - match this with - | Typar(id, _, _) -> - id.idRange - -//------------------------------------------------------------------------ -// AST: the grammar of constants and measures -//----------------------------------------------------------------------- - -type - [] - /// The unchecked abstract syntax tree of constants in F# types and expressions. - SynConst = - - /// F# syntax: () - | Unit - - /// F# syntax: true, false - | Bool of bool - - /// F# syntax: 13y, 0xFFy, 0o077y, 0b0111101y - | SByte of sbyte - - /// F# syntax: 13uy, 0x40uy, 0oFFuy, 0b0111101uy - | Byte of byte - - /// F# syntax: 13s, 0x4000s, 0o0777s, 0b0111101s - | Int16 of int16 - - /// F# syntax: 13us, 0x4000us, 0o0777us, 0b0111101us - | UInt16 of uint16 - - /// F# syntax: 13, 0x4000, 0o0777 - | Int32 of int32 - - /// F# syntax: 13u, 0x4000u, 0o0777u - | UInt32 of uint32 - - /// F# syntax: 13L - | Int64 of int64 - - /// F# syntax: 13UL - | UInt64 of uint64 - - /// F# syntax: 13n - | IntPtr of int64 - - /// F# syntax: 13un - | UIntPtr of uint64 - - /// F# syntax: 1.30f, 1.40e10f etc. - | Single of single - - /// F# syntax: 1.30, 1.40e10 etc. - | Double of double - - /// F# syntax: 'a' - | Char of char - - /// F# syntax: 23.4M - | Decimal of System.Decimal - - /// UserNum(value, suffix) - /// - /// F# syntax: 1Q, 1Z, 1R, 1N, 1G - | UserNum of value: string * suffix: string - - /// F# syntax: verbatim or regular string, e.g. "abc" - | String of text: string * range: range - - /// F# syntax: verbatim or regular byte string, e.g. "abc"B. - /// - /// Also used internally in the typechecker once an array of unit16 constants - /// is detected, to allow more efficient processing of large arrays of uint16 constants. - | Bytes of bytes: byte[] * range: range - - /// Used internally in the typechecker once an array of unit16 constants - /// is detected, to allow more efficient processing of large arrays of uint16 constants. - | UInt16s of uint16[] - - /// Old comment: "we never iterate, so the const here is not another SynConst.Measure" - | Measure of constant: SynConst * SynMeasure - - member c.Range dflt = - match c with - | SynConst.String (_, m0) | SynConst.Bytes (_, m0) -> m0 - | _ -> dflt - -and - [] - /// The unchecked abstract syntax tree of F# unit of measure annotations. - /// This should probably be merged with the representation of SynType. - SynMeasure = - | Named of longId: LongIdent * range: range - - | Product of SynMeasure * SynMeasure * range: range - - | Seq of SynMeasure list * range: range - - | Divide of SynMeasure * SynMeasure * range: range - - | Power of SynMeasure * SynRationalConst * range: range - - | One - - | Anon of range: range - - | Var of SynTypar * range: range - -and - [] - /// The unchecked abstract syntax tree of F# unit of measure exponents. - SynRationalConst = - | Integer of int32 - - | Rational of int32 * int32 * range: range - - | Negate of SynRationalConst - -//------------------------------------------------------------------------ -// AST: the grammar of types, expressions, declarations etc. -//----------------------------------------------------------------------- - -[] -type SynAccess = - | Public - | Internal - | Private - -type SequencePointInfoForTarget = - | SequencePointAtTarget - | SuppressSequencePointAtTarget - -type SequencePointInfoForSeq = - | SequencePointsAtSeq - - // This means "suppress a in 'a;b'" and "suppress b in 'a before b'" - | SuppressSequencePointOnExprOfSequential - - // This means "suppress b in 'a;b'" and "suppress a in 'a before b'" - | SuppressSequencePointOnStmtOfSequential - -type SequencePointInfoForTry = - | SequencePointAtTry of range: range - // Used for "use" and "for" - | SequencePointInBodyOfTry - | NoSequencePointAtTry - -type SequencePointInfoForWith = - | SequencePointAtWith of range: range - | NoSequencePointAtWith - -type SequencePointInfoForFinally = - | SequencePointAtFinally of range: range - | NoSequencePointAtFinally - -type SequencePointInfoForForLoop = - | SequencePointAtForLoop of range: range - | NoSequencePointAtForLoop - -type SequencePointInfoForWhileLoop = - | SequencePointAtWhileLoop of range: range - | NoSequencePointAtWhileLoop - -type SequencePointInfoForBinding = - | SequencePointAtBinding of range: range - - // Indicates the omission of a sequence point for a binding for a 'do expr' - | NoSequencePointAtDoBinding - - // Indicates the omission of a sequence point for a binding for a 'let e = expr' where - // 'expr' has immediate control flow - | NoSequencePointAtLetBinding - - // Indicates the omission of a sequence point for a compiler generated binding - // where we've done a local expansion of some construct into something that involves - // a 'let'. e.g. we've inlined a function and bound its arguments using 'let' - // The let bindings are 'sticky' in that the inversion of the inlining would involve - // replacing the entire expression with the original and not just the let bindings alone. - | NoSequencePointAtStickyBinding - - // Given 'let v = e1 in e2', where this is a compiler generated binding, - // we are sometimes forced to generate a sequence point for the expression anyway based on its - // overall range. If the let binding is given the flag below then it is asserting that - // the binding has no interesting side effects and can be totally ignored and the range - // of the inner expression is used instead - | NoSequencePointAtInvisibleBinding - - // Don't drop sequence points when combining sequence points - member x.Combine(y: SequencePointInfoForBinding) = - match x, y with - | SequencePointAtBinding _ as g, _ -> g - | _, (SequencePointAtBinding _ as g) -> g - | _ -> x - -/// Indicates if a for loop is 'for x in e1 -> e2', only valid in sequence expressions -type SeqExprOnly = - /// Indicates if a for loop is 'for x in e1 -> e2', only valid in sequence expressions - | SeqExprOnly of bool - -/// denotes location of the separator block + optional position of the semicolon (used for tooling support) -type BlockSeparator = range * pos option - -/// stores pair: record field name + (true if given record field name is syntactically correct and can be used in name resolution) -type RecordFieldName = LongIdentWithDots * bool - -type ExprAtomicFlag = - - /// Says that the expression is an atomic expression, i.e. is of a form that has no whitespace unless - /// enclosed in parentheses, e.g. 1, "3", ident, ident.[expr] and (expr). If an atomic expression has - /// type T, then the largest expression ending at the same range as the atomic expression also has type T. - | Atomic = 0 - - | NonAtomic = 1 - -/// The kind associated with a binding - "let", "do" or a standalone expression -type SynBindingKind = - - /// A standalone expression in a module - | StandaloneExpression - - /// A normal 'let' binding in a module - | NormalBinding - - /// A 'do' binding in a module. Must have type 'unit' - | DoBinding - -type - [] - /// Represents the explicit declaration of a type parameter - SynTyparDecl = - | TyparDecl of attributes: SynAttributes * SynTypar - -and - [] - /// The unchecked abstract syntax tree of F# type constraints - SynTypeConstraint = - - /// F# syntax: is 'typar: struct - | WhereTyparIsValueType of genericName: SynTypar * range: range - - /// F# syntax: is 'typar: not struct - | WhereTyparIsReferenceType of genericName: SynTypar * range: range - - /// F# syntax is 'typar: unmanaged - | WhereTyparIsUnmanaged of genericName: SynTypar * range: range - - /// F# syntax is 'typar: null - | WhereTyparSupportsNull of genericName: SynTypar * range: range - - /// F# syntax is 'typar: comparison - | WhereTyparIsComparable of genericName: SynTypar * range: range - - /// F# syntax is 'typar: equality - | WhereTyparIsEquatable of genericName: SynTypar * range: range - - /// F# syntax is default ^T: type - | WhereTyparDefaultsToType of genericName: SynTypar * typeName: SynType * range: range - - /// F# syntax is 'typar :> type - | WhereTyparSubtypeOfType of genericName: SynTypar * typeName: SynType * range: range - - /// F# syntax is ^T: (static member MemberName: ^T * int -> ^T) - | WhereTyparSupportsMember of genericNames: SynType list * memberSig: SynMemberSig * range: range - - /// F# syntax is 'typar: enum<'UnderlyingType> - | WhereTyparIsEnum of genericName: SynTypar * SynType list * range: range - - /// F# syntax is 'typar: delegate<'Args, unit> - | WhereTyparIsDelegate of genericName: SynTypar * SynType list * range: range - -and - [] - /// The unchecked abstract syntax tree of F# types - SynType = - /// F# syntax: A.B.C - | LongIdent of longDotId: LongIdentWithDots - /// App(typeName, LESSm, typeArgs, commasm, GREATERm, isPostfix, m) - /// - /// F# syntax: type or type type or (type, ..., type) type - /// isPostfix: indicates a postfix type application e.g. "int list" or "(int, string) dict" - /// commasm: ranges for interstitial commas, these only matter for parsing/design-time tooling, the typechecker may munge/discard them - | App of typeName: SynType * LESSrange: range option * typeArgs: SynType list * commaRanges: range list * GREATERrange: range option * isPostfix: bool * range: range - /// LongIdentApp(typeName, longId, LESSm, tyArgs, commasm, GREATERm, wholem) - /// - /// F# syntax: type.A.B.C - /// commasm: ranges for interstitial commas, these only matter for parsing/design-time tooling, the typechecker may munge/discard them - | LongIdentApp of typeName: SynType * longDotId: LongIdentWithDots * LESSRange: range option * typeArgs: SynType list * commaRanges: range list * GREATERrange: range option * range: range - - /// F# syntax: type * ... * type - /// F# syntax: struct (type * ... * type) - // the bool is true if / rather than * follows the type - | Tuple of isStruct: bool * typeNames:(bool*SynType) list * range: range - - /// F# syntax: {| id: type; ...; id: type |} - /// F# syntax: struct {| id: type; ...; id: type |} - | AnonRecd of isStruct: bool * typeNames:(Ident * SynType) list * range: range - - /// F# syntax: type[] - | Array of int * elementType: SynType * range: range - - /// F# syntax: type -> type - | Fun of argType: SynType * returnType: SynType * range: range - - /// F# syntax: 'Var - | Var of genericName: SynTypar * range: range - - /// F# syntax: _ - | Anon of range: range - - /// F# syntax: typ with constraints - | WithGlobalConstraints of typeName: SynType * constraints: SynTypeConstraint list * range: range - - /// F# syntax: #type - | HashConstraint of SynType * range: range - - /// F# syntax: for units of measure e.g. m / s - | MeasureDivide of dividendType: SynType * divisorType: SynType * range: range - - /// F# syntax: for units of measure e.g. m^3, kg^1/2 - | MeasurePower of measureType: SynType * SynRationalConst * range: range - - /// F# syntax: 1, "abc" etc, used in parameters to type providers - /// For the dimensionless units i.e. 1, and static parameters to provided types - | StaticConstant of constant: SynConst * range: range - - /// F# syntax: const expr, used in static parameters to type providers - | StaticConstantExpr of expr: SynExpr * range: range - - /// F# syntax: ident=1 etc., used in static parameters to type providers - | StaticConstantNamed of expr: SynType * SynType * range: range - - /// Get the syntactic range of source code covered by this construct. - member x.Range = - match x with - | SynType.App (range=m) - | SynType.LongIdentApp (range=m) - | SynType.Tuple (range=m) - | SynType.Array (range=m) - | SynType.AnonRecd (range=m) - | SynType.Fun (range=m) - | SynType.Var (range=m) - | SynType.Anon (range=m) - | SynType.WithGlobalConstraints (range=m) - | SynType.StaticConstant (range=m) - | SynType.StaticConstantExpr (range=m) - | SynType.StaticConstantNamed (range=m) - | SynType.HashConstraint (range=m) - | SynType.MeasureDivide (range=m) - | SynType.MeasurePower (range=m) -> m - | SynType.LongIdent(lidwd) -> lidwd.Range - -and - [] - SynExpr = - - /// F# syntax: (expr) - /// - /// Paren(expr, leftParenRange, rightParenRange, wholeRangeIncludingParentheses) - /// - /// Parenthesized expressions. Kept in AST to distinguish A.M((x, y)) - /// from A.M(x, y), among other things. - | Paren of expr: SynExpr * leftParenRange: range * rightParenRange: range option * range: range - - /// F# syntax: <@ expr @>, <@@ expr @@> - /// - /// Quote(operator, isRaw, quotedSynExpr, isFromQueryExpression, m) - | Quote of operator: SynExpr * isRaw: bool * quotedSynExpr: SynExpr * isFromQueryExpression: bool * range: range - - /// F# syntax: 1, 1.3, () etc. - | Const of constant: SynConst * range: range - - /// F# syntax: expr: type - | Typed of expr: SynExpr * typeName: SynType * range: range - - /// F# syntax: e1, ..., eN - | Tuple of isStruct: bool * exprs: SynExpr list * commaRanges: range list * range: range // "range list" is for interstitial commas, these only matter for parsing/design-time tooling, the typechecker may munge/discard them - - /// F# syntax: {| id1=e1; ...; idN=eN |} - /// F# syntax: struct {| id1=e1; ...; idN=eN |} - | AnonRecd of isStruct: bool * copyInfo:(SynExpr * BlockSeparator) option * recordFields:(Ident * SynExpr) list * range: range - - /// F# syntax: [ e1; ...; en ], [| e1; ...; en |] - | ArrayOrList of isList: bool * exprs: SynExpr list * range: range - - /// F# syntax: { f1=e1; ...; fn=en } - /// SynExpr.Record((baseType, baseCtorArgs, mBaseCtor, sepAfterBase, mInherits), (copyExpr, sepAfterCopyExpr), (recordFieldName, fieldValue, sepAfterField), mWholeExpr) - /// inherit includes location of separator (for tooling) - /// copyOpt contains range of the following WITH part (for tooling) - /// every field includes range of separator after the field (for tooling) - | Record of baseInfo:(SynType * SynExpr * range * BlockSeparator option * range) option * copyInfo:(SynExpr * BlockSeparator) option * recordFields:(RecordFieldName * (SynExpr option) * BlockSeparator option) list * range: range - - /// F# syntax: new C(...) - /// The flag is true if known to be 'family' ('protected') scope - | New of isProtected: bool * typeName: SynType * expr: SynExpr * range: range - - /// SynExpr.ObjExpr(objTy, argOpt, binds, extraImpls, mNewExpr, mWholeExpr) - /// - /// F# syntax: { new ... with ... } - | ObjExpr of objType: SynType * argOptions:(SynExpr * Ident option) option * bindings: SynBinding list * extraImpls: SynInterfaceImpl list * newExprRange: range * range: range - - /// F# syntax: 'while ... do ...' - | While of whileSeqPoint: SequencePointInfoForWhileLoop * whileExpr: SynExpr * doExpr: SynExpr * range: range - - /// F# syntax: 'for i = ... to ... do ...' - | For of forSeqPoint: SequencePointInfoForForLoop * ident: Ident * identBody: SynExpr * bool * toBody: SynExpr * doBody: SynExpr * range: range - - /// SynExpr.ForEach (spBind, seqExprOnly, isFromSource, pat, enumExpr, bodyExpr, mWholeExpr). - /// - /// F# syntax: 'for ... in ... do ...' - | ForEach of forSeqPoint: SequencePointInfoForForLoop * seqExprOnly: SeqExprOnly * isFromSource: bool * pat: SynPat * enumExpr: SynExpr * bodyExpr: SynExpr * range: range - - /// F# syntax: [ expr ], [| expr |] - | ArrayOrListOfSeqExpr of isArray: bool * expr: SynExpr * range: range - - /// CompExpr(isArrayOrList, isNotNakedRefCell, expr) - /// - /// F# syntax: { expr } - | CompExpr of isArrayOrList: bool * isNotNakedRefCell: bool ref * expr: SynExpr * range: range - - /// First bool indicates if lambda originates from a method. Patterns here are always "simple" - /// Second bool indicates if this is a "later" part of an iterated sequence of lambdas - /// - /// F# syntax: fun pat -> expr - | Lambda of fromMethod: bool * inLambdaSeq: bool * args: SynSimplePats * body: SynExpr * range: range - - /// F# syntax: function pat1 -> expr | ... | patN -> exprN - | MatchLambda of isExnMatch: bool * range * SynMatchClause list * matchSeqPoint: SequencePointInfoForBinding * range: range - - /// F# syntax: match expr with pat1 -> expr | ... | patN -> exprN - | Match of matchSeqPoint: SequencePointInfoForBinding * expr: SynExpr * clauses: SynMatchClause list * range: range (* bool indicates if this is an exception match in a computation expression which throws unmatched exceptions *) - - /// F# syntax: do expr - | Do of expr: SynExpr * range: range - - /// F# syntax: assert expr - | Assert of expr: SynExpr * range: range - - /// App(exprAtomicFlag, isInfix, funcExpr, argExpr, m) - /// - exprAtomicFlag: indicates if the application is syntactically atomic, e.g. f.[1] is atomic, but 'f x' is not - /// - isInfix is true for the first app of an infix operator, e.g. 1+2 becomes App(App(+, 1), 2), where the inner node is marked isInfix - /// (or more generally, for higher operator fixities, if App(x, y) is such that y comes before x in the source code, then the node is marked isInfix=true) - /// - /// F# syntax: f x - | App of ExprAtomicFlag * isInfix: bool * funcExpr: SynExpr * argExpr: SynExpr * range: range - - /// TypeApp(expr, mLessThan, types, mCommas, mGreaterThan, mTypeArgs, mWholeExpr) - /// "mCommas" are the ranges for interstitial commas, these only matter for parsing/design-time tooling, the typechecker may munge/discard them - /// - /// F# syntax: expr - | TypeApp of expr: SynExpr * LESSrange: range * typeNames: SynType list * commaRanges: range list * GREATERrange: range option * typeArgsRange: range * range: range - - /// LetOrUse(isRecursive, isUse, bindings, body, wholeRange) - /// - /// F# syntax: let pat = expr in expr - /// F# syntax: let f pat1 .. patN = expr in expr - /// F# syntax: let rec f pat1 .. patN = expr in expr - /// F# syntax: use pat = expr in expr - | LetOrUse of isRecursive: bool * isUse: bool * bindings: SynBinding list * body: SynExpr * range: range - - /// F# syntax: try expr with pat -> expr - | TryWith of tryExpr: SynExpr * tryRange: range * withCases: SynMatchClause list * withRange: range * range: range * trySeqPoint: SequencePointInfoForTry * withSeqPoint: SequencePointInfoForWith - - /// F# syntax: try expr finally expr - | TryFinally of tryExpr: SynExpr * finallyExpr: SynExpr * range: range * trySeqPoint: SequencePointInfoForTry * finallySeqPoint: SequencePointInfoForFinally - - /// F# syntax: lazy expr - | Lazy of SynExpr * range: range - - /// Seq(seqPoint, isTrueSeq, e1, e2, m) - /// isTrueSeq: false indicates "let v = a in b; v" - /// - /// F# syntax: expr; expr - | Sequential of seqPoint: SequencePointInfoForSeq * isTrueSeq: bool * expr1: SynExpr * expr2: SynExpr * range: range - - /// IfThenElse(exprGuard, exprThen, optionalExprElse, spIfToThen, isFromErrorRecovery, mIfToThen, mIfToEndOfLastBranch) - /// - /// F# syntax: if expr then expr - /// F# syntax: if expr then expr else expr - | IfThenElse of ifExpr: SynExpr * thenExpr: SynExpr * elseExpr: SynExpr option * spIfToThen: SequencePointInfoForBinding * isFromErrorRecovery: bool * ifToThenRange: range * range: range - - /// F# syntax: ident - /// Optimized representation, = SynExpr.LongIdent(false, [id], id.idRange) - | Ident of Ident - - /// F# syntax: ident.ident...ident - /// LongIdent(isOptional, longIdent, altNameRefCell, m) - /// isOptional: true if preceded by a '?' for an optional named parameter - /// altNameRefCell: Normally 'None' except for some compiler-generated variables in desugaring pattern matching. See SynSimplePat.Id - | LongIdent of isOptional: bool * longDotId: LongIdentWithDots * altNameRefCell: SynSimplePatAlternativeIdInfo ref option * range: range - - /// F# syntax: ident.ident...ident <- expr - | LongIdentSet of longDotId: LongIdentWithDots * expr: SynExpr * range: range - - /// DotGet(expr, rangeOfDot, lid, wholeRange) - /// - /// F# syntax: expr.ident.ident - | DotGet of expr: SynExpr * rangeOfDot: range * longDotId: LongIdentWithDots * range: range - - /// F# syntax: expr.ident...ident <- expr - | DotSet of SynExpr * longDotId: LongIdentWithDots * SynExpr * range: range - - /// F# syntax: expr <- expr - | Set of SynExpr * SynExpr * range: range - - /// F# syntax: expr.[expr, ..., expr] - | DotIndexedGet of SynExpr * SynIndexerArg list * range * range: range - - /// DotIndexedSet (objectExpr, indexExprs, valueExpr, rangeOfLeftOfSet, rangeOfDot, rangeOfWholeExpr) - /// - /// F# syntax: expr.[expr, ..., expr] <- expr - | DotIndexedSet of objectExpr: SynExpr * indexExprs: SynIndexerArg list * valueExpr: SynExpr * leftOfSetRange: range * dotRange: range * range: range - - /// F# syntax: Type.Items(e1) <- e2, rarely used named-property-setter notation, e.g. Foo.Bar.Chars(3) <- 'a' - | NamedIndexedPropertySet of longDotId: LongIdentWithDots * SynExpr * SynExpr * range: range - - /// F# syntax: expr.Items(e1) <- e2, rarely used named-property-setter notation, e.g. (stringExpr).Chars(3) <- 'a' - | DotNamedIndexedPropertySet of SynExpr * longDotId: LongIdentWithDots * SynExpr * SynExpr * range: range - - /// F# syntax: expr :? type - | TypeTest of expr: SynExpr * typeName: SynType * range: range - - /// F# syntax: expr :> type - | Upcast of expr: SynExpr * typeName: SynType * range: range - - /// F# syntax: expr :?> type - | Downcast of expr: SynExpr * typeName: SynType * range: range - - /// F# syntax: upcast expr - | InferredUpcast of expr: SynExpr * range: range - - /// F# syntax: downcast expr - | InferredDowncast of expr: SynExpr * range: range - - /// F# syntax: null - | Null of range: range - - /// F# syntax: &expr, &&expr - | AddressOf of isByref: bool * SynExpr * range * range: range - - /// F# syntax: ((typar1 or ... or typarN): (member-dig) expr) - | TraitCall of SynTypar list * SynMemberSig * SynExpr * range: range - - /// F# syntax: ... in ... - /// Computation expressions only, based on JOIN_IN token from lex filter - | JoinIn of SynExpr * range * SynExpr * range: range - - /// F# syntax: - /// Computation expressions only, implied by final "do" or "do!" - | ImplicitZero of range: range - - /// F# syntax: yield expr - /// F# syntax: return expr - /// Computation expressions only - | YieldOrReturn of (bool * bool) * expr: SynExpr * range: range - - /// F# syntax: yield! expr - /// F# syntax: return! expr - /// Computation expressions only - | YieldOrReturnFrom of (bool * bool) * expr: SynExpr * range: range - - /// SynExpr.LetOrUseBang(spBind, isUse, isFromSource, pat, rhsExpr, bodyExpr, mWholeExpr). - /// - /// F# syntax: let! pat = expr in expr - /// F# syntax: use! pat = expr in expr - /// Computation expressions only - | LetOrUseBang of bindSeqPoint: SequencePointInfoForBinding * isUse: bool * isFromSource: bool * SynPat * SynExpr * SynExpr * range: range - - /// F# syntax: match! expr with pat1 -> expr | ... | patN -> exprN - | MatchBang of matchSeqPoint: SequencePointInfoForBinding * expr: SynExpr * clauses: SynMatchClause list * range: range (* bool indicates if this is an exception match in a computation expression which throws unmatched exceptions *) - - /// F# syntax: do! expr - /// Computation expressions only - | DoBang of expr: SynExpr * range: range - - /// Only used in FSharp.Core - | LibraryOnlyILAssembly of ILInstr array * SynType list * SynExpr list * SynType list * range: range (* Embedded IL assembly code *) - - /// Only used in FSharp.Core - | LibraryOnlyStaticOptimization of SynStaticOptimizationConstraint list * SynExpr * SynExpr * range: range - - /// Only used in FSharp.Core - | LibraryOnlyUnionCaseFieldGet of expr: SynExpr * longId: LongIdent * int * range: range - - /// Only used in FSharp.Core - | LibraryOnlyUnionCaseFieldSet of SynExpr * longId: LongIdent * int * SynExpr * range: range - - /// Inserted for error recovery - | ArbitraryAfterError of debugStr: string * range: range - - /// Inserted for error recovery - | FromParseError of expr: SynExpr * range: range - - /// Inserted for error recovery when there is "expr." and missing tokens or error recovery after the dot - | DiscardAfterMissingQualificationAfterDot of SynExpr * range: range - - /// 'use x = fixed expr' - | Fixed of expr: SynExpr * range: range - - /// Get the syntactic range of source code covered by this construct. - member e.Range = - match e with - | SynExpr.Paren (range=m) - | SynExpr.Quote (range=m) - | SynExpr.Const (range=m) - | SynExpr.Typed (range=m) - | SynExpr.Tuple (range=m) - | SynExpr.AnonRecd (range=m) - | SynExpr.ArrayOrList (range=m) - | SynExpr.Record (range=m) - | SynExpr.New (range=m) - | SynExpr.ObjExpr (range=m) - | SynExpr.While (range=m) - | SynExpr.For (range=m) - | SynExpr.ForEach (range=m) - | SynExpr.CompExpr (range=m) - | SynExpr.ArrayOrListOfSeqExpr (range=m) - | SynExpr.Lambda (range=m) - | SynExpr.Match (range=m) - | SynExpr.MatchLambda (range=m) - | SynExpr.Do (range=m) - | SynExpr.Assert (range=m) - | SynExpr.App (range=m) - | SynExpr.TypeApp (range=m) - | SynExpr.LetOrUse (range=m) - | SynExpr.TryWith (range=m) - | SynExpr.TryFinally (range=m) - | SynExpr.Sequential (range=m) - | SynExpr.ArbitraryAfterError (range=m) - | SynExpr.FromParseError (range=m) - | SynExpr.DiscardAfterMissingQualificationAfterDot (range=m) - | SynExpr.IfThenElse (range=m) - | SynExpr.LongIdent (range=m) - | SynExpr.LongIdentSet (range=m) - | SynExpr.NamedIndexedPropertySet (range=m) - | SynExpr.DotIndexedGet (range=m) - | SynExpr.DotIndexedSet (range=m) - | SynExpr.DotGet (range=m) - | SynExpr.DotSet (range=m) - | SynExpr.Set (range=m) - | SynExpr.DotNamedIndexedPropertySet (range=m) - | SynExpr.LibraryOnlyUnionCaseFieldGet (range=m) - | SynExpr.LibraryOnlyUnionCaseFieldSet (range=m) - | SynExpr.LibraryOnlyILAssembly (range=m) - | SynExpr.LibraryOnlyStaticOptimization (range=m) - | SynExpr.TypeTest (range=m) - | SynExpr.Upcast (range=m) - | SynExpr.AddressOf (range=m) - | SynExpr.Downcast (range=m) - | SynExpr.JoinIn (range=m) - | SynExpr.InferredUpcast (range=m) - | SynExpr.InferredDowncast (range=m) - | SynExpr.Null (range=m) - | SynExpr.Lazy (range=m) - | SynExpr.TraitCall (range=m) - | SynExpr.ImplicitZero (range=m) - | SynExpr.YieldOrReturn (range=m) - | SynExpr.YieldOrReturnFrom (range=m) - | SynExpr.LetOrUseBang (range=m) - | SynExpr.MatchBang (range=m) - | SynExpr.DoBang (range=m) - | SynExpr.Fixed (range=m) -> m - | SynExpr.Ident id -> id.idRange - - /// range ignoring any (parse error) extra trailing dots - member e.RangeSansAnyExtraDot = - match e with - | SynExpr.Paren (range=m) - | SynExpr.Quote (range=m) - | SynExpr.Const (range=m) - | SynExpr.Typed (range=m) - | SynExpr.Tuple (range=m) - | SynExpr.ArrayOrList (range=m) - | SynExpr.AnonRecd (range=m) - | SynExpr.Record (range=m) - | SynExpr.New (range=m) - | SynExpr.ObjExpr (range=m) - | SynExpr.While (range=m) - | SynExpr.For (range=m) - | SynExpr.ForEach (range=m) - | SynExpr.CompExpr (range=m) - | SynExpr.ArrayOrListOfSeqExpr (range=m) - | SynExpr.Lambda (range=m) - | SynExpr.Match (range=m) - | SynExpr.MatchLambda (range=m) - | SynExpr.Do (range=m) - | SynExpr.Assert (range=m) - | SynExpr.App (range=m) - | SynExpr.TypeApp (range=m) - | SynExpr.LetOrUse (range=m) - | SynExpr.TryWith (range=m) - | SynExpr.TryFinally (range=m) - | SynExpr.Sequential (range=m) - | SynExpr.ArbitraryAfterError (range=m) - | SynExpr.FromParseError (range=m) - | SynExpr.IfThenElse (range=m) - | SynExpr.LongIdentSet (range=m) - | SynExpr.NamedIndexedPropertySet (range=m) - | SynExpr.DotIndexedGet (range=m) - | SynExpr.DotIndexedSet (range=m) - | SynExpr.DotSet (range=m) - | SynExpr.Set (range=m) - | SynExpr.DotNamedIndexedPropertySet (range=m) - | SynExpr.LibraryOnlyUnionCaseFieldGet (range=m) - | SynExpr.LibraryOnlyUnionCaseFieldSet (range=m) - | SynExpr.LibraryOnlyILAssembly (range=m) - | SynExpr.LibraryOnlyStaticOptimization (range=m) - | SynExpr.TypeTest (range=m) - | SynExpr.Upcast (range=m) - | SynExpr.AddressOf (range=m) - | SynExpr.Downcast (range=m) - | SynExpr.JoinIn (range=m) - | SynExpr.InferredUpcast (range=m) - | SynExpr.InferredDowncast (range=m) - | SynExpr.Null (range=m) - | SynExpr.Lazy (range=m) - | SynExpr.TraitCall (range=m) - | SynExpr.ImplicitZero (range=m) - | SynExpr.YieldOrReturn (range=m) - | SynExpr.YieldOrReturnFrom (range=m) - | SynExpr.LetOrUseBang (range=m) - | SynExpr.MatchBang (range=m) - | SynExpr.DoBang (range=m) -> m - | SynExpr.DotGet (expr, _, lidwd, m) -> if lidwd.ThereIsAnExtraDotAtTheEnd then unionRanges expr.Range lidwd.RangeSansAnyExtraDot else m - | SynExpr.LongIdent (_, lidwd, _, _) -> lidwd.RangeSansAnyExtraDot - | SynExpr.DiscardAfterMissingQualificationAfterDot (expr, _) -> expr.Range - | SynExpr.Fixed (_, m) -> m - | SynExpr.Ident id -> id.idRange - - /// Attempt to get the range of the first token or initial portion only - this is extremely ad-hoc, just a cheap way to improve a certain 'query custom operation' error range - member e.RangeOfFirstPortion = - match e with - // haven't bothered making these cases better than just .Range - | SynExpr.Quote (range=m) - | SynExpr.Const (range=m) - | SynExpr.Typed (range=m) - | SynExpr.Tuple (range=m) - | SynExpr.ArrayOrList (range=m) - | SynExpr.AnonRecd (range=m) - | SynExpr.Record (range=m) - | SynExpr.New (range=m) - | SynExpr.ObjExpr (range=m) - | SynExpr.While (range=m) - | SynExpr.For (range=m) - | SynExpr.CompExpr (range=m) - | SynExpr.ArrayOrListOfSeqExpr (range=m) - | SynExpr.Lambda (range=m) - | SynExpr.Match (range=m) - | SynExpr.MatchLambda (range=m) - | SynExpr.Do (range=m) - | SynExpr.Assert (range=m) - | SynExpr.TypeApp (range=m) - | SynExpr.LetOrUse (range=m) - | SynExpr.TryWith (range=m) - | SynExpr.TryFinally (range=m) - | SynExpr.ArbitraryAfterError (range=m) - | SynExpr.FromParseError (range=m) - | SynExpr.DiscardAfterMissingQualificationAfterDot (range=m) - | SynExpr.IfThenElse (range=m) - | SynExpr.LongIdent (range=m) - | SynExpr.LongIdentSet (range=m) - | SynExpr.NamedIndexedPropertySet (range=m) - | SynExpr.DotIndexedGet (range=m) - | SynExpr.DotIndexedSet (range=m) - | SynExpr.DotGet (range=m) - | SynExpr.DotSet (range=m) - | SynExpr.Set (range=m) - | SynExpr.DotNamedIndexedPropertySet (range=m) - | SynExpr.LibraryOnlyUnionCaseFieldGet (range=m) - | SynExpr.LibraryOnlyUnionCaseFieldSet (range=m) - | SynExpr.LibraryOnlyILAssembly (range=m) - | SynExpr.LibraryOnlyStaticOptimization (range=m) - | SynExpr.TypeTest (range=m) - | SynExpr.Upcast (range=m) - | SynExpr.AddressOf (range=m) - | SynExpr.Downcast (range=m) - | SynExpr.JoinIn (range=m) - | SynExpr.InferredUpcast (range=m) - | SynExpr.InferredDowncast (range=m) - | SynExpr.Null (range=m) - | SynExpr.Lazy (range=m) - | SynExpr.TraitCall (range=m) - | SynExpr.ImplicitZero (range=m) - | SynExpr.YieldOrReturn (range=m) - | SynExpr.YieldOrReturnFrom (range=m) - | SynExpr.LetOrUseBang (range=m) - | SynExpr.MatchBang (range=m) - | SynExpr.DoBang (range=m) -> m - // these are better than just .Range, and also commonly applicable inside queries - | SynExpr.Paren(_, m, _, _) -> m - | SynExpr.Sequential (_, _, e1, _, _) - | SynExpr.App (_, _, e1, _, _) -> - e1.RangeOfFirstPortion - | SynExpr.ForEach (_, _, _, pat, _, _, r) -> - let start = r.Start - let e = (pat.Range: range).Start - mkRange r.FileName start e - | SynExpr.Ident id -> id.idRange - | SynExpr.Fixed (_, m) -> m - -and - [] - SynIndexerArg = - - | Two of SynExpr * SynExpr - - | One of SynExpr - - member x.Range = match x with Two (e1, e2) -> unionRanges e1.Range e2.Range | One e -> e.Range - - member x.Exprs = match x with Two (e1, e2) -> [e1;e2] | One e -> [e] - -and - [] - SynSimplePat = - - /// Id (ident, altNameRefCell, isCompilerGenerated, isThisVar, isOptArg, range) - /// - /// Indicates a simple pattern variable. - /// - /// altNameRefCell - /// Normally 'None' except for some compiler-generated variables in desugaring pattern matching. - /// Pattern processing sets this reference for hidden variable introduced by desugaring pattern matching in arguments. - /// The info indicates an alternative (compiler generated) identifier to be used because the name of the identifier is already bound. - /// See Product Studio FSharp 1.0, bug 6389. - /// - /// isCompilerGenerated: true if a compiler generated name - /// isThisVar: true if 'this' variable in member - /// isOptArg: true if a '?' is in front of the name - | Id of ident: Ident * altNameRefCell: SynSimplePatAlternativeIdInfo ref option * isCompilerGenerated: bool * isThisVar: bool * isOptArg: bool * range: range - - | Typed of SynSimplePat * SynType * range: range - - | Attrib of SynSimplePat * SynAttributes * range: range - -and SynSimplePatAlternativeIdInfo = - - /// We have not decided to use an alternative name in tha pattern and related expression - | Undecided of Ident - - /// We have decided to use an alternative name in tha pattern and related expression - | Decided of Ident - -and - [] - SynStaticOptimizationConstraint = - - | WhenTyparTyconEqualsTycon of SynTypar * SynType * range: range - - | WhenTyparIsStruct of SynTypar * range: range - -and - [] - /// Represents a simple set of variable bindings a, (a, b) or (a: Type, b: Type) at a lambda, - /// function definition or other binding point, after the elimination of pattern matching - /// from the construct, e.g. after changing a "function pat1 -> rule1 | ..." to a - /// "fun v -> match v with ..." - SynSimplePats = - - | SimplePats of SynSimplePat list * range: range - - | Typed of SynSimplePats * SynType * range: range - -and SynConstructorArgs = - | Pats of SynPat list - | NamePatPairs of (Ident * SynPat) list * range: range -and - [] - SynPat = - - | Const of SynConst * range: range - - | Wild of range: range - - | Named of SynPat * Ident * isSelfIdentifier: bool (* true if 'this' variable *) * accessibility: SynAccess option * range: range - - | Typed of SynPat * SynType * range: range - - | Attrib of SynPat * SynAttributes * range: range - - | Or of SynPat * SynPat * range: range - - | Ands of SynPat list * range: range - - | LongIdent of - longDotId: LongIdentWithDots * - Ident option * // holds additional ident for tooling - SynValTyparDecls option * // usually None: temporary used to parse "f<'a> x = x"*) - SynConstructorArgs * - accessibility: SynAccess option * - range: range - - | Tuple of isStruct: bool * SynPat list * range: range - - | Paren of SynPat * range: range - - | ArrayOrList of bool * SynPat list * range: range - - | Record of ((LongIdent * Ident) * SynPat) list * range: range - - /// 'null' - | Null of range: range - - /// '?id' -- for optional argument names - | OptionalVal of Ident * range: range - - /// ':? type ' - | IsInst of SynType * range: range - - /// <@ expr @>, used for active pattern arguments - | QuoteExpr of SynExpr * range: range - - /// Deprecated character range: ranges - | DeprecatedCharRange of char * char * range: range - - /// Used internally in the type checker - | InstanceMember of Ident * Ident * (* holds additional ident for tooling *) Ident option * accessibility: SynAccess option * range: range (* adhoc overloaded method/property *) - - /// A pattern arising from a parse error - | FromParseError of SynPat * range: range - - member p.Range = - match p with - | SynPat.Const (range=m) - | SynPat.Wild (range=m) - | SynPat.Named (range=m) - | SynPat.Or (range=m) - | SynPat.Ands (range=m) - | SynPat.LongIdent (range=m) - | SynPat.ArrayOrList (range=m) - | SynPat.Tuple (range=m) - | SynPat.Typed (range=m) - | SynPat.Attrib (range=m) - | SynPat.Record (range=m) - | SynPat.DeprecatedCharRange (range=m) - | SynPat.Null (range=m) - | SynPat.IsInst (range=m) - | SynPat.QuoteExpr (range=m) - | SynPat.InstanceMember (range=m) - | SynPat.OptionalVal (range=m) - | SynPat.Paren (range=m) - | SynPat.FromParseError (range=m) -> m - -and - [] - SynInterfaceImpl = - | InterfaceImpl of SynType * SynBinding list * range: range - -and - [] - SynMatchClause = - | Clause of SynPat * whenExpr: SynExpr option * SynExpr * range: range * SequencePointInfoForTarget - - member this.RangeOfGuardAndRhs = - match this with - | Clause(_, eo, e, _, _) -> - match eo with - | None -> e.Range - | Some x -> unionRanges e.Range x.Range - - member this.Range = - match this with - | Clause(_, eo, e, m, _) -> - match eo with - | None -> unionRanges e.Range m - | Some x -> unionRanges (unionRanges e.Range m) x.Range - -and SynAttributes = SynAttribute list - -and - [] - SynAttribute = - { TypeName: LongIdentWithDots - - ArgExpr: SynExpr - - /// Target specifier, e.g. "assembly", "module", etc. - Target: Ident option - - /// Is this attribute being applied to a property getter or setter? - AppliesToGetterAndSetter: bool - - Range: range } - -and - [] - SynValData = - | SynValData of MemberFlags option * SynValInfo * Ident option - -and - [] - SynBinding = - | Binding of - accessibility: SynAccess option * - kind: SynBindingKind * - mustInline: bool * - isMutable: bool * - attrs: SynAttributes * - xmlDoc: PreXmlDoc * - valData: SynValData * - headPat: SynPat * - returnInfo: SynBindingReturnInfo option * - expr: SynExpr * - range: range * - seqPoint: SequencePointInfoForBinding - - // no member just named "Range", as that would be confusing: - // - for everything else, the 'range' member that appears last/second-to-last is the 'full range' of the whole tree construct - // - but for Binding, the 'range' is only the range of the left-hand-side, the right-hand-side range is in the SynExpr - // - so we use explicit names to avoid confusion - member x.RangeOfBindingSansRhs = let (Binding(range=m)) = x in m - - member x.RangeOfBindingAndRhs = let (Binding(expr=e; range=m)) = x in unionRanges e.Range m - - member x.RangeOfHeadPat = let (Binding(headPat=headPat)) = x in headPat.Range - -and - [] - SynBindingReturnInfo = - | SynBindingReturnInfo of typeName: SynType * range: range * attributes: SynAttributes - - -and - [] - MemberFlags = - { IsInstance: bool - IsDispatchSlot: bool - IsOverrideOrExplicitImpl: bool - IsFinal: bool - MemberKind: MemberKind } - -/// Note the member kind is actually computed partially by a syntax tree transformation in tc.fs -and - [] - MemberKind = - - | ClassConstructor - - | Constructor - - | Member - - | PropertyGet - - | PropertySet - - /// An artificial member kind used prior to the point where a get/set property is split into two distinct members. - | PropertyGetSet - -and - [] - /// The untyped, unchecked syntax tree for a member signature, used in signature files, abstract member declarations - /// and member constraints. - SynMemberSig = - - | Member of SynValSig * MemberFlags * range: range - - | Interface of typeName: SynType * range: range - - | Inherit of typeName: SynType * range: range - - | ValField of SynField * range: range - - | NestedType of SynTypeDefnSig * range: range - -and SynMemberSigs = SynMemberSig list - -and - [] - SynTypeDefnKind = - | TyconUnspecified - | TyconClass - | TyconInterface - | TyconStruct - | TyconRecord - | TyconUnion - | TyconAbbrev - | TyconHiddenRepr - | TyconAugmentation - | TyconILAssemblyCode - | TyconDelegate of SynType * SynValInfo - -and - [] - /// The untyped, unchecked syntax tree for the core of a simple type definition, in either signature - /// or implementation. - SynTypeDefnSimpleRepr = - - /// A union type definition, type X = A | B - | Union of accessibility: SynAccess option * unionCases: SynUnionCases * range: range - - /// An enum type definition, type X = A = 1 | B = 2 - | Enum of SynEnumCases * range: range - - /// A record type definition, type X = { A: int; B: int } - | Record of accessibility: SynAccess option * recordFields: SynFields * range: range - - /// An object oriented type definition. This is not a parse-tree form, but represents the core - /// type representation which the type checker splits out from the "ObjectModel" cases of type definitions. - | General of SynTypeDefnKind * (SynType * range * Ident option) list * (SynValSig * MemberFlags) list * SynField list * bool * bool * SynSimplePat list option * range: range - - /// A type defined by using an IL assembly representation. Only used in FSharp.Core. - /// - /// F# syntax: "type X = (# "..."#) - | LibraryOnlyILAssembly of ILType * range: range - - /// A type abbreviation, "type X = A.B.C" - | TypeAbbrev of ParserDetail * SynType * range: range - - /// An abstract definition, "type X" - | None of range: range - - /// An exception definition, "exception E = ..." - | Exception of SynExceptionDefnRepr - - member this.Range = - match this with - | Union (range=m) - | Enum (range=m) - | Record (range=m) - | General (range=m) - | LibraryOnlyILAssembly (range=m) - | TypeAbbrev (range=m) - | None (range=m) -> m - | Exception t -> t.Range - -and SynEnumCases = SynEnumCase list - -and - [] - SynEnumCase = - - /// The untyped, unchecked syntax tree for one case in an enum definition. - | EnumCase of attrs: SynAttributes * ident: Ident * SynConst * PreXmlDoc * range: range - - member this.Range = - match this with - | EnumCase (range=m) -> m - -and SynUnionCases = SynUnionCase list - -and - [] - SynUnionCase = - - /// The untyped, unchecked syntax tree for one case in a union definition. - | UnionCase of SynAttributes * ident: Ident * SynUnionCaseType * PreXmlDoc * accessibility: SynAccess option * range: range - - member this.Range = - match this with - | UnionCase (range=m) -> m - -and - [] - /// The untyped, unchecked syntax tree for the right-hand-side of union definition, excluding members, - /// in either a signature or implementation. - SynUnionCaseType = - - /// Normal style declaration - | UnionCaseFields of cases: SynField list - - /// Full type spec given by 'UnionCase: ty1 * tyN -> rty'. Only used in FSharp.Core, otherwise a warning. - | UnionCaseFullType of (SynType * SynValInfo) - -and - [] - /// The untyped, unchecked syntax tree for the right-hand-side of a type definition in a signature. - /// Note: in practice, using a discriminated union to make a distinction between - /// "simple" types and "object oriented" types is not particularly useful. - SynTypeDefnSigRepr = - - /// Indicates the right right-hand-side is a class, struct, interface or other object-model type - | ObjectModel of SynTypeDefnKind * memberSigs: SynMemberSigs * range: range - - /// Indicates the right right-hand-side is a record, union or other simple type. - | Simple of SynTypeDefnSimpleRepr * range: range - - | Exception of SynExceptionDefnRepr - - member this.Range = - match this with - | ObjectModel (range=m) - | Simple (range=m) -> m - | Exception e -> e.Range - -and - [] - /// The untyped, unchecked syntax tree for a type definition in a signature - SynTypeDefnSig = - - /// The information for a type definition in a signature - | TypeDefnSig of SynComponentInfo * SynTypeDefnSigRepr * SynMemberSigs * range: range - -and SynFields = SynField list - -and - [] - /// The untyped, unchecked syntax tree for a field declaration in a record or class - SynField = - | Field of attrs: SynAttributes * isStatic: bool * Ident option * SynType * isMutable: bool * xmlDoc: PreXmlDoc * accessibility: SynAccess option * range: range - -and - [] - /// The untyped, unchecked syntax tree associated with the name of a type definition or module - /// in signature or implementation. - /// - /// This includes the name, attributes, type parameters, constraints, documentation and accessibility - /// for a type definition or module. For modules, entries such as the type parameters are - /// always empty. - SynComponentInfo = - | ComponentInfo of attribs: SynAttributes * typeParams: SynTyparDecl list * constraints: SynTypeConstraint list * longId: LongIdent * xmlDoc: PreXmlDoc * preferPostfix: bool * accessibility: SynAccess option * range: range - - member this.Range = - match this with - | ComponentInfo (range=m) -> m - -and - [] - SynValSig = - | ValSpfn of - synAttributes: SynAttributes * - ident: Ident * - explicitValDecls: SynValTyparDecls * - synType: SynType * - arity: SynValInfo * - isInline: bool * - isMutable: bool * - xmlDoc: PreXmlDoc * - accessibility: SynAccess option * - synExpr: SynExpr option * - range: range - - member x.RangeOfId = let (ValSpfn(ident=id)) = x in id.idRange - - member x.SynInfo = let (ValSpfn(arity=v)) = x in v - - member x.SynType = let (ValSpfn(synType=ty)) = x in ty - -/// The argument names and other metadata for a member or function -and - [] - SynValInfo = - - /// SynValInfo(curriedArgInfos, returnInfo) - | SynValInfo of SynArgInfo list list * SynArgInfo - - member x.ArgInfos = (let (SynValInfo(args, _)) = x in args) - -/// The argument names and other metadata for a parameter for a member or function -and - [] - SynArgInfo = - - | SynArgInfo of SynAttributes * optional: bool * Ident option - -/// The names and other metadata for the type parameters for a member or function -and - [] - SynValTyparDecls = - - | SynValTyparDecls of SynTyparDecl list * bool * constraints: SynTypeConstraint list - -/// 'exception E = ... ' -and [] - SynExceptionDefnRepr = - - | SynExceptionDefnRepr of SynAttributes * SynUnionCase * longId: LongIdent option * xmlDoc: PreXmlDoc * accessiblity: SynAccess option * range: range - - member this.Range = match this with SynExceptionDefnRepr (range=m) -> m - -/// 'exception E = ... with ...' -and - [] - SynExceptionDefn = - - | SynExceptionDefn of SynExceptionDefnRepr * SynMemberDefns * range: range - - member this.Range = - match this with - | SynExceptionDefn (range=m) -> m - -and - [] - SynTypeDefnRepr = - - | ObjectModel of SynTypeDefnKind * SynMemberDefns * range: range - - | Simple of SynTypeDefnSimpleRepr * range: range - - | Exception of SynExceptionDefnRepr - - member this.Range = - match this with - | ObjectModel (range=m) - | Simple (range=m) -> m - | Exception t -> t.Range - -and - [] - SynTypeDefn = - | TypeDefn of SynComponentInfo * SynTypeDefnRepr * members: SynMemberDefns * range: range - member this.Range = - match this with - | TypeDefn (range=m) -> m - -and - [] - SynMemberDefn = - - | Open of longId: LongIdent * range: range - - | Member of memberDefn: SynBinding * range: range - - /// implicit ctor args as a defn line, 'as' specification - | ImplicitCtor of accessiblity: SynAccess option * attributes: SynAttributes * ctorArgs: SynSimplePat list * selfIdentifier: Ident option * range: range - - /// inherit (args...) as base - | ImplicitInherit of inheritType: SynType * inheritArgs: SynExpr * inheritAlias: Ident option * range: range - - /// LetBindings(bindingList, isStatic, isRecursive, wholeRange) - /// - /// localDefns - | LetBindings of SynBinding list * isStatic: bool * isRecursive: bool * range: range - - | AbstractSlot of SynValSig * MemberFlags * range: range - - | Interface of SynType * SynMemberDefns option * range: range - - | Inherit of SynType * Ident option * range: range - - | ValField of SynField * range: range - - /// A feature that is not implemented - | NestedType of typeDefn: SynTypeDefn * accessibility: SynAccess option * range: range - - /// SynMemberDefn.AutoProperty (attribs, isStatic, id, tyOpt, propKind, memberFlags, xmlDoc, access, synExpr, mGetSet, mWholeAutoProp). - /// - /// F# syntax: 'member val X = expr' - | AutoProperty of - attribs: SynAttributes * - isStatic: bool * - ident: Ident * - typeOpt: SynType option * - propKind: MemberKind * - memberFlags:(MemberKind -> MemberFlags) * - xmlDoc: PreXmlDoc * - accessiblity: SynAccess option * - synExpr: SynExpr * - getSetRange: range option * - range: range - - member d.Range = - match d with - | SynMemberDefn.Member (range=m) - | SynMemberDefn.Interface (range=m) - | SynMemberDefn.Open (range=m) - | SynMemberDefn.LetBindings (range=m) - | SynMemberDefn.ImplicitCtor (range=m) - | SynMemberDefn.ImplicitInherit (range=m) - | SynMemberDefn.AbstractSlot (range=m) - | SynMemberDefn.Inherit (range=m) - | SynMemberDefn.ValField (range=m) - | SynMemberDefn.AutoProperty (range=m) - | SynMemberDefn.NestedType (range=m) -> m - -and SynMemberDefns = SynMemberDefn list - -and - [] - SynModuleDecl = - | ModuleAbbrev of ident: Ident * longId: LongIdent * range: range - | NestedModule of SynComponentInfo * isRecursive: bool * SynModuleDecls * bool * range: range - | Let of isRecursive: bool * SynBinding list * range: range - | DoExpr of SequencePointInfoForBinding * SynExpr * range: range - | Types of SynTypeDefn list * range: range - | Exception of SynExceptionDefn * range: range - | Open of longDotId: LongIdentWithDots * range: range - | Attributes of SynAttributes * range: range - | HashDirective of ParsedHashDirective * range: range - | NamespaceFragment of SynModuleOrNamespace - member d.Range = - match d with - | SynModuleDecl.ModuleAbbrev (range=m) - | SynModuleDecl.NestedModule (range=m) - | SynModuleDecl.Let (range=m) - | SynModuleDecl.DoExpr (range=m) - | SynModuleDecl.Types (range=m) - | SynModuleDecl.Exception (range=m) - | SynModuleDecl.Open (range=m) - | SynModuleDecl.HashDirective (range=m) - | SynModuleDecl.NamespaceFragment (SynModuleOrNamespace (range=m)) - | SynModuleDecl.Attributes (range=m) -> m - -and SynModuleDecls = SynModuleDecl list - -and - [] - SynExceptionSig = - | SynExceptionSig of SynExceptionDefnRepr * SynMemberSigs * range: range - -and - [] - SynModuleSigDecl = - | ModuleAbbrev of ident: Ident * longId: LongIdent * range: range - | NestedModule of SynComponentInfo * isRecursive: bool * SynModuleSigDecls * range: range - | Val of SynValSig * range: range - | Types of SynTypeDefnSig list * range: range - | Exception of SynExceptionSig * range: range - | Open of longId: LongIdent * range: range - | HashDirective of ParsedHashDirective * range: range - | NamespaceFragment of SynModuleOrNamespaceSig - - member d.Range = - match d with - | SynModuleSigDecl.ModuleAbbrev (range=m) - | SynModuleSigDecl.NestedModule (range=m) - | SynModuleSigDecl.Val (range=m) - | SynModuleSigDecl.Types (range=m) - | SynModuleSigDecl.Exception (range=m) - | SynModuleSigDecl.Open (range=m) - | SynModuleSigDecl.NamespaceFragment (SynModuleOrNamespaceSig(range=m)) - | SynModuleSigDecl.HashDirective (range=m) -> m - -and SynModuleSigDecls = SynModuleSigDecl list - -and - [] - SynModuleOrNamespaceKind = - | NamedModule - | AnonModule - | DeclaredNamespace - | GlobalNamespace - - member x.IsModule = - match x with - | NamedModule | AnonModule -> true - | _ -> false - -and - [] - SynModuleOrNamespace = - | SynModuleOrNamespace of longId: LongIdent * isRecursive: bool * kind: SynModuleOrNamespaceKind * decls: SynModuleDecls * xmlDoc: PreXmlDoc * attribs: SynAttributes * accessibility: SynAccess option * range: range - member this.Range = - match this with - | SynModuleOrNamespace (range=m) -> m - -and - [] - SynModuleOrNamespaceSig = - | SynModuleOrNamespaceSig of longId: LongIdent * isRecursive: bool * kind: SynModuleOrNamespaceKind * SynModuleSigDecls * xmlDoc: PreXmlDoc * attribs: SynAttributes * accessibility: SynAccess option * range: range - -and [] - ParsedHashDirective = - | ParsedHashDirective of string * string list * range: range - -[] -type ParsedImplFileFragment = - | AnonModule of SynModuleDecls * range: range - | NamedModule of SynModuleOrNamespace - | NamespaceFragment of longId: LongIdent * bool * SynModuleOrNamespaceKind * SynModuleDecls * xmlDoc: PreXmlDoc * SynAttributes * range: range - -[] -type ParsedSigFileFragment = - | AnonModule of SynModuleSigDecls * range: range - | NamedModule of SynModuleOrNamespaceSig - | NamespaceFragment of longId: LongIdent * bool * SynModuleOrNamespaceKind * SynModuleSigDecls * xmlDoc: PreXmlDoc * SynAttributes * range: range - -[] -type ParsedFsiInteraction = - | IDefns of SynModuleDecl list * range: range - | IHash of ParsedHashDirective * range: range - -[] -type ParsedImplFile = - | ParsedImplFile of hashDirectives: ParsedHashDirective list * ParsedImplFileFragment list - -[] -type ParsedSigFile = - | ParsedSigFile of hashDirectives: ParsedHashDirective list * ParsedSigFileFragment list - -//---------------------------------------------------------------------- -// AST and parsing utilities. -//---------------------------------------------------------------------- - -let ident (s, r) = new Ident(s, r) -let textOfId (id: Ident) = id.idText -let pathOfLid lid = List.map textOfId lid -let arrPathOfLid lid = Array.ofList (pathOfLid lid) -let textOfPath path = String.concat "." path -let textOfLid lid = textOfPath (pathOfLid lid) - -let rangeOfLid (lid: Ident list) = - match lid with - | [] -> failwith "rangeOfLid" - | [id] -> id.idRange - | h::t -> unionRanges h.idRange (List.last t).idRange - -[] -type ScopedPragma = - | WarningOff of range: range * int - // Note: this type may be extended in the future with optimization on/off switches etc. - -// These are the results of parsing + folding in the implicit file name -/// ImplFile(modname, isScript, qualName, hashDirectives, modules, isLastCompiland) - -/// QualifiedNameOfFile acts to fully-qualify module specifications and implementations, -/// most importantly the ones that simply contribute fragments to a namespace (i.e. the ParsedSigFileFragment.NamespaceFragment case) -/// There may be multiple such fragments in a single assembly. There may thus also -/// be multiple matching pairs of these in an assembly, all contributing types to the same -/// namespace. -[] -type QualifiedNameOfFile = - | QualifiedNameOfFile of Ident - member x.Text = (let (QualifiedNameOfFile t) = x in t.idText) - member x.Id = (let (QualifiedNameOfFile t) = x in t) - member x.Range = (let (QualifiedNameOfFile t) = x in t.idRange) - -[] -type ParsedImplFileInput = - | ParsedImplFileInput of - fileName: string * - isScript: bool * - qualifiedNameOfFile: QualifiedNameOfFile * - scopedPragmas: ScopedPragma list * - hashDirectives: ParsedHashDirective list * - modules: SynModuleOrNamespace list * - isLastCompiland: (bool * bool) - -[] -type ParsedSigFileInput = - | ParsedSigFileInput of - fileName: string * - qualifiedNameOfFile: QualifiedNameOfFile * - scopedPragmas: ScopedPragma list * - hashDirectives: ParsedHashDirective list * - modules: SynModuleOrNamespaceSig list - -[] -type ParsedInput = - | ImplFile of ParsedImplFileInput - | SigFile of ParsedSigFileInput - - member inp.Range = - match inp with - | ParsedInput.ImplFile (ParsedImplFileInput (modules=SynModuleOrNamespace(range=m) :: _)) - | ParsedInput.SigFile (ParsedSigFileInput (modules=SynModuleOrNamespaceSig(range=m) :: _)) -> m - | ParsedInput.ImplFile (ParsedImplFileInput (fileName=filename)) - | ParsedInput.SigFile (ParsedSigFileInput (fileName=filename)) -> -#if DEBUG - assert("" = "compiler expects ParsedInput.ImplFile and ParsedInput.SigFile to have at least one fragment, 4488") -#endif - rangeN filename 0 (* There are no implementations, e.g. due to errors, so return a default range for the file *) - - -//---------------------------------------------------------------------- -// Construct syntactic AST nodes -//----------------------------------------------------------------------- - -// REVIEW: get rid of this global state -type SynArgNameGenerator() = - let mutable count = 0 - let generatedArgNamePrefix = "_arg" - - member __.New() : string = count <- count + 1; generatedArgNamePrefix + string count - member __.Reset() = count <- 0 - -//---------------------------------------------------------------------- -// Construct syntactic AST nodes -//----------------------------------------------------------------------- - - -let mkSynId m s = Ident(s, m) -let pathToSynLid m p = List.map (mkSynId m) p -let mkSynIdGet m n = SynExpr.Ident(mkSynId m n) -let mkSynLidGet m path n = - let lid = pathToSynLid m path @ [mkSynId m n] - let dots = List.replicate (lid.Length - 1) m - SynExpr.LongIdent(false, LongIdentWithDots(lid, dots), None, m) -let mkSynIdGetWithAlt m id altInfo = - match altInfo with - | None -> SynExpr.Ident id - | _ -> SynExpr.LongIdent(false, LongIdentWithDots([id], []), altInfo, m) - -let mkSynSimplePatVar isOpt id = SynSimplePat.Id (id, None, false, false, isOpt, id.idRange) -let mkSynCompGenSimplePatVar id = SynSimplePat.Id (id, None, true, false, false, id.idRange) - -/// Match a long identifier, including the case for single identifiers which gets a more optimized node in the syntax tree. -let (|LongOrSingleIdent|_|) inp = - match inp with - | SynExpr.LongIdent(isOpt, lidwd, altId, _m) -> Some (isOpt, lidwd, altId, lidwd.RangeSansAnyExtraDot) - | SynExpr.Ident id -> Some (false, LongIdentWithDots([id], []), None, id.idRange) - | _ -> None - -let (|SingleIdent|_|) inp = - match inp with - | SynExpr.LongIdent(false, LongIdentWithDots([id], _), None, _) -> Some id - | SynExpr.Ident id -> Some id - | _ -> None - -/// This affects placement of sequence points -let rec IsControlFlowExpression e = - match e with - | SynExpr.ObjExpr _ - | SynExpr.Lambda _ - | SynExpr.LetOrUse _ - | SynExpr.Sequential _ - // Treat "ident { ... }" as a control flow expression - | SynExpr.App (_, _, SynExpr.Ident _, SynExpr.CompExpr _, _) - | SynExpr.IfThenElse _ - | SynExpr.LetOrUseBang _ - | SynExpr.Match _ - | SynExpr.TryWith _ - | SynExpr.TryFinally _ - | SynExpr.For _ - | SynExpr.ForEach _ - | SynExpr.While _ -> true - | SynExpr.Typed(e, _, _) -> IsControlFlowExpression e - | _ -> false - -let mkAnonField (ty: SynType) = Field([], false, None, ty, false, PreXmlDoc.Empty, None, ty.Range) -let mkNamedField (ident, ty: SynType) = Field([], false, Some ident, ty, false, PreXmlDoc.Empty, None, ty.Range) - -let mkSynPatVar vis (id: Ident) = SynPat.Named (SynPat.Wild id.idRange, id, false, vis, id.idRange) -let mkSynThisPatVar (id: Ident) = SynPat.Named (SynPat.Wild id.idRange, id, true, None, id.idRange) -let mkSynPatMaybeVar lidwd vis m = SynPat.LongIdent (lidwd, None, None, SynConstructorArgs.Pats [], vis, m) - -/// Extract the argument for patterns corresponding to the declaration of 'new ... = ...' -let (|SynPatForConstructorDecl|_|) x = - match x with - | SynPat.LongIdent (LongIdentWithDots([_], _), _, _, SynConstructorArgs.Pats [arg], _, _) -> Some arg - | _ -> None - -/// Recognize the '()' in 'new()' -let (|SynPatForNullaryArgs|_|) x = - match x with - | SynPat.Paren(SynPat.Const(SynConst.Unit, _), _) -> Some() - | _ -> None - -let (|SynExprErrorSkip|) (p: SynExpr) = - match p with - | SynExpr.FromParseError(p, _) -> p - | _ -> p - -let (|SynExprParen|_|) (e: SynExpr) = - match e with - | SynExpr.Paren(SynExprErrorSkip e, a, b, c) -> Some (e, a, b, c) - | _ -> None - -let (|SynPatErrorSkip|) (p: SynPat) = - match p with - | SynPat.FromParseError(p, _) -> p - | _ -> p - -/// Push non-simple parts of a patten match over onto the r.h.s. of a lambda. -/// Return a simple pattern and a function to build a match on the r.h.s. if the pattern is complex -let rec SimplePatOfPat (synArgNameGenerator: SynArgNameGenerator) p = - match p with - | SynPat.Typed(p', ty, m) -> - let p2, laterf = SimplePatOfPat synArgNameGenerator p' - SynSimplePat.Typed(p2, ty, m), - laterf - | SynPat.Attrib(p', attribs, m) -> - let p2, laterf = SimplePatOfPat synArgNameGenerator p' - SynSimplePat.Attrib(p2, attribs, m), - laterf - | SynPat.Named (SynPat.Wild _, v, thisv, _, m) -> - SynSimplePat.Id (v, None, false, thisv, false, m), - None - | SynPat.OptionalVal (v, m) -> - SynSimplePat.Id (v, None, false, false, true, m), - None - | SynPat.Paren (p, _) -> SimplePatOfPat synArgNameGenerator p - | SynPat.FromParseError (p, _) -> SimplePatOfPat synArgNameGenerator p - | _ -> - let m = p.Range - let isCompGen, altNameRefCell, id, item = - match p with - | SynPat.LongIdent(LongIdentWithDots([id], _), _, None, SynConstructorArgs.Pats [], None, _) -> - // The pattern is 'V' or some other capitalized identifier. - // It may be a real variable, in which case we want to maintain its name. - // But it may also be a nullary union case or some other identifier. - // In this case, we want to use an alternate compiler generated name for the hidden variable. - let altNameRefCell = Some (ref (Undecided (mkSynId m (synArgNameGenerator.New())))) - let item = mkSynIdGetWithAlt m id altNameRefCell - false, altNameRefCell, id, item - | _ -> - let nm = synArgNameGenerator.New() - let id = mkSynId m nm - let item = mkSynIdGet m nm - true, None, id, item - SynSimplePat.Id (id, altNameRefCell, isCompGen, false, false, id.idRange), - Some (fun e -> - let clause = Clause(p, None, e, m, SuppressSequencePointAtTarget) - SynExpr.Match(NoSequencePointAtInvisibleBinding, item, [clause], clause.Range)) - -let appFunOpt funOpt x = match funOpt with None -> x | Some f -> f x -let composeFunOpt funOpt1 funOpt2 = match funOpt2 with None -> funOpt1 | Some f -> Some (fun x -> appFunOpt funOpt1 (f x)) -let rec SimplePatsOfPat synArgNameGenerator p = - match p with - | SynPat.FromParseError (p, _) -> SimplePatsOfPat synArgNameGenerator p - | SynPat.Typed(p', ty, m) -> - let p2, laterf = SimplePatsOfPat synArgNameGenerator p' - SynSimplePats.Typed(p2, ty, m), - laterf -// | SynPat.Paren (p, m) -> SimplePatsOfPat synArgNameGenerator p - | SynPat.Tuple (false, ps, m) - | SynPat.Paren(SynPat.Tuple (false, ps, m), _) -> - let ps2, laterf = - List.foldBack - (fun (p', rhsf) (ps', rhsf') -> - p'::ps', - (composeFunOpt rhsf rhsf')) - (List.map (SimplePatOfPat synArgNameGenerator) ps) - ([], None) - SynSimplePats.SimplePats (ps2, m), - laterf - | SynPat.Paren(SynPat.Const (SynConst.Unit, m), _) - | SynPat.Const (SynConst.Unit, m) -> - SynSimplePats.SimplePats ([], m), - None - | _ -> - let m = p.Range - let sp, laterf = SimplePatOfPat synArgNameGenerator p - SynSimplePats.SimplePats ([sp], m), laterf - -let PushPatternToExpr synArgNameGenerator isMember pat (rhs: SynExpr) = - let nowpats, laterf = SimplePatsOfPat synArgNameGenerator pat - nowpats, SynExpr.Lambda (isMember, false, nowpats, appFunOpt laterf rhs, rhs.Range) - -let private isSimplePattern pat = - let _nowpats, laterf = SimplePatsOfPat (SynArgNameGenerator()) pat - Option.isNone laterf - -/// "fun (UnionCase x) (UnionCase y) -> body" -/// ==> -/// "fun tmp1 tmp2 -> -/// let (UnionCase x) = tmp1 in -/// let (UnionCase y) = tmp2 in -/// body" -let PushCurriedPatternsToExpr synArgNameGenerator wholem isMember pats rhs = - // Two phases - // First phase: Fold back, from right to left, pushing patterns into r.h.s. expr - let spatsl, rhs = - (pats, ([], rhs)) - ||> List.foldBack (fun arg (spatsl, body) -> - let spats, bodyf = SimplePatsOfPat synArgNameGenerator arg - // accumulate the body. This builds "let (UnionCase y) = tmp2 in body" - let body = appFunOpt bodyf body - // accumulate the patterns - let spatsl = spats::spatsl - (spatsl, body)) - // Second phase: build lambdas. Mark subsequent ones with "true" indicating they are part of an iterated sequence of lambdas - let expr = - match spatsl with - | [] -> rhs - | h::t -> - let expr = List.foldBack (fun spats e -> SynExpr.Lambda (isMember, true, spats, e, wholem)) t rhs - let expr = SynExpr.Lambda (isMember, false, h, expr, wholem) - expr - spatsl, expr - -/// Helper for parsing the inline IL fragments. -#if NO_INLINE_IL_PARSER -let ParseAssemblyCodeInstructions _s m = - errorR(Error((193, "Inline IL not valid in a hosted environment"), m)) - [| |] -#else -let ParseAssemblyCodeInstructions s m = - try FSharp.Compiler.AbstractIL.Internal.AsciiParser.ilInstrs - FSharp.Compiler.AbstractIL.Internal.AsciiLexer.token - (UnicodeLexing.StringAsLexbuf s) - with RecoverableParseError -> - errorR(Error(FSComp.SR.astParseEmbeddedILError(), m)); [| |] -#endif - - -/// Helper for parsing the inline IL fragments. -#if NO_INLINE_IL_PARSER -let ParseAssemblyCodeType _s m = - errorR(Error((193, "Inline IL not valid in a hosted environment"), m)) - IL.EcmaMscorlibILGlobals.typ_Object -#else -let ParseAssemblyCodeType s m = - try FSharp.Compiler.AbstractIL.Internal.AsciiParser.ilType - FSharp.Compiler.AbstractIL.Internal.AsciiLexer.token - (UnicodeLexing.StringAsLexbuf s) - with RecoverableParseError -> - errorR(Error(FSComp.SR.astParseEmbeddedILTypeError(), m)); - IL.EcmaMscorlibILGlobals.typ_Object -#endif - -//------------------------------------------------------------------------ -// AST constructors -//------------------------------------------------------------------------ - -let opNameParenGet = CompileOpName parenGet -let opNameQMark = CompileOpName qmark -let mkSynOperator opm oper = mkSynIdGet opm (CompileOpName oper) - -let mkSynInfix opm (l: SynExpr) oper (r: SynExpr) = - let firstTwoRange = unionRanges l.Range opm - let wholeRange = unionRanges l.Range r.Range - SynExpr.App (ExprAtomicFlag.NonAtomic, false, SynExpr.App (ExprAtomicFlag.NonAtomic, true, mkSynOperator opm oper, l, firstTwoRange), r, wholeRange) - -let mkSynBifix m oper x1 x2 = - SynExpr.App (ExprAtomicFlag.NonAtomic, false, SynExpr.App (ExprAtomicFlag.NonAtomic, true, mkSynOperator m oper, x1, m), x2, m) - -let mkSynTrifix m oper x1 x2 x3 = - SynExpr.App (ExprAtomicFlag.NonAtomic, false, SynExpr.App (ExprAtomicFlag.NonAtomic, false, SynExpr.App (ExprAtomicFlag.NonAtomic, true, mkSynOperator m oper, x1, m), x2, m), x3, m) - -let mkSynPrefixPrim opm m oper x = - SynExpr.App (ExprAtomicFlag.NonAtomic, false, mkSynOperator opm oper, x, m) - -let mkSynPrefix opm m oper x = - if oper = "~&" then - SynExpr.AddressOf(true, x, opm, m) - elif oper = "~&&" then - SynExpr.AddressOf(false, x, opm, m) - else - mkSynPrefixPrim opm m oper x - -let mkSynCaseName m n = [mkSynId m (CompileOpName n)] - -let mkSynApp1 f x1 m = SynExpr.App(ExprAtomicFlag.NonAtomic, false, f, x1, m) -let mkSynApp2 f x1 x2 m = mkSynApp1 (mkSynApp1 f x1 m) x2 m -let mkSynApp3 f x1 x2 x3 m = mkSynApp1 (mkSynApp2 f x1 x2 m) x3 m -let mkSynApp4 f x1 x2 x3 x4 m = mkSynApp1 (mkSynApp3 f x1 x2 x3 m) x4 m -let mkSynApp5 f x1 x2 x3 x4 x5 m = mkSynApp1 (mkSynApp4 f x1 x2 x3 x4 m) x5 m -let mkSynDotParenSet m a b c = mkSynTrifix m parenSet a b c -let mkSynDotBrackGet m mDot a b = SynExpr.DotIndexedGet(a, [SynIndexerArg.One b], mDot, m) -let mkSynQMarkSet m a b c = mkSynTrifix m qmarkSet a b c -let mkSynDotBrackSliceGet m mDot arr sliceArg = SynExpr.DotIndexedGet(arr, [sliceArg], mDot, m) - -let mkSynDotBrackSeqSliceGet m mDot arr (argslist: list) = - let notsliced=[ for arg in argslist do - match arg with - | SynIndexerArg.One x -> yield x - | _ -> () ] - if notsliced.Length = argslist.Length then - SynExpr.DotIndexedGet(arr, [SynIndexerArg.One (SynExpr.Tuple(false, notsliced, [], unionRanges (List.head notsliced).Range (List.last notsliced).Range))], mDot, m) - else - SynExpr.DotIndexedGet(arr, argslist, mDot, m) - -let mkSynDotParenGet lhsm dotm a b = - match b with - | SynExpr.Tuple (false, [_;_], _, _) -> errorR(Deprecated(FSComp.SR.astDeprecatedIndexerNotation(), lhsm)) ; SynExpr.Const(SynConst.Unit, lhsm) - | SynExpr.Tuple (false, [_;_;_], _, _) -> errorR(Deprecated(FSComp.SR.astDeprecatedIndexerNotation(), lhsm)) ; SynExpr.Const(SynConst.Unit, lhsm) - | _ -> mkSynInfix dotm a parenGet b - -let mkSynUnit m = SynExpr.Const(SynConst.Unit, m) -let mkSynUnitPat m = SynPat.Const(SynConst.Unit, m) -let mkSynDelay m e = SynExpr.Lambda (false, false, SynSimplePats.SimplePats ([mkSynCompGenSimplePatVar (mkSynId m "unitVar")], m), e, m) - -let mkSynAssign (l: SynExpr) (r: SynExpr) = - let m = unionRanges l.Range r.Range - match l with - //| SynExpr.Paren(l2, m2) -> mkSynAssign m l2 r - | LongOrSingleIdent(false, v, None, _) -> SynExpr.LongIdentSet (v, r, m) - | SynExpr.DotGet(e, _, v, _) -> SynExpr.DotSet (e, v, r, m) - | SynExpr.DotIndexedGet(e1, e2, mDot, mLeft) -> SynExpr.DotIndexedSet (e1, e2, r, mLeft, mDot, m) - | SynExpr.LibraryOnlyUnionCaseFieldGet (x, y, z, _) -> SynExpr.LibraryOnlyUnionCaseFieldSet (x, y, z, r, m) - | SynExpr.App (_, _, SynExpr.App(_, _, SingleIdent(nm), a, _), b, _) when nm.idText = opNameQMark -> - mkSynQMarkSet m a b r - | SynExpr.App (_, _, SynExpr.App(_, _, SingleIdent(nm), a, _), b, _) when nm.idText = opNameParenGet -> - mkSynDotParenSet m a b r - | SynExpr.App (_, _, SynExpr.LongIdent(false, v, None, _), x, _) -> SynExpr.NamedIndexedPropertySet (v, x, r, m) - | SynExpr.App (_, _, SynExpr.DotGet(e, _, v, _), x, _) -> SynExpr.DotNamedIndexedPropertySet (e, v, x, r, m) - | l -> SynExpr.Set (l, r, m) - //| _ -> errorR(Error(FSComp.SR.astInvalidExprLeftHandOfAssignment(), m)); l // return just the LHS, so the typechecker can see it and capture expression typings that may be useful for dot lookups - -let rec mkSynDot dotm m l r = - match l with - | SynExpr.LongIdent(isOpt, LongIdentWithDots(lid, dots), None, _) -> - SynExpr.LongIdent(isOpt, LongIdentWithDots(lid@[r], dots@[dotm]), None, m) // REVIEW: MEMORY PERFORMANCE: This list operation is memory intensive (we create a lot of these list nodes) - an ImmutableArray would be better here - | SynExpr.Ident id -> - SynExpr.LongIdent(false, LongIdentWithDots([id;r], [dotm]), None, m) - | SynExpr.DotGet(e, dm, LongIdentWithDots(lid, dots), _) -> - SynExpr.DotGet(e, dm, LongIdentWithDots(lid@[r], dots@[dotm]), m)// REVIEW: MEMORY PERFORMANCE: This is memory intensive (we create a lot of these list nodes) - an ImmutableArray would be better here - | expr -> - SynExpr.DotGet(expr, dotm, LongIdentWithDots([r], []), m) - -let rec mkSynDotMissing dotm m l = - match l with - | SynExpr.LongIdent(isOpt, LongIdentWithDots(lid, dots), None, _) -> - SynExpr.LongIdent(isOpt, LongIdentWithDots(lid, dots@[dotm]), None, m) // REVIEW: MEMORY PERFORMANCE: This list operation is memory intensive (we create a lot of these list nodes) - an ImmutableArray would be better here - | SynExpr.Ident id -> - SynExpr.LongIdent(false, LongIdentWithDots([id], [dotm]), None, m) - | SynExpr.DotGet(e, dm, LongIdentWithDots(lid, dots), _) -> - SynExpr.DotGet(e, dm, LongIdentWithDots(lid, dots@[dotm]), m)// REVIEW: MEMORY PERFORMANCE: This is memory intensive (we create a lot of these list nodes) - an ImmutableArray would be better here - | expr -> - SynExpr.DiscardAfterMissingQualificationAfterDot(expr, m) - -let mkSynFunMatchLambdas synArgNameGenerator isMember wholem ps e = - let _, e = PushCurriedPatternsToExpr synArgNameGenerator wholem isMember ps e - e - - -// error recovery - the contract is that these expressions can only be produced if an error has already been reported -// (as a result, future checking may choose not to report errors involving these, to prevent noisy cascade errors) -let arbExpr(debugStr, range: range) = SynExpr.ArbitraryAfterError(debugStr, range.MakeSynthetic()) -type SynExpr with - member this.IsArbExprAndThusAlreadyReportedError = - match this with - | SynExpr.ArbitraryAfterError _ -> true - | _ -> false - -/// The syntactic elements associated with the "return" of a function or method. Some of this is -/// mostly dummy information to make the return element look like an argument, -/// the important thing is that (a) you can give a return type for the function or method, and -/// (b) you can associate .NET attributes to return of a function or method and these get stored in .NET metadata. -type SynReturnInfo = SynReturnInfo of (SynType * SynArgInfo) * range: range - - -/// Operations related to the syntactic analysis of arguments of value, function and member definitions and signatures. -/// -/// Function and member definitions have strongly syntactically constrained arities. We infer -/// the arity from the syntax. -/// -/// For example, we record the arity for: -/// StaticProperty --> [1] -- for unit arg -/// this.InstanceProperty --> [1;1] -- for unit arg -/// StaticMethod(args) --> map InferSynArgInfoFromSimplePat args -/// this.InstanceMethod() --> 1 :: map InferSynArgInfoFromSimplePat args -/// this.InstanceProperty with get(argpat) --> 1 :: [InferSynArgInfoFromSimplePat argpat] -/// StaticProperty with get(argpat) --> [InferSynArgInfoFromSimplePat argpat] -/// this.InstanceProperty with get() --> 1 :: [InferSynArgInfoFromSimplePat argpat] -/// StaticProperty with get() --> [InferSynArgInfoFromSimplePat argpat] -/// -/// this.InstanceProperty with set(argpat)(v) --> 1 :: [InferSynArgInfoFromSimplePat argpat; 1] -/// StaticProperty with set(argpat)(v) --> [InferSynArgInfoFromSimplePat argpat; 1] -/// this.InstanceProperty with set(v) --> 1 :: [1] -/// StaticProperty with set(v) --> [1] -module SynInfo = - /// The argument information for an argument without a name - let unnamedTopArg1 = SynArgInfo([], false, None) - - /// The argument information for a curried argument without a name - let unnamedTopArg = [unnamedTopArg1] - - /// The argument information for a '()' argument - let unitArgData = unnamedTopArg - - /// The 'argument' information for a return value where no attributes are given for the return value (the normal case) - let unnamedRetVal = SynArgInfo([], false, None) - - /// The 'argument' information for the 'this'/'self' parameter in the cases where it is not given explicitly - let selfMetadata = unnamedTopArg - - /// Determine if a syntactic information represents a member without arguments (which is implicitly a property getter) - let HasNoArgs (SynValInfo(args, _)) = isNil args - - /// Check if one particular argument is an optional argument. Used when adjusting the - /// types of optional arguments for function and member signatures. - let IsOptionalArg (SynArgInfo(_, isOpt, _)) = isOpt - - /// Check if there are any optional arguments in the syntactic argument information. Used when adjusting the - /// types of optional arguments for function and member signatures. - let HasOptionalArgs (SynValInfo(args, _)) = List.exists (List.exists IsOptionalArg) args - - /// Add a parameter entry to the syntactic value information to represent the '()' argument to a property getter. This is - /// used for the implicit '()' argument in property getter signature specifications. - let IncorporateEmptyTupledArgForPropertyGetter (SynValInfo(args, retInfo)) = SynValInfo([]::args, retInfo) - - /// Add a parameter entry to the syntactic value information to represent the 'this' argument. This is - /// used for the implicit 'this' argument in member signature specifications. - let IncorporateSelfArg (SynValInfo(args, retInfo)) = SynValInfo(selfMetadata::args, retInfo) - - /// Add a parameter entry to the syntactic value information to represent the value argument for a property setter. This is - /// used for the implicit value argument in property setter signature specifications. - let IncorporateSetterArg (SynValInfo(args, retInfo)) = - let args = - match args with - | [] -> [unnamedTopArg] - | [arg] -> [arg@[unnamedTopArg1]] - | _ -> failwith "invalid setter type" - SynValInfo(args, retInfo) - - /// Get the argument counts for each curried argument group. Used in some adhoc places in tc.fs. - let AritiesOfArgs (SynValInfo(args, _)) = List.map List.length args - - /// Get the argument attributes from the syntactic information for an argument. - let AttribsOfArgData (SynArgInfo(attribs, _, _)) = attribs - - /// Infer the syntactic argument info for a single argument from a simple pattern. - let rec InferSynArgInfoFromSimplePat attribs p = - match p with - | SynSimplePat.Id(nm, _, isCompGen, _, isOpt, _) -> - SynArgInfo(attribs, isOpt, (if isCompGen then None else Some nm)) - | SynSimplePat.Typed(a, _, _) -> InferSynArgInfoFromSimplePat attribs a - | SynSimplePat.Attrib(a, attribs2, _) -> InferSynArgInfoFromSimplePat (attribs @ attribs2) a - - /// Infer the syntactic argument info for one or more arguments one or more simple patterns. - let rec InferSynArgInfoFromSimplePats x = - match x with - | SynSimplePats.SimplePats(ps, _) -> List.map (InferSynArgInfoFromSimplePat []) ps - | SynSimplePats.Typed(ps, _, _) -> InferSynArgInfoFromSimplePats ps - - /// Infer the syntactic argument info for one or more arguments a pattern. - let InferSynArgInfoFromPat p = - // It is ok to use a fresh SynArgNameGenerator here, because compiler generated names are filtered from SynArgInfo, see InferSynArgInfoFromSimplePat above - let sp, _ = SimplePatsOfPat (SynArgNameGenerator()) p - InferSynArgInfoFromSimplePats sp - - /// Make sure only a solitary unit argument has unit elimination - let AdjustArgsForUnitElimination infosForArgs = - match infosForArgs with - | [[]] -> infosForArgs - | _ -> infosForArgs |> List.map (function [] -> unitArgData | x -> x) - - /// Transform a property declared using '[static] member P = expr' to a method taking a "unit" argument. - /// This is similar to IncorporateEmptyTupledArgForPropertyGetter, but applies to member definitions - /// rather than member signatures. - let AdjustMemberArgs memFlags infosForArgs = - match infosForArgs with - | [] when memFlags=MemberKind.Member -> [] :: infosForArgs - | _ -> infosForArgs - - /// For 'let' definitions, we infer syntactic argument information from the r.h.s. of a definition, if it - /// is an immediate 'fun ... -> ...' or 'function ...' expression. This is noted in the F# language specification. - /// This does not apply to member definitions. - let InferLambdaArgs origRhsExpr = - let rec loop e = - match e with - | SynExpr.Lambda(false, _, spats, rest, _) -> - InferSynArgInfoFromSimplePats spats :: loop rest - | _ -> [] - loop origRhsExpr - - let InferSynReturnData (retInfo: SynReturnInfo option) = - match retInfo with - | None -> unnamedRetVal - | Some(SynReturnInfo((_, retInfo), _)) -> retInfo - - let private emptySynValInfo = SynValInfo([], unnamedRetVal) - - let emptySynValData = SynValData(None, emptySynValInfo, None) - - /// Infer the syntactic information for a 'let' or 'member' definition, based on the argument pattern, - /// any declared return information (e.g. .NET attributes on the return element), and the r.h.s. expression - /// in the case of 'let' definitions. - let InferSynValData (memberFlagsOpt, pat, retInfo, origRhsExpr) = - - let infosForExplicitArgs = - match pat with - | Some(SynPat.LongIdent(_, _, _, SynConstructorArgs.Pats curriedArgs, _, _)) -> List.map InferSynArgInfoFromPat curriedArgs - | _ -> [] - - let explicitArgsAreSimple = - match pat with - | Some(SynPat.LongIdent(_, _, _, SynConstructorArgs.Pats curriedArgs, _, _)) -> List.forall isSimplePattern curriedArgs - | _ -> true - - let retInfo = InferSynReturnData retInfo - - match memberFlagsOpt with - | None -> - let infosForLambdaArgs = InferLambdaArgs origRhsExpr - let infosForArgs = infosForExplicitArgs @ (if explicitArgsAreSimple then infosForLambdaArgs else []) - let infosForArgs = AdjustArgsForUnitElimination infosForArgs - SynValData(None, SynValInfo(infosForArgs, retInfo), None) - - | Some memFlags -> - let infosForObjArgs = - if memFlags.IsInstance then [ selfMetadata ] else [] - - let infosForArgs = AdjustMemberArgs memFlags.MemberKind infosForExplicitArgs - let infosForArgs = AdjustArgsForUnitElimination infosForArgs - - let argInfos = infosForObjArgs @ infosForArgs - SynValData(Some(memFlags), SynValInfo(argInfos, retInfo), None) - - - -let mkSynBindingRhs staticOptimizations rhsExpr mRhs retInfo = - let rhsExpr = List.foldBack (fun (c, e1) e2 -> SynExpr.LibraryOnlyStaticOptimization (c, e1, e2, mRhs)) staticOptimizations rhsExpr - let rhsExpr, retTyOpt = - match retInfo with - | Some (SynReturnInfo((ty, SynArgInfo(rattribs, _, _)), tym)) -> SynExpr.Typed(rhsExpr, ty, rhsExpr.Range), Some(SynBindingReturnInfo(ty, tym, rattribs) ) - | None -> rhsExpr, None - rhsExpr, retTyOpt - -let mkSynBinding (xmlDoc, headPat) (vis, isInline, isMutable, mBind, spBind, retInfo, origRhsExpr, mRhs, staticOptimizations, attrs, memberFlagsOpt) = - let info = SynInfo.InferSynValData (memberFlagsOpt, Some headPat, retInfo, origRhsExpr) - let rhsExpr, retTyOpt = mkSynBindingRhs staticOptimizations origRhsExpr mRhs retInfo - Binding (vis, NormalBinding, isInline, isMutable, attrs, xmlDoc, info, headPat, retTyOpt, rhsExpr, mBind, spBind) - -let NonVirtualMemberFlags k = { MemberKind=k; IsInstance=true; IsDispatchSlot=false; IsOverrideOrExplicitImpl=false; IsFinal=false } -let CtorMemberFlags = { MemberKind=MemberKind.Constructor; IsInstance=false; IsDispatchSlot=false; IsOverrideOrExplicitImpl=false; IsFinal=false } -let ClassCtorMemberFlags = { MemberKind=MemberKind.ClassConstructor; IsInstance=false; IsDispatchSlot=false; IsOverrideOrExplicitImpl=false; IsFinal=false } -let OverrideMemberFlags k = { MemberKind=k; IsInstance=true; IsDispatchSlot=false; IsOverrideOrExplicitImpl=true; IsFinal=false } -let AbstractMemberFlags k = { MemberKind=k; IsInstance=true; IsDispatchSlot=true; IsOverrideOrExplicitImpl=false; IsFinal=false } -let StaticMemberFlags k = { MemberKind=k; IsInstance=false; IsDispatchSlot=false; IsOverrideOrExplicitImpl=false; IsFinal=false } - -let inferredTyparDecls = SynValTyparDecls([], true, []) -let noInferredTypars = SynValTyparDecls([], false, []) - -//------------------------------------------------------------------------ -// Lexer args: status of #if/#endif processing. -//------------------------------------------------------------------------ - -type LexerIfdefStackEntry = IfDefIf | IfDefElse -type LexerIfdefStackEntries = (LexerIfdefStackEntry * range) list -type LexerIfdefStack = LexerIfdefStackEntries ref - -/// Specifies how the 'endline' function in the lexer should continue after -/// it reaches end of line or eof. The options are to continue with 'token' function -/// or to continue with 'skip' function. -type LexerEndlineContinuation = - | Token of LexerIfdefStackEntries - | Skip of LexerIfdefStackEntries * int * range: range - member x.LexerIfdefStack = - match x with - | LexerEndlineContinuation.Token(ifd) - | LexerEndlineContinuation.Skip(ifd, _, _) -> ifd - -type LexerIfdefExpression = - | IfdefAnd of LexerIfdefExpression*LexerIfdefExpression - | IfdefOr of LexerIfdefExpression*LexerIfdefExpression - | IfdefNot of LexerIfdefExpression - | IfdefId of string - -let rec LexerIfdefEval (lookup: string -> bool) = function - | IfdefAnd (l, r) -> (LexerIfdefEval lookup l) && (LexerIfdefEval lookup r) - | IfdefOr (l, r) -> (LexerIfdefEval lookup l) || (LexerIfdefEval lookup r) - | IfdefNot e -> not (LexerIfdefEval lookup e) - | IfdefId id -> lookup id - -/// The parser defines a number of tokens for whitespace and -/// comments eliminated by the lexer. These carry a specification of -/// a continuation for the lexer for continued processing after we've dealt with -/// the whitespace. -[] -[] -type LexerWhitespaceContinuation = - | Token of ifdef: LexerIfdefStackEntries - | IfDefSkip of ifdef: LexerIfdefStackEntries * int * range: range - | String of ifdef: LexerIfdefStackEntries * range: range - | VerbatimString of ifdef: LexerIfdefStackEntries * range: range - | TripleQuoteString of ifdef: LexerIfdefStackEntries * range: range - | Comment of ifdef: LexerIfdefStackEntries * int * range: range - | SingleLineComment of ifdef: LexerIfdefStackEntries * int * range: range - | StringInComment of ifdef: LexerIfdefStackEntries * int * range: range - | VerbatimStringInComment of ifdef: LexerIfdefStackEntries * int * range: range - | TripleQuoteStringInComment of ifdef: LexerIfdefStackEntries * int * range: range - | MLOnly of ifdef: LexerIfdefStackEntries * range: range - | EndLine of LexerEndlineContinuation - - member x.LexerIfdefStack = - match x with - | LexCont.Token (ifdef=ifd) - | LexCont.IfDefSkip (ifdef=ifd) - | LexCont.String (ifdef=ifd) - | LexCont.VerbatimString (ifdef=ifd) - | LexCont.Comment (ifdef=ifd) - | LexCont.SingleLineComment (ifdef=ifd) - | LexCont.TripleQuoteString (ifdef=ifd) - | LexCont.StringInComment (ifdef=ifd) - | LexCont.VerbatimStringInComment (ifdef=ifd) - | LexCont.TripleQuoteStringInComment (ifdef=ifd) - | LexCont.MLOnly (ifdef=ifd) -> ifd - | LexCont.EndLine endl -> endl.LexerIfdefStack - -and LexCont = LexerWhitespaceContinuation - -//------------------------------------------------------------------------ -// Parser/Lexer state -//------------------------------------------------------------------------ - -/// The error raised by the parse_error_rich function, which is called by the parser engine -/// when a syntax error occurs. The first object is the ParseErrorContext which contains a dump of -/// information about the grammar at the point where the error occurred, e.g. what tokens -/// are valid to shift next at that point in the grammar. This information is processed in CompileOps.fs. -[] -exception SyntaxError of obj (* ParseErrorContext<_> *) * range: range - -/// Get an F# compiler position from a lexer position -let internal posOfLexPosition (p: Position) = - mkPos p.Line p.Column - -/// Get an F# compiler range from a lexer range -let internal mkSynRange (p1: Position) (p2: Position) = - mkFileIndexRange p1.FileIndex (posOfLexPosition p1) (posOfLexPosition p2) - -type LexBuffer<'Char> with - member internal lexbuf.LexemeRange = mkSynRange lexbuf.StartPos lexbuf.EndPos - -/// Get the range corresponding to the result of a grammar rule while it is being reduced -let internal lhs (parseState: IParseState) = - let p1 = parseState.ResultStartPosition - let p2 = parseState.ResultEndPosition - mkSynRange p1 p2 - -/// Get the range covering two of the r.h.s. symbols of a grammar rule while it is being reduced -let internal rhs2 (parseState: IParseState) i j = - let p1 = parseState.InputStartPosition i - let p2 = parseState.InputEndPosition j - mkSynRange p1 p2 - -/// Get the range corresponding to one of the r.h.s. symbols of a grammar rule while it is being reduced -let internal rhs parseState i = rhs2 parseState i i - -type IParseState with - - /// Get the generator used for compiler-generated argument names. - member internal x.SynArgNameGenerator = - let key = "SynArgNameGenerator" - let bls = x.LexBuffer.BufferLocalStore - let gen = - match bls.TryGetValue(key) with - | true, gen -> gen - | _ -> - let gen = box (SynArgNameGenerator()) - bls.[key] <- gen - gen - gen :?> SynArgNameGenerator - - /// Reset the generator used for compiler-generated argument names. - member internal x.ResetSynArgNameGenerator() = x.SynArgNameGenerator.Reset() - - -/// XmlDoc F# lexer/parser state, held in the BufferLocalStore for the lexer. -/// This is the only use of the lexer BufferLocalStore in the codebase. -module LexbufLocalXmlDocStore = - // The key into the BufferLocalStore used to hold the current accumulated XmlDoc lines - let private xmlDocKey = "XmlDoc" - - let internal ClearXmlDoc (lexbuf: Lexbuf) = - lexbuf.BufferLocalStore.[xmlDocKey] <- box (XmlDocCollector()) - - /// Called from the lexer to save a single line of XML doc comment. - let internal SaveXmlDocLine (lexbuf: Lexbuf, lineText, pos) = - let collector = - match lexbuf.BufferLocalStore.TryGetValue(xmlDocKey) with - | true, collector -> collector - | _ -> - let collector = box (XmlDocCollector()) - lexbuf.BufferLocalStore.[xmlDocKey] <- collector - collector - let collector = unbox(collector) - collector.AddXmlDocLine(lineText, pos) - - /// Called from the parser each time we parse a construct that marks the end of an XML doc comment range, - /// e.g. a 'type' declaration. The markerRange is the range of the keyword that delimits the construct. - let internal GrabXmlDocBeforeMarker (lexbuf: Lexbuf, markerRange: range) = - match lexbuf.BufferLocalStore.TryGetValue(xmlDocKey) with - | true, collector -> - let collector = unbox(collector) - PreXmlDoc.CreateFromGrabPoint(collector, markerRange.End) - | _ -> - PreXmlDoc.Empty - - - -/// Generates compiler-generated names. Each name generated also includes the StartLine number of the range passed in -/// at the point of first generation. -/// -/// This type may be accessed concurrently, though in practice it is only used from the compilation thread. -/// It is made concurrency-safe since a global instance of the type is allocated in tast.fs, and it is good -/// policy to make all globally-allocated objects concurrency safe in case future versions of the compiler -/// are used to host multiple concurrent instances of compilation. -type NiceNameGenerator() = - - let lockObj = obj() - let basicNameCounts = new Dictionary(100) - - member x.FreshCompilerGeneratedName (name, m: range) = - lock lockObj (fun () -> - let basicName = GetBasicNameOfPossibleCompilerGeneratedName name - let n = - match basicNameCounts.TryGetValue(basicName) with - | true, count -> count - | _ -> 0 - let nm = CompilerGeneratedNameSuffix basicName (string m.StartLine + (match n with 0 -> "" | n -> "-" + string n)) - basicNameCounts.[basicName] <- n + 1 - nm) - - member x.Reset () = - lock lockObj (fun () -> - basicNameCounts.Clear() - ) - - - -/// Generates compiler-generated names marked up with a source code location, but if given the same unique value then -/// return precisely the same name. Each name generated also includes the StartLine number of the range passed in -/// at the point of first generation. -/// -/// This type may be accessed concurrently, though in practice it is only used from the compilation thread. -/// It is made concurrency-safe since a global instance of the type is allocated in tast.fs. -type StableNiceNameGenerator() = - - let lockObj = obj() - - let names = new Dictionary<(string * int64), string>(100) - let basicNameCounts = new Dictionary(100) - - member x.GetUniqueCompilerGeneratedName (name, m: range, uniq) = - lock lockObj (fun () -> - let basicName = GetBasicNameOfPossibleCompilerGeneratedName name - let key = basicName, uniq - match names.TryGetValue(key) with - | true, nm -> nm - | _ -> - let n = - match basicNameCounts.TryGetValue(basicName) with - | true, c -> c - | _ -> 0 - let nm = CompilerGeneratedNameSuffix basicName (string m.StartLine + (match n with 0 -> "" | n -> "-" + string n)) - names.[key] <- nm - basicNameCounts.[basicName] <- n + 1 - nm - ) - - member x.Reset () = - lock lockObj (fun () -> - basicNameCounts.Clear() - names.Clear() - ) - -let rec synExprContainsError inpExpr = - let rec walkBind (Binding(_, _, _, _, _, _, _, _, _, synExpr, _, _)) = walkExpr synExpr - and walkExprs es = es |> List.exists walkExpr - and walkBinds es = es |> List.exists walkBind - and walkMatchClauses cl = cl |> List.exists (fun (Clause(_, whenExpr, e, _, _)) -> walkExprOpt whenExpr || walkExpr e) - and walkExprOpt eOpt = eOpt |> Option.exists walkExpr - and walkExpr e = - match e with - | SynExpr.FromParseError _ - | SynExpr.DiscardAfterMissingQualificationAfterDot _ - | SynExpr.ArbitraryAfterError _ -> true - | SynExpr.LongIdent _ - | SynExpr.Quote _ - | SynExpr.LibraryOnlyILAssembly _ - | SynExpr.LibraryOnlyStaticOptimization _ - | SynExpr.Null _ - | SynExpr.Ident _ - | SynExpr.ImplicitZero _ - | SynExpr.Const _ -> false - - | SynExpr.TypeTest (e, _, _) - | SynExpr.Upcast (e, _, _) - | SynExpr.AddressOf (_, e, _, _) - | SynExpr.CompExpr (_, _, e, _) - | SynExpr.ArrayOrListOfSeqExpr (_, e, _) - | SynExpr.Typed (e, _, _) - | SynExpr.FromParseError (e, _) - | SynExpr.Do (e, _) - | SynExpr.Assert (e, _) - | SynExpr.DotGet (e, _, _, _) - | SynExpr.LongIdentSet (_, e, _) - | SynExpr.New (_, _, e, _) - | SynExpr.TypeApp (e, _, _, _, _, _, _) - | SynExpr.LibraryOnlyUnionCaseFieldGet (e, _, _, _) - | SynExpr.Downcast (e, _, _) - | SynExpr.InferredUpcast (e, _) - | SynExpr.InferredDowncast (e, _) - | SynExpr.Lazy (e, _) - | SynExpr.TraitCall(_, _, e, _) - | SynExpr.YieldOrReturn (_, e, _) - | SynExpr.YieldOrReturnFrom (_, e, _) - | SynExpr.DoBang (e, _) - | SynExpr.Fixed (e, _) - | SynExpr.Paren (e, _, _, _) -> - walkExpr e - - | SynExpr.NamedIndexedPropertySet (_, e1, e2, _) - | SynExpr.DotSet (e1, _, e2, _) - | SynExpr.Set (e1, e2, _) - | SynExpr.LibraryOnlyUnionCaseFieldSet (e1, _, _, e2, _) - | SynExpr.JoinIn (e1, _, e2, _) - | SynExpr.App (_, _, e1, e2, _) -> - walkExpr e1 || walkExpr e2 - - | SynExpr.ArrayOrList (_, es, _) - | SynExpr.Tuple (_, es, _, _) -> - walkExprs es - - | SynExpr.AnonRecd (_, origExpr, flds, _) -> - (match origExpr with Some (e, _) -> walkExpr e | None -> false) || - walkExprs (List.map snd flds) - - | SynExpr.Record (_, origExpr, fs, _) -> - (match origExpr with Some (e, _) -> walkExpr e | None -> false) || - let flds = fs |> List.choose (fun (_, v, _) -> v) - walkExprs (flds) - - | SynExpr.ObjExpr (_, _, bs, is, _, _) -> - walkBinds bs || walkBinds [ for (InterfaceImpl(_, bs, _)) in is do yield! bs ] - | SynExpr.ForEach (_, _, _, _, e1, e2, _) - | SynExpr.While (_, e1, e2, _) -> - walkExpr e1 || walkExpr e2 - | SynExpr.For (_, _, e1, _, e2, e3, _) -> - walkExpr e1 || walkExpr e2 || walkExpr e3 - | SynExpr.MatchLambda(_, _, cl, _, _) -> - walkMatchClauses cl - | SynExpr.Lambda (_, _, _, e, _) -> - walkExpr e - | SynExpr.Match (_, e, cl, _) -> - walkExpr e || walkMatchClauses cl - | SynExpr.LetOrUse (_, _, bs, e, _) -> - walkBinds bs || walkExpr e - - | SynExpr.TryWith (e, _, cl, _, _, _, _) -> - walkExpr e || walkMatchClauses cl - - | SynExpr.TryFinally (e1, e2, _, _, _) -> - walkExpr e1 || walkExpr e2 - | SynExpr.Sequential (_, _, e1, e2, _) -> - walkExpr e1 || walkExpr e2 - | SynExpr.IfThenElse (e1, e2, e3opt, _, _, _, _) -> - walkExpr e1 || walkExpr e2 || walkExprOpt e3opt - | SynExpr.DotIndexedGet (e1, es, _, _) -> - walkExpr e1 || walkExprs [ for e in es do yield! e.Exprs ] - - | SynExpr.DotIndexedSet (e1, es, e2, _, _, _) -> - walkExpr e1 || walkExprs [ for e in es do yield! e.Exprs ] || walkExpr e2 - | SynExpr.DotNamedIndexedPropertySet (e1, _, e2, e3, _) -> - walkExpr e1 || walkExpr e2 || walkExpr e3 - - | SynExpr.MatchBang (_, e, cl, _) -> - walkExpr e || walkMatchClauses cl - | SynExpr.LetOrUseBang (_, _, _, _, e1, e2, _) -> - walkExpr e1 || walkExpr e2 - walkExpr inpExpr diff --git a/src/fcs-fable/src/fsharp/autobox.fs b/src/fcs-fable/src/fsharp/autobox.fs index dd76156619..a63790e59e 100644 --- a/src/fcs-fable/src/fsharp/autobox.fs +++ b/src/fcs-fable/src/fsharp/autobox.fs @@ -5,8 +5,9 @@ module internal FSharp.Compiler.AutoBox open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.Lib open FSharp.Compiler.TcGlobals open FSharp.Compiler.TypeRelations @@ -18,6 +19,8 @@ type cenv = { g: TcGlobals amap: Import.ImportMap } + override x.ToString() = "" + /// Find all the mutable locals that escape a method, function or lambda expression let DecideEscapes syntacticArgs body = let cantBeFree v = @@ -48,16 +51,16 @@ let DecideLambda exprF cenv topValInfo expr ety z = let DecideExprOp exprF noInterceptF (z: Zset) (expr: Expr) (op, tyargs, args) = match op, tyargs, args with - | TOp.While _, _, [Expr.Lambda(_, _, _, [_], e1, _, _);Expr.Lambda(_, _, _, [_], e2, _, _)] -> + | TOp.While _, _, [Expr.Lambda (_, _, _, [_], e1, _, _);Expr.Lambda (_, _, _, [_], e2, _, _)] -> exprF (exprF z e1) e2 - | TOp.TryFinally _, [_], [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [_], e2, _, _)] -> + | TOp.TryFinally _, [_], [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [_], e2, _, _)] -> exprF (exprF z e1) e2 - | TOp.For(_), _, [Expr.Lambda(_, _, _, [_], e1, _, _);Expr.Lambda(_, _, _, [_], e2, _, _);Expr.Lambda(_, _, _, [_], e3, _, _)] -> + | TOp.For (_), _, [Expr.Lambda (_, _, _, [_], e1, _, _);Expr.Lambda (_, _, _, [_], e2, _, _);Expr.Lambda (_, _, _, [_], e3, _, _)] -> exprF (exprF (exprF z e1) e2) e3 - | TOp.TryCatch _, [_], [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [_], _e2, _, _); Expr.Lambda(_, _, _, [_], e3, _, _)] -> + | TOp.TryCatch _, [_], [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [_], _e2, _, _); Expr.Lambda (_, _, _, [_], e3, _, _)] -> exprF (exprF (exprF z e1) _e2) e3 // In Check code it said // e2; -- don't check filter body - duplicates logic in 'catch' body @@ -68,12 +71,12 @@ let DecideExprOp exprF noInterceptF (z: Zset) (expr: Expr) (op, tyargs, arg /// Find all the mutable locals that escape a lambda expression or object expression let DecideExpr cenv exprF noInterceptF z expr = match expr with - | Expr.Lambda(_, _ctorThisValOpt, _baseValOpt, argvs, _, m, rty) -> + | Expr.Lambda (_, _ctorThisValOpt, _baseValOpt, argvs, _, m, rty) -> let topValInfo = ValReprInfo ([], [argvs |> List.map (fun _ -> ValReprInfo.unnamedTopArg1)], ValReprInfo.unnamedRetVal) let ty = mkMultiLambdaTy m argvs rty DecideLambda (Some exprF) cenv topValInfo expr ty z - | Expr.TyLambda(_, tps, _, _m, rty) -> + | Expr.TyLambda (_, tps, _, _m, rty) -> let topValInfo = ValReprInfo (ValReprInfo.InferTyparInfo tps, [], ValReprInfo.unnamedRetVal) let ty = mkForallTyIfNeeded tps rty DecideLambda (Some exprF) cenv topValInfo expr ty z @@ -81,7 +84,7 @@ let DecideExpr cenv exprF noInterceptF z expr = | Expr.Obj (_, _, baseValOpt, superInitCall, overrides, iimpls, _m) -> let CheckMethod z (TObjExprMethod(_, _attribs, _tps, vs, body, _m)) = let vs = List.concat vs - let syntacticArgs = (match baseValOpt with Some x -> x:: vs | None -> vs) + let syntacticArgs = (match baseValOpt with Some x -> x :: vs | None -> vs) let z = Zset.union z (DecideEscapes syntacticArgs body) exprF z body @@ -124,7 +127,6 @@ let DecideImplFile g amap implFile = z - //---------------------------------------------------------------------------- // Apply the transform @@ -139,20 +141,19 @@ let TransformExpr g (nvs: ValMap<_>) exprF expr = Some (mkRefCellGet g m v.Type nve) // Rewrite assignments to mutable values - | Expr.Op(TOp.LValueOp (LSet, ValDeref(v)), [], [arg], m) when nvs.ContainsVal v -> + | Expr.Op (TOp.LValueOp (LSet, ValDeref(v)), [], [arg], m) when nvs.ContainsVal v -> let _nv, nve = nvs.[v] let arg = exprF arg Some (mkRefCellSet g m v.Type nve arg) // Rewrite taking the address of mutable values - | Expr.Op(TOp.LValueOp (LAddrOf readonly, ValDeref(v)), [], [], m) when nvs.ContainsVal v -> + | Expr.Op (TOp.LValueOp (LAddrOf readonly, ValDeref(v)), [], [], m) when nvs.ContainsVal v -> let _nv,nve = nvs.[v] Some (mkRecdFieldGetAddrViaExprAddr (readonly, nve, mkRefCellContentsRef g, [v.Type], m)) | _ -> None - /// Rewrite bindings for mutable locals which we are transforming let TransformBinding g (nvs: ValMap<_>) exprF (TBind(v, expr, m)) = if nvs.ContainsVal v then diff --git a/src/fcs-fable/src/fsharp/autobox.fsi b/src/fcs-fable/src/fsharp/autobox.fsi new file mode 100644 index 0000000000..09e62ff8df --- /dev/null +++ b/src/fcs-fable/src/fsharp/autobox.fsi @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +module internal FSharp.Compiler.AutoBox + +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.Import + +/// Rewrite mutable locals to reference cells across an entire implementation file +val TransformImplFile: g: TcGlobals -> amap: ImportMap -> implFile: TypedImplFile -> TypedImplFile + + diff --git a/src/fcs-fable/src/fsharp/fsc.fs b/src/fcs-fable/src/fsharp/fsc.fs old mode 100755 new mode 100644 index f88d7789ee..628120aa72 --- a/src/fcs-fable/src/fsharp/fsc.fs +++ b/src/fcs-fable/src/fsharp/fsc.fs @@ -13,13 +13,11 @@ module internal FSharp.Compiler.Driver open System -open System.Collections.Concurrent open System.Collections.Generic open System.Diagnostics open System.Globalization open System.IO open System.Reflection -open System.Runtime.CompilerServices open System.Text open System.Threading @@ -31,24 +29,27 @@ open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.ILBinaryReader -open FSharp.Compiler.AbstractIL.Internal +open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.AbstractIL.Internal.Utils open FSharp.Compiler.AbstractIL.Diagnostics -open FSharp.Compiler.IlxGen - open FSharp.Compiler.AccessibilityLogic -open FSharp.Compiler.AttributeChecking -open FSharp.Compiler.Ast open FSharp.Compiler.CompileOps open FSharp.Compiler.CompileOptions +open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.IlxGen open FSharp.Compiler.InfoReader open FSharp.Compiler.Lib +open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.SyntaxTree open FSharp.Compiler.Range -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals open FSharp.Compiler.TypeChecker +open FSharp.Compiler.XmlDoc #if !NO_EXTENSIONTYPING open FSharp.Compiler.ExtensionTyping @@ -105,7 +106,7 @@ let ConsoleErrorLoggerUpToMaxErrors (tcConfigB: TcConfigBuilder, exiter : Exiter member __.HandleIssue(tcConfigB, err, isError) = DoWithErrorColor isError (fun () -> let diag = OutputDiagnostic (tcConfigB.implicitIncludeDir, tcConfigB.showFullPaths, tcConfigB.flatErrors, tcConfigB.errorStyle, isError) - writeViaBufferWithEnvironmentNewLines stderr diag err + writeViaBuffer stderr diag err stderr.WriteLine()) } :> ErrorLogger @@ -116,12 +117,12 @@ type DelayAndForwardErrorLogger(exiter: Exiter, errorLoggerProvider: ErrorLogger member x.ForwardDelayedDiagnostics(tcConfigB: TcConfigBuilder) = let errorLogger = errorLoggerProvider.CreateErrorLoggerUpToMaxErrors(tcConfigB, exiter) - x.CommitDelayedDiagnostics(errorLogger) + x.CommitDelayedDiagnostics errorLogger and [] ErrorLoggerProvider() = - member this.CreateDelayAndForwardLogger(exiter) = DelayAndForwardErrorLogger(exiter, this) + member this.CreateDelayAndForwardLogger exiter = DelayAndForwardErrorLogger(exiter, this) abstract CreateErrorLoggerUpToMaxErrors : tcConfigBuilder : TcConfigBuilder * exiter : Exiter -> ErrorLogger @@ -140,15 +141,16 @@ type InProcErrorLoggerProvider() = { new ErrorLoggerUpToMaxErrors(tcConfigBuilder, exiter, "InProcCompilerErrorLoggerUpToMaxErrors") with - member this.HandleTooManyErrors(text) = warnings.Add(Diagnostic.Short(false, text)) + member this.HandleTooManyErrors text = warnings.Add(Diagnostic.Short(false, text)) - member this.HandleIssue(tcConfigBuilder, err, isError) = - let errs = + member this.HandleIssue(tcConfigBuilder, err, isError) = + // 'true' is passed for "suggestNames", since we want to suggest names with fsc.exe runs and this doesn't affect IDE perf + let errs = CollectDiagnostic - (tcConfigBuilder.implicitIncludeDir, tcConfigBuilder.showFullPaths, - tcConfigBuilder.flatErrors, tcConfigBuilder.errorStyle, isError, err) - let container = if isError then errors else warnings - container.AddRange(errs) } + (tcConfigBuilder.implicitIncludeDir, tcConfigBuilder.showFullPaths, + tcConfigBuilder.flatErrors, tcConfigBuilder.errorStyle, isError, err, true) + let container = if isError then errors else warnings + container.AddRange(errs) } :> ErrorLogger } member __.CapturedErrors = errors.ToArray() @@ -176,7 +178,7 @@ type DisposablesTracker() = let items = Stack() - member this.Register(i) = items.Push i + member this.Register i = items.Push i interface IDisposable with @@ -202,24 +204,24 @@ let AdjustForScriptCompile(ctok, tcConfigB: TcConfigBuilder, commandLineSourceFi let combineFilePath file = try - if FileSystem.IsPathRootedShim(file) then file + if FileSystem.IsPathRootedShim file then file else Path.Combine(tcConfigB.implicitIncludeDir, file) with _ -> - error (Error(FSComp.SR.pathIsInvalid(file), rangeStartup)) + error (Error(FSComp.SR.pathIsInvalid file, rangeStartup)) let commandLineSourceFiles = commandLineSourceFiles |> List.map combineFilePath - let allSources = ref [] + let mutable allSources = [] let tcConfig = TcConfig.Create(tcConfigB, validate=false) let AddIfNotPresent(filename: string) = - if not(!allSources |> List.contains filename) then - allSources := filename::!allSources + if not(allSources |> List.contains filename) then + allSources <- filename :: allSources - let AppendClosureInformation(filename) = + let AppendClosureInformation filename = if IsScript filename then let closure = LoadClosure.ComputeClosureOfScriptFiles @@ -227,31 +229,31 @@ let AdjustForScriptCompile(ctok, tcConfigB: TcConfigBuilder, commandLineSourceFi // Record the references from the analysis of the script. The full resolutions are recorded as the corresponding #I paths used to resolve them // are local to the scripts and not added to the tcConfigB (they are added to localized clones of the tcConfigB). - let references = - closure.References - |> List.collect snd - |> List.filter (fun r -> r.originalReference.Range<>range0 && r.originalReference.Range<>rangeStartup) + let references = + closure.References + |> List.collect snd + |> List.filter (fun r -> not (Range.equals r.originalReference.Range range0) && not (Range.equals r.originalReference.Range rangeStartup)) references |> List.iter (fun r -> tcConfigB.AddReferencedAssemblyByPath(r.originalReference.Range, r.resolvedPath)) closure.NoWarns |> List.collect (fun (n, ms) -> ms|>List.map(fun m->m, n)) |> List.iter (fun (x,m) -> tcConfigB.TurnWarningOff(x, m)) closure.SourceFiles |> List.map fst |> List.iter AddIfNotPresent closure.AllRootFileDiagnostics |> List.iter diagnosticSink - else AddIfNotPresent(filename) + else AddIfNotPresent filename // Find closure of .fsx files. commandLineSourceFiles |> List.iter AppendClosureInformation - List.rev !allSources + List.rev allSources let ProcessCommandLineFlags (tcConfigB: TcConfigBuilder, setProcessThreadLocals, lcidFromCodePage, argv) = - let inputFilesRef = ref ([] : string list) + let mutable inputFilesRef = [] let collect name = let lower = String.lowercase name if List.exists (Filename.checkSuffix lower) [".resx"] then error(Error(FSComp.SR.fscResxSourceFileDeprecated name, rangeStartup)) else - inputFilesRef := name :: !inputFilesRef + inputFilesRef <- name :: inputFilesRef let abbrevArgs = GetAbbrevFlagSet tcConfigB true // This is where flags are interpreted by the command line fsc.exe. @@ -263,23 +265,27 @@ let ProcessCommandLineFlags (tcConfigB: TcConfigBuilder, setProcessThreadLocals, if not (String.IsNullOrEmpty(tcConfigB.sourceLink)) then error(Error(FSComp.SR.optsSourceLinkRequirePortablePDBs(), rangeCmdArgs)) - if tcConfigB.deterministic && tcConfigB.debuginfo && (tcConfigB.portablePDB = false) then - error(Error(FSComp.SR.fscDeterministicDebugRequiresPortablePdb(), rangeCmdArgs)) + if tcConfigB.debuginfo && not tcConfigB.portablePDB then + if tcConfigB.deterministic then + error(Error(FSComp.SR.fscDeterministicDebugRequiresPortablePdb(), rangeCmdArgs)) - let inputFiles = List.rev !inputFilesRef + if tcConfigB.pathMap <> PathMap.empty then + error(Error(FSComp.SR.fscPathMapDebugRequiresPortablePdb(), rangeCmdArgs)) + + let inputFiles = List.rev inputFilesRef // Check if we have a codepage from the console match tcConfigB.lcid with | Some _ -> () | None -> tcConfigB.lcid <- lcidFromCodePage - setProcessThreadLocals(tcConfigB) + setProcessThreadLocals tcConfigB (* step - get dll references *) let dllFiles, sourceFiles = inputFiles |> List.map(fun p -> trimQuotes p) |> List.partition Filename.isDll match dllFiles with | [] -> () - | h::_ -> errorR (Error(FSComp.SR.fscReferenceOnCommandLine(h), rangeStartup)) + | h :: _ -> errorR (Error(FSComp.SR.fscReferenceOnCommandLine h, rangeStartup)) dllFiles |> List.iter (fun f->tcConfigB.AddReferencedAssemblyByPath(rangeStartup, f)) sourceFiles @@ -312,9 +318,9 @@ module InterfaceFileWriter = fprintfn os "#light" fprintfn os "" - for (TImplFile(_, _, mexpr, _, _, _)) in declaredImpls do + for (TImplFile (_, _, mexpr, _, _, _)) in declaredImpls do let denv = BuildInitialDisplayEnvForSigFileGeneration tcGlobals - writeViaBufferWithEnvironmentNewLines os (fun os s -> Printf.bprintf os "%s\n\n" s) + writeViaBuffer os (fun os s -> Printf.bprintf os "%s\n\n" s) (NicePrint.layoutInferredSigOfModuleExpr true denv infoReader AccessibleFromSomewhere range0 mexpr |> Layout.squashTo 80 |> Layout.showL) if tcConfig.printSignatureFile <> "" then os.Dispose() @@ -379,11 +385,11 @@ module XmlDocWriter = if not (Filename.hasSuffixCaseInsensitive "xml" xmlfile ) then error(Error(FSComp.SR.docfileNoXmlSuffix(), Range.rangeStartup)) (* the xmlDocSigOf* functions encode type into string to be used in "id" *) - let members = ref [] + let mutable members = [] let addMember id xmlDoc = if hasDoc xmlDoc then let doc = getDoc xmlDoc - members := (id, doc) :: !members + members <- (id, doc) :: members let doVal (v: Val) = addMember v.XmlDocSig v.XmlDoc let doUnionCase (uc: UnionCase) = addMember uc.XmlDocSig uc.XmlDoc let doField (rf: RecdField) = addMember rf.XmlDocSig rf.XmlDoc @@ -414,13 +420,13 @@ module XmlDocWriter = doModule generatedCcu.Contents - use os = File.CreateText(xmlfile) + use os = File.CreateText xmlfile fprintfn os ("") fprintfn os ("") fprintfn os ("%s") assemblyName fprintfn os ("") - !members |> List.iter (fun (id, doc) -> + members |> List.iter (fun (id, doc) -> fprintfn os "" id fprintfn os "%s" doc fprintfn os "") @@ -434,13 +440,15 @@ let GenerateInterfaceData(tcConfig: TcConfig) = not tcConfig.standalone && not tcConfig.noSignatureData let EncodeInterfaceData(tcConfig: TcConfig, tcGlobals, exportRemapping, generatedCcu, outfile, isIncrementalBuild) = - if GenerateInterfaceData(tcConfig) then + if GenerateInterfaceData tcConfig then let resource = WriteSignatureData (tcConfig, tcGlobals, exportRemapping, generatedCcu, outfile, isIncrementalBuild) // The resource gets written to a file for FSharp.Core let useDataFiles = (tcConfig.useOptimizationDataFile || tcGlobals.compilingFslib) && not isIncrementalBuild if useDataFiles then let sigDataFileName = (Filename.chopExtension outfile)+".sigdata" - File.WriteAllBytes(sigDataFileName, resource.GetBytes()) + let bytes = resource.GetBytes() + use fileStream = File.Create(sigDataFileName, bytes.Length) + bytes.CopyTo fileStream let resources = [ resource ] let sigAttr = mkSignatureDataVersionAttr tcGlobals (IL.parseILVersion Internal.Utilities.FSharpEnvironment.FSharpBinaryMetadataFormatRevision) @@ -448,8 +456,8 @@ let EncodeInterfaceData(tcConfig: TcConfig, tcGlobals, exportRemapping, generate else [], [] -let GenerateOptimizationData(tcConfig) = - GenerateInterfaceData(tcConfig) +let GenerateOptimizationData tcConfig = + GenerateInterfaceData tcConfig let EncodeOptimizationData(tcGlobals, tcConfig: TcConfig, outfile, exportRemapping, data, isIncrementalBuild) = if GenerateOptimizationData tcConfig then @@ -458,7 +466,7 @@ let EncodeOptimizationData(tcGlobals, tcConfig: TcConfig, outfile, exportRemappi let useDataFiles = (tcConfig.useOptimizationDataFile || tcGlobals.compilingFslib) && not isIncrementalBuild if useDataFiles then let ccu, modulInfo = data - let bytes = TastPickle.pickleObjWithDanglingCcus isIncrementalBuild outfile tcGlobals ccu Optimizer.p_CcuOptimizationInfo modulInfo + let bytes = TypedTreePickle.pickleObjWithDanglingCcus isIncrementalBuild outfile tcGlobals ccu Optimizer.p_CcuOptimizationInfo modulInfo let optDataFileName = (Filename.chopExtension outfile)+".optdata" File.WriteAllBytes(optDataFileName, bytes) let (ccu, optData) = @@ -491,11 +499,10 @@ module BinaryGenerationUtilities = for _ in 1..(4 - (initialAlignment + v.Length) % 4) % 4 do yield 0x0uy |] -// Generate nodes in a .res file format. These are then linked by Abstract IL using the -// linkNativeResources function, which invokes the cvtres.exe utility -module ResFileFormat = +// Generate nodes in a .res file format. These are then linked by Abstract IL using linkNativeResources +module ResFileFormat = open BinaryGenerationUtilities - + let ResFileNode(dwTypeID, dwNameID, wMemFlags, wLangID, data: byte[]) = [| yield! i32 data.Length // DWORD ResHdr.dwDataSize yield! i32 0x00000020 // dwHeaderSize @@ -533,18 +540,18 @@ module VersionResourceFormat = for child in children do yield! child |] - let Version((v1, v2, v3, v4):ILVersionInfo) = + let Version(version: ILVersionInfo) = [| // DWORD dwFileVersionMS // Specifies the most significant 32 bits of the file's binary // version number. This member is used with dwFileVersionLS to form a 64-bit value used // for numeric comparisons. - yield! i32 (int32 v1 <<< 16 ||| int32 v2) + yield! i32 (int32 version.Major <<< 16 ||| int32 version.Minor) // DWORD dwFileVersionLS // Specifies the least significant 32 bits of the file's binary // version number. This member is used with dwFileVersionMS to form a 64-bit value used // for numeric comparisons. - yield! i32 (int32 v3 <<< 16 ||| int32 v4) + yield! i32 (int32 version.Build <<< 16 ||| int32 version.Revision) |] let String(string, value) = @@ -559,7 +566,7 @@ module VersionResourceFormat = let children = [| for string in strings do - yield String(string) |] + yield String string |] VersionInfoElement(wType, szKey, None, children, false) let StringFileInfo(stringTables: #seq >) = @@ -568,7 +575,7 @@ module VersionResourceFormat = // Contains an array of one or more StringTable structures. let children = [| for stringTable in stringTables do - yield StringTable(stringTable) |] + yield StringTable stringTable |] VersionInfoElement(wType, szKey, None, children, false) let VarFileInfo(vars: #seq) = @@ -680,17 +687,17 @@ module VersionResourceFormat = let szKey = Bytes.stringAsUnicodeNullTerminated "VS_VERSION_INFO" // Contains the Unicode string VS_VERSION_INFO let value = VS_FIXEDFILEINFO (fixedFileInfo) let children = - [| yield StringFileInfo(stringFileInfo) - yield VarFileInfo(varFileInfo) + [| yield StringFileInfo stringFileInfo + yield VarFileInfo varFileInfo |] VersionInfoElement(wType, szKey, Some value, children, false) - let VS_VERSION_INFO_RESOURCE(data) = + let VS_VERSION_INFO_RESOURCE data = let dwTypeID = 0x0010 let dwNameID = 0x0001 let wMemFlags = 0x0030 // REVIEW: HARDWIRED TO ENGLISH let wLangID = 0x0 - ResFileFormat.ResFileNode(dwTypeID, dwNameID, wMemFlags, wLangID, VS_VERSION_INFO(data)) + ResFileFormat.ResFileNode(dwTypeID, dwNameID, wMemFlags, wLangID, VS_VERSION_INFO data) module ManifestResourceFormat = @@ -713,7 +720,7 @@ module AttributeHelpers = | None -> None | Some attribRef -> match TryFindFSharpAttribute g attribRef attribs with - | Some (Attrib(_, _, [ AttribStringArg(s) ], _, _, _, _)) -> Some (s) + | Some (Attrib(_, _, [ AttribStringArg s ], _, _, _, _)) -> Some (s) | _ -> None let TryFindIntAttribute (g: TcGlobals) attrib attribs = @@ -721,7 +728,7 @@ module AttributeHelpers = | None -> None | Some attribRef -> match TryFindFSharpAttribute g attribRef attribs with - | Some (Attrib(_, _, [ AttribInt32Arg(i) ], _, _, _, _)) -> Some (i) + | Some (Attrib(_, _, [ AttribInt32Arg i ], _, _, _, _)) -> Some (i) | _ -> None let TryFindBoolAttribute (g: TcGlobals) attrib attribs = @@ -729,7 +736,7 @@ module AttributeHelpers = | None -> None | Some attribRef -> match TryFindFSharpAttribute g attribRef attribs with - | Some (Attrib(_, _, [ AttribBoolArg(p) ], _, _, _, _)) -> Some (p) + | Some (Attrib(_, _, [ AttribBoolArg p ], _, _, _, _)) -> Some (p) | _ -> None let (|ILVersion|_|) (versionString: string) = @@ -804,7 +811,7 @@ module MainModuleBuilder = let systemNumericsAssemblyRef = ILAssemblyRef.Create(refNumericsDllName, aref.Hash, aref.PublicKey, aref.Retargetable, aref.Version, aref.Locale) typesForwardedToSystemNumerics |> Seq.map (fun t -> - { ScopeRef = ILScopeRef.Assembly(systemNumericsAssemblyRef) + { ScopeRef = ILScopeRef.Assembly systemNumericsAssemblyRef Name = t Attributes = enum(0x00200000) ||| TypeAttributes.Public Nested = mkILNestedExportedTypes [] @@ -817,30 +824,43 @@ module MainModuleBuilder = let attrName = "System.Reflection.AssemblyFileVersionAttribute" match findStringAttr attrName with | None -> assemblyVersion - | Some (AttributeHelpers.ILVersion(v)) -> v + | Some (AttributeHelpers.ILVersion v) -> v | Some _ -> // Warning will be reported by TypeChecker.fs assemblyVersion let productVersion findStringAttr (fileVersion: ILVersionInfo) = let attrName = "System.Reflection.AssemblyInformationalVersionAttribute" - let toDotted (v1, v2, v3, v4) = sprintf "%d.%d.%d.%d" v1 v2 v3 v4 + let toDotted (version: ILVersionInfo) = sprintf "%d.%d.%d.%d" version.Major version.Minor version.Build version.Revision match findStringAttr attrName with | None | Some "" -> fileVersion |> toDotted - | Some (AttributeHelpers.ILVersion(v)) -> v |> toDotted + | Some (AttributeHelpers.ILVersion v) -> v |> toDotted | Some v -> // Warning will be reported by TypeChecker.fs v let productVersionToILVersionInfo (version: string) : ILVersionInfo = - let parseOrZero v = match System.UInt16.TryParse v with (true, i) -> i | (false, _) -> 0us + let parseOrZero i (v:string) = + let v = + // When i = 3 then this is the 4th part of the version. The last part of the version can be trailed by any characters so we trim them off + if i <> 3 then + v + else + ((false, ""), v) + ||> Seq.fold(fun (finished, v) c -> + match finished with + | false when Char.IsDigit(c) -> false, v + c.ToString() + | _ -> true, v) + |> snd + match System.UInt16.TryParse v with + | (true, i) -> i + | (false, _) -> 0us let validParts = version.Split('.') - |> Seq.map parseOrZero - |> Seq.takeWhile ((<>) 0us) + |> Array.mapi(fun i v -> parseOrZero i v) |> Seq.toList match validParts @ [0us; 0us; 0us; 0us] with - | major :: minor :: build :: rev :: _ -> (major, minor, build, rev) + | major :: minor :: build :: rev :: _ -> ILVersionInfo(major, minor, build, rev) | x -> failwithf "error converting product version '%s' to binary, tried '%A' " version x @@ -865,11 +885,9 @@ module MainModuleBuilder = error(Error(FSComp.SR.fscAssemblyCultureAttributeError(), rangeCmdArgs)) // Add the type forwarders to any .NET DLL post-.NET-2.0, to give binary compatibility - let exportedTypesList = - if (tcConfig.compilingFslib && tcConfig.compilingFslib40) then - (List.append (createMscorlibExportList tcGlobals) - (if tcConfig.compilingFslibNoBigInt then [] else (createSystemNumericsExportList tcConfig tcImports)) - ) + let exportedTypesList = + if tcConfig.compilingFslib then + List.append (createMscorlibExportList tcGlobals) (createSystemNumericsExportList tcConfig tcImports) else [] @@ -893,7 +911,7 @@ module MainModuleBuilder = [ ] let reflectedDefinitionResource = { Name=reflectedDefinitionResourceName - Location = ILResourceLocation.LocalOut reflectedDefinitionBytes + Location = ILResourceLocation.Local(ByteMemory.FromArray(reflectedDefinitionBytes).AsReadOnly()) Access= ILResourceAccess.Public CustomAttrsStored = storeILCustomAttrs emptyILCustomAttrs MetadataIndex = NoMetadataIdx } @@ -937,7 +955,7 @@ module MainModuleBuilder = let bytes = FileSystem.ReadAllBytesShim file name, bytes, pub yield { Name=name - Location=ILResourceLocation.LocalOut bytes + Location=ILResourceLocation.Local(ByteMemory.FromArray(bytes).AsReadOnly()) Access=pub CustomAttrsStored=storeILCustomAttrs emptyILCustomAttrs MetadataIndex = NoMetadataIdx } @@ -986,11 +1004,11 @@ module MainModuleBuilder = // specify the major language, and the high-order 6 bits specify the sublanguage. // For a table of valid identifiers see Language Identifiers. // // see e.g. http://msdn.microsoft.com/en-us/library/aa912040.aspx 0000 is neutral and 04b0(hex)=1252(dec) is the code page. - [ ("000004b0", [ yield ("Assembly Version", (let v1, v2, v3, v4 = assemblyVersion in sprintf "%d.%d.%d.%d" v1 v2 v3 v4)) - yield ("FileVersion", (let v1, v2, v3, v4 = fileVersionInfo in sprintf "%d.%d.%d.%d" v1 v2 v3 v4)) + [ ("000004b0", [ yield ("Assembly Version", (sprintf "%d.%d.%d.%d" assemblyVersion.Major assemblyVersion.Minor assemblyVersion.Build assemblyVersion.Revision)) + yield ("FileVersion", (sprintf "%d.%d.%d.%d" fileVersionInfo.Major fileVersionInfo.Minor fileVersionInfo.Build fileVersionInfo.Revision)) yield ("ProductVersion", productVersionString) match tcConfig.outputFile with - | Some f -> yield ("OriginalFilename", Path.GetFileName(f)) + | Some f -> yield ("OriginalFilename", Path.GetFileName f) | None -> () yield! FindAttribute "Comments" "System.Reflection.AssemblyDescriptionAttribute" yield! FindAttribute "FileDescription" "System.Reflection.AssemblyTitleAttribute" @@ -1061,13 +1079,10 @@ module MainModuleBuilder = elif not(tcConfig.target.IsExe) || not(tcConfig.includewin32manifest) || not(tcConfig.win32res = "") || runningOnMono then "" // otherwise, include the default manifest else -#if FX_NO_RUNTIMEENVIRONMENT - // On coreclr default manifest is alongside the compiler - Path.Combine(System.AppContext.BaseDirectory, @"default.win32manifest") -#else - // On the desktop default manifest is alongside the clr - Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(), @"default.win32manifest") -#endif + let path = Path.Combine(System.AppContext.BaseDirectory, @"default.win32manifest") + if File.Exists(path) then path + else Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(), @"default.win32manifest") + let nativeResources = [ for av in assemblyVersionResources findAttribute assemblyVersion do yield ILNativeResource.Out av @@ -1104,13 +1119,79 @@ module MainModuleBuilder = //---------------------------------------------------------------------------- /// Optional static linking of all DLLs that depend on the F# Library, plus other specified DLLs -module StaticLinker = +module StaticLinker = + + + // Handles TypeForwarding for the generated IL model + type TypeForwarding (tcImports: TcImports) = + + // Make a dictionary of ccus passed to the compiler will be looked up by qualified assembly name + let ccuThunksQualifiedName = + tcImports.GetCcusInDeclOrder() + |> List.filter(fun ccuThunk -> ccuThunk.QualifiedName |> Option.isSome) + |> List.map(fun ccuThunk -> ccuThunk.QualifiedName |> Option.defaultValue "Assembly Name Not Passed", ccuThunk) + |> dict + + // If we can't type forward using exact assembly match, we need to rely on the loader (Policy, Configuration or the coreclr load heuristics), so use try simple name + let ccuThunksSimpleName = + tcImports.GetCcusInDeclOrder() + |> List.filter(fun ccuThunk -> not (String.IsNullOrEmpty(ccuThunk.AssemblyName))) + |> List.map(fun ccuThunk -> ccuThunk.AssemblyName, ccuThunk) + |> dict + + let followTypeForwardForILTypeRef (tref:ILTypeRef) = + let typename = + let parts = tref.FullName.Split([|'.'|]) + match parts.Length with + | 0 -> None + | 1 -> Some (Array.empty, parts.[0]) + | n -> Some (parts.[0..n-2], parts.[n-1]) + + let scoref = tref.Scope + match scoref with + | ILScopeRef.Assembly scope -> + match ccuThunksQualifiedName.TryGetValue(scope.QualifiedName) with + | true, ccu -> + match typename with + | Some (parts, name) -> + let forwarded = ccu.TryForward(parts, name) + let result = + match forwarded with + | Some fwd -> fwd.CompilationPath.ILScopeRef + | None -> scoref + result + | None -> scoref + | false, _ -> + // Couldn't find an assembly with the version so try using a simple name + match ccuThunksSimpleName.TryGetValue(scope.Name) with + | true, ccu -> + match typename with + | Some (parts, name) -> + let forwarded = ccu.TryForward(parts, name) + let result = + match forwarded with + | Some fwd -> fwd.CompilationPath.ILScopeRef + | None -> scoref + result + | None -> scoref + | false, _ -> scoref + | _ -> scoref + + let typeForwardILTypeRef (tref: ILTypeRef) = + let scoref1 = tref.Scope + let scoref2 = followTypeForwardForILTypeRef tref + if scoref1 === scoref2 then tref + else ILTypeRef.Create (scoref2, tref.Enclosing, tref.Name) + + member __.TypeForwardILTypeRef tref = typeForwardILTypeRef tref + let debugStaticLinking = condition "FSHARP_DEBUG_STATIC_LINKING" - let StaticLinkILModules (tcConfig, ilGlobals, ilxMainModule, dependentILModules: (CcuThunk option * ILModuleDef) list) = + let StaticLinkILModules (tcConfig:TcConfig, ilGlobals, tcImports, ilxMainModule, dependentILModules: (CcuThunk option * ILModuleDef) list) = if isNil dependentILModules then ilxMainModule, (fun x -> x) else + let typeForwarding = new TypeForwarding(tcImports) // Check no dependent assemblies use quotations let dependentCcuUsingQuotations = dependentILModules |> List.tryPick (function (Some ccu, _) when ccu.UsesFSharp20PlusQuotations -> Some ccu | _ -> None) @@ -1196,74 +1277,18 @@ module StaticLinker = (mkILMethods (topTypeDefs |> List.collect (fun td -> td.Methods.AsList)), mkILFields (topTypeDefs |> List.collect (fun td -> td.Fields.AsList))) - let ilxMainModule = - { ilxMainModule with - Manifest = (let m = ilxMainModule.ManifestOfAssembly in Some {m with CustomAttrsStored = storeILCustomAttrs (mkILCustomAttrs (m.CustomAttrs.AsList @ savedManifestAttrs)) }) - CustomAttrsStored = storeILCustomAttrs (mkILCustomAttrs [ for m in moduls do yield! m.CustomAttrs.AsArray ]) - TypeDefs = mkILTypeDefs (topTypeDef :: List.concat normalTypeDefs) - Resources = mkILResources (savedResources @ ilxMainModule.Resources.AsList) - NativeResources = savedNativeResources } + let ilxMainModule = + let main = + { ilxMainModule with + Manifest = (let m = ilxMainModule.ManifestOfAssembly in Some {m with CustomAttrsStored = storeILCustomAttrs (mkILCustomAttrs (m.CustomAttrs.AsList @ savedManifestAttrs)) }) + CustomAttrsStored = storeILCustomAttrs (mkILCustomAttrs [ for m in moduls do yield! m.CustomAttrs.AsArray ]) + TypeDefs = mkILTypeDefs (topTypeDef :: List.concat normalTypeDefs) + Resources = mkILResources (savedResources @ ilxMainModule.Resources.AsList) + NativeResources = savedNativeResources } + Morphs.morphILTypeRefsInILModuleMemoized ilGlobals typeForwarding.TypeForwardILTypeRef main ilxMainModule, rewriteExternalRefsToLocalRefs - - // LEGACY: This is only used when compiling an FSharp.Core for .NET 2.0 (FSharp.Core 2.3.0.0). We no longer - // build new FSharp.Core for that configuration. - // - // Find all IL modules that are to be statically linked given the static linking roots. - let LegacyFindAndAddMscorlibTypesForStaticLinkingIntoFSharpCoreLibraryForNet20 (tcConfig: TcConfig, ilGlobals: ILGlobals, ilxMainModule) = - let mscorlib40 = tcConfig.compilingFslib20.Value - - let ilBinaryReader = - let ilGlobals = mkILGlobals ILScopeRef.Local - let opts : ILReaderOptions = - { ilGlobals = ilGlobals - reduceMemoryUsage = tcConfig.reduceMemoryUsage - metadataOnly = MetadataOnlyFlag.No - tryGetMetadataSnapshot = (fun _ -> None) - pdbDirPath = None } - ILBinaryReader.OpenILModuleReader mscorlib40 opts - - let tdefs1 = ilxMainModule.TypeDefs.AsList |> List.filter (fun td -> not (MainModuleBuilder.injectedCompatTypes.Contains(td.Name))) - let tdefs2 = ilBinaryReader.ILModuleDef.TypeDefs.AsList |> List.filter (fun td -> MainModuleBuilder.injectedCompatTypes.Contains(td.Name)) - //printfn "tdefs2 = %A" (tdefs2 |> List.map (fun tdef -> tdef.Name)) - - // rewrite the mscorlib references - let tdefs2 = - let fakeModule = mkILSimpleModule "" "" true (4, 0) false (mkILTypeDefs tdefs2) None None 0 (mkILExportedTypes []) "" - let fakeModule = - fakeModule |> Morphs.morphILTypeRefsInILModuleMemoized ilGlobals (fun tref -> - if MainModuleBuilder.injectedCompatTypes.Contains(tref.Name) || (tref.Enclosing |> List.exists (fun x -> MainModuleBuilder.injectedCompatTypes.Contains(x))) then - tref - //|> Morphs.morphILScopeRefsInILTypeRef (function ILScopeRef.Local -> ilGlobals.mscorlibScopeRef | x -> x) - // The implementations of Tuple use two private methods from System.Environment to get a resource string. Remap it - elif tref.Name = "System.Environment" then - ILTypeRef.Create(ILScopeRef.Local, [], "Microsoft.FSharp.Core.PrivateEnvironment") //|> Morphs.morphILScopeRefsInILTypeRef (function ILScopeRef.Local -> ilGlobals.mscorlibScopeRef | x -> x) - else - tref |> Morphs.morphILScopeRefsInILTypeRef (fun _ -> ilGlobals.primaryAssemblyScopeRef) ) - - // strip out System.Runtime.TargetedPatchingOptOutAttribute, which doesn't exist for 2.0 - let fakeModule = - {fakeModule with - TypeDefs = - mkILTypeDefs - ([ for td in fakeModule.TypeDefs do - let meths = td.Methods.AsList - |> List.map (fun md -> - md.With(customAttrs = - mkILCustomAttrs (td.CustomAttrs.AsList |> List.filter (fun ilattr -> - ilattr.Method.DeclaringType.TypeRef.FullName <> "System.Runtime.TargetedPatchingOptOutAttribute")))) - |> mkILMethods - let td = td.With(methods=meths) - yield td.With(methods=meths) ])} - //ILAsciiWriter.output_module stdout fakeModule - fakeModule.TypeDefs.AsList - - let ilxMainModule = - { ilxMainModule with - TypeDefs = mkILTypeDefs (tdefs1 @ tdefs2) } - ilxMainModule - [] type Node = { name: string @@ -1274,7 +1299,7 @@ module StaticLinker = mutable visited: bool } // Find all IL modules that are to be statically linked given the static linking roots. - let FindDependentILModulesForStaticLinking (ctok, tcConfig: TcConfig, tcImports: TcImports, ilGlobals, ilxMainModule) = + let FindDependentILModulesForStaticLinking (ctok, tcConfig: TcConfig, tcImports: TcImports, ilGlobals: ILGlobals, ilxMainModule) = if not tcConfig.standalone && tcConfig.extraStaticLinkRoots.IsEmpty then [] else @@ -1290,10 +1315,10 @@ module StaticLinker = let assumedIndependentSet = set [ "mscorlib"; "System"; "System.Core"; "System.Xml"; "Microsoft.Build.Framework"; "Microsoft.Build.Utilities" ] begin - let remaining = ref (computeILRefs ilxMainModule).AssemblyReferences - while not (isNil !remaining) do - let ilAssemRef = List.head !remaining - remaining := List.tail !remaining + let mutable remaining = (computeILRefs ilGlobals ilxMainModule).AssemblyReferences + while not (isNil remaining) do + let ilAssemRef = List.head remaining + remaining <- List.tail remaining if assumedIndependentSet.Contains ilAssemRef.Name || (ilAssemRef.PublicKey = Some ecmaPublicKey) then depModuleTable.[ilAssemRef.Name] <- dummyEntry ilAssemRef.Name else @@ -1322,8 +1347,7 @@ module StaticLinker = None let opts : ILReaderOptions = - { ilGlobals = ilGlobals - metadataOnly = MetadataOnlyFlag.No // turn this off here as we need the actual IL code + { metadataOnly = MetadataOnlyFlag.No // turn this off here as we need the actual IL code reduceMemoryUsage = tcConfig.reduceMemoryUsage pdbDirPath = pdbDirPathOption tryGetMetadataSnapshot = (fun _ -> None) } @@ -1350,7 +1374,7 @@ module StaticLinker = visited = false } // Push the new work items - remaining := refs.AssemblyReferences @ !remaining + remaining <- refs.AssemblyReferences @ remaining | None -> warning(Error(FSComp.SR.fscAssumeStaticLinkContainsNoDependencies(ilAssemRef.Name), rangeStartup)) @@ -1373,23 +1397,26 @@ module StaticLinker = for n in tcConfig.extraStaticLinkRoots do match depModuleTable.TryFind n with | Some x -> yield x - | None -> error(Error(FSComp.SR.fscAssemblyNotFoundInDependencySet(n), rangeStartup)) + | None -> error(Error(FSComp.SR.fscAssemblyNotFoundInDependencySet n, rangeStartup)) ] - let remaining = ref roots - [ while not (isNil !remaining) do - let n = List.head !remaining - remaining := List.tail !remaining + let mutable remaining = roots + [ while not (isNil remaining) do + let n = List.head remaining + remaining <- List.tail remaining if not n.visited then if verbose then dprintn ("Module "+n.name+" depends on "+GetFSharpCoreLibraryName()) n.visited <- true - remaining := n.edges @ !remaining + remaining <- n.edges @ remaining yield (n.ccu, n.data) ] // Add all provider-generated assemblies into the static linking set let FindProviderGeneratedILModules (ctok, tcImports: TcImports, providerGeneratedAssemblies: (ImportedBinary * _) list) = [ for (importedBinary, provAssemStaticLinkInfo) in providerGeneratedAssemblies do - let ilAssemRef = importedBinary.ILScopeRef.AssemblyRef + let ilAssemRef = + match importedBinary.ILScopeRef with + | ILScopeRef.Assembly aref -> aref + | _ -> failwith "Invalid ILScopeRef, expected ILScopeRef.Assembly" if debugStaticLinking then printfn "adding provider-generated assembly '%s' into static linking set" ilAssemRef.Name match tcImports.TryFindDllInfo(ctok, Range.rangeStartup, ilAssemRef.Name, lookupOnly=false) with | Some dllInfo -> @@ -1408,7 +1435,7 @@ module StaticLinker = let StaticLink (ctok, tcConfig: TcConfig, tcImports: TcImports, ilGlobals: ILGlobals) = #if !NO_EXTENSIONTYPING - let providerGeneratedAssemblies = + let providerGeneratedAssemblies = [ // Add all EST-generated assemblies into the static linking set for KeyValue(_, importedBinary: ImportedBinary) in tcImports.DllTable do @@ -1417,10 +1444,7 @@ module StaticLinker = | None -> () | Some provAssemStaticLinkInfo -> yield (importedBinary, provAssemStaticLinkInfo) ] #endif - if tcConfig.compilingFslib && tcConfig.compilingFslib20.IsSome then - (fun ilxMainModule -> LegacyFindAndAddMscorlibTypesForStaticLinkingIntoFSharpCoreLibraryForNet20 (tcConfig, ilGlobals, ilxMainModule)) - - elif not tcConfig.standalone && tcConfig.extraStaticLinkRoots.IsEmpty + if not tcConfig.standalone && tcConfig.extraStaticLinkRoots.IsEmpty #if !NO_EXTENSIONTYPING && providerGeneratedAssemblies.IsEmpty #endif @@ -1465,7 +1489,7 @@ module StaticLinker = let providerGeneratedILModules, ilxMainModule = // Build a dictionary of all remapped IL type defs let ilOrigTyRefsForProviderGeneratedTypesToRelocate = - let rec walk acc (ProviderGeneratedType(ilOrigTyRef, _, xs) as node) = List.fold walk ((ilOrigTyRef, node)::acc) xs + let rec walk acc (ProviderGeneratedType(ilOrigTyRef, _, xs) as node) = List.fold walk ((ilOrigTyRef, node) :: acc) xs dict (Seq.fold walk [] tcImports.ProviderGeneratedTypeRoots) // Build a dictionary of all IL type defs, mapping ilOrigTyRef --> ilTypeDef @@ -1489,7 +1513,7 @@ module StaticLinker = let generatedILTypeDefs = let rec buildRelocatedGeneratedType (ProviderGeneratedType(ilOrigTyRef, ilTgtTyRef, ch)) = let isNested = not (isNil ilTgtTyRef.Enclosing) - match allTypeDefsInProviderGeneratedAssemblies.TryGetValue(ilOrigTyRef) with + match allTypeDefsInProviderGeneratedAssemblies.TryGetValue ilOrigTyRef with | true, ilOrigTypeDef -> if debugStaticLinking then printfn "Relocating %s to %s " ilOrigTyRef.QualifiedName ilTgtTyRef.QualifiedName let ilOrigTypeDef = @@ -1524,14 +1548,14 @@ module StaticLinker = let rec loop xs acc = match xs with | [] -> List.rev acc, None, [] - | h::t -> if p h then List.rev acc, Some h, t else loop t (h::acc) + | h :: t -> if p h then List.rev acc, Some h, t else loop t (h :: acc) loop xs [] /// Implant the (nested) type definition 'td' at path 'enc' in 'tdefs'. let rec implantTypeDef isNested (tdefs: ILTypeDefs) (enc: string list) (td: ILTypeDef) = match enc with | [] -> addILTypeDef td tdefs - | h::t -> + | h :: t -> let tdefs = tdefs.AsList let (ltdefs, htd, rtdefs) = match tdefs |> trySplitFind (fun td -> td.Name = h) with @@ -1573,8 +1597,8 @@ module StaticLinker = // Glue all this stuff into ilxMainModule let ilxMainModule, rewriteExternalRefsToLocalRefs = - StaticLinkILModules (tcConfig, ilGlobals, ilxMainModule, dependentILModules @ providerGeneratedILModules) - + StaticLinkILModules (tcConfig, ilGlobals, tcImports, ilxMainModule, dependentILModules @ providerGeneratedILModules) + // Rewrite type and assembly references let ilxMainModule = let isMscorlib = ilGlobals.primaryAssemblyName = PrimaryAssembly.Mscorlib.Name @@ -1583,7 +1607,7 @@ module StaticLinker = if (not isMscorlib && name = PrimaryAssembly.Mscorlib.Name) then error (Error(FSComp.SR.fscStaticLinkingNoProfileMismatches(), rangeCmdArgs)) scopeRef - let rewriteAssemblyRefsToMatchLibraries = NormalizeAssemblyRefs (ctok, tcImports) + let rewriteAssemblyRefsToMatchLibraries = NormalizeAssemblyRefs (ctok, ilGlobals, tcImports) Morphs.morphILTypeRefsInILModuleMemoized ilGlobals (Morphs.morphILScopeRefsInILTypeRef (validateTargetPlatform >> rewriteExternalRefsToLocalRefs >> rewriteAssemblyRefsToMatchLibraries)) ilxMainModule ilxMainModule) @@ -1658,8 +1682,8 @@ let GetStrongNameSigner signingInfo = else Some (ILBinaryWriter.ILStrongNameSigner.OpenKeyPairFile s) with e -> - // Note:: don't use errorR here since we really want to fail and not produce a binary - error(Error(FSComp.SR.fscKeyFileCouldNotBeOpened(s), rangeCmdArgs)) + // Note :: don't use errorR here since we really want to fail and not produce a binary + error(Error(FSComp.SR.fscKeyFileCouldNotBeOpened s, rangeCmdArgs)) //---------------------------------------------------------------------------- // CopyFSharpCore @@ -1670,11 +1694,11 @@ let GetStrongNameSigner signingInfo = // 2) If not, but FSharp.Core.dll exists beside the compiler binaries, it will copy it to output directory. // 3) If not, it will produce an error. let CopyFSharpCore(outFile: string, referencedDlls: AssemblyReference list) = - let outDir = Path.GetDirectoryName(outFile) + let outDir = Path.GetDirectoryName outFile let fsharpCoreAssemblyName = GetFSharpCoreLibraryName() + ".dll" let fsharpCoreDestinationPath = Path.Combine(outDir, fsharpCoreAssemblyName) let copyFileIfDifferent src dest = - if not (File.Exists(dest)) || (File.GetCreationTimeUtc(src) <> File.GetCreationTimeUtc(dest)) then + if not (File.Exists dest) || (File.GetCreationTimeUtc src <> File.GetCreationTimeUtc dest) then File.Copy(src, dest, true) match referencedDlls |> Seq.tryFind (fun dll -> String.Equals(Path.GetFileName(dll.Text), fsharpCoreAssemblyName, StringComparison.CurrentCultureIgnoreCase)) with @@ -1682,9 +1706,9 @@ let CopyFSharpCore(outFile: string, referencedDlls: AssemblyReference list) = | None -> let executionLocation = Assembly.GetExecutingAssembly().Location - let compilerLocation = Path.GetDirectoryName(executionLocation) + let compilerLocation = Path.GetDirectoryName executionLocation let compilerFsharpCoreDllPath = Path.Combine(compilerLocation, fsharpCoreAssemblyName) - if File.Exists(compilerFsharpCoreDllPath) then + if File.Exists compilerFsharpCoreDllPath then copyFileIfDifferent compilerFsharpCoreDllPath fsharpCoreDestinationPath else errorR(Error(FSComp.SR.fsharpCoreNotFoundToBeCopied(), rangeCmdArgs)) @@ -1701,25 +1725,19 @@ let main0(ctok, argv, legacyReferenceResolver, bannerAlreadyPrinted, exiter: Exiter, errorLoggerProvider : ErrorLoggerProvider, disposables : DisposablesTracker) = // See Bug 735819 - let lcidFromCodePage = -#if FX_LCIDFROMCODEPAGE + let lcidFromCodePage = if (Console.OutputEncoding.CodePage <> 65001) && (Console.OutputEncoding.CodePage <> Thread.CurrentThread.CurrentUICulture.TextInfo.OEMCodePage) && (Console.OutputEncoding.CodePage <> Thread.CurrentThread.CurrentUICulture.TextInfo.ANSICodePage) then Thread.CurrentThread.CurrentUICulture <- new CultureInfo("en-US") Some 1033 else -#endif None let directoryBuildingFrom = Directory.GetCurrentDirectory() let setProcessThreadLocals tcConfigB = match tcConfigB.preferredUiLang with -#if FX_RESHAPED_GLOBALIZATION - | Some s -> System.Globalization.CultureInfo.CurrentUICulture <- new System.Globalization.CultureInfo(s) -#else - | Some s -> Thread.CurrentThread.CurrentUICulture <- new System.Globalization.CultureInfo(s) -#endif + | Some s -> Thread.CurrentThread.CurrentUICulture <- new CultureInfo(s) | None -> () if tcConfigB.utf8output then Console.OutputEncoding <- Encoding.UTF8 @@ -1744,7 +1762,7 @@ let main0(ctok, argv, legacyReferenceResolver, bannerAlreadyPrinted, SetTailcallSwitch tcConfigB OptionSwitch.On // Now install a delayed logger to hold all errors from flags until after all flags have been parsed (for example, --vserrors) - let delayForFlagsLogger = errorLoggerProvider.CreateDelayAndForwardLogger(exiter) + let delayForFlagsLogger = errorLoggerProvider.CreateDelayAndForwardLogger exiter let _unwindEL_1 = PushErrorLoggerPhaseUntilUnwind (fun _ -> delayForFlagsLogger) // Share intern'd strings across all lexing/parsing @@ -1763,7 +1781,7 @@ let main0(ctok, argv, legacyReferenceResolver, bannerAlreadyPrinted, with e -> errorRecovery e rangeStartup - delayForFlagsLogger.ForwardDelayedDiagnostics(tcConfigB) + delayForFlagsLogger.ForwardDelayedDiagnostics tcConfigB exiter.Exit 1 tcConfigB.conditionalCompilationDefines <- "COMPILED" :: tcConfigB.conditionalCompilationDefines @@ -1775,12 +1793,12 @@ let main0(ctok, argv, legacyReferenceResolver, bannerAlreadyPrinted, tcConfigB.DecideNames sourceFiles with e -> errorRecovery e rangeStartup - delayForFlagsLogger.ForwardDelayedDiagnostics(tcConfigB) + delayForFlagsLogger.ForwardDelayedDiagnostics tcConfigB exiter.Exit 1 // DecideNames may give "no inputs" error. Abort on error at this point. bug://3911 if not tcConfigB.continueAfterParseFailure && delayForFlagsLogger.ErrorCount > 0 then - delayForFlagsLogger.ForwardDelayedDiagnostics(tcConfigB) + delayForFlagsLogger.ForwardDelayedDiagnostics tcConfigB exiter.Exit 1 // If there's a problem building TcConfig, abort @@ -1788,7 +1806,7 @@ let main0(ctok, argv, legacyReferenceResolver, bannerAlreadyPrinted, try TcConfig.Create(tcConfigB, validate=false) with e -> - delayForFlagsLogger.ForwardDelayedDiagnostics(tcConfigB) + delayForFlagsLogger.ForwardDelayedDiagnostics tcConfigB exiter.Exit 1 let errorLogger = errorLoggerProvider.CreateErrorLoggerUpToMaxErrors(tcConfigB, exiter) @@ -1797,14 +1815,14 @@ let main0(ctok, argv, legacyReferenceResolver, bannerAlreadyPrinted, let _unwindEL_2 = PushErrorLoggerPhaseUntilUnwind (fun _ -> errorLogger) // Forward all errors from flags - delayForFlagsLogger.CommitDelayedDiagnostics(errorLogger) + delayForFlagsLogger.CommitDelayedDiagnostics errorLogger if not tcConfigB.continueAfterParseFailure then AbortOnError(errorLogger, exiter) // Resolve assemblies ReportTime tcConfig "Import mscorlib and FSharp.Core.dll" - let foundationalTcConfigP = TcConfigProvider.Constant(tcConfig) + let foundationalTcConfigP = TcConfigProvider.Constant tcConfig let sysRes, otherRes, knownUnresolved = TcAssemblyResolutions.SplitNonFoundationalResolutions(ctok, tcConfig) // Import basic assemblies @@ -1822,7 +1840,7 @@ let main0(ctok, argv, legacyReferenceResolver, bannerAlreadyPrinted, isLastCompiland |> List.zip sourceFiles // PERF: consider making this parallel, once uses of global state relevant to parsing are cleaned up |> List.choose (fun (filename: string, isLastCompiland) -> - let pathOfMetaCommandSource = Path.GetDirectoryName(filename) + let pathOfMetaCommandSource = Path.GetDirectoryName filename match ParseOneInputFile(tcConfig, lexResourceManager, ["COMPILED"], filename, (isLastCompiland, isExe), errorLogger, (*retryLocked*)false) with | Some input -> Some (input, pathOfMetaCommandSource) | None -> None @@ -1843,7 +1861,7 @@ let main0(ctok, argv, legacyReferenceResolver, bannerAlreadyPrinted, inputs |> List.iter (fun (input, _filename) -> printf "AST:\n"; printfn "%+A" input; printf "\n") let tcConfig = (tcConfig, inputs) ||> List.fold (fun z (x, m) -> ApplyMetaCommandsFromInputToTcConfig(z, x, m)) - let tcConfigP = TcConfigProvider.Constant(tcConfig) + let tcConfigP = TcConfigProvider.Constant tcConfig // Import other assemblies ReportTime tcConfig "Import non-system references" @@ -1887,7 +1905,7 @@ let main1(Args (ctok, tcGlobals, tcImports: TcImports, frameworkTcImports, gener // it as the updated global error logger and never remove it let oldLogger = errorLogger let errorLogger = - let scopedPragmas = [ for (TImplFile(_, pragmas, _, _, _, _)) in typedImplFiles do yield! pragmas ] + let scopedPragmas = [ for (TImplFile (_, pragmas, _, _, _, _)) in typedImplFiles do yield! pragmas ] GetErrorLoggerFilteringByScopedPragmas(true, scopedPragmas, oldLogger) let _unwindEL_3 = PushErrorLoggerPhaseUntilUnwind(fun _ -> errorLogger) @@ -1960,7 +1978,7 @@ let main1OfAst (ctok, legacyReferenceResolver, reduceMemoryUsage, assemblyName, with e -> exiter.Exit 1 - let foundationalTcConfigP = TcConfigProvider.Constant(tcConfig) + let foundationalTcConfigP = TcConfigProvider.Constant tcConfig let sysRes,otherRes,knownUnresolved = TcAssemblyResolutions.SplitNonFoundationalResolutions(ctok, tcConfig) let tcGlobals,frameworkTcImports = TcImports.BuildFrameworkTcImports (ctok, foundationalTcConfigP, sysRes, otherRes) |> Cancellable.runWithoutCancellation @@ -1968,7 +1986,7 @@ let main1OfAst (ctok, legacyReferenceResolver, reduceMemoryUsage, assemblyName, let meta = Directory.GetCurrentDirectory() let tcConfig = (tcConfig,inputs) ||> List.fold (fun tcc inp -> ApplyMetaCommandsFromInputToTcConfig (tcc, inp,meta)) - let tcConfigP = TcConfigProvider.Constant(tcConfig) + let tcConfigP = TcConfigProvider.Constant tcConfig let tcGlobals,tcImports = let tcImports = TcImports.BuildNonFrameworkTcImports(ctok, tcConfigP, tcGlobals, frameworkTcImports, otherRes,knownUnresolved) |> Cancellable.runWithoutCancellation @@ -1977,7 +1995,7 @@ let main1OfAst (ctok, legacyReferenceResolver, reduceMemoryUsage, assemblyName, use unwindParsePhase = PushThreadBuildPhaseUntilUnwind (BuildPhase.TypeCheck) let tcEnv0 = GetInitialTcEnv (assemblyName, rangeStartup, tcConfig, tcImports, tcGlobals) - let tcState,topAttrs,typedAssembly,_tcEnvAtEnd = + let tcState, topAttrs, typedAssembly, _tcEnvAtEnd = TypeCheck(ctok, tcConfig, tcImports, tcGlobals, errorLogger, assemblyName, NiceNameGenerator(), tcEnv0, inputs,exiter) let generatedCcu = tcState.Ccu @@ -2023,7 +2041,7 @@ let main2a(Args (ctok, tcConfig, tcImports, frameworkTcImports: TcImports, tcGlo use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Optimize let optEnv0 = GetInitialOptimizationEnv (tcImports, tcGlobals) - + let importMap = tcImports.GetImportMap() let metadataVersion = match tcConfig.metadataVersion with @@ -2140,8 +2158,10 @@ let main4 dynamicAssemblyCreator (Args (ctok, tcConfig, tcImports: TcImports, t embedAllSource = tcConfig.embedAllSource embedSourceList = tcConfig.embedSourceList sourceLink = tcConfig.sourceLink + checksumAlgorithm = tcConfig.checksumAlgorithm signer = GetStrongNameSigner signingInfo - dumpDebugInfo = tcConfig.dumpDebugInfo }, + dumpDebugInfo = tcConfig.dumpDebugInfo + pathMap = tcConfig.pathMap }, ilxMainModule, normalizeAssemblyRefs ) @@ -2170,7 +2190,13 @@ let typecheckAndCompile defaultCopyFSharpCore, exiter: Exiter, errorLoggerProvider, tcImportsCapture, dynamicAssemblyCreator) = use d = new DisposablesTracker() - use e = new SaveAndRestoreConsoleEncoding() + let savedOut = System.Console.Out + use __ = + { new IDisposable with + member __.Dispose() = + try + System.Console.SetOut(savedOut) + with _ -> ()} main0(ctok, argv, legacyReferenceResolver, bannerAlreadyPrinted, reduceMemoryUsage, defaultCopyFSharpCore, exiter, errorLoggerProvider, d) |> main1 @@ -2199,4 +2225,3 @@ let mainCompile (ctok, argv, legacyReferenceResolver, bannerAlreadyPrinted, reduceMemoryUsage, defaultCopyFSharpCore, exiter, errorLoggerProvider, tcImportsCapture, dynamicAssemblyCreator) - diff --git a/src/fcs-fable/src/fsharp/fsc.fsi b/src/fcs-fable/src/fsharp/fsc.fsi index b07c6fd120..ae90b34b82 100755 --- a/src/fcs-fable/src/fsharp/fsc.fsi +++ b/src/fcs-fable/src/fsharp/fsc.fsi @@ -2,14 +2,17 @@ module internal FSharp.Compiler.Driver -open FSharp.Compiler.Ast +open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.ILBinaryReader open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.ErrorLogger open FSharp.Compiler.CompileOps +open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.SyntaxTree open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypeChecker +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps [] type ErrorLoggerProvider = @@ -18,8 +21,10 @@ type ErrorLoggerProvider = type StrongNameSigningInfo -val EncodeInterfaceData: tcConfig:TcConfig * tcGlobals:TcGlobals * exportRemapping:Tastops.Remap * generatedCcu: Tast.CcuThunk * outfile: string * isIncrementalBuild: bool -> ILAttribute list * ILResource list -val ValidateKeySigningAttributes : tcConfig:TcConfig * tcGlobals:TcGlobals * TypeChecker.TopAttribs -> StrongNameSigningInfo +val EncodeInterfaceData: tcConfig:TcConfig * tcGlobals:TcGlobals * exportRemapping:Remap * generatedCcu: CcuThunk * outfile: string * isIncrementalBuild: bool -> ILAttribute list * ILResource list + +val ValidateKeySigningAttributes : tcConfig:TcConfig * tcGlobals:TcGlobals * TopAttribs -> StrongNameSigningInfo + val GetStrongNameSigner : StrongNameSigningInfo -> ILBinaryWriter.ILStrongNameSigner option /// Process the given set of command line arguments @@ -71,7 +76,6 @@ val compileOfAst : dynamicAssemblyCreator: (TcGlobals * string * ILModuleDef -> unit) option -> unit - /// Part of LegacyHostedCompilerForTesting type InProcErrorLoggerProvider = new : unit -> InProcErrorLoggerProvider diff --git a/src/fcs-fable/src/fsharp/fsc/fsc.fsproj b/src/fcs-fable/src/fsharp/fsc/fsc.fsproj deleted file mode 100644 index 581b4a1179..0000000000 --- a/src/fcs-fable/src/fsharp/fsc/fsc.fsproj +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - Exe - net46;netcoreapp2.1 - netcoreapp2.1 - .exe - $(NoWarn);45;55;62;75;1204 - true - $(OtherFlags) --maxerrors:20 --extraoptimizationloops:1 - true - true - - - - x86 - - - - - fscmain.fs - - - - default.win32manifest - PreserveNewest - - - - - - - - - - - - - - - - - - diff --git a/src/fcs-fable/src/fsharp/fscmain.fs b/src/fcs-fable/src/fsharp/fscmain.fs index f74c47e0da..f4c6b87c28 100644 --- a/src/fcs-fable/src/fsharp/fscmain.fs +++ b/src/fcs-fable/src/fsharp/fscmain.fs @@ -62,7 +62,7 @@ module Driver = #if CROSS_PLATFORM_COMPILER SimulatedMSBuildReferenceResolver.SimulatedMSBuildResolver #else - MSBuildReferenceResolver.Resolver + LegacyMSBuildReferenceResolver.getResolver() #endif // This is the only place where ReduceMemoryFlag.No is set. This is because fsc.exe is not a long-running process and @@ -77,7 +77,6 @@ let main(argv) = System.Runtime.GCSettings.LatencyMode <- System.Runtime.GCLatencyMode.Batch use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parameter - if not runningOnMono then Lib.UnmanagedProcessExecutionOptions.EnableHeapTerminationOnCorruption() (* SDL recommendation *) Lib.UnmanagedProcessExecutionOptions.EnableHeapTerminationOnCorruption() (* SDL recommendation *) try diff --git a/src/fcs-fable/src/fsharp/fsi/FSIstrings.txt b/src/fcs-fable/src/fsharp/fsi/FSIstrings.txt deleted file mode 100755 index d02cfeb79c..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/FSIstrings.txt +++ /dev/null @@ -1,54 +0,0 @@ -# fsi.exe resource strings -stoppedDueToError,"Stopped due to error\n" -fsiUsage,"Usage: %s [script.fsx []]" -fsiInputFiles,"- INPUT FILES -" -fsiCodeGeneration,"- CODE GENERATION -" -fsiErrorsAndWarnings,"- ERRORS AND WARNINGS -" -fsiLanguage,"- LANGUAGE -" -fsiMiscellaneous,"- MISCELLANEOUS -" -fsiAdvanced,"- ADVANCED -" -fsiExceptionRaisedStartingServer,"Exception raised when starting remoting server.\n%s" -fsiUse,"Use the given file on startup as initial input" -fsiLoad,"#load the given file on startup" -fsiRemaining,"Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs" -fsiHelp,"Display this usage message (Short form: -?)" -fsiExec,"Exit fsi after loading the files or running the .fsx script given on the command line" -fsiGui,"Execute interactions on a Windows Forms event loop (on by default)" -fsiQuiet,"Suppress fsi writing to stdout" -fsiReadline,"Support TAB completion in console (on by default)" -fsiEmitDebugInfoInQuotations,"Emit debug information in quotations" -fsiBanner3,"For help type #help;;" -fsiConsoleProblem,"A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'." -2301,fsiInvalidAssembly,"'%s' is not a valid assembly name" -2302,fsiDirectoryDoesNotExist,"Directory '%s' doesn't exist" -fsiInvalidDirective,"Invalid directive '#%s %s'" -fsiLineTooLong,"Warning: line too long, ignoring some characters\n" -fsiTimeInfoMainString,"Real: %s, CPU: %s, GC %s" -fsiTimeInfoGCGenerationLabelSomeShorthandForTheWordGeneration,"gen" -fsiExceptionDuringPrettyPrinting,"\n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: %s\n" -fsiIntroTextHeader1directives," F# Interactive directives:" -fsiIntroTextHashrInfo,"Reference (dynamically load) the given DLL" -fsiIntroTextHashIInfo,"Add the given search path for referenced DLLs" -fsiIntroTextHashloadInfo,"Load the given file(s) as if compiled and referenced" -fsiIntroTextHashtimeInfo,"Toggle timing on/off" -fsiIntroTextHashhelpInfo,"Display help" -fsiIntroTextHashquitInfo,"Exit" -fsiIntroTextHeader2commandLine," F# Interactive command line options:" -fsiIntroTextHeader3," See '%s' for options" -fsiLoadingFilesPrefixText,"Loading" -fsiInterrupt,"\n- Interrupt\n" -fsiExit,"\n- Exit...\n" -fsiAbortingMainThread,"- Aborting main thread..." -fsiCouldNotInstallCtrlCHandler,"Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t%s" -fsiDidAHashr,"--> Referenced '%s'" -fsiDidAHashrWithLockWarning,"--> Referenced '%s' (file may be locked by F# Interactive process)" -fsiDidAHashrWithStaleWarning,"--> Referenced '%s' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly)" -fsiDidAHashI,"--> Added '%s' to library include path" -fsiTurnedTimingOn,"--> Timing now on" -fsiTurnedTimingOff,"--> Timing now off" -fsiUnexpectedThreadAbortException,"- Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart..." -fsiFailedToResolveAssembly,"Failed to resolve assembly '%s'" -fsiBindingSessionTo,"Binding session to '%s'..." -fsiProductName,"Microsoft (R) F# Interactive version %s" -fsiProductNameCommunity,"F# Interactive for F# %s" -shadowCopyReferences,"Prevents references from being locked by the F# Interactive process" diff --git a/src/fcs-fable/src/fsharp/fsi/fsi.fs b/src/fcs-fable/src/fsharp/fsi/fsi.fs deleted file mode 100644 index 7a4a8edead..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/fsi.fs +++ /dev/null @@ -1,3036 +0,0 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. - -module FSharp.Compiler.Interactive.Shell - -#nowarn "55" - -[] -[] -do() - - -open System -open System.Collections.Generic -open System.Diagnostics -open System.Globalization -open System.Runtime.InteropServices -open System.IO -open System.Text -open System.Threading -open System.Reflection -open System.Runtime.CompilerServices -open FSharp.Compiler -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.Diagnostics -open FSharp.Compiler.AbstractIL.IL -open FSharp.Compiler.AbstractIL.ILBinaryReader -open FSharp.Compiler.AbstractIL.Internal -open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.AbstractIL.Extensions.ILX -open FSharp.Compiler.AbstractIL.ILRuntimeWriter -open FSharp.Compiler.Lib -open FSharp.Compiler.AccessibilityLogic -open FSharp.Compiler.Ast -open FSharp.Compiler.CompileOptions -open FSharp.Compiler.CompileOps -open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Infos -open FSharp.Compiler.InfoReader -open FSharp.Compiler.NameResolution -open FSharp.Compiler.IlxGen -open FSharp.Compiler.Lexhelp -open FSharp.Compiler.Layout -open FSharp.Compiler.Lib -open FSharp.Compiler.Optimizer -open FSharp.Compiler.PostTypeCheckSemanticChecks -open FSharp.Compiler.Range -open FSharp.Compiler.TypeChecker -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.TcGlobals -open FSharp.Compiler.SourceCodeServices -open FSharp.Compiler.ReferenceResolver - -open Internal.Utilities -open Internal.Utilities.Collections -open Internal.Utilities.StructuredFormat - -//---------------------------------------------------------------------------- -// For the FSI as a service methods... -//---------------------------------------------------------------------------- - -type FsiValue(reflectionValue:obj, reflectionType:Type, fsharpType:FSharpType) = - member x.ReflectionValue = reflectionValue - member x.ReflectionType = reflectionType - member x.FSharpType = fsharpType - - -[] -module internal Utilities = - type IAnyToLayoutCall = - abstract AnyToLayout : FormatOptions * obj * Type -> Internal.Utilities.StructuredFormat.Layout - abstract FsiAnyToLayout : FormatOptions * obj * Type -> Internal.Utilities.StructuredFormat.Layout - - type private AnyToLayoutSpecialization<'T>() = - interface IAnyToLayoutCall with - member this.AnyToLayout(options, o : obj, ty : Type) = Internal.Utilities.StructuredFormat.Display.any_to_layout options ((Unchecked.unbox o : 'T), ty) - member this.FsiAnyToLayout(options, o : obj, ty : Type) = Internal.Utilities.StructuredFormat.Display.fsi_any_to_layout options ((Unchecked.unbox o : 'T), ty) - - let getAnyToLayoutCall ty = - let specialized = typedefof>.MakeGenericType [| ty |] - Activator.CreateInstance(specialized) :?> IAnyToLayoutCall - - let callStaticMethod (ty:Type) name args = - ty.InvokeMember(name, (BindingFlags.InvokeMethod ||| BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic), null, null, Array.ofList args,Globalization.CultureInfo.InvariantCulture) - - let ignoreAllErrors f = try f() with _ -> () - - // TODO: this dotnet/core polyfill can be removed when it surfaces in Type - let getMember (name: string) (memberType: MemberTypes) (attr: BindingFlags) (declaringType: Type) = - let memberType = - if memberType &&& MemberTypes.NestedType = MemberTypes.NestedType then - memberType ||| MemberTypes.TypeInfo - else - memberType - declaringType.GetMembers(attr) |> Array.filter(fun m -> 0 <> (int(m.MemberType &&& memberType)) && m.Name = name) - - let rec tryFindMember (name: string) (memberType: MemberTypes) (declaringType: Type) = - let bindingFlags = BindingFlags.Instance ||| BindingFlags.Public ||| BindingFlags.NonPublic - match declaringType |> getMember name memberType bindingFlags with - | [||] -> declaringType.GetInterfaces() |> Array.tryPick (tryFindMember name memberType) - | [|m|] -> Some m - | _ -> raise <| new AmbiguousMatchException(sprintf "Ambiguous match for member '%s'" name) - - let getInstanceProperty (obj:obj) (nm:string) = - let p = (tryFindMember nm MemberTypes.Property <| obj.GetType()).Value :?> PropertyInfo - p.GetValue(obj, [||]) |> unbox - - let setInstanceProperty (obj:obj) (nm:string) (v:obj) = - let p = (tryFindMember nm MemberTypes.Property <| obj.GetType()).Value :?> PropertyInfo - p.SetValue(obj, v, [||]) |> unbox - - let callInstanceMethod0 (obj:obj) (typeArgs : Type []) (nm:string) = - let m = (tryFindMember nm MemberTypes.Method <| obj.GetType()).Value :?> MethodInfo - let m = match typeArgs with [||] -> m | _ -> m.MakeGenericMethod(typeArgs) - m.Invoke(obj, [||]) |> unbox - - let callInstanceMethod1 (obj:obj) (typeArgs : Type []) (nm:string) (v:obj) = - let m = (tryFindMember nm MemberTypes.Method <| obj.GetType()).Value :?> MethodInfo - let m = match typeArgs with [||] -> m | _ -> m.MakeGenericMethod(typeArgs) - m.Invoke(obj, [|v|]) |> unbox - - let callInstanceMethod3 (obj:obj) (typeArgs : Type []) (nm:string) (v1:obj) (v2:obj) (v3:obj) = - let m = (tryFindMember nm MemberTypes.Method <| obj.GetType()).Value :?> MethodInfo - let m = match typeArgs with [||] -> m | _ -> m.MakeGenericMethod(typeArgs) - m.Invoke(obj, [|v1;v2;v3|]) |> unbox - - let colorPrintL (outWriter : TextWriter) opts layout = - let renderer = - { new LayoutRenderer with - member r.Start () = NoState - - member r.AddText z s = - let color = - match s.Tag with - | LayoutTag.Keyword -> ConsoleColor.White - | LayoutTag.TypeParameter - | LayoutTag.Alias - | LayoutTag.Class - | LayoutTag.Module - | LayoutTag.Interface - | LayoutTag.Record - | LayoutTag.Struct - | LayoutTag.Union - | LayoutTag.UnknownType -> ConsoleColor.Cyan - | LayoutTag.UnionCase - | LayoutTag.ActivePatternCase -> ConsoleColor.Magenta - | LayoutTag.StringLiteral -> ConsoleColor.Yellow - | LayoutTag.NumericLiteral -> ConsoleColor.Green - | _ -> Console.ForegroundColor - - DoWithColor color (fun () -> outWriter.Write s.Text) - - z - - member r.AddBreak z n = - outWriter.WriteLine() - outWriter.Write (String.replicate n " ") - z - - member r.AddTag z (tag,attrs,start) = z - - member r.Finish z = - outWriter.WriteLine() - NoResult - } - - layout - |> Internal.Utilities.StructuredFormat.Display.squash_layout opts - |> Layout.renderL renderer - |> ignore - - outWriter.WriteLine() - -//---------------------------------------------------------------------------- -// Timing support -//---------------------------------------------------------------------------- - -[] -type internal FsiTimeReporter(outWriter: TextWriter) = - let stopwatch = new System.Diagnostics.Stopwatch() - let ptime = System.Diagnostics.Process.GetCurrentProcess() - let numGC = System.GC.MaxGeneration - member tr.TimeOp(f) = - let startTotal = ptime.TotalProcessorTime - let startGC = [| for i in 0 .. numGC -> System.GC.CollectionCount(i) |] - stopwatch.Reset() - stopwatch.Start() - let res = f () - stopwatch.Stop() - let total = ptime.TotalProcessorTime - startTotal - let spanGC = [ for i in 0 .. numGC-> System.GC.CollectionCount(i) - startGC.[i] ] - let elapsed = stopwatch.Elapsed - fprintfn outWriter "%s" (FSIstrings.SR.fsiTimeInfoMainString((sprintf "%02d:%02d:%02d.%03d" (int elapsed.TotalHours) elapsed.Minutes elapsed.Seconds elapsed.Milliseconds),(sprintf "%02d:%02d:%02d.%03d" (int total.TotalHours) total.Minutes total.Seconds total.Milliseconds),(String.concat ", " (List.mapi (sprintf "%s%d: %d" (FSIstrings.SR.fsiTimeInfoGCGenerationLabelSomeShorthandForTheWordGeneration())) spanGC)))) - res - - member tr.TimeOpIf flag f = if flag then tr.TimeOp f else f () - - -type internal FsiValuePrinterMode = - | PrintExpr - | PrintDecl - -type EvaluationEventArgs(fsivalue : FsiValue option, symbolUse : FSharpSymbolUse, decl: FSharpImplementationFileDeclaration) = - inherit EventArgs() - member x.Name = symbolUse.Symbol.DisplayName - member x.FsiValue = fsivalue - member x.SymbolUse = symbolUse - member x.Symbol = symbolUse.Symbol - member x.ImplementationDeclaration = decl - -[] -/// User-configurable information that changes how F# Interactive operates, stored in the 'fsi' object -/// and accessible via the programming model -type FsiEvaluationSessionHostConfig () = - let evaluationEvent = new Event () - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract FormatProvider: System.IFormatProvider - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract FloatingPointFormat: string - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract AddedPrinters : Choice<(System.Type * (obj -> string)), (System.Type * (obj -> obj))> list - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract ShowDeclarationValues: bool - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract ShowIEnumerable: bool - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract ShowProperties : bool - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract PrintSize : int - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract PrintDepth : int - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract PrintWidth : int - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract PrintLength : int - - /// The evaluation session calls this to report the preferred view of the command line arguments after - /// stripping things like "/use:file.fsx", "-r:Foo.dll" etc. - abstract ReportUserCommandLineArgs : string [] -> unit - - - /// The evaluation session calls this to ask the host for the special console reader. - /// Returning 'Some' indicates a console is to be used, so some special rules apply. - /// - /// A "console" gets used if - /// --readline- is specified (the default on Windows + .NET); and - /// not --fsi-server (which should always be combined with --readline-); and - /// GetOptionalConsoleReadLine() returns a Some - /// - /// "Peekahead" occurs if --peekahead- is not specified (i.e. it is the default): - /// - If a console is being used then - /// - a prompt is printed early - /// - a background thread is created - /// - the GetOptionalConsoleReadLine() callback is used to read the first line - /// - Otherwise call inReader.Peek() - /// - /// Further lines are read as follows: - /// - If a console is being used then use GetOptionalConsoleReadLine() - /// - Otherwise use inReader.ReadLine() - - abstract GetOptionalConsoleReadLine : probeToSeeIfConsoleWorks: bool -> (unit -> string) option - - /// The evaluation session calls this at an appropriate point in the startup phase if the --fsi-server parameter was given - abstract StartServer : fsiServerName:string -> unit - - /// Called by the evaluation session to ask the host to enter a dispatch loop like Application.Run(). - /// Only called if --gui option is used (which is the default). - /// Gets called towards the end of startup and every time a ThreadAbort escaped to the backup driver loop. - /// Return true if a 'restart' is required, which is a bit meaningless. - abstract EventLoopRun : unit -> bool - - /// Request that the given operation be run synchronously on the event loop. - abstract EventLoopInvoke : codeToRun: (unit -> 'T) -> 'T - - /// Schedule a restart for the event loop. - abstract EventLoopScheduleRestart : unit -> unit - - /// Implicitly reference FSharp.Compiler.Interactive.Settings.dll - abstract UseFsiAuxLib : bool - - /// Hook for listening for evaluation bindings - member x.OnEvaluation = evaluationEvent.Publish - member internal x.TriggerEvaluation (value, symbolUse, decl) = - evaluationEvent.Trigger (EvaluationEventArgs (value, symbolUse, decl) ) - -/// Used to print value signatures along with their values, according to the current -/// set of pretty printers installed in the system, and default printing rules. -type internal FsiValuePrinter(fsi: FsiEvaluationSessionHostConfig, g: TcGlobals, generateDebugInfo, resolveAssemblyRef, outWriter: TextWriter) = - - /// This printer is used by F# Interactive if no other printers apply. - let DefaultPrintingIntercept (ienv: Internal.Utilities.StructuredFormat.IEnvironment) (obj:obj) = - match obj with - | null -> None - | :? System.Collections.IDictionary as ie -> - let it = ie.GetEnumerator() - try - let itemLs = - Internal.Utilities.StructuredFormat.LayoutOps.unfoldL // the function to layout each object in the unfold - (fun obj -> ienv.GetLayout obj) - // the function to call at each step of the unfold - (fun () -> - if it.MoveNext() then - Some((it.Key, it.Value),()) - else None) () - // the maximum length - (1+fsi.PrintLength/3) - let makeListL itemLs = - (leftL (TaggedTextOps.tagText "[")) ^^ - sepListL (rightL (TaggedTextOps.tagText ";")) itemLs ^^ - (rightL (TaggedTextOps.tagText "]")) - Some(wordL (TaggedTextOps.tagText "dict") --- makeListL itemLs) - finally - match it with - | :? System.IDisposable as d -> d.Dispose() - | _ -> () - - | _ -> None - - - /// Get the print options used when formatting output using the structured printer. - member __.GetFsiPrintOptions() = - { Internal.Utilities.StructuredFormat.FormatOptions.Default with - FormatProvider = fsi.FormatProvider; - PrintIntercepts = - // The fsi object supports the addition of two kinds of printers, one which converts to a string - // and one which converts to another object that is recursively formatted. - // The internal AddedPrinters reports these to FSI.EXE and we pick them up here to produce a layout - [ for x in fsi.AddedPrinters do - match x with - | Choice1Of2 (aty: System.Type, printer) -> - yield (fun _ienv (obj:obj) -> - match obj with - | null -> None - | _ when aty.IsAssignableFrom(obj.GetType()) -> - match printer obj with - | null -> None - | s -> Some (wordL (TaggedTextOps.tagText s)) - | _ -> None) - - | Choice2Of2 (aty: System.Type, converter) -> - yield (fun ienv (obj:obj) -> - match obj with - | null -> None - | _ when aty.IsAssignableFrom(obj.GetType()) -> - match converter obj with - | null -> None - | res -> Some (ienv.GetLayout res) - | _ -> None) - yield DefaultPrintingIntercept]; - FloatingPointFormat = fsi.FloatingPointFormat; - PrintWidth = fsi.PrintWidth; - PrintDepth = fsi.PrintDepth; - PrintLength = fsi.PrintLength; - PrintSize = fsi.PrintSize; - ShowProperties = fsi.ShowProperties; - ShowIEnumerable = fsi.ShowIEnumerable; } - - /// Get the evaluation context used when inverting the storage mapping of the ILRuntimeWriter. - member __.GetEvaluationContext emEnv = - let cenv = { ilg = g.ilg ; generatePdb = generateDebugInfo; resolveAssemblyRef=resolveAssemblyRef; tryFindSysILTypeRef=g.TryFindSysILTypeRef } - { LookupFieldRef = ILRuntimeWriter.LookupFieldRef emEnv >> Option.get - LookupMethodRef = ILRuntimeWriter.LookupMethodRef emEnv >> Option.get - LookupTypeRef = ILRuntimeWriter.LookupTypeRef cenv emEnv - LookupType = ILRuntimeWriter.LookupType cenv emEnv } - - /// Generate a layout for an actual F# value, where we know the value has the given static type. - member __.PrintValue (printMode, opts:FormatOptions, x:obj, ty:System.Type) = - // We do a dynamic invoke of any_to_layout with the right System.Type parameter for the static type of the saved value. - // In principle this helps any_to_layout do the right thing as it descends through terms. In practice it means - // it at least does the right thing for top level 'null' list and option values (but not for nested ones). - // - // The static type was saved into the location used by RuntimeHelpers.GetSavedItType when RuntimeHelpers.SaveIt was called. - // RuntimeHelpers.SaveIt has type ('a -> unit), and fetches the System.Type for 'a by using a typeof<'a> call. - // The funny thing here is that you might think that the driver (this file) knows more about the static types - // than the compiled code does. But it doesn't! In particular, it's not that easy to get a System.Type value based on the - // static type information we do have: we have no direct way to bind a F# TAST type or even an AbstractIL type to - // a System.Type value (I guess that functionality should be in ilreflect.fs). - // - // This will be more significant when we print values other then 'it' - // - try - let anyToLayoutCall = Utilities.getAnyToLayoutCall ty - match printMode with - | PrintDecl -> - // When printing rhs of fsi declarations, use "fsi_any_to_layout". - // This will suppress some less informative values, by returning an empty layout. [fix 4343]. - anyToLayoutCall.FsiAnyToLayout(opts, x, ty) - | PrintExpr -> - anyToLayoutCall.AnyToLayout(opts, x, ty) - with -#if !FX_REDUCED_EXCEPTIONS - | :? ThreadAbortException -> Layout.wordL (TaggedTextOps.tagText "") -#endif - | e -> -#if DEBUG - printf "\n\nPrintValue: x = %+A and ty=%s\n" x (ty.FullName) -#endif - printf "%s" (FSIstrings.SR.fsiExceptionDuringPrettyPrinting(e.ToString())); - Layout.wordL (TaggedTextOps.tagText "") - - /// Display the signature of an F# value declaration, along with its actual value. - member valuePrinter.InvokeDeclLayout (emEnv, ilxGenerator: IlxAssemblyGenerator, v:Val) = - // Implemented via a lookup from v to a concrete (System.Object,System.Type). - // This (obj,objTy) pair can then be fed to the fsi value printer. - // Note: The value may be (null:Object). - // Note: A System.Type allows the value printer guide printing of nulls, e.g. as None or []. - //------- - // IlxGen knows what the v:Val was converted to w.r.t. AbsIL datastructures. - // Ilreflect knows what the AbsIL was generated to. - // Combining these allows for obtaining the (obj,objTy) by reflection where possible. - // This assumes the v:Val was given appropriate storage, e.g. StaticField. - if fsi.ShowDeclarationValues then - // Adjust "opts" for printing for "declared-values": - // - No sequences, because they may have effects or time cost. - // - No properties, since they may have unexpected effects. - // - Limit strings to roughly one line, since huge strings (e.g. 1 million chars without \n are slow in vfsi). - // - Limit PrintSize which is a count on nodes. - let declaredValueReductionFactor = 10 (* reduce PrintSize for declared values, e.g. see less of large terms *) - let opts = valuePrinter.GetFsiPrintOptions() - let opts = {opts with ShowProperties = false // properties off, motivated by Form props - ShowIEnumerable = false // seq off, motivated by db query concerns - StringLimit = max 0 (opts.PrintWidth-4) // 4 allows for an indent of 2 and 2 quotes (rough) - PrintSize = opts.PrintSize / declaredValueReductionFactor } // print less - let res = - try ilxGenerator.LookupGeneratedValue (valuePrinter.GetEvaluationContext emEnv, v) - with e -> - assert false -#if DEBUG - //fprintfn fsiConsoleOutput.Out "lookGenerateVal: failed on v=%+A v.Name=%s" v v.LogicalName -#endif - None // lookup may fail - match res with - | None -> None - | Some (obj,objTy) -> - let lay = valuePrinter.PrintValue (FsiValuePrinterMode.PrintDecl, opts, obj, objTy) - if isEmptyL lay then None else Some lay // suppress empty layout - - else - None - - - /// Format a value - member valuePrinter.FormatValue (obj:obj, objTy) = - let opts = valuePrinter.GetFsiPrintOptions() - let lay = valuePrinter.PrintValue (FsiValuePrinterMode.PrintExpr, opts, obj, objTy) - Internal.Utilities.StructuredFormat.Display.layout_to_string opts lay - - /// Fetch the saved value of an expression out of the 'it' register and show it. - member valuePrinter.InvokeExprPrinter (denv, emEnv, ilxGenerator: IlxAssemblyGenerator, vref) = - let opts = valuePrinter.GetFsiPrintOptions() - let res = ilxGenerator.LookupGeneratedValue (valuePrinter.GetEvaluationContext emEnv, vref) - let rhsL = - match res with - | None -> None - | Some (obj,objTy) -> - let lay = valuePrinter.PrintValue (FsiValuePrinterMode.PrintExpr, opts, obj, objTy) - if isEmptyL lay then None else Some lay // suppress empty layout - let denv = { denv with suppressMutableKeyword = true } // suppress 'mutable' in 'val mutable it = ...' - let fullL = - if Option.isNone rhsL || isEmptyL rhsL.Value then - NicePrint.prettyLayoutOfValOrMemberNoInst denv vref (* the rhs was suppressed by the printer, so no value to print *) - else - (NicePrint.prettyLayoutOfValOrMemberNoInst denv vref ++ wordL (TaggedTextOps.tagText "=")) --- rhsL.Value - - Utilities.colorPrintL outWriter opts fullL - -/// Used to make a copy of input in order to include the input when displaying the error text. -type internal FsiStdinSyphon(errorWriter: TextWriter) = - let syphonText = new StringBuilder() - - /// Clears the syphon text - member x.Reset () = - syphonText.Clear() |> ignore - - /// Adds a new line to the syphon text - member x.Add (str:string) = - syphonText.Append str |> ignore - - /// Gets the indicated line in the syphon text - member x.GetLine filename i = - if filename <> Lexhelp.stdinMockFilename then - "" - else - let text = syphonText.ToString() - // In Visual Studio, when sending a block of text, it prefixes with '# "filename"\n' - // and postfixes with '# 1 "stdin"\n'. To first, get errors filename context, - // and second to get them back into stdin context (no position stack...). - // To find an error line, trim upto the last stdinReset string the syphoned text. - //printf "PrePrune:-->%s<--\n\n" text; - let rec prune (text:string) = - let stdinReset = "# 1 \"stdin\"\n" - let idx = text.IndexOf(stdinReset,StringComparison.Ordinal) - if idx <> -1 then - prune (text.Substring(idx + stdinReset.Length)) - else - text - - let text = prune text - let lines = text.Split '\n' - if 0 < i && i <= lines.Length then lines.[i-1] else "" - - /// Display the given error. - member syphon.PrintError (tcConfig:TcConfigBuilder, err) = - Utilities.ignoreAllErrors (fun () -> - let isError = true - DoWithErrorColor isError (fun () -> - errorWriter.WriteLine(); - writeViaBufferWithEnvironmentNewLines errorWriter (OutputDiagnosticContext " " syphon.GetLine) err; - writeViaBufferWithEnvironmentNewLines errorWriter (OutputDiagnostic (tcConfig.implicitIncludeDir,tcConfig.showFullPaths,tcConfig.flatErrors,tcConfig.errorStyle,isError)) err; - errorWriter.WriteLine() - errorWriter.WriteLine() - errorWriter.Flush())) - - - -/// Encapsulates functions used to write to outWriter and errorWriter -type internal FsiConsoleOutput(tcConfigB, outWriter:TextWriter, errorWriter:TextWriter) = - - let nullOut = new StreamWriter(Stream.Null) :> TextWriter - let fprintfnn (os: TextWriter) fmt = Printf.kfprintf (fun _ -> os.WriteLine(); os.WriteLine()) os fmt - /// uprintf to write usual responses to stdout (suppressed by --quiet), with various pre/post newlines - member out.uprintf fmt = fprintf (if tcConfigB.noFeedback then nullOut else outWriter) fmt - member out.uprintfn fmt = fprintfn (if tcConfigB.noFeedback then nullOut else outWriter) fmt - member out.uprintfnn fmt = fprintfnn (if tcConfigB.noFeedback then nullOut else outWriter) fmt - member out.uprintnf fmt = out.uprintfn ""; out.uprintf fmt - member out.uprintnfn fmt = out.uprintfn ""; out.uprintfn fmt - member out.uprintnfnn fmt = out.uprintfn ""; out.uprintfnn fmt - - member out.Out = outWriter - member out.Error = errorWriter - - -/// This ErrorLogger reports all warnings, but raises StopProcessing on first error or early exit -type internal ErrorLoggerThatStopsOnFirstError(tcConfigB:TcConfigBuilder, fsiStdinSyphon:FsiStdinSyphon, fsiConsoleOutput: FsiConsoleOutput) = - inherit ErrorLogger("ErrorLoggerThatStopsOnFirstError") - let mutable errorCount = 0 - - member x.SetError() = - errorCount <- 1 - - member x.ResetErrorCount() = (errorCount <- 0) - - override x.DiagnosticSink(err, isError) = - if isError || ReportWarningAsError tcConfigB.errorSeverityOptions err then - fsiStdinSyphon.PrintError(tcConfigB,err) - errorCount <- errorCount + 1 - if tcConfigB.abortOnError then exit 1 (* non-zero exit code *) - // STOP ON FIRST ERROR (AVOIDS PARSER ERROR RECOVERY) - raise StopProcessing - else - DoWithErrorColor isError (fun () -> - if ReportWarning tcConfigB.errorSeverityOptions err then - fsiConsoleOutput.Error.WriteLine() - writeViaBufferWithEnvironmentNewLines fsiConsoleOutput.Error (OutputDiagnosticContext " " fsiStdinSyphon.GetLine) err - writeViaBufferWithEnvironmentNewLines fsiConsoleOutput.Error (OutputDiagnostic (tcConfigB.implicitIncludeDir,tcConfigB.showFullPaths,tcConfigB.flatErrors,tcConfigB.errorStyle,isError)) err - fsiConsoleOutput.Error.WriteLine() - fsiConsoleOutput.Error.WriteLine() - fsiConsoleOutput.Error.Flush()) - - override x.ErrorCount = errorCount - -type ErrorLogger with - member x.CheckForErrors() = (x.ErrorCount > 0) - /// A helper function to check if its time to abort - member x.AbortOnError(fsiConsoleOutput:FsiConsoleOutput) = - if x.ErrorCount > 0 then - fprintf fsiConsoleOutput.Error "%s" (FSIstrings.SR.stoppedDueToError()) - fsiConsoleOutput.Error.Flush() - raise StopProcessing - -/// Get the directory name from a string, with some defaults if it doesn't have one -let internal directoryName (s:string) = - if s = "" then "." - else - match Path.GetDirectoryName s with - | null -> if FileSystem.IsPathRootedShim s then s else "." - | res -> if res = "" then "." else res - - - - -//---------------------------------------------------------------------------- -// cmd line - state for options -//---------------------------------------------------------------------------- - -/// Process the command line options -type internal FsiCommandLineOptions(fsi: FsiEvaluationSessionHostConfig, argv: string[], tcConfigB, fsiConsoleOutput: FsiConsoleOutput) = - let mutable enableConsoleKeyProcessing = -#if FX_REDUCED_CONSOLE - false -#else - // Mono on Win32 doesn't implement correct console processing - not (runningOnMono && System.Environment.OSVersion.Platform = System.PlatformID.Win32NT) -#endif - let mutable gui = not runningOnMono // override via "--gui", on by default except when on Mono -#if DEBUG - let mutable showILCode = false // show modul il code -#endif - let mutable showTypes = true // show types after each interaction? - let mutable fsiServerName = "" - let mutable interact = true - let mutable explicitArgs = [] - - let mutable inputFilesAcc = [] - - let mutable fsiServerInputCodePage = None - let mutable fsiServerOutputCodePage = None - let mutable fsiLCID = None - - // internal options - let mutable probeToSeeIfConsoleWorks = true - let mutable peekAheadOnConsoleToPermitTyping = true - - let isInteractiveServer() = fsiServerName <> "" - let recordExplicitArg arg = explicitArgs <- explicitArgs @ [arg] - - let executableFileName = - lazy - match tcConfigB.exename with - | Some s -> s - | None -> - let currentProcess = System.Diagnostics.Process.GetCurrentProcess() - Path.GetFileName(currentProcess.MainModule.FileName) - - - // Additional fsi options are list below. - // In the "--help", these options can be printed either before (fsiUsagePrefix) or after (fsiUsageSuffix) the core options. - - let displayHelpFsi tcConfigB (blocks:CompilerOptionBlock list) = - DisplayBannerText tcConfigB; - fprintfn fsiConsoleOutput.Out "" - fprintfn fsiConsoleOutput.Out "%s" (FSIstrings.SR.fsiUsage(executableFileName.Value)) - PrintCompilerOptionBlocks blocks - exit 0 - - // option tags - let tagFile = "" - let tagNone = "" - - /// These options precede the FsiCoreCompilerOptions in the help blocks - let fsiUsagePrefix tcConfigB = - [PublicOptions(FSIstrings.SR.fsiInputFiles(), - [CompilerOption("use",tagFile, OptionString (fun s -> inputFilesAcc <- inputFilesAcc @ [(s,true)]), None, - Some (FSIstrings.SR.fsiUse())); - CompilerOption("load",tagFile, OptionString (fun s -> inputFilesAcc <- inputFilesAcc @ [(s,false)]), None, - Some (FSIstrings.SR.fsiLoad())); - ]); - PublicOptions(FSIstrings.SR.fsiCodeGeneration(),[]); - PublicOptions(FSIstrings.SR.fsiErrorsAndWarnings(),[]); - PublicOptions(FSIstrings.SR.fsiLanguage(),[]); - PublicOptions(FSIstrings.SR.fsiMiscellaneous(),[]); - PublicOptions(FSIstrings.SR.fsiAdvanced(),[]); - PrivateOptions( - [// Make internal fsi-server* options. Do not print in the help. They are used by VFSI. - CompilerOption("fsi-server","", OptionString (fun s -> fsiServerName <- s), None, None); // "FSI server mode on given named channel"); - CompilerOption("fsi-server-input-codepage","",OptionInt (fun n -> fsiServerInputCodePage <- Some(n)), None, None); // " Set the input codepage for the console"); - CompilerOption("fsi-server-output-codepage","",OptionInt (fun n -> fsiServerOutputCodePage <- Some(n)), None, None); // " Set the output codepage for the console"); - CompilerOption("fsi-server-no-unicode","", OptionUnit (fun () -> fsiServerOutputCodePage <- None; fsiServerInputCodePage <- None), None, None); // "Do not set the codepages for the console"); - CompilerOption("fsi-server-lcid","", OptionInt (fun n -> fsiLCID <- Some(n)), None, None); // "LCID from Visual Studio" - - // We do not want to print the "script.fsx arg2..." as part of the options - CompilerOption("script.fsx arg1 arg2 ...","", - OptionGeneral((fun args -> args.Length > 0 && IsScript args.[0]), - (fun args -> let scriptFile = args.[0] - let scriptArgs = List.tail args - inputFilesAcc <- inputFilesAcc @ [(scriptFile,true)] (* record script.fsx for evaluation *) - List.iter recordExplicitArg scriptArgs (* record rest of line as explicit arguments *) - tcConfigB.noFeedback <- true (* "quiet", no banners responses etc *) - interact <- false (* --exec, exit after eval *) - [] (* no arguments passed on, all consumed here *) - - )),None,None); // "Run script.fsx with the follow command line arguments: arg1 arg2 ..."); - ]); - PrivateOptions( - [ - // Private options, related to diagnostics around console probing - CompilerOption("probeconsole","", OptionSwitch (fun flag -> probeToSeeIfConsoleWorks <- flag=OptionSwitch.On), None, None); // "Probe to see if Console looks functional"); - - CompilerOption("peekahead","", OptionSwitch (fun flag -> peekAheadOnConsoleToPermitTyping <- flag=OptionSwitch.On), None, None); // "Probe to see if Console looks functional"); - - // Disables interaction (to be used by libraries embedding FSI only!) - CompilerOption("noninteractive","", OptionUnit (fun () -> interact <- false), None, None); // "Deprecated, use --exec instead" - - ]) - ] - - /// These options follow the FsiCoreCompilerOptions in the help blocks - let fsiUsageSuffix tcConfigB = - [PublicOptions(FSComp.SR.optsHelpBannerInputFiles(), - [CompilerOption("--","", OptionRest recordExplicitArg, None, - Some (FSIstrings.SR.fsiRemaining())); - ]); - PublicOptions(FSComp.SR.optsHelpBannerMisc(), - [ CompilerOption("help", tagNone, - OptionHelp (fun blocks -> displayHelpFsi tcConfigB blocks),None, - Some (FSIstrings.SR.fsiHelp())) - ]); - PrivateOptions( - [ CompilerOption("?", tagNone, OptionHelp (fun blocks -> displayHelpFsi tcConfigB blocks), None, None); // "Short form of --help"); - CompilerOption("help", tagNone, OptionHelp (fun blocks -> displayHelpFsi tcConfigB blocks), None, None); // "Short form of --help"); - CompilerOption("full-help", tagNone, OptionHelp (fun blocks -> displayHelpFsi tcConfigB blocks), None, None); // "Short form of --help"); - ]); - PublicOptions(FSComp.SR.optsHelpBannerAdvanced(), - [CompilerOption("exec", "", OptionUnit (fun () -> interact <- false), None, Some (FSIstrings.SR.fsiExec())); - CompilerOption("gui", tagNone, OptionSwitch(fun flag -> gui <- (flag = OptionSwitch.On)),None,Some (FSIstrings.SR.fsiGui())); - CompilerOption("quiet", "", OptionUnit (fun () -> tcConfigB.noFeedback <- true), None,Some (FSIstrings.SR.fsiQuiet())); - (* Renamed --readline and --no-readline to --tabcompletion:+|- *) - CompilerOption("readline", tagNone, OptionSwitch(fun flag -> enableConsoleKeyProcessing <- (flag = OptionSwitch.On)), None, Some(FSIstrings.SR.fsiReadline())); - CompilerOption("quotations-debug", tagNone, OptionSwitch(fun switch -> tcConfigB.emitDebugInfoInQuotations <- switch = OptionSwitch.On),None, Some(FSIstrings.SR.fsiEmitDebugInfoInQuotations())); - CompilerOption("shadowcopyreferences", tagNone, OptionSwitch(fun flag -> tcConfigB.shadowCopyReferences <- flag = OptionSwitch.On), None, Some(FSIstrings.SR.shadowCopyReferences())); - ]); - ] - - - /// Process command line, flags and collect filenames. - /// The ParseCompilerOptions function calls imperative function to process "real" args - /// Rather than start processing, just collect names, then process them. - let sourceFiles = - let collect name = - let fsx = CompileOps.IsScript name - inputFilesAcc <- inputFilesAcc @ [(name,fsx)] // O(n^2), but n small... - try - let fsiCompilerOptions = fsiUsagePrefix tcConfigB @ GetCoreFsiCompilerOptions tcConfigB @ fsiUsageSuffix tcConfigB - let abbrevArgs = GetAbbrevFlagSet tcConfigB false - ParseCompilerOptions (collect, fsiCompilerOptions, List.tail (PostProcessCompilerArgs abbrevArgs argv)) - with e -> - stopProcessingRecovery e range0; failwithf "Error creating evaluation session: %A" e - inputFilesAcc - - do - if tcConfigB.utf8output then - let prev = Console.OutputEncoding - Console.OutputEncoding <- System.Text.Encoding.UTF8 -#if FX_NO_APP_DOMAINS - ignore prev -#else - System.AppDomain.CurrentDomain.ProcessExit.Add(fun _ -> Console.OutputEncoding <- prev) -#endif - do - let firstArg = - match sourceFiles with - | [] -> argv.[0] - | _ -> fst (List.head (List.rev sourceFiles) ) - let args = Array.ofList (firstArg :: explicitArgs) - fsi.ReportUserCommandLineArgs args - - - //---------------------------------------------------------------------------- - // Banner - //---------------------------------------------------------------------------- - - member __.ShowBanner() = - fsiConsoleOutput.uprintnfn "%s" (tcConfigB.productNameForBannerText) - fsiConsoleOutput.uprintfnn "%s" (FSComp.SR.optsCopyright()) - fsiConsoleOutput.uprintfn "%s" (FSIstrings.SR.fsiBanner3()) - - member __.ShowHelp() = - let helpLine = sprintf "%s --help" (Path.GetFileNameWithoutExtension executableFileName.Value) - - fsiConsoleOutput.uprintfn "" - fsiConsoleOutput.uprintfnn "%s" (FSIstrings.SR.fsiIntroTextHeader1directives()); - fsiConsoleOutput.uprintfn " #r \"file.dll\";; %s" (FSIstrings.SR.fsiIntroTextHashrInfo()); - fsiConsoleOutput.uprintfn " #I \"path\";; %s" (FSIstrings.SR.fsiIntroTextHashIInfo()); - fsiConsoleOutput.uprintfn " #load \"file.fs\" ...;; %s" (FSIstrings.SR.fsiIntroTextHashloadInfo()); - fsiConsoleOutput.uprintfn " #time [\"on\"|\"off\"];; %s" (FSIstrings.SR.fsiIntroTextHashtimeInfo()); - fsiConsoleOutput.uprintfn " #help;; %s" (FSIstrings.SR.fsiIntroTextHashhelpInfo()); - fsiConsoleOutput.uprintfn " #quit;; %s" (FSIstrings.SR.fsiIntroTextHashquitInfo()); (* last thing you want to do, last thing in the list - stands out more *) - fsiConsoleOutput.uprintfn ""; - fsiConsoleOutput.uprintfnn "%s" (FSIstrings.SR.fsiIntroTextHeader2commandLine()); - fsiConsoleOutput.uprintfn "%s" (FSIstrings.SR.fsiIntroTextHeader3(helpLine)); - fsiConsoleOutput.uprintfn ""; - fsiConsoleOutput.uprintfn ""; - -#if DEBUG - member __.ShowILCode with get() = showILCode and set v = showILCode <- v -#endif - member __.ShowTypes with get() = showTypes and set v = showTypes <- v - member __.FsiServerName = fsiServerName - member __.FsiServerInputCodePage = fsiServerInputCodePage - member __.FsiServerOutputCodePage = fsiServerOutputCodePage - member __.FsiLCID with get() = fsiLCID and set v = fsiLCID <- v - member __.IsInteractiveServer = isInteractiveServer() - member __.ProbeToSeeIfConsoleWorks = probeToSeeIfConsoleWorks - member __.EnableConsoleKeyProcessing = enableConsoleKeyProcessing - - member __.Interact = interact - member __.PeekAheadOnConsoleToPermitTyping = peekAheadOnConsoleToPermitTyping - member __.SourceFiles = sourceFiles - member __.Gui = gui - -/// Set the current ui culture for the current thread. -#if FX_LCIDFROMCODEPAGE -let internal SetCurrentUICultureForThread (lcid : int option) = - let culture = Thread.CurrentThread.CurrentUICulture - match lcid with - | Some n -> Thread.CurrentThread.CurrentUICulture <- new CultureInfo(n) - | None -> () - { new IDisposable with member x.Dispose() = Thread.CurrentThread.CurrentUICulture <- culture } -#endif - -//---------------------------------------------------------------------------- -// Reporting - warnings, errors -//---------------------------------------------------------------------------- - -let internal InstallErrorLoggingOnThisThread errorLogger = - if !progress then dprintfn "Installing logger on id=%d name=%s" Thread.CurrentThread.ManagedThreadId Thread.CurrentThread.Name - SetThreadErrorLoggerNoUnwind(errorLogger) - SetThreadBuildPhaseNoUnwind(BuildPhase.Interactive) - -#if !FX_NO_SERVERCODEPAGES -/// Set the input/output encoding. The use of a thread is due to a known bug on -/// on Vista where calls to Console.InputEncoding can block the process. -let internal SetServerCodePages(fsiOptions: FsiCommandLineOptions) = - match fsiOptions.FsiServerInputCodePage, fsiOptions.FsiServerOutputCodePage with - | None,None -> () - | inputCodePageOpt,outputCodePageOpt -> - let successful = ref false - Async.Start (async { do match inputCodePageOpt with - | None -> () - | Some(n:int) -> - let encoding = System.Text.Encoding.GetEncoding(n) - // Note this modifies the real honest-to-goodness settings for the current shell. - // and the modifications hang around even after the process has exited. - Console.InputEncoding <- encoding - do match outputCodePageOpt with - | None -> () - | Some(n:int) -> - let encoding = System.Text.Encoding.GetEncoding n - // Note this modifies the real honest-to-goodness settings for the current shell. - // and the modifications hang around even after the process has exited. - Console.OutputEncoding <- encoding - do successful := true }); - for pause in [10;50;100;1000;2000;10000] do - if not !successful then - Thread.Sleep(pause); -#if LOGGING_GUI - if not !successful then - System.Windows.Forms.MessageBox.Show(FSIstrings.SR.fsiConsoleProblem()) |> ignore -#endif -#endif - -//---------------------------------------------------------------------------- -// Prompt printing -//---------------------------------------------------------------------------- - -type internal FsiConsolePrompt(fsiOptions: FsiCommandLineOptions, fsiConsoleOutput: FsiConsoleOutput) = - - // A prompt gets "printed ahead" at start up. Tells users to start type while initialisation completes. - // A prompt can be skipped by "silent directives", e.g. ones sent to FSI by VS. - let mutable dropPrompt = 0 - // NOTE: SERVER-PROMPT is not user displayed, rather it's a prefix that code elsewhere - // uses to identify the prompt, see service\FsPkgs\FSharp.VS.FSI\fsiSessionToolWindow.fs - let prompt = if fsiOptions.IsInteractiveServer then "SERVER-PROMPT>\n" else "> " - - member __.Print() = if dropPrompt = 0 then fsiConsoleOutput.uprintf "%s" prompt else dropPrompt <- dropPrompt - 1 - member __.PrintAhead() = dropPrompt <- dropPrompt + 1; fsiConsoleOutput.uprintf "%s" prompt - member __.SkipNext() = dropPrompt <- dropPrompt + 1 - member __.FsiOptions = fsiOptions - - - -//---------------------------------------------------------------------------- -// Startup processing -//---------------------------------------------------------------------------- -type internal FsiConsoleInput(fsi: FsiEvaluationSessionHostConfig, fsiOptions: FsiCommandLineOptions, inReader: TextReader, outWriter: TextWriter) = - - let consoleOpt = - // The "console.fs" code does a limited form of "TAB-completion". - // Currently, it turns on if it looks like we have a console. - if fsiOptions.EnableConsoleKeyProcessing then - fsi.GetOptionalConsoleReadLine(fsiOptions.ProbeToSeeIfConsoleWorks) - else - None - - // When VFSI is running, there should be no "console", and in particular the console.fs readline code should not to run. - do if fsiOptions.IsInteractiveServer then assert(consoleOpt.IsNone) - - /// This threading event gets set after the first-line-reader has finished its work - let consoleReaderStartupDone = new ManualResetEvent(false) - - /// When using a key-reading console this holds the first line after it is read - let mutable firstLine = None - - /// Peek on the standard input so that the user can type into it from a console window. - do if fsiOptions.Interact then - if fsiOptions.PeekAheadOnConsoleToPermitTyping then - (new Thread(fun () -> - match consoleOpt with - | Some console when fsiOptions.EnableConsoleKeyProcessing && not fsiOptions.IsInteractiveServer -> - if List.isEmpty fsiOptions.SourceFiles then - if !progress then fprintfn outWriter "first-line-reader-thread reading first line..."; - firstLine <- Some(console()); - if !progress then fprintfn outWriter "first-line-reader-thread got first line = %A..." firstLine; - consoleReaderStartupDone.Set() |> ignore - if !progress then fprintfn outWriter "first-line-reader-thread has set signal and exited." ; - | _ -> - ignore(inReader.Peek()); - consoleReaderStartupDone.Set() |> ignore - )).Start() - else - if !progress then fprintfn outWriter "first-line-reader-thread not in use." - consoleReaderStartupDone.Set() |> ignore - - /// Try to get the first line, if we snarfed it while probing. - member __.TryGetFirstLine() = let r = firstLine in firstLine <- None; r - - /// Try to get the console, if it appears operational. - member __.TryGetConsole() = consoleOpt - - member __.In = inReader - - member __.WaitForInitialConsoleInput() = WaitHandle.WaitAll [| consoleReaderStartupDone |] |> ignore; - - -//---------------------------------------------------------------------------- -// FsiDynamicCompilerState -//---------------------------------------------------------------------------- - -type internal FsiInteractionStepStatus = - | CtrlC - | EndOfFile - | Completed of option - | CompletedWithReportedError of exn - -[] -[] -type internal FsiDynamicCompilerState = - { optEnv : Optimizer.IncrementalOptimizationEnv - emEnv : ILRuntimeWriter.emEnv - tcGlobals : TcGlobals - tcState : TcState - tcImports : TcImports - ilxGenerator : IlxGen.IlxAssemblyGenerator - // Why is this not in FsiOptions? - timing : bool - debugBreak : bool } - -let internal WithImplicitHome (tcConfigB, dir) f = - let old = tcConfigB.implicitIncludeDir - tcConfigB.implicitIncludeDir <- dir; - try f() - finally tcConfigB.implicitIncludeDir <- old - - - -/// Encapsulates the coordination of the typechecking, optimization and code generation -/// components of the F# compiler for interactively executed fragments of code. -/// -/// A single instance of this object is created per interactive session. -type internal FsiDynamicCompiler - (fsi: FsiEvaluationSessionHostConfig, - timeReporter : FsiTimeReporter, - tcConfigB: TcConfigBuilder, - tcLockObject : obj, - outWriter: TextWriter, - tcImports: TcImports, - tcGlobals: TcGlobals, - ilGlobals: ILGlobals, - fsiOptions : FsiCommandLineOptions, - fsiConsoleOutput : FsiConsoleOutput, - fsiCollectible: bool, - niceNameGen, - resolveAssemblyRef) = - - let outfile = "TMPFSCI.exe" - let assemblyName = "FSI-ASSEMBLY" - - let mutable fragmentId = 0 - let mutable prevIt : ValRef option = None - - let generateDebugInfo = tcConfigB.debuginfo - - let valuePrinter = FsiValuePrinter(fsi, tcGlobals, generateDebugInfo, resolveAssemblyRef, outWriter) - - let assemblyBuilder,moduleBuilder = ILRuntimeWriter.mkDynamicAssemblyAndModule (assemblyName, tcConfigB.optSettings.localOpt(), generateDebugInfo, fsiCollectible) - - let rangeStdin = rangeN Lexhelp.stdinMockFilename 0 - - //let _writer = moduleBuilder.GetSymWriter() - - let infoReader = InfoReader(tcGlobals,tcImports.GetImportMap()) - - /// Add attributes - let CreateModuleFragment (tcConfigB: TcConfigBuilder, assemblyName, codegenResults) = - if !progress then fprintfn fsiConsoleOutput.Out "Creating main module..."; - let mainModule = mkILSimpleModule assemblyName (GetGeneratedILModuleName tcConfigB.target assemblyName) (tcConfigB.target = CompilerTarget.Dll) tcConfigB.subsystemVersion tcConfigB.useHighEntropyVA (mkILTypeDefs codegenResults.ilTypeDefs) None None 0x0 (mkILExportedTypes []) "" - { mainModule - with Manifest = - (let man = mainModule.ManifestOfAssembly - Some { man with CustomAttrsStored = storeILCustomAttrs (mkILCustomAttrs codegenResults.ilAssemAttrs) }) } - - let ProcessInputs (ctok, errorLogger: ErrorLogger, istate: FsiDynamicCompilerState, inputs: ParsedInput list, showTypes: bool, isIncrementalFragment: bool, isInteractiveItExpr: bool, prefixPath: LongIdent) = - let optEnv = istate.optEnv - let emEnv = istate.emEnv - let tcState = istate.tcState - let ilxGenerator = istate.ilxGenerator - let tcConfig = TcConfig.Create(tcConfigB,validate=false) - - // Typecheck. The lock stops the type checker running at the same time as the - // server intellisense implementation (which is currently incomplete and #if disabled) - let (tcState:TcState),topCustomAttrs,declaredImpls,tcEnvAtEndOfLastInput = - lock tcLockObject (fun _ -> TypeCheckClosedInputSet(ctok, errorLogger.CheckForErrors, tcConfig, tcImports, tcGlobals, Some prefixPath, tcState, inputs)) - -#if DEBUG - // Logging/debugging - if tcConfig.printAst then - for input in declaredImpls do - fprintfn fsiConsoleOutput.Out "AST:" - fprintfn fsiConsoleOutput.Out "%+A" input -#endif - - errorLogger.AbortOnError(fsiConsoleOutput); - - let importMap = tcImports.GetImportMap() - - // optimize: note we collect the incremental optimization environment - let optimizedImpls, _optData, optEnv = ApplyAllOptimizations (tcConfig, tcGlobals, (LightweightTcValForUsingInBuildMethodCall tcGlobals), outfile, importMap, isIncrementalFragment, optEnv, tcState.Ccu, declaredImpls) - errorLogger.AbortOnError(fsiConsoleOutput); - - let fragName = textOfLid prefixPath - let codegenResults = GenerateIlxCode (IlReflectBackend, isInteractiveItExpr, runningOnMono, tcConfig, topCustomAttrs, optimizedImpls, fragName, ilxGenerator) - errorLogger.AbortOnError(fsiConsoleOutput); - - // Each input is like a small separately compiled extension to a single source file. - // The incremental extension to the environment is dictated by the "signature" of the values as they come out - // of the type checker. Hence we add the declaredImpls (unoptimized) to the environment, rather than the - // optimizedImpls. - ilxGenerator.AddIncrementalLocalAssemblyFragment (isIncrementalFragment, fragName, declaredImpls) - - ReportTime tcConfig "TAST -> ILX"; - errorLogger.AbortOnError(fsiConsoleOutput); - - ReportTime tcConfig "Linking"; - let ilxMainModule = CreateModuleFragment (tcConfigB, assemblyName, codegenResults) - - errorLogger.AbortOnError(fsiConsoleOutput); - - ReportTime tcConfig "Assembly refs Normalised"; - let mainmod3 = Morphs.morphILScopeRefsInILModuleMemoized ilGlobals (NormalizeAssemblyRefs (ctok, tcImports)) ilxMainModule - errorLogger.AbortOnError(fsiConsoleOutput); - -#if DEBUG - if fsiOptions.ShowILCode then - fsiConsoleOutput.uprintnfn "--------------------"; - ILAsciiWriter.output_module outWriter ilGlobals mainmod3; - fsiConsoleOutput.uprintnfn "--------------------" -#else - ignore(fsiOptions) -#endif - - ReportTime tcConfig "Reflection.Emit"; - - let emEnv,execs = ILRuntimeWriter.emitModuleFragment(ilGlobals, emEnv, assemblyBuilder, moduleBuilder, mainmod3, generateDebugInfo, resolveAssemblyRef, tcGlobals.TryFindSysILTypeRef) - - errorLogger.AbortOnError(fsiConsoleOutput); - - // Explicitly register the resources with the QuotationPickler module - // We would save them as resources into the dynamic assembly but there is missing - // functionality System.Reflection for dynamic modules that means they can't be read back out - let cenv = { ilg = ilGlobals ; generatePdb = generateDebugInfo; resolveAssemblyRef=resolveAssemblyRef; tryFindSysILTypeRef=tcGlobals.TryFindSysILTypeRef } - for (referencedTypeDefs, bytes) in codegenResults.quotationResourceInfo do - let referencedTypes = - [| for tref in referencedTypeDefs do - yield ILRuntimeWriter.LookupTypeRef cenv emEnv tref |] - Microsoft.FSharp.Quotations.Expr.RegisterReflectedDefinitions (assemblyBuilder, fragName, bytes, referencedTypes); - - - ReportTime tcConfig "Run Bindings"; - timeReporter.TimeOpIf istate.timing (fun () -> - execs |> List.iter (fun exec -> - match exec() with - | Some err -> - match errorLogger with - | :? ErrorLoggerThatStopsOnFirstError as errorLogger -> - fprintfn fsiConsoleOutput.Error "%s" (err.ToString()) - errorLogger.SetError() - errorLogger.AbortOnError(fsiConsoleOutput) - | _ -> - raise (StopProcessingExn (Some err)) - - | None -> ())) ; - - errorLogger.AbortOnError(fsiConsoleOutput); - - // Echo the decls (reach inside wrapping) - // This code occurs AFTER the execution of the declarations. - // So stored values will have been initialised, modified etc. - if showTypes && not tcConfig.noFeedback then - let denv = tcState.TcEnvFromImpls.DisplayEnv - let denv = - if isIncrementalFragment then - // Extend denv with a (Val -> layout option) function for printing of val bindings. - {denv with generatedValueLayout = (fun v -> valuePrinter.InvokeDeclLayout (emEnv, ilxGenerator, v)) } - else - // With #load items, the vals in the inferred signature do not tie up with those generated. Disable printing. - denv - - // 'Open' the path for the fragment we just compiled for any future printing. - let denv = denv.AddOpenPath (pathOfLid prefixPath) - - for (TImplFile(_qname,_,mexpr,_,_,_)) in declaredImpls do - let responseL = NicePrint.layoutInferredSigOfModuleExpr false denv infoReader AccessibleFromSomewhere rangeStdin mexpr - if not (Layout.isEmptyL responseL) then - let opts = valuePrinter.GetFsiPrintOptions() - Utilities.colorPrintL outWriter opts responseL |> ignore - - // Build the new incremental state. - let istate = {istate with optEnv = optEnv; - emEnv = emEnv; - ilxGenerator = ilxGenerator; - tcState = tcState } - - // Return the new state and the environment at the end of the last input, ready for further inputs. - (istate,tcEnvAtEndOfLastInput,declaredImpls) - - let nextFragmentId() = fragmentId <- fragmentId + 1; fragmentId - - let mkFragmentPath i = - // NOTE: this text shows in exn traces and type names. Make it clear and fixed width - [mkSynId rangeStdin (FsiDynamicModulePrefix + sprintf "%04d" i)] - - member __.DynamicAssemblyName = assemblyName - member __.DynamicAssembly = (assemblyBuilder :> Assembly) - - member __.EvalParsedSourceFiles (ctok, errorLogger, istate, inputs) = - let i = nextFragmentId() - let prefix = mkFragmentPath i - // Ensure the path includes the qualifying name - let inputs = inputs |> List.map (PrependPathToInput prefix) - let istate,_,_ = ProcessInputs (ctok, errorLogger, istate, inputs, true, false, false, prefix) - istate - - /// Evaluate the given definitions and produce a new interactive state. - member __.EvalParsedDefinitions (ctok, errorLogger: ErrorLogger, istate, showTypes, isInteractiveItExpr, defs: SynModuleDecls) = - let filename = Lexhelp.stdinMockFilename - let i = nextFragmentId() - let prefix = mkFragmentPath i - let prefixPath = pathOfLid prefix - let impl = SynModuleOrNamespace(prefix,(*isRec*)false, NamedModule,defs,PreXmlDoc.Empty,[],None,rangeStdin) - let input = ParsedInput.ImplFile(ParsedImplFileInput(filename,true, ComputeQualifiedNameOfFileFromUniquePath (rangeStdin,prefixPath),[],[],[impl],(true (* isLastCompiland *), false (* isExe *)) )) - let istate,tcEnvAtEndOfLastInput,declaredImpls = ProcessInputs (ctok, errorLogger, istate, [input], showTypes, true, isInteractiveItExpr, prefix) - let tcState = istate.tcState - let newState = { istate with tcState = tcState.NextStateAfterIncrementalFragment(tcEnvAtEndOfLastInput) } - - // Find all new declarations the EvaluationListener - try - let contents = FSharpAssemblyContents(tcGlobals, tcState.Ccu, Some tcState.CcuSig, tcImports, declaredImpls) - let contentFile = contents.ImplementationFiles.[0] - // Skip the "FSI_NNNN" - match contentFile.Declarations with - | [FSharpImplementationFileDeclaration.Entity (_eFakeModule,modDecls) ] -> - let cenv = SymbolEnv(newState.tcGlobals, newState.tcState.Ccu, Some newState.tcState.CcuSig, newState.tcImports) - for decl in modDecls do - match decl with - | FSharpImplementationFileDeclaration.MemberOrFunctionOrValue (v,_,_) -> - // Report a top-level function or value definition - if v.IsModuleValueOrMember && not v.IsMember then - let fsiValueOpt = - match v.Item with - | Item.Value vref -> - let optValue = newState.ilxGenerator.LookupGeneratedValue(valuePrinter.GetEvaluationContext(newState.emEnv), vref.Deref) - match optValue with - | Some (res, ty) -> Some(FsiValue(res, ty, FSharpType(cenv, vref.Type))) - | None -> None - | _ -> None - - let symbol = FSharpSymbol.Create(cenv, v.Item) - let symbolUse = FSharpSymbolUse(tcGlobals, newState.tcState.TcEnvFromImpls.DisplayEnv, symbol, ItemOccurence.Binding, v.DeclarationLocation) - fsi.TriggerEvaluation (fsiValueOpt, symbolUse, decl) - | FSharpImplementationFileDeclaration.Entity (e,_) -> - // Report a top-level module or namespace definition - let symbol = FSharpSymbol.Create(cenv, e.Item) - let symbolUse = FSharpSymbolUse(tcGlobals, newState.tcState.TcEnvFromImpls.DisplayEnv, symbol, ItemOccurence.Binding, e.DeclarationLocation) - fsi.TriggerEvaluation (None, symbolUse, decl) - | FSharpImplementationFileDeclaration.InitAction _ -> - // Top level 'do' bindings are not reported as incremental declarations - () - | _ -> () - with _ -> () - - newState - - - /// Evaluate the given expression and produce a new interactive state. - member fsiDynamicCompiler.EvalParsedExpression (ctok, errorLogger: ErrorLogger, istate, expr: SynExpr) = - let tcConfig = TcConfig.Create (tcConfigB, validate=false) - let itName = "it" - - // Construct the code that saves the 'it' value into the 'SaveIt' register. - let defs = fsiDynamicCompiler.BuildItBinding expr - - // Evaluate the overall definitions. - let istate = fsiDynamicCompiler.EvalParsedDefinitions (ctok, errorLogger, istate, false, true, defs) - // Snarf the type for 'it' via the binding - match istate.tcState.TcEnvFromImpls.NameEnv.FindUnqualifiedItem itName with - | NameResolution.Item.Value vref -> - if not tcConfig.noFeedback then - valuePrinter.InvokeExprPrinter (istate.tcState.TcEnvFromImpls.DisplayEnv, istate.emEnv, istate.ilxGenerator, vref.Deref) - - /// Clear the value held in the previous "it" binding, if any, as long as it has never been referenced. - match prevIt with - | Some prevVal when not prevVal.Deref.HasBeenReferenced -> - istate.ilxGenerator.ClearGeneratedValue (valuePrinter.GetEvaluationContext istate.emEnv, prevVal.Deref) - | _ -> () - prevIt <- Some vref - - // - let optValue = istate.ilxGenerator.LookupGeneratedValue(valuePrinter.GetEvaluationContext(istate.emEnv), vref.Deref); - match optValue with - | Some (res, ty) -> istate, Completed(Some(FsiValue(res, ty, FSharpType(tcGlobals, istate.tcState.Ccu, istate.tcState.CcuSig, istate.tcImports, vref.Type)))) - | _ -> istate, Completed None - - // Return the interactive state. - | _ -> istate, Completed None - - // Construct the code that saves the 'it' value into the 'SaveIt' register. - member __.BuildItBinding (expr: SynExpr) = - let m = expr.Range - let itName = "it" - - let itID = mkSynId m itName - //let itExp = SynExpr.Ident itID - let mkBind pat expr = Binding (None, DoBinding, false, (*mutable*)false, [], PreXmlDoc.Empty, SynInfo.emptySynValData, pat, None, expr, m, NoSequencePointAtInvisibleBinding) - let bindingA = mkBind (mkSynPatVar None itID) expr (* let it = *) // NOTE: the generalizability of 'expr' must not be damaged, e.g. this can't be an application - //let saverPath = ["Microsoft";"FSharp";"Compiler";"Interactive";"RuntimeHelpers";"SaveIt"] - //let dots = List.replicate (saverPath.Length - 1) m - //let bindingB = mkBind (SynPat.Wild m) (SynExpr.App(ExprAtomicFlag.NonAtomic, false, SynExpr.LongIdent(false, LongIdentWithDots(List.map (mkSynId m) saverPath,dots),None,m), itExp,m)) (* let _ = saverPath it *) - let defA = SynModuleDecl.Let (false, [bindingA], m) - //let defB = SynModuleDecl.Let (false, [bindingB], m) - - [defA (* ; defB *) ] - - // construct an invisible call to Debugger.Break(), in the specified range - member __.CreateDebuggerBreak (m : range) = - let breakPath = ["System";"Diagnostics";"Debugger";"Break"] - let dots = List.replicate (breakPath.Length - 1) m - let methCall = SynExpr.LongIdent(false, LongIdentWithDots(List.map (mkSynId m) breakPath, dots), None, m) - let args = SynExpr.Const(SynConst.Unit, m) - let breakStatement = SynExpr.App(ExprAtomicFlag.Atomic, false, methCall, args, m) - SynModuleDecl.DoExpr(SequencePointInfoForBinding.NoSequencePointAtDoBinding, breakStatement, m) - - member __.EvalRequireReference (ctok, istate, m, path) = - if FileSystem.IsInvalidPathShim(path) then - error(Error(FSIstrings.SR.fsiInvalidAssembly(path),m)) - // Check the file can be resolved before calling requireDLLReference - let resolutions = tcImports.ResolveAssemblyReference(ctok, AssemblyReference(m,path,None), ResolveAssemblyReferenceMode.ReportErrors) - tcConfigB.AddReferencedAssemblyByPath(m,path) - let tcState = istate.tcState - let tcEnv,(_dllinfos,ccuinfos) = - try - RequireDLL (ctok, tcImports, tcState.TcEnvFromImpls, assemblyName, m, path) - with e -> - tcConfigB.RemoveReferencedAssemblyByPath(m,path) - reraise() - let optEnv = List.fold (AddExternalCcuToOpimizationEnv tcGlobals) istate.optEnv ccuinfos - istate.ilxGenerator.AddExternalCcus (ccuinfos |> List.map (fun ccuinfo -> ccuinfo.FSharpViewOfMetadata)) - resolutions, - { istate with tcState = tcState.NextStateAfterIncrementalFragment(tcEnv); optEnv = optEnv } - - member fsiDynamicCompiler.ProcessMetaCommandsFromInputAsInteractiveCommands(ctok, istate, sourceFile, inp) = - WithImplicitHome - (tcConfigB, directoryName sourceFile) - (fun () -> - ProcessMetaCommandsFromInput - ((fun st (m,nm) -> tcConfigB.TurnWarningOff(m,nm); st), - (fun st (m,nm) -> snd (fsiDynamicCompiler.EvalRequireReference (ctok, st, m, nm))), - (fun _ _ -> ())) - (tcConfigB, inp, Path.GetDirectoryName sourceFile, istate)) - - member fsiDynamicCompiler.EvalSourceFiles(ctok, istate, m, sourceFiles, lexResourceManager, errorLogger: ErrorLogger) = - let tcConfig = TcConfig.Create(tcConfigB,validate=false) - match sourceFiles with - | [] -> istate - | _ -> - // use a set of source files as though they were command line inputs - let sourceFiles = sourceFiles |> List.map (fun nm -> tcConfig.ResolveSourceFile(m, nm, tcConfig.implicitIncludeDir),m) - - // Close the #load graph on each file and gather the inputs from the scripts. - let tcConfig = TcConfig.Create(tcConfigB,validate=false) - let closure = LoadClosure.ComputeClosureOfScriptFiles(ctok, tcConfig, sourceFiles, CodeContext.CompilationAndEvaluation, lexResourceManager=lexResourceManager) - - // Intent "[Loading %s]\n" (String.concat "\n and " sourceFiles) - fsiConsoleOutput.uprintf "[%s " (FSIstrings.SR.fsiLoadingFilesPrefixText()) - closure.Inputs |> List.iteri (fun i input -> - if i=0 then fsiConsoleOutput.uprintf "%s" input.FileName - else fsiConsoleOutput.uprintnf " %s %s" (FSIstrings.SR.fsiLoadingFilesPrefixText()) input.FileName) - fsiConsoleOutput.uprintfn "]" - - closure.NoWarns |> Seq.map (fun (n,ms) -> ms |> Seq.map (fun m -> m,n)) |> Seq.concat |> Seq.iter tcConfigB.TurnWarningOff - - // Play errors and warnings from resolution - closure.ResolutionDiagnostics |> List.iter diagnosticSink - - // Non-scripts will not have been parsed during #load closure so parse them now - let sourceFiles,inputs = - closure.Inputs - |> List.map (fun input-> - input.ParseDiagnostics |> List.iter diagnosticSink - input.MetaCommandDiagnostics |> List.iter diagnosticSink - let parsedInput = - match input.SyntaxTree with - | None -> ParseOneInputFile(tcConfig,lexResourceManager,["INTERACTIVE"],input.FileName,(true,false),errorLogger,(*retryLocked*)false) - | _-> input.SyntaxTree - input.FileName, parsedInput) - |> List.unzip - - errorLogger.AbortOnError(fsiConsoleOutput); - if inputs |> List.exists Option.isNone then failwith "parse error" - let inputs = List.map Option.get inputs - let istate = (istate, sourceFiles, inputs) |||> List.fold2 (fun istate sourceFile input -> fsiDynamicCompiler.ProcessMetaCommandsFromInputAsInteractiveCommands(ctok, istate, sourceFile, input)) - fsiDynamicCompiler.EvalParsedSourceFiles (ctok, errorLogger, istate, inputs) - - - member __.GetInitialInteractiveState () = - let tcConfig = TcConfig.Create(tcConfigB,validate=false) - let optEnv0 = GetInitialOptimizationEnv (tcImports, tcGlobals) - let emEnv = ILRuntimeWriter.emEnv0 - let tcEnv = GetInitialTcEnv (assemblyName, rangeStdin, tcConfig, tcImports, tcGlobals) - let ccuName = assemblyName - - let tcState = GetInitialTcState (rangeStdin, ccuName, tcConfig, tcGlobals, tcImports, niceNameGen, tcEnv) - - let ilxGenerator = CreateIlxAssemblyGenerator (tcConfig, tcImports, tcGlobals, (LightweightTcValForUsingInBuildMethodCall tcGlobals), tcState.Ccu) - {optEnv = optEnv0 - emEnv = emEnv - tcGlobals = tcGlobals - tcState = tcState - tcImports = tcImports - ilxGenerator = ilxGenerator - timing = false - debugBreak = false - } - - member __.CurrentPartialAssemblySignature(istate) = - FSharpAssemblySignature(istate.tcGlobals, istate.tcState.Ccu, istate.tcState.CcuSig, istate.tcImports, None, istate.tcState.CcuSig) - - member __.FormatValue(obj:obj, objTy) = - valuePrinter.FormatValue(obj, objTy) - - -//---------------------------------------------------------------------------- -// ctrl-c handling -//---------------------------------------------------------------------------- - -module internal NativeMethods = - - type ControlEventHandler = delegate of int -> bool - -#if !FX_REDUCED_CONSOLE - [] - extern bool SetConsoleCtrlHandler(ControlEventHandler _callback,bool _add) -#endif - -// One strange case: when a TAE happens a strange thing -// occurs the next read from stdin always returns -// 0 bytes, i.e. the channel will look as if it has been closed. So we check -// for this condition explicitly. We also recreate the lexbuf whenever CtrlC kicks. -type internal FsiInterruptStdinState = - | StdinEOFPermittedBecauseCtrlCRecentlyPressed - | StdinNormal - -type internal FsiInterruptControllerState = - | InterruptCanRaiseException - | InterruptIgnored - -type internal FsiInterruptControllerKillerThreadRequest = - | ThreadAbortRequest - | NoRequest - | ExitRequest - | PrintInterruptRequest - -type internal FsiInterruptController(fsiOptions : FsiCommandLineOptions, - fsiConsoleOutput: FsiConsoleOutput) = - - let mutable stdinInterruptState = StdinNormal - let CTRL_C = 0 - let mutable interruptAllowed = InterruptIgnored - let mutable killThreadRequest = NoRequest - let mutable ctrlEventHandlers = [] : NativeMethods.ControlEventHandler list - let mutable ctrlEventActions = [] : (unit -> unit) list - let mutable exitViaKillThread = false - - let mutable posixReinstate = (fun () -> ()) - - member __.Exit() = - if exitViaKillThread then - killThreadRequest <- ExitRequest - Thread.Sleep(1000) - exit 0 - - member __.FsiInterruptStdinState with get () = stdinInterruptState and set v = stdinInterruptState <- v - - member __.ClearInterruptRequest() = killThreadRequest <- NoRequest - - member __.InterruptAllowed with set v = interruptAllowed <- v - - member __.Interrupt() = ctrlEventActions |> List.iter (fun act -> act()) - - member __.EventHandlers = ctrlEventHandlers - - // REVIEW: streamline all this code to use the same code on Windows and Posix. - member controller.InstallKillThread(threadToKill:Thread, pauseMilliseconds:int) = -#if DYNAMIC_CODE_EMITS_INTERRUPT_CHECKS - let action() = - Microsoft.FSharp.Silverlight.InterruptThread(threadToKill.ManagedThreadId) - - ctrlEventActions <- action :: ctrlEventActions; -#else -#if FX_NO_THREADABORT - ignore threadToKill - ignore pauseMilliseconds - ignore fsiConsoleOutput - ignore CTRL_C - ignore fsiOptions - exitViaKillThread <- false -#else - if !progress then fprintfn fsiConsoleOutput.Out "installing CtrlC handler" - // WINDOWS TECHNIQUE: .NET has more safe points, and you can do more when a safe point. - // Hence we actually start up the killer thread within the handler. - try - let raiseCtrlC() = -#if FX_LCIDFROMCODEPAGE - use _scope = SetCurrentUICultureForThread fsiOptions.FsiLCID -#else - ignore fsiOptions -#endif - fprintf fsiConsoleOutput.Error "%s" (FSIstrings.SR.fsiInterrupt()) - stdinInterruptState <- StdinEOFPermittedBecauseCtrlCRecentlyPressed - if (interruptAllowed = InterruptCanRaiseException) then - killThreadRequest <- ThreadAbortRequest - let killerThread = - new Thread(new ThreadStart(fun () -> -#if FX_LCIDFROMCODEPAGE - use _scope = SetCurrentUICultureForThread fsiOptions.FsiLCID -#endif - // sleep long enough to allow ControlEventHandler handler on main thread to return - // Also sleep to give computations a bit of time to terminate - Thread.Sleep(pauseMilliseconds) - if (killThreadRequest = ThreadAbortRequest) then - if !progress then fsiConsoleOutput.uprintnfn "%s" (FSIstrings.SR.fsiAbortingMainThread()) - killThreadRequest <- NoRequest - threadToKill.Abort() - ()),Name="ControlCAbortThread") - killerThread.IsBackground <- true - killerThread.Start() - - let ctrlEventHandler = new NativeMethods.ControlEventHandler(fun i -> if i = CTRL_C then (raiseCtrlC(); true) else false ) - ctrlEventHandlers <- ctrlEventHandler :: ctrlEventHandlers - ctrlEventActions <- raiseCtrlC :: ctrlEventActions - let _resultOK = NativeMethods.SetConsoleCtrlHandler(ctrlEventHandler,true) - exitViaKillThread <- false // don't exit via kill thread - with e -> - if !progress then fprintfn fsiConsoleOutput.Error "Failed to install ctrl-c handler using Windows technique - trying to install one using Unix signal handling..."; - // UNIX TECHNIQUE: We start up a killer thread, and it watches the mutable reference location. - // We can't have a dependency on Mono DLLs (indeed we don't even have them!) - // So SOFT BIND the following code: - // Mono.Unix.Native.Stdlib.signal(Mono.Unix.Native.Signum.SIGINT,new Mono.Unix.Native.SignalHandler(fun n -> PosixSignalProcessor.PosixInvoke(n))) |> ignore; - match (try Choice1Of2(Assembly.Load(new System.Reflection.AssemblyName("Mono.Posix, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"))) with e -> Choice2Of2 e) with - | Choice1Of2(monoPosix) -> - try - if !progress then fprintfn fsiConsoleOutput.Error "loading type Mono.Unix.Native.Stdlib..." - let monoUnixStdlib = monoPosix.GetType("Mono.Unix.Native.Stdlib") - if !progress then fprintfn fsiConsoleOutput.Error "loading type Mono.Unix.Native.SignalHandler..." - let monoUnixSignalHandler = monoPosix.GetType("Mono.Unix.Native.SignalHandler") - if !progress then fprintfn fsiConsoleOutput.Error "creating delegate..." - controller.PosixInvoke(-1) - let monoHandler = System.Delegate.CreateDelegate(monoUnixSignalHandler,controller,"PosixInvoke") - if !progress then fprintfn fsiConsoleOutput.Error "registering signal handler..." - let monoSignalNumber = System.Enum.Parse(monoPosix.GetType("Mono.Unix.Native.Signum"),"SIGINT") - let register () = Utilities.callStaticMethod monoUnixStdlib "signal" [ monoSignalNumber; box monoHandler ] |> ignore - posixReinstate <- register - register() - let killerThread = - new Thread(new ThreadStart(fun () -> -#if FX_LCIDFROMCODEPAGE - use _scope = SetCurrentUICultureForThread fsiOptions.FsiLCID -#endif - while true do - //fprintf fsiConsoleOutput.Error "\n- kill thread loop...\n"; errorWriter.Flush(); - Thread.Sleep(pauseMilliseconds*2) - match killThreadRequest with - | PrintInterruptRequest -> - fprintf fsiConsoleOutput.Error "%s" (FSIstrings.SR.fsiInterrupt()); fsiConsoleOutput.Error.Flush() - killThreadRequest <- NoRequest - | ThreadAbortRequest -> - fprintf fsiConsoleOutput.Error "%s" (FSIstrings.SR.fsiInterrupt()); fsiConsoleOutput.Error.Flush() - if !progress then fsiConsoleOutput.uprintnfn "%s" (FSIstrings.SR.fsiAbortingMainThread()) - killThreadRequest <- NoRequest - threadToKill.Abort() - | ExitRequest -> - // Mono has some weird behaviour where it blocks on exit - // once CtrlC has ever been pressed. Who knows why? Perhaps something - // to do with having a signal handler installed, but it only happens _after_ - // at least one CtrLC has been pressed. Maybe raising a ThreadAbort causes - // exiting to have problems. - // - // Anyway, we make "#q" work this case by setting ExitRequest and brutally calling - // the process-wide 'exit' - fprintf fsiConsoleOutput.Error "%s" (FSIstrings.SR.fsiExit()); fsiConsoleOutput.Error.Flush() - Utilities.callStaticMethod monoUnixStdlib "exit" [ box 0 ] |> ignore - | _ -> () - done),Name="ControlCAbortAlternativeThread") - killerThread.IsBackground <- true - killerThread.Start() - // exit via kill thread to workaround block-on-exit bugs with Mono once a CtrlC has been pressed - exitViaKillThread <- true - with e -> - fprintf fsiConsoleOutput.Error "%s" (FSIstrings.SR.fsiCouldNotInstallCtrlCHandler(e.Message)) - exitViaKillThread <- false - | Choice2Of2 e -> - fprintf fsiConsoleOutput.Error "%s" (FSIstrings.SR.fsiCouldNotInstallCtrlCHandler(e.Message)) - exitViaKillThread <- false -#endif - - - member x.PosixInvoke(n:int) = - // we run this code once with n = -1 to make sure it is JITted before execution begins - // since we are not allowed to JIT a signal handler. This also ensures the "PosixInvoke" - // method is not eliminated by dead-code elimination - if n >= 0 then - posixReinstate() - stdinInterruptState <- StdinEOFPermittedBecauseCtrlCRecentlyPressed - killThreadRequest <- if (interruptAllowed = InterruptCanRaiseException) then ThreadAbortRequest else PrintInterruptRequest - -#endif - -//---------------------------------------------------------------------------- -// assembly finder -//---------------------------------------------------------------------------- - -#nowarn "40" - -// From http://msdn.microsoft.com/en-us/library/ff527268.aspx -// What the Event Handler Does -// -// The handler for the AssemblyResolve event receives the display name of the assembly to -// be loaded, in the ResolveEventArgs.Name property. If the handler does not recognize the -// assembly name, it returns null (Nothing in Visual Basic, nullptr in Visual C++). -// -// - If the handler recognizes the assembly name, it can load and return an assembly that -// satisfies the request. The following list describes some sample scenarios. -// -// - If the handler knows the location of a version of the assembly, it can load the assembly by -// using the Assembly.LoadFrom or Assembly.LoadFile method, and can return the loaded assembly if successful. -// -// - If the handler has access to a database of assemblies stored as byte arrays, it can load a byte array by -// using one of the Assembly.Load method overloads that take a byte array. -// -// - The handler can generate a dynamic assembly and return it. -// -// It is the responsibility of the event handler to return a suitable assembly. The handler can parse the display -// name of the requested assembly by passing the ResolveEventArgs.Name property value to the AssemblyName(String) -// constructor. Beginning with the .NET Framework version 4, the handler can use the ResolveEventArgs.RequestingAssembly -// property to determine whether the current request is a dependency of another assembly. This information can help -// identify an assembly that will satisfy the dependency. -// -// The event handler can return a different version of the assembly than the version that was requested. -// -// In most cases, the assembly that is returned by the handler appears in the load context, regardless of the context -// the handler loads it into. For example, if the handler uses the Assembly.LoadFrom method to load an assembly into -// the load-from context, the assembly appears in the load context when the handler returns it. However, in the following -// case the assembly appears without context when the handler returns it: -// -// - The handler loads an assembly without context. -// - The ResolveEventArgs.RequestingAssembly property is not null. -// - The requesting assembly (that is, the assembly that is returned by the ResolveEventArgs.RequestingAssembly property) -// was loaded without context. -// -// For information about contexts, see the Assembly.LoadFrom(String) method overload. - -module internal MagicAssemblyResolution = - // FxCop identifies Assembly.LoadFrom. - // See bug 5501 for details on decision to use UnsafeLoadFrom here. - // Summary: - // It is an explicit user trust decision to load an assembly with #r. Scripts are not run automatically (for example, by double-clicking in explorer). - // We considered setting loadFromRemoteSources in fsi.exe.config but this would transitively confer unsafe loading to the code in the referenced - // assemblies. Better to let those assemblies decide for themselves which is safer. - [] - let private assemblyLoadFrom (path:string) = Assembly.UnsafeLoadFrom(path) - - let Install(tcConfigB, tcImports: TcImports, fsiDynamicCompiler: FsiDynamicCompiler, fsiConsoleOutput: FsiConsoleOutput) = - -#if NETSTANDARD - ignore tcConfigB - ignore tcImports - ignore fsiDynamicCompiler - ignore fsiConsoleOutput - { new System.IDisposable with - member x.Dispose() = () } -#else - let ResolveAssembly (ctok, m, tcConfigB, tcImports: TcImports, fsiDynamicCompiler: FsiDynamicCompiler, fsiConsoleOutput: FsiConsoleOutput, fullAssemName:string) = - - try - // Grab the name of the assembly - let tcConfig = TcConfig.Create(tcConfigB,validate=false) - let simpleAssemName = fullAssemName.Split([| ',' |]).[0] - if !progress then fsiConsoleOutput.uprintfn "ATTEMPT MAGIC LOAD ON ASSEMBLY, simpleAssemName = %s" simpleAssemName // "Attempting to load a dynamically required assembly in response to an AssemblyResolve event by using known static assembly references..." - - // Special case: Mono Windows Forms attempts to load an assembly called something like "Windows.Forms.resources" - // We can't resolve this, so don't try. - // REVIEW: Suggest 4481, delete this special case. - if simpleAssemName.EndsWith(".resources",StringComparison.OrdinalIgnoreCase) || - // See F# 1.0 Product Studio bug 1171 - simpleAssemName.EndsWith(".XmlSerializers",StringComparison.OrdinalIgnoreCase) || - (runningOnMono && simpleAssemName = "UIAutomationWinforms") then null else - - // Special case: Is this the global unique dynamic assembly for FSI code? In this case just - // return the dynamic assembly itself. - if fsiDynamicCompiler.DynamicAssemblyName = simpleAssemName then fsiDynamicCompiler.DynamicAssembly else - - // Otherwise continue - let assemblyReferenceTextDll = (simpleAssemName + ".dll") - let assemblyReferenceTextExe = (simpleAssemName + ".exe") - let overallSearchResult = - - // OK, try to resolve as an existing DLL in the resolved reference set. This does unification by assembly name - // once an assembly has been referenced. - let searchResult = tcImports.TryFindExistingFullyQualifiedPathBySimpleAssemblyName (ctok, simpleAssemName) - - match searchResult with - | Some r -> OkResult ([], Choice1Of2 r) - | _ -> - - // OK, try to resolve as a .dll - let searchResult = tcImports.TryResolveAssemblyReference (ctok, AssemblyReference (m, assemblyReferenceTextDll, None), ResolveAssemblyReferenceMode.Speculative) - - match searchResult with - | OkResult (warns,[r]) -> OkResult (warns, Choice1Of2 r.resolvedPath) - | _ -> - - // OK, try to resolve as a .exe - let searchResult = tcImports.TryResolveAssemblyReference (ctok, AssemblyReference (m, assemblyReferenceTextExe, None), ResolveAssemblyReferenceMode.Speculative) - - match searchResult with - | OkResult (warns, [r]) -> OkResult (warns, Choice1Of2 r.resolvedPath) - | _ -> - - if !progress then fsiConsoleOutput.uprintfn "ATTEMPT LOAD, assemblyReferenceTextDll = %s" assemblyReferenceTextDll - /// Take a look through the files quoted, perhaps with explicit paths - let searchResult = - (tcConfig.referencedDLLs - |> List.tryPick (fun assemblyReference -> - if !progress then fsiConsoleOutput.uprintfn "ATTEMPT MAGIC LOAD ON FILE, referencedDLL = %s" assemblyReference.Text - if System.String.Compare(Filename.fileNameOfPath assemblyReference.Text, assemblyReferenceTextDll,StringComparison.OrdinalIgnoreCase) = 0 || - System.String.Compare(Filename.fileNameOfPath assemblyReference.Text, assemblyReferenceTextExe,StringComparison.OrdinalIgnoreCase) = 0 then - Some(tcImports.TryResolveAssemblyReference (ctok, assemblyReference, ResolveAssemblyReferenceMode.Speculative)) - else None )) - - match searchResult with - | Some (OkResult (warns,[r])) -> OkResult (warns, Choice1Of2 r.resolvedPath) - | _ -> - -#if !NO_EXTENSIONTYPING - match tcImports.TryFindProviderGeneratedAssemblyByName(ctok, simpleAssemName) with - | Some(assembly) -> OkResult([],Choice2Of2 assembly) - | None -> -#endif - - // As a last resort, try to find the reference without an extension - match tcImports.TryFindExistingFullyQualifiedPathByExactAssemblyRef(ctok, ILAssemblyRef.Create(simpleAssemName,None,None,false,None,None)) with - | Some(resolvedPath) -> - OkResult([],Choice1Of2 resolvedPath) - | None -> - - ErrorResult([],Failure (FSIstrings.SR.fsiFailedToResolveAssembly(simpleAssemName))) - - match overallSearchResult with - | ErrorResult _ -> null - | OkResult _ -> - let res = CommitOperationResult overallSearchResult - match res with - | Choice1Of2 assemblyName -> - if simpleAssemName <> "Mono.Posix" then fsiConsoleOutput.uprintfn "%s" (FSIstrings.SR.fsiBindingSessionTo(assemblyName)) - assemblyLoadFrom assemblyName - | Choice2Of2 assembly -> - assembly - - with e -> - stopProcessingRecovery e range0 - null - - let rangeStdin = rangeN Lexhelp.stdinMockFilename 0 - - let handler = new ResolveEventHandler(fun _ args -> - // Explanation: our understanding is that magic assembly resolution happens - // during compilation. So we recover the CompilationThreadToken here. - let ctok = AssumeCompilationThreadWithoutEvidence () - ResolveAssembly (ctok, rangeStdin, tcConfigB, tcImports, fsiDynamicCompiler, fsiConsoleOutput, args.Name)) - - AppDomain.CurrentDomain.add_AssemblyResolve(handler) - - { new System.IDisposable with - member x.Dispose() = AppDomain.CurrentDomain.remove_AssemblyResolve(handler) } -#endif - -//---------------------------------------------------------------------------- -// Reading stdin -//---------------------------------------------------------------------------- - -type internal FsiStdinLexerProvider - (tcConfigB, fsiStdinSyphon, - fsiConsoleInput : FsiConsoleInput, - fsiConsoleOutput : FsiConsoleOutput, - fsiOptions : FsiCommandLineOptions, - lexResourceManager : LexResourceManager) = - - // #light is the default for FSI - let interactiveInputLightSyntaxStatus = - let initialLightSyntaxStatus = tcConfigB.light <> Some false - LightSyntaxStatus (initialLightSyntaxStatus, false (* no warnings *)) - - let LexbufFromLineReader (fsiStdinSyphon: FsiStdinSyphon) readf = - UnicodeLexing.FunctionAsLexbuf - (fun (buf, start, len) -> - //fprintf fsiConsoleOutput.Out "Calling ReadLine\n" - let inputOption = try Some(readf()) with :? EndOfStreamException -> None - inputOption |> Option.iter (fun t -> fsiStdinSyphon.Add (t + "\n")) - match inputOption with - | Some(null) | None -> - if !progress then fprintfn fsiConsoleOutput.Out "End of file from TextReader.ReadLine" - 0 - | Some (input:string) -> - let input = input + "\n" - let ninput = input.Length - if ninput > len then fprintf fsiConsoleOutput.Error "%s" (FSIstrings.SR.fsiLineTooLong()) - let ntrimmed = min len ninput - for i = 0 to ntrimmed-1 do -#if FABLE_COMPILER - buf.[i+start] <- uint16 input.[i] -#else - buf.[i+start] <- input.[i] -#endif - ntrimmed - ) - - //---------------------------------------------------------------------------- - // Reading stdin as a lex stream - //---------------------------------------------------------------------------- - - let removeZeroCharsFromString (str:string) = (* bug://4466 *) - if str<>null && str.Contains("\000") then - System.String(str |> Seq.filter (fun c -> c<>'\000') |> Seq.toArray) - else - str - - let CreateLexerForLexBuffer (sourceFileName, lexbuf, errorLogger) = - - Lexhelp.resetLexbufPos sourceFileName lexbuf - let skip = true // don't report whitespace from lexer - let defines = "INTERACTIVE"::tcConfigB.conditionalCompilationDefines - let lexargs = mkLexargs (sourceFileName,defines, interactiveInputLightSyntaxStatus, lexResourceManager, ref [], errorLogger) - let tokenizer = LexFilter.LexFilter(interactiveInputLightSyntaxStatus, tcConfigB.compilingFslib, Lexer.token lexargs skip, lexbuf) - tokenizer - - - // Create a new lexer to read stdin - member __.CreateStdinLexer (errorLogger) = - let lexbuf = - match fsiConsoleInput.TryGetConsole() with - | Some console when fsiOptions.EnableConsoleKeyProcessing && not fsiOptions.IsInteractiveServer -> - LexbufFromLineReader fsiStdinSyphon (fun () -> - match fsiConsoleInput.TryGetFirstLine() with - | Some firstLine -> firstLine - | None -> console()) - | _ -> - LexbufFromLineReader fsiStdinSyphon (fun () -> fsiConsoleInput.In.ReadLine() |> removeZeroCharsFromString) - - fsiStdinSyphon.Reset() - CreateLexerForLexBuffer (Lexhelp.stdinMockFilename, lexbuf, errorLogger) - - // Create a new lexer to read an "included" script file - member __.CreateIncludedScriptLexer (sourceFileName, errorLogger) = - let lexbuf = UnicodeLexing.UnicodeFileAsLexbuf(sourceFileName,tcConfigB.inputCodePage,(*retryLocked*)false) - CreateLexerForLexBuffer (sourceFileName, lexbuf, errorLogger) - - // Create a new lexer to read a string - member this.CreateStringLexer (sourceFileName, source, errorLogger) = - let lexbuf = UnicodeLexing.StringAsLexbuf(source) - CreateLexerForLexBuffer (sourceFileName, lexbuf, errorLogger) - - member __.ConsoleInput = fsiConsoleInput - - member __.CreateBufferLexer (sourceFileName, lexbuf, errorLogger) = CreateLexerForLexBuffer (sourceFileName, lexbuf, errorLogger) - - -//---------------------------------------------------------------------------- -// Process one parsed interaction. This runs on the GUI thread. -// It might be simpler if it ran on the parser thread. -//---------------------------------------------------------------------------- - -type internal FsiInteractionProcessor - (fsi: FsiEvaluationSessionHostConfig, - tcConfigB, - fsiOptions: FsiCommandLineOptions, - fsiDynamicCompiler: FsiDynamicCompiler, - fsiConsolePrompt : FsiConsolePrompt, - fsiConsoleOutput : FsiConsoleOutput, - fsiInterruptController : FsiInterruptController, - fsiStdinLexerProvider : FsiStdinLexerProvider, - lexResourceManager : LexResourceManager, - initialInteractiveState) = - - let referencedAssemblies = Dictionary() - - let mutable currState = initialInteractiveState - let event = Control.Event() - let setCurrState s = currState <- s; event.Trigger() - - let runCodeOnEventLoop errorLogger f istate = - try - fsi.EventLoopInvoke (fun () -> - - // Explanation: We assume the event loop on the 'fsi' object correctly transfers control to - // a unique compilation thread. - let ctok = AssumeCompilationThreadWithoutEvidence() - - // FSI error logging on switched to thread - InstallErrorLoggingOnThisThread errorLogger -#if FX_LCIDFROMCODEPAGE - use _scope = SetCurrentUICultureForThread fsiOptions.FsiLCID -#endif - f ctok istate) - with _ -> - (istate,Completed None) - - let InteractiveCatch (errorLogger: ErrorLogger) (f:_ -> _ * FsiInteractionStepStatus) istate = - try - // reset error count - match errorLogger with - | :? ErrorLoggerThatStopsOnFirstError as errorLogger -> errorLogger.ResetErrorCount() - | _ -> () - - f istate - with e -> - stopProcessingRecovery e range0 - istate,CompletedWithReportedError e - - - let rangeStdin = rangeN Lexhelp.stdinMockFilename 0 - - let ChangeDirectory (path:string) m = - let tcConfig = TcConfig.Create(tcConfigB,validate=false) - let path = tcConfig.MakePathAbsolute path - if Directory.Exists(path) then - tcConfigB.implicitIncludeDir <- path - else - error(Error(FSIstrings.SR.fsiDirectoryDoesNotExist(path),m)) - - - /// Parse one interaction. Called on the parser thread. - let ParseInteraction (tokenizer:LexFilter.LexFilter) = - let lastToken = ref Parser.ELSE // Any token besides SEMICOLON_SEMICOLON will do for initial value - try - if !progress then fprintfn fsiConsoleOutput.Out "In ParseInteraction..." - - let input = - Lexhelp.reusingLexbufForParsing tokenizer.LexBuffer (fun () -> - let lexerWhichSavesLastToken lexbuf = - let tok = tokenizer.Lexer lexbuf - lastToken := tok - tok - Parser.interaction lexerWhichSavesLastToken tokenizer.LexBuffer) - Some input - with e -> - // On error, consume tokens until to ;; or EOF. - // Caveat: Unless the error parse ended on ;; - so check the lastToken returned by the lexer function. - // Caveat: What if this was a look-ahead? That's fine! Since we need to skip to the ;; anyway. - if (match !lastToken with Parser.SEMICOLON_SEMICOLON -> false | _ -> true) then - let mutable tok = Parser.ELSE (* <-- any token <> SEMICOLON_SEMICOLON will do *) - while (match tok with Parser.SEMICOLON_SEMICOLON -> false | _ -> true) - && not tokenizer.LexBuffer.IsPastEndOfStream do - tok <- tokenizer.Lexer tokenizer.LexBuffer - - stopProcessingRecovery e range0 - None - - /// Execute a single parsed interaction. Called on the GUI/execute/main thread. - let ExecInteraction (ctok, tcConfig:TcConfig, istate, action:ParsedFsiInteraction, errorLogger: ErrorLogger) = - istate |> InteractiveCatch errorLogger (fun istate -> - match action with - | IDefns ([ ],_) -> - istate,Completed None - | IDefns ([ SynModuleDecl.DoExpr(_,expr,_)],_) -> - fsiDynamicCompiler.EvalParsedExpression(ctok, errorLogger, istate, expr) - | IDefns (defs,_) -> - fsiDynamicCompiler.EvalParsedDefinitions (ctok, errorLogger, istate, true, false, defs),Completed None - - | IHash (ParsedHashDirective("load",sourceFiles,m),_) -> - fsiDynamicCompiler.EvalSourceFiles (ctok, istate, m, sourceFiles, lexResourceManager, errorLogger),Completed None - - | IHash (ParsedHashDirective(("reference" | "r"),[path],m),_) -> - let resolutions,istate = fsiDynamicCompiler.EvalRequireReference(ctok, istate, m, path) - resolutions |> List.iter (fun ar -> - let format = - if tcConfig.shadowCopyReferences then - let resolvedPath = ar.resolvedPath.ToUpperInvariant() - let fileTime = File.GetLastWriteTimeUtc(resolvedPath) - match referencedAssemblies.TryGetValue(resolvedPath) with - | false, _ -> - referencedAssemblies.Add(resolvedPath, fileTime) - FSIstrings.SR.fsiDidAHashr(ar.resolvedPath) - | true, time when time <> fileTime -> - FSIstrings.SR.fsiDidAHashrWithStaleWarning(ar.resolvedPath) - | _ -> - FSIstrings.SR.fsiDidAHashr(ar.resolvedPath) - else - FSIstrings.SR.fsiDidAHashrWithLockWarning(ar.resolvedPath) - fsiConsoleOutput.uprintnfnn "%s" format) - istate,Completed None - - | IHash (ParsedHashDirective("I",[path],m),_) -> - tcConfigB.AddIncludePath (m,path, tcConfig.implicitIncludeDir) - fsiConsoleOutput.uprintnfnn "%s" (FSIstrings.SR.fsiDidAHashI(tcConfig.MakePathAbsolute path)) - istate,Completed None - - | IHash (ParsedHashDirective("cd",[path],m),_) -> - ChangeDirectory path m - istate,Completed None - - | IHash (ParsedHashDirective("silentCd",[path],m),_) -> - ChangeDirectory path m - fsiConsolePrompt.SkipNext() (* "silent" directive *) - istate,Completed None - - | IHash (ParsedHashDirective("dbgbreak",[],_),_) -> - {istate with debugBreak = true},Completed None - - | IHash (ParsedHashDirective("time",[],_),_) -> - if istate.timing then - fsiConsoleOutput.uprintnfnn "%s" (FSIstrings.SR.fsiTurnedTimingOff()) - else - fsiConsoleOutput.uprintnfnn "%s" (FSIstrings.SR.fsiTurnedTimingOn()) - {istate with timing = not istate.timing},Completed None - - | IHash (ParsedHashDirective("time",[("on" | "off") as v],_),_) -> - if v <> "on" then - fsiConsoleOutput.uprintnfnn "%s" (FSIstrings.SR.fsiTurnedTimingOff()) - else - fsiConsoleOutput.uprintnfnn "%s" (FSIstrings.SR.fsiTurnedTimingOn()) - {istate with timing = (v = "on")},Completed None - - | IHash (ParsedHashDirective("nowarn",numbers,m),_) -> - List.iter (fun (d:string) -> tcConfigB.TurnWarningOff(m,d)) numbers - istate,Completed None - - | IHash (ParsedHashDirective("terms",[],_),_) -> - tcConfigB.showTerms <- not tcConfig.showTerms - istate,Completed None - - | IHash (ParsedHashDirective("types",[],_),_) -> - fsiOptions.ShowTypes <- not fsiOptions.ShowTypes - istate,Completed None - - #if DEBUG - | IHash (ParsedHashDirective("ilcode",[],_m),_) -> - fsiOptions.ShowILCode <- not fsiOptions.ShowILCode; - istate,Completed None - - | IHash (ParsedHashDirective("info",[],_m),_) -> - PrintOptionInfo tcConfigB - istate,Completed None - #endif - - | IHash (ParsedHashDirective(("q" | "quit"),[],_),_) -> - fsiInterruptController.Exit() - - | IHash (ParsedHashDirective("help",[],_),_) -> - fsiOptions.ShowHelp() - istate,Completed None - - | IHash (ParsedHashDirective(c,arg,_),_) -> - fsiConsoleOutput.uprintfn "%s" (FSIstrings.SR.fsiInvalidDirective(c, String.concat " " arg)) // REVIEW: uprintnfnn - like other directives above - istate,Completed None (* REVIEW: cont = CompletedWithReportedError *) - ) - - /// Execute a single parsed interaction which may contain multiple items to be executed - /// independently, because some are #directives. Called on the GUI/execute/main thread. - /// - /// #directive comes through with other definitions as a SynModuleDecl.HashDirective. - /// We split these out for individual processing. - let rec execParsedInteractions (ctok, tcConfig, istate, action, errorLogger: ErrorLogger, lastResult:option) = - let action,nextAction,istate = - match action with - | None -> None,None,istate - | Some (IHash _) -> action,None,istate - | Some (IDefns ([],_)) -> None,None,istate - | Some (IDefns (SynModuleDecl.HashDirective(hash,mh)::defs,m)) -> - Some (IHash(hash,mh)),Some (IDefns(defs,m)),istate - - | Some (IDefns (defs,m)) -> - let isDefHash = function SynModuleDecl.HashDirective(_,_) -> true | _ -> false - let isBreakable def = - // only add automatic debugger breaks before 'let' or 'do' expressions with sequence points - match def with - | SynModuleDecl.DoExpr (SequencePointInfoForBinding.SequencePointAtBinding _, _, _) - | SynModuleDecl.Let (_, SynBinding.Binding(_, _, _, _, _, _, _, _,_,_,_, SequencePointInfoForBinding.SequencePointAtBinding _) :: _, _) -> true - | _ -> false - let defsA = Seq.takeWhile (isDefHash >> not) defs |> Seq.toList - let defsB = Seq.skipWhile (isDefHash >> not) defs |> Seq.toList - - // If user is debugging their script interactively, inject call - // to Debugger.Break() at the first "breakable" line. - // Update istate so that more Break() calls aren't injected when recursing - let defsA,istate = - if istate.debugBreak then - let preBreak = Seq.takeWhile (isBreakable >> not) defsA |> Seq.toList - let postBreak = Seq.skipWhile (isBreakable >> not) defsA |> Seq.toList - match postBreak with - | h :: _ -> preBreak @ (fsiDynamicCompiler.CreateDebuggerBreak(h.Range) :: postBreak), { istate with debugBreak = false } - | _ -> defsA, istate - else defsA,istate - - // When the last declaration has a shape of DoExp (i.e., non-binding), - // transform it to a shape of "let it = ", so we can refer it. - let defsA = if defsA.Length <= 1 || not (List.isEmpty defsB) then defsA else - match List.headAndTail (List.rev defsA) with - | SynModuleDecl.DoExpr(_,exp,_), rest -> (rest |> List.rev) @ (fsiDynamicCompiler.BuildItBinding exp) - | _ -> defsA - - Some (IDefns(defsA,m)),Some (IDefns(defsB,m)),istate - - match action, lastResult with - | None, Some prev -> assert(nextAction.IsNone); istate, prev - | None,_ -> assert(nextAction.IsNone); istate, Completed None - | Some action, _ -> - let istate,cont = ExecInteraction (ctok, tcConfig, istate, action, errorLogger) - match cont with - | Completed _ -> execParsedInteractions (ctok, tcConfig, istate, nextAction, errorLogger, Some cont) - | CompletedWithReportedError e -> istate,CompletedWithReportedError e (* drop nextAction on error *) - | EndOfFile -> istate,defaultArg lastResult (Completed None) (* drop nextAction on EOF *) - | CtrlC -> istate,CtrlC (* drop nextAction on CtrlC *) - - /// Execute a single parsed interaction on the parser/execute thread. - let mainThreadProcessAction ctok action istate = - try - let tcConfig = TcConfig.Create(tcConfigB,validate=false) - if !progress then fprintfn fsiConsoleOutput.Out "In mainThreadProcessAction..."; - fsiInterruptController.InterruptAllowed <- InterruptCanRaiseException; - let res = action ctok tcConfig istate - fsiInterruptController.ClearInterruptRequest() - fsiInterruptController.InterruptAllowed <- InterruptIgnored; - res - with -#if !FX_REDUCED_EXCEPTIONS - | :? ThreadAbortException -> - fsiInterruptController.ClearInterruptRequest() - fsiInterruptController.InterruptAllowed <- InterruptIgnored; - (try Thread.ResetAbort() with _ -> ()); - (istate,CtrlC) -#endif - | e -> - fsiInterruptController.ClearInterruptRequest() - fsiInterruptController.InterruptAllowed <- InterruptIgnored; - stopProcessingRecovery e range0; - istate, CompletedWithReportedError e - - let mainThreadProcessParsedInteractions ctok errorLogger (action, istate) = - istate |> mainThreadProcessAction ctok (fun ctok tcConfig istate -> - execParsedInteractions (ctok, tcConfig, istate, action, errorLogger, None)) - - let parseExpression (tokenizer:LexFilter.LexFilter) = - reusingLexbufForParsing tokenizer.LexBuffer (fun () -> - Parser.typedSeqExprEOF tokenizer.Lexer tokenizer.LexBuffer) - -// let parseType (tokenizer:LexFilter.LexFilter) = -// reusingLexbufForParsing tokenizer.LexBuffer (fun () -> -// Parser.typEOF tokenizer.Lexer tokenizer.LexBuffer) - - let mainThreadProcessParsedExpression ctok errorLogger (expr, istate) = - istate |> InteractiveCatch errorLogger (fun istate -> - istate |> mainThreadProcessAction ctok (fun ctok _tcConfig istate -> - fsiDynamicCompiler.EvalParsedExpression(ctok, errorLogger, istate, expr) )) - - let commitResult (istate, result) = - match result with - | FsiInteractionStepStatus.CtrlC -> Choice2Of2 (Some (OperationCanceledException() :> exn)) - | FsiInteractionStepStatus.EndOfFile -> Choice2Of2 (Some (System.Exception "End of input")) - | FsiInteractionStepStatus.Completed res -> - setCurrState istate - Choice1Of2 res - | FsiInteractionStepStatus.CompletedWithReportedError (StopProcessingExn userExnOpt) -> - Choice2Of2 userExnOpt - | FsiInteractionStepStatus.CompletedWithReportedError _ -> - Choice2Of2 None - - /// Parse then process one parsed interaction. - /// - /// During normal execution, this initially runs on the parser - /// thread, then calls runCodeOnMainThread when it has completed - /// parsing and needs to typecheck and execute a definition. This blocks the parser thread - /// until execution has competed on the GUI thread. - /// - /// During processing of startup scripts, this runs on the main thread. - /// - /// This is blocking: it reads until one chunk of input have been received, unless IsPastEndOfStream is true - member __.ParseAndExecOneSetOfInteractionsFromLexbuf (runCodeOnMainThread, istate:FsiDynamicCompilerState, tokenizer:LexFilter.LexFilter, errorLogger) = - - if tokenizer.LexBuffer.IsPastEndOfStream then - let stepStatus = - if fsiInterruptController.FsiInterruptStdinState = StdinEOFPermittedBecauseCtrlCRecentlyPressed then - fsiInterruptController.FsiInterruptStdinState <- StdinNormal; - CtrlC - else - EndOfFile - istate,stepStatus - - else - - fsiConsolePrompt.Print(); - istate |> InteractiveCatch errorLogger (fun istate -> - if !progress then fprintfn fsiConsoleOutput.Out "entering ParseInteraction..."; - - // Parse the interaction. When FSI.EXE is waiting for input from the console the - // parser thread is blocked somewhere deep this call. - let action = ParseInteraction tokenizer - - if !progress then fprintfn fsiConsoleOutput.Out "returned from ParseInteraction...calling runCodeOnMainThread..."; - - // After we've unblocked and got something to run we switch - // over to the run-thread (e.g. the GUI thread) - let res = istate |> runCodeOnMainThread (fun ctok istate -> mainThreadProcessParsedInteractions ctok errorLogger (action, istate)) - - if !progress then fprintfn fsiConsoleOutput.Out "Just called runCodeOnMainThread, res = %O..." res; - res) - - member __.CurrentState = currState - - /// Perform an "include" on a script file (i.e. a script file specified on the command line) - member processor.EvalIncludedScript (ctok, istate, sourceFile, m, errorLogger) = - let tcConfig = TcConfig.Create(tcConfigB, validate=false) - // Resolve the filename to an absolute filename - let sourceFile = tcConfig.ResolveSourceFile(m, sourceFile, tcConfig.implicitIncludeDir) - // During the processing of the file, further filenames are - // resolved relative to the home directory of the loaded file. - WithImplicitHome (tcConfigB, directoryName sourceFile) (fun () -> - // An included script file may contain maybe several interaction blocks. - // We repeatedly parse and process these, until an error occurs. - let tokenizer = fsiStdinLexerProvider.CreateIncludedScriptLexer (sourceFile, errorLogger) - let rec run istate = - let istate,cont = processor.ParseAndExecOneSetOfInteractionsFromLexbuf ((fun f istate -> f ctok istate), istate, tokenizer, errorLogger) - match cont with Completed _ -> run istate | _ -> istate,cont - - let istate,cont = run istate - - match cont with - | Completed _ -> failwith "EvalIncludedScript: Completed expected to have relooped" - | CompletedWithReportedError e -> istate,CompletedWithReportedError e - | EndOfFile -> istate,Completed None// here file-EOF is normal, continue required - | CtrlC -> istate,CtrlC - ) - - - /// Load the source files, one by one. Called on the main thread. - member processor.EvalIncludedScripts (ctok, istate, sourceFiles, errorLogger) = - match sourceFiles with - | [] -> istate - | sourceFile :: moreSourceFiles -> - // Catch errors on a per-file basis, so results/bindings from pre-error files can be kept. - let istate,cont = InteractiveCatch errorLogger (fun istate -> processor.EvalIncludedScript (ctok, istate, sourceFile, rangeStdin, errorLogger)) istate - match cont with - | Completed _ -> processor.EvalIncludedScripts (ctok, istate, moreSourceFiles, errorLogger) - | CompletedWithReportedError _ -> istate // do not process any more files - | CtrlC -> istate // do not process any more files - | EndOfFile -> assert false; istate // This is unexpected. EndOfFile is replaced by Completed in the called function - - - member processor.LoadInitialFiles (ctok, errorLogger) = - /// Consume initial source files in chunks of scripts or non-scripts - let rec consume istate sourceFiles = - match sourceFiles with - | [] -> istate - | (_,isScript1) :: _ -> - let sourceFiles,rest = List.takeUntil (fun (_,isScript2) -> isScript1 <> isScript2) sourceFiles - let sourceFiles = List.map fst sourceFiles - let istate = - if isScript1 then - processor.EvalIncludedScripts (ctok, istate, sourceFiles, errorLogger) - else - istate |> InteractiveCatch errorLogger (fun istate -> fsiDynamicCompiler.EvalSourceFiles(ctok, istate, rangeStdin, sourceFiles, lexResourceManager, errorLogger), Completed None) |> fst - consume istate rest - - setCurrState (consume currState fsiOptions.SourceFiles) - - if not (List.isEmpty fsiOptions.SourceFiles) then - fsiConsolePrompt.PrintAhead(); // Seems required. I expected this could be deleted. Why not? - - /// Send a dummy interaction through F# Interactive, to ensure all the most common code generation paths are - /// JIT'ed and ready for use. - member __.LoadDummyInteraction(ctok, errorLogger) = - setCurrState (currState |> InteractiveCatch errorLogger (fun istate -> fsiDynamicCompiler.EvalParsedDefinitions (ctok, errorLogger, istate, true, false, []), Completed None) |> fst) - - member __.EvalInteraction(ctok, sourceText, scriptFileName, errorLogger) = - use _unwind1 = ErrorLogger.PushThreadBuildPhaseUntilUnwind(ErrorLogger.BuildPhase.Interactive) - use _unwind2 = ErrorLogger.PushErrorLoggerPhaseUntilUnwind(fun _ -> errorLogger) -#if FX_LCIDFROMCODEPAGE - use _scope = SetCurrentUICultureForThread fsiOptions.FsiLCID -#endif - let lexbuf = UnicodeLexing.StringAsLexbuf(sourceText) - let tokenizer = fsiStdinLexerProvider.CreateBufferLexer(scriptFileName, lexbuf, errorLogger) - currState - |> InteractiveCatch errorLogger (fun istate -> - let expr = ParseInteraction tokenizer - mainThreadProcessParsedInteractions ctok errorLogger (expr, istate) ) - |> commitResult - - member this.EvalScript (ctok, scriptPath, errorLogger) = - // Todo: this runs the script as expected but errors are displayed one line to far in debugger - let sourceText = sprintf "#load @\"%s\" " scriptPath - this.EvalInteraction (ctok, sourceText, scriptPath, errorLogger) - - member __.EvalExpression (ctok, sourceText, scriptFileName, errorLogger) = - use _unwind1 = ErrorLogger.PushThreadBuildPhaseUntilUnwind(ErrorLogger.BuildPhase.Interactive) - use _unwind2 = ErrorLogger.PushErrorLoggerPhaseUntilUnwind(fun _ -> errorLogger) -#if FX_LCIDFROMCODEPAGE - use _scope = SetCurrentUICultureForThread fsiOptions.FsiLCID -#endif - let lexbuf = UnicodeLexing.StringAsLexbuf(sourceText) - let tokenizer = fsiStdinLexerProvider.CreateBufferLexer(scriptFileName, lexbuf, errorLogger) - currState - |> InteractiveCatch errorLogger (fun istate -> - let expr = parseExpression tokenizer - let m = expr.Range - // Make this into "(); expr" to suppress generalization and compilation-as-function - let exprWithSeq = SynExpr.Sequential(SequencePointInfoForSeq.SuppressSequencePointOnStmtOfSequential,true,SynExpr.Const(SynConst.Unit,m.StartRange), expr, m) - mainThreadProcessParsedExpression ctok errorLogger (exprWithSeq, istate)) - |> commitResult - - member __.PartialAssemblySignatureUpdated = event.Publish - - /// Start the background thread used to read the input reader and/or console - /// - /// This is the main stdin loop, running on the stdinReaderThread. - /// - // We run the actual computations for each action on the main GUI thread by using - // mainForm.Invoke to pipe a message back through the form's main event loop. (The message - // is a delegate to execute on the main Thread) - // - member processor.StartStdinReadAndProcessThread (errorLogger) = - - if !progress then fprintfn fsiConsoleOutput.Out "creating stdinReaderThread"; - - let stdinReaderThread = - new Thread(new ThreadStart(fun () -> - InstallErrorLoggingOnThisThread errorLogger // FSI error logging on stdinReaderThread, e.g. parse errors. -#if FX_LCIDFROMCODEPAGE - use _scope = SetCurrentUICultureForThread fsiOptions.FsiLCID -#endif - try - try - let initialTokenizer = fsiStdinLexerProvider.CreateStdinLexer(errorLogger) - if !progress then fprintfn fsiConsoleOutput.Out "READER: stdin thread started..."; - - // Delay until we've peeked the input or read the entire first line - fsiStdinLexerProvider.ConsoleInput.WaitForInitialConsoleInput() - - if !progress then fprintfn fsiConsoleOutput.Out "READER: stdin thread got first line..."; - - let runCodeOnMainThread = runCodeOnEventLoop errorLogger - - // Keep going until EndOfFile on the inReader or console - let rec loop currTokenizer = - - let istateNew,contNew = - processor.ParseAndExecOneSetOfInteractionsFromLexbuf (runCodeOnMainThread, currState, currTokenizer, errorLogger) - - setCurrState istateNew - - match contNew with - | EndOfFile -> () - | CtrlC -> loop (fsiStdinLexerProvider.CreateStdinLexer(errorLogger)) // After each interrupt, restart to a brand new tokenizer - | CompletedWithReportedError _ - | Completed _ -> loop currTokenizer - - loop initialTokenizer - - - if !progress then fprintfn fsiConsoleOutput.Out "- READER: Exiting stdinReaderThread"; - - with e -> stopProcessingRecovery e range0; - - finally - if !progress then fprintfn fsiConsoleOutput.Out "- READER: Exiting process because of failure/exit on stdinReaderThread"; - // REVIEW: On some flavors of Mono, calling exit may freeze the process if we're using the WinForms event handler - // Basically, on Mono 2.6.3, the GUI thread may be left dangling on exit. At that point: - // -- System.Environment.Exit will cause the process to stop responding - // -- Calling Application.Exit() will leave the GUI thread up and running, creating a Zombie process - // -- Calling Abort() on the Main thread or the GUI thread will have no effect, and the process will remain unresponsive - // Also, even the the GUI thread is up and running, the WinForms event loop will be listed as closed - // In this case, killing the process is harmless, since we've already cleaned up after ourselves and FSI is responding - // to an error. (CTRL-C is handled elsewhere.) - // We'll only do this if we're running on Mono, "--gui" is specified and our input is piped in from stdin, so it's still - // fairly constrained. -#if FX_NO_WINFORMS - exit 1 -#else - if runningOnMono && fsiOptions.Gui then - System.Environment.ExitCode <- 1 - Process.GetCurrentProcess().Kill() - else - exit 1 -#endif - - ),Name="StdinReaderThread") - - if !progress then fprintfn fsiConsoleOutput.Out "MAIN: starting stdin thread..." - stdinReaderThread.Start() - - member __.CompletionsForPartialLID (istate, prefix:string) = - let lid,stem = - if prefix.IndexOf(".",StringComparison.Ordinal) >= 0 then - let parts = prefix.Split('.') - let n = parts.Length - Array.sub parts 0 (n-1) |> Array.toList,parts.[n-1] - else - [],prefix - - let tcState = istate.tcState - let amap = istate.tcImports.GetImportMap() - let infoReader = new InfoReader(istate.tcGlobals,amap) - let ncenv = new NameResolver(istate.tcGlobals,amap,infoReader,FakeInstantiationGenerator) - let ad = tcState.TcEnvFromImpls.AccessRights - let nenv = tcState.TcEnvFromImpls.NameEnv - - let nItems = NameResolution.ResolvePartialLongIdent ncenv nenv (ConstraintSolver.IsApplicableMethApprox istate.tcGlobals amap rangeStdin) rangeStdin ad lid false - let names = nItems |> List.map (fun d -> d.DisplayName) - let names = names |> List.filter (fun name -> name.StartsWithOrdinal(stem)) - names - - member __.ParseAndCheckInteraction (ctok, legacyReferenceResolver, checker, istate, text:string) = - let tcConfig = TcConfig.Create(tcConfigB,validate=false) - - let fsiInteractiveChecker = FsiInteractiveChecker(legacyReferenceResolver, checker, tcConfig, istate.tcGlobals, istate.tcImports, istate.tcState) - fsiInteractiveChecker.ParseAndCheckInteraction(ctok, text) - - -//---------------------------------------------------------------------------- -// Server mode: -//---------------------------------------------------------------------------- - -let internal SpawnThread name f = - let th = new Thread(new ThreadStart(f),Name=name) - th.IsBackground <- true; - th.Start() - -let internal SpawnInteractiveServer - (fsi: FsiEvaluationSessionHostConfig, - fsiOptions : FsiCommandLineOptions, - fsiConsoleOutput: FsiConsoleOutput) = - //printf "Spawning fsi server on channel '%s'" !fsiServerName; - SpawnThread "ServerThread" (fun () -> -#if FX_LCIDFROMCODEPAGE - use _scope = SetCurrentUICultureForThread fsiOptions.FsiLCID -#endif - try - fsi.StartServer(fsiOptions.FsiServerName) - with e -> - fprintfn fsiConsoleOutput.Error "%s" (FSIstrings.SR.fsiExceptionRaisedStartingServer(e.ToString()))) - -/// Repeatedly drive the event loop (e.g. Application.Run()) but catching ThreadAbortException and re-running. -/// -/// This gives us a last chance to catch an abort on the main execution thread. -let internal DriveFsiEventLoop (fsi: FsiEvaluationSessionHostConfig, fsiConsoleOutput: FsiConsoleOutput) = - let rec runLoop() = - if !progress then fprintfn fsiConsoleOutput.Out "GUI thread runLoop"; - let restart = - try - // BLOCKING POINT: The GUI Thread spends most (all) of its time this event loop - if !progress then fprintfn fsiConsoleOutput.Out "MAIN: entering event loop..."; - fsi.EventLoopRun() - with -#if !FX_REDUCED_EXCEPTIONS - | :? ThreadAbortException -> - // If this TAE handler kicks it's almost certainly too late to save the - // state of the process - the state of the message loop may have been corrupted - fsiConsoleOutput.uprintnfn "%s" (FSIstrings.SR.fsiUnexpectedThreadAbortException()); - (try Thread.ResetAbort() with _ -> ()); - true - // Try again, just case we can restart -#endif - | e -> - stopProcessingRecovery e range0; - true - // Try again, just case we can restart - if !progress then fprintfn fsiConsoleOutput.Out "MAIN: exited event loop..."; - if restart then runLoop() - - runLoop(); - -/// The primary type, representing a full F# Interactive session, reading from the given -/// text input, writing to the given text output and error writers. -type FsiEvaluationSession (fsi: FsiEvaluationSessionHostConfig, argv:string[], inReader:TextReader, outWriter:TextWriter, errorWriter: TextWriter, fsiCollectible: bool, legacyReferenceResolver: ReferenceResolver.Resolver option) = - - do if not runningOnMono then Lib.UnmanagedProcessExecutionOptions.EnableHeapTerminationOnCorruption() (* SDL recommendation *) - - // Explanation: When FsiEvaluationSession.Create is called we do a bunch of processing. For fsi.exe - // and fsiAnyCpu.exe there are no other active threads at this point, so we can assume this is the - // unique compilation thread. For other users of FsiEvaluationSession it is reasonable to assume that - // the object is not accessed concurrently during startup preparation. - // - // We later switch to doing interaction-by-interaction processing on the "event loop" thread. - let ctokStartup = AssumeCompilationThreadWithoutEvidence () - - let timeReporter = FsiTimeReporter(outWriter) - -#if !FX_REDUCED_CONSOLE - //---------------------------------------------------------------------------- - // Console coloring - //---------------------------------------------------------------------------- - - // Testing shows "console coloring" is broken on some Mono configurations (e.g. Mono 2.4 Suse LiveCD). - // To support fsi usage, the console coloring is switched off by default on Mono. - do if runningOnMono then enableConsoleColoring <- false -#endif - - - //---------------------------------------------------------------------------- - // tcConfig - build the initial config - //---------------------------------------------------------------------------- - - let currentDirectory = Directory.GetCurrentDirectory() - let tryGetMetadataSnapshot = (fun _ -> None) - - let defaultFSharpBinariesDir = FSharpEnvironment.BinFolderOfDefaultFSharpCompiler(FSharpEnvironment.tryCurrentDomain()).Value - - let legacyReferenceResolver = - match legacyReferenceResolver with - | None -> SimulatedMSBuildReferenceResolver.GetBestAvailableResolver() - | Some rr -> rr - - let tcConfigB = - TcConfigBuilder.CreateNew(legacyReferenceResolver, - defaultFSharpBinariesDir=defaultFSharpBinariesDir, - reduceMemoryUsage=ReduceMemoryFlag.Yes, - implicitIncludeDir=currentDirectory, - isInteractive=true, - isInvalidationSupported=false, - defaultCopyFSharpCore=CopyFSharpCoreFlag.No, - tryGetMetadataSnapshot=tryGetMetadataSnapshot) - - let tcConfigP = TcConfigProvider.BasedOnMutableBuilder(tcConfigB) - do tcConfigB.resolutionEnvironment <- ResolutionEnvironment.CompilationAndEvaluation // See Bug 3608 - do tcConfigB.useFsiAuxLib <- fsi.UseFsiAuxLib - -#if NETSTANDARD - do tcConfigB.useSimpleResolution <- true - do SetTargetProfile tcConfigB "netcore" // always assume System.Runtime codegen -#endif - - // Preset: --optimize+ -g --tailcalls+ (see 4505) - do SetOptimizeSwitch tcConfigB OptionSwitch.On - do SetDebugSwitch tcConfigB (Some "pdbonly") OptionSwitch.On - do SetTailcallSwitch tcConfigB OptionSwitch.On - -#if NETSTANDARD - // set platform depending on whether the current process is a 64-bit process. - // BUG 429882 : FsiAnyCPU.exe issues warnings (x64 v MSIL) when referencing 64-bit assemblies - do tcConfigB.platform <- if IntPtr.Size = 8 then Some AMD64 else Some X86 -#endif - - let fsiStdinSyphon = new FsiStdinSyphon(errorWriter) - let fsiConsoleOutput = FsiConsoleOutput(tcConfigB, outWriter, errorWriter) - - let errorLogger = ErrorLoggerThatStopsOnFirstError(tcConfigB, fsiStdinSyphon, fsiConsoleOutput) - - do InstallErrorLoggingOnThisThread errorLogger // FSI error logging on main thread. - - let updateBannerText() = - tcConfigB.productNameForBannerText <- FSIstrings.SR.fsiProductName(FSharpEnvironment.FSharpBannerVersion) - - do updateBannerText() // setting the correct banner so that 'fsi -?' display the right thing - - let fsiOptions = FsiCommandLineOptions(fsi, argv, tcConfigB, fsiConsoleOutput) - let fsiConsolePrompt = FsiConsolePrompt(fsiOptions, fsiConsoleOutput) - - do - match tcConfigB.preferredUiLang with -#if FX_RESHAPED_GLOBALIZATION - | Some s -> System.Globalization.CultureInfo.CurrentUICulture <- new System.Globalization.CultureInfo(s) -#else - | Some s -> Thread.CurrentThread.CurrentUICulture <- new System.Globalization.CultureInfo(s) -#endif - | None -> () - -#if !FX_NO_SERVERCODEPAGES - do - try - SetServerCodePages fsiOptions - with e -> - warning(e) -#endif - - do - updateBannerText() // resetting banner text after parsing options - - if tcConfigB.showBanner then - fsiOptions.ShowBanner() - - do fsiConsoleOutput.uprintfn "" - - // When no source files to load, print ahead prompt here - do if List.isEmpty fsiOptions.SourceFiles then - fsiConsolePrompt.PrintAhead() - - - let fsiConsoleInput = FsiConsoleInput(fsi, fsiOptions, inReader, outWriter) - - /// The single, global interactive checker that can be safely used in conjunction with other operations - /// on the FsiEvaluationSession. - let checker = FSharpChecker.Create(legacyReferenceResolver=legacyReferenceResolver) - - let (tcGlobals,frameworkTcImports,nonFrameworkResolutions,unresolvedReferences) = - try - let tcConfig = tcConfigP.Get(ctokStartup) - checker.FrameworkImportsCache.Get (ctokStartup, tcConfig) |> Cancellable.runWithoutCancellation - with e -> - stopProcessingRecovery e range0; failwithf "Error creating evaluation session: %A" e - - let tcImports = - try - TcImports.BuildNonFrameworkTcImports(ctokStartup, tcConfigP, tcGlobals, frameworkTcImports, nonFrameworkResolutions, unresolvedReferences) |> Cancellable.runWithoutCancellation - with e -> - stopProcessingRecovery e range0; failwithf "Error creating evaluation session: %A" e - - let ilGlobals = tcGlobals.ilg - - let niceNameGen = NiceNameGenerator() - - // Share intern'd strings across all lexing/parsing - let lexResourceManager = new Lexhelp.LexResourceManager() - - /// The lock stops the type checker running at the same time as the server intellisense implementation. - let tcLockObject = box 7 // any new object will do - - let resolveAssemblyRef (aref: ILAssemblyRef) = - // Explanation: This callback is invoked during compilation to resolve assembly references - // We don't yet propagate the ctok through these calls (though it looks plausible to do so). - let ctok = AssumeCompilationThreadWithoutEvidence () -#if !NO_EXTENSIONTYPING - match tcImports.TryFindProviderGeneratedAssemblyByName (ctok, aref.Name) with - | Some assembly -> Some (Choice2Of2 assembly) - | None -> -#endif - match tcImports.TryFindExistingFullyQualifiedPathByExactAssemblyRef (ctok, aref) with - | Some resolvedPath -> Some (Choice1Of2 resolvedPath) - | None -> None - - let fsiDynamicCompiler = FsiDynamicCompiler(fsi, timeReporter, tcConfigB, tcLockObject, outWriter, tcImports, tcGlobals, ilGlobals, fsiOptions, fsiConsoleOutput, fsiCollectible, niceNameGen, resolveAssemblyRef) - - let fsiInterruptController = FsiInterruptController(fsiOptions, fsiConsoleOutput) - - let uninstallMagicAssemblyResolution = MagicAssemblyResolution.Install(tcConfigB, tcImports, fsiDynamicCompiler, fsiConsoleOutput) - - /// This reference cell holds the most recent interactive state - let initialInteractiveState = fsiDynamicCompiler.GetInitialInteractiveState () - - let fsiStdinLexerProvider = FsiStdinLexerProvider(tcConfigB, fsiStdinSyphon, fsiConsoleInput, fsiConsoleOutput, fsiOptions, lexResourceManager) - - let fsiInteractionProcessor = FsiInteractionProcessor(fsi, tcConfigB, fsiOptions, fsiDynamicCompiler, fsiConsolePrompt, fsiConsoleOutput, fsiInterruptController, fsiStdinLexerProvider, lexResourceManager, initialInteractiveState) - - let commitResult res = - match res with - | Choice1Of2 r -> r - | Choice2Of2 None -> failwith "Operation failed. The error text has been printed in the error stream. To return the corresponding FSharpErrorInfo use the EvalInteractionNonThrowing, EvalScriptNonThrowing or EvalExpressionNonThrowing" - | Choice2Of2 (Some userExn) -> raise userExn - - let commitResultNonThrowing errorOptions scriptFile (errorLogger: CompilationErrorLogger) res = - let errs = errorLogger.GetErrors() - let userRes = - match res with - | Choice1Of2 r -> Choice1Of2 r - | Choice2Of2 None -> Choice2Of2 (System.Exception "Operation could not be completed due to earlier error") - | Choice2Of2 (Some userExn) -> Choice2Of2 userExn - - userRes, ErrorHelpers.CreateErrorInfos (errorOptions, true, scriptFile, errs) - - let dummyScriptFileName = "input.fsx" - - interface IDisposable with - member x.Dispose() = - (tcImports :> IDisposable).Dispose() - uninstallMagicAssemblyResolution.Dispose() - - /// Load the dummy interaction, load the initial files, and, - /// if interacting, start the background thread to read the standard input. - member x.Interrupt() = fsiInterruptController.Interrupt() - - /// A host calls this to get the completions for a long identifier, e.g. in the console - member x.GetCompletions(longIdent) = - fsiInteractionProcessor.CompletionsForPartialLID (fsiInteractionProcessor.CurrentState, longIdent) |> Seq.ofList - - member x.ParseAndCheckInteraction(code) = - let ctok = AssumeCompilationThreadWithoutEvidence () - fsiInteractionProcessor.ParseAndCheckInteraction (ctok, legacyReferenceResolver, checker.ReactorOps, fsiInteractionProcessor.CurrentState, code) - - member x.InteractiveChecker = checker - - member x.CurrentPartialAssemblySignature = - fsiDynamicCompiler.CurrentPartialAssemblySignature (fsiInteractionProcessor.CurrentState) - - member x.DynamicAssembly = - fsiDynamicCompiler.DynamicAssembly - /// A host calls this to determine if the --gui parameter is active - member x.IsGui = fsiOptions.Gui - - /// A host calls this to get the active language ID if provided by fsi-server-lcid - member x.LCID = fsiOptions.FsiLCID - -#if FX_NO_APP_DOMAINS - member x.ReportUnhandledException (exn:exn) = ignore exn; () -#else - /// A host calls this to report an unhandled exception in a standard way, e.g. an exception on the GUI thread gets printed to stderr - member x.ReportUnhandledException exn = x.ReportUnhandledExceptionSafe true exn - - member x.ReportUnhandledExceptionSafe isFromThreadException (exn:exn) = - fsi.EventLoopInvoke ( - fun () -> - fprintfn fsiConsoleOutput.Error "%s" (exn.ToString()) - errorLogger.SetError() - try - errorLogger.AbortOnError(fsiConsoleOutput) - with StopProcessing -> - // BUG 664864 some window that use System.Windows.Forms.DataVisualization types (possible FSCharts) was created in FSI. - // at some moment one chart has raised InvalidArgumentException from OnPaint, this exception was intercepted by the code in higher layer and - // passed to Application.OnThreadException. FSI has already attached its own ThreadException handler, inside it will log the original error - // and then raise StopProcessing exception to unwind the stack (and possibly shut down current Application) and get to DriveFsiEventLoop. - // DriveFsiEventLoop handles StopProcessing by suppressing it and restarting event loop from the beginning. - // This schema works almost always except when FSI is started as 64 bit process (FsiAnyCpu) on Windows 7. - - // http://msdn.microsoft.com/en-us/library/windows/desktop/ms633573(v=vs.85).aspx - // Remarks: - // If your application runs on a 32-bit version of Windows operating system, uncaught exceptions from the callback - // will be passed onto higher-level exception handlers of your application when available. - // The system then calls the unhandled exception filter to handle the exception prior to terminating the process. - // If the PCA is enabled, it will offer to fix the problem the next time you run the application. - // However, if your application runs on a 64-bit version of Windows operating system or WOW64, - // you should be aware that a 64-bit operating system handles uncaught exceptions differently based on its 64-bit processor architecture, - // exception architecture, and calling convention. - // The following table summarizes all possible ways that a 64-bit Windows operating system or WOW64 handles uncaught exceptions. - // 1. The system suppresses any uncaught exceptions. - // 2. The system first terminates the process, and then the Program Compatibility Assistant (PCA) offers to fix it the next time - // you run the application. You can disable the PCA mitigation by adding a Compatibility section to the application manifest. - // 3. The system calls the exception filters but suppresses any uncaught exceptions when it leaves the callback scope, - // without invoking the associated handlers. - // Behavior type 2 only applies to the 64-bit version of the Windows 7 operating system. - - // NOTE: tests on Win8 box showed that 64 bit version of the Windows 8 always apply type 2 behavior - - // Effectively this means that when StopProcessing exception is raised from ThreadException callback - it won't be intercepted in DriveFsiEventLoop. - // Instead it will be interpreted as unhandled exception and crash the whole process. - - // FIX: detect if current process in 64 bit running on Windows 7 or Windows 8 and if yes - swallow the StopProcessing and ScheduleRestart instead. - // Visible behavior should not be different, previously exception unwinds the stack and aborts currently running Application. - // After that it will be intercepted and suppressed in DriveFsiEventLoop. - // Now we explicitly shut down Application so after execution of callback will be completed the control flow - // will also go out of WinFormsEventLoop.Run and again get to DriveFsiEventLoop => restart the loop. I'd like the fix to be as conservative as possible - // so we use special case for problematic case instead of just always scheduling restart. - - // http://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx - let os = Environment.OSVersion - // Win7 6.1 - let isWindows7 = os.Version.Major = 6 && os.Version.Minor = 1 - // Win8 6.2 - let isWindows8Plus = os.Version >= Version(6, 2, 0, 0) - if isFromThreadException && ((isWindows7 && (IntPtr.Size = 8) && isWindows8Plus)) -#if DEBUG - // for debug purposes - && Environment.GetEnvironmentVariable("FSI_SCHEDULE_RESTART_WITH_ERRORS") = null -#endif - then - fsi.EventLoopScheduleRestart() - else - reraise() - ) -#endif - - member x.PartialAssemblySignatureUpdated = fsiInteractionProcessor.PartialAssemblySignatureUpdated - - - member x.FormatValue(obj:obj, objTy) = - fsiDynamicCompiler.FormatValue(obj, objTy) - - member x.EvalExpression(sourceText) = - - // Explanation: When the user of the FsiInteractiveSession object calls this method, the - // code is parsed, checked and evaluated on the calling thread. This means EvalExpression - // is not safe to call concurrently. - let ctok = AssumeCompilationThreadWithoutEvidence() - - fsiInteractionProcessor.EvalExpression(ctok, sourceText, dummyScriptFileName, errorLogger) - |> commitResult - - member x.EvalExpressionNonThrowing(sourceText) = - // Explanation: When the user of the FsiInteractiveSession object calls this method, the - // code is parsed, checked and evaluated on the calling thread. This means EvalExpression - // is not safe to call concurrently. - let ctok = AssumeCompilationThreadWithoutEvidence() - - let errorOptions = TcConfig.Create(tcConfigB,validate = false).errorSeverityOptions - let errorLogger = CompilationErrorLogger("EvalInteraction", errorOptions) - fsiInteractionProcessor.EvalExpression(ctok, sourceText, dummyScriptFileName, errorLogger) - |> commitResultNonThrowing errorOptions dummyScriptFileName errorLogger - - member x.EvalInteraction(sourceText) : unit = - // Explanation: When the user of the FsiInteractiveSession object calls this method, the - // code is parsed, checked and evaluated on the calling thread. This means EvalExpression - // is not safe to call concurrently. - let ctok = AssumeCompilationThreadWithoutEvidence() - - fsiInteractionProcessor.EvalInteraction(ctok, sourceText, dummyScriptFileName, errorLogger) - |> commitResult - |> ignore - - member x.EvalInteractionNonThrowing(sourceText) = - // Explanation: When the user of the FsiInteractiveSession object calls this method, the - // code is parsed, checked and evaluated on the calling thread. This means EvalExpression - // is not safe to call concurrently. - let ctok = AssumeCompilationThreadWithoutEvidence() - - let errorOptions = TcConfig.Create(tcConfigB,validate = false).errorSeverityOptions - let errorLogger = CompilationErrorLogger("EvalInteraction", errorOptions) - fsiInteractionProcessor.EvalInteraction(ctok, sourceText, dummyScriptFileName, errorLogger) - |> commitResultNonThrowing errorOptions "input.fsx" errorLogger - |> function Choice1Of2 (_), errs -> Choice1Of2 (), errs | Choice2Of2 exn, errs -> Choice2Of2 exn, errs - - member x.EvalScript(scriptPath) : unit = - // Explanation: When the user of the FsiInteractiveSession object calls this method, the - // code is parsed, checked and evaluated on the calling thread. This means EvalExpression - // is not safe to call concurrently. - let ctok = AssumeCompilationThreadWithoutEvidence() - - fsiInteractionProcessor.EvalScript(ctok, scriptPath, errorLogger) - |> commitResult - |> ignore - - member x.EvalScriptNonThrowing(scriptPath) = - // Explanation: When the user of the FsiInteractiveSession object calls this method, the - // code is parsed, checked and evaluated on the calling thread. This means EvalExpression - // is not safe to call concurrently. - let ctok = AssumeCompilationThreadWithoutEvidence() - - let errorOptions = TcConfig.Create(tcConfigB, validate = false).errorSeverityOptions - let errorLogger = CompilationErrorLogger("EvalInteraction", errorOptions) - fsiInteractionProcessor.EvalScript(ctok, scriptPath, errorLogger) - |> commitResultNonThrowing errorOptions scriptPath errorLogger - |> function Choice1Of2 (_), errs -> Choice1Of2 (), errs | Choice2Of2 exn, errs -> Choice2Of2 exn, errs - - /// Performs these steps: - /// - Load the dummy interaction, if any - /// - Set up exception handling, if any - /// - Load the initial files, if any - /// - Start the background thread to read the standard input, if any - /// - Sit in the GUI event loop indefinitely, if needed - /// - /// This method only returns after "exit". The method repeatedly calls the event loop and - /// the thread may be subject to Thread.Abort() signals if Interrupt() is used, giving rise - /// to internal ThreadAbortExceptions. - /// - /// A background thread is started by this thread to read from the inReader and/or console reader. - - [] - member x.Run() = - progress := condition "FSHARP_INTERACTIVE_PROGRESS" - - // Explanation: When Run is called we do a bunch of processing. For fsi.exe - // and fsiAnyCpu.exe there are no other active threads at this point, so we can assume this is the - // unique compilation thread. For other users of FsiEvaluationSession it is reasonable to assume that - // the object is not accessed concurrently during startup preparation. - // - // We later switch to doing interaction-by-interaction processing on the "event loop" thread - let ctokRun = AssumeCompilationThreadWithoutEvidence () - - if not runningOnMono && fsiOptions.IsInteractiveServer then - SpawnInteractiveServer (fsi, fsiOptions, fsiConsoleOutput) - - use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Interactive - - if fsiOptions.Interact then - // page in the type check env - fsiInteractionProcessor.LoadDummyInteraction(ctokStartup, errorLogger) - if !progress then fprintfn fsiConsoleOutput.Out "MAIN: InstallKillThread!"; - - // Compute how long to pause before a ThreadAbort is actually executed. - // A somewhat arbitrary choice. - let pauseMilliseconds = (if fsiOptions.Gui then 400 else 100) - - // Request that ThreadAbort interrupts be performed on this (current) thread - fsiInterruptController.InstallKillThread(Thread.CurrentThread, pauseMilliseconds) - if !progress then fprintfn fsiConsoleOutput.Out "MAIN: got initial state, creating form"; - -#if !FX_NO_APP_DOMAINS - // Route background exceptions to the exception handlers - AppDomain.CurrentDomain.UnhandledException.Add (fun args -> - match args.ExceptionObject with - | :? System.Exception as err -> x.ReportUnhandledExceptionSafe false err - | _ -> ()) -#endif - - fsiInteractionProcessor.LoadInitialFiles(ctokRun, errorLogger) - - fsiInteractionProcessor.StartStdinReadAndProcessThread(errorLogger) - - DriveFsiEventLoop (fsi, fsiConsoleOutput ) - - else // not interact - if !progress then fprintfn fsiConsoleOutput.Out "Run: not interact, loading intitial files..." - fsiInteractionProcessor.LoadInitialFiles(ctokRun, errorLogger) - - if !progress then fprintfn fsiConsoleOutput.Out "Run: done..." - exit (min errorLogger.ErrorCount 1) - - // The Ctrl-C exception handler that we've passed to native code has - // to be explicitly kept alive. - GC.KeepAlive fsiInterruptController.EventHandlers - - - static member Create(fsiConfig, argv, inReader, outWriter, errorWriter, ?collectible, ?legacyReferenceResolver) = - new FsiEvaluationSession(fsiConfig, argv, inReader, outWriter, errorWriter, defaultArg collectible false, legacyReferenceResolver) - - static member GetDefaultConfiguration(fsiObj:obj) = FsiEvaluationSession.GetDefaultConfiguration(fsiObj, true) - - static member GetDefaultConfiguration(fsiObj:obj, useFsiAuxLib: bool) = - // We want to avoid modifying FSharp.Compiler.Interactive.Settings to avoid republishing that DLL. - // So we access these via reflection - { // Connect the configuration through to the 'fsi' object from FSharp.Compiler.Interactive.Settings - new FsiEvaluationSessionHostConfig () with - member __.FormatProvider = getInstanceProperty fsiObj "FormatProvider" - member __.FloatingPointFormat = getInstanceProperty fsiObj "FloatingPointFormat" - member __.AddedPrinters = getInstanceProperty fsiObj "AddedPrinters" - member __.ShowDeclarationValues = getInstanceProperty fsiObj "ShowDeclarationValues" - member __.ShowIEnumerable = getInstanceProperty fsiObj "ShowIEnumerable" - member __.ShowProperties = getInstanceProperty fsiObj "ShowProperties" - member __.PrintSize = getInstanceProperty fsiObj "PrintSize" - member __.PrintDepth = getInstanceProperty fsiObj "PrintDepth" - member __.PrintWidth = getInstanceProperty fsiObj "PrintWidth" - member __.PrintLength = getInstanceProperty fsiObj "PrintLength" - member __.ReportUserCommandLineArgs args = setInstanceProperty fsiObj "CommandLineArgs" args - member __.StartServer(fsiServerName) = failwith "--fsi-server not implemented in the default configuration" - member __.EventLoopRun() = callInstanceMethod0 (getInstanceProperty fsiObj "EventLoop") [||] "Run" - member __.EventLoopInvoke(f : unit -> 'T) = callInstanceMethod1 (getInstanceProperty fsiObj "EventLoop") [|typeof<'T>|] "Invoke" f - member __.EventLoopScheduleRestart() = callInstanceMethod0 (getInstanceProperty fsiObj "EventLoop") [||] "ScheduleRestart" - member __.UseFsiAuxLib = useFsiAuxLib - member __.GetOptionalConsoleReadLine(_probe) = None } - - -//------------------------------------------------------------------------------- -// If no "fsi" object for the configuration is specified, make the default -// configuration one which stores the settings in-process - -module Settings = - type IEventLoop = - abstract Run : unit -> bool - abstract Invoke : (unit -> 'T) -> 'T - abstract ScheduleRestart : unit -> unit - - // fsi.fs in FSHarp.Compiler.Sevice.dll avoids a hard dependency on FSharp.Compiler.Interactive.Settings.dll - // by providing an optional reimplementation of the functionality - - // An implementation of IEventLoop suitable for the command-line console - [] - type internal SimpleEventLoop() = - let runSignal = new AutoResetEvent(false) - let exitSignal = new AutoResetEvent(false) - let doneSignal = new AutoResetEvent(false) - let mutable queue = ([] : (unit -> obj) list) - let mutable result = (None : obj option) - let setSignal(signal : AutoResetEvent) = while not (signal.Set()) do Thread.Sleep(1); done - let waitSignal signal = WaitHandle.WaitAll([| (signal :> WaitHandle) |]) |> ignore - let waitSignal2 signal1 signal2 = - WaitHandle.WaitAny([| (signal1 :> WaitHandle); (signal2 :> WaitHandle) |]) - let mutable running = false - let mutable restart = false - interface IEventLoop with - member x.Run() = - running <- true - let rec run() = - match waitSignal2 runSignal exitSignal with - | 0 -> - queue |> List.iter (fun f -> result <- try Some(f()) with _ -> None); - setSignal doneSignal - run() - | 1 -> - running <- false; - restart - | _ -> run() - run(); - member x.Invoke(f : unit -> 'T) : 'T = - queue <- [f >> box] - setSignal runSignal - waitSignal doneSignal - result.Value |> unbox - member x.ScheduleRestart() = - if running then - restart <- true - setSignal exitSignal - interface System.IDisposable with - member x.Dispose() = - runSignal.Dispose() - exitSignal.Dispose() - doneSignal.Dispose() - - - - [] - type InteractiveSettings() = - let mutable evLoop = (new SimpleEventLoop() :> IEventLoop) - let mutable showIDictionary = true - let mutable showDeclarationValues = true - let mutable args = Environment.GetCommandLineArgs() - let mutable fpfmt = "g10" - let mutable fp = (CultureInfo.InvariantCulture :> System.IFormatProvider) - let mutable printWidth = 78 - let mutable printDepth = 100 - let mutable printLength = 100 - let mutable printSize = 10000 - let mutable showIEnumerable = true - let mutable showProperties = true - let mutable addedPrinters = [] - - member __.FloatingPointFormat with get() = fpfmt and set v = fpfmt <- v - member __.FormatProvider with get() = fp and set v = fp <- v - member __.PrintWidth with get() = printWidth and set v = printWidth <- v - member __.PrintDepth with get() = printDepth and set v = printDepth <- v - member __.PrintLength with get() = printLength and set v = printLength <- v - member __.PrintSize with get() = printSize and set v = printSize <- v - member __.ShowDeclarationValues with get() = showDeclarationValues and set v = showDeclarationValues <- v - member __.ShowProperties with get() = showProperties and set v = showProperties <- v - member __.ShowIEnumerable with get() = showIEnumerable and set v = showIEnumerable <- v - member __.ShowIDictionary with get() = showIDictionary and set v = showIDictionary <- v - member __.AddedPrinters with get() = addedPrinters and set v = addedPrinters <- v - member __.CommandLineArgs with get() = args and set v = args <- v - member __.AddPrinter(printer : 'T -> string) = - addedPrinters <- Choice1Of2 (typeof<'T>, (fun (x:obj) -> printer (unbox x))) :: addedPrinters - - member __.EventLoop - with get () = evLoop - and set (x:IEventLoop) = evLoop.ScheduleRestart(); evLoop <- x - - member __.AddPrintTransformer(printer : 'T -> obj) = - addedPrinters <- Choice2Of2 (typeof<'T>, (fun (x:obj) -> printer (unbox x))) :: addedPrinters - - let fsi = InteractiveSettings() - -type FsiEvaluationSession with - static member GetDefaultConfiguration() = - FsiEvaluationSession.GetDefaultConfiguration(Settings.fsi, false) - -/// Defines a read-only input stream used to feed content to the hosted F# Interactive dynamic compiler. -[] -type CompilerInputStream() = - inherit Stream() - // Duration (in milliseconds) of the pause in the loop of waitForAtLeastOneByte. - let pauseDuration = 100 - - // Queue of characters waiting to be read. - let readQueue = new Queue() - - let waitForAtLeastOneByte(count : int) = - let rec loop() = - let attempt = - lock readQueue (fun () -> - let n = readQueue.Count - if (n >= 1) then - let lengthToRead = if (n < count) then n else count - let ret = Array.zeroCreate lengthToRead - for i in 0 .. lengthToRead - 1 do - ret.[i] <- readQueue.Dequeue() - Some ret - else - None) - match attempt with - | None -> System.Threading.Thread.Sleep(pauseDuration); loop() - | Some res -> res - loop() - - override x.CanRead = true - override x.CanWrite = false - override x.CanSeek = false - override x.Position with get() = raise (NotSupportedException()) and set _v = raise (NotSupportedException()) - override x.Length = raise (NotSupportedException()) - override x.Flush() = () - override x.Seek(_offset, _origin) = raise (NotSupportedException()) - override x.SetLength(_value) = raise (NotSupportedException()) - override x.Write(_buffer, _offset, _count) = raise (NotSupportedException("Cannot write to input stream")) - override x.Read(buffer, offset, count) = - let bytes = waitForAtLeastOneByte count - Array.Copy(bytes, 0, buffer, offset, bytes.Length) - bytes.Length - - /// Feeds content into the stream. - member x.Add(str:string) = - if (System.String.IsNullOrEmpty(str)) then () else - - lock readQueue (fun () -> - let bytes = System.Text.Encoding.UTF8.GetBytes(str) - for i in 0 .. bytes.Length - 1 do - readQueue.Enqueue(bytes.[i])) - - - -/// Defines a write-only stream used to capture output of the hosted F# Interactive dynamic compiler. -[] -type CompilerOutputStream() = - inherit Stream() - // Queue of characters waiting to be read. - let contentQueue = new Queue() - let nyi() = raise (NotSupportedException()) - - override x.CanRead = false - override x.CanWrite = true - override x.CanSeek = false - override x.Position with get() = nyi() and set _v = nyi() - override x.Length = nyi() - override x.Flush() = () - override x.Seek(_offset, _origin) = nyi() - override x.SetLength(_value) = nyi() - override x.Read(_buffer, _offset, _count) = raise (NotSupportedException("Cannot write to input stream")) - override x.Write(buffer, offset, count) = - let stop = offset + count - if (stop > buffer.Length) then raise (ArgumentException("offset,count")) - - lock contentQueue (fun () -> - for i in offset .. stop - 1 do - contentQueue.Enqueue(buffer.[i])) - - member x.Read() = - lock contentQueue (fun () -> - let n = contentQueue.Count - if (n > 0) then - let bytes = Array.zeroCreate n - for i in 0 .. n-1 do - bytes.[i] <- contentQueue.Dequeue() - - System.Text.Encoding.UTF8.GetString(bytes, 0, n) - else - "") - diff --git a/src/fcs-fable/src/fsharp/fsi/fsi.fsi b/src/fcs-fable/src/fsharp/fsi/fsi.fsi deleted file mode 100644 index 845639cfdc..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/fsi.fsi +++ /dev/null @@ -1,333 +0,0 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. - - -module public FSharp.Compiler.Interactive.Shell - -open System.IO -open FSharp.Compiler -open FSharp.Compiler.SourceCodeServices - -[] -/// Represents an evaluated F# value -type FsiValue = - /// The value, as an object - member ReflectionValue : obj - /// The type of the value, from the point of view of the .NET type system - member ReflectionType : System.Type -#if COMPILER_API - /// The type of the value, from the point of view of the F# type system - member FSharpType : FSharpType -#endif - -[] -type EvaluationEventArgs = - inherit System.EventArgs - - /// The display name of the symbol defined - member Name : string - - /// The value of the symbol defined, if any - member FsiValue : FsiValue option - - /// The FSharpSymbolUse for the symbol defined - member SymbolUse : FSharpSymbolUse - - /// The symbol defined - member Symbol : FSharpSymbol - - /// The details of the expression defined - member ImplementationDeclaration : FSharpImplementationFileDeclaration - -[] -type public FsiEvaluationSessionHostConfig = - new : unit -> FsiEvaluationSessionHostConfig - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract FormatProvider: System.IFormatProvider - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract FloatingPointFormat: string - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract AddedPrinters : Choice<(System.Type * (obj -> string)), (System.Type * (obj -> obj))> list - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract ShowDeclarationValues: bool - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract ShowIEnumerable: bool - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract ShowProperties : bool - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract PrintSize : int - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract PrintDepth : int - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract PrintWidth : int - /// Called by the evaluation session to ask the host for parameters to format text for output - abstract PrintLength : int - /// The evaluation session calls this to report the preferred view of the command line arguments after - /// stripping things like "/use:file.fsx", "-r:Foo.dll" etc. - abstract ReportUserCommandLineArgs : string [] -> unit - - /// Hook for listening for evaluation bindings - member OnEvaluation : IEvent - - - /// - /// Indicate a special console "readline" reader for the evaluation session, if any.  - /// - /// A "console" gets used if --readline is specified (the default on Windows + .NET); and --fsi-server is not - /// given (always combine with --readline-), and OptionalConsoleReadLine is given. - /// When a console is used, special rules apply to "peekahead", which allows early typing on the console. - /// Peekahead happens if --peekahead- is not specified (the default). - /// In this case, a prompt is printed early, a background thread is created and - /// the OptionalConsoleReadLine is used to read the first line. - /// If a console is not used, then inReader.Peek() is called early instead. - ///   - /// - /// Further lines are read using OptionalConsoleReadLine(). - /// If not provided, lines are read using inReader.ReadLine(). - ///   - /// - - abstract GetOptionalConsoleReadLine : probeToSeeIfConsoleWorks: bool -> (unit -> string) option - - /// The evaluation session calls this at an appropriate point in the startup phase if the --fsi-server parameter was given - abstract StartServer : fsiServerName:string -> unit - - /// Called by the evaluation session to ask the host to enter a dispatch loop like Application.Run(). - /// Only called if --gui option is used (which is the default). - /// Gets called towards the end of startup and every time a ThreadAbort escaped to the backup driver loop. - /// Return true if a 'restart' is required, which is a bit meaningless. - abstract EventLoopRun : unit -> bool - - /// Request that the given operation be run synchronously on the event loop. - abstract EventLoopInvoke : codeToRun: (unit -> 'T) -> 'T - - /// Schedule a restart for the event loop. - abstract EventLoopScheduleRestart : unit -> unit - - /// Implicitly reference FSharp.Compiler.Interactive.Settings.dll - abstract UseFsiAuxLib : bool - - -/// Represents an F# Interactive evaluation session. -[] -type FsiEvaluationSession = - - interface System.IDisposable - - /// Create an FsiEvaluationSession, reading from the given text input, writing to the given text output and error writers. - /// - /// Create an FsiEvaluationSession, reading from the given text input, writing to the given text output and error writers - /// - /// The dynamic configuration of the evaluation session - /// The commmand line arguments for the evaluation session - /// Read input from the given reader - /// Write output to the given writer - /// Optionally make the dynamic assmbly for the session collectible - static member Create : fsiConfig: FsiEvaluationSessionHostConfig * argv:string[] * inReader:TextReader * outWriter:TextWriter * errorWriter: TextWriter * ?collectible: bool * ?legacyReferenceResolver: ReferenceResolver.Resolver -> FsiEvaluationSession - - /// A host calls this to request an interrupt on the evaluation thread. - member Interrupt : unit -> unit - - /// A host calls this to get the completions for a long identifier, e.g. in the console - /// - /// Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - /// by input from 'stdin'. - member GetCompletions : longIdent: string -> seq - - /// Execute the code as if it had been entered as one or more interactions, with an - /// implicit termination at the end of the input. Stop on first error, discarding the rest - /// of the input. Errors are sent to the output writer, a 'true' return value indicates there - /// were no errors overall. Execution is performed on the 'Run()' thread. - /// - /// Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - /// by input from 'stdin'. - member EvalInteraction : code: string -> unit - - /// Execute the code as if it had been entered as one or more interactions, with an - /// implicit termination at the end of the input. Stop on first error, discarding the rest - /// of the input. Errors and warnings are collected apart from any exception arising from execution - /// which is returned via a Choice. Execution is performed on the 'Run()' thread. - /// - /// Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - /// by input from 'stdin'. - member EvalInteractionNonThrowing : code: string -> Choice * FSharpErrorInfo[] - - /// Execute the given script. Stop on first error, discarding the rest - /// of the script. Errors are sent to the output writer, a 'true' return value indicates there - /// were no errors overall. Execution is performed on the 'Run()' thread. - /// - /// Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - /// by input from 'stdin'. - member EvalScript : filePath: string -> unit - - /// Execute the given script. Stop on first error, discarding the rest - /// of the script. Errors and warnings are collected apart from any exception arising from execution - /// which is returned via a Choice. Execution is performed on the 'Run()' thread. - /// - /// Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - /// by input from 'stdin'. - member EvalScriptNonThrowing : filePath: string -> Choice * FSharpErrorInfo[] - - /// Execute the code as if it had been entered as one or more interactions, with an - /// implicit termination at the end of the input. Stop on first error, discarding the rest - /// of the input. Errors are sent to the output writer. Parsing is performed on the current thread, and execution is performed - /// sycnhronously on the 'main' thread. - /// - /// Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - /// by input from 'stdin'. - member EvalExpression : code: string -> FsiValue option - - /// Execute the code as if it had been entered as one or more interactions, with an - /// implicit termination at the end of the input. Stop on first error, discarding the rest - /// of the input. Errors and warnings are collected apart from any exception arising from execution - /// which is returned via a Choice. Parsing is performed on the current thread, and execution is performed - /// sycnhronously on the 'main' thread. - /// - /// Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - /// by input from 'stdin'. - member EvalExpressionNonThrowing : code: string -> Choice * FSharpErrorInfo[] - - /// Format a value to a string using the current PrintDepth, PrintLength etc settings provided by the active fsi configuration object - member FormatValue : reflectionValue: obj * reflectionType: System.Type -> string - - /// Raised when an interaction is successfully typechecked and executed, resulting in an update to the - /// type checking state. - /// - /// This event is triggered after parsing and checking, either via input from 'stdin', or via a call to EvalInteraction. - member PartialAssemblySignatureUpdated : IEvent - - /// Typecheck the given script fragment in the type checking context implied by the current state - /// of F# Interactive. The results can be used to access intellisense, perform resolutions, - /// check brace matching and other information. - /// - /// Operations may be run concurrently with other requests to the InteractiveChecker. - /// - /// Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered - /// by input from 'stdin'. - member ParseAndCheckInteraction : code: string -> Async - - /// The single, global interactive checker to use in conjunction with other operations - /// on the FsiEvaluationSession. - /// - /// If you are using an FsiEvaluationSession in this process, you should only use this InteractiveChecker - /// for additional checking operations. - member InteractiveChecker: FSharpChecker - - /// Get a handle to the resolved view of the current signature of the incrementally generated assembly. - member CurrentPartialAssemblySignature : FSharpAssemblySignature - - /// Get a handle to the dynamicly generated assembly - member DynamicAssembly : System.Reflection.Assembly - - /// A host calls this to determine if the --gui parameter is active - member IsGui : bool - - /// A host calls this to get the active language ID if provided by fsi-server-lcid - member LCID : int option - - /// A host calls this to report an unhandled exception in a standard way, e.g. an exception on the GUI thread gets printed to stderr - member ReportUnhandledException : exn: exn -> unit - - /// Load the dummy interaction, load the initial files, and, - /// if interacting, start the background thread to read the standard input. - /// - /// Performs these steps: - /// - Load the dummy interaction, if any - /// - Set up exception handling, if any - /// - Load the initial files, if any - /// - Start the background thread to read the standard input, if any - /// - Sit in the GUI event loop indefinitely, if needed - - member Run : unit -> unit - - /// Get a configuration that uses the 'fsi' object (normally from FSharp.Compiler.Interactive.Settings.dll, - /// an object from another DLL with identical characteristics) to provide an implementation of the configuration. - /// The flag indicates if FSharp.Compiler.Interactive.Settings.dll is referenced by default. - static member GetDefaultConfiguration: fsiObj: obj * useFsiAuxLib: bool -> FsiEvaluationSessionHostConfig - - /// Get a configuration that uses the 'fsi' object (normally from FSharp.Compiler.Interactive.Settings.dll, - /// an object from another DLL with identical characteristics) to provide an implementation of the configuration. - /// FSharp.Compiler.Interactive.Settings.dll is referenced by default. - static member GetDefaultConfiguration: fsiObj: obj -> FsiEvaluationSessionHostConfig - - /// Get a configuration that uses a private inbuilt implementation of the 'fsi' object and does not - /// implicitly reference FSharp.Compiler.Interactive.Settings.dll. - static member GetDefaultConfiguration: unit -> FsiEvaluationSessionHostConfig - - -/// A default implementation of the 'fsi' object, used by GetDefaultConfiguration() -module Settings = - /// An event loop used by the currently executing F# Interactive session to execute code - /// in the context of a GUI or another event-based system. - type IEventLoop = - /// Run the event loop. - /// True if the event loop was restarted; false otherwise. - abstract Run : unit -> bool - /// Request that the given operation be run synchronously on the event loop. - /// The result of the operation. - abstract Invoke : (unit -> 'T) -> 'T - /// Schedule a restart for the event loop. - abstract ScheduleRestart : unit -> unit - - [] - /// Operations supported by the currently executing F# Interactive session. - type InteractiveSettings = - /// Get or set the floating point format used in the output of the interactive session. - member FloatingPointFormat: string with get,set - /// Get or set the format provider used in the output of the interactive session. - member FormatProvider: System.IFormatProvider with get,set - /// Get or set the print width of the interactive session. - member PrintWidth : int with get,set - /// Get or set the print depth of the interactive session. - member PrintDepth : int with get,set - /// Get or set the total print length of the interactive session. - member PrintLength : int with get,set - /// Get or set the total print size of the interactive session. - member PrintSize : int with get,set - /// When set to 'false', disables the display of properties of evaluated objects in the output of the interactive session. - member ShowProperties : bool with get,set - /// When set to 'false', disables the display of sequences in the output of the interactive session. - member ShowIEnumerable: bool with get,set - /// When set to 'false', disables the display of declaration values in the output of the interactive session. - member ShowDeclarationValues: bool with get,set - /// Register a printer that controls the output of the interactive session. - member AddPrinter: ('T -> string) -> unit - /// Register a print transformer that controls the output of the interactive session. - member AddPrintTransformer: ('T -> obj) -> unit - - member internal AddedPrinters : Choice<(System.Type * (obj -> string)), - (System.Type * (obj -> obj))> list - - - /// The command line arguments after ignoring the arguments relevant to the interactive - /// environment and replacing the first argument with the name of the last script file, - /// if any. Thus 'fsi.exe test1.fs test2.fs -- hello goodbye' will give arguments - /// 'test2.fs', 'hello', 'goodbye'. This value will normally be different to those - /// returned by System.Environment.GetCommandLineArgs. - member CommandLineArgs : string [] with get,set - - /// Gets or sets a the current event loop being used to process interactions. - member EventLoop: IEventLoop with get,set - - /// A default implementation of the 'fsi' object, used by GetDefaultConfiguration(). Note this - /// is a different object to FSharp.Compiler.Interactive.Settings.fsi in FSharp.Compiler.Interactive.Settings.dll, - /// which can be used as an alternative implementation of the interactiev settings if passed as a parameter - /// to GetDefaultConfiguration(fsiObj). - val fsi : InteractiveSettings - -/// Defines a read-only input stream used to feed content to the hosted F# Interactive dynamic compiler. -[] -type CompilerInputStream = - inherit Stream - new : unit -> CompilerInputStream - /// Feeds content into the stream. - member Add: str:string -> unit - -/// Defines a write-only stream used to capture output of the hosted F# Interactive dynamic compiler. -[] -type CompilerOutputStream = - inherit Stream - new : unit -> CompilerOutputStream - - member Read : unit -> string - - diff --git a/src/fcs-fable/src/fsharp/fsi/fsi.fsproj b/src/fcs-fable/src/fsharp/fsi/fsi.fsproj deleted file mode 100644 index 77a9274a1e..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/fsi.fsproj +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - Exe - net46;netcoreapp2.1 - netcoreapp2.1 - .exe - $(NoWarn);45;55;62;75;1204 - true - $(OtherFlags) --warnon:1182 --maxerrors:20 --extraoptimizationloops:1 - fsi.res - true - true - - - - x86 - $(DefineConstants);FSI_SHADOW_COPY_REFERENCES;FSI_SERVER - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/fcs-fable/src/fsharp/fsi/fsi.ico b/src/fcs-fable/src/fsharp/fsi/fsi.ico deleted file mode 100644 index 236615e876..0000000000 Binary files a/src/fcs-fable/src/fsharp/fsi/fsi.ico and /dev/null differ diff --git a/src/fcs-fable/src/fsharp/fsi/fsi.rc b/src/fcs-fable/src/fsharp/fsi/fsi.rc deleted file mode 100644 index 8bb21ca275..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/fsi.rc +++ /dev/null @@ -1,5 +0,0 @@ -// compile fsi.res by running Windows SDK tool rc.exe like so -// > rc.exe /i "C:\Program Files (x86)\MSBuild\12.0\Bin" /r fsi.rc -// (can replace msbuild path with any path containing default.win32manifest) -1 ICON "fsi.ico" -1 24 "default.win32manifest" \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/fsi/fsi.res b/src/fcs-fable/src/fsharp/fsi/fsi.res deleted file mode 100644 index e651be6745..0000000000 Binary files a/src/fcs-fable/src/fsharp/fsi/fsi.res and /dev/null differ diff --git a/src/fcs-fable/src/fsharp/fsi/fsimain.fs b/src/fcs-fable/src/fsharp/fsi/fsimain.fs deleted file mode 100644 index 8bb27f1c63..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/fsimain.fs +++ /dev/null @@ -1,344 +0,0 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. - - -// This file provides the actual entry point for fsi.exe. -// -// Configure the F# Interactive Session to -// 1. use a WinForms event loop (introduces a System.Windows.Forms.dll dependency) -// 2. provide a remoting connection for the use of editor-hosted sessions (introduces a System.Remoting dependency) -// 3. connect the configuration to the global state programmer-settable settings in FSharp.Compiler.Interactive.Settings.dll -// 4. implement shadow copy of references - -module internal Sample.FSharp.Compiler.Interactive.Main - -open System -open System.Globalization -open System.IO -open System.Reflection -open System.Threading -open System.Runtime.CompilerServices -#if !FX_NO_WINFORMS -open System.Windows.Forms -#endif - -open FSharp.Compiler -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.Lib -open FSharp.Compiler.Interactive.Shell -open FSharp.Compiler.Interactive -open FSharp.Compiler.Interactive.Shell.Settings - -#nowarn "55" -#nowarn "40" // let rec on value 'fsiConfig' - - -// Hardbinding dependencies should we NGEN fsi.exe -[] do () -[] do () -// Standard attributes -[] -[] -do() - - -/// Set the current ui culture for the current thread. -#if FX_LCIDFROMCODEPAGE -let internal SetCurrentUICultureForThread (lcid : int option) = - let culture = Thread.CurrentThread.CurrentUICulture - match lcid with - | Some n -> Thread.CurrentThread.CurrentUICulture <- new CultureInfo(n) - | None -> () - { new IDisposable with member x.Dispose() = Thread.CurrentThread.CurrentUICulture <- culture } -#endif - -let callStaticMethod (ty:Type) name args = - ty.InvokeMember(name, (BindingFlags.InvokeMethod ||| BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic), null, null, Array.ofList args,Globalization.CultureInfo.InvariantCulture) - -#if !FX_NO_WINFORMS -///Use a dummy to access protected member -type internal DummyForm() = - inherit Form() - member x.DoCreateHandle() = x.CreateHandle() - /// Creating the dummy form object can crash on Mono Mac, and then prints a nasty background - /// error during finalization of the half-initialized object... - override x.Finalize() = () - -/// This is the event loop implementation for winforms -type WinFormsEventLoop() = - let mainForm = new DummyForm() - do mainForm.DoCreateHandle() - let mutable lcid = None - // Set the default thread exception handler - let restart = ref false - member __.LCID with get () = lcid and set v = lcid <- v - interface IEventLoop with - member x.Run() = - restart := false - Application.Run() - !restart - member x.Invoke (f: unit -> 'T) : 'T = - if not mainForm.InvokeRequired then - f() - else - - // Workaround: Mono's Control.Invoke returns a null result. Hence avoid the problem by - // transferring the resulting state using a mutable location. - let mainFormInvokeResultHolder = ref None - - // Actually, Mono's Control.Invoke isn't even blocking (or wasn't on 1.1.15)! So use a signal to indicate completion. - // Indeed, we should probably do this anyway with a timeout so we can report progress from - // the GUI thread. - use doneSignal = new AutoResetEvent(false) - - - // BLOCKING: This blocks the stdin-reader thread until the - // form invocation has completed. NOTE: does not block on Mono, or did not on 1.1.15 - mainForm.Invoke(new MethodInvoker(fun () -> - try - // When we get called back, someone may jack our culture - // So we must reset our UI culture every time -#if FX_LCIDFROMCODEPAGE - use _scope = SetCurrentUICultureForThread lcid -#else - ignore lcid -#endif - mainFormInvokeResultHolder := Some(f ()) - finally - doneSignal.Set() |> ignore)) |> ignore - - //if !progress then fprintfn outWriter "RunCodeOnWinFormsMainThread: Waiting for completion signal...." - while not (doneSignal.WaitOne(new TimeSpan(0,0,1),true)) do - () // if !progress then fprintf outWriter "." outWriter.Flush() - - //if !progress then fprintfn outWriter "RunCodeOnWinFormsMainThread: Got completion signal, res = %b" (Option.isSome !mainFormInvokeResultHolder) - !mainFormInvokeResultHolder |> Option.get - - member x.ScheduleRestart() = restart := true; Application.Exit() - -/// Try to set the unhandled exception mode of System.Windows.Forms -let internal TrySetUnhandledExceptionMode() = - let i = ref 0 // stop inlining - try - Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException) - with _ -> - decr i;() - -#endif - -/// Starts the remoting server to handle interrupt reuests from a host tool. -let StartServer (fsiSession : FsiEvaluationSession) (fsiServerName) = -#if FSI_SERVER - let server = - {new Server.Shared.FSharpInteractiveServer() with - member this.Interrupt() = - //printf "FSI-SERVER: received CTRL-C request...\n" - try - fsiSession.Interrupt() - with e -> - // Final sanity check! - catch all exns - but not expected - assert false - () - } - - Server.Shared.FSharpInteractiveServer.StartServer(fsiServerName,server) -#else - ignore (fsiSession, fsiServerName) -#endif - -//---------------------------------------------------------------------------- -// GUI runCodeOnMainThread -//---------------------------------------------------------------------------- - -let evaluateSession(argv: string[]) = -#if DEBUG - if argv |> Array.exists (fun x -> x = "/pause" || x = "--pause") then - Console.WriteLine("Press any key to continue...") - Console.ReadKey() |> ignore -#endif - -#if !FX_REDUCED_CONSOLE - // When VFSI is running, set the input/output encoding to UTF8. - // Otherwise, unicode gets lost during redirection. - // It is required only under Net4.5 or above (with unicode console feature). - if argv |> Array.exists (fun x -> x.Contains "fsi-server") then - Console.InputEncoding <- System.Text.Encoding.UTF8 - Console.OutputEncoding <- System.Text.Encoding.UTF8 -#else - ignore argv -#endif - - try - // Create the console reader - let console = new FSharp.Compiler.Interactive.ReadLineConsole() - - // Define the function we pass to the FsiEvaluationSession - let getConsoleReadLine (probeToSeeIfConsoleWorks) = - let consoleIsOperational = - if probeToSeeIfConsoleWorks then - //if progress then fprintfn outWriter "probing to see if console works..." - try - // Probe to see if the console looks functional on this version of .NET - let _ = Console.KeyAvailable - let _ = Console.ForegroundColor - let _ = Console.CursorLeft <- Console.CursorLeft - true - with _ -> - //if progress then fprintfn outWriter "probe failed, we have no console..." - false - else true - if consoleIsOperational then - Some (fun () -> console.ReadLine()) - else - None - -//#if USE_FSharp_Compiler_Interactive_Settings - let fsiObjOpt = - let defaultFSharpBinariesDir = -#if FX_NO_APP_DOMAINS - System.AppContext.BaseDirectory -#else - System.AppDomain.CurrentDomain.BaseDirectory -#endif - // We use LoadFrom to make sure we get the copy of this assembly from the right load context - let fsiAssemblyPath = Path.Combine(defaultFSharpBinariesDir,"FSharp.Compiler.Interactive.Settings.dll") - let fsiAssembly = Assembly.LoadFrom(fsiAssemblyPath) - if isNull fsiAssembly then - None - else - let fsiTy = fsiAssembly.GetType("FSharp.Compiler.Interactive.Settings") - if isNull fsiAssembly then failwith "failed to find type FSharp.Compiler.Interactive.Settings in FSharp.Compiler.Interactive.Settings.dll" - Some (callStaticMethod fsiTy "get_fsi" [ ]) - - let fsiConfig0 = - match fsiObjOpt with - | None -> FsiEvaluationSession.GetDefaultConfiguration() - | Some fsiObj -> FsiEvaluationSession.GetDefaultConfiguration(fsiObj, true) - -//fsiSession.LCID -#if !FX_NO_WINFORMS - // Create the WinForms event loop - let fsiWinFormsLoop = - lazy - try Some (WinFormsEventLoop()) - with e -> - printfn "Your system doesn't seem to support WinForms correctly. You will" - printfn "need to set fsi.EventLoop use GUI windows from F# Interactive." - printfn "You can set different event loops for MonoMac, Gtk#, WinForms and other" - printfn "UI toolkits. Drop the --gui argument if no event loop is required." - None -#endif - - let legacyReferenceResolver = -#if CROSS_PLATFORM_COMPILER - SimulatedMSBuildReferenceResolver.SimulatedMSBuildResolver -#else - MSBuildReferenceResolver.Resolver -#endif - // Update the configuration to include 'StartServer', WinFormsEventLoop and 'GetOptionalConsoleReadLine()' - let rec fsiConfig = - { new FsiEvaluationSessionHostConfig () with - member __.FormatProvider = fsiConfig0.FormatProvider - member __.FloatingPointFormat = fsiConfig0.FloatingPointFormat - member __.AddedPrinters = fsiConfig0.AddedPrinters - member __.ShowDeclarationValues = fsiConfig0.ShowDeclarationValues - member __.ShowIEnumerable = fsiConfig0.ShowIEnumerable - member __.ShowProperties = fsiConfig0.ShowProperties - member __.PrintSize = fsiConfig0.PrintSize - member __.PrintDepth = fsiConfig0.PrintDepth - member __.PrintWidth = fsiConfig0.PrintWidth - member __.PrintLength = fsiConfig0.PrintLength - member __.ReportUserCommandLineArgs args = fsiConfig0.ReportUserCommandLineArgs args - member __.EventLoopRun() = -#if !FX_NO_WINFORMS - match (if fsiSession.IsGui then fsiWinFormsLoop.Value else None) with - | Some l -> (l :> IEventLoop).Run() - | _ -> -#endif - fsiConfig0.EventLoopRun() - member __.EventLoopInvoke(f) = -#if !FX_NO_WINFORMS - match (if fsiSession.IsGui then fsiWinFormsLoop.Value else None) with - | Some l -> (l :> IEventLoop).Invoke(f) - | _ -> -#endif - fsiConfig0.EventLoopInvoke(f) - member __.EventLoopScheduleRestart() = -#if !FX_NO_WINFORMS - match (if fsiSession.IsGui then fsiWinFormsLoop.Value else None) with - | Some l -> (l :> IEventLoop).ScheduleRestart() - | _ -> -#endif - fsiConfig0.EventLoopScheduleRestart() - - member __.UseFsiAuxLib = fsiConfig0.UseFsiAuxLib - - member __.StartServer(fsiServerName) = StartServer fsiSession fsiServerName - - // Connect the configuration through to the 'fsi' Event loop - member __.GetOptionalConsoleReadLine(probe) = getConsoleReadLine(probe) } - - // Create the console - and fsiSession : FsiEvaluationSession = FsiEvaluationSession.Create (fsiConfig, argv, Console.In, Console.Out, Console.Error, collectible=false, legacyReferenceResolver=legacyReferenceResolver) - - -#if !FX_NO_WINFORMS - // Configure some remaining parameters of the GUI support - if fsiSession.IsGui then - try - Application.EnableVisualStyles() - with _ -> - () - - // Route GUI application exceptions to the exception handlers - Application.add_ThreadException(new ThreadExceptionEventHandler(fun _ args -> fsiSession.ReportUnhandledException args.Exception)); - - let runningOnMono = try System.Type.GetType("Mono.Runtime") <> null with e-> false - if not runningOnMono then - try - TrySetUnhandledExceptionMode() - with _ -> - () - - fsiWinFormsLoop.Value |> Option.iter (fun l -> l.LCID <- fsiSession.LCID) -#endif - - // Setup the completion function for intellisense in the console - console.SetCompletionFunction(fun (s1,s2) -> fsiSession.GetCompletions (match s1 with | Some s -> s + "." + s2 | None -> s2)) - - // Start the session - fsiSession.Run() - 0 - with - | FSharp.Compiler.ErrorLogger.StopProcessingExn _ -> 1 - | FSharp.Compiler.ErrorLogger.ReportedError _ -> 1 - | e -> eprintf "Exception by fsi.exe:\n%+A\n" e; 1 - -// Mark the main thread as STAThread since it is a GUI thread -[] -[] -[] -let MainMain argv = - ignore argv - let argv = System.Environment.GetCommandLineArgs() - use e = new SaveAndRestoreConsoleEncoding() - -#if !FX_NO_APP_DOMAINS - let timesFlag = argv |> Array.exists (fun x -> x = "/times" || x = "--times") - if timesFlag then - AppDomain.CurrentDomain.ProcessExit.Add(fun _ -> - let stats = ILBinaryReader.GetStatistics() - printfn "STATS: #ByteArrayFile = %d, #MemoryMappedFileOpen = %d, #MemoryMappedFileClosed = %d, #RawMemoryFile = %d, #WeakByteArrayFile = %d" stats.byteFileCount stats.memoryMapFileOpenedCount stats.memoryMapFileClosedCount stats.rawMemoryFileCount stats.weakByteFileCount) -#endif - -#if FSI_SHADOW_COPY_REFERENCES - let isShadowCopy x = (x = "/shadowcopyreferences" || x = "--shadowcopyreferences" || x = "/shadowcopyreferences+" || x = "--shadowcopyreferences+") - if AppDomain.CurrentDomain.IsDefaultAppDomain() && argv |> Array.exists isShadowCopy then - let setupInformation = AppDomain.CurrentDomain.SetupInformation - setupInformation.ShadowCopyFiles <- "true" - let helper = AppDomain.CreateDomain("FSI_Domain", null, setupInformation) - helper.ExecuteAssemblyByName(Assembly.GetExecutingAssembly().GetName()) - else - evaluateSession(argv) -#else - evaluateSession(argv) -#endif diff --git a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.cs.xlf b/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.cs.xlf deleted file mode 100644 index 9841900326..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.cs.xlf +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - Stopped due to error\n - Zastavilo se kvůli chybě.\n - - - - Usage: {0} <options> [script.fsx [<arguments>]] - Použití: {0} <parametry> [skript.fsx [<argumenty>]] - - - - - INPUT FILES - - - VSTUPNÍ SOUBORY - - - - - - CODE GENERATION - - - GENEROVÁNÍ KÓDU - - - - - - ERRORS AND WARNINGS - - - CHYBY A UPOZORNĚNÍ - - - - - - LANGUAGE - - - JAZYK - - - - - - MISCELLANEOUS - - - RŮZNÉ - - - - - - ADVANCED - - - UPŘESNIT - - - - - Exception raised when starting remoting server.\n{0} - Při spouštění serveru vzdálené komunikace se vyvolala výjimka.\n{0} - - - - Use the given file on startup as initial input - Použít při spuštění zadaný soubor jako počáteční vstup - - - - #load the given file on startup - #load zadaného souboru při spuštění - - - - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - Zpracovat zbývající argumenty jako argumenty příkazového řádku, ke kterým se přistupuje pomocí fsi.CommandLineArgs - - - - Display this usage message (Short form: -?) - Zobrazí tuto zprávu o použití (krátký tvar: -?). - - - - Exit fsi after loading the files or running the .fsx script given on the command line - Ukončit soubor fsi po načtení souborů nebo spuštění skriptu .fsx zadaného na příkazovém řádku - - - - Execute interactions on a Windows Forms event loop (on by default) - Provést interakce u smyčky událostí modelu Windows Forms (ve výchozím nastavení zapnuté) - - - - Suppress fsi writing to stdout - Potlačit zapisování fsi do stdout - - - - Support TAB completion in console (on by default) - Podpora dokončování pomocí tabulátorů v konzole (ve výchozím nastavení zapnuté) - - - - Emit debug information in quotations - Generovat ladicí informace v uvozovkách - - - - For help type #help;; - Nápovědu zobrazíte zadáním #help;; - - - - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - Při spuštění procesu F# Interactive se vyskytl problém. Ten mohly způsobit známé potíže s podporou konzoly procesu na pozadí pro aplikace umožňující kódování Unicode v některých systémech Windows. V případě Visual Studia zkuste vybrat Nástroje->Možnosti->F# Interactive a zadat: --fsi-server-no-unicode. - - - - '{0}' is not a valid assembly name - {0} není platný název sestavení. - - - - Directory '{0}' doesn't exist - Adresář {0} neexistuje. - - - - Invalid directive '#{0} {1}' - Neplatná direktiva #{0} {1} - - - - Warning: line too long, ignoring some characters\n - Upozornění: řádek je příliš dlouhý, některé znaky se ignorují.\n - - - - Real: {0}, CPU: {1}, GC {2} - Real: {0}, CPU: {1}, GC {2} - - - - gen - obec - - - - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - \n\nFunkce přehledného výpisu vyvolala výjimku.\nNahlaste prosím tento problém, abychom ho mohli opravit.\nTrasování: {0}\n - - - - F# Interactive directives: - Direktivy F# Interactive: - - - - Reference (dynamically load) the given DLL - Odkazovat (dynamicky načíst) zadanou knihovnu DLL - - - - Add the given search path for referenced DLLs - Přidat zadanou cestu hledání pro odkazované knihovny DLL - - - - Load the given file(s) as if compiled and referenced - Načíst zadané soubory, jako by byly zkompilované a odkazované - - - - Toggle timing on/off - Přepnout časování do polohy zapnuto nebo vypnuto - - - - Display help - Zobrazí nápovědu. - - - - Exit - Ukončit - - - - F# Interactive command line options: - Možnosti příkazového řádku F# Interactive: - - - - See '{0}' for options - Možnosti viz {0} - - - - Loading - Načítání - - - - \n- Interrupt\n - \n- Přerušit\n - - - - \n- Exit...\n - \n- Ukončit...\n - - - - - Aborting main thread... - – Ukončuje se hlavní vlákno... - - - - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - Nepovedlo se nainstalovat obslužnou rutinu ctrl-c. Obslužná rutina Ctrl-C nebude dostupná. Vyskytla se tato chyba:\n\t{0} - - - - --> Referenced '{0}' - --> Odkazovaný soubor {0} - - - - --> Referenced '{0}' (file may be locked by F# Interactive process) - --> Odkazovaný soubor {0} (Soubor musí být procesem F# Interactive uzamčený.) - - - - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - --> Odkazováno {0} (na sestavení s odlišným časovým razítkem se už z tohoto umístění odkazovalo, pro načtení aktualizovaného sestavení obnovte soubor fsi) - - - - --> Added '{0}' to library include path - --> Soubory přidané do knihovny ({0}) zahrnují cestu. - - - - --> Timing now on - --> Časování je teď zapnuté. - - - - --> Timing now off - --> Časování je teď vypnuté. - - - - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - Při zpracování události se vyvolala neočekávaná výjimka ThreadAbortException (Ctrl-C): Pokus o restartování... - - - - Failed to resolve assembly '{0}' - Nepovedlo se přeložit sestavení {0}. - - - - Binding session to '{0}'... - Relace se váže na {0}... - - - - Microsoft (R) F# Interactive version {0} - Microsoft (R) F# Interactive verze {0} - - - - F# Interactive for F# {0} - F# Interactive pro F# {0} - - - - Prevents references from being locked by the F# Interactive process - Znemožňuje zamknutí referencí procesem nástroje F# Interactive. - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.de.xlf b/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.de.xlf deleted file mode 100644 index 93303b279f..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.de.xlf +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - Stopped due to error\n - Aufgrund eines Fehlers beendet\n - - - - Usage: {0} <options> [script.fsx [<arguments>]] - Verwendung: {0} <Optionen> [script.fsx [<Argumente>]] - - - - - INPUT FILES - - - EINGABEDATEIEN - - - - - - CODE GENERATION - - - CODEGENERIERUNG - - - - - - ERRORS AND WARNINGS - - - FEHLER UND WARNUNGEN - - - - - - LANGUAGE - - - SPRACHE - - - - - - MISCELLANEOUS - - - VERSCHIEDENES - - - - - - ADVANCED - - - ERWEITERT - - - - - Exception raised when starting remoting server.\n{0} - Ausnahme beim Starten des Remoteservers.\n{0} - - - - Use the given file on startup as initial input - Die angegebene Datei beim Start als ursprüngliche Eingabe verwenden - - - - #load the given file on startup - #load der angegebenen Datei beim Start - - - - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - Verbleibende Argumente als Befehlszeilenargumente (Zugriff mithilfe von fsi.CommandLineArgs) behandeln - - - - Display this usage message (Short form: -?) - Diesen Hilfetext anzeigen (Kurzform: -?) - - - - Exit fsi after loading the files or running the .fsx script given on the command line - FSI nach Laden der Dateien oder Ausführen des in der Befehlszeile angegebenen .fsx-Skripts beenden - - - - Execute interactions on a Windows Forms event loop (on by default) - Interaktionen in einer Windows Forms-Ereignisschleife ausführen (standardmäßig aktiviert) - - - - Suppress fsi writing to stdout - Schreiben von FSI in stdout unterdrücken - - - - Support TAB completion in console (on by default) - Vervollständigung mit der TAB-TASTE in der Konsole unterstützen (standardmäßig aktiviert) - - - - Emit debug information in quotations - Debugginginformationen in Anführungszeichen ausgeben - - - - For help type #help;; - Um Hilfe zu erhalten, geben Sie "#help;;" ein. - - - - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - Beim Starten des F# Interactive-Prozesses ist ein Fehler aufgetreten. Ursache hierfür kann ein bekanntes Problem mit der Hintergrundprozess-Konsolenunterstützung für Unicode-aktivierte Anwendungen unter manchen Windows-Systemen sein. Wählen Sie "Tools" -> "Optionen" -> "F# Interactive für Visual Studio" aus, und geben Sie "--fsi-server-no-unicode" ein. - - - - '{0}' is not a valid assembly name - {0} ist kein gültiger Assemblyname. - - - - Directory '{0}' doesn't exist - Das Verzeichnis "{0}" ist nicht vorhanden. - - - - Invalid directive '#{0} {1}' - Ungültige Direktive "#{0} {1}" - - - - Warning: line too long, ignoring some characters\n - Warnung: Die Zeile ist zu lang, einige Zeichen werden ignoriert.\n - - - - Real: {0}, CPU: {1}, GC {2} - Real: {0}, CPU: {1}, GC {2} - - - - gen - Gen - - - - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - \n\nAusnahme beim Schöndruck.\nMelden Sie dies, damit das Problem behoben werden kann.\nAblaufverfolgung: {0}\n - - - - F# Interactive directives: - F# Interactive-Direktiven: - - - - Reference (dynamically load) the given DLL - Auf die angegebene DLL verweisen (dynamisch laden) - - - - Add the given search path for referenced DLLs - Angegebenen Suchpfad für DLLs, auf die verwiesen wird, hinzufügen - - - - Load the given file(s) as if compiled and referenced - Angegebene Datei(en) laden, als wären sie kompiliert und würden Verweise aufweisen - - - - Toggle timing on/off - Zeitliche Steuerung ein/aus - - - - Display help - Hilfe anzeigen - - - - Exit - Beenden - - - - F# Interactive command line options: - F# Interactive-Befehlszeilenoptionen: - - - - See '{0}' for options - Optionen finden Sie unter "{0}". - - - - Loading - Laden - - - - \n- Interrupt\n - \n- Unterbrechen\n - - - - \n- Exit...\n - \n- Beenden...\n - - - - - Aborting main thread... - - Hauptthread wird abgebrochen... - - - - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - Fehler beim Installieren des STRG-C-Handlers. STRG-C-Behandlung ist nicht verfügbar. Fehler:\n\t{0} - - - - --> Referenced '{0}' - --> Auf "{0}" wurde verwiesen - - - - --> Referenced '{0}' (file may be locked by F# Interactive process) - --> Auf "{0}" wurde verwiesen (die Datei wird möglicherweise vom F# Interactive-Prozess gesperrt) - - - - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - --> Auf "{0}" wurde verwiesen (eine Assembly mit einem anderen Zeitstempel wurde bereits von diesem Ort verwiesen; stellen Sie fsi wieder her, um die aktualisierte Assembly zu laden) - - - - --> Added '{0}' to library include path - --> "{0}" wurde zum Bibliotheksincludepfad hinzugefügt - - - - --> Timing now on - --> Zeitliche Steuerung jetzt ein - - - - --> Timing now off - --> Zeitliche Steuerung jetzt aus - - - - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - Unerwartete ThreadAbortException (Ctrl-C) während der Ereignisbehandlung: Es wird versucht, neu zu starten... - - - - Failed to resolve assembly '{0}' - Fehler beim Auflösen der Assembly "{0}" - - - - Binding session to '{0}'... - Sitzung wird an "{0}" gebunden... - - - - Microsoft (R) F# Interactive version {0} - Microsoft (R) F# Interactive, Version {0} - - - - F# Interactive for F# {0} - F# Interactive für F# {0} - - - - Prevents references from being locked by the F# Interactive process - Verhindert, dass Verweise vom F# Interactive-Prozess gesperrt werden - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.en.xlf b/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.en.xlf deleted file mode 100644 index b34138d772..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.en.xlf +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - Stopped due to error\n - Stopped due to error\n - - - - Usage: {0} <options> [script.fsx [<arguments>]] - Usage: {0} <options> [script.fsx [<arguments>]] - - - - - INPUT FILES - - - INPUT FILES - - - - - - CODE GENERATION - - - CODE GENERATION - - - - - - ERRORS AND WARNINGS - - - ERRORS AND WARNINGS - - - - - - LANGUAGE - - - LANGUAGE - - - - - - MISCELLANEOUS - - - MISCELLANEOUS - - - - - - ADVANCED - - - ADVANCED - - - - - Exception raised when starting remoting server.\n{0} - Exception raised when starting remoting server.\n{0} - - - - Use the given file on startup as initial input - Use the given file on startup as initial input - - - - #load the given file on startup - #load the given file on startup - - - - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - - - - Display this usage message (Short form: -?) - Display this usage message (Short form: -?) - - - - Exit fsi after loading the files or running the .fsx script given on the command line - Exit fsi after loading the files or running the .fsx script given on the command line - - - - Execute interactions on a Windows Forms event loop (on by default) - Execute interactions on a Windows Forms event loop (on by default) - - - - Suppress fsi writing to stdout - Suppress fsi writing to stdout - - - - Support TAB completion in console (on by default) - Support TAB completion in console (on by default) - - - - Emit debug information in quotations - Emit debug information in quotations - - - - For help type #help;; - For help type #help;; - - - - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - - - - '{0}' is not a valid assembly name - '{0}' is not a valid assembly name - - - - Directory '{0}' doesn't exist - Directory '{0}' doesn't exist - - - - Invalid directive '#{0} {1}' - Invalid directive '#{0} {1}' - - - - Warning: line too long, ignoring some characters\n - Warning: line too long, ignoring some characters\n - - - - Real: {0}, CPU: {1}, GC {2} - Real: {0}, CPU: {1}, GC {2} - - - - gen - gen - - - - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - - - - F# Interactive directives: - F# Interactive directives: - - - - Reference (dynamically load) the given DLL - Reference (dynamically load) the given DLL - - - - Add the given search path for referenced DLLs - Add the given search path for referenced DLLs - - - - Load the given file(s) as if compiled and referenced - Load the given file(s) as if compiled and referenced - - - - Toggle timing on/off - Toggle timing on/off - - - - Display help - Display help - - - - Exit - Exit - - - - F# Interactive command line options: - F# Interactive command line options: - - - - See '{0}' for options - See '{0}' for options - - - - Loading - Loading - - - - \n- Interrupt\n - \n- Interrupt\n - - - - \n- Exit...\n - \n- Exit...\n - - - - - Aborting main thread... - - Aborting main thread... - - - - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - - - - --> Referenced '{0}' - --> Referenced '{0}' - - - - --> Referenced '{0}' (file may be locked by F# Interactive process) - --> Referenced '{0}' (file may be locked by F# Interactive process) - - - - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - - - - --> Added '{0}' to library include path - --> Added '{0}' to library include path - - - - --> Timing now on - --> Timing now on - - - - --> Timing now off - --> Timing now off - - - - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - - - Failed to resolve assembly '{0}' - Failed to resolve assembly '{0}' - - - - Binding session to '{0}'... - Binding session to '{0}'... - - - - Microsoft (R) F# Interactive version {0} - Microsoft (R) F# Interactive version {0} - - - - F# Interactive for F# {0} - F# Interactive for F# {0} - - - - Prevents references from being locked by the F# Interactive process - Prevents references from being locked by the F# Interactive process - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.es.xlf b/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.es.xlf deleted file mode 100644 index 6b25550fed..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.es.xlf +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - Stopped due to error\n - Detenido debido a un error.\n - - - - Usage: {0} <options> [script.fsx [<arguments>]] - Uso: {0} <opciones> [script.fsx [<argumentos>]] - - - - - INPUT FILES - - - ARCHIVOS DE ENTRADA - - - - - - CODE GENERATION - - - GENERACIÓN DE CÓDIGO - - - - - - ERRORS AND WARNINGS - - - ERRORES Y ADVERTENCIAS - - - - - - LANGUAGE - - - LENGUAJE - - - - - - MISCELLANEOUS - - - VARIOS - - - - - - ADVANCED - - - AVANZADAS - - - - - Exception raised when starting remoting server.\n{0} - Se generó una excepción al iniciar el servidor remoto.\n{0} - - - - Use the given file on startup as initial input - Usar el archivo proporcionado al inicio como entrada inicial - - - - #load the given file on startup - #load Cargar el archivo proporcionado al inicio - - - - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - Tratar los demás argumentos como argumentos de la línea de comandos, a los que se obtiene acceso con fsi.CommandLineArgs - - - - Display this usage message (Short form: -?) - Muestra este mensaje de uso (forma corta: -?) - - - - Exit fsi after loading the files or running the .fsx script given on the command line - Salir de fsi después de cargar los archivos o ejecutar el script .fsx proporcionado en la línea de comandos - - - - Execute interactions on a Windows Forms event loop (on by default) - Ejecutar interacciones en un bucle de evento de Windows Forms (activado de forma predeterminada) - - - - Suppress fsi writing to stdout - Suprimir escritura fsi en stdout - - - - Support TAB completion in console (on by default) - Admitir finalización con TAB en la consola (activada de forma predeterminada) - - - - Emit debug information in quotations - Emitir información de depuración en expresiones de código delimitadas - - - - For help type #help;; - Para obtener ayuda, escriba #help;; - - - - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - Se produjo un problema al iniciar el proceso de F# interactivo. Esto puede deberse a un problema conocido de compatibilidad de la consola de procesos en segundo plano con aplicaciones habilitadas para Unicode en algunos sistemas Windows. Pruebe lo siguiente: seleccione Herramientas->Opciones->F# interactivo para Visual Studio y escriba “--fsi-server-no-unicode”. - - - - '{0}' is not a valid assembly name - '{0}' no es un nombre de ensamblado válido. - - - - Directory '{0}' doesn't exist - El directorio '{0}' no existe. - - - - Invalid directive '#{0} {1}' - Directiva '#{0} {1}' no válida. - - - - Warning: line too long, ignoring some characters\n - Advertencia: línea demasiado larga, omitiendo algunos caracteres.\n - - - - Real: {0}, CPU: {1}, GC {2} - Real: {0}, CPU: {1}, GC: {2} - - - - gen - gen - - - - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - \n\nSe generó una excepción durante la impresión con sangría.\nComuníquelo para poder corregirlo.\nSeguimiento: {0}\n - - - - F# Interactive directives: - Directivas de F# interactivo: - - - - Reference (dynamically load) the given DLL - Hacer referencia (cargada dinámicamente) al archivo DLL proporcionado - - - - Add the given search path for referenced DLLs - Agregar la ruta de acceso de búsqueda proporcionada para archivos DLL a los que se hace referencia - - - - Load the given file(s) as if compiled and referenced - Cargar los archivos proporcionados como si estuvieran compilados y referenciados - - - - Toggle timing on/off - Activar o desactivar el control de tiempo - - - - Display help - Mostrar ayuda - - - - Exit - Salir - - - - F# Interactive command line options: - Opciones de la línea de comandos de F# interactivo: - - - - See '{0}' for options - Vea '{0}' para conocer las opciones - - - - Loading - Cargando - - - - \n- Interrupt\n - \n- Interrumpir\n - - - - \n- Exit...\n - \n- Salir...\n - - - - - Aborting main thread... - - Anulando el subproceso principal... - - - - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - No se pudo instalar el controlador ctrl-c. No estará disponible, por tanto, el control mediante Ctrl-C. El error es:\n\t{0} - - - - --> Referenced '{0}' - --> '{0}' referenciado - - - - --> Referenced '{0}' (file may be locked by F# Interactive process) - --> “{0}” al que se hace referencia (el archivo puede estar bloqueado por un proceso de F# interactivo) - - - - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - --> Se hace referencia a '{0}' (ya se ha hecho referencia a un ensamblado con una marca de tiempo distinta desde esta ubicación, restablecer fsi para cargar el ensamblado actualizado) - - - - --> Added '{0}' to library include path - --> Se agregó '{0}' a la ruta de acceso de inclusión de biblioteca - - - - --> Timing now on - --> Control de tiempo activado - - - - --> Timing now off - --> Control de tiempo desactivado - - - - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - ThreadAbortException inesperado (Ctrl-C) durante el control de eventos: intentando reiniciar... - - - - Failed to resolve assembly '{0}' - No se pudo resolver el ensamblado '{0}'. - - - - Binding session to '{0}'... - Enlazando sesión con '{0}'... - - - - Microsoft (R) F# Interactive version {0} - Microsoft (R) F# interactivo, versión {0} - - - - F# Interactive for F# {0} - F# interactivo para F# {0} - - - - Prevents references from being locked by the F# Interactive process - Impide que el proceso de F# interactivo bloquee las referencias - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.fr.xlf b/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.fr.xlf deleted file mode 100644 index b69c71103d..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.fr.xlf +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - Stopped due to error\n - Arrêt en raison d'une erreur\n - - - - Usage: {0} <options> [script.fsx [<arguments>]] - Utilisation : {0} <options> [script.fsx [<arguments>]] - - - - - INPUT FILES - - - FICHIERS D'ENTRÉE - - - - - - CODE GENERATION - - - GÉNÉRATION DE CODE - - - - - - ERRORS AND WARNINGS - - - ERREURS ET AVERTISSEMENTS - - - - - - LANGUAGE - - - LANGAGE - - - - - - MISCELLANEOUS - - - DIVERS - - - - - - ADVANCED - - - AVANCÉ - - - - - Exception raised when starting remoting server.\n{0} - Exception déclenchée lors du démarrage du serveur de communication à distance.\n{0} - - - - Use the given file on startup as initial input - Utilise le fichier spécifié au démarrage en tant qu'entrée initiale - - - - #load the given file on startup - #load le fichier spécifié au démarrage - - - - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - Traite les arguments restants en tant qu'arguments de ligne de commande, accessibles via fsi.CommandLineArgs - - - - Display this usage message (Short form: -?) - Affiche ce message d'utilisation (forme abrégée : -?) - - - - Exit fsi after loading the files or running the .fsx script given on the command line - Sortie de fsi après le chargement des fichiers ou l'exécution du script .fsx spécifié dans la ligne de commande - - - - Execute interactions on a Windows Forms event loop (on by default) - Exécute des interactions dans une boucle d'événements Windows Forms (activé par default) - - - - Suppress fsi writing to stdout - Supprime l'écriture de fsi dans stdout - - - - Support TAB completion in console (on by default) - Prend en charge la saisie semi-automatique via la touche Tab dans la console (activée par défaut) - - - - Emit debug information in quotations - Émettre les informations de débogage entre quotations - - - - For help type #help;; - Pour obtenir de l'aide, tapez #help;; - - - - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - Un problème s'est produit lors du démarrage du processus F# Interactive. Cela peut être dû à un problème connu lié à la prise en charge par la console des processus en arrière-plan pour les applications Unicode sur certains systèmes Windows. Essayez de sélectionner Outils->Options->F# Interactive pour Visual Studio, puis entrez '--fsi-server-no-unicode'. - - - - '{0}' is not a valid assembly name - '{0}' n'est pas un nom d'assembly valide - - - - Directory '{0}' doesn't exist - Le répertoire '{0}' n'existe pas - - - - Invalid directive '#{0} {1}' - Directive non valide '#{0} {1}' - - - - Warning: line too long, ignoring some characters\n - Avertissement : ligne trop longue, certains caractères sont ignorés\n - - - - Real: {0}, CPU: {1}, GC {2} - Réel : {0}, Processeur : {1}, GC {2} - - - - gen - gén - - - - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - \n\nException déclenchée durant l'impression automatique.\nSignalez ce problème afin qu'il soit corrigé.\nTrace : {0}\n - - - - F# Interactive directives: - Directives F# Interactive : - - - - Reference (dynamically load) the given DLL - Référence (charger dynamiquement) la DLL spécifiée - - - - Add the given search path for referenced DLLs - Ajoute le chemin de recherche spécifié pour les DLL référencées - - - - Load the given file(s) as if compiled and referenced - Charge le ou les fichiers spécifiés comme s'ils étaient compilés et référencés - - - - Toggle timing on/off - Minutage activé/désactivé - - - - Display help - Afficher l'aide - - - - Exit - Quitter - - - - F# Interactive command line options: - Options de ligne de commande F# Interactive : - - - - See '{0}' for options - Consulter '{0}' pour les options - - - - Loading - Chargement - - - - \n- Interrupt\n - \n- Interrompre\n - - - - \n- Exit...\n - \n- Quitter...\n - - - - - Aborting main thread... - - Abandon du thread principal... - - - - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - Impossible d'installer le gestionnaire ctrl-c - La gestion Ctrl-C n'est pas disponible. L'erreur était :\n\t{0} - - - - --> Referenced '{0}' - --> Référencement de '{0}' - - - - --> Referenced '{0}' (file may be locked by F# Interactive process) - --> Référencement de '{0}' (le fichier est peut-être verrouillé par le processus F# Interactive) - - - - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - --> Référencement de '{0}' (un assembly avec un horodatage différent a déjà été référencé à partir de cet emplacement, réinitialisez fsi pour charger l'assembly mis à jour) - - - - --> Added '{0}' to library include path - --> Ajout de '{0}' au chemin d'accès Include de la bibliothèque - - - - --> Timing now on - --> Minutage activé - - - - --> Timing now off - --> Minutage désactivé - - - - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - ThreadAbortException inattendu (Ctrl-C) durant la gestion des événements : tentative de redémarrage... - - - - Failed to resolve assembly '{0}' - Échec de la résolution de l'assembly '{0}' - - - - Binding session to '{0}'... - Liaison de la session à '{0}'... - - - - Microsoft (R) F# Interactive version {0} - Microsoft (R) F# Interactive version {0} - - - - F# Interactive for F# {0} - F# Interactive pour F# {0} - - - - Prevents references from being locked by the F# Interactive process - Empêche le blocage des références par le processus de F# Interactive - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.it.xlf b/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.it.xlf deleted file mode 100644 index 51a94aabb2..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.it.xlf +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - Stopped due to error\n - Interruzione a causa di un errore\n - - - - Usage: {0} <options> [script.fsx [<arguments>]] - Sintassi: {0} <opzioni> [script.fsx [<argomenti>]] - - - - - INPUT FILES - - - FILE DI INPUT - - - - - - CODE GENERATION - - - GENERAZIONE CODICE - - - - - - ERRORS AND WARNINGS - - - ERRORI E AVVISI - - - - - - LANGUAGE - - - LINGUAGGIO - - - - - - MISCELLANEOUS - - - VARIE - - - - - - ADVANCED - - - AVANZATE - - - - - Exception raised when starting remoting server.\n{0} - Eccezione all'avvio del server remoto.\n{0} - - - - Use the given file on startup as initial input - Usa il file specificato all'avvio come input iniziale - - - - #load the given file on startup - #load file specificato all'avvio - - - - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - Tratta gli argomenti rimanenti come argomenti della riga di comando accessibili mediante fsi.CommandLineArgs - - - - Display this usage message (Short form: -?) - Visualizza questo messaggio relativo all'uso (forma breve: -?) - - - - Exit fsi after loading the files or running the .fsx script given on the command line - Uscita da fsi dopo il caricamento dei file o l'esecuzione dello script .fsx specificato nella riga di comando - - - - Execute interactions on a Windows Forms event loop (on by default) - Esegue interazioni in un ciclo di eventi di Windows Forms (abilitata per impostazione predefinita) - - - - Suppress fsi writing to stdout - Impedisci scrittura fsi su stdout - - - - Support TAB completion in console (on by default) - Supporta completamento con tasto TAB in console (abilitata per impostazione predefinita) - - - - Emit debug information in quotations - Crea informazioni di debug in quotation - - - - For help type #help;; - Per informazioni, digitare #help;; - - - - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - Si è verificato un problema durante l'avvio del processo F# Interactive. Può trattarsi di un problema noto del supporto della console dei processi in background per le applicazioni abilitate per Unicode in alcuni sistemi Windows. Provare a scegliere Strumenti->Opzioni->F# Interactive per Visual Studio e immettere '--fsi-server-no-unicode'. - - - - '{0}' is not a valid assembly name - '{0}' non è un nome di assembly valido - - - - Directory '{0}' doesn't exist - La directory '{0}' non esiste - - - - Invalid directive '#{0} {1}' - Direttiva '#{0} {1}' non valida - - - - Warning: line too long, ignoring some characters\n - Avviso: riga troppo lunga; alcuni caratteri verranno ignorati\n - - - - Real: {0}, CPU: {1}, GC {2} - Reale: {0}, CPU: {1}, GC {2} - - - - gen - gen - - - - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - \n\nEccezione durante la riformattazione.\nSegnalare il problema affinché possa essere risolto.\nTraccia: {0}\n - - - - F# Interactive directives: - Direttive F# Interactive: - - - - Reference (dynamically load) the given DLL - Aggiunge riferimento alla DLL specificata (caricamento dinamico) - - - - Add the given search path for referenced DLLs - Aggiunge il percorso di ricerca specificato per le DLL a cui viene fatto riferimento - - - - Load the given file(s) as if compiled and referenced - Carica il file (o i file) specificati come se compilati ed aggiunti come riferimento - - - - Toggle timing on/off - Attiva/disattiva la temporizzazione - - - - Display help - Visualizza la guida - - - - Exit - Esci - - - - F# Interactive command line options: - Opzioni della riga di comando F# Interactive: - - - - See '{0}' for options - Vedere '{0}' per le opzioni - - - - Loading - Caricamento - - - - \n- Interrupt\n - \n- Interrupt\n - - - - \n- Exit...\n - \n- Esci...\n - - - - - Aborting main thread... - - Interruzione del thread principale... - - - - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - Non è stato possibile installare il gestore di CTRL+C. La gestione di CTRL+C non sarà disponibile. Errore:\n\t{0} - - - - --> Referenced '{0}' - --> Riferimento a '{0}' - - - - --> Referenced '{0}' (file may be locked by F# Interactive process) - --> Riferimento a '{0}' (il file potrebbe essere bloccato dal processo di F# Interactive) - - - - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - --> Riferimento già presente a '{0}' (un assembly con timestamp diverso è già presente come riferimento in questa posizione. Reimpostare fsi per caricare l'assembly aggiornato) - - - - --> Added '{0}' to library include path - --> Aggiunto '{0}' al percorso di inclusione della libreria - - - - --> Timing now on - --> Temporizzazione attivata - - - - --> Timing now off - --> Temporizzazione disattivata - - - - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - Eccezione ThreadAbortException (Ctrl-C) imprevista durante la gestione dell'evento. Verrà effettuato un tentativo di riavvio... - - - - Failed to resolve assembly '{0}' - Non è stato possibile risolvere l'assembly '{0}' - - - - Binding session to '{0}'... - Binding della sessione a '{0}'... - - - - Microsoft (R) F# Interactive version {0} - Microsoft (R) F# Interactive versione {0} - - - - F# Interactive for F# {0} - F# Interactive per F# {0} - - - - Prevents references from being locked by the F# Interactive process - Impedisce che i riferimenti vengano bloccati dal processo F# Interactive - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.ja.xlf b/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.ja.xlf deleted file mode 100644 index 0751b4601e..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.ja.xlf +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - Stopped due to error\n - エラーのため停止しました\n - - - - Usage: {0} <options> [script.fsx [<arguments>]] - 使い方: {0} <オプション> [script.fsx [<引数>]] - - - - - INPUT FILES - - - 入力ファイル - - - - - - CODE GENERATION - - - コード生成 - - - - - - ERRORS AND WARNINGS - - - エラーと警告 - - - - - - LANGUAGE - - - 言語 - - - - - - MISCELLANEOUS - - - その他 - - - - - - ADVANCED - - - 詳細 - - - - - Exception raised when starting remoting server.\n{0} - サーバーのリモート処理の開始中に例外が発生しました。\n{0} - - - - Use the given file on startup as initial input - 指定されたファイルをスタートアップ時の初期入力として使用します - - - - #load the given file on startup - #load: 指定されたファイルをスタートアップ時に読み込みます - - - - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - 残りの引数は、fsi.CommandLineArgs を使用してアクセスするコマンド ライン引数として扱います - - - - Display this usage message (Short form: -?) - この使用方法に関するメッセージを表示します (短い形式: -?) - - - - Exit fsi after loading the files or running the .fsx script given on the command line - コマンド ライン上で指定されたファイルの読み込みまたは .fsx スクリプトの実行後、fsi を終了します - - - - Execute interactions on a Windows Forms event loop (on by default) - Windows フォーム イベント ループでの対話の実行 (既定でオン) - - - - Suppress fsi writing to stdout - fsi の stdout への書き込みの抑止 - - - - Support TAB completion in console (on by default) - コンソールでの TAB 補完のサポート (既定でオン) - - - - Emit debug information in quotations - デバッグ情報を引用符で囲んで生成します - - - - For help type #help;; - ヘルプを表示するには次を入力してください: #help;; - - - - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - F# インタラクティブのプロセスの開始中に問題が発生しました。この原因は、一部の Windows システム上での Unicode 対応アプリケーションのバックグラウンド プロセス コンソールのサポートに関する既知の問題にある可能性があります。[ツール]5D; の [オプション]5D; から [F# Interactive for Visual Studio]5D; を選択し、「--fsi-server-no-unicode」と入力してください。 - - - - '{0}' is not a valid assembly name - '{0}' は有効なアセンブリ名ではありません - - - - Directory '{0}' doesn't exist - ディレクトリ "{0}" は存在しません - - - - Invalid directive '#{0} {1}' - 無効なディレクティブ '#{0} {1}' - - - - Warning: line too long, ignoring some characters\n - 警告: 行が長すぎます。一部の文字は無視されます\n - - - - Real: {0}, CPU: {1}, GC {2} - リアル: {0}、CPU: {1}、GC {2} - - - - gen - gen - - - - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - \n\n再フォーマット中に例外が発生しました。\nこの問題を解決できるように報告してください。\nトレース: {0}\n - - - - F# Interactive directives: - F# インタラクティブ ディレクティブ: - - - - Reference (dynamically load) the given DLL - 指定された DLL を参照します (動的読み込み) - - - - Add the given search path for referenced DLLs - 参照されている DLL に対し、指定された検索パスを追加します - - - - Load the given file(s) as if compiled and referenced - コンパイルおよび参照されているように、指定されたファイルを読み込みます - - - - Toggle timing on/off - タイミングのオンとオフを切り替えます - - - - Display help - ヘルプの表示 - - - - Exit - 終了 - - - - F# Interactive command line options: - F# インタラクティブ コマンド ライン オプション: - - - - See '{0}' for options - オプションについては '{0}' を参照してください - - - - Loading - 読み込み中 - - - - \n- Interrupt\n - \n- 割り込み\n - - - - \n- Exit...\n - \n- 終了...\n - - - - - Aborting main thread... - - メイン スレッドを中止しています... - - - - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - ctrl-c ハンドラーをインストールできませんでした - Ctrl-C 処理を使用できるようになりません。エラー:\n\t{0} - - - - --> Referenced '{0}' - --> '{0}' を参照しました - - - - --> Referenced '{0}' (file may be locked by F# Interactive process) - --> '{0}' を参照しました (ファイルが F# インタラクティブのプロセスによってロックされている可能性があります) - - - - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - --> 参照された '{0}' (タイムスタンプが異なるアセンブリが既にこの場所から参照されています。fsi をリセットして更新されたアセンブリを読み込んでください) - - - - --> Added '{0}' to library include path - --> ライブラリのインクルード パスに '{0}' を追加しました - - - - --> Timing now on - --> 現在タイミングはオンです - - - - --> Timing now off - --> 現在タイミングはオフです - - - - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - イベント処理中に予期しない ThreadAbortException (Ctrl-C) が発生しました: 再開を試行しています... - - - - Failed to resolve assembly '{0}' - アセンブリ '{0}' を解決できませんでした - - - - Binding session to '{0}'... - セッションを '{0}' にバインドしています... - - - - Microsoft (R) F# Interactive version {0} - Microsoft (R) F# インタラクティブ バージョン {0} - - - - F# Interactive for F# {0} - F# {0} の F# インタラクティブ - - - - Prevents references from being locked by the F# Interactive process - 参照が F# インタラクティブ プロセスによってロックされないようにします。 - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.ko.xlf b/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.ko.xlf deleted file mode 100644 index 5d0b2017d6..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.ko.xlf +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - Stopped due to error\n - 오류 때문에 중지되었습니다.\n - - - - Usage: {0} <options> [script.fsx [<arguments>]] - 사용법: {0} <options> [script.fsx [<arguments>]] - - - - - INPUT FILES - - - 입력 파일 - - - - - - CODE GENERATION - - - 코드 생성 - - - - - - ERRORS AND WARNINGS - - - 오류 및 경고 - - - - - - LANGUAGE - - - 언어 - - - - - - MISCELLANEOUS - - - 기타 - - - - - - ADVANCED - - - 고급 - - - - - Exception raised when starting remoting server.\n{0} - 원격 서버를 시작하는 동안 예외가 발생했습니다.\n{0} - - - - Use the given file on startup as initial input - 시작 시 지정된 파일을 초기 입력으로 사용합니다. - - - - #load the given file on startup - #load: 시작할 때 지정된 파일을 로드합니다. - - - - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - 나머지 인수를 fsi.CommandLineArgs를 사용하여 액세스하는 명령줄 인수로 처리합니다. - - - - Display this usage message (Short form: -?) - 이 사용법 메시지를 표시합니다(약식: -?). - - - - Exit fsi after loading the files or running the .fsx script given on the command line - 파일을 로드한 후 또는 명령줄에 지정된 .fsx 스크립트를 실행한 후 fsi를 종료하세요. - - - - Execute interactions on a Windows Forms event loop (on by default) - Windows Forms 이벤트 루프에서 상호 작용을 실행합니다(기본값: 설정). - - - - Suppress fsi writing to stdout - fsi에서 stdout에 쓰지 않습니다. - - - - Support TAB completion in console (on by default) - 콘솔에서 Tab 키 완성 기능을 지원합니다(기본값: 설정). - - - - Emit debug information in quotations - 인용구의 디버그 정보를 내보냅니다. - - - - For help type #help;; - 도움말을 보려면 #help;;를 입력하세요. - - - - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - F# 대화형 프로세스를 시작하는 동안 오류가 발생했습니다. 일부 Windows 시스템에서 나타나는 유니코드 기반 응용 프로그램의 백그라운드 프로세스 콘솔 지원과 관련된 알려진 문제가 원인일 수 있습니다. [도구]5D;->[옵션]5D;->[Visual Studio용 F# 대화형]5D;를 선택하고 '--fsi-server-no-unicode'를 입력해 보세요. - - - - '{0}' is not a valid assembly name - '{0}'은(는) 올바른 어셈블리 이름이 아닙니다. - - - - Directory '{0}' doesn't exist - '{0}' 디렉터리가 없습니다. - - - - Invalid directive '#{0} {1}' - 잘못된 지시문 '#{0} {1}' - - - - Warning: line too long, ignoring some characters\n - 경고: 줄이 너무 길어 일부 문자가 무시됩니다.\n - - - - Real: {0}, CPU: {1}, GC {2} - 실제: {0}, CPU: {1}, GC {2} - - - - gen - gen - - - - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - \n\n자동 서식 지정 중 예외가 발생했습니다.\n문제를 해결할 수 있도록 보고하세요.\n추적: {0}\n - - - - F# Interactive directives: - F# 대화형 지시문: - - - - Reference (dynamically load) the given DLL - 지정된 DLL을 참조(동적 로드)합니다. - - - - Add the given search path for referenced DLLs - 참조된 DLL에 대해 지정된 검색 경로를 추가합니다. - - - - Load the given file(s) as if compiled and referenced - 지정된 파일이 컴파일되고 참조된 것으로 간주하여 해당 파일을 로드합니다. - - - - Toggle timing on/off - 타이밍을 설정/해제합니다. - - - - Display help - 도움말을 표시합니다. - - - - Exit - 끝내기 - - - - F# Interactive command line options: - F# 대화형 명령줄 옵션: - - - - See '{0}' for options - 옵션에 대해서는 '{0}'을(를) 참조하세요. - - - - Loading - 로드 - - - - \n- Interrupt\n - \n- 중단\n - - - - \n- Exit...\n - \n- 끝내기...\n - - - - - Aborting main thread... - - 주 스레드를 중단하는 중... - - - - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - Ctrl-C 처리기를 설치하지 못했습니다. Ctrl-C 처리를 사용할 수 없습니다. 오류는 다음과 같습니다.\n\t{0} - - - - --> Referenced '{0}' - --> '{0}'이(가) 참조되었습니다. - - - - --> Referenced '{0}' (file may be locked by F# Interactive process) - --> '{0}' 참조됨(파일은 F# 대화형 프로세스에 의해 잠길 수 있음) - - - - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - --> 참조된 '{0}'(다른 타임스탬프가 포함된 어셈블리가 이 위치에서 이미 참조되었습니다. fsi를 다시 설정하여 업데이트된 어셈블리를 로드하세요.) - - - - --> Added '{0}' to library include path - --> 라이브러리 포함 경로에 '{0}'을(를) 추가했습니다. - - - - --> Timing now on - --> 타이밍이 설정되었습니다. - - - - --> Timing now off - --> 타이밍이 해제되었습니다. - - - - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - 이벤트를 처리하는 동안 예기치 않은 ThreadAbortException(Ctrl-C)이 발생했습니다. 다시 시작합니다... - - - - Failed to resolve assembly '{0}' - 어셈블리 '{0}'을(를) 확인하지 못했습니다. - - - - Binding session to '{0}'... - 세션을 '{0}'에 바인딩하는 중... - - - - Microsoft (R) F# Interactive version {0} - Microsoft (R) F# 대화형 버전 {0} - - - - F# Interactive for F# {0} - F# {0}에 대한 F# 대화형 - - - - Prevents references from being locked by the F# Interactive process - 참조가 F# 대화형 프로세스에 의해 잠기지 않도록 합니다. - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.pl.xlf b/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.pl.xlf deleted file mode 100644 index f6b3de9b34..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.pl.xlf +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - Stopped due to error\n - Zatrzymano ze względu na błąd\n - - - - Usage: {0} <options> [script.fsx [<arguments>]] - Składnia: {0} <opcje> [script.fsx [<argumenty>]] - - - - - INPUT FILES - - - PLIKI WEJŚCIOWE - - - - - - CODE GENERATION - - - GENEROWANIE KODU - - - - - - ERRORS AND WARNINGS - - - BŁĘDY I OSTRZEŻENIA - - - - - - LANGUAGE - - - JĘZYK - - - - - - MISCELLANEOUS - - - RÓŻNE - - - - - - ADVANCED - - - ZAAWANSOWANE - - - - - Exception raised when starting remoting server.\n{0} - Wystąpił wyjątek podczas uruchamiania serwera usług zdalnych.\n{0} - - - - Use the given file on startup as initial input - Użyj danego pliku przy uruchamianiu jako początkowych danych wejściowych - - - - #load the given file on startup - #load załaduj dany plik przy uruchamianiu - - - - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - Traktuj pozostałe argumenty jak argumenty wiersza polecenia, do których uzyskano dostęp przy użyciu elementu fsi.CommandLineArgs - - - - Display this usage message (Short form: -?) - Wyświetl ten komunikat dotyczący składni (krótka wersja: -?) - - - - Exit fsi after loading the files or running the .fsx script given on the command line - Po załadowaniu plików lub uruchomieniu skryptu .fsx podanego w wierszu polecenia zakończ działanie programu fsi - - - - Execute interactions on a Windows Forms event loop (on by default) - Wykonaj interakcje w pętli zdarzenia Windows Forms (domyślnie włączone) - - - - Suppress fsi writing to stdout - Pomiń zapisywanie przez program fsi w stdout - - - - Support TAB completion in console (on by default) - Obsługa uzupełniania po naciśnięciu klawisza TAB w konsoli (domyślnie włączona) - - - - Emit debug information in quotations - Emituj informacje debugowania w cudzysłowach - - - - For help type #help;; - Aby uzyskać pomoc, wpisz #help;; - - - - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - Wystąpił problem podczas uruchamiania procesu narzędzia F# Interactive. Taka sytuacja może być spowodowana znanym problemem z obsługą konsoli procesu w tle dla aplikacji obsługujących kodowanie Unicode w niektórych systemach Windows. Spróbuj wybrać kolejno opcje Narzędzia->Opcje->F# Interactive dla Visual Studio i wprowadź „--fsi-server-no-unicode”. - - - - '{0}' is not a valid assembly name - Nazwa „{0}” nie jest prawidłową nazwą zestawu - - - - Directory '{0}' doesn't exist - Katalog „{0}” nie istnieje - - - - Invalid directive '#{0} {1}' - Nieprawidłowa dyrektywa „#{0} {1}” - - - - Warning: line too long, ignoring some characters\n - Ostrzeżenie: wiersz jest zbyt długi, niektóre znaki zostaną zignorowane\n - - - - Real: {0}, CPU: {1}, GC {2} - Czas rzeczywisty: {0}, czas procesora: {1}, operacje odzyskiwania pamięci: {2} - - - - gen - generacja - - - - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - \n\nWystąpił wyjątek podczas formatowania kodu.\nZgłoś go, aby można było rozwiązać ten problem.\nŚlad: {0}\n - - - - F# Interactive directives: - Dyrektywy narzędzia F# Interactive: - - - - Reference (dynamically load) the given DLL - Przywołaj (załaduj dynamicznie) daną bibliotekę DLL - - - - Add the given search path for referenced DLLs - Dodaj daną ścieżkę wyszukiwania dla przywoływanych bibliotek DLL - - - - Load the given file(s) as if compiled and referenced - Załaduj dane pliki tak, jakby były skompilowane i przywoływane - - - - Toggle timing on/off - Włącz/wyłącz funkcję chronometrażu - - - - Display help - Wyświetl pomoc - - - - Exit - Zakończ - - - - F# Interactive command line options: - Opcje wiersza polecenia narzędzia F# Interactive: - - - - See '{0}' for options - Aby uzyskać informacje o opcjach, zobacz „{0}” - - - - Loading - Ładowanie - - - - \n- Interrupt\n - \n- Przerwanie\n - - - - \n- Exit...\n - \n- Trwa kończenie działania...\n - - - - - Aborting main thread... - - Trwa przerywanie głównego wątku... - - - - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - Nie powiodło się zainstalowanie procedury obsługi ctrl-c. Obsługa Ctrl-C będzie niedostępna. Błąd:\n\t{0} - - - - --> Referenced '{0}' - --> Przywołano element „{0}” - - - - --> Referenced '{0}' (file may be locked by F# Interactive process) - --> Przywołano element „{0}” (plik może być zablokowany przez proces narzędzia F# Interactive) - - - - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - --> Zestaw „{0}” występujący w odwołaniu (zestaw z inną sygnaturą czasową występuje już w odwołaniu z tej lokalizacji; zresetuj narzędzie fsi, aby załadować zaktualizowany zestaw) - - - - --> Added '{0}' to library include path - --> Dodano element „{0}” do ścieżki dołączenia biblioteki - - - - --> Timing now on - --> Funkcja chronometrażu została włączona - - - - --> Timing now off - --> Funkcja chronometrażu została wyłączona - - - - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - Nieoczekiwany element ThreadAbortException (Ctrl-C) podczas obsługi zdarzenia: trwa próba ponownego uruchomienia... - - - - Failed to resolve assembly '{0}' - Nie powiodło się rozpoznanie zestawu „{0}” - - - - Binding session to '{0}'... - Trwa tworzenie powiązania sesji z „{0}”... - - - - Microsoft (R) F# Interactive version {0} - Microsoft (R) F# Interactive, wersja {0} - - - - F# Interactive for F# {0} - F# Interactive dla języka F# {0} - - - - Prevents references from being locked by the F# Interactive process - Uniemożliwia blokowanie odwołań przez proces narzędzia F# Interactive - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.pt-BR.xlf b/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.pt-BR.xlf deleted file mode 100644 index 70a3636f04..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.pt-BR.xlf +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - Stopped due to error\n - Interrompido devido a erro\n - - - - Usage: {0} <options> [script.fsx [<arguments>]] - Uso: {0} <opções> [script.fsx [<argumentos>]] - - - - - INPUT FILES - - - ARQUIVOS DE ENTRADA - - - - - - CODE GENERATION - - - GERAÇÃO DE CÓDIGO - - - - - - ERRORS AND WARNINGS - - - ERROS E AVISOS - - - - - - LANGUAGE - - - LINGUAGEM - - - - - - MISCELLANEOUS - - - DIVERSOS - - - - - - ADVANCED - - - AVANÇADO - - - - - Exception raised when starting remoting server.\n{0} - Exceção levantadas ao iniciar o servidor remoto.\n{0} - - - - Use the given file on startup as initial input - Use o arquivo fornecido na inicialização como entrada inicial - - - - #load the given file on startup - #load o arquivo dado na inicialização - - - - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - Tratar argumentos restantes como argumentos de linha de comando acessados através de fsi.CommandLineArgs - - - - Display this usage message (Short form: -?) - Exibir esta mensagem de uso (Forma abreviada: -?) - - - - Exit fsi after loading the files or running the .fsx script given on the command line - Feche fsi após o carregamento dos arquivos ou execução do script .fsx fornecido na linha de comando - - - - Execute interactions on a Windows Forms event loop (on by default) - Execute interações em um loop de eventos do Windows Forms (por padrão) - - - - Suppress fsi writing to stdout - Suprimir fsi gravando ao stdout - - - - Support TAB completion in console (on by default) - Suportar a conclusão TAB no console (por padrão) - - - - Emit debug information in quotations - Emitir informações de depuração entre aspas - - - - For help type #help;; - Para ajuda digite #help;; - - - - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - Um problema ocorreu na inicialização do processo F# Interativo. Isto pode ter ocorrido devido a um problema conhecido com processo de fundo do console de apoio pelo aplicativos habilitados Unicode em alguns sistemas do Windows. Tente Ferramentas->Opções->F# Interativo para Visual Studio e insira '--fsi-server-no-unicode'. - - - - '{0}' is not a valid assembly name - '{0}' não é um nome de assembly válido - - - - Directory '{0}' doesn't exist - O diretório '{0}' não existe - - - - Invalid directive '#{0} {1}' - Diretriz inválida '#{0} {1}' - - - - Warning: line too long, ignoring some characters\n - Aviso: linha muito longa, ignore alguns caracteres\n - - - - Real: {0}, CPU: {1}, GC {2} - Real: {0}, CPU: {1}, GC {2} - - - - gen - gen - - - - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - \n\nExceção levantadas durante a reformatação automática.\nReporte esta exceção para ela que possa ser corrigida.\nRastrear: {0}\n - - - - F# Interactive directives: - Diretrizes F# Interativo: - - - - Reference (dynamically load) the given DLL - Referenciar (carregar dinamicamente) o DLL dado - - - - Add the given search path for referenced DLLs - Adicionar o caminho pesquisado dado aos DLLs referenciados - - - - Load the given file(s) as if compiled and referenced - Carregar os arquivo(s) como se compilados e referenciados - - - - Toggle timing on/off - Liga/desliga medição de tempo - - - - Display help - Exibir ajuda - - - - Exit - Sair - - - - F# Interactive command line options: - Opções de linha de comando F# Interativo: - - - - See '{0}' for options - Consulte '{0}' para obter opções - - - - Loading - Carregando - - - - \n- Interrupt\n - \n- Interrupção\n - - - - \n- Exit...\n - \n- Sair...\n - - - - - Aborting main thread... - – Anulando o thread principal... - - - - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - Falha ao instalar o manipulador ctrl-c - As manipulações Ctrl-C não estarão disponíveis. O erro foi:\n\t{0} - - - - --> Referenced '{0}' - --> Referenciado '{0}' - - - - --> Referenced '{0}' (file may be locked by F# Interactive process) - --> Referenciado '{0}' (o arquivo pode ter sido bloqueado pelo processo F# Interativo) - - - - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - --> '{0}' referenciado (um assembly com um carimbo de data/hora diferente já foi referenciado deste local, redefina o fsi para carregar o assembly atualizado) - - - - --> Added '{0}' to library include path - --> '{0}' foi adicionado à biblioteca de caminho de inclusão - - - - --> Timing now on - --> Timing ligado agora - - - - --> Timing now off - --> Timing desligado agora - - - - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - Inesperada ThreadAbortException (Ctrl-C) durante o manuseio do evento: Tentando reiniciar... - - - - Failed to resolve assembly '{0}' - Falha ao resolver assembly '{0}' - - - - Binding session to '{0}'... - Associando sessão a '{0}'... - - - - Microsoft (R) F# Interactive version {0} - Microsoft (R) F# Interativo versão {0} - - - - F# Interactive for F# {0} - F# Interativo para F# {0} - - - - Prevents references from being locked by the F# Interactive process - Impede que as referências sejam bloqueadas pelo processo de F# Interativo - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.ru.xlf b/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.ru.xlf deleted file mode 100644 index de3a08eed1..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.ru.xlf +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - Stopped due to error\n - Остановлено из-за ошибки\n - - - - Usage: {0} <options> [script.fsx [<arguments>]] - Использование: {0} <параметры> [script.fsx [<аргументы>]] - - - - - INPUT FILES - - - ВХОДНЫЕ ФАЙЛЫ - - - - - - CODE GENERATION - - - ФОРМИРОВАНИЕ КОДА - - - - - - ERRORS AND WARNINGS - - - ОШИБКИ И ПРЕДУПРЕЖДЕНИЯ - - - - - - LANGUAGE - - - ЯЗЫК - - - - - - MISCELLANEOUS - - - ПРОЧЕЕ - - - - - - ADVANCED - - - ДОПОЛНИТЕЛЬНО - - - - - Exception raised when starting remoting server.\n{0} - При запуске удаленного сервера возникло исключение.\n{0} - - - - Use the given file on startup as initial input - Использование данного файла при запуске в качестве начальных входных данных - - - - #load the given file on startup - #load: загружать данный файл при запуске - - - - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - Обрабатывать остальные аргументы как аргументы командной строки с использованием fsi.CommandLineArgs - - - - Display this usage message (Short form: -?) - Вывод данного сообщения об использовании (краткая форма: -?) - - - - Exit fsi after loading the files or running the .fsx script given on the command line - Выход из FSI после загрузки файлов или выполнение скрипта .fsx, указанного в командной строке - - - - Execute interactions on a Windows Forms event loop (on by default) - Выполнение взаимодействий при зацикливании события Windows Forms (включено по умолчанию) - - - - Suppress fsi writing to stdout - Запретить fsi запись в stdout - - - - Support TAB completion in console (on by default) - Поддержка заполнения нажатием клавиши TAB в консоли (включено по умолчанию) - - - - Emit debug information in quotations - Вывод отладочной информации в кавычках - - - - For help type #help;; - Для получения справки введите #help;; - - - - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - Возникла проблема при запуске процесса F# Interactive. Это может быть вызвано известной проблемой с поддержкой консоли фонового процесса для приложений с поддержкой Юникода в некоторых системах Windows. Попробуйте выбрать "Сервис" -> "Параметры" -> "F# Interactive для Visual Studio" и ввести "--fsi-server-no-unicode". - - - - '{0}' is not a valid assembly name - {0} не является допустимым именем сборки - - - - Directory '{0}' doesn't exist - Каталог "{0}" не существует - - - - Invalid directive '#{0} {1}' - Недопустимая директива "#{0} {1}" - - - - Warning: line too long, ignoring some characters\n - Предупреждение: слишком длинная строка, некоторые знаки игнорируются\n - - - - Real: {0}, CPU: {1}, GC {2} - Real: {0}, ЦП: {1}, GC {2} - - - - gen - gen - - - - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - \n\nВозникло исключение при автоматическом форматировании.\nОтправьте отчет об этой неполадке для ее устранения.\nТрассировка: {0}\n - - - - F# Interactive directives: - Директивы F# Interactive: - - - - Reference (dynamically load) the given DLL - Ссылка на (динамическая загрузка) данную библиотеку DLL - - - - Add the given search path for referenced DLLs - Добавление данного пути поиска для указанных библиотек DLL - - - - Load the given file(s) as if compiled and referenced - Загрузка данных файлов как скомпилированных и указанных ссылками - - - - Toggle timing on/off - Включение и отключение таймера - - - - Display help - Отображать справку - - - - Exit - Выход - - - - F# Interactive command line options: - Параметры командной строки F# Interactive: - - - - See '{0}' for options - Параметры см. в "{0}" - - - - Loading - Загрузка - - - - \n- Interrupt\n - \n- Interrupt\n - - - - \n- Exit...\n - \n- Выход...\n - - - - - Aborting main thread... - — Отменяется главный поток… - - - - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - Не удалось установить обработчик ctrl-c - обработка Ctrl-C будет недоступна. Ошибка:\n\t{0} - - - - --> Referenced '{0}' - --> Задана ссылка на "{0}" - - - - --> Referenced '{0}' (file may be locked by F# Interactive process) - --> Задана ссылка на "{0}" (возможно, файл заблокирован процессом F# Interactive) - - - - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - --> "{0}" с заданной ссылкой (из этого расположения уже задана ссылка на сборку с другой меткой времени, выполните сброс fsi, чтобы загрузить обновленную сборку) - - - - --> Added '{0}' to library include path - --> Выполнено добавление "{0}" по пути включения в библиотеку - - - - --> Timing now on - --> Таймер включен - - - - --> Timing now off - --> Таймер отключен - - - - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - Непредвиденное ThreadAbortException (Ctrl-C) в ходе обработки события: Попытка перезапуска... - - - - Failed to resolve assembly '{0}' - Не удалось выполнить разрешение сборки ''{0}'' - - - - Binding session to '{0}'... - Привязка сеанса к "{0}"... - - - - Microsoft (R) F# Interactive version {0} - Microsoft (R) F# Interactive, версия {0} - - - - F# Interactive for F# {0} - F# Interactive для F# {0} - - - - Prevents references from being locked by the F# Interactive process - Предотвращает блокировку ссылок процессом F# Interactive. - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.tr.xlf b/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.tr.xlf deleted file mode 100644 index 35bd3478f9..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.tr.xlf +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - Stopped due to error\n - Hata nedeniyle durduruldu\n - - - - Usage: {0} <options> [script.fsx [<arguments>]] - Kullanım: {0} <seçenekler> [script.fsx [<bağımsız değişkenler>]] - - - - - INPUT FILES - - - GİRİŞ DOSYALARI - - - - - - CODE GENERATION - - - KOD ÜRETİMİ - - - - - - ERRORS AND WARNINGS - - - HATALAR VE UYARILAR - - - - - - LANGUAGE - - - DİL - - - - - - MISCELLANEOUS - - - ÇEŞİTLİ - - - - - - ADVANCED - - - GELİŞMİŞ - - - - - Exception raised when starting remoting server.\n{0} - Uzaktan iletişim sunucusu başlatılırken özel durum tetiklendi.\n{0} - - - - Use the given file on startup as initial input - Verilen dosyayı başlangıçta ilk giriş olarak kullan - - - - #load the given file on startup - #load verilen dosyayı başlangıçta - - - - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - Kalan bağımsız değişkenlere fsi.CommandLineArgs kullanılarak erişilen komut satırı bağımsız değişkenleri gibi davran - - - - Display this usage message (Short form: -?) - Bu kullanım iletisini görüntüle (Kısa biçimi: -?) - - - - Exit fsi after loading the files or running the .fsx script given on the command line - Dosyaları yükledikten veya komut satırında verilen .fsx betiğini çalıştırdıktan sonra fsi'den çık - - - - Execute interactions on a Windows Forms event loop (on by default) - Etkileşimleri Windows Forms olay döngüsünde yürüt (varsayılan seçenek olarak açık) - - - - Suppress fsi writing to stdout - stdout yazdırırken fsi'yi gizle - - - - Support TAB completion in console (on by default) - Konsolda SEKME ile tamamlamayı destekle (varsayılan seçenek olarak açık) - - - - Emit debug information in quotations - Tırnak içindeki hata ayıklama bilgilerini yay - - - - For help type #help;; - Yardım için #help yazın;; - - - - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - F# Etkileşimli işlemi başlatılırken bir sorun oluştu. Bu durum, bazı Windows sistemlerindeki Unicode kullanan uygulamalara yönelik arka plan işlemi konsol desteğinde bilinen bir soruna bağlı olabilir. Visual Studio için Araçlar->Seçenekler->F# Etkileşimli'yi seçmeyi deneyin ve '--fsi-server-no-unicode' girin. - - - - '{0}' is not a valid assembly name - '{0}' geçerli bir bütünleştirilmiş kod adı değil - - - - Directory '{0}' doesn't exist - '{0}' dizini yok - - - - Invalid directive '#{0} {1}' - Geçersiz yönerge '#{0} {1}' - - - - Warning: line too long, ignoring some characters\n - Uyarı: satır çok uzun, bazı karakterler yok sayılıyor\n - - - - Real: {0}, CPU: {1}, GC {2} - Gerçek: {0}, CPU: {1}, GC {2} - - - - gen - olş - - - - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - \n\nDüzgün yazdırma sırasında özel durum tetiklendi.\nDüzeltilebilmesi için lütfen bunu bildirin.\nİz: {0}\n - - - - F# Interactive directives: - F# Etkileşimli yönergeleri: - - - - Reference (dynamically load) the given DLL - Verilen DLL'ye başvur (dinamik olarak yükle) - - - - Add the given search path for referenced DLLs - Başvurulan DLL'ler için verilen arama yolunu ekle - - - - Load the given file(s) as if compiled and referenced - Verilen dosyaları derlenmiş ve başvurulmuş gibi yükle - - - - Toggle timing on/off - Zamanlamayı aç/kapat - - - - Display help - Yardımı göster - - - - Exit - Çıkış - - - - F# Interactive command line options: - F# Etkileşimli komut satırı seçenekleri: - - - - See '{0}' for options - Seçenekler için bkz. '{0}' - - - - Loading - Yükleniyor - - - - \n- Interrupt\n - \n- Kesme\n - - - - \n- Exit...\n - \n- Çıkış...\n - - - - - Aborting main thread... - - Ana iş parçacığı iptal ediliyor... - - - - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - ctrl-c işleyicisi yüklenemedi - Ctrl-C işlemi kullanılamayacak. Hata:\n\t{0} - - - - --> Referenced '{0}' - --> '{0}' öğesine başvuruldu - - - - --> Referenced '{0}' (file may be locked by F# Interactive process) - --> '{0}' öğesine başvuruldu (dosya F# Etkileşimli işlemi tarafından kilitlenmiş olabilir) - - - - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - --> Başvurulan '{0}' (farklı bir zaman damgası olan bir bütünleştirilmiş koda bu konumdan zaten başvuruldu; güncelleştirilen bütünleştirilmiş kodu yüklemek için fsi'yi sıfırlayın) - - - - --> Added '{0}' to library include path - --> Kitaplık ekleme yoluna '{0}' eklendi - - - - --> Timing now on - --> Zamanlama şimdi açık - - - - --> Timing now off - --> Zamanlama şimdi kapalı - - - - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - Olay işlenirken beklenmeyen ThreadAbortException (Ctrl-C): Yeniden başlatma deneniyor... - - - - Failed to resolve assembly '{0}' - '{0}' bütünleştirilmiş kodu çözümlenemedi - - - - Binding session to '{0}'... - Oturum '{0}' öğesine bağlanıyor... - - - - Microsoft (R) F# Interactive version {0} - Microsoft (R) F# Etkileşimli sürüm {0} - - - - F# Interactive for F# {0} - F# {0} için F# Etkileşimli - - - - Prevents references from being locked by the F# Interactive process - Başvuruların F# Etkileşimli işlemi tarafından kilitlenmesini engeller - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.zh-Hans.xlf b/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.zh-Hans.xlf deleted file mode 100644 index 6089715c68..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.zh-Hans.xlf +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - Stopped due to error\n - 已因出错而停止\n - - - - Usage: {0} <options> [script.fsx [<arguments>]] - 用法: {0} <选项> [script.fsx [<参数>]] - - - - - INPUT FILES - - - 输入文件 - - - - - - CODE GENERATION - - - 代码生成 - - - - - - ERRORS AND WARNINGS - - - 错误和警告 - - - - - - LANGUAGE - - - 语言 - - - - - - MISCELLANEOUS - - - 杂项 - - - - - - ADVANCED - - - 高级 - - - - - Exception raised when starting remoting server.\n{0} - 启动远程处理服务器时发生异常。\n{0} - - - - Use the given file on startup as initial input - 在启动时使用给定文件作为初始输入 - - - - #load the given file on startup - #load 在启动时给定的文件 - - - - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - 将剩余参数视为可使用 fsi.CommandLineArgs 访问的命令行参数 - - - - Display this usage message (Short form: -?) - 显示此用法消息(缩写为: -?) - - - - Exit fsi after loading the files or running the .fsx script given on the command line - 在加载文件或在命令行上运行给定的 .fsx 脚本之后退出 fsi - - - - Execute interactions on a Windows Forms event loop (on by default) - 在 Windows 窗体事件循环中执行交互(默认情况下启用) - - - - Suppress fsi writing to stdout - 禁止 fsi 写入到 stdout - - - - Support TAB completion in console (on by default) - 支持控制台中的 Tab 完成操作(默认情况下启用) - - - - Emit debug information in quotations - 发出用引号引起来的调试信息 - - - - For help type #help;; - 若要获得帮助,请键入 #help;; - - - - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - 启动 F# 交互窗口进程时发生问题。此情况可能是由一个已知问题导致的,即某些 Windows 系统上的后台进程控制台不支持启用了 Unicode 的应用程序。请尝试选择“工具”->“选项”->“适用于 Visual Studio 的 F# 交互窗口”,然后输入“--fsi-server-no-unicode”。 - - - - '{0}' is not a valid assembly name - “{0}”不是有效的程序集名称 - - - - Directory '{0}' doesn't exist - 目录“{0}”不存在 - - - - Invalid directive '#{0} {1}' - 无效的指令“#{0} {1}” - - - - Warning: line too long, ignoring some characters\n - 警告: 由于行太长,将忽略某些字符\n - - - - Real: {0}, CPU: {1}, GC {2} - Real: {0},CPU: {1},GC {2} - - - - gen - gen - - - - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - \n\n在整齐打印期间发生异常。\n请报告此异常,以便能够将其修复。\n跟踪: {0}\n - - - - F# Interactive directives: - F# 交互窗口指令: - - - - Reference (dynamically load) the given DLL - 引用(动态加载)给定的 DLL - - - - Add the given search path for referenced DLLs - 为被引用的 DLL 添加给定搜索路径 - - - - Load the given file(s) as if compiled and referenced - 像已编译和被引用的文件一样加载给定的文件 - - - - Toggle timing on/off - 启用/停止计时 - - - - Display help - 显示帮助 - - - - Exit - 退出 - - - - F# Interactive command line options: - F# 交互窗口命令行选项: - - - - See '{0}' for options - 请参阅“{0}”以了解各个选项 - - - - Loading - 正在加载 - - - - \n- Interrupt\n - \n- 中断\n - - - - \n- Exit...\n - \n- 退出...\n - - - - - Aborting main thread... - - 正在中止主线程... - - - - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - 未能安装 ctrl-c 处理程序,Ctrl-C 处理将不可用。错误为:\n\t{0} - - - - --> Referenced '{0}' - --> 已引用“{0}” - - - - --> Referenced '{0}' (file may be locked by F# Interactive process) - --> 已引用“{0}”(文件可能由 F# 交互窗口进程锁定) - - - - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - ->引用“{0}”(具有不同时间戳的程序集已经从该位置引用并重置 fsi 以加载更新的程序集) - - - - --> Added '{0}' to library include path - --> 已将“{0}”添加到库包含路径 - - - - --> Timing now on - --> 现在已启用计时 - - - - --> Timing now off - --> 现在已关闭计时 - - - - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - 在事件处理过程中出现意外 ThreadAbortException (Ctrl-C): 正在尝试重新启动... - - - - Failed to resolve assembly '{0}' - 未能解析程序集“{0}” - - - - Binding session to '{0}'... - 正在将会话绑定到“{0}”... - - - - Microsoft (R) F# Interactive version {0} - Microsoft(R) F# 交互窗口版本 {0} - - - - F# Interactive for F# {0} - 适用于 F# {0} 的 F# 交互窗口 - - - - Prevents references from being locked by the F# Interactive process - 防止引用被 F# 交互窗口进程锁定 - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.zh-Hant.xlf b/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.zh-Hant.xlf deleted file mode 100644 index 1752c12240..0000000000 --- a/src/fcs-fable/src/fsharp/fsi/xlf/FSIstrings.txt.zh-Hant.xlf +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - Stopped due to error\n - 已因錯誤而停止\n - - - - Usage: {0} <options> [script.fsx [<arguments>]] - 使用方式: {0} <選項> [script.fsx [<引數>]] - - - - - INPUT FILES - - - 輸入檔 - - - - - - CODE GENERATION - - - 程式碼產生 - - - - - - ERRORS AND WARNINGS - - - 錯誤和警告 - - - - - - LANGUAGE - - - 語言 - - - - - - MISCELLANEOUS - - - 其他 - - - - - - ADVANCED - - - 進階 - - - - - Exception raised when starting remoting server.\n{0} - 啟動遠端處理伺服器時發生例外狀況。\n{0} - - - - Use the given file on startup as initial input - 啟動時使用所指定的檔案做為初始輸入 - - - - #load the given file on startup - #load 啟動時指定的檔案 - - - - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - 將其餘引數視為命令列引數,使用 fsi.CommandLineArgs 存取 - - - - Display this usage message (Short form: -?) - 顯示此訊息 (簡短形式: -?) - - - - Exit fsi after loading the files or running the .fsx script given on the command line - 載入檔案或執行命令列上指定的 .fsx 指令碼後結束 fsi - - - - Execute interactions on a Windows Forms event loop (on by default) - 在 Windows Form 事件迴圈上執行互動 (預設為開啟) - - - - Suppress fsi writing to stdout - 禁止 fsi 寫入 stdout - - - - Support TAB completion in console (on by default) - 支援主控台中的 TAB 鍵自動完成 (預設為開啟) - - - - Emit debug information in quotations - 發出在引號內的偵錯資訊 - - - - For help type #help;; - 如需說明,請輸入 #help;; - - - - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - 啟動 F# 互動處理序時發生問題。這可能是因為背景處理序主控台對於支援某些 Windows 系統上具備 Unicode 支援功能之應用程式的已知問題所造成。請嘗試選取 [工具]5D; -> [選項]5D; -> [F# Interactive for Visual Studio]5D;,然後輸入 '--fsi-server-no-unicode'。 - - - - '{0}' is not a valid assembly name - '{0}' 不是有效的組件名稱 - - - - Directory '{0}' doesn't exist - 目錄 '{0}' 不存在 - - - - Invalid directive '#{0} {1}' - 無效的指示詞 '#{0} {1}' - - - - Warning: line too long, ignoring some characters\n - 警告: 行太長,將忽略某些字元\n - - - - Real: {0}, CPU: {1}, GC {2} - 實際: {0},CPU: {1},GC {2} - - - - gen - gen - - - - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - \n\n美化顯示期間發生例外狀況。\n請回報此問題以便修正。\n追蹤: {0}\n - - - - F# Interactive directives: - F# 互動指示詞: - - - - Reference (dynamically load) the given DLL - 參考 (以動態方式載入) 所指定的 DLL - - - - Add the given search path for referenced DLLs - 加入所參考 DLL 的指定搜尋路徑 - - - - Load the given file(s) as if compiled and referenced - 載入指定的檔案,視為已編譯及已參考 - - - - Toggle timing on/off - 切換計時開/關 - - - - Display help - 顯示說明 - - - - Exit - 結束 - - - - F# Interactive command line options: - F# 互動命令列選項: - - - - See '{0}' for options - 相關選項請參閱 '{0}' - - - - Loading - 正在載入 - - - - \n- Interrupt\n - \n- 中斷\n - - - - \n- Exit...\n - \n- 結束...\n - - - - - Aborting main thread... - - 正在中止主要執行緒... - - - - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - 無法安裝 ctrl-c 處理常式,Ctrl-C 處理將無法使用。錯誤為:\n\t{0} - - - - --> Referenced '{0}' - --> 參考的 '{0}' - - - - --> Referenced '{0}' (file may be locked by F# Interactive process) - --> 參考的 '{0}' (檔案可能已被 F# 互動處理序鎖定) - - - - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - --> 已參考 '{0}' (已經從這個位置參考有不同時間戳記的組件,請重設 fsi 以載入更新的組件) - - - - --> Added '{0}' to library include path - --> 已將 '{0}' 加入程式庫 Include 路徑 - - - - --> Timing now on - --> 計時現已開啟 - - - - --> Timing now off - --> 計時現已關閉 - - - - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - 事件處理時發生未預期的 ThreadAbortException (Ctrl-C): 正嘗試重新啟動... - - - - Failed to resolve assembly '{0}' - 無法解析組件 '{0}' - - - - Binding session to '{0}'... - 正在將工作階段繫結到 '{0}'... - - - - Microsoft (R) F# Interactive version {0} - Microsoft (R) F# 互動版本 {0} - - - - F# Interactive for F# {0} - 適用於 F# {0} 的 F# 互動 - - - - Prevents references from being locked by the F# Interactive process - 避免參考遭 F# 互動處理序封鎖 - - - - - \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/fsiAnyCpu/fsiAnyCpu.fsproj b/src/fcs-fable/src/fsharp/fsiAnyCpu/fsiAnyCpu.fsproj deleted file mode 100644 index b310a33b43..0000000000 --- a/src/fcs-fable/src/fsharp/fsiAnyCpu/fsiAnyCpu.fsproj +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - Exe - net46 - AnyCPU - .exe - $(NoWarn);45;55;62;75;1204 - true - $(OtherFlags) --warnon:1182 --maxerrors:20 --extraoptimizationloops:1 - ..\fsi\fsi.res - true - true - - - - $(DefineConstants);FSI_SHADOW_COPY_REFERENCES;FSI_SERVER - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/fcs-fable/src/fsharp/fsiattrs.fs b/src/fcs-fable/src/fsharp/fsiattrs.fs old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/fsharp/fsiaux.fs b/src/fcs-fable/src/fsharp/fsiaux.fs old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/fsharp/fsiaux.fsi b/src/fcs-fable/src/fsharp/fsiaux.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/fsharp/import.fs b/src/fcs-fable/src/fsharp/import.fs old mode 100755 new mode 100644 index 2bbb90d638..fc6a8f0fa8 --- a/src/fcs-fable/src/fsharp/import.fs +++ b/src/fcs-fable/src/fsharp/import.fs @@ -3,19 +3,23 @@ /// Functions to import .NET binary metadata as TAST objects module internal FSharp.Compiler.Import -open System.Reflection open System.Collections.Concurrent open System.Collections.Generic +open FSharp.Compiler open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler +open FSharp.Compiler.CompilerGlobalState +open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Lib open FSharp.Compiler.Range -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Ast -open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.XmlDoc + #if !NO_EXTENSIONTYPING open FSharp.Compiler.ExtensionTyping #endif @@ -37,8 +41,6 @@ type AssemblyLoader = abstract RecordGeneratedTypeRoot : ProviderGeneratedType -> unit #endif - - //------------------------------------------------------------------------- // Import an IL types as F# types. //------------------------------------------------------------------------- @@ -59,32 +61,38 @@ type ImportMap(g: TcGlobals, assemblyLoader: AssemblyLoader) = member this.ILTypeRefToTyconRefCache = typeRefToTyconRefCache let CanImportILScopeRef (env: ImportMap) m scoref = - match scoref with - | ILScopeRef.Local -> true - | ILScopeRef.Module _ -> true - | ILScopeRef.Assembly assemblyRef -> + let isResolved assemblyRef = // Explanation: This represents an unchecked invariant in the hosted compiler: that any operations // which import types (and resolve assemblies from the tcImports tables) happen on the compilation thread. let ctok = AssumeCompilationThreadWithoutEvidence() - + match env.assemblyLoader.FindCcuFromAssemblyRef (ctok, m, assemblyRef) with - | UnresolvedCcu _ -> false + | UnresolvedCcu _ -> false | ResolvedCcu _ -> true + match scoref with + | ILScopeRef.Local + | ILScopeRef.Module _ -> true + | ILScopeRef.Assembly assemblyRef -> isResolved assemblyRef + | ILScopeRef.PrimaryAssembly -> isResolved env.g.ilg.primaryAssemblyRef /// Import a reference to a type definition, given the AbstractIL data for the type reference let ImportTypeRefData (env: ImportMap) m (scoref, path, typeName) = - - // Explanation: This represents an unchecked invariant in the hosted compiler: that any operations - // which import types (and resolve assemblies from the tcImports tables) happen on the compilation thread. - let ctok = AssumeCompilationThreadWithoutEvidence() - let ccu = + let findCcu assemblyRef = + // Explanation: This represents an unchecked invariant in the hosted compiler: that any operations + // which import types (and resolve assemblies from the tcImports tables) happen on the compilation thread. + let ctok = AssumeCompilationThreadWithoutEvidence() + + env.assemblyLoader.FindCcuFromAssemblyRef (ctok, m, assemblyRef) + + let ccu = match scoref with | ILScopeRef.Local -> error(InternalError("ImportILTypeRef: unexpected local scope", m)) | ILScopeRef.Module _ -> error(InternalError("ImportILTypeRef: reference found to a type in an auxiliary module", m)) - | ILScopeRef.Assembly assemblyRef -> env.assemblyLoader.FindCcuFromAssemblyRef (ctok, m, assemblyRef) // NOTE: only assemblyLoader callsite + | ILScopeRef.Assembly assemblyRef -> findCcu assemblyRef + | ILScopeRef.PrimaryAssembly -> findCcu env.g.ilg.primaryAssemblyRef // Do a dereference of a fake tcref for the type just to check it exists in the target assembly and to find // the corresponding Tycon. @@ -134,7 +142,7 @@ let ImportILTypeRefUncached (env: ImportMap) m (tref: ILTypeRef) = /// Import a reference to a type definition, given an AbstractIL ILTypeRef, with caching let ImportILTypeRef (env: ImportMap) m (tref: ILTypeRef) = - match env.ILTypeRefToTyconRefCache.TryGetValue(tref) with + match env.ILTypeRefToTyconRefCache.TryGetValue tref with | true, tcref -> tcref | _ -> let tcref = ImportILTypeRefUncached env m tref @@ -180,6 +188,7 @@ let rec ImportILType (env: ImportMap) m tinst ty = with _ -> error(Error(FSComp.SR.impNotEnoughTypeParamsInScopeWhileImporting(), m)) +/// Determines if an IL type can be imported as an F# type let rec CanImportILType (env: ImportMap) m ty = match ty with | ILType.Void -> true @@ -391,7 +400,6 @@ let ImportProvidedMethodBaseAsILMethodRef (env: ImportMap) (m: range) (mbase: Ta // assembly on startup. //-------------------------------------------------------------------------- - /// Import a set of Abstract IL generic parameter specifications as a list of new /// F# generic parameters. /// @@ -402,19 +410,18 @@ let ImportILGenericParameters amap m scoref tinst (gps: ILGenericParameterDefs) | [] -> [] | _ -> let amap = amap() - let tps = gps |> List.map (fun gp -> NewRigidTypar gp.Name m) + let tps = gps |> List.map (fun gp -> Construct.NewRigidTypar gp.Name m) let tptys = tps |> List.map mkTyparTy let importInst = tinst@tptys (tps, gps) ||> List.iter2 (fun tp gp -> let constraints = gp.Constraints |> List.map (fun ilty -> TyparConstraint.CoercesTo(ImportILType amap m importInst (rescopeILType scoref ilty), m) ) - let constraints = if gp.HasReferenceTypeConstraint then (TyparConstraint.IsReferenceType(m)::constraints) else constraints - let constraints = if gp.HasNotNullableValueTypeConstraint then (TyparConstraint.IsNonNullableStruct(m)::constraints) else constraints - let constraints = if gp.HasDefaultConstructorConstraint then (TyparConstraint.RequiresDefaultConstructor(m)::constraints) else constraints + let constraints = if gp.HasReferenceTypeConstraint then (TyparConstraint.IsReferenceType(m) :: constraints) else constraints + let constraints = if gp.HasNotNullableValueTypeConstraint then (TyparConstraint.IsNonNullableStruct(m) :: constraints) else constraints + let constraints = if gp.HasDefaultConstructorConstraint then (TyparConstraint.RequiresDefaultConstructor(m) :: constraints) else constraints tp.SetConstraints constraints) tps - /// Given a list of items each keyed by an ordered list of keys, apply 'nodef' to the each group /// with the same leading key. Apply 'tipf' to the elements where the keylist is empty, and return /// the overall results. Used to bucket types, so System.Char and System.Collections.Generic.List @@ -436,14 +443,13 @@ let multisetDiscriminateAndMap nodef tipf (items: ('Key list * 'Value) list) = | [] -> () | key :: rest -> buckets.[key] <- - match buckets.TryGetValue(key) with + match buckets.TryGetValue key with | true, b -> (rest, v) :: b | _ -> (rest, v) :: [] [ for (KeyValue(key, items)) in buckets -> nodef key items ] tips @ nodes - /// Import an IL type definition as a new F# TAST Entity node. let rec ImportILTypeDef amap m scoref (cpath: CompilationPath) enc nm (tdef: ILTypeDef) = @@ -452,7 +458,7 @@ let rec ImportILTypeDef amap m scoref (cpath: CompilationPath) enc nm (tdef: ILT let cpath = cpath.NestedCompPath nm ModuleOrType ImportILTypeDefs amap m scoref cpath (enc@[tdef]) tdef.NestedTypes // Add the type itself. - NewILTycon + Construct.NewILTycon (Some cpath) (nm, m) // The read of the type parameters may fail to resolve types. We pick up a new range from the point where that read is forced @@ -478,20 +484,20 @@ and ImportILTypeDefList amap m (cpath: CompilationPath) enc items = |> multisetDiscriminateAndMap (fun n tgs -> let modty = lazy (ImportILTypeDefList amap m (cpath.NestedCompPath n Namespace) enc tgs) - NewModuleOrNamespace (Some cpath) taccessPublic (mkSynId m n) XmlDoc.Empty [] (MaybeLazy.Lazy modty)) + Construct.NewModuleOrNamespace (Some cpath) taccessPublic (mkSynId m n) XmlDoc.Empty [] (MaybeLazy.Lazy modty)) (fun (n, info: Lazy<_>) -> - let (scoref2, _, lazyTypeDef: ILPreTypeDef) = info.Force() + let (scoref2, lazyTypeDef: ILPreTypeDef) = info.Force() ImportILTypeDef amap m scoref2 cpath enc n (lazyTypeDef.GetTypeDef())) let kind = match enc with [] -> Namespace | _ -> ModuleOrType - NewModuleOrNamespaceType kind entities [] + Construct.NewModuleOrNamespaceType kind entities [] /// Import a table of IL types as a ModuleOrNamespaceType. /// and ImportILTypeDefs amap m scoref cpath enc (tdefs: ILTypeDefs) = // We be very careful not to force a read of the type defs here tdefs.AsArrayOfPreTypeDefs - |> Array.map (fun pre -> (pre.Namespace, (pre.Name, notlazy(scoref, pre.MetadataIndex, pre)))) + |> Array.map (fun pre -> (pre.Namespace, (pre.Name, notlazy(scoref, pre)))) |> Array.toList |> ImportILTypeDefList amap m cpath enc @@ -521,7 +527,7 @@ let ImportILAssemblyExportedType amap m auxModLoader (scoref: ILScopeRef) (expor | None -> error(Error(FSComp.SR.impReferenceToDllRequiredByAssembly(exportedType.ScopeRef.QualifiedName, scoref.QualifiedName, exportedType.Name), m)) | Some preTypeDef -> - scoref, -1, preTypeDef) + scoref, preTypeDef) [ ImportILTypeDefList amap m (CompPath(scoref, [])) [] [(ns, (n, info))] ] @@ -557,36 +563,37 @@ let ImportILAssemblyTypeForwarders (amap, m, exportedTypes: ILExportedTypesAndFo yield! nested net.Nested (enc @ [ net.Name ]) ] yield! nested exportedType.Nested (ns@[n]) ] |> Map.ofList - /// Import an IL assembly as a new TAST CCU -let ImportILAssembly(amap:(unit -> ImportMap), m, auxModuleLoader, ilScopeRef, sourceDir, filename, ilModule: ILModuleDef, invalidateCcu: IEvent) = - invalidateCcu |> ignore - let aref = - match ilScopeRef with - | ILScopeRef.Assembly aref -> aref - | _ -> error(InternalError("ImportILAssembly: cannot reference .NET netmodules directly, reference the containing assembly instead", m)) - let nm = aref.Name - let mty = ImportILAssemblyTypeDefs(amap, m, auxModuleLoader, aref, ilModule) - let ccuData : CcuData = - { IsFSharp=false - UsesFSharp20PlusQuotations=false +let ImportILAssembly(amap: (unit -> ImportMap), m, auxModuleLoader, ilScopeRef, sourceDir, filename, ilModule: ILModuleDef, invalidateCcu: IEvent) = + invalidateCcu |> ignore + let aref = + match ilScopeRef with + | ILScopeRef.Assembly aref -> aref + | _ -> error(InternalError("ImportILAssembly: cannot reference .NET netmodules directly, reference the containing assembly instead", m)) + let nm = aref.Name + let mty = ImportILAssemblyTypeDefs(amap, m, auxModuleLoader, aref, ilModule) + let forwarders = + match ilModule.Manifest with + | None -> Map.empty + | Some manifest -> ImportILAssemblyTypeForwarders(amap, m, manifest.ExportedTypes) + + let ccuData: CcuData = + { IsFSharp=false + UsesFSharp20PlusQuotations=false #if !NO_EXTENSIONTYPING - InvalidateEvent=invalidateCcu - IsProviderGenerated = false - ImportProvidedType = (fun ty -> ImportProvidedType (amap()) m ty) + InvalidateEvent=invalidateCcu + IsProviderGenerated = false + ImportProvidedType = (fun ty -> ImportProvidedType (amap()) m ty) #endif - QualifiedName= Some ilScopeRef.QualifiedName - Contents = NewCcuContents ilScopeRef m nm mty - ILScopeRef = ilScopeRef - Stamp = newStamp() - SourceCodeDirectory = sourceDir // note: not an accurate value, but IL assemblies don't give us this information in any attributes. - FileName = filename - MemberSignatureEquality= (fun ty1 ty2 -> Tastops.typeEquivAux EraseAll (amap()).g ty1 ty2) - TryGetILModuleDef = (fun () -> Some ilModule) - TypeForwarders = - (match ilModule.Manifest with - | None -> Map.empty - | Some manifest -> ImportILAssemblyTypeForwarders(amap, m, manifest.ExportedTypes)) } + QualifiedName= Some ilScopeRef.QualifiedName + Contents = Construct.NewCcuContents ilScopeRef m nm mty + ILScopeRef = ilScopeRef + Stamp = newStamp() + SourceCodeDirectory = sourceDir // note: not an accurate value, but IL assemblies don't give us this information in any attributes. + FileName = filename + MemberSignatureEquality= (fun ty1 ty2 -> typeEquivAux EraseAll (amap()).g ty1 ty2) + TryGetILModuleDef = (fun () -> Some ilModule) + TypeForwarders = forwarders } - CcuThunk.Create(nm, ccuData) + CcuThunk.Create(nm, ccuData) diff --git a/src/fcs-fable/src/fsharp/import.fsi b/src/fcs-fable/src/fsharp/import.fsi old mode 100755 new mode 100644 index 1070bd302a..cc75a8f896 --- a/src/fcs-fable/src/fsharp/import.fsi +++ b/src/fcs-fable/src/fsharp/import.fsi @@ -3,17 +3,16 @@ /// Functions to import .NET binary metadata as TAST objects module internal FSharp.Compiler.Import -open FSharp.Compiler.Tast -open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Range open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.Range +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypedTree + #if !NO_EXTENSIONTYPING open FSharp.Compiler.ExtensionTyping #endif - - /// Represents an interface to some of the functionality of TcImports, for loading assemblies /// and accessing information about generated provided assemblies. type AssemblyLoader = @@ -31,7 +30,6 @@ type AssemblyLoader = abstract RecordGeneratedTypeRoot : ProviderGeneratedType -> unit #endif - /// Represents a context used for converting AbstractIL .NET and provided types to F# internal compiler data structures. /// Also cache the conversion of AbstractIL ILTypeRef nodes, based on hashes of these. /// @@ -61,7 +59,6 @@ val internal ImportILType : ImportMap -> range -> TType list -> ILType -> TType val internal CanImportILType : ImportMap -> range -> ILType -> bool #if !NO_EXTENSIONTYPING - /// Import a provided type as an F# type. val internal ImportProvidedType : ImportMap -> range -> (* TType list -> *) Tainted -> TType diff --git a/src/fcs-fable/src/fsharp/infos.fs b/src/fcs-fable/src/fsharp/infos.fs index ae9e1ff49a..e511470475 100755 --- a/src/fcs-fable/src/fsharp/infos.fs +++ b/src/fcs-fable/src/fsharp/infos.fs @@ -2,19 +2,22 @@ module internal FSharp.Compiler.Infos +open System +open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler -open FSharp.Compiler.Range -open FSharp.Compiler.Ast open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.Tastops.DebugPrint -open FSharp.Compiler.TcGlobals open FSharp.Compiler.Lib -open Microsoft.FSharp.Core.Printf +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.TypedTreeOps.DebugPrint +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.XmlDoc #if !NO_EXTENSIONTYPING open FSharp.Compiler.ExtensionTyping @@ -76,9 +79,9 @@ let GetSuperTypeOfType g amap m ty = Some g.obj_ty elif isFSharpStructOrEnumTy g ty then if isFSharpEnumTy g ty then - Some(g.system_Enum_ty) + Some g.system_Enum_ty else - Some (g.system_Value_ty) + Some g.system_Value_ty elif isAnonRecdTy g ty then Some g.obj_ty elif isRecdTy g ty || isUnionTy g ty then @@ -240,7 +243,7 @@ let SearchEntireHierarchyOfType f g amap m ty = FoldHierarchyOfTypeAux true AllowMultiIntfInstantiations.Yes SkipUnrefInterfaces.Yes (fun ty acc -> match acc with - | None -> if f ty then Some(ty) else None + | None -> if f ty then Some ty else None | Some _ -> acc) g amap m ty None @@ -415,7 +418,7 @@ let GetCompiledReturnTyOfProvidedMethodInfo amap m (mi: Tainted - let parentToMemberInst, _ = mkTyparToTyparRenaming (ovByMethValRef.MemberApparentEntity.Typars(m)) enclosingTypars + let parentToMemberInst, _ = mkTyparToTyparRenaming (ovByMethValRef.MemberApparentEntity.Typars m) enclosingTypars let res = instSlotSig parentToMemberInst slotsig res | None -> @@ -524,7 +527,7 @@ type OptionalArgInfo = PassByRef (ty, analyze ty) elif isObjTy g ty then match ilParam.Marshal with - | Some(ILNativeType.IUnknown | ILNativeType.IDispatch | ILNativeType.Interface) -> Constant(ILFieldInit.Null) + | Some(ILNativeType.IUnknown | ILNativeType.IDispatch | ILNativeType.Interface) -> Constant ILFieldInit.Null | _ -> if TryFindILAttributeOpt g.attrib_IUnknownConstantAttribute ilParam.CustomAttrs then WrapperForIUnknown elif TryFindILAttributeOpt g.attrib_IDispatchConstantAttribute ilParam.CustomAttrs then WrapperForIDispatch @@ -577,8 +580,7 @@ type ParamNameAndType = [] /// Full information about a parameter returned for use by the type checker and language service. type ParamData = - /// ParamData(isParamArray, isOut, optArgInfo, callerInfo, nameOpt, reflArgInfo, ttype) - ParamData of bool * bool * bool * OptionalArgInfo * CallerInfo * Ident option * ReflectedArgInfo * TType + ParamData of isParamArray: bool * isInArg: bool * isOut: bool * optArgInfo: OptionalArgInfo * callerInfo: CallerInfo * nameOpt: Ident option * reflArgInfo: ReflectedArgInfo * ttype: TType //------------------------------------------------------------------------- @@ -593,7 +595,7 @@ type ILFieldInit with | null -> ILFieldInit.Null | _ -> let objTy = v.GetType() - let v = if objTy.IsEnum then objTy.GetField("value__").GetValue(v) else v + let v = if objTy.IsEnum then objTy.GetField("value__").GetValue v else v match v with | :? single as i -> ILFieldInit.Single i | :? double as i -> ILFieldInit.Double i @@ -835,7 +837,15 @@ type ILMethInfo = member x.IsDllImport (g: TcGlobals) = match g.attrib_DllImportAttribute with | None -> false - | Some (AttribInfo(tref, _)) ->x.RawMetadata.CustomAttrs |> TryDecodeILAttribute g tref |> Option.isSome + | Some attr -> + x.RawMetadata.CustomAttrs + |> TryFindILAttribute attr + + /// Indicates if the method is marked with the [] attribute. This is done by looking at the IL custom attributes on + /// the method. + member x.IsReadOnly (g: TcGlobals) = + x.RawMetadata.CustomAttrs + |> TryFindILAttribute g.attrib_IsReadOnlyAttribute /// Get the (zero or one) 'self'/'this'/'object' arguments associated with an IL method. /// An instance extension method returns one object argument. @@ -863,9 +873,7 @@ type ILMethInfo = // MethInfo -#if DEBUG [] -#endif /// Describes an F# use of a method [] type MethInfo = @@ -924,7 +932,7 @@ type MethInfo = | FSMeth _ -> None #if !NO_EXTENSIONTYPING | ProvidedMeth (_, mb, _, m) -> - let staticParams = mb.PApplyWithProvider((fun (mb, provider) -> mb.GetStaticParametersForMethod(provider)), range=m) + let staticParams = mb.PApplyWithProvider((fun (mb, provider) -> mb.GetStaticParametersForMethod provider), range=m) let staticParams = staticParams.PApplyArray(id, "GetStaticParametersForMethod", m) match staticParams with | [| |] -> None @@ -948,7 +956,6 @@ type MethInfo = /// over extension members. member x.ExtensionMemberPriority = defaultArg x.ExtensionMemberPriorityOption System.UInt64.MaxValue -#if DEBUG /// Get the method name in DebuggerDisplayForm member x.DebuggerDisplayName = match x with @@ -958,7 +965,6 @@ type MethInfo = | ProvidedMeth(_, mi, _, m) -> "ProvidedMeth: " + mi.PUntaint((fun mi -> mi.Name), m) #endif | DefaultStructCtor _ -> ".ctor" -#endif /// Get the method name in LogicalName form, i.e. the name as it would be stored in .NET metadata member x.LogicalName = @@ -1031,7 +1037,7 @@ type MethInfo = | DefaultStructCtor _ -> XmlDoc.Empty #if !NO_EXTENSIONTYPING | ProvidedMeth(_, mi, _, m)-> - XmlDoc (mi.PUntaint((fun mix -> (mix :> IProvidedCustomAttributeProvider).GetXmlDocAttributes(mi.TypeProvider.PUntaintNoFailure(id))), m)) + XmlDoc (mi.PUntaint((fun mix -> (mix :> IProvidedCustomAttributeProvider).GetXmlDocAttributes(mi.TypeProvider.PUntaintNoFailure id)), m)) #endif /// Try to get an arbitrary F# ValRef associated with the member. This is to determine if the member is virtual, amongst other things. @@ -1069,7 +1075,7 @@ type MethInfo = /// For an extension method this includes all type parameters, even if it is extending a generic type. member x.GenericArity = x.FormalMethodTypars.Length - member x.IsProtectedAccessiblity = + member x.IsProtectedAccessibility = match x with | ILMeth(_, ilmeth, _) -> ilmeth.IsProtectedAccessibility | FSMeth _ -> false @@ -1146,7 +1152,6 @@ type MethInfo = #endif member x.IsNewSlot = - isInterfaceTy x.TcGlobals x.ApparentEnclosingType || (x.IsVirtual && (match x with | ILMeth(_, x, _) -> x.IsNewSlot @@ -1156,6 +1161,12 @@ type MethInfo = #endif | DefaultStructCtor _ -> false)) + /// Indicates if this is an IL method. + member x.IsILMethod = + match x with + | ILMeth _ -> true + | _ -> false + /// Check if this method is an explicit implementation of an interface member member x.IsFSharpExplicitInterfaceImplementation = match x with @@ -1217,13 +1228,13 @@ type MethInfo = // xs.Map // but is compiled as a generic methods with two type arguments // Map<'T, 'U>(this: List<'T>, f : 'T -> 'U) - member x.AdjustUserTypeInstForFSharpStyleIndexedExtensionMembers(tyargs) = + member x.AdjustUserTypeInstForFSharpStyleIndexedExtensionMembers tyargs = (if x.IsFSharpStyleExtensionMember then argsOfAppTy x.TcGlobals x.ApparentEnclosingAppType else []) @ tyargs /// Indicates if this method is a generated method associated with an F# CLIEvent property compiled as a .NET event member x.IsFSharpEventPropertyMethod = match x with - | FSMeth(g, _, vref, _) -> vref.IsFSharpEventProperty(g) + | FSMeth(g, _, vref, _) -> vref.IsFSharpEventProperty g #if !NO_EXTENSIONTYPING | ProvidedMeth _ -> false #endif @@ -1238,6 +1249,25 @@ type MethInfo = member x.IsStruct = isStructTy x.TcGlobals x.ApparentEnclosingType + /// Indicates if this method is read-only; usually by the [] attribute. + /// Must be an instance method. + /// Receiver must be a struct type. + member x.IsReadOnly = + // Perf Review: Is there a way we can cache this result? + x.IsInstance && + x.IsStruct && + match x with + | ILMeth (g, ilMethInfo, _) -> ilMethInfo.IsReadOnly g + | FSMeth _ -> false // F# defined methods not supported yet. Must be a language feature. + | _ -> false + + /// Indicates if this method is an extension member that is read-only. + /// An extension member is considered read-only if the first argument is a read-only byref (inref) type. + member x.IsReadOnlyExtensionMember (amap: Import.ImportMap, m) = + x.IsExtensionMember && + x.TryObjArgByrefType(amap, m, x.FormalMethodInst) + |> Option.exists (isInByrefTy amap.g) + /// Build IL method infos. static member CreateILMeth (amap: Import.ImportMap, m, ty: TType, md: ILMethodDef) = let tinfo = ILTypeInfo.FromType amap.g ty @@ -1271,7 +1301,7 @@ type MethInfo = | DefaultStructCtor(_, _ty) -> 34892 // "ty" doesn't support hashing. We could use "hash (tcrefOfAppTy g ty).CompiledName" or // something but we don't have a "g" parameter here yet. But this hash need only be very approximate anyway #if !NO_EXTENSIONTYPING - | ProvidedMeth(_, mi, _, _) -> ProvidedMethodInfo.TaintedGetHashCode(mi) + | ProvidedMeth(_, mi, _, _) -> ProvidedMethodInfo.TaintedGetHashCode mi #endif /// Apply a type instantiation to a method info, i.e. apply the instantiation to the enclosing type. @@ -1415,7 +1445,7 @@ type MethInfo = // Emit a warning, and ignore the DefaultParameterValue argument altogether. warning(Error(FSComp.SR.DefaultParameterValueNotAppropriateForArgument(), m)) NotOptional - | Some (Expr.Const((ConstToILFieldInit fi), _, _)) -> + | Some (Expr.Const ((ConstToILFieldInit fi), _, _)) -> // Good case - all is well. CallerSide (Constant fi) | _ -> @@ -1456,10 +1486,10 @@ type MethInfo = | ProvidedMeth(amap, mi, _, _) -> // A single group of tupled arguments [ [for p in mi.PApplyArray((fun mi -> mi.GetParameters()), "GetParameters", m) do - let isParamArrayArg = p.PUntaint((fun px -> (px :> IProvidedCustomAttributeProvider).GetAttributeConstructorArgs(p.TypeProvider.PUntaintNoFailure(id), typeof.FullName).IsSome), m) + let isParamArrayArg = p.PUntaint((fun px -> (px :> IProvidedCustomAttributeProvider).GetAttributeConstructorArgs(p.TypeProvider.PUntaintNoFailure id, typeof.FullName).IsSome), m) let optArgInfo = OptionalArgInfoOfProvidedParameter amap m p let reflArgInfo = - match p.PUntaint((fun px -> (px :> IProvidedCustomAttributeProvider).GetAttributeConstructorArgs(p.TypeProvider.PUntaintNoFailure(id), typeof.FullName)), m) with + match p.PUntaint((fun px -> (px :> IProvidedCustomAttributeProvider).GetAttributeConstructorArgs(p.TypeProvider.PUntaintNoFailure id, typeof.FullName)), m) with | Some ([ Some (:? bool as b) ], _) -> ReflectedArgInfo.Quote b | Some _ -> ReflectedArgInfo.Quote false | None -> ReflectedArgInfo.None @@ -1478,13 +1508,13 @@ type MethInfo = match x with | FSMeth(g, _, vref, _) -> match vref.RecursiveValInfo with - | ValInRecScope(false) -> error(Error((FSComp.SR.InvalidRecursiveReferenceToAbstractSlot()), m)) + | ValInRecScope false -> error(Error((FSComp.SR.InvalidRecursiveReferenceToAbstractSlot()), m)) | _ -> () let allTyparsFromMethod, _, retTy, _ = GetTypeOfMemberInMemberForm g vref // A slot signature is w.r.t. the type variables of the type it is associated with. // So we have to rename from the member type variables to the type variables of the type. - let formalEnclosingTypars = x.ApparentEnclosingTyconRef.Typars(m) + let formalEnclosingTypars = x.ApparentEnclosingTyconRef.Typars m let formalEnclosingTyparsFromMethod, formalMethTypars = List.splitAt formalEnclosingTypars.Length allTyparsFromMethod let methodToParentRenaming, _ = mkTyparToTyparRenaming formalEnclosingTyparsFromMethod formalEnclosingTypars let formalParams = @@ -1502,7 +1532,7 @@ type MethInfo = // then that does not correspond to a slotsig compiled as a 'void' return type. // REVIEW: should we copy down attributes to slot params? let tcref = tcrefOfAppTy g x.ApparentEnclosingAppType - let formalEnclosingTyparsOrig = tcref.Typars(m) + let formalEnclosingTyparsOrig = tcref.Typars m let formalEnclosingTypars = copyTypars formalEnclosingTyparsOrig let _, formalEnclosingTyparTys = FixupNewTypars m [] [] formalEnclosingTyparsOrig formalEnclosingTypars let formalMethTypars = copyTypars x.FormalMethodTypars @@ -1514,7 +1544,7 @@ type MethInfo = let formalRetTy = ImportReturnTypeFromMetadata amap m ilminfo.RawMetadata.Return.Type ilminfo.RawMetadata.Return.CustomAttrs ftinfo.ILScopeRef ftinfo.TypeInstOfRawMetadata formalMethTyparTys let formalParams = [ [ for p in ilminfo.RawMetadata.Parameters do - let paramType = ImportILTypeFromMetadata amap m ftinfo.ILScopeRef ftinfo.TypeInstOfRawMetadata formalMethTyparTys p.Type + let paramType = ImportILTypeFromMetadataWithAttributes amap m ftinfo.ILScopeRef ftinfo.TypeInstOfRawMetadata formalMethTyparTys p.Type p.CustomAttrs yield TSlotParam(p.Name, paramType, p.IsIn, p.IsOut, p.IsOptional, []) ] ] formalRetTy, formalParams #if !NO_EXTENSIONTYPING @@ -1587,14 +1617,14 @@ type MethInfo = let memberParentTypars, _, _, _ = AnalyzeTypeOfMemberVal false g (ty, vref) memberParentTypars | _ -> - x.DeclaringTyconRef.Typars(m) + x.DeclaringTyconRef.Typars m /// Tries to get the object arg type if it's a byref type. member x.TryObjArgByrefType(amap, m, minst) = x.GetObjArgTypes(amap, m, minst) |> List.tryHead |> Option.bind (fun ty -> - if isByrefTy x.TcGlobals ty then Some(ty) + if isByrefTy x.TcGlobals ty then Some ty else None) //------------------------------------------------------------------------- @@ -1740,7 +1770,7 @@ type ILFieldInfo = /// Describes an F# use of a field in an F#-declared record, class or struct type [] type RecdFieldInfo = - | RecdFieldInfo of TypeInst * Tast.RecdFieldRef + | RecdFieldInfo of TypeInst * RecdFieldRef /// Get the generic instantiation of the declaring type of the field member x.TypeInst = let (RecdFieldInfo(tinst, _)) = x in tinst @@ -1777,7 +1807,7 @@ type RecdFieldInfo = /// Describes an F# use of a union case [] type UnionCaseInfo = - | UnionCaseInfo of TypeInst * Tast.UnionCaseRef + | UnionCaseInfo of TypeInst * UnionCaseRef /// Get the list of types for the instantiation of the type parameters of the declaring type of the union case member x.TypeInst = let (UnionCaseInfo(tinst, _)) = x in tinst @@ -1798,7 +1828,7 @@ type UnionCaseInfo = member x.Name = x.UnionCase.DisplayName /// Get the instantiation of the type parameters of the declaring type of the union case - member x.GetTyparInst(m) = mkTyparInst (x.TyconRef.Typars(m)) x.TypeInst + member x.GetTyparInst m = mkTyparInst (x.TyconRef.Typars m) x.TypeInst override x.ToString() = x.TyconRef.ToString() + "::" + x.Name @@ -2073,7 +2103,7 @@ type PropInfo = /// Indicates if this is an F# property compiled as a CLI event, e.g. a [] property. member x.IsFSharpEventProperty = match x with - | FSProp(g, _, Some vref, None) -> vref.IsFSharpEventProperty(g) + | FSProp(g, _, Some vref, None) -> vref.IsFSharpEventProperty g #if !NO_EXTENSIONTYPING | ProvidedProp _ -> false #endif @@ -2104,7 +2134,7 @@ type PropInfo = | FSProp(_, _, None, None) -> failwith "unreachable" #if !NO_EXTENSIONTYPING | ProvidedProp(_, pi, m) -> - XmlDoc (pi.PUntaint((fun pix -> (pix :> IProvidedCustomAttributeProvider).GetXmlDocAttributes(pi.TypeProvider.PUntaintNoFailure(id))), m)) + XmlDoc (pi.PUntaint((fun pix -> (pix :> IProvidedCustomAttributeProvider).GetXmlDocAttributes(pi.TypeProvider.PUntaintNoFailure id)), m)) #endif /// Get the TcGlobals associated with the object @@ -2197,7 +2227,7 @@ type PropInfo = /// Must be compatible with ItemsAreEffectivelyEqual relation. static member PropInfosUseIdenticalDefinitions x1 x2 = let optVrefEq g = function - | Some(v1), Some(v2) -> valRefEq g v1 v2 + | Some v1, Some v2 -> valRefEq g v1 v2 | None, None -> true | _ -> false match x1, x2 with @@ -2218,9 +2248,11 @@ type PropInfo = let vth = (vrefOpt1 |> Option.map (fun vr -> vr.LogicalName), (vrefOpt2 |> Option.map (fun vr -> vr.LogicalName))) hash vth #if !NO_EXTENSIONTYPING - | ProvidedProp(_, pi, _) -> ProvidedPropertyInfo.TaintedGetHashCode(pi) + | ProvidedProp(_, pi, _) -> ProvidedPropertyInfo.TaintedGetHashCode pi #endif + override x.ToString() = "property " + x.PropertyName + //------------------------------------------------------------------------- // ILEventInfo @@ -2356,7 +2388,7 @@ type EventInfo = | FSEvent (_, p, _, _) -> p.XmlDoc #if !NO_EXTENSIONTYPING | ProvidedEvent (_, ei, m) -> - XmlDoc (ei.PUntaint((fun eix -> (eix :> IProvidedCustomAttributeProvider).GetXmlDocAttributes(ei.TypeProvider.PUntaintNoFailure(id))), m)) + XmlDoc (ei.PUntaint((fun eix -> (eix :> IProvidedCustomAttributeProvider).GetXmlDocAttributes(ei.TypeProvider.PUntaintNoFailure id)), m)) #endif /// Get the logical name of the event. @@ -2449,7 +2481,7 @@ type EventInfo = /// Test whether two event infos have the same underlying definition. /// Must be compatible with ItemsAreEffectivelyEqual relation. - static member EventInfosUseIdenticalDefintions x1 x2 = + static member EventInfosUseIdenticalDefinitions x1 x2 = match x1, x2 with | FSEvent(g, pi1, vrefa1, vrefb1), FSEvent(_, pi2, vrefa2, vrefb2) -> PropInfo.PropInfosUseIdenticalDefinitions pi1 pi2 && valRefEq g vrefa1 vrefa2 && valRefEq g vrefb1 vrefb2 @@ -2466,8 +2498,9 @@ type EventInfo = | ILEvent ileinfo -> hash ileinfo.RawMetadata.Name | FSEvent(_, pi, vref1, vref2) -> hash ( pi.ComputeHashCode(), vref1.LogicalName, vref2.LogicalName) #if !NO_EXTENSIONTYPING - | ProvidedEvent (_, ei, _) -> ProvidedEventInfo.TaintedGetHashCode(ei) + | ProvidedEvent (_, ei, _) -> ProvidedEventInfo.TaintedGetHashCode ei #endif + override x.ToString() = "event " + x.EventName //------------------------------------------------------------------------- // Helpers associated with getting and comparing method signatures @@ -2499,10 +2532,9 @@ let CompiledSigOfMeth g amap m (minfo: MethInfo) = CompiledSig(vargtys, vrty, formalMethTypars, fmtpinst) -/// Used to hide/filter members from super classes based on signature + /// Inref and outref parameter types will be treated as a byref type for equivalency. -let MethInfosEquivByNameAndPartialSig erasureFlag ignoreFinal g amap m (minfo: MethInfo) (minfo2: MethInfo) = - (minfo.LogicalName = minfo2.LogicalName) && +let MethInfosEquivByPartialSig erasureFlag ignoreFinal g amap m (minfo: MethInfo) (minfo2: MethInfo) = (minfo.GenericArity = minfo2.GenericArity) && (ignoreFinal || minfo.IsFinal = minfo2.IsFinal) && let formalMethTypars = minfo.FormalMethodTypars @@ -2514,6 +2546,12 @@ let MethInfosEquivByNameAndPartialSig erasureFlag ignoreFinal g amap m (minfo: M (argtys, argtys2) ||> List.lengthsEqAndForall2 (List.lengthsEqAndForall2 (fun ty1 ty2 -> typeAEquivAux erasureFlag g (TypeEquivEnv.FromEquivTypars formalMethTypars formalMethTypars2) (stripByrefTy g ty1) (stripByrefTy g ty2))) +/// Used to hide/filter members from super classes based on signature +/// Inref and outref parameter types will be treated as a byref type for equivalency. +let MethInfosEquivByNameAndPartialSig erasureFlag ignoreFinal g amap m (minfo: MethInfo) (minfo2: MethInfo) = + (minfo.LogicalName = minfo2.LogicalName) && + MethInfosEquivByPartialSig erasureFlag ignoreFinal g amap m minfo minfo2 + /// Used to hide/filter members from super classes based on signature let PropInfosEquivByNameAndPartialSig erasureFlag g amap m (pinfo: PropInfo) (pinfo2: PropInfo) = pinfo.PropertyName = pinfo2.PropertyName && diff --git a/src/fcs-fable/src/fsharp/layout.fs b/src/fcs-fable/src/fsharp/layout.fs old mode 100755 new mode 100644 index a28c84c695..27a552d45a --- a/src/fcs-fable/src/fsharp/layout.fs +++ b/src/fcs-fable/src/fsharp/layout.fs @@ -3,7 +3,6 @@ module FSharp.Compiler.Layout open System -open System.Collections.Generic open System.IO open Internal.Utilities.StructuredFormat open Microsoft.FSharp.Core.Printf @@ -19,6 +18,7 @@ type NavigableTaggedText(taggedText: TaggedText, range: Range.range) = interface TaggedText with member x.Tag = taggedText.Tag member x.Text = taggedText.Text + let mkNav r t = NavigableTaggedText(t, r) :> TaggedText let spaces n = new String(' ', n) @@ -238,10 +238,10 @@ let (@@--) l r = apply2 (fun l r -> mkNode l r (Broken 2)) l r let tagListL tagger = function | [] -> emptyL | [x] -> x - | x::xs -> + | x :: xs -> let rec process' prefixL = function | [] -> prefixL - | y::ys -> process' ((tagger prefixL) ++ y) ys in + | y :: ys -> process' ((tagger prefixL) ++ y) ys in process' x xs let commaListL x = tagListL (fun prefixL -> prefixL ^^ rightL Literals.comma) x @@ -254,7 +254,7 @@ let tupleL xs = bracketL (sepListL (sepL Literals.comma) xs) let aboveListL = function | [] -> emptyL | [x] -> x - | x::ys -> List.fold (fun pre y -> pre @@ y) x ys + | x :: ys -> List.fold (fun pre y -> pre @@ y) x ys let optionL xL = function | None -> wordL (tagUnionCase "None") @@ -389,7 +389,7 @@ type LayoutRenderer<'a, 'b> = let renderL (rr: LayoutRenderer<_, _>) layout = let rec addL z pos i layout k = match layout with - | ObjLeaf _ -> failwith "ObjLeaf should never apper here" + | ObjLeaf _ -> failwith "ObjLeaf should never appear here" (* pos is tab level *) | Leaf (_, text, _) -> k(rr.AddText z text, i + text.Text.Length) @@ -419,7 +419,7 @@ let renderL (rr: LayoutRenderer<_, _>) layout = let stringR = { new LayoutRenderer with member x.Start () = [] - member x.AddText rstrs taggedText = taggedText.Text::rstrs + member x.AddText rstrs taggedText = taggedText.Text :: rstrs member x.AddBreak rstrs n = (spaces n) :: "\n" :: rstrs member x.AddTag z (_, _, _) = z member x.Finish rstrs = String.Join("", Array.ofList (List.rev rstrs)) } diff --git a/src/fcs-fable/src/fsharp/layout.fsi b/src/fcs-fable/src/fsharp/layout.fsi old mode 100755 new mode 100644 index 28ae94ab73..0182efe2e1 --- a/src/fcs-fable/src/fsharp/layout.fsi +++ b/src/fcs-fable/src/fsharp/layout.fsi @@ -1,61 +1,90 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. +/// DSL to create structured layout objects with optional breaks and render them module public FSharp.Compiler.Layout open System.Text -open System.Collections.Generic open System.IO +open FSharp.Compiler.Range open Internal.Utilities.StructuredFormat -open Internal.Utilities.StructuredFormat.TaggedTextOps type layout = Internal.Utilities.StructuredFormat.Layout type LayoutTag = Internal.Utilities.StructuredFormat.LayoutTag type TaggedText = Internal.Utilities.StructuredFormat.TaggedText type NavigableTaggedText = - new : TaggedText * Range.range -> NavigableTaggedText - member Range: Range.range + new : TaggedText * range -> NavigableTaggedText + member Range: range interface TaggedText -val mkNav : Range.range -> TaggedText -> TaggedText -module TaggedTextOps = Internal.Utilities.StructuredFormat.TaggedTextOps +val mkNav : range -> TaggedText -> TaggedText val emptyL : Layout val isEmptyL : Layout -> bool val wordL : TaggedText -> Layout + val sepL : TaggedText -> Layout + val rightL : TaggedText -> Layout + val leftL : TaggedText -> Layout -val ( ^^ ) : Layout -> Layout -> Layout (* never break "glue" *) -val ( ++ ) : Layout -> Layout -> Layout (* if break, indent=0 *) -val ( -- ) : Layout -> Layout -> Layout (* if break, indent=1 *) -val ( --- ) : Layout -> Layout -> Layout (* if break, indent=2 *) -val ( ---- ) : Layout -> Layout -> Layout (* if break, indent=2 *) -val ( ----- ) : Layout -> Layout -> Layout (* if break, indent=2 *) -val ( @@ ) : Layout -> Layout -> Layout (* broken ident=0 *) -val ( @@- ) : Layout -> Layout -> Layout (* broken ident=1 *) -val ( @@-- ) : Layout -> Layout -> Layout (* broken ident=2 *) + +/// never break "glue" +val ( ^^ ) : Layout -> Layout -> Layout + +/// optional break, indent=0 +val ( ++ ) : Layout -> Layout -> Layout + +// optional break, indent=1 +val ( -- ) : Layout -> Layout -> Layout + +/// optional break, indent=2 +val ( --- ) : Layout -> Layout -> Layout + +/// optional break, indent=3 +val ( ---- ) : Layout -> Layout -> Layout + +/// optional break, indent=4 +val ( ----- ) : Layout -> Layout -> Layout + +/// non-optional break ident=0 +val ( @@ ) : Layout -> Layout -> Layout + +/// non-optional break ident=1 +val ( @@- ) : Layout -> Layout -> Layout + +/// non-optional break ident=2 +val ( @@-- ) : Layout -> Layout -> Layout val commaListL : Layout list -> Layout + val spaceListL : Layout list -> Layout + val semiListL : Layout list -> Layout + val sepListL : Layout -> Layout list -> Layout val bracketL : Layout -> Layout + val tupleL : Layout list -> Layout + val aboveL : Layout -> Layout -> Layout + val aboveListL : Layout list -> Layout val optionL : ('a -> Layout) -> 'a option -> Layout + val listL : ('a -> Layout) -> 'a list -> Layout val squashTo : int -> Layout -> Layout val showL : Layout -> string + #if !FABLE_COMPILER val outL : TextWriter -> Layout -> unit #endif + val bufferL : StringBuilder -> Layout -> unit module TaggedTextOps = @@ -179,7 +208,7 @@ module RightL = val rightBracketAngle: Layout val rightBracketBar: Layout -/// render a Layout yielding an 'a using a 'b (hidden state) type +/// Render a Layout yielding an 'a using a 'b (hidden state) type type LayoutRenderer<'a,'b> = abstract Start : unit -> 'b abstract AddText : 'b -> TaggedText -> 'b @@ -193,11 +222,17 @@ type NoResult = NoResult /// Run a render on a Layout val renderL : LayoutRenderer<'b,'a> -> Layout -> 'b -/// Primitive renders +/// Render layout to string val stringR : LayoutRenderer + #if !FABLE_COMPILER +/// Render layout to channel val channelR : TextWriter -> LayoutRenderer #endif + +/// Render layout to StringBuilder val bufferR : StringBuilder -> LayoutRenderer + +/// Render layout to collector of TaggedText val taggedTextListR : collector: (TaggedText -> unit) -> LayoutRenderer diff --git a/src/fcs-fable/src/fsharp/lex.fsl b/src/fcs-fable/src/fsharp/lex.fsl old mode 100755 new mode 100644 index c56f655f22..2ae885496c --- a/src/fcs-fable/src/fsharp/lex.fsl +++ b/src/fcs-fable/src/fsharp/lex.fsl @@ -13,26 +13,31 @@ module internal FSharp.Compiler.Lexer open System open System.Globalization open System.Text + open Internal.Utilities +open Internal.Utilities.Text.Lexing +open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler - -open FSharp.Compiler.Range -open FSharp.Compiler.Ast open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Parser +open FSharp.Compiler.Features open FSharp.Compiler.Lexhelp open FSharp.Compiler.Lib -open Internal.Utilities.Text.Lexing +open FSharp.Compiler.Range +open FSharp.Compiler.ParseHelpers +open FSharp.Compiler.Parser +open FSharp.Compiler.SyntaxTree let lexeme (lexbuf : UnicodeLexing.Lexbuf) = UnicodeLexing.Lexbuf.LexemeString lexbuf let trimBoth (s:string) n m = s.Substring(n, s.Length - (n+m)) + let lexemeTrimBoth lexbuf n m = trimBoth (lexeme lexbuf) n m + let lexemeTrimRight lexbuf n = lexemeTrimBoth lexbuf 0 n + let lexemeTrimLeft lexbuf n = lexemeTrimBoth lexbuf n 0 let fail args (lexbuf:UnicodeLexing.Lexbuf) msg dflt = @@ -67,13 +72,11 @@ let get0OXB (s:string) (p:int) l = let formatError() = raise (new System.FormatException(SR.GetString("bad format string"))) -let parseBinaryUInt64 (s:string) p l = - let rec parse n acc = if n < l then parse (n+1) (acc * 2UL + (match s.[n] with '0' -> 0UL | '1' -> 1UL | _ -> formatError())) else acc - parse p 0UL +let parseBinaryUInt64 (s:string) = + Convert.ToUInt64(s, 2) -let parseOctalUInt64 (s:string) p l = - let rec parse n acc = if n < l then parse (n+1) (acc * 8UL + (let c = s.[n] in if c >= '0' && c <= '7' then Convert.ToUInt64 c - Convert.ToUInt64 '0' else formatError())) else acc - parse p 0UL +let parseOctalUInt64 (s:string) = + Convert.ToUInt64(s, 8) let removeUnderscores (s:string) = match s with @@ -83,24 +86,23 @@ let removeUnderscores (s:string) = let parseInt32 (s:string) = let s = removeUnderscores s let l = s.Length +#if FABLE_COMPILER let p = 0 let sign, p = getSign32 s p l let specifier, p = get0OXB s p l -#if FX_RESHAPED_GLOBALIZATION - match CultureInfo.InvariantCulture.TextInfo.ToLower(specifier) with -#else match Char.ToLowerInvariant(specifier) with -#endif -#if FABLE_COMPILER | 'x' -> sign * Convert.ToInt32(s.Substring(p), 16) -#else - | 'x' -> sign * (int32 (uint32(UInt64.Parse(s.Substring(p), NumberStyles.AllowHexSpecifier,CultureInfo.InvariantCulture)))) -#endif - | 'b' -> sign * (int32 (uint32(parseBinaryUInt64 s p l))) - | 'o' -> sign * (int32 (uint32(parseOctalUInt64 s p l))) -#if FABLE_COMPILER + | 'b' -> sign * (int32 (Convert.ToUInt32(parseBinaryUInt64 (s.Substring(p))))) + | 'o' -> sign * (int32 (Convert.ToUInt32(parseOctalUInt64 (s.Substring(p))))) | _ -> Convert.ToInt32(s) #else + let mutable p = 0 + let sign = getSign32 s &p l + let specifier = get0OXB s &p l + match Char.ToLower(specifier,CultureInfo.InvariantCulture) with + | 'x' -> sign * (int32 (Convert.ToUInt32(UInt64.Parse(s.Substring(p), NumberStyles.AllowHexSpecifier,CultureInfo.InvariantCulture)))) + | 'b' -> sign * (int32 (Convert.ToUInt32(parseBinaryUInt64 (s.Substring(p))))) + | 'o' -> sign * (int32 (Convert.ToUInt32(parseOctalUInt64 (s.Substring(p))))) | _ -> Int32.Parse(s, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture) #endif @@ -155,74 +157,132 @@ let tryAppendXmlDoc (buff:option) (s:string) = let shouldStartLine args lexbuf (m:range) err tok = if (m.StartColumn <> 0) then fail args lexbuf err tok else tok - + let shouldStartFile args lexbuf (m:range) err tok = if (m.StartColumn <> 0 || m.StartLine <> 1) then fail args lexbuf err tok else tok - -let evalIfDefExpression startPos args (lookup:string->bool) (lexed:string) = - let lexbuf = LexBuffer<_>.FromString (lexed) + +let evalIfDefExpression startPos isFeatureSupported args (lookup:string->bool) (lexed:string) = +#if FABLE_COMPILER + let lexbuf = LexBuffer<_>.FromString (isFeatureSupported, lexed) +#else + let lexbuf = LexBuffer.FromChars (isFeatureSupported, lexed.ToCharArray ()) +#endif lexbuf.StartPos <- startPos lexbuf.EndPos <- startPos let tokenStream = FSharp.Compiler.PPLexer.tokenstream args - let expr = FSharp.Compiler.PPParser.start tokenStream lexbuf - LexerIfdefEval lookup expr +let evalFloat args lexbuf = + try + float32(removeUnderscores (lexemeTrimRight lexbuf 1)) + with _ -> + fail args lexbuf (FSComp.SR.lexInvalidFloat()) 0.0f + } + let letter = '\Lu' | '\Ll' | '\Lt' | '\Lm' | '\Lo' | '\Nl' + let surrogateChar = '\Cs' + let digit = '\Nd' + let hex = ['0'-'9'] | ['A'-'F'] | ['a'-'f'] + let truewhite = [' '] + let offwhite = ['\t'] + let anywhite = truewhite | offwhite + let anychar = [^'\n''\r'] + let anystring = anychar* + let op_char = '!'|'$'|'%'|'&'|'*'|'+'|'-'|'.'|'/'|'<'|'='|'>'|'?'|'@'|'^'|'|'|'~'|':' + let ignored_op_char = '.' | '$' | '?' + let separator = '_' + let xinteger = ( '0' ('x'| 'X') hex ((hex | separator)* hex)? | '0' ('o'| 'O') (['0'-'7']) (((['0'-'7']) | separator)* (['0'-'7']))? | '0' ('b'| 'B') (['0'-'1']) (((['0'-'1']) | separator)* (['0'-'1']))?) + let integer = digit ((digit | separator)* digit)? + let int8 = integer 'y' + let uint8 = (xinteger | integer) 'u' 'y' + let int16 = integer 's' + let uint16 = (xinteger | integer) 'u' 's' + let int = integer + let int32 = integer 'l' + let uint32 = (xinteger | integer) 'u' + let uint32l = (xinteger | integer) 'u' 'l' + let nativeint = (xinteger | integer) 'n' + let unativeint = (xinteger | integer) 'u' 'n' + let int64 = (xinteger | integer) 'L' + let uint64 = (xinteger | integer) ('u' | 'U') 'L' + let xint8 = xinteger 'y' + let xint16 = xinteger 's' + let xint = xinteger + let xint32 = xinteger 'l' + let floatp = digit ((digit | separator)* digit)? '.' (digit ((digit | separator)* digit)?)? + let floate = digit ((digit | separator)* digit)? ('.' (digit ((digit | separator)* digit)?)? )? ('e'| 'E') ['+' '-']? digit ((digit | separator)* digit)? + let float = floatp | floate + let bignum = integer ('I' | 'N' | 'Z' | 'Q' | 'R' | 'G') + let ieee64 = float + let ieee32 = float ('f' | 'F') -let decimal = (float | integer) ('m' | 'M') + +let ieee32_dotless_no_exponent = integer ('f' | 'F') + +let decimal = (float | integer) ('m' | 'M') + let xieee32 = xinteger 'l' 'f' + let xieee64 = xinteger 'L' 'F' + let escape_char = ('\\' ( '\\' | "\"" | '\'' | 'a' | 'f' | 'v' | 'n' | 't' | 'b' | 'r')) + let char = '\'' ( [^'\\''\n''\r''\t''\b'] | escape_char) '\'' + let trigraph = '\\' digit digit digit + let hexGraphShort = '\\' 'x' hex hex + let unicodeGraphShort = '\\' 'u' hex hex hex hex + let unicodeGraphLong = '\\' 'U' hex hex hex hex hex hex hex hex + let newline = ('\n' | '\r' '\n') let connecting_char = '\Pc' + let combining_char = '\Mn' | '\Mc' + let formatting_char = '\Cf' let ident_start_char = @@ -241,49 +301,65 @@ let ident = ident_start_char ident_char* rule token args skip = parse | ident { Keywords.KeywordOrIdentifierToken args lexbuf (lexeme lexbuf) } + | "do!" { DO_BANG } + | "yield!" { YIELD_BANG(true) } + | "return!" { YIELD_BANG(false) } + | "match!" { MATCH_BANG } + + | "and!" + { AND_BANG(false) } + | ident '!' { let tok = Keywords.KeywordOrIdentifierToken args lexbuf (lexemeTrimRight lexbuf 1) match tok with - | LET _ -> BINDER (lexemeTrimRight lexbuf 1) + | LET _ -> BINDER (lexemeTrimRight lexbuf 1) | _ -> fail args lexbuf (FSComp.SR.lexIdentEndInMarkReserved("!")) (Keywords.KeywordOrIdentifierToken args lexbuf (lexeme lexbuf)) } + | ident ('#') { fail args lexbuf (FSComp.SR.lexIdentEndInMarkReserved("#")) (Keywords.KeywordOrIdentifierToken args lexbuf (lexeme lexbuf)) } + | int8 { let n = lexemeTrimRightToInt32 args lexbuf 1 if n > 0x80 || n < -0x80 then fail args lexbuf (FSComp.SR.lexOutsideEightBitSigned()) (INT8(0y,false)) // Allow to parse as min_int. Allowed only because we parse '-' as an operator. else if n = 0x80 then INT8(sbyte(-0x80), true (* 'true' = 'bad'*) ) else INT8(sbyte n,false) } + | xint8 { let n = lexemeTrimRightToInt32 args lexbuf 1 if n > 0xFF || n < 0 then fail args lexbuf (FSComp.SR.lexOutsideEightBitSignedHex()) (INT8(0y,false)) else INT8(sbyte(byte(n)),false) } + | uint8 { let n = lexemeTrimRightToInt32 args lexbuf 2 if n > 0xFF || n < 0 then fail args lexbuf (FSComp.SR.lexOutsideEightBitUnsigned()) (UINT8(0uy)) else UINT8(byte n) } + | int16 { let n = lexemeTrimRightToInt32 args lexbuf 1 if n > 0x8000 || n < -0x8000 then fail args lexbuf (FSComp.SR.lexOutsideSixteenBitSigned()) (INT16(0s,false)) // Allow to parse as min_int. Allowed only because we parse '-' as an operator. else if n = 0x8000 then INT16(-0x8000s,true) else INT16(int16 n,false) } + | xint16 { let n = lexemeTrimRightToInt32 args lexbuf 1 if n > 0xFFFF || n < 0 then fail args lexbuf (FSComp.SR.lexOutsideSixteenBitSigned()) (INT16(0s,false)) else INT16(int16(uint16(n)),false) } + | uint16 { let n = lexemeTrimRightToInt32 args lexbuf 2 if n > 0xFFFF || n < 0 then fail args lexbuf (FSComp.SR.lexOutsideSixteenBitUnsigned()) (UINT16(0us)) else UINT16(uint16 n) } + | int '.' '.' { let s = removeUnderscores (lexemeTrimRight lexbuf 2) // Allow to parse as min_int. Allowed only because we parse '-' as an operator. @@ -291,6 +367,7 @@ rule token args skip = parse let n = try int32 s with _ -> fail args lexbuf (FSComp.SR.lexOutsideThirtyTwoBitSigned()) 0 INT32_DOT_DOT(n,false) } + | xint | int { let s = removeUnderscores (lexeme lexbuf) @@ -300,6 +377,7 @@ rule token args skip = parse try int32 s with _ -> fail args lexbuf (FSComp.SR.lexOutsideThirtyTwoBitSigned()) 0 INT32(n,false) } + | xint32 | int32 { let s = removeUnderscores (lexemeTrimRight lexbuf 1) @@ -351,9 +429,17 @@ rule token args skip = parse UNATIVEINT(uint64 (removeUnderscores (lexemeTrimRight lexbuf 2))) with _ -> fail args lexbuf (FSComp.SR.lexOutsideNativeUnsigned()) (UNATIVEINT(0UL)) } - | ieee32 - { IEEE32 (try float32(removeUnderscores (lexemeTrimRight lexbuf 1)) with _ -> fail args lexbuf (FSComp.SR.lexInvalidFloat()) 0.0f) } - | ieee64 + | ieee32 + { IEEE32 (evalFloat args lexbuf) } + + | ieee32_dotless_no_exponent + { if lexbuf.SupportsFeature LanguageFeature.DotlessFloat32Literal then + IEEE32 (evalFloat args lexbuf) + else + fail args lexbuf (FSComp.SR.lexInvalidFloat()) (IEEE32 0.0f) + } + + | ieee64 { IEEE64 (try float(lexeme lexbuf) with _ -> fail args lexbuf (FSComp.SR.lexInvalidFloat()) 0.0) } | decimal @@ -431,73 +517,79 @@ rule token args skip = parse UINT8 (byte(x)) } | '\'' hexGraphShort '\'' { CHAR (char (int32 (hexGraphShort (lexemeTrimBoth lexbuf 3 1)))) } + | '\'' unicodeGraphShort '\'' { CHAR (char (int32 (unicodeGraphShort (lexemeTrimBoth lexbuf 3 1)))) } + | '\'' unicodeGraphLong '\'' { match unicodeGraphLong (lexemeTrimBoth lexbuf 3 1) with | SingleChar(c) -> CHAR (char c) | _ -> fail args lexbuf (FSComp.SR.lexThisUnicodeOnlyInStringLiterals()) (CHAR (char 0)) } + | "(*IF-FSHARP" - { if not skip then (COMMENT (LexCont.Token !args.ifdefStack)) else token args skip lexbuf } + { if not skip then (COMMENT (LexCont.Token args.ifdefStack)) else token args skip lexbuf } + | "(*F#" - { if not skip then (COMMENT (LexCont.Token !args.ifdefStack)) else token args skip lexbuf } + { if not skip then (COMMENT (LexCont.Token args.ifdefStack)) else token args skip lexbuf } + | "ENDIF-FSHARP*)" - { if not skip then (COMMENT (LexCont.Token !args.ifdefStack)) else token args skip lexbuf } + { if not skip then (COMMENT (LexCont.Token args.ifdefStack)) else token args skip lexbuf } + | "F#*)" - { if not skip then (COMMENT (LexCont.Token !args.ifdefStack)) else token args skip lexbuf } + { if not skip then (COMMENT (LexCont.Token args.ifdefStack)) else token args skip lexbuf } | "(*)" { LPAREN_STAR_RPAREN } | "(*" { let m = lexbuf.LexemeRange - if not skip then (COMMENT (LexCont.Comment(!args.ifdefStack,1,m))) else comment (1,m,args) skip lexbuf } + if not skip then (COMMENT (LexCont.Comment(args.ifdefStack,1,m))) else comment (1,m,args) skip lexbuf } | "(*IF-CAML*)" | "(*IF-OCAML*)" { let m = lexbuf.LexemeRange - if not skip then (COMMENT (LexCont.MLOnly(!args.ifdefStack,m))) else mlOnly m args skip lexbuf } + if not skip then (COMMENT (LexCont.MLOnly(args.ifdefStack,m))) else mlOnly m args skip lexbuf } | '"' { let buf,fin,m = startString args lexbuf - if not skip then (STRING_TEXT (LexCont.String(!args.ifdefStack,m))) else string (buf,fin,m,args) skip lexbuf } + if not skip then (STRING_TEXT (LexCont.String(args.ifdefStack,m))) else string (buf,fin,m,args) skip lexbuf } | '"' '"' '"' { let buf,fin,m = startString args lexbuf - if not skip then (STRING_TEXT (LexCont.TripleQuoteString(!args.ifdefStack,m))) else tripleQuoteString (buf,fin,m,args) skip lexbuf } + if not skip then (STRING_TEXT (LexCont.TripleQuoteString(args.ifdefStack,m))) else tripleQuoteString (buf,fin,m,args) skip lexbuf } | '$' '"' - { fail args lexbuf (FSComp.SR.lexTokenReserved()) (WHITESPACE (LexCont.Token !args.ifdefStack)) } + { fail args lexbuf (FSComp.SR.lexTokenReserved()) (WHITESPACE (LexCont.Token args.ifdefStack)) } | '@' '"' { let buf,fin,m = startString args lexbuf - if not skip then (STRING_TEXT (LexCont.VerbatimString(!args.ifdefStack,m))) else verbatimString (buf,fin,m,args) skip lexbuf } + if not skip then (STRING_TEXT (LexCont.VerbatimString(args.ifdefStack,m))) else verbatimString (buf,fin,m,args) skip lexbuf } | truewhite+ { if skip then token args skip lexbuf - else WHITESPACE (LexCont.Token !args.ifdefStack) } + else WHITESPACE (LexCont.Token args.ifdefStack) } | offwhite+ { if args.lightSyntaxStatus.Status then errorR(Error(FSComp.SR.lexTabsNotAllowed(),lexbuf.LexemeRange)) - if not skip then (WHITESPACE (LexCont.Token !args.ifdefStack)) else token args skip lexbuf } + if not skip then (WHITESPACE (LexCont.Token args.ifdefStack)) else token args skip lexbuf } | "////" op_char* { // 4+ slash are 1-line comments, online 3 slash are XmlDoc let m = lexbuf.LexemeRange - if not skip then (LINE_COMMENT (LexCont.SingleLineComment(!args.ifdefStack,1,m))) else singleLineComment (None,1,m,args) skip lexbuf } + if not skip then (LINE_COMMENT (LexCont.SingleLineComment(args.ifdefStack,1,m))) else singleLineComment (None,1,m,args) skip lexbuf } | "///" op_char* { // Match exactly 3 slash, 4+ slash caught by preceding rule let m = lexbuf.LexemeRange let doc = lexemeTrimLeft lexbuf 3 let sb = (new StringBuilder(100)).Append(doc) - if not skip then (LINE_COMMENT (LexCont.SingleLineComment(!args.ifdefStack,1,m))) else singleLineComment (Some sb,1,m,args) skip lexbuf } + if not skip then (LINE_COMMENT (LexCont.SingleLineComment(args.ifdefStack,1,m))) else singleLineComment (Some sb,1,m,args) skip lexbuf } | "//" op_char* { // Need to read all operator symbols too, otherwise it might be parsed by a rule below let m = lexbuf.LexemeRange - if not skip then (LINE_COMMENT (LexCont.SingleLineComment(!args.ifdefStack,1,m))) else singleLineComment (None,1,m,args) skip lexbuf } + if not skip then (LINE_COMMENT (LexCont.SingleLineComment(args.ifdefStack,1,m))) else singleLineComment (None,1,m,args) skip lexbuf } | newline - { newline lexbuf; if not skip then (WHITESPACE (LexCont.Token !args.ifdefStack)) else token args skip lexbuf } + { newline lexbuf; if not skip then (WHITESPACE (LexCont.Token args.ifdefStack)) else token args skip lexbuf } | '`' '`' ([^'`' '\n' '\r' '\t'] | '`' [^'`''\n' '\r' '\t']) + '`' '`' { Keywords.IdentifierToken args lexbuf (lexemeTrimBoth lexbuf 2 2) } @@ -542,75 +634,141 @@ rule token args skip = parse // Construct the new position if args.applyLineDirectives then lexbuf.EndPos <- pos.ApplyLineDirective((match file with Some f -> fileIndexOfFile f | None -> pos.FileIndex), line) - + else + // add a newline when we don't apply a directive since we consumed a newline getting here + newline lexbuf token args skip lexbuf - else - if not skip then (HASH_LINE (LexCont.Token !args.ifdefStack)) else token args skip lexbuf } + else + // add a newline when we don't apply a directive since we consumed a newline getting here + newline lexbuf + (HASH_LINE (LexCont.Token args.ifdefStack)) } | "<@" { checkExprOp lexbuf; LQUOTE ("<@ @>", false) } + | "<@@" { checkExprOp lexbuf; LQUOTE ("<@@ @@>", true) } + | "@>" { checkExprOp lexbuf; RQUOTE ("<@ @>", false) } + | "@@>" { checkExprOp lexbuf; RQUOTE ("<@@ @@>", true) } + | '#' { HASH } + | '&' { AMP } + | "&&" { AMP_AMP } + | "||" { BAR_BAR } + | '\'' { QUOTE } + | '(' { LPAREN } + | ')' { RPAREN } + | '*' { STAR } + | ',' { COMMA } + | "->" { RARROW } + | "?" { QMARK } + | "??" { QMARK_QMARK } + | ".." { DOT_DOT } + + | "..^" { DOT_DOT_HAT } + | "." { DOT } + | ":" { COLON } + | "::" { COLON_COLON } + | ":>" { COLON_GREATER } + | "@>." { RQUOTE_DOT ("<@ @>",false) } + | "@@>." { RQUOTE_DOT ("<@@ @@>",true) } + | ">|]" { GREATER_BAR_RBRACK } + | ":?>" { COLON_QMARK_GREATER } + | ":?" { COLON_QMARK } + | ":=" { COLON_EQUALS } + | ";;" { SEMICOLON_SEMICOLON } + | ";" { SEMICOLON } + | "<-" { LARROW } + | "=" { EQUALS } + | "[" { LBRACK } + | "[|" { LBRACK_BAR } + | "{|" { LBRACE_BAR } + | "<" { LESS false } + | ">" { GREATER false } + | "[<" { LBRACK_LESS } + | "]" { RBRACK } + | "|]" { BAR_RBRACK } + | "|}" { BAR_RBRACE } + | ">]" { GREATER_RBRACK } + | "{" { LBRACE } + | "|" { BAR } + | "}" { RBRACE } + | "$" { DOLLAR } + | "%" { PERCENT_OP("%") } + | "%%" { PERCENT_OP("%%") } + | "-" { MINUS } + | "~" { RESERVED } + | "`" { RESERVED } + | ignored_op_char* '*' '*' op_char* { checkExprOp lexbuf; INFIX_STAR_STAR_OP(lexeme lexbuf) } + | ignored_op_char* ('*' | '/'|'%') op_char* { checkExprOp lexbuf; INFIX_STAR_DIV_MOD_OP(lexeme lexbuf) } + | ignored_op_char* ('+'|'-') op_char* { checkExprOp lexbuf; PLUS_MINUS_OP(lexeme lexbuf) } + | ignored_op_char* ('@'|'^') op_char* { checkExprOp lexbuf; INFIX_AT_HAT_OP(lexeme lexbuf) } + | ignored_op_char* ('=' | "!=" | '<' | '>' | '$') op_char* { checkExprOp lexbuf; INFIX_COMPARE_OP(lexeme lexbuf) } + | ignored_op_char* ('&') op_char* { checkExprOp lexbuf; INFIX_AMP_OP(lexeme lexbuf) } + | ignored_op_char* '|' op_char* { checkExprOp lexbuf; INFIX_BAR_OP(lexeme lexbuf) } + | ignored_op_char* ('!' | '~' ) op_char* { checkExprOp lexbuf; PREFIX_OP(lexeme lexbuf) } + | ".[]" | ".[]<-" | ".[,]<-" | ".[,,]<-" | ".[,,,]<-" | ".[,,,]" | ".[,,]" | ".[,]" | ".[..]" | ".[..,..]" | ".[..,..,..]" | ".[..,..,..,..]" + | ".()" | ".()<-" { FUNKY_OPERATOR_NAME(lexeme lexbuf) } + | "#!" op_char* { // Treat shebangs like regular comments, but they are only allowed at the start of a file let m = lexbuf.LexemeRange - let tok = shouldStartFile args lexbuf m (0,FSComp.SR.lexHashBangMustBeFirstInFile()) (LINE_COMMENT (LexCont.SingleLineComment(!args.ifdefStack,1,m))) + let tok = shouldStartFile args lexbuf m (0,FSComp.SR.lexHashBangMustBeFirstInFile()) (LINE_COMMENT (LexCont.SingleLineComment(args.ifdefStack,1,m))) if not skip then tok else singleLineComment (None,1,m,args) skip lexbuf } | "#light" anywhite* @@ -619,59 +777,61 @@ rule token args skip = parse warning(Error((0,"#light should only occur as the first non-comment text in an F# source file"),lexbuf.LexemeRange)) // TODO unreachable error above, I think? - brianmcn args.lightSyntaxStatus.Status <- true - if not skip then (HASH_LIGHT (LexCont.Token !args.ifdefStack)) else token args skip lexbuf } + if not skip then (HASH_LIGHT (LexCont.Token args.ifdefStack)) else token args skip lexbuf } | ("#indent" | "#light") anywhite+ "\"off\"" { args.lightSyntaxStatus.Status <- false mlCompatWarning (FSComp.SR.lexIndentOffForML()) lexbuf.LexemeRange - if not skip then (HASH_LIGHT (LexCont.Token !args.ifdefStack)) else token args skip lexbuf } + if not skip then (HASH_LIGHT (LexCont.Token args.ifdefStack)) else token args skip lexbuf } | anywhite* "#if" anywhite+ anystring { let m = lexbuf.LexemeRange let lookup id = List.contains id args.defines let lexed = lexeme lexbuf - let isTrue = evalIfDefExpression lexbuf.StartPos args lookup lexed - args.ifdefStack := (IfDefIf,m) :: !(args.ifdefStack) + let isTrue = evalIfDefExpression lexbuf.StartPos lexbuf.SupportsFeature args lookup lexed + args.ifdefStack <- (IfDefIf,m) :: args.ifdefStack // Get the token; make sure it starts at zero position & return let cont, f = - ( if isTrue then (LexCont.EndLine(LexerEndlineContinuation.Token(!args.ifdefStack)), endline (LexerEndlineContinuation.Token !args.ifdefStack) args skip) - else (LexCont.EndLine(LexerEndlineContinuation.Skip(!args.ifdefStack,0,m)), endline (LexerEndlineContinuation.Skip(!args.ifdefStack,0,m)) args skip) ) + ( if isTrue then (LexCont.EndLine(LexerEndlineContinuation.Token(args.ifdefStack)), endline (LexerEndlineContinuation.Token args.ifdefStack) args skip) + else (LexCont.EndLine(LexerEndlineContinuation.Skip(args.ifdefStack,0,m)), endline (LexerEndlineContinuation.Skip(args.ifdefStack,0,m)) args skip) ) let tok = shouldStartLine args lexbuf m (FSComp.SR.lexHashIfMustBeFirst()) (HASH_IF(m,lexed,cont)) if not skip then tok else f lexbuf } | anywhite* "#else" anywhite* ("//" [^'\n''\r']*)? { let lexed = (lexeme lexbuf) - match !(args.ifdefStack) with + match args.ifdefStack with | [] -> LEX_FAILURE (FSComp.SR.lexHashElseNoMatchingIf()) | (IfDefElse,_) :: _rest -> LEX_FAILURE (FSComp.SR.lexHashEndifRequiredForElse()) | (IfDefIf,_) :: rest -> let m = lexbuf.LexemeRange - args.ifdefStack := (IfDefElse,m) :: rest - let tok = HASH_ELSE(m,lexed, LexCont.EndLine(LexerEndlineContinuation.Skip(!args.ifdefStack,0,m))) + args.ifdefStack <- (IfDefElse,m) :: rest + let tok = HASH_ELSE(m,lexed, LexCont.EndLine(LexerEndlineContinuation.Skip(args.ifdefStack,0,m))) let tok = shouldStartLine args lexbuf m (FSComp.SR.lexHashElseMustBeFirst()) tok - if not skip then tok else endline (LexerEndlineContinuation.Skip(!args.ifdefStack,0,m)) args skip lexbuf } + if not skip then tok else endline (LexerEndlineContinuation.Skip(args.ifdefStack,0,m)) args skip lexbuf } | anywhite* "#endif" anywhite* ("//" [^'\n''\r']*)? { let lexed = (lexeme lexbuf) let m = lexbuf.LexemeRange - match !(args.ifdefStack) with + match args.ifdefStack with | []-> LEX_FAILURE (FSComp.SR.lexHashEndingNoMatchingIf()) | _ :: rest -> - args.ifdefStack := rest - let tok = HASH_ENDIF(m,lexed,LexCont.EndLine(LexerEndlineContinuation.Token(!args.ifdefStack))) + args.ifdefStack <- rest + let tok = HASH_ENDIF(m,lexed,LexCont.EndLine(LexerEndlineContinuation.Token(args.ifdefStack))) let tok = shouldStartLine args lexbuf m (FSComp.SR.lexHashEndifMustBeFirst()) tok - if not skip then tok else endline (LexerEndlineContinuation.Token(!args.ifdefStack)) args skip lexbuf } + if not skip then tok else endline (LexerEndlineContinuation.Token(args.ifdefStack)) args skip lexbuf } | "#if" - { let tok = fail args lexbuf (FSComp.SR.lexHashIfMustHaveIdent()) (WHITESPACE (LexCont.Token !args.ifdefStack)) + { let tok = fail args lexbuf (FSComp.SR.lexHashIfMustHaveIdent()) (WHITESPACE (LexCont.Token args.ifdefStack)) if not skip then tok else token args skip lexbuf } | surrogateChar surrogateChar + | _ { unexpectedChar lexbuf } + | eof - { EOF (LexCont.Token !args.ifdefStack) } + { EOF (LexCont.Token args.ifdefStack) } // Skips INACTIVE code until if finds #else / #endif matching with the #if or #else @@ -681,10 +841,10 @@ and ifdefSkip n m args skip = parse // If #if is the first thing on the line then increase depth, otherwise skip, because it is invalid (e.g. "(**) #if ...") if (m.StartColumn <> 0) then - if not skip then (INACTIVECODE (LexCont.IfDefSkip(!args.ifdefStack,n,m))) else ifdefSkip n m args skip lexbuf + if not skip then (INACTIVECODE (LexCont.IfDefSkip(args.ifdefStack,n,m))) else ifdefSkip n m args skip lexbuf else - let tok = INACTIVECODE(LexCont.EndLine(LexerEndlineContinuation.Skip(!args.ifdefStack,n+1,m))) - if not skip then tok else endline (LexerEndlineContinuation.Skip(!args.ifdefStack,n+1,m)) args skip lexbuf } + let tok = INACTIVECODE(LexCont.EndLine(LexerEndlineContinuation.Skip(args.ifdefStack,n+1,m))) + if not skip then tok else endline (LexerEndlineContinuation.Skip(args.ifdefStack,n+1,m)) args skip lexbuf } | anywhite* "#else" anywhite* ("//" [^'\n''\r']*)? { let lexed = (lexeme lexbuf) @@ -692,17 +852,17 @@ and ifdefSkip n m args skip = parse // If #else is the first thing on the line then process it, otherwise ignore, because it is invalid (e.g. "(**) #else ...") if (m.StartColumn <> 0) then - if not skip then (INACTIVECODE (LexCont.IfDefSkip(!args.ifdefStack,n,m))) else ifdefSkip n m args skip lexbuf + if not skip then (INACTIVECODE (LexCont.IfDefSkip(args.ifdefStack,n,m))) else ifdefSkip n m args skip lexbuf elif n = 0 then - match !(args.ifdefStack) with + match args.ifdefStack with | []-> LEX_FAILURE (FSComp.SR.lexHashElseNoMatchingIf()) | (IfDefElse,_) :: _rest -> LEX_FAILURE (FSComp.SR.lexHashEndifRequiredForElse()) | (IfDefIf,_) :: rest -> let m = lexbuf.LexemeRange - args.ifdefStack := (IfDefElse,m) :: rest - if not skip then (HASH_ELSE(m,lexed,LexCont.EndLine(LexerEndlineContinuation.Token(!args.ifdefStack)))) else endline (LexerEndlineContinuation.Token(!args.ifdefStack)) args skip lexbuf + args.ifdefStack <- (IfDefElse,m) :: rest + if not skip then (HASH_ELSE(m,lexed,LexCont.EndLine(LexerEndlineContinuation.Token(args.ifdefStack)))) else endline (LexerEndlineContinuation.Token(args.ifdefStack)) args skip lexbuf else - if not skip then (INACTIVECODE(LexCont.EndLine(LexerEndlineContinuation.Skip(!args.ifdefStack,n,m)))) else endline (LexerEndlineContinuation.Skip(!args.ifdefStack,n,m)) args skip lexbuf } + if not skip then (INACTIVECODE(LexCont.EndLine(LexerEndlineContinuation.Skip(args.ifdefStack,n,m)))) else endline (LexerEndlineContinuation.Skip(args.ifdefStack,n,m)) args skip lexbuf } | anywhite* "#endif" anywhite* ("//" [^'\n''\r']*)? { let lexed = lexeme lexbuf @@ -710,29 +870,33 @@ and ifdefSkip n m args skip = parse // If #endif is the first thing on the line then process it, otherwise ignore, because it is invalid (e.g. "(**) #endif ...") if (m.StartColumn <> 0) then - if not skip then (INACTIVECODE (LexCont.IfDefSkip(!args.ifdefStack,n,m))) else ifdefSkip n m args skip lexbuf + if not skip then (INACTIVECODE (LexCont.IfDefSkip(args.ifdefStack,n,m))) else ifdefSkip n m args skip lexbuf elif n = 0 then - match !(args.ifdefStack) with + match args.ifdefStack with | [] -> LEX_FAILURE (FSComp.SR.lexHashEndingNoMatchingIf()) | _ :: rest -> - args.ifdefStack := rest - if not skip then (HASH_ENDIF(m,lexed,LexCont.EndLine(LexerEndlineContinuation.Token(!args.ifdefStack)))) else endline (LexerEndlineContinuation.Token(!args.ifdefStack)) args skip lexbuf + args.ifdefStack <- rest + if not skip then (HASH_ENDIF(m,lexed,LexCont.EndLine(LexerEndlineContinuation.Token(args.ifdefStack)))) else endline (LexerEndlineContinuation.Token(args.ifdefStack)) args skip lexbuf else - let tok = INACTIVECODE(LexCont.EndLine(LexerEndlineContinuation.Skip(!args.ifdefStack,n-1,m))) + let tok = INACTIVECODE(LexCont.EndLine(LexerEndlineContinuation.Skip(args.ifdefStack,n-1,m))) let tok = shouldStartLine args lexbuf m (FSComp.SR.lexWrongNestedHashEndif()) tok - if not skip then tok else endline (LexerEndlineContinuation.Skip(!args.ifdefStack,(n-1),m)) args skip lexbuf } + if not skip then tok else endline (LexerEndlineContinuation.Skip(args.ifdefStack,(n-1),m)) args skip lexbuf } | newline { newline lexbuf; ifdefSkip n m args skip lexbuf } | [^ ' ' '\n' '\r' ]+ + | anywhite+ + | surrogateChar surrogateChar + | _ { // This tries to be nice and get tokens as 'words' because VS uses this when selecting stuff - if not skip then (INACTIVECODE (LexCont.IfDefSkip(!args.ifdefStack,n,m))) else ifdefSkip n m args skip lexbuf } + if not skip then (INACTIVECODE (LexCont.IfDefSkip(args.ifdefStack,n,m))) else ifdefSkip n m args skip lexbuf } + | eof - { EOF (LexCont.IfDefSkip(!args.ifdefStack,n,m)) } + { EOF (LexCont.IfDefSkip(args.ifdefStack,n,m)) } // Called after lexing #if IDENT/#else/#endif - this checks whether there is nothing except end of line // or end of file and then calls the lexing function specified by 'cont' - either token or ifdefSkip @@ -743,47 +907,50 @@ and endline cont args skip = parse | LexerEndlineContinuation.Token(ifdefStack) -> if not skip then (WHITESPACE(LexCont.Token ifdefStack)) else token args skip lexbuf | LexerEndlineContinuation.Skip(ifdefStack, n, m) -> if not skip then (INACTIVECODE (LexCont.IfDefSkip(ifdefStack,n,m))) else ifdefSkip n m args skip lexbuf } + | eof { match cont with | LexerEndlineContinuation.Token(ifdefStack) -> (EOF(LexCont.Token ifdefStack)) | LexerEndlineContinuation.Skip(ifdefStack, n, m) -> (EOF(LexCont.IfDefSkip(ifdefStack,n,m))) } + | [^'\r' '\n']+ + | _ - { let tok = fail args lexbuf (FSComp.SR.pplexExpectedSingleLineComment()) (WHITESPACE (LexCont.Token !args.ifdefStack)) + { let tok = fail args lexbuf (FSComp.SR.pplexExpectedSingleLineComment()) (WHITESPACE (LexCont.Token args.ifdefStack)) if not skip then tok else token args skip lexbuf } and string sargs skip = parse | '\\' newline anywhite* { let (_buf,_fin,m,args) = sargs newline lexbuf - if not skip then (STRING_TEXT (LexCont.String(!args.ifdefStack,m))) else string sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.String(args.ifdefStack,m))) else string sargs skip lexbuf } | escape_char { let (buf,_fin,m,args) = sargs addByteChar buf (escape (lexeme lexbuf).[1]) - if not skip then (STRING_TEXT (LexCont.String(!args.ifdefStack,m))) else string sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.String(args.ifdefStack,m))) else string sargs skip lexbuf } | trigraph { let (buf,_fin,m,args) = sargs let s = lexeme lexbuf addByteChar buf (trigraph s.[1] s.[2] s.[3]) - if not skip then (STRING_TEXT (LexCont.String(!args.ifdefStack,m))) else string sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.String(args.ifdefStack,m))) else string sargs skip lexbuf } | hexGraphShort { let (buf,_fin,m,args) = sargs addUnicodeChar buf (int (hexGraphShort (lexemeTrimLeft lexbuf 2))) - if not skip then (STRING_TEXT (LexCont.String(!args.ifdefStack,m))) else string sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.String(args.ifdefStack,m))) else string sargs skip lexbuf } | unicodeGraphShort { let (buf,_fin,m,args) = sargs addUnicodeChar buf (int (unicodeGraphShort (lexemeTrimLeft lexbuf 2))) - if not skip then (STRING_TEXT (LexCont.String(!args.ifdefStack,m))) else string sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.String(args.ifdefStack,m))) else string sargs skip lexbuf } | unicodeGraphLong { let (buf,_fin,m,args) = sargs let hexChars = lexemeTrimLeft lexbuf 2 - let result () = if not skip then (STRING_TEXT (LexCont.String(!args.ifdefStack,m))) else string sargs skip lexbuf + let result () = if not skip then (STRING_TEXT (LexCont.String(args.ifdefStack,m))) else string sargs skip lexbuf match unicodeGraphLong hexChars with | Invalid -> fail args lexbuf (FSComp.SR.lexInvalidUnicodeLiteral hexChars) (result ()) @@ -809,38 +976,40 @@ and string sargs skip = parse { let (buf,_fin,m,args) = sargs newline lexbuf addUnicodeString buf (lexeme lexbuf) - if not skip then (STRING_TEXT (LexCont.String(!args.ifdefStack,m))) else string sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.String(args.ifdefStack,m))) else string sargs skip lexbuf } | ident { let (buf,_fin,m,args) = sargs addUnicodeString buf (lexeme lexbuf) - if not skip then (STRING_TEXT (LexCont.String(!args.ifdefStack,m))) else string sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.String(args.ifdefStack,m))) else string sargs skip lexbuf } | integer | xinteger { let (buf,_fin,m,args) = sargs addUnicodeString buf (lexeme lexbuf) - if not skip then (STRING_TEXT (LexCont.String(!args.ifdefStack,m))) else string sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.String(args.ifdefStack,m))) else string sargs skip lexbuf } | anywhite + { let (buf,_fin,m,args) = sargs addUnicodeString buf (lexeme lexbuf) - if not skip then (STRING_TEXT (LexCont.String(!args.ifdefStack,m))) else string sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.String(args.ifdefStack,m))) else string sargs skip lexbuf } | eof { let (_buf,_fin,m,args) = sargs - EOF (LexCont.String(!args.ifdefStack,m)) } + EOF (LexCont.String(args.ifdefStack,m)) } + | surrogateChar surrogateChar // surrogate code points always come in pairs + | _ { let (buf,_fin,m,args) = sargs addUnicodeString buf (lexeme lexbuf) - if not skip then (STRING_TEXT (LexCont.String(!args.ifdefStack,m))) else string sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.String(args.ifdefStack,m))) else string sargs skip lexbuf } and verbatimString sargs skip = parse | '"' '"' { let (buf,_fin,m,args) = sargs addByteChar buf '\"' - if not skip then (STRING_TEXT (LexCont.VerbatimString(!args.ifdefStack,m))) else verbatimString sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.VerbatimString(args.ifdefStack,m))) else verbatimString sargs skip lexbuf } | '"' { let (buf,fin,_m,_args) = sargs @@ -856,32 +1025,32 @@ and verbatimString sargs skip = parse { let (buf,_fin,m,args) = sargs newline lexbuf addUnicodeString buf (lexeme lexbuf) - if not skip then (STRING_TEXT (LexCont.VerbatimString(!args.ifdefStack,m))) else verbatimString sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.VerbatimString(args.ifdefStack,m))) else verbatimString sargs skip lexbuf } | ident { let (buf,_fin,m,args) = sargs addUnicodeString buf (lexeme lexbuf) - if not skip then (STRING_TEXT (LexCont.VerbatimString(!args.ifdefStack,m))) else verbatimString sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.VerbatimString(args.ifdefStack,m))) else verbatimString sargs skip lexbuf } | integer | xinteger { let (buf,_fin,m,args) = sargs addUnicodeString buf (lexeme lexbuf) - if not skip then (STRING_TEXT (LexCont.VerbatimString(!args.ifdefStack,m))) else verbatimString sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.VerbatimString(args.ifdefStack,m))) else verbatimString sargs skip lexbuf } | anywhite + { let (buf,_fin,m,args) = sargs addUnicodeString buf (lexeme lexbuf) - if not skip then (STRING_TEXT (LexCont.VerbatimString(!args.ifdefStack,m))) else verbatimString sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.VerbatimString(args.ifdefStack,m))) else verbatimString sargs skip lexbuf } | eof { let (_buf,_fin,m,args) = sargs - EOF (LexCont.VerbatimString(!args.ifdefStack,m)) } + EOF (LexCont.VerbatimString(args.ifdefStack,m)) } | surrogateChar surrogateChar // surrogate code points always come in pairs | _ { let (buf,_fin,m,args) = sargs addUnicodeString buf (lexeme lexbuf) - if not skip then (STRING_TEXT (LexCont.VerbatimString(!args.ifdefStack,m))) else verbatimString sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.VerbatimString(args.ifdefStack,m))) else verbatimString sargs skip lexbuf } and tripleQuoteString sargs skip = parse | '"' '"' '"' @@ -893,33 +1062,34 @@ and tripleQuoteString sargs skip = parse { let (buf,_fin,m,args) = sargs newline lexbuf addUnicodeString buf (lexeme lexbuf) - if not skip then (STRING_TEXT (LexCont.TripleQuoteString(!args.ifdefStack,m))) else tripleQuoteString sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.TripleQuoteString(args.ifdefStack,m))) else tripleQuoteString sargs skip lexbuf } // The rest is to break into pieces to allow double-click-on-word and other such things | ident { let (buf,_fin,m,args) = sargs addUnicodeString buf (lexeme lexbuf) - if not skip then (STRING_TEXT (LexCont.TripleQuoteString(!args.ifdefStack,m))) else tripleQuoteString sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.TripleQuoteString(args.ifdefStack,m))) else tripleQuoteString sargs skip lexbuf } | integer | xinteger { let (buf,_fin,m,args) = sargs addUnicodeString buf (lexeme lexbuf) - if not skip then (STRING_TEXT (LexCont.TripleQuoteString(!args.ifdefStack,m))) else tripleQuoteString sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.TripleQuoteString(args.ifdefStack,m))) else tripleQuoteString sargs skip lexbuf } | anywhite + { let (buf,_fin,m,args) = sargs addUnicodeString buf (lexeme lexbuf) - if not skip then (STRING_TEXT (LexCont.TripleQuoteString(!args.ifdefStack,m))) else tripleQuoteString sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.TripleQuoteString(args.ifdefStack,m))) else tripleQuoteString sargs skip lexbuf } | eof { let (_buf,_fin,m,args) = sargs - EOF (LexCont.TripleQuoteString(!args.ifdefStack,m)) } + EOF (LexCont.TripleQuoteString(args.ifdefStack,m)) } + | surrogateChar surrogateChar // surrogate code points always come in pairs | _ { let (buf,_fin,m,args) = sargs addUnicodeString buf (lexeme lexbuf) - if not skip then (STRING_TEXT (LexCont.TripleQuoteString(!args.ifdefStack,m))) else tripleQuoteString sargs skip lexbuf } + if not skip then (STRING_TEXT (LexCont.TripleQuoteString(args.ifdefStack,m))) else tripleQuoteString sargs skip lexbuf } // Parsing single-line comment - we need to split it into words for Visual Studio IDE and singleLineComment cargs skip = parse @@ -928,78 +1098,78 @@ and singleLineComment cargs skip = parse trySaveXmlDoc lexbuf buff newline lexbuf // Saves the documentation (if we're collecting any) into a buffer-local variable. - if not skip then (LINE_COMMENT (LexCont.Token !args.ifdefStack)) else token args skip lexbuf } + if not skip then (LINE_COMMENT (LexCont.Token args.ifdefStack)) else token args skip lexbuf } | eof { let _, _n,_m,args = cargs // NOTE: it is legal to end a file with this comment, so we'll return EOF as a token - EOF (LexCont.Token !args.ifdefStack) } + EOF (LexCont.Token args.ifdefStack) } | [^ ' ' '\n' '\r' ]+ | anywhite+ { let buff,n,m,args = cargs // Append the current token to the XML documentation if we're collecting it tryAppendXmlDoc buff (lexeme lexbuf) - if not skip then (LINE_COMMENT (LexCont.SingleLineComment(!args.ifdefStack,n,m))) else singleLineComment (buff,n,m,args) skip lexbuf } + if not skip then (LINE_COMMENT (LexCont.SingleLineComment(args.ifdefStack,n,m))) else singleLineComment (buff,n,m,args) skip lexbuf } | surrogateChar surrogateChar | _ { let _, _n,_m,args = cargs - if not skip then (LINE_COMMENT (LexCont.Token !args.ifdefStack)) else token args skip lexbuf } + if not skip then (LINE_COMMENT (LexCont.Token args.ifdefStack)) else token args skip lexbuf } and comment cargs skip = parse | char { let n,m,args = cargs - if not skip then (COMMENT (LexCont.Comment(!args.ifdefStack,n,m))) else comment (n,m,args) skip lexbuf } + if not skip then (COMMENT (LexCont.Comment(args.ifdefStack,n,m))) else comment (n,m,args) skip lexbuf } | '"' { let n,m,args = cargs - if not skip then (COMMENT (LexCont.StringInComment(!args.ifdefStack,n,m))) else stringInComment n m args skip lexbuf } + if not skip then (COMMENT (LexCont.StringInComment(args.ifdefStack,n,m))) else stringInComment n m args skip lexbuf } | '"' '"' '"' { let n,m,args = cargs - if not skip then (COMMENT (LexCont.TripleQuoteStringInComment(!args.ifdefStack,n,m))) else tripleQuoteStringInComment n m args skip lexbuf } + if not skip then (COMMENT (LexCont.TripleQuoteStringInComment(args.ifdefStack,n,m))) else tripleQuoteStringInComment n m args skip lexbuf } | '@' '"' { let n,m,args = cargs - if not skip then (COMMENT (LexCont.VerbatimStringInComment(!args.ifdefStack,n,m))) else verbatimStringInComment n m args skip lexbuf } + if not skip then (COMMENT (LexCont.VerbatimStringInComment(args.ifdefStack,n,m))) else verbatimStringInComment n m args skip lexbuf } | "(*)" { let n,m,args = cargs - if not skip then (COMMENT (LexCont.Comment(!args.ifdefStack,n,m))) else comment cargs skip lexbuf } + if not skip then (COMMENT (LexCont.Comment(args.ifdefStack,n,m))) else comment cargs skip lexbuf } | '(' '*' { let n,m,args = cargs - if not skip then (COMMENT (LexCont.Comment(!args.ifdefStack,n+1,m))) else comment (n+1,m,args) skip lexbuf } + if not skip then (COMMENT (LexCont.Comment(args.ifdefStack,n+1,m))) else comment (n+1,m,args) skip lexbuf } | newline { let n,m,args = cargs newline lexbuf - if not skip then (COMMENT (LexCont.Comment(!args.ifdefStack,n,m))) else comment cargs skip lexbuf } + if not skip then (COMMENT (LexCont.Comment(args.ifdefStack,n,m))) else comment cargs skip lexbuf } | "*)" { let n,m,args = cargs - if n > 1 then if not skip then (COMMENT (LexCont.Comment(!args.ifdefStack,n-1,m))) else comment (n-1,m,args) skip lexbuf - else if not skip then (COMMENT (LexCont.Token !args.ifdefStack)) else token args skip lexbuf } + if n > 1 then if not skip then (COMMENT (LexCont.Comment(args.ifdefStack,n-1,m))) else comment (n-1,m,args) skip lexbuf + else if not skip then (COMMENT (LexCont.Token args.ifdefStack)) else token args skip lexbuf } | anywhite+ | [^ '\'' '(' '*' '\n' '\r' '"' ')' '@' ' ' '\t' ]+ { let n,m,args = cargs - if not skip then (COMMENT (LexCont.Comment(!args.ifdefStack,n,m))) else comment cargs skip lexbuf } + if not skip then (COMMENT (LexCont.Comment(args.ifdefStack,n,m))) else comment cargs skip lexbuf } | eof { let n,m,args = cargs - EOF (LexCont.Comment(!args.ifdefStack,n,m)) } + EOF (LexCont.Comment(args.ifdefStack,n,m)) } | surrogateChar surrogateChar | _ { let n,m,args = cargs - if not skip then (COMMENT (LexCont.Comment(!args.ifdefStack,n,m))) else comment (n,m,args) skip lexbuf } + if not skip then (COMMENT (LexCont.Comment(args.ifdefStack,n,m))) else comment (n,m,args) skip lexbuf } and stringInComment n m args skip = parse // Follow string lexing, skipping tokens until it finishes | '\\' newline anywhite* { newline lexbuf - if not skip then (COMMENT (LexCont.StringInComment(!args.ifdefStack,n,m))) else stringInComment n m args skip lexbuf } + if not skip then (COMMENT (LexCont.StringInComment(args.ifdefStack,n,m))) else stringInComment n m args skip lexbuf } | escape_char | trigraph @@ -1010,69 +1180,69 @@ and stringInComment n m args skip = parse | integer | xinteger | anywhite + - { if not skip then (COMMENT (LexCont.StringInComment(!args.ifdefStack,n,m))) else stringInComment n m args skip lexbuf } + { if not skip then (COMMENT (LexCont.StringInComment(args.ifdefStack,n,m))) else stringInComment n m args skip lexbuf } | '"' - { if not skip then (COMMENT (LexCont.Comment(!args.ifdefStack,n,m))) else comment (n,m,args) skip lexbuf } + { if not skip then (COMMENT (LexCont.Comment(args.ifdefStack,n,m))) else comment (n,m,args) skip lexbuf } | newline { newline lexbuf - if not skip then (COMMENT (LexCont.StringInComment(!args.ifdefStack,n,m))) else stringInComment n m args skip lexbuf } + if not skip then (COMMENT (LexCont.StringInComment(args.ifdefStack,n,m))) else stringInComment n m args skip lexbuf } | eof - { EOF (LexCont.StringInComment(!args.ifdefStack,n,m)) } + { EOF (LexCont.StringInComment(args.ifdefStack,n,m)) } | surrogateChar surrogateChar | _ - { if not skip then (COMMENT (LexCont.StringInComment(!args.ifdefStack,n,m))) else stringInComment n m args skip lexbuf } + { if not skip then (COMMENT (LexCont.StringInComment(args.ifdefStack,n,m))) else stringInComment n m args skip lexbuf } and verbatimStringInComment n m args skip = parse // Follow verbatimString lexing, in short, skip double-quotes and other chars until we hit a single quote | '"' '"' - { if not skip then (COMMENT (LexCont.VerbatimStringInComment(!args.ifdefStack,n,m))) else verbatimStringInComment n m args skip lexbuf } + { if not skip then (COMMENT (LexCont.VerbatimStringInComment(args.ifdefStack,n,m))) else verbatimStringInComment n m args skip lexbuf } | '"' - { if not skip then (COMMENT (LexCont.Comment(!args.ifdefStack,n,m))) else comment (n,m,args) skip lexbuf } + { if not skip then (COMMENT (LexCont.Comment(args.ifdefStack,n,m))) else comment (n,m,args) skip lexbuf } | ident | integer | xinteger | anywhite + - { if not skip then (COMMENT (LexCont.VerbatimStringInComment(!args.ifdefStack,n,m))) else verbatimStringInComment n m args skip lexbuf } + { if not skip then (COMMENT (LexCont.VerbatimStringInComment(args.ifdefStack,n,m))) else verbatimStringInComment n m args skip lexbuf } | newline { newline lexbuf - if not skip then (COMMENT (LexCont.VerbatimStringInComment(!args.ifdefStack,n,m))) else verbatimStringInComment n m args skip lexbuf } + if not skip then (COMMENT (LexCont.VerbatimStringInComment(args.ifdefStack,n,m))) else verbatimStringInComment n m args skip lexbuf } | eof - { EOF (LexCont.VerbatimStringInComment(!args.ifdefStack,n,m)) } + { EOF (LexCont.VerbatimStringInComment(args.ifdefStack,n,m)) } | surrogateChar surrogateChar | _ - { if not skip then (COMMENT (LexCont.VerbatimStringInComment(!args.ifdefStack,n,m))) else verbatimStringInComment n m args skip lexbuf } + { if not skip then (COMMENT (LexCont.VerbatimStringInComment(args.ifdefStack,n,m))) else verbatimStringInComment n m args skip lexbuf } and tripleQuoteStringInComment n m args skip = parse // Follow tripleQuoteString lexing | '"' '"' '"' - { if not skip then (COMMENT (LexCont.Comment(!args.ifdefStack,n,m))) else comment (n,m,args) skip lexbuf } + { if not skip then (COMMENT (LexCont.Comment(args.ifdefStack,n,m))) else comment (n,m,args) skip lexbuf } | ident | integer | xinteger | anywhite + - { if not skip then (COMMENT (LexCont.TripleQuoteStringInComment(!args.ifdefStack,n,m))) else tripleQuoteStringInComment n m args skip lexbuf } + { if not skip then (COMMENT (LexCont.TripleQuoteStringInComment(args.ifdefStack,n,m))) else tripleQuoteStringInComment n m args skip lexbuf } | newline { newline lexbuf - if not skip then (COMMENT (LexCont.TripleQuoteStringInComment(!args.ifdefStack,n,m))) else tripleQuoteStringInComment n m args skip lexbuf } + if not skip then (COMMENT (LexCont.TripleQuoteStringInComment(args.ifdefStack,n,m))) else tripleQuoteStringInComment n m args skip lexbuf } | eof - { EOF (LexCont.TripleQuoteStringInComment(!args.ifdefStack,n,m)) } + { EOF (LexCont.TripleQuoteStringInComment(args.ifdefStack,n,m)) } | surrogateChar surrogateChar | _ - { if not skip then (COMMENT (LexCont.TripleQuoteStringInComment(!args.ifdefStack,n,m))) else tripleQuoteStringInComment n m args skip lexbuf } + { if not skip then (COMMENT (LexCont.TripleQuoteStringInComment(args.ifdefStack,n,m))) else tripleQuoteStringInComment n m args skip lexbuf } and mlOnly m args skip = parse @@ -1080,17 +1250,23 @@ and mlOnly m args skip = parse { let buf = ByteBuffer.Create 100 let m2 = lexbuf.LexemeRange let _ = string (buf,defaultStringFinisher,m2,args) skip lexbuf - if not skip then (COMMENT (LexCont.MLOnly(!args.ifdefStack,m))) else mlOnly m args skip lexbuf } + if not skip then (COMMENT (LexCont.MLOnly(args.ifdefStack,m))) else mlOnly m args skip lexbuf } + | newline - { newline lexbuf; if not skip then (COMMENT (LexCont.MLOnly(!args.ifdefStack,m))) else mlOnly m args skip lexbuf } + { newline lexbuf; if not skip then (COMMENT (LexCont.MLOnly(args.ifdefStack,m))) else mlOnly m args skip lexbuf } + | "(*ENDIF-CAML*)" - { if not skip then (COMMENT (LexCont.Token !args.ifdefStack)) else token args skip lexbuf } + { if not skip then (COMMENT (LexCont.Token args.ifdefStack)) else token args skip lexbuf } + | "(*ENDIF-OCAML*)" - { if not skip then (COMMENT (LexCont.Token !args.ifdefStack)) else token args skip lexbuf } + { if not skip then (COMMENT (LexCont.Token args.ifdefStack)) else token args skip lexbuf } + | [^ '(' '"' '\n' '\r' ]+ - { if not skip then (COMMENT (LexCont.MLOnly(!args.ifdefStack,m))) else mlOnly m args skip lexbuf } + { if not skip then (COMMENT (LexCont.MLOnly(args.ifdefStack,m))) else mlOnly m args skip lexbuf } + | eof - { EOF (LexCont.MLOnly(!args.ifdefStack,m)) } + { EOF (LexCont.MLOnly(args.ifdefStack,m)) } + | surrogateChar surrogateChar | _ - { if not skip then (COMMENT (LexCont.MLOnly(!args.ifdefStack,m))) else mlOnly m args skip lexbuf } + { if not skip then (COMMENT (LexCont.MLOnly(args.ifdefStack,m))) else mlOnly m args skip lexbuf } diff --git a/src/fcs-fable/src/fsharp/lexhelp.fs b/src/fcs-fable/src/fsharp/lexhelp.fs old mode 100755 new mode 100644 index 5e1f99f8b8..3fe28b6ee3 --- a/src/fcs-fable/src/fsharp/lexhelp.fs +++ b/src/fcs-fable/src/fsharp/lexhelp.fs @@ -6,21 +6,19 @@ open System open System.Text open Internal.Utilities -open Internal.Utilities.Collections -open Internal.Utilities.Text open Internal.Utilities.Text.Lexing open FSharp.Compiler -open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Lib -open FSharp.Compiler.Ast +open FSharp.Compiler.ParseHelpers +open FSharp.Compiler.Parser open FSharp.Compiler.PrettyNaming -open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.AbstractIL.Diagnostics open FSharp.Compiler.Range -open FSharp.Compiler.Parser +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.XmlDoc /// The "mock" filename used by fsi.exe when reading from stdin. /// Has special treatment by the lexer, i.e. __SOURCE_DIRECTORY__ becomes GetCurrentDirectory() @@ -40,17 +38,12 @@ type LightSyntaxStatus(initial:bool,warn:bool) = /// Manage lexer resources (string interning) [] -type LexResourceManager() = - let strings = new System.Collections.Generic.Dictionary(1024) +type LexResourceManager(?capacity: int) = + let strings = new System.Collections.Generic.Dictionary(defaultArg capacity 1024) member x.InternIdentifierToken(s) = -#if FABLE_COMPILER - let ok, res = strings.TryGetValue(s) -#else - let mutable res = Unchecked.defaultof<_> - let ok = strings.TryGetValue(s, &res) -#endif - if ok then res - else + match strings.TryGetValue s with + | true, res -> res + | _ -> let res = IDENT s strings.[s] <- res res @@ -58,25 +51,28 @@ type LexResourceManager() = /// Lexer parameters type lexargs = { defines: string list - ifdefStack: LexerIfdefStack + mutable ifdefStack: LexerIfdefStack resourceManager: LexResourceManager lightSyntaxStatus : LightSyntaxStatus errorLogger: ErrorLogger - applyLineDirectives: bool } + applyLineDirectives: bool + pathMap: PathMap } -/// possible results of lexing a long unicode escape sequence in a string literal, e.g. "\UDEADBEEF" +/// possible results of lexing a long Unicode escape sequence in a string literal, e.g. "\U0001F47D", +/// "\U000000E7", or "\UDEADBEEF" returning SurrogatePair, SingleChar, or Invalid, respectively type LongUnicodeLexResult = | SurrogatePair of uint16 * uint16 | SingleChar of uint16 | Invalid -let mkLexargs (_filename, defines, lightSyntaxStatus, resourceManager, ifdefStack, errorLogger) = +let mkLexargs (_filename, defines, lightSyntaxStatus, resourceManager, ifdefStack, errorLogger, pathMap:PathMap) = { defines = defines ifdefStack= ifdefStack lightSyntaxStatus=lightSyntaxStatus resourceManager=resourceManager errorLogger=errorLogger - applyLineDirectives=true } + applyLineDirectives=true + pathMap=pathMap } /// Register the lexbuf and call the given function let reusingLexbufForParsing lexbuf f = @@ -172,7 +168,9 @@ let unicodeGraphLong (s:string) = if high = 0 then SingleChar(uint16 low) // invalid encoding elif high > 0x10 then Invalid - // valid surrogate pair - see http://www.unicode.org/unicode/uni2book/ch03.pdf, section 3.7 *) + // valid supplementary character: code points U+10000 to U+10FFFF + // valid surrogate pair: see http://www.unicode.org/versions/latest/ch03.pdf , "Surrogates" section + // high-surrogate code point (U+D800 to U+DBFF) followed by low-surrogate code point (U+DC00 to U+DFFF) else let codepoint = high * 0x10000 + low let hiSurr = uint16 (0xD800 + ((codepoint - 0x10000) / 0x400)) @@ -331,7 +329,7 @@ module Keywords = match s with | "__SOURCE_DIRECTORY__" -> let filename = fileOfFileIndex lexbuf.StartPos.FileIndex - let dirname = + let dirname = if String.IsNullOrWhiteSpace(filename) then String.Empty else if filename = stdinMockFilename then @@ -341,10 +339,13 @@ module Keywords = "." #endif else - filename + filename |> FileSystem.GetFullPathShim (* asserts that path is already absolute *) |> System.IO.Path.GetDirectoryName - KEYWORD_STRING dirname + + if String.IsNullOrEmpty dirname then dirname + else PathMap.applyDir args.pathMap dirname + |> KEYWORD_STRING | "__SOURCE_FILE__" -> KEYWORD_STRING (System.IO.Path.GetFileName((fileOfFileIndex lexbuf.StartPos.FileIndex))) | "__LINE__" -> @@ -352,7 +353,7 @@ module Keywords = | _ -> IdentifierToken args lexbuf s - let inline private DoesIdentifierNeedQuotation (s : string) : bool = + let DoesIdentifierNeedQuotation (s : string) : bool = not (String.forall IsIdentifierPartCharacter s) // if it has funky chars || s.Length > 0 && (not(IsIdentifierFirstCharacter s.[0])) // or if it starts with a non-(letter-or-underscore) || keywordTable.ContainsKey s // or if it's a language keyword like "type" @@ -447,4 +448,5 @@ module Keywords = "<@", FSComp.SR.keywordDescriptionTypedQuotation() "@>", FSComp.SR.keywordDescriptionTypedQuotation() "<@@", FSComp.SR.keywordDescriptionUntypedQuotation() - "@@>", FSComp.SR.keywordDescriptionUntypedQuotation() ] \ No newline at end of file + "@@>", FSComp.SR.keywordDescriptionUntypedQuotation() ] + diff --git a/src/fcs-fable/src/fsharp/lexhelp.fsi b/src/fcs-fable/src/fsharp/lexhelp.fsi old mode 100755 new mode 100644 index 42dd615b39..2bed4e89c6 --- a/src/fcs-fable/src/fsharp/lexhelp.fsi +++ b/src/fcs-fable/src/fsharp/lexhelp.fsi @@ -4,72 +4,99 @@ module internal FSharp.Compiler.Lexhelp open Internal.Utilities open Internal.Utilities.Text -open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.Ast -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.Internal -open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler - +open FSharp.Compiler +open FSharp.Compiler.AbstractIL.Internal +open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.ParseHelpers +open FSharp.Compiler.Range -val stdinMockFilename : string +val stdinMockFilename: string [] type LightSyntaxStatus = - new : initial:bool * warn : bool -> LightSyntaxStatus - member ExplicitlySet : bool - member Status : bool - member Status : bool with set - member WarnOnMultipleTokens : bool + new: initial:bool * warn: bool -> LightSyntaxStatus + member ExplicitlySet: bool + member Status: bool + member Status: bool with set + member WarnOnMultipleTokens: bool [] type LexResourceManager = - new : unit -> LexResourceManager + new: ?capacity: int -> LexResourceManager type lexargs = { defines: string list - ifdefStack: LexerIfdefStack + mutable ifdefStack: LexerIfdefStack resourceManager: LexResourceManager - lightSyntaxStatus : LightSyntaxStatus + lightSyntaxStatus: LightSyntaxStatus errorLogger: ErrorLogger - applyLineDirectives: bool } + applyLineDirectives: bool + pathMap: PathMap } type LongUnicodeLexResult = | SurrogatePair of uint16 * uint16 | SingleChar of uint16 | Invalid -val resetLexbufPos : string -> UnicodeLexing.Lexbuf -> unit -val mkLexargs : 'a * string list * LightSyntaxStatus * LexResourceManager * LexerIfdefStack * ErrorLogger -> lexargs -val reusingLexbufForParsing : UnicodeLexing.Lexbuf -> (unit -> 'a) -> 'a - -val usingLexbufForParsing : UnicodeLexing.Lexbuf * string -> (UnicodeLexing.Lexbuf -> 'a) -> 'a -val defaultStringFinisher : 'a -> 'b -> byte[] -> Parser.token -val callStringFinisher : ('a -> 'b -> byte[] -> 'c) -> ByteBuffer -> 'a -> 'b -> 'c -val addUnicodeString : ByteBuffer -> string -> unit -val addUnicodeChar : ByteBuffer -> int -> unit -val addByteChar : ByteBuffer -> char -> unit -val stringBufferAsString : byte[] -> string -val stringBufferAsBytes : ByteBuffer -> byte[] -val stringBufferIsBytes : ByteBuffer -> bool -val newline : Lexing.LexBuffer<'a> -> unit -val trigraph : char -> char -> char -> char -val digit : char -> int32 -val hexdigit : char -> int32 -val unicodeGraphShort : string -> uint16 -val hexGraphShort : string -> uint16 -val unicodeGraphLong : string -> LongUnicodeLexResult -val escape : char -> char +val resetLexbufPos: string -> UnicodeLexing.Lexbuf -> unit + +val mkLexargs: 'a * string list * LightSyntaxStatus * LexResourceManager * LexerIfdefStack * ErrorLogger * PathMap -> lexargs + +val reusingLexbufForParsing: UnicodeLexing.Lexbuf -> (unit -> 'a) -> 'a + +val usingLexbufForParsing: UnicodeLexing.Lexbuf * string -> (UnicodeLexing.Lexbuf -> 'a) -> 'a + +val defaultStringFinisher: 'a -> 'b -> byte[] -> Parser.token + +val callStringFinisher: ('a -> 'b -> byte[] -> 'c) -> ByteBuffer -> 'a -> 'b -> 'c + +val addUnicodeString: ByteBuffer -> string -> unit + +val addUnicodeChar: ByteBuffer -> int -> unit + +val addByteChar: ByteBuffer -> char -> unit + +val stringBufferAsString: byte[] -> string + +val stringBufferAsBytes: ByteBuffer -> byte[] + +val stringBufferIsBytes: ByteBuffer -> bool + +val newline: Lexing.LexBuffer<'a> -> unit + +val trigraph: char -> char -> char -> char + +val digit: char -> int32 + +val hexdigit: char -> int32 + +val unicodeGraphShort: string -> uint16 + +val hexGraphShort: string -> uint16 + +val unicodeGraphLong: string -> LongUnicodeLexResult + +val escape: char -> char exception ReservedKeyword of string * Range.range + exception IndentationProblem of string * Range.range module Keywords = - val KeywordOrIdentifierToken : lexargs -> UnicodeLexing.Lexbuf -> string -> Parser.token - val IdentifierToken : lexargs -> UnicodeLexing.Lexbuf -> string -> Parser.token - val QuoteIdentifierIfNeeded : string -> string - val NormalizeIdentifierBackticks : string -> string - val keywordNames : string list + + val KeywordOrIdentifierToken: lexargs -> UnicodeLexing.Lexbuf -> string -> Parser.token + + val IdentifierToken: lexargs -> UnicodeLexing.Lexbuf -> string -> Parser.token + + val DoesIdentifierNeedQuotation: string -> bool + + val QuoteIdentifierIfNeeded: string -> string + + val NormalizeIdentifierBackticks: string -> string + + val keywordNames: string list + /// Keywords paired with their descriptions. Used in completion and quick info. - val keywordsWithDescription : (string * string) list + val keywordsWithDescription: (string * string) list + diff --git a/src/fcs-fable/src/fsharp/lib.fs b/src/fcs-fable/src/fsharp/lib.fs index 6829dba9d4..31b56b73ac 100755 --- a/src/fcs-fable/src/fsharp/lib.fs +++ b/src/fcs-fable/src/fsharp/lib.fs @@ -4,8 +4,8 @@ module internal FSharp.Compiler.Lib open System.IO open System.Collections.Generic +open System.Runtime.InteropServices open Internal.Utilities -open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library @@ -13,8 +13,8 @@ open FSharp.Compiler.AbstractIL.Internal.Library /// is this the developer-debug build? let debug = false let verbose = false -let progress = ref false -let tracking = ref false // intended to be a general hook to control diagnostic output when tracking down bugs +let mutable progress = false +let mutable tracking = false // intended to be a general hook to control diagnostic output when tracking down bugs #if FABLE_COMPILER let condition _s = false @@ -26,15 +26,6 @@ let condition s = let GetEnvInteger e dflt = match System.Environment.GetEnvironmentVariable(e) with null -> dflt | t -> try int t with _ -> dflt let dispose (x:System.IDisposable) = match x with null -> () | x -> x.Dispose() - -type SaveAndRestoreConsoleEncoding () = - let savedOut = System.Console.Out - - interface System.IDisposable with - member this.Dispose() = - try - System.Console.SetOut(savedOut) - with _ -> () #endif //------------------------------------------------------------------------- @@ -112,31 +103,31 @@ module Check = /// Throw System.InvalidOperationException() if argument is None. /// If there is a value (e.g. Some(value)) then value is returned. - let NotNone argname (arg:'T option) : 'T = + let NotNone argName (arg:'T option) : 'T = match arg with - | None -> raise (new System.InvalidOperationException(argname)) + | None -> raise (new System.InvalidOperationException(argName)) | Some x -> x /// Throw System.ArgumentNullException() if argument is null. - let ArgumentNotNull arg argname = + let ArgumentNotNull arg argName = match box(arg) with - | null -> raise (new System.ArgumentNullException(argname)) + | null -> raise (new System.ArgumentNullException(argName)) | _ -> () /// Throw System.ArgumentNullException() if array argument is null. /// Throw System.ArgumentOutOfRangeException() is array argument is empty. - let ArrayArgumentNotNullOrEmpty (arr:'T[]) argname = - ArgumentNotNull arr argname + let ArrayArgumentNotNullOrEmpty (arr:'T[]) argName = + ArgumentNotNull arr argName if (0 = arr.Length) then - raise (new System.ArgumentOutOfRangeException(argname)) + raise (new System.ArgumentOutOfRangeException(argName)) /// Throw System.ArgumentNullException() if string argument is null. /// Throw System.ArgumentOutOfRangeException() is string argument is empty. - let StringArgumentNotNullOrEmpty (s:string) argname = - ArgumentNotNull s argname + let StringArgumentNotNullOrEmpty (s:string) argName = + ArgumentNotNull s argName if s.Length = 0 then - raise (new System.ArgumentNullException(argname)) + raise (new System.ArgumentNullException(argName)) //------------------------------------------------------------------------- // Library @@ -168,7 +159,7 @@ module ListAssoc = let rec find f x l = match l with | [] -> notFound() - | (x2, y)::t -> if f x x2 then y else find f x t + | (x2, y) :: t -> if f x x2 then y else find f x t /// Treat a list of key-value pairs as a lookup collection. /// This function looks up a value based on a match from the supplied @@ -176,7 +167,7 @@ module ListAssoc = let rec tryFind (f:'key->'key->bool) (x:'key) (l:('key*'value) list) : 'value option = match l with | [] -> None - | (x2, y)::t -> if f x x2 then Some y else tryFind f x t + | (x2, y) :: t -> if f x x2 then Some y else tryFind f x t //------------------------------------------------------------------------- // Library: lists as generalized sets @@ -186,7 +177,7 @@ module ListSet = let inline contains f x l = List.exists (f x) l (* NOTE: O(n)! *) - let insert f x l = if contains f x l then l else x::l + let insert f x l = if contains f x l then l else x :: l let unionFavourRight f l1 l2 = match l1, l2 with @@ -198,19 +189,19 @@ module ListSet = let rec private findIndexAux eq x l n = match l with | [] -> notFound() - | (h::t) -> if eq h x then n else findIndexAux eq x t (n+1) + | (h :: t) -> if eq h x then n else findIndexAux eq x t (n+1) let findIndex eq x l = findIndexAux eq x l 0 let rec remove f x l = match l with - | (h::t) -> if f x h then t else h:: remove f x t + | (h :: t) -> if f x h then t else h :: remove f x t | [] -> [] (* NOTE: quadratic! *) let rec subtract f l1 l2 = match l2 with - | (h::t) -> subtract f (remove (fun y2 y1 -> f y1 y2) h l1) t + | (h :: t) -> subtract f (remove (fun y2 y1 -> f y1 y2) h l1) t | [] -> l1 let isSubsetOf f l1 l2 = List.forall (fun x1 -> contains f x1 l2) l1 @@ -228,7 +219,7 @@ module ListSet = (* NOTE: not tail recursive! *) let rec intersect f l1 l2 = match l2 with - | (h::t) -> if contains f h l1 then h::intersect f l1 t else intersect f l1 t + | (h :: t) -> if contains f h l1 then h :: intersect f l1 t else intersect f l1 t | [] -> [] // Note: if duplicates appear, keep the ones toward the _front_ of the list @@ -239,15 +230,15 @@ module ListSet = | [] -> false | [_] -> false | [x; y] -> f x y - | x::rest -> + | x :: rest -> let rec loop acc l = match l with | [] -> false - | x::rest -> + | x :: rest -> if contains f x acc then true else - loop (x::acc) rest + loop (x :: acc) rest loop [x] rest @@ -328,20 +319,13 @@ let bufs f = buf.ToString() #if !FABLE_COMPILER -let buff (os: TextWriter) f x = +// writing to output stream via a string buffer. +let writeViaBuffer (os: TextWriter) f x = let buf = System.Text.StringBuilder 100 f buf x os.Write(buf.ToString()) - -// Converts "\n" into System.Environment.NewLine before writing to os. See lib.fs:buff -let writeViaBufferWithEnvironmentNewLines (os: TextWriter) f x = - let buf = System.Text.StringBuilder 100 - f buf x - let text = buf.ToString() - let text = text.Replace("\n", System.Environment.NewLine) - os.Write text #endif - + //--------------------------------------------------------------------------- // Imperative Graphs //--------------------------------------------------------------------------- @@ -365,7 +349,7 @@ type Graph<'Data, 'Id when 'Id : comparison and 'Id : equality> member g.IterateCycles f = let rec trace path node = if List.exists (nodeIdentity >> (=) node.nodeId) path then f (List.rev path) - else List.iter (trace (node.nodeData::path)) node.nodeNeighbours + else List.iter (trace (node.nodeData :: path)) node.nodeNeighbours List.iter (fun node -> trace [] node) nodes //--------------------------------------------------------------------------- @@ -394,23 +378,38 @@ let nullableSlotFull x = x type cache<'T> = { mutable cacheVal: 'T NonNullSlot } let newCache() = { cacheVal = nullableSlotEmpty() } -let inline cached cache resf = +let inline cached cache resF = match box cache.cacheVal with | null -> - let res = resf() + let res = resF() cache.cacheVal <- nullableSlotFull res res | _ -> cache.cacheVal +let inline cacheOptByref (cache: byref<'T option>) f = + match cache with + | Some v -> v + | None -> + let res = f() + cache <- Some res + res + +// REVIEW: this is only used because we want to mutate a record field, +// and because you cannot take a byref<_> of such a thing directly, +// we cannot use 'cacheOptByref'. If that is changed, this can be removed. let inline cacheOptRef cache f = - match !cache with + match !cache with | Some v -> v | None -> let res = f() cache := Some res res +let inline tryGetCacheValue cache = + match box cache.cacheVal with + | null -> ValueNone + | _ -> ValueSome cache.cacheVal #if DUMPER type Dumper(x:obj) = @@ -436,11 +435,11 @@ module internal AsyncUtil = | AsyncCanceled of OperationCanceledException static member Commit(res:AsyncResult<'T>) = - Async.FromContinuations (fun (cont, econt, ccont) -> + Async.FromContinuations (fun (cont, eCont, cCont) -> match res with | AsyncOk v -> cont v - | AsyncException exn -> econt exn - | AsyncCanceled exn -> ccont exn) + | AsyncException exn -> eCont exn + | AsyncCanceled exn -> cCont exn) /// When using .NET 4.0 you can replace this type by [] @@ -463,7 +462,7 @@ module internal AsyncUtil = else result <- Some res // Invoke continuations in FIFO order - // Continuations that Async.FromContinuations provide do QUWI/SynchContext.Post, + // Continuations that Async.FromContinuations provide do QUWI/SyncContext.Post, // so the order is not overly relevant but still. List.rev savedConts) let postOrQueue (sc:SynchronizationContext, cont) = @@ -493,7 +492,7 @@ module internal AsyncUtil = | None -> // Otherwise save the continuation and call it in RegisterResult let sc = SynchronizationContext.Current - savedConts <- (sc, cont)::savedConts + savedConts <- (sc, cont) :: savedConts None) // Run the action outside the lock match grabbedResult with @@ -530,11 +529,9 @@ module UnmanagedProcessExecutionOptions = extern UInt32 private GetLastError() // Translation of C# from http://swikb/v1/DisplayOnlineDoc.aspx?entryID=826 and copy in bug://5018 -#if !FX_NO_SECURITY_PERMISSIONS [] -#endif let EnableHeapTerminationOnCorruption() = - if (System.Environment.OSVersion.Version.Major >= 6 && // If OS is Vista or higher + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && System.Environment.OSVersion.Version.Major >= 6 && // If OS is Vista or higher System.Environment.Version.Major < 3) then // and CLR not 3.0 or higher // "The flag HeapSetInformation sets is available in Windows XP SP3 and later. // The data structure used for heap information is available on earlier versions of Windows. @@ -553,5 +550,31 @@ module UnmanagedProcessExecutionOptions = "HeapSetInformation() returned FALSE; LastError = 0x" + GetLastError().ToString("X").PadLeft(8, '0') + ".")) +[] +module StackGuard = + + open System.Runtime.CompilerServices + + [] + let private MaxUncheckedRecursionDepth = 20 + + let EnsureSufficientExecutionStack recursionDepth = + if recursionDepth > MaxUncheckedRecursionDepth then + RuntimeHelpers.EnsureSufficientExecutionStack () + +#endif //!FABLE_COMPILER + +[] +type MaybeLazy<'T> = + | Strict of 'T + | Lazy of Lazy<'T> + + member this.Value: 'T = + match this with + | Strict x -> x + | Lazy x -> x.Value -#endif //!FABLE_COMPILER \ No newline at end of file + member this.Force() : 'T = + match this with + | Strict x -> x + | Lazy x -> x.Force() diff --git a/src/fcs-fable/src/fsharp/msft.pubkey b/src/fcs-fable/src/fsharp/msft.pubkey old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/fsharp/pars.fsy b/src/fcs-fable/src/fsharp/pars.fsy index d0201861ad..0bbd3def9e 100644 --- a/src/fcs-fable/src/fsharp/pars.fsy +++ b/src/fcs-fable/src/fsharp/pars.fsy @@ -4,37 +4,42 @@ #nowarn "1182" // generated code has lots of unused "parseState" +open System + open Internal.Utilities +open Internal.Utilities.Text.Parsing +open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler -open Internal.Utilities.Text.Parsing - -open System -open FSharp.Compiler.Range -open FSharp.Compiler.Ast +open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features open FSharp.Compiler.Lib +open FSharp.Compiler.ParseHelpers open FSharp.Compiler.PrettyNaming -open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.XmlDoc #if DEBUG -let debugPrint(s) = +let debugPrint s = if Internal.Utilities.Text.Parsing.Flags.debug then printfn "\n%s" s #else -let debugPrint(s) = ignore s +let debugPrint s = ignore s #endif -let exprFromParseError (e:SynExpr) = SynExpr.FromParseError(e,e.Range) +let exprFromParseError (e:SynExpr) = SynExpr.FromParseError (e, e.Range) + let patFromParseError (e:SynPat) = SynPat.FromParseError(e, e.Range) let mkSynOptionalExpr (m: range) xopt = let m = m.MakeSynthetic() match xopt with - | None -> mkSynLidGet m Ast.FSharpLib.CorePath "None" - | Some x -> SynExpr.App(ExprAtomicFlag.NonAtomic, false, mkSynLidGet m Ast.FSharpLib.CorePath "Some",x,m) + | None -> mkSynLidGet m FSharpLib.CorePath "None" + | Some x -> SynExpr.App (ExprAtomicFlag.NonAtomic, false, mkSynLidGet m FSharpLib.CorePath "Some", x, m) // record bindings returned by the recdExprBindings rule has shape: // (binding, separator-before-this-binding) @@ -45,28 +50,29 @@ let mkSynOptionalExpr (m: range) xopt = let rebindRanges first fields lastSep = let rec run (name, value) l acc = match l with - | [] -> List.rev ((name, value, lastSep)::acc) - | (f, m)::xs -> run f xs ((name, value, m)::acc) + | [] -> List.rev ((name, value, lastSep) :: acc) + | (f, m) :: xs -> run f xs ((name, value, m) :: acc) run first fields [] let mkUnderscoreRecdField m = LongIdentWithDots([ident("_", m)], []), false + let mkRecdField lidwd = lidwd, true -let mkSynDoBinding (vis,strict,expr,m) = +let mkSynDoBinding (vis, strict, expr, m) = match vis with - | Some vis -> errorR(Error(FSComp.SR.parsDoCannotHaveVisibilityDeclarations (vis.ToString()),m)) + | Some vis -> errorR(Error(FSComp.SR.parsDoCannotHaveVisibilityDeclarations (vis.ToString()), m)) | None -> () Binding (None, (if strict then DoBinding else StandaloneExpression), - false,false,[],PreXmlDoc.Empty,SynInfo.emptySynValData, - (if strict then SynPat.Const(SynConst.Unit,m) else SynPat.Wild m), - None,expr,m,NoSequencePointAtDoBinding) + false, false, [], PreXmlDoc.Empty, SynInfo.emptySynValData, + (if strict then SynPat.Const(SynConst.Unit, m) else SynPat.Wild m), + None, expr, m, NoDebugPointAtDoBinding) let mkSynDoDecl (e: SynExpr) = - let spExpr = if IsControlFlowExpression e then NoSequencePointAtDoBinding else SequencePointAtBinding e.Range in + let spExpr = if IsControlFlowExpression e then NoDebugPointAtDoBinding else DebugPointAtBinding e.Range in SynModuleDecl.DoExpr(spExpr, e, e.Range) -let addAttribs attrs p = SynPat.Attrib(p,attrs,p.Range) +let addAttribs attrs p = SynPat.Attrib(p, attrs, p.Range) // This function is called by the generated parser code. Returning initiates error recovery @@ -74,7 +80,7 @@ let addAttribs attrs p = SynPat.Attrib(p,attrs,p.Range) let parse_error_rich = Some (fun (ctxt: ParseErrorContext<_>) -> errorR(SyntaxError(box ctxt, ctxt.ParseState.LexBuffer.LexemeRange))) -let reportParseErrorAt m s = errorR(Error(s,m)) +let reportParseErrorAt m s = errorR(Error(s, m)) let unionRangeWithPos (r:range) p = let r2 = mkRange r.FileName p p @@ -87,70 +93,65 @@ let raiseParseErrorAt m s = let checkEndOfFileError t = match t with - | LexCont.IfDefSkip(_,_,m) -> reportParseErrorAt m (FSComp.SR.parsEofInHashIf()) - | LexCont.String (_,m) -> reportParseErrorAt m (FSComp.SR.parsEofInString()) - | LexCont.TripleQuoteString (_,m) -> reportParseErrorAt m (FSComp.SR.parsEofInTripleQuoteString()) - | LexCont.VerbatimString (_,m) -> reportParseErrorAt m (FSComp.SR.parsEofInVerbatimString()) - | LexCont.Comment (_,_,m) -> reportParseErrorAt m (FSComp.SR.parsEofInComment()) - | LexCont.SingleLineComment (_,_,m) -> reportParseErrorAt m (FSComp.SR.parsEofInComment()) - | LexCont.StringInComment (_,_,m) -> reportParseErrorAt m (FSComp.SR.parsEofInStringInComment()) - | LexCont.VerbatimStringInComment (_,_,m) -> reportParseErrorAt m (FSComp.SR.parsEofInVerbatimStringInComment()) - | LexCont.TripleQuoteStringInComment (_,_,m) -> reportParseErrorAt m (FSComp.SR.parsEofInTripleQuoteStringInComment()) - | LexCont.MLOnly (_,m) -> reportParseErrorAt m (FSComp.SR.parsEofInIfOcaml()) - | LexCont.EndLine(LexerEndlineContinuation.Skip(_,_,m)) -> reportParseErrorAt m (FSComp.SR.parsEofInDirective()) + | LexCont.IfDefSkip(_, _, m) -> reportParseErrorAt m (FSComp.SR.parsEofInHashIf()) + | LexCont.String (_, m) -> reportParseErrorAt m (FSComp.SR.parsEofInString()) + | LexCont.TripleQuoteString (_, m) -> reportParseErrorAt m (FSComp.SR.parsEofInTripleQuoteString()) + | LexCont.VerbatimString (_, m) -> reportParseErrorAt m (FSComp.SR.parsEofInVerbatimString()) + | LexCont.Comment (_, _, m) -> reportParseErrorAt m (FSComp.SR.parsEofInComment()) + | LexCont.SingleLineComment (_, _, m) -> reportParseErrorAt m (FSComp.SR.parsEofInComment()) + | LexCont.StringInComment (_, _, m) -> reportParseErrorAt m (FSComp.SR.parsEofInStringInComment()) + | LexCont.VerbatimStringInComment (_, _, m) -> reportParseErrorAt m (FSComp.SR.parsEofInVerbatimStringInComment()) + | LexCont.TripleQuoteStringInComment (_, _, m) -> reportParseErrorAt m (FSComp.SR.parsEofInTripleQuoteStringInComment()) + | LexCont.MLOnly (_, m) -> reportParseErrorAt m (FSComp.SR.parsEofInIfOcaml()) + | LexCont.EndLine(LexerEndlineContinuation.Skip(_, _, m)) -> reportParseErrorAt m (FSComp.SR.parsEofInDirective()) | LexCont.EndLine(LexerEndlineContinuation.Token(stack)) | LexCont.Token(stack) -> match stack with | [] -> () - | (_,m) :: _ -> reportParseErrorAt m (FSComp.SR.parsNoHashEndIfFound()) + | (_, m) :: _ -> reportParseErrorAt m (FSComp.SR.parsNoHashEndIfFound()) -// BindingSetPreAttrs(letRange, isRec, isUse, builderFunction, wholeRange) type BindingSet = BindingSetPreAttrs of range * bool * bool * (SynAttributes -> SynAccess option -> SynAttributes * SynBinding list) * range -let mkClassMemberLocalBindings(isStatic,initialRangeOpt,attrs,vis,BindingSetPreAttrs(_,isRec,isUse,declsPreAttrs,bindingSetRange)) = - let ignoredFreeAttrs,decls = declsPreAttrs attrs vis +let mkClassMemberLocalBindings(isStatic, initialRangeOpt, attrs, vis, BindingSetPreAttrs(_, isRec, isUse, declsPreAttrs, bindingSetRange)) = + let ignoredFreeAttrs, decls = declsPreAttrs attrs vis let wholeRange = match initialRangeOpt with | None -> bindingSetRange | Some m -> unionRanges m bindingSetRange - if not (isNil ignoredFreeAttrs) then warning(Error(FSComp.SR.parsAttributesIgnored(),wholeRange)); - if isUse then errorR(Error(FSComp.SR.parsUseBindingsIllegalInImplicitClassConstructors(),wholeRange)) - SynMemberDefn.LetBindings (decls,isStatic,isRec,wholeRange) - -let mkLocalBindings (mWhole,BindingSetPreAttrs(_,isRec,isUse,declsPreAttrs,_),body) = - let ignoredFreeAttrs,decls = declsPreAttrs [] None - if not (isNil ignoredFreeAttrs) then warning(Error(FSComp.SR.parsAttributesIgnored(),mWhole)) - SynExpr.LetOrUse (isRec,isUse,decls,body,mWhole) - -let mkDefnBindings (mWhole,BindingSetPreAttrs(_,isRec,isUse,declsPreAttrs,_bindingSetRange),attrs,vis,attrsm) = - if isUse then warning(Error(FSComp.SR.parsUseBindingsIllegalInModules(),mWhole)) - let freeAttrs,decls = declsPreAttrs attrs vis - let letDecls = [ SynModuleDecl.Let (isRec,decls,mWhole) ] - let attrDecls = if not (isNil freeAttrs) then [ SynModuleDecl.Attributes (freeAttrs,attrsm) ] else [] + if not (isNil ignoredFreeAttrs) then warning(Error(FSComp.SR.parsAttributesIgnored(), wholeRange)); + if isUse then errorR(Error(FSComp.SR.parsUseBindingsIllegalInImplicitClassConstructors(), wholeRange)) + SynMemberDefn.LetBindings (decls, isStatic, isRec, wholeRange) + +let mkLocalBindings (mWhole, BindingSetPreAttrs(_, isRec, isUse, declsPreAttrs, _), body) = + let ignoredFreeAttrs, decls = declsPreAttrs [] None + if not (isNil ignoredFreeAttrs) then warning(Error(FSComp.SR.parsAttributesIgnored(), mWhole)) + SynExpr.LetOrUse (isRec, isUse, decls, body, mWhole) + +let mkDefnBindings (mWhole, BindingSetPreAttrs(_, isRec, isUse, declsPreAttrs, _bindingSetRange), attrs, vis, attrsm) = + if isUse then warning(Error(FSComp.SR.parsUseBindingsIllegalInModules(), mWhole)) + let freeAttrs, decls = declsPreAttrs attrs vis + let letDecls = [ SynModuleDecl.Let (isRec, decls, mWhole) ] + let attrDecls = if not (isNil freeAttrs) then [ SynModuleDecl.Attributes (freeAttrs, attrsm) ] else [] attrDecls @ letDecls -let idOfPat m p = - match p with - | SynPat.Named (SynPat.Wild _,id,false,_,_) -> id - | SynPat.LongIdent(LongIdentWithDots([id],_),_,_,_,_,_) -> id +let idOfPat (parseState:IParseState) m p = + match p with + | SynPat.Wild r when parseState.LexBuffer.SupportsFeature LanguageFeature.WildCardInForLoop -> + mkSynId r "_" + | SynPat.Named (SynPat.Wild _, id, false, _, _) -> id + | SynPat.LongIdent(LongIdentWithDots([id], _), _, None, SynArgPats.Pats [], None, _) -> id | _ -> raiseParseErrorAt m (FSComp.SR.parsIntegerForLoopRequiresSimpleIdentifier()) let checkForMultipleAugmentations m a1 a2 = if not (isNil a1) && not (isNil a2) then raiseParseErrorAt m (FSComp.SR.parsOnlyOneWithAugmentationAllowed()) a1 @ a2 -let grabXmlDoc(parseState:IParseState,elemIdx) = - LexbufLocalXmlDocStore.GrabXmlDocBeforeMarker(parseState.LexBuffer,rhs parseState elemIdx) - -let unionRangeWithListBy projectRangeFromThing m listOfThing = - (m, listOfThing) ||> List.fold (fun m thing -> unionRanges m (projectRangeFromThing thing)) - -let rangeOfNonNilAttrs(attrs:SynAttributes) = - (attrs.Head.Range,attrs.Tail) ||> unionRangeWithListBy (fun a -> a.Range) +let grabXmlDoc(parseState:IParseState, elemIdx) = + LexbufLocalXmlDocStore.GrabXmlDocBeforeMarker(parseState.LexBuffer, rhs parseState elemIdx) let rangeOfLongIdent(lid:LongIdent) = System.Diagnostics.Debug.Assert(not lid.IsEmpty, "the parser should never produce a long-id that is the empty list") - (lid.Head.idRange,lid) ||> unionRangeWithListBy (fun id -> id.idRange) + (lid.Head.idRange, lid) ||> unionRangeWithListBy (fun id -> id.idRange) %} @@ -186,12 +187,12 @@ let rangeOfLongIdent(lid:LongIdent) = %token CHAR %token DECIMAL %token <(string * string)> BIGNUM -%token LET YIELD YIELD_BANG +%token LET YIELD YIELD_BANG AND_BANG %token LESS GREATER /* here the bool indicates if the tokens are part of a type application or type parameter declaration, e.g. C, detected by the lex filter */ %token PERCENT_OP BINDER %token LQUOTE RQUOTE RQUOTE_DOT %token BAR_BAR UPCAST DOWNCAST NULL RESERVED MODULE NAMESPACE DELEGATE CONSTRAINT BASE -%token AND AS ASSERT OASSERT ASR BEGIN DO DONE DOWNTO ELSE ELIF END DOT_DOT +%token AND AS ASSERT OASSERT ASR BEGIN DO DONE DOWNTO ELSE ELIF END DOT_DOT DOT_DOT_HAT %token EXCEPTION FALSE FOR FUN FUNCTION IF IN JOIN_IN FINALLY DO_BANG %token LAZY OLAZY MATCH MATCH_BANG MUTABLE NEW OF %token OPEN OR REC THEN TO TRUE TRY TYPE VAL INLINE INTERFACE INSTANCE CONST @@ -215,6 +216,7 @@ let rangeOfLongIdent(lid:LongIdent) = /* for offside rule */ %token OLET /* LexFilter #light converts 'LET' tokens to 'OLET' when starting (CtxtLetDecl(blockLet=true)) */ %token OBINDER /* LexFilter #light converts 'BINDER' tokens to 'OBINDER' when starting (CtxtLetDecl(blockLet=true)) */ +%token OAND_BANG /* LexFilter #light converts 'AND_BANG' tokens to 'OAND_BANG' when starting (CtxtLetDecl(blockLet=true)) */ %token ODO /* LexFilter #light converts 'DO' tokens to 'ODO' */ %token ODO_BANG /* LexFilter #light converts 'DO_BANG' tokens to 'ODO_BANG' */ %token OTHEN /* LexFilter #light converts 'THEN' tokens to 'OTHEN' */ @@ -245,13 +247,13 @@ let rangeOfLongIdent(lid:LongIdent) = - just after '->' in any context - when opening CtxtNamespaceHead, CtxtModuleHead */ -%token OBLOCKSEP /* LexFilter #light inserts when transforming CtxtSeqBlock(NotFirstInSeqBlock,_,AddBlockEnd) to CtxtSeqBlock(FirstInSeqBlock,_,AddBlockEnd) on exact alignment */ +%token OBLOCKSEP /* LexFilter #light inserts when transforming CtxtSeqBlock(NotFirstInSeqBlock, _, AddBlockEnd) to CtxtSeqBlock(FirstInSeqBlock, _, AddBlockEnd) on exact alignment */ /* REVIEW: merge OEND, ODECLEND, OBLOCKEND and ORIGHT_BLOCK_END into one token */ %token OEND /* LexFilter #light inserts when closing CtxtFun, CtxtMatchClauses, CtxtWithAsLet _ */ %token ODECLEND /* LexFilter #light inserts when closing CtxtDo and CtxtLetDecl(block) */ -%token ORIGHT_BLOCK_END /* LexFilter #light inserts when closing CtxtSeqBlock(_,_,AddOneSidedBlockEnd) */ -%token OBLOCKEND OBLOCKEND_COMING_SOON OBLOCKEND_IS_HERE /* LexFilter #light inserts when closing CtxtSeqBlock(_,_,AddBlockEnd) */ +%token ORIGHT_BLOCK_END /* LexFilter #light inserts when closing CtxtSeqBlock(_, _, AddOneSidedBlockEnd) */ +%token OBLOCKEND OBLOCKEND_COMING_SOON OBLOCKEND_IS_HERE /* LexFilter #light inserts when closing CtxtSeqBlock(_, _, AddBlockEnd) */ %token OINTERFACE_MEMBER /* inserted for non-paranthetical use of 'INTERFACE', i.e. not INTERFACE/END */ %token FIXED @@ -259,41 +261,41 @@ let rangeOfLongIdent(lid:LongIdent) = /* These are artificial */ %token LEX_FAILURE -%token COMMENT WHITESPACE HASH_LINE HASH_LIGHT INACTIVECODE LINE_COMMENT STRING_TEXT EOF -%token HASH_IF HASH_ELSE HASH_ENDIF +%token COMMENT WHITESPACE HASH_LINE HASH_LIGHT INACTIVECODE LINE_COMMENT STRING_TEXT EOF +%token HASH_IF HASH_ELSE HASH_ENDIF %start signatureFile implementationFile interaction typedSeqExprEOF typEOF -%type typedSeqExprEOF -%type implementationFile -%type signatureFile -%type interaction -%type ident -%type typ typEOF -%type tyconSpfns -%type patternResult -%type declExpr -%type minusExpr -%type appExpr -%type argExpr -%type declExprBlock -%type headBindingPattern -%type atomicExprAfterType -%type typedSeqExprBlock -%type atomicExpr -%type tyconDefnOrSpfnSimpleRepr -%type list> unionTypeRepr -%type tyconDefnAugmentation -%type exconDefn -%type exconCore -%type moduleDefnsOrExprPossiblyEmptyOrBlock -%type openDecl -%type path -%type pathOp +%type typedSeqExprEOF +%type implementationFile +%type signatureFile +%type interaction +%type ident +%type typ typEOF +%type tyconSpfns +%type patternResult +%type declExpr +%type minusExpr +%type appExpr +%type argExpr +%type declExprBlock +%type headBindingPattern +%type atomicExprAfterType +%type typedSeqExprBlock +%type atomicExpr +%type tyconDefnOrSpfnSimpleRepr +%type list> unionTypeRepr +%type tyconDefnAugmentation +%type exconDefn +%type exconCore +%type moduleDefnsOrExprPossiblyEmptyOrBlock +%type openDecl +%type path +%type pathOp /* LESS GREATER parsedOk typeArgs m for each mWhole */ -%type typeArgsActual +%type typeArgsActual /* LESS GREATER typeArgs m for each mWhole */ -%type typeArgsNoHpaDeprecated -%type typar +%type typeArgsNoHpaDeprecated +%type typar /* About precedence rules: * @@ -375,7 +377,8 @@ let rangeOfLongIdent(lid:LongIdent) = * - constant terminals. * - null * - LBRACK = [ - * - TRUE,FALSE + * - TRUE, FALSE + */ %nonassoc prec_atompat_pathop %nonassoc INT8 UINT8 INT16 UINT16 INT32 UINT32 INT64 UINT64 NATIVEINT UNATIVEINT IEEE32 IEEE64 CHAR KEYWORD_STRING STRING BYTEARRAY BIGNUM DECIMAL @@ -404,9 +407,9 @@ let rangeOfLongIdent(lid:LongIdent) = * Committing to an opt_attribute (reduce) forces the decision that a following LET is a moduleDefn. * At the top-level, it could turn out to be an expr, so prefer to shift and find out... */ -%nonassoc prec_opt_attributes_none /* lower than LET,NEW */ +%nonassoc prec_opt_attributes_none /* lower than LET, NEW */ -/* LET,NEW higher than SEMICOLON so shift +/* LET, NEW higher than SEMICOLON so shift * "seqExpr = seqExpr; . let x = y in z" * "seqExpr = seqExpr; . new...." */ @@ -423,7 +426,7 @@ let rangeOfLongIdent(lid:LongIdent) = %nonassoc ELSE /* prec_atomtyp_path = precedence of atomType "path" - * Lower than possible extension "path" to allow "path . <" shift. + * Lower than possible extension "path" to allow "path . <" shift. * Extensions: LESS */ %nonassoc prec_atomtyp_path /* lower than LESS */ @@ -444,12 +447,13 @@ let rangeOfLongIdent(lid:LongIdent) = %nonassoc pat_tuple expr_tuple %left COMMA %nonassoc slice_expr /* matrix.[e COMMA e] has higher precedence than "e COMMA e" */ -%nonassoc DOT_DOT /* for matrix.[1..2,3..4] the ".." has higher precedence than expression "2 COMMA 3" */ -%nonassoc slice_comma /* for matrix.[1..2,3..4] the "," has higher precedence than ".." */ +%nonassoc DOT_DOT /* for matrix.[1..2, 3..4] the ".." has higher precedence than expression "2 COMMA 3" */ +%nonassoc slice_comma /* for matrix.[1..2, 3..4] the ", " has higher precedence than ".." */ %nonassoc paren_pat_colon %nonassoc paren_pat_attribs %left OR BAR_BAR JOIN_IN -%left AND /* check */ +%left AND +%left AND_BANG %left AMP AMP_AMP %nonassoc pat_conj %nonassoc expr_not @@ -490,14 +494,14 @@ let rangeOfLongIdent(lid:LongIdent) = /* An interaction in F# Interactive */ interaction: | interactiveItemsTerminator - { IDefns ($1,lhs parseState) } + { IDefns ($1, lhs parseState) } | SEMICOLON - { warning(Error(FSComp.SR.parsUnexpectedSemicolon(),rhs parseState 1)) - IDefns ([],lhs parseState) } + { warning(Error(FSComp.SR.parsUnexpectedSemicolon(), rhs parseState 1)) + IDefns ([], lhs parseState) } | OBLOCKSEP - { IDefns ([],lhs parseState) } + { IDefns ([], lhs parseState) } interactiveTerminator: @@ -550,7 +554,7 @@ interactiveDefns: interactiveExpr: | opt_attributes opt_declVisibility declExpr { match $2 with - | Some vis -> errorR(Error(FSComp.SR.parsUnexpectedVisibilityDeclaration(vis.ToString()),rhs parseState 3)) + | Some vis -> errorR(Error(FSComp.SR.parsUnexpectedVisibilityDeclaration(vis.ToString()), rhs parseState 3)) | _ -> () let attrDecls = if not (isNil $1) then [ SynModuleDecl.Attributes ($1, rangeOfNonNilAttrs $1) ] else [] in attrDecls @ [ mkSynDoDecl($3)] } @@ -559,21 +563,20 @@ interactiveExpr: /* A #directive interaction in F# Interactive */ interactiveHash: | hashDirective - { [SynModuleDecl.HashDirective($1,rhs parseState 1)] } + { [SynModuleDecl.HashDirective($1, rhs parseState 1)] } /* One or more separators between interactions in F# Interactive */ interactiveSeparators: - | interactiveSeparator { } - | interactiveSeparator interactiveSeparators { } + | interactiveSeparator { } + | interactiveSeparator interactiveSeparators { } /* One separator between interactions in F# Interactive */ interactiveSeparator: | SEMICOLON { } | OBLOCKSEP { } - /*--------------------------------------------------------------------------*/ /* #directives - used by both F# Interactive directives and #nowarn etc. */ @@ -581,7 +584,7 @@ interactiveSeparator: /* A #directive in a module, namespace or an interaction */ hashDirective: | HASH IDENT hashDirectiveArgs - { ParsedHashDirective ($2,$3,lhs parseState) } + { ParsedHashDirective ($2, $3, lhs parseState) } /* The arguments to a #directive */ @@ -614,43 +617,43 @@ signatureFile: /* This will result in NO intellisense for the file! Ideally we wouldn't need this rule */ /* Note: the compiler assumes there is at least one "fragment", so an empty one is used (see 4488) */ | error EOF - { let emptySigFileFrag = ParsedSigFileFragment.AnonModule([],rhs parseState 1) in - ParsedSigFile([],[emptySigFileFrag]) } + { let emptySigFileFrag = ParsedSigFileFragment.AnonModule([], rhs parseState 1) in + ParsedSigFile ([], [emptySigFileFrag]) } /* The start of a module declaration */ moduleIntro: | moduleKeyword opt_access opt_rec path - { $3, $4.Lid, grabXmlDoc(parseState,1), $2 } + { $3, $4.Lid, grabXmlDoc(parseState, 1), $2 } /* The start of a namespace declaration */ namespaceIntro: | NAMESPACE opt_rec path - { $2, $3.Lid, grabXmlDoc(parseState,1) } + { $2, $3.Lid, grabXmlDoc(parseState, 1) } /* The contents of a signature file */ fileNamespaceSpecs: | fileModuleSpec - { ParsedSigFile([],[ ($1 (false,[],PreXmlDoc.Empty)) ]) } + { ParsedSigFile ([], [ ($1 (false, [], PreXmlDoc.Empty)) ]) } | fileModuleSpec fileNamespaceSpecList { // If there are namespaces, the first fileModuleImpl may only contain # directives let decls = - match ($1 (false,[],PreXmlDoc.Empty)) with - | ParsedSigFileFragment.AnonModule(decls,m) -> decls - | ParsedSigFileFragment.NamespaceFragment(_,_,_, decls, _,_,_) -> decls - | ParsedSigFileFragment.NamedModule(SynModuleOrNamespaceSig(_,_,_,_,_,_,_,m)) -> + match ($1 (false, [], PreXmlDoc.Empty)) with + | ParsedSigFileFragment.AnonModule(decls, m) -> decls + | ParsedSigFileFragment.NamespaceFragment(_, _, _, decls, _, _, _) -> decls + | ParsedSigFileFragment.NamedModule(SynModuleOrNamespaceSig(_, _, _, _, _, _, _, m)) -> raiseParseErrorAt m (FSComp.SR.parsOnlyHashDirectivesAllowed()) let decls = decls |> List.collect (function - | (SynModuleSigDecl.HashDirective (hd,_)) -> [hd] + | (SynModuleSigDecl.HashDirective (hd, _)) -> [hd] | d -> reportParseErrorAt d.Range (FSComp.SR.parsOnlyHashDirectivesAllowed()) []) - ParsedSigFile(decls, $2) } + ParsedSigFile (decls, $2) } fileNamespaceSpecList: @@ -662,27 +665,27 @@ fileNamespaceSpecList: fileNamespaceSpec: | namespaceIntro deprecated_opt_equals fileModuleSpec - { let isRec,path,xml = $1 in ($3 (isRec,path,xml)) } + { let isRec, path, xml = $1 in ($3 (isRec, path, xml)) } /* The single module declaration that can make up a signature file */ fileModuleSpec: | opt_attributes opt_declVisibility moduleIntro moduleSpfnsPossiblyEmptyBlock - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) let m2 = rhs parseState 3 - let m = (rhs2 parseState 3 4) - let isRec,path2,xml,vis = $3 - (fun (isRec2,path,_) -> - if not (isNil path) then errorR(Error(FSComp.SR.parsNamespaceOrModuleNotBoth(),m2)) + let m = (rhs2 parseState 1 4) + let isRec, path2, xml, vis = $3 + (fun (isRec2, path, _) -> + if not (isNil path) then errorR(Error(FSComp.SR.parsNamespaceOrModuleNotBoth(), m2)) let lid = path@path2 - ParsedSigFileFragment.NamedModule(SynModuleOrNamespaceSig(lid, (isRec || isRec2), NamedModule, $4, xml,$1,vis,m))) } + ParsedSigFileFragment.NamedModule(SynModuleOrNamespaceSig(lid, (isRec || isRec2), NamedModule, $4, xml, $1, vis, m))) } | moduleSpfnsPossiblyEmptyBlock { let m = (rhs parseState 1) (fun (isRec, path, xml) -> match path with | [] -> ParsedSigFileFragment.AnonModule($1, m) - | _ -> ParsedSigFileFragment.NamespaceFragment(path, isRec, DeclaredNamespace, $1, xml,[],m)) } + | _ -> ParsedSigFileFragment.NamespaceFragment(path, isRec, DeclaredNamespace, $1, xml, [], m)) } moduleSpfnsPossiblyEmptyBlock: @@ -726,42 +729,42 @@ moduleSpfns: moduleSpfn: | hashDirective - { SynModuleSigDecl.HashDirective ($1,rhs2 parseState 1 1) } + { SynModuleSigDecl.HashDirective ($1, rhs2 parseState 1 1) } | valSpfn { $1 } | opt_attributes opt_declVisibility moduleIntro colonOrEquals namedModuleAbbrevBlock - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) let isRec, path, xml, vis = $3 if isRec then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsInvalidUseOfRec()) if not (isSingleton path) then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsModuleAbbreviationMustBeSimpleName()) if not (isNil $1) then raiseParseErrorAt (rhs parseState 1) (FSComp.SR.parsIgnoreAttributesOnModuleAbbreviation()) match vis with | Some vis -> raiseParseErrorAt (rhs parseState 1) (FSComp.SR.parsIgnoreVisibilityOnModuleAbbreviationAlwaysPrivate(vis.ToString())) - | _ -> SynModuleSigDecl.ModuleAbbrev(List.head path,$5,rhs2 parseState 3 5) } + | _ -> SynModuleSigDecl.ModuleAbbrev(List.head path, $5, rhs2 parseState 1 5) } | opt_attributes opt_declVisibility moduleIntro colonOrEquals moduleSpecBlock { let isRec, path, xml, vis = $3 if not (isSingleton path) then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsModuleDefnMustBeSimpleName()) if isRec then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsInvalidUseOfRec()) - let info = ComponentInfo($1,[],[],path,xml,false,vis,rhs parseState 3) - if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - SynModuleSigDecl.NestedModule(info, isRec, $5, rhs2 parseState 3 5) } + let info = ComponentInfo($1, [], [], path, xml, false, vis, rhs parseState 3) + if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + SynModuleSigDecl.NestedModule(info, isRec, $5, rhs2 parseState 1 5) } | opt_attributes opt_declVisibility tyconSpfns - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - let (TypeDefnSig(ComponentInfo(cas,a,cs,b,c,d,d2,d3),e,f,g)),rest = + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + let (TypeDefnSig(ComponentInfo(cas, a, cs, b, c, d, d2, d3), e, f, g)), rest = match $3 with | [] -> raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsUnexpectedEmptyModuleDefn()) - | h::t -> h,t - let tc = (TypeDefnSig(ComponentInfo($1@cas,a,cs,b,c,d,d2,d3),e,f,g))in - SynModuleSigDecl.Types (tc::rest,rhs parseState 3) } + | h :: t -> h, t + let tc = (TypeDefnSig(ComponentInfo($1@cas, a, cs, b, c, d, d2, d3), e, f, g))in + SynModuleSigDecl.Types (tc :: rest, rhs parseState 3) } | opt_attributes opt_declVisibility exconSpfn - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - let (SynExceptionSig(SynExceptionDefnRepr(cas,a,b,c,d,d2),e,f)) = $3 - let ec = (SynExceptionSig(SynExceptionDefnRepr($1@cas,a,b,c,d,d2),e,f)) + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + let (SynExceptionSig(SynExceptionDefnRepr(cas, a, b, c, d, d2), e, f)) = $3 + let ec = (SynExceptionSig(SynExceptionDefnRepr($1@cas, a, b, c, d, d2), e, f)) SynModuleSigDecl.Exception(ec, rhs parseState 3) } | OPEN path @@ -769,12 +772,12 @@ moduleSpfn: valSpfn: | opt_attributes opt_declVisibility VAL opt_attributes opt_inline opt_mutable opt_access nameop opt_explicitValTyparDecls COLON topTypeWithTypeConstraints optLiteralValueSpfn - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - let attr1,attr2,isInline,isMutable,vis2,id,doc,explicitValTyparDecls,(ty,arity),konst = ($1),($4),($5),($6),($7),($8),grabXmlDoc(parseState,3),($9),($11),($12) - if not (isNil attr2) then errorR(Deprecated(FSComp.SR.parsAttributesMustComeBeforeVal(),rhs parseState 4)) - let m = rhs2 parseState 3 11 - let valSpfn = ValSpfn((attr1@attr2),id,explicitValTyparDecls,ty,arity,isInline,isMutable,doc, vis2,konst,m) - SynModuleSigDecl.Val(valSpfn,m) + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + let attr1, attr2, isInline, isMutable, vis2, id, doc, explicitValTyparDecls, (ty, arity), konst = ($1), ($4), ($5), ($6), ($7), ($8), grabXmlDoc(parseState, 3), ($9), ($11), ($12) + if not (isNil attr2) then errorR(Deprecated(FSComp.SR.parsAttributesMustComeBeforeVal(), rhs parseState 4)) + let m = rhs2 parseState 1 11 + let valSpfn = ValSpfn((attr1@attr2), id, explicitValTyparDecls, ty, arity, isInline, isMutable, doc, vis2, konst, m) + SynModuleSigDecl.Val(valSpfn, m) } /* The optional literal value on a literal specification in a signature */ @@ -785,7 +788,7 @@ optLiteralValueSpfn: | EQUALS declExpr { Some($2) } - | EQUALS OBLOCKBEGIN declExpr oblockend + | EQUALS OBLOCKBEGIN declExpr oblockend opt_ODECLEND { Some($3) } @@ -825,7 +828,7 @@ tyconSpfn: { let lhsm = rhs parseState 1 $3 lhsm $1 } | typeNameInfo opt_classSpfn - { TypeDefnSig($1,SynTypeDefnSigRepr.Simple (SynTypeDefnSimpleRepr.None (lhs parseState),lhs parseState),$2,lhs parseState) } + { TypeDefnSig($1, SynTypeDefnSigRepr.Simple (SynTypeDefnSimpleRepr.None (lhs parseState), lhs parseState), $2, lhs parseState) } /* The right-hand-side of a type definition in a signature */ @@ -854,41 +857,41 @@ tyconSpfnRhs: | tyconDefnOrSpfnSimpleRepr { let m = $1.Range (fun lhsm nameInfo augmentation -> - TypeDefnSig(nameInfo,SynTypeDefnSigRepr.Simple ($1,m),augmentation,m)) } + TypeDefnSig(nameInfo, SynTypeDefnSigRepr.Simple ($1, m), augmentation, m)) } | tyconClassSpfn { let m = lhs parseState - let needsCheck,(kind,decls) = $1 + let needsCheck, (kind, decls) = $1 (fun nameRange nameInfo augmentation -> if needsCheck && isNil decls then reportParseErrorAt nameRange (FSComp.SR.parsEmptyTypeDefinition()) - TypeDefnSig(nameInfo,SynTypeDefnSigRepr.ObjectModel (kind,decls,m),augmentation,m)) } + TypeDefnSig(nameInfo, SynTypeDefnSigRepr.ObjectModel (kind, decls, m), augmentation, m)) } | DELEGATE OF topType { let m = lhs parseState - let ty,arity = $3 - let invoke = SynMemberSig.Member(ValSpfn([],mkSynId m "Invoke",inferredTyparDecls,ty,arity,false,false,PreXmlDoc.Empty,None,None,m),AbstractMemberFlags MemberKind.Member,m) + let ty, arity = $3 + let invoke = SynMemberSig.Member(ValSpfn([], mkSynId m "Invoke", inferredTyparDecls, ty, arity, false, false, PreXmlDoc.Empty, None, None, m), AbstractMemberFlags MemberKind.Member, m) (fun nameRange nameInfo augmentation -> if not (isNil augmentation) then raiseParseErrorAt m (FSComp.SR.parsAugmentationsIllegalOnDelegateType()) - TypeDefnSig(nameInfo,SynTypeDefnSigRepr.ObjectModel (TyconDelegate (ty,arity),[invoke],m),[],m)) } + TypeDefnSig(nameInfo, SynTypeDefnSigRepr.ObjectModel (TyconDelegate (ty, arity), [invoke], m), [], m)) } /* The right-hand-side of an object type definition in a signature */ tyconClassSpfn: | classSpfnBlockKindUnspecified - { let needsCheck,decls = $1 - needsCheck,(TyconUnspecified, decls) } + { let needsCheck, decls = $1 + needsCheck, (TyconUnspecified, decls) } | classOrInterfaceOrStruct classSpfnBlock END - { false,($1,$2) } + { false, ($1, $2) } | classOrInterfaceOrStruct classSpfnBlock recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedClassInterfaceOrStruct()) - false,($1,$2) } + false, ($1, $2) } | classOrInterfaceOrStruct error END { // silent recovery - false,($1,[]) } + false, ($1, []) } /* The right-hand-side of an object type definition in a signature with no explicit kind */ @@ -937,49 +940,51 @@ classSpfnMembersAtLeastOne: /* A object member in a signature */ classMemberSpfn: | opt_attributes opt_declVisibility memberSpecFlags opt_inline opt_access nameop opt_explicitValTyparDecls COLON topTypeWithTypeConstraints classMemberSpfnGetSet optLiteralValueSpfn - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - let isInline,doc,vis2,id,explicitValTyparDecls,(ty,arity),optLiteralValue = $4,grabXmlDoc(parseState,3),$5,$6,$7,$9,$11 + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + let isInline, doc, vis2, id, explicitValTyparDecls, (ty, arity), optLiteralValue = $4, grabXmlDoc(parseState, 3), $5, $6, $7, $9, $11 let getSetRangeOpt, getSet = $10 - let getSetAdjuster arity = match arity,getSet with SynValInfo([],_),MemberKind.Member -> MemberKind.PropertyGet | _ -> getSet + let getSetAdjuster arity = match arity, getSet with SynValInfo([], _), MemberKind.Member -> MemberKind.PropertyGet | _ -> getSet let wholeRange = let m = rhs parseState 3 match getSetRangeOpt with | None -> unionRanges m ty.Range | Some m2 -> unionRanges m m2 - let valSpfn = ValSpfn($1,id,explicitValTyparDecls,ty,arity, isInline,false,doc, vis2,optLiteralValue,wholeRange) - let _,flags = $3 - SynMemberSig.Member(valSpfn, flags (getSetAdjuster arity),wholeRange) } + let valSpfn = ValSpfn($1, id, explicitValTyparDecls, ty, arity, isInline, false, doc, vis2, optLiteralValue, wholeRange) + let _, flags = $3 + SynMemberSig.Member(valSpfn, flags (getSetAdjuster arity), wholeRange) } | opt_attributes opt_declVisibility interfaceMember appType - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - SynMemberSig.Interface ($4,unionRanges (rhs parseState 3) ($4).Range) } + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + SynMemberSig.Interface ($4, unionRanges (rhs parseState 3) ($4).Range) } | opt_attributes opt_declVisibility INHERIT appType - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - SynMemberSig.Inherit ($4,unionRanges (rhs parseState 3) ($4).Range) } + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + SynMemberSig.Inherit ($4, unionRanges (rhs parseState 3) ($4).Range) } | opt_attributes opt_declVisibility VAL fieldDecl - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - let fld = $4 $1 false - SynMemberSig.ValField(fld,rhs2 parseState 3 4) } + { let wholeRange = rhs2 parseState 1 4 + if Option.isSome $2 then errorR (Error (FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier (), rhs parseState 2)) + let fld = $4 $1 false wholeRange + SynMemberSig.ValField (fld, wholeRange) } | opt_attributes opt_declVisibility STATIC VAL fieldDecl - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - SynMemberSig.ValField($5 $1 true,rhs2 parseState 3 5) } + { let wholeRange = rhs2 parseState 1 5 + if Option.isSome $2 then errorR (Error (FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier (), rhs parseState 2)) + SynMemberSig.ValField($5 $1 true wholeRange, wholeRange) } | opt_attributes opt_declVisibility STATIC typeKeyword tyconSpfn - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - SynMemberSig.NestedType($5,rhs2 parseState 3 5) } + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + SynMemberSig.NestedType($5, rhs2 parseState 1 5) } | opt_attributes opt_declVisibility NEW COLON topTypeWithTypeConstraints - { let vis,doc,(ty,valSynInfo) = $2,grabXmlDoc(parseState,3),$5 - let m = unionRanges (rhs parseState 3) ty.Range + { let vis, doc, (ty, valSynInfo) = $2, grabXmlDoc(parseState, 3), $5 + let m = unionRanges (rhs parseState 1) ty.Range let isInline = false let valSpfn = ValSpfn ($1, mkSynId (rhs parseState 3) "new", noInferredTypars, ty, valSynInfo, isInline, false, doc, vis, None, m) - SynMemberSig.Member(valSpfn, CtorMemberFlags,m) } + SynMemberSig.Member(valSpfn, CtorMemberFlags, m) } -/* The optional "with get,set" on a member in a signature */ +/* The optional "with get, set" on a member in a signature */ classMemberSpfnGetSet: | /* EMPTY */ { None, MemberKind.Member } @@ -995,7 +1000,7 @@ classMemberSpfnGetSet: Some (rhs2 parseState 1 2), $2 } -/* The "get,set" on a property member in a signature */ +/* The "get, set" on a property member in a signature */ classMemberSpfnGetSetElements: | nameop { (let (id:Ident) = $1 @@ -1012,14 +1017,14 @@ classMemberSpfnGetSetElements: memberSpecFlags: | memberFlags { $1 } - | ABSTRACT { (false,AbstractMemberFlags) } - | ABSTRACT MEMBER { (false,AbstractMemberFlags) } + | ABSTRACT { (false, AbstractMemberFlags) } + | ABSTRACT MEMBER { (false, AbstractMemberFlags) } /* Part of an exception definition in a signature file */ exconSpfn: | exconCore opt_classSpfn - { SynExceptionSig($1,$2,lhs parseState) } + { SynExceptionSig($1, $2, lhs parseState) } /* The optional augmentation on a type definition in a signature */ @@ -1046,30 +1051,30 @@ implementationFile: /* This will result in NO intellisense for the file! Ideally we wouldn't need this rule */ /* Note: the compiler assumes there is at least one "fragment", so an empty one is used (see 4488) */ | error EOF - { let emptyImplFileFrag = ParsedImplFileFragment.AnonModule([],rhs parseState 1) in - ParsedImplFile([],[emptyImplFileFrag]) } + { let emptyImplFileFrag = ParsedImplFileFragment.AnonModule([], rhs parseState 1) in + ParsedImplFile ([], [emptyImplFileFrag]) } /* The sequence of namespace definitions or a single module definition that makes up an implementation file */ fileNamespaceImpls: | fileModuleImpl - { ParsedImplFile([], [ ($1 (false,[],PreXmlDoc.Empty)) ]) } + { ParsedImplFile ([], [ ($1 (false, [], PreXmlDoc.Empty)) ]) } | fileModuleImpl fileNamespaceImplList { // If there are namespaces, the first fileModuleImpl may only contain # directives let decls = - match ($1 (false,[],PreXmlDoc.Empty)) with - | ParsedImplFileFragment.AnonModule(decls,m) -> decls - | ParsedImplFileFragment.NamespaceFragment(_,_,_, decls, _,_,_) -> decls - | ParsedImplFileFragment.NamedModule(SynModuleOrNamespace(_,_,_,_,_,_,_,m)) -> + match ($1 (false, [], PreXmlDoc.Empty)) with + | ParsedImplFileFragment.AnonModule(decls, m) -> decls + | ParsedImplFileFragment.NamespaceFragment(_, _, _, decls, _, _, _) -> decls + | ParsedImplFileFragment.NamedModule(SynModuleOrNamespace(_, _, _, _, _, _, _, m)) -> raiseParseErrorAt m (FSComp.SR.parsOnlyHashDirectivesAllowed()) let decls = decls |> List.collect (function - | (SynModuleDecl.HashDirective (hd,_)) -> [hd] + | (SynModuleDecl.HashDirective (hd, _)) -> [hd] | d -> reportParseErrorAt d.Range (FSComp.SR.parsOnlyHashDirectivesAllowed()) []) - ParsedImplFile(decls, $2) } + ParsedImplFile (decls, $2) } /* The sequence of namespace definitions that can make up an implementation file */ @@ -1090,21 +1095,21 @@ fileNamespaceImpl: /* A single module definition in an implementation file */ fileModuleImpl: | opt_attributes opt_declVisibility moduleIntro moduleDefnsOrExprPossiblyEmptyOrBlock - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) let m2 = rhs parseState 3 let m = (m2, $4) ||> unionRangeWithListBy (fun modu -> modu.Range) - let isRec2,path2,xml,vis = $3 + let isRec2, path2, xml, vis = $3 (fun (isRec, path, _) -> - if not (isNil path) then errorR(Error(FSComp.SR.parsNamespaceOrModuleNotBoth(),m2)) + if not (isNil path) then errorR(Error(FSComp.SR.parsNamespaceOrModuleNotBoth(), m2)) let lid = path@path2 - ParsedImplFileFragment.NamedModule(SynModuleOrNamespace(lid, (isRec || isRec2), NamedModule, $4, xml,$1,vis,m))) } + ParsedImplFileFragment.NamedModule(SynModuleOrNamespace(lid, (isRec || isRec2), NamedModule, $4, xml, $1, vis, m))) } | moduleDefnsOrExprPossiblyEmptyOrBlock { let m = (rhs parseState 1) (fun (isRec, path, xml) -> match path with - | [] -> ParsedImplFileFragment.AnonModule($1,m) - | _ -> ParsedImplFileFragment.NamespaceFragment(path, isRec, DeclaredNamespace, $1, xml,[],m)) } + | [] -> ParsedImplFileFragment.AnonModule($1, m) + | _ -> ParsedImplFileFragment.NamespaceFragment(path, isRec, DeclaredNamespace, $1, xml, [], m)) } /* A collection/block of definitions or expressions making up a module or namespace, possibly empty */ @@ -1138,21 +1143,21 @@ moduleDefnsOrExprPossiblyEmpty: moduleDefnsOrExpr: | opt_attributes opt_declVisibility declExpr topSeparators moduleDefnsOrExpr { match $2 with - | Some vis -> errorR(Error(FSComp.SR.parsUnexpectedVisibilityDeclaration(vis.ToString()),rhs parseState 3)) + | Some vis -> errorR(Error(FSComp.SR.parsUnexpectedVisibilityDeclaration(vis.ToString()), rhs parseState 3)) | _ -> () let attrDecls = if not (isNil $1) then [ SynModuleDecl.Attributes ($1, rangeOfNonNilAttrs $1) ] else [] attrDecls @ mkSynDoDecl ($3) :: $5 } | opt_attributes opt_declVisibility declExpr topSeparators { match $2 with - | Some vis -> errorR(Error(FSComp.SR.parsUnexpectedVisibilityDeclaration(vis.ToString()),rhs parseState 3)) + | Some vis -> errorR(Error(FSComp.SR.parsUnexpectedVisibilityDeclaration(vis.ToString()), rhs parseState 3)) | _ -> () let attrDecls = if not (isNil $1) then [ SynModuleDecl.Attributes ($1, rangeOfNonNilAttrs $1) ] else [] attrDecls @ [ mkSynDoDecl($3) ] } | opt_attributes opt_declVisibility declExpr { match $2 with - | Some vis -> errorR(Error(FSComp.SR.parsUnexpectedVisibilityDeclaration(vis.ToString()),rhs parseState 3)) + | Some vis -> errorR(Error(FSComp.SR.parsUnexpectedVisibilityDeclaration(vis.ToString()), rhs parseState 3)) | _ -> () let attrDecls = if not (isNil $1) then [ SynModuleDecl.Attributes ($1, rangeOfNonNilAttrs $1) ] else [] attrDecls @ [ mkSynDoDecl($3) ] } @@ -1188,7 +1193,7 @@ moduleDefnOrDirective: { $1 } | hashDirective - { [ SynModuleDecl.HashDirective ($1,rhs2 parseState 1 1) ] } + { [ SynModuleDecl.HashDirective ($1, rhs2 parseState 1 1) ] } /* A single definition in a namespace, module or interaction. */ @@ -1197,62 +1202,62 @@ moduleDefn: /* 'let' definitions in non-#light*/ | opt_attributes opt_declVisibility defnBindings %prec decl_let - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) parseState.ResetSynArgNameGenerator() - let (BindingSetPreAttrs(_,_,_,_,mWhole)) = $3 - mkDefnBindings (mWhole,$3,$1,$2,mWhole) } + let (BindingSetPreAttrs(_, _, _, _, mWhole)) = $3 + mkDefnBindings (mWhole, $3, $1, $2, mWhole) } /* 'let' or 'do' definitions in #light */ | opt_attributes opt_declVisibility hardwhiteLetBindings %prec decl_let - { let hwlb,m = $3 - if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) + { let hwlb, m = $3 + if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) parseState.ResetSynArgNameGenerator() - mkDefnBindings (m,hwlb,$1,$2,m) } + mkDefnBindings (m, hwlb, $1, $2, m) } /* 'do' definitions in non-#light*/ | opt_attributes opt_declVisibility doBinding %prec decl_let - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) let mWhole = rhs parseState 3 - mkDefnBindings (mWhole,$3,$1,$2,mWhole) } + mkDefnBindings (mWhole, $3, $1, $2, mWhole) } /* 'type' definitions */ | opt_attributes opt_declVisibility typeKeyword tyconDefn tyconDefnList - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - let (TypeDefn(ComponentInfo(cas,a,cs,b,c,d,d2,d3),e,f,g)) = $4 - let tc = (TypeDefn(ComponentInfo($1@cas,a,cs,b,c,d,d2,d3),e,f,g)) + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + let (TypeDefn(ComponentInfo(cas, a, cs, b, c, d, d2, d3), e, f, g)) = $4 + let tc = (TypeDefn(ComponentInfo($1@cas, a, cs, b, c, d, d2, d3), e, f, g)) let types = tc :: $5 [ SynModuleDecl.Types(types, (rhs parseState 3, types) ||> unionRangeWithListBy (fun t -> t.Range) ) ] } /* 'exception' definitions */ | opt_attributes opt_declVisibility exconDefn - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - let (SynExceptionDefn(SynExceptionDefnRepr(cas,a,b,c,d,d2),e,f)) = $3 + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + let (SynExceptionDefn(SynExceptionDefnRepr(cas, a, b, c, d, d2), e, f)) = $3 let f = (f, $1) ||> unionRangeWithListBy (fun a -> a.Range) - let ec = (SynExceptionDefn(SynExceptionDefnRepr($1@cas,a,b,c,d,d2),e,f)) + let ec = (SynExceptionDefn(SynExceptionDefnRepr($1@cas, a, b, c, d, d2), e, f)) [ SynModuleDecl.Exception(ec, f) ] } /* 'module' definitions */ | opt_attributes opt_declVisibility moduleIntro EQUALS namedModuleDefnBlock - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - let attribs, (isRec, path, xml, vis) = $1,$3 + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + let attribs, (isRec, path, xml, vis) = $1, $3 match $5 with | Choice1Of2 eqn -> - if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) + if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) if isRec then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsInvalidUseOfRec()) if not (isSingleton path) then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsModuleAbbreviationMustBeSimpleName()) if not (isNil $1) then raiseParseErrorAt (rhs parseState 1) (FSComp.SR.parsIgnoreAttributesOnModuleAbbreviation()) match vis with | Some vis -> raiseParseErrorAt (rhs parseState 1) (FSComp.SR.parsIgnoreAttributesOnModuleAbbreviationAlwaysPrivate(vis.ToString())) | _ -> () - [ SynModuleDecl.ModuleAbbrev(List.head path,eqn,(rhs parseState 3, eqn) ||> unionRangeWithListBy (fun id -> id.idRange) ) ] + [ SynModuleDecl.ModuleAbbrev(List.head path, eqn, (rhs parseState 3, eqn) ||> unionRangeWithListBy (fun id -> id.idRange) ) ] | Choice2Of2 def -> if not (isSingleton path) then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsModuleAbbreviationMustBeSimpleName()) - let info = ComponentInfo(attribs,[],[],path,xml,false,vis,rhs parseState 3) - [ SynModuleDecl.NestedModule(info, isRec, def, false,(rhs2 parseState 3 4, def) ||> unionRangeWithListBy (fun d -> d.Range) ) ] } + let info = ComponentInfo(attribs, [], [], path, xml, false, vis, rhs parseState 3) + [ SynModuleDecl.NestedModule(info, isRec, def, false, (rhs2 parseState 1 4, def) ||> unionRangeWithListBy (fun d -> d.Range) ) ] } /* unattached custom attributes */ | attributes recover - { errorR(Error(FSComp.SR.parsAttributeOnIncompleteCode(),rhs parseState 1)) + { errorR(Error(FSComp.SR.parsAttributeOnIncompleteCode(), rhs parseState 1)) [] } /* 'open' declarations */ @@ -1300,7 +1305,7 @@ namedModuleDefnBlock: // However in that case we do use type name lookup to make the resolution. match $2 with - | [ SynModuleDecl.DoExpr (_,LongOrSingleIdent(false,LongIdentWithDots(path,_),None,_),_) ] -> + | [ SynModuleDecl.DoExpr (_, LongOrSingleIdent(false, LongIdentWithDots(path, _), None, _), _) ] -> Choice1Of2 path | _ -> Choice2Of2 $2 @@ -1357,20 +1362,20 @@ attributes: /* One set of custom attributes, including [< ... >] */ -attributeList: - | LBRACK_LESS attributeListElements opt_seps GREATER_RBRACK opt_OBLOCKSEP - { $2 } +attributeList: + | LBRACK_LESS attributeListElements opt_seps GREATER_RBRACK opt_OBLOCKSEP + { mkAttributeList $2 (rhs2 parseState 1 3) } - | LBRACK_LESS error GREATER_RBRACK opt_OBLOCKSEP - { [] } + | LBRACK_LESS error GREATER_RBRACK opt_OBLOCKSEP + { mkAttributeList [] (rhs2 parseState 1 3) } - | LBRACK_LESS attributeListElements opt_seps ends_coming_soon_or_recover + | LBRACK_LESS attributeListElements opt_seps ends_coming_soon_or_recover { if not $4 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedLBrackLess()) - $2 } + mkAttributeList $2 (rhs2 parseState 1 2) } - | LBRACK_LESS ends_coming_soon_or_recover + | LBRACK_LESS ends_coming_soon_or_recover { if not $2 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedLBrackLess()) - [] } + mkAttributeList [] (rhs parseState 1) } /* One set of custom attributes, not including [< ... >] */ @@ -1403,31 +1408,31 @@ attribute: /* The target of a custom attribute */ attributeTarget: | moduleKeyword COLON - { Some(ident("module",(rhs parseState 1))) } + { Some(ident("module", (rhs parseState 1))) } | typeKeyword COLON - { Some(ident("type",(rhs parseState 1))) } + { Some(ident("type", (rhs parseState 1))) } | ident COLON { Some($1) } /* return */ | YIELD COLON { if $1 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsSyntaxError()) - Some(ident("return",(rhs parseState 1))) } + Some(ident("return", (rhs parseState 1))) } /* Flags on a member */ memberFlags: - | STATIC MEMBER { (true,StaticMemberFlags) } - | MEMBER { (false,NonVirtualMemberFlags) } - | OVERRIDE { (false,OverrideMemberFlags) } - | DEFAULT { (false,OverrideMemberFlags) } + | STATIC MEMBER { (true, StaticMemberFlags) } + | MEMBER { (false, NonVirtualMemberFlags) } + | OVERRIDE { (false, OverrideMemberFlags) } + | DEFAULT { (false, OverrideMemberFlags) } /* The name of a type in a signature or implementation, possibly with type parameters and constraints */ typeNameInfo: | opt_attributes tyconNameAndTyparDecls opt_typeConstraints - { let typars,lid,fixity,tpcs1,vis,xmlDoc = $2 + { let typars, lid, fixity, tpcs1, vis, xmlDoc = $2 let tpcs2 = $3 - ComponentInfo($1,typars,(tpcs1 @ tpcs2),lid,xmlDoc,fixity,vis,rangeOfLid lid) } + ComponentInfo($1, typars, (tpcs1 @ tpcs2), lid, xmlDoc, fixity, vis, rangeOfLid lid) } /* Part of a set of type definitions */ tyconDefnList: @@ -1439,33 +1444,33 @@ tyconDefnList: /* A type definition */ tyconDefn: | typeNameInfo - { TypeDefn($1,SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.None($1.Range),$1.Range),[],$1.Range) } + { TypeDefn($1, SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.None($1.Range), $1.Range), [], $1.Range) } | typeNameInfo EQUALS tyconDefnRhsBlock { let nameRange = rhs parseState 1 - let (tcDefRepr:SynTypeDefnRepr),members = $3 nameRange + let (tcDefRepr:SynTypeDefnRepr), members = $3 nameRange let declRange = unionRanges (rhs parseState 1) tcDefRepr.Range let mWhole = (declRange, members) ||> unionRangeWithListBy (fun (mem:SynMemberDefn) -> mem.Range) TypeDefn($1, tcDefRepr, members, mWhole) } | typeNameInfo tyconDefnAugmentation { let m = (rhs parseState 1, $2) ||> unionRangeWithListBy (fun mem -> mem.Range) - TypeDefn($1,SynTypeDefnRepr.ObjectModel(TyconAugmentation,[],m),$2,m) } + TypeDefn($1, SynTypeDefnRepr.ObjectModel(TyconAugmentation, [], m), $2, m) } | typeNameInfo opt_attributes opt_declVisibility opt_HIGH_PRECEDENCE_APP simplePatterns optAsSpec EQUALS tyconDefnRhsBlock - { let vis,spats, az = $3,$5,$6 + { let vis, spats, az = $3, $5, $6 let nameRange = rhs parseState 1 - let (tcDefRepr,members) = $8 nameRange - let (ComponentInfo(_,_,_,lid,_,_,_,_)) = $1 - let memberCtorPattern = SynMemberDefn.ImplicitCtor (vis,$2,spats,az,rangeOfLid lid) + let (tcDefRepr, members) = $8 nameRange + let (ComponentInfo(_, _, _, lid, _, _, _, _)) = $1 + let memberCtorPattern = SynMemberDefn.ImplicitCtor (vis, $2, spats, az, rangeOfLid lid) let tcDefRepr = match tcDefRepr with - | SynTypeDefnRepr.ObjectModel (k,cspec,m) -> SynTypeDefnRepr.ObjectModel (k,memberCtorPattern::cspec,m) + | SynTypeDefnRepr.ObjectModel (k, cspec, m) -> SynTypeDefnRepr.ObjectModel (k, memberCtorPattern :: cspec, m) | _ -> reportParseErrorAt (rhs2 parseState 1 5) (FSComp.SR.parsOnlyClassCanTakeValueArguments()); tcDefRepr let declRange = unionRanges (rhs parseState 1) tcDefRepr.Range let mWhole = (declRange, members) ||> unionRangeWithListBy (fun (mem:SynMemberDefn) -> mem.Range) - TypeDefn($1,tcDefRepr,members,mWhole) } + TypeDefn($1, tcDefRepr, members, mWhole) } /* The right-hand-side of a type definition */ @@ -1498,48 +1503,48 @@ tyconDefnRhs: /* A simple type definition */ | tyconDefnOrSpfnSimpleRepr { let m = $1.Range - (fun nameRange augmentation -> SynTypeDefnRepr.Simple ($1,m),augmentation) } + (fun nameRange augmentation -> SynTypeDefnRepr.Simple ($1, m), augmentation) } /* An object type definition */ | tyconClassDefn - { let needsCheck,(kind,decls),mopt = $1 + { let needsCheck, (kind, decls), mopt = $1 let m = match mopt with | None -> (lhs parseState).StartRange // create a zero-width range | Some m -> m (fun nameRange augmentation -> if needsCheck && isNil decls then reportParseErrorAt nameRange (FSComp.SR.parsEmptyTypeDefinition()) - SynTypeDefnRepr.ObjectModel (kind,decls,m),augmentation) } + SynTypeDefnRepr.ObjectModel (kind, decls, m), augmentation) } /* A delegate type definition */ | DELEGATE OF topType { let m = lhs parseState - let ty,arity = $3 + let ty, arity = $3 (fun nameRange augmentation -> - let valSpfn = ValSpfn([],mkSynId m "Invoke",inferredTyparDecls,ty,arity,false,false,PreXmlDoc.Empty,None,None,m) - let invoke = SynMemberDefn.AbstractSlot(valSpfn,AbstractMemberFlags MemberKind.Member,m) + let valSpfn = ValSpfn([], mkSynId m "Invoke", inferredTyparDecls, ty, arity, false, false, PreXmlDoc.Empty, None, None, m) + let invoke = SynMemberDefn.AbstractSlot(valSpfn, AbstractMemberFlags MemberKind.Member, m) if not (isNil augmentation) then raiseParseErrorAt m (FSComp.SR.parsAugmentationsIllegalOnDelegateType()) - SynTypeDefnRepr.ObjectModel (TyconDelegate (ty,arity),[invoke],m),[]) } + SynTypeDefnRepr.ObjectModel (TyconDelegate (ty, arity), [invoke], m), []) } /* The right-hand-side of a object type definition */ tyconClassDefn: | classDefnBlockKindUnspecified - { let needsCheck,decls,mopt = $1 - needsCheck,(TyconUnspecified, decls),mopt } + { let needsCheck, decls, mopt = $1 + needsCheck, (TyconUnspecified, decls), mopt } | classOrInterfaceOrStruct classDefnBlock END { let m = (rhs parseState 1, $2) ||> unionRangeWithListBy (fun (d:SynMemberDefn) -> d.Range) - false,($1,$2),Some(m) } + false, ($1, $2), Some(m) } | classOrInterfaceOrStruct classDefnBlock recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedClassInterfaceOrStruct()) let m = (rhs parseState 1, $2) ||> unionRangeWithListBy (fun (d:SynMemberDefn) -> d.Range) - false,($1,$2),Some(m) } + false, ($1, $2), Some(m) } | classOrInterfaceOrStruct error END { // silent recovery - false,($1,[]),Some(rhs parseState 1) } + false, ($1, []), Some(rhs parseState 1) } /* The right-hand-side of a object type definition where the class/interface/struct kind has not been specified */ @@ -1548,14 +1553,14 @@ classDefnBlockKindUnspecified: { if not $3 then reportParseErrorAt (rhs parseState 3) (FSComp.SR.parsUnexpectedEndOfFileTypeDefinition()) let mopt = match $2 with - | _::_ -> Some( (rhs parseState 1, $2) ||> unionRangeWithListBy (fun (d:SynMemberDefn) -> d.Range) ) + | _ :: _ -> Some( (rhs parseState 1, $2) ||> unionRangeWithListBy (fun (d:SynMemberDefn) -> d.Range) ) | _ -> None - false,$2,mopt } + false, $2, mopt } | OBLOCKBEGIN classDefnMembers oblockend { let mopt = match $2 with - | _::_ -> Some( (rhs parseState 1, $2) ||> unionRangeWithListBy (fun (d:SynMemberDefn) -> d.Range) ) + | _ :: _ -> Some( (rhs parseState 1, $2) ||> unionRangeWithListBy (fun (d:SynMemberDefn) -> d.Range) ) | _ -> None true, $2, mopt } @@ -1592,7 +1597,7 @@ classDefnMembersAtLeastOne: { $1 @ $3 } -/* The "with get,set" part of a member definition */ +/* The "with get, set" part of a member definition */ classDefnMemberGetSet: | WITH classDefnMemberGetSetElements { $2 } @@ -1604,7 +1609,7 @@ classDefnMemberGetSet: { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedWith()) $2 } -/* The "get,set" part of a member definition */ +/* The "get, set" part of a member definition */ classDefnMemberGetSetElements: | classDefnMemberGetSetElement { [$1] } @@ -1614,93 +1619,98 @@ classDefnMemberGetSetElements: classDefnMemberGetSetElement: | opt_inline opt_attributes bindingPattern opt_topReturnTypeWithTypeConstraints EQUALS typedSeqExprBlock { let mRhs = ($6 : SynExpr).Range - ($1,$2,$3,$4,$6,mRhs) } + ($1, $2, $3, $4, $6, mRhs) } /* The core of a member definition */ memberCore: /* Methods and simple getter properties */ - | opt_inline bindingPattern opt_topReturnTypeWithTypeConstraints EQUALS typedSeqExprBlock - { let mRhs = $5.Range - let mWhole = unionRanges (rhs2 parseState 3 4) mRhs - let optReturnType = $3 - let bindingBuilder,mBindLhs = $2 - (fun vis memFlagsBuilder attrs -> - [ SynMemberDefn.Member (bindingBuilder (vis,$1,false,mBindLhs,NoSequencePointAtInvisibleBinding,optReturnType,$5,mRhs,[],attrs,Some(memFlagsBuilder MemberKind.Member)),unionRanges mWhole mBindLhs) ]) } + | opt_inline bindingPattern opt_topReturnTypeWithTypeConstraints EQUALS typedSeqExprBlock + { let mRhs = $5.Range + let optReturnType = $3 + let bindingBuilder, mBindLhs = $2 + (fun vis memFlagsBuilder attrs rangeStart -> + let memberFlags = Some (memFlagsBuilder MemberKind.Member) + let binding = bindingBuilder (vis, $1, false, mBindLhs, NoDebugPointAtInvisibleBinding, optReturnType, $5, mRhs, [], attrs, memberFlags) + let memberRange = unionRanges rangeStart mRhs + [ SynMemberDefn.Member (binding, memberRange) ]) } /* Properties with explicit get/set, also indexer properties */ - | opt_inline bindingPattern opt_topReturnTypeWithTypeConstraints classDefnMemberGetSet - { let mWhole = (rhs parseState 2, $4) ||> unionRangeWithListBy (fun (_,_,_,_,_,m2) -> m2) - let propertyNameBindingBuilder,_ = $2 + | opt_inline bindingPattern opt_topReturnTypeWithTypeConstraints classDefnMemberGetSet + { let mWhole = (rhs parseState 2, $4) ||> unionRangeWithListBy (fun (_, _, _, _, _, m2) -> m2) + let propertyNameBindingBuilder, _ = $2 let optPropertyType = $3 let isMutable = false - (fun visNoLongerUsed memFlagsBuilder attrs -> + (fun visNoLongerUsed memFlagsBuilder attrs rangeStart -> let hasGet = ref false let hasSet = ref false // Iterate over 1 or 2 'get'/'set' entries - $4 |> List.choose (fun (optInline,optAttrs,(bindingBuilder,mBindLhs),optReturnType,expr,exprm) -> + $4 |> List.choose (fun (optInline, optAttrs, (bindingBuilder, mBindLhs), optReturnType, expr, exprm) -> let optInline = $1 || optInline // optional attributes are only applied to getters and setters // the "top level" attrs will be applied to both - let optAttrs = optAttrs |> List.map (fun (a:SynAttribute) -> { a with AppliesToGetterAndSetter=true }) + let optAttrs = + optAttrs |> List.map (fun attrList -> + { attrList with Attributes = attrList.Attributes |> List.map (fun a -> { a with AppliesToGetterAndSetter = true } ) }) + let attrs = attrs @ optAttrs - let binding = bindingBuilder (visNoLongerUsed,optInline,isMutable,mBindLhs,NoSequencePointAtInvisibleBinding,optReturnType,expr,exprm,[],attrs,Some (memFlagsBuilder MemberKind.Member)) + let binding = bindingBuilder (visNoLongerUsed, optInline, isMutable, mBindLhs, NoDebugPointAtInvisibleBinding, optReturnType, expr, exprm, [], attrs, Some (memFlagsBuilder MemberKind.Member)) let (Binding (vis, _, isInline, _, attrs, doc, valSynData, pv, _, _, mBindLhs, spBind)) = binding let memberKind = let getset = let rec go p = match p with - | SynPat.LongIdent (LongIdentWithDots([id],_),_,_,_,_,_) -> id.idText - | SynPat.Named (_,nm,_,_,_) -> nm.idText - | SynPat.Typed (p,_,_) -> go p - | SynPat.Attrib (p,_,_) -> go p + | SynPat.LongIdent (LongIdentWithDots([id], _), _, _, _, _, _) -> id.idText + | SynPat.Named (_, nm, _, _, _) -> nm.idText + | SynPat.Typed (p, _, _) -> go p + | SynPat.Attrib (p, _, _) -> go p | _ -> raiseParseErrorAt mBindLhs (FSComp.SR.parsInvalidDeclarationSyntax()) go pv - if getset = "get" then ( + if getset = "get" then if !hasGet then reportParseErrorAt mBindLhs (FSComp.SR.parsGetAndOrSetRequired()) None else hasGet := true Some MemberKind.PropertyGet - ) else if getset = "set" then ( + else if getset = "set" then if !hasSet then reportParseErrorAt mBindLhs (FSComp.SR.parsGetAndOrSetRequired()) None else hasSet := true Some MemberKind.PropertySet - ) else + else raiseParseErrorAt mBindLhs (FSComp.SR.parsGetAndOrSetRequired()) match memberKind with | None -> None | Some memberKind -> - // REVIEW: It's hard not to ignore the optPropertyType type annotation for 'set' properties. To apply it, + // REVIEW: It's hard not to ignore the optPropertyType type annotation for 'set' properties. To apply it, // we should apply it to the last argument, but at this point we've already pushed the patterns that // make up the arguments onto the RHS. So we just always give a warning. begin match optPropertyType with - | Some _ -> errorR(Error(FSComp.SR.parsTypeAnnotationsOnGetSet(),mBindLhs)) + | Some _ -> errorR(Error(FSComp.SR.parsTypeAnnotationsOnGetSet(), mBindLhs)) | None -> () end let optReturnType = match (memberKind, optReturnType) with - | MemberKind.PropertySet,_ -> optReturnType + | MemberKind.PropertySet, _ -> optReturnType | _, None -> optPropertyType | _ -> optReturnType // REDO with the correct member kind - let binding = bindingBuilder(vis,isInline,isMutable,mBindLhs,NoSequencePointAtInvisibleBinding,optReturnType,expr,exprm,[],attrs,Some(memFlagsBuilder memberKind)) + let binding = bindingBuilder(vis, isInline, isMutable, mBindLhs, NoDebugPointAtInvisibleBinding, optReturnType, expr, exprm, [], attrs, Some(memFlagsBuilder memberKind)) let (Binding (vis, _, isInline, _, attrs, doc, valSynData, pv, rhsRetInfo, rhsExpr, mBindLhs, spBind)) = binding - let (SynValData(_,valSynInfo,_)) = valSynData + let (SynValData(_, valSynInfo, _)) = valSynData // Setters have all arguments tupled in their internal TAST form, though they don't appear to be // tupled from the syntax @@ -1713,96 +1723,102 @@ memberCore: | _ -> SynInfo.unnamedTopArg match memberKind, valSynInfo, memFlags.IsInstance with - | MemberKind.PropertyGet,SynValInfo ([],_ret), false - | MemberKind.PropertyGet,SynValInfo ([_],_ret), true -> + | MemberKind.PropertyGet, SynValInfo ([], _ret), false + | MemberKind.PropertyGet, SynValInfo ([_], _ret), true -> raiseParseErrorAt mBindLhs (FSComp.SR.parsGetterMustHaveAtLeastOneArgument()) - | MemberKind.PropertyGet,SynValInfo (thisArg::indexOrUnitArgs::rest,ret), true -> - if not rest.IsEmpty then reportParseErrorAt mBindLhs (FSComp.SR.parsGetterAtMostOneArgument()) - SynValInfo ([thisArg; indexOrUnitArgs],ret) + | MemberKind.PropertyGet, SynValInfo (thisArg :: indexOrUnitArgs :: rest, ret), true -> + if not rest.IsEmpty then + reportParseErrorAt mBindLhs (FSComp.SR.parsGetterAtMostOneArgument ()) + SynValInfo ([thisArg; indexOrUnitArgs], ret) - | MemberKind.PropertyGet,SynValInfo (indexOrUnitArgs::rest,ret), false -> - if not rest.IsEmpty then reportParseErrorAt mBindLhs (FSComp.SR.parsGetterAtMostOneArgument()) - SynValInfo ([indexOrUnitArgs],ret) + | MemberKind.PropertyGet, SynValInfo (indexOrUnitArgs :: rest, ret), false -> + if not rest.IsEmpty then + reportParseErrorAt mBindLhs (FSComp.SR.parsGetterAtMostOneArgument ()) + SynValInfo ([indexOrUnitArgs], ret) - | MemberKind.PropertySet,SynValInfo ([thisArg;valueArg],ret), true -> - SynValInfo ([thisArg; adjustValueArg valueArg],ret) + | MemberKind.PropertySet, SynValInfo ([thisArg;valueArg], ret), true -> + SynValInfo ([thisArg; adjustValueArg valueArg], ret) - | MemberKind.PropertySet,SynValInfo (thisArg::indexArgs::valueArg::rest,ret), true -> - if not rest.IsEmpty then reportParseErrorAt mBindLhs (FSComp.SR.parsSetterAtMostTwoArguments()) - SynValInfo ([thisArg; indexArgs @ adjustValueArg valueArg],ret) + | MemberKind.PropertySet, SynValInfo (thisArg :: indexArgs :: valueArg :: rest, ret), true -> + if not rest.IsEmpty then + reportParseErrorAt mBindLhs (FSComp.SR.parsSetterAtMostTwoArguments ()) + SynValInfo ([thisArg; indexArgs @ adjustValueArg valueArg], ret) - | MemberKind.PropertySet,SynValInfo ([valueArg],ret), false -> - SynValInfo ([adjustValueArg valueArg],ret) + | MemberKind.PropertySet, SynValInfo ([valueArg], ret), false -> + SynValInfo ([adjustValueArg valueArg], ret) - | MemberKind.PropertySet,SynValInfo (indexArgs::valueArg::rest,ret), _ -> - if not rest.IsEmpty then reportParseErrorAt mBindLhs (FSComp.SR.parsSetterAtMostTwoArguments()) - SynValInfo ([indexArgs @ adjustValueArg valueArg],ret) + | MemberKind.PropertySet, SynValInfo (indexArgs :: valueArg :: rest, ret), _ -> + if not rest.IsEmpty then + reportParseErrorAt mBindLhs (FSComp.SR.parsSetterAtMostTwoArguments ()) + SynValInfo ([indexArgs @ adjustValueArg valueArg], ret) | _ -> // should be unreachable, cover just in case - raiseParseErrorAt mBindLhs (FSComp.SR.parsInvalidProperty()) + raiseParseErrorAt mBindLhs (FSComp.SR.parsInvalidProperty ()) - let valSynData = SynValData(Some(memFlags), valSynInfo,None) + let valSynData = SynValData(Some(memFlags), valSynInfo, None) // Fold together the information from the first lambda pattern and the get/set binding - // This uses the 'this' variable from the first and the patterns for the get/set binding, + // This uses the 'this' variable from the first and the patterns for the get/set binding, // replacing the get/set identifier. A little gross. let bindingPatAdjusted, xmlDocAdjusted = - let bindingOuter = propertyNameBindingBuilder(vis,optInline,isMutable,mBindLhs,spBind,optReturnType,expr,exprm,[],attrs,Some(memFlagsBuilder MemberKind.Member)) + let bindingOuter = propertyNameBindingBuilder(vis, optInline, isMutable, mBindLhs, spBind, optReturnType, expr, exprm, [], attrs, Some(memFlagsBuilder MemberKind.Member)) - let (Binding (_,_,_,_,_,doc2,_,bindingPatOuter,_,_,_,_)) = bindingOuter + let (Binding (_, _, _, _, _, doc2, _, bindingPatOuter, _, _, _, _)) = bindingOuter - let lidOuter,lidVisOuter = + let lidOuter, lidVisOuter = match bindingPatOuter with - | SynPat.LongIdent (lid,None,None, SynConstructorArgs.Pats [],lidVisOuter,m) -> lid,lidVisOuter - | SynPat.Named (_,id,_,visOuter,m) -> LongIdentWithDots([id],[]),visOuter + | SynPat.LongIdent (lid, None, None, SynArgPats.Pats [], lidVisOuter, m) -> lid, lidVisOuter + | SynPat.Named (_, id, _, visOuter, m) -> LongIdentWithDots([id], []), visOuter | p -> raiseParseErrorAt mBindLhs (FSComp.SR.parsInvalidDeclarationSyntax()) // Merge the visibility from the outer point with the inner point, e.g. // member this.Size with get () = m_size let mergeLidVisOuter lidVisInner = - match lidVisInner,lidVisOuter with - | None,None -> None - | Some lidVisInner,None | None,Some lidVisInner -> Some lidVisInner + match lidVisInner, lidVisOuter with + | None, None -> None + | Some lidVisInner, None | None, Some lidVisInner -> Some lidVisInner | Some _, Some _ -> - errorR(Error(FSComp.SR.parsMultipleAccessibilitiesForGetSet(),mBindLhs)) + errorR(Error(FSComp.SR.parsMultipleAccessibilitiesForGetSet(), mBindLhs)) lidVisInner // Replace the "get" or the "set" with the right name let rec go p = match p with - | SynPat.LongIdent (LongIdentWithDots([id],_),_,tyargs,SynConstructorArgs.Pats args,lidVisInner,m) -> + | SynPat.LongIdent (LongIdentWithDots([id], _), _, tyargs, SynArgPats.Pats args, lidVisInner, m) -> // Setters have all arguments tupled in their internal form, though they don't // appear to be tupled from the syntax. Somewhat unfortunate let args = if id.idText = "set" then match args with - | [SynPat.Paren(SynPat.Tuple (false,indexPats,_),indexPatRange);valuePat] when id.idText = "set" -> - [SynPat.Tuple(false,indexPats@[valuePat],unionRanges indexPatRange valuePat.Range)] + | [SynPat.Paren(SynPat.Tuple (false, indexPats, _), indexPatRange);valuePat] when id.idText = "set" -> + [SynPat.Tuple(false, indexPats@[valuePat], unionRanges indexPatRange valuePat.Range)] | [indexPat;valuePat] -> - [SynPat.Tuple(false,args,unionRanges indexPat.Range valuePat.Range)] + [SynPat.Tuple(false, args, unionRanges indexPat.Range valuePat.Range)] | [valuePat] -> [valuePat] | _ -> raiseParseErrorAt m (FSComp.SR.parsSetSyntax()) else args -// let idTool : Ident list = lidOuter |> List.map (fun (li:Ident) -> ident(li.idText,id.idRange)) |> List.rev |> List.take 1 - SynPat.LongIdent (lidOuter,Some(id),tyargs, SynConstructorArgs.Pats args,mergeLidVisOuter lidVisInner,m) - | SynPat.Named (_,nm,_,lidVisInner,m) -> SynPat.LongIdent (lidOuter,None,None, SynConstructorArgs.Pats [], mergeLidVisOuter lidVisInner,m) - | SynPat.Typed (p,ty,m) -> SynPat.Typed(go p,ty,m) - | SynPat.Attrib (p,attribs,m) -> SynPat.Attrib(go p,attribs,m) +// let idTool : Ident list = lidOuter |> List.map (fun (li:Ident) -> ident(li.idText, id.idRange)) |> List.rev |> List.take 1 + SynPat.LongIdent (lidOuter, Some(id), tyargs, SynArgPats.Pats args, mergeLidVisOuter lidVisInner, m) + | SynPat.Named (_, nm, _, lidVisInner, m) -> SynPat.LongIdent (lidOuter, None, None, SynArgPats.Pats [], mergeLidVisOuter lidVisInner, m) + | SynPat.Typed (p, ty, m) -> SynPat.Typed(go p, ty, m) + | SynPat.Attrib (p, attribs, m) -> SynPat.Attrib(go p, attribs, m) | SynPat.Wild(m) -> SynPat.Wild(m) | _ -> raiseParseErrorAt mBindLhs (FSComp.SR.parsInvalidDeclarationSyntax()) - go pv,PreXmlDoc.Merge doc2 doc + go pv, PreXmlDoc.Merge doc2 doc - Some <| SynMemberDefn.Member (Binding (vis, NormalBinding, isInline, isMutable, attrs, xmlDocAdjusted, valSynData, bindingPatAdjusted, rhsRetInfo, rhsExpr, mBindLhs, spBind),mWhole))) + let binding = Binding (vis, NormalBinding, isInline, isMutable, attrs, xmlDocAdjusted, valSynData, bindingPatAdjusted, rhsRetInfo, rhsExpr, mBindLhs, spBind) + let memberRange = unionRanges rangeStart mWhole + Some (SynMemberDefn.Member (binding, memberRange)))) } @@ -1814,95 +1830,102 @@ abstractMemberFlags: /* A member definition */ classDefnMember: | opt_attributes opt_declVisibility classDefnBindings - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - [mkClassMemberLocalBindings(false,None,$1,$2,$3)] } + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + [mkClassMemberLocalBindings(false, None, $1, $2, $3)] } | opt_attributes opt_declVisibility STATIC classDefnBindings - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - [mkClassMemberLocalBindings(true,Some (rhs parseState 3),$1,$2,$4)] } + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + [mkClassMemberLocalBindings(true, Some (rhs parseState 3), $1, $2, $4)] } - | opt_attributes opt_declVisibility memberFlags memberCore opt_ODECLEND - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - let _,flags = $3 - $4 $2 flags $1 } + | opt_attributes opt_declVisibility memberFlags memberCore opt_ODECLEND + { let rangeStart = rhs parseState 1 + if Option.isSome $2 then + errorR (Error (FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier (), rhs parseState 2)) + let _, flags = $3 + $4 $2 flags $1 rangeStart } | opt_attributes opt_declVisibility interfaceMember appType opt_interfaceImplDefn - { if not (isNil $1) then errorR(Error(FSComp.SR.parsAttributesAreNotPermittedOnInterfaceImplementations(),rhs parseState 1)) - if Option.isSome $2 then errorR(Error(FSComp.SR.parsInterfacesHaveSameVisibilityAsEnclosingType(),rhs parseState 3)) + { if not (isNil $1) then errorR(Error(FSComp.SR.parsAttributesAreNotPermittedOnInterfaceImplementations(), rhs parseState 1)) + if Option.isSome $2 then errorR(Error(FSComp.SR.parsInterfacesHaveSameVisibilityAsEnclosingType(), rhs parseState 3)) let mWhole = match $5 with - | None -> rhs2 parseState 3 4 - | Some(mems) -> (rhs2 parseState 3 4, mems) ||> unionRangeWithListBy (fun (mem:SynMemberDefn) -> mem.Range) + | None -> rhs2 parseState 1 4 + | Some(mems) -> (rhs2 parseState 1 4, mems) ||> unionRangeWithListBy (fun (mem:SynMemberDefn) -> mem.Range) [ SynMemberDefn.Interface ($4, $5, mWhole) ] } | opt_attributes opt_declVisibility abstractMemberFlags opt_inline nameop opt_explicitValTyparDecls COLON topTypeWithTypeConstraints classMemberSpfnGetSet opt_ODECLEND - { let ty,arity = $8 - let isInline,doc,id,explicitValTyparDecls = $4,grabXmlDoc(parseState,3),$5,$6 + { let ty, arity = $8 + let isInline, doc, id, explicitValTyparDecls = $4, grabXmlDoc(parseState, 3), $5, $6 let getSetRangeOpt, getSet = $9 - let getSetAdjuster arity = match arity,getSet with SynValInfo([],_),MemberKind.Member -> MemberKind.PropertyGet | _ -> getSet + let getSetAdjuster arity = match arity, getSet with SynValInfo([], _), MemberKind.Member -> MemberKind.PropertyGet | _ -> getSet let wholeRange = - let m = rhs parseState 3 + let m = rhs parseState 1 match getSetRangeOpt with | None -> unionRanges m ty.Range | Some m2 -> unionRanges m m2 - if Option.isSome $2 then errorR(Error(FSComp.SR.parsAccessibilityModsIllegalForAbstract(),wholeRange)) - let valSpfn = ValSpfn($1,id,explicitValTyparDecls,ty,arity, isInline,false,doc, None,None,wholeRange) - [ SynMemberDefn.AbstractSlot(valSpfn,AbstractMemberFlags (getSetAdjuster arity), wholeRange) ] } + if Option.isSome $2 then errorR(Error(FSComp.SR.parsAccessibilityModsIllegalForAbstract(), wholeRange)) + let valSpfn = ValSpfn($1, id, explicitValTyparDecls, ty, arity, isInline, false, doc, None, None, wholeRange) + [ SynMemberDefn.AbstractSlot(valSpfn, AbstractMemberFlags (getSetAdjuster arity), wholeRange) ] } | opt_attributes opt_declVisibility inheritsDefn - { if not (isNil $1) then errorR(Error(FSComp.SR.parsAttributesIllegalOnInherit(),rhs parseState 1)) - if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityIllegalOnInherit(),rhs parseState 1)) + { if not (isNil $1) then errorR(Error(FSComp.SR.parsAttributesIllegalOnInherit(), rhs parseState 1)) + if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityIllegalOnInherit(), rhs parseState 1)) [ $3 ] } | opt_attributes opt_declVisibility valDefnDecl opt_ODECLEND - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - $3 None $1 false } + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + let rangeStart = rhs parseState 1 + $3 rangeStart $1 false } | opt_attributes opt_declVisibility STATIC valDefnDecl opt_ODECLEND - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - $4 (Some (rhs parseState 3)) $1 true } + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + let rangeStart = rhs parseState 1 + $4 rangeStart $1 true } | opt_attributes opt_declVisibility memberFlags autoPropsDefnDecl opt_ODECLEND - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - let isStatic, flags = $3 - $4 $1 isStatic flags } + { let rangeStart = rhs parseState 1 + if Option.isSome $2 then + errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + let isStatic, flags = $3 + $4 $1 isStatic flags rangeStart } | opt_attributes opt_declVisibility NEW atomicPattern optAsSpec EQUALS typedSeqExprBlock opt_ODECLEND - { let m = unionRanges (rhs2 parseState 3 6) $7.Range + { let m = unionRanges (rhs2 parseState 1 6) $7.Range let expr = $7 - let valSynData = SynValData (Some CtorMemberFlags, SynValInfo([SynInfo.InferSynArgInfoFromPat $4],SynInfo.unnamedRetVal), $5) + let valSynData = SynValData (Some CtorMemberFlags, SynValInfo([SynInfo.InferSynArgInfoFromPat $4], SynInfo.unnamedRetVal), $5) let vis = $2 - let declPat = SynPat.LongIdent (LongIdentWithDots([mkSynId (rhs parseState 3) "new"],[]),None,Some noInferredTypars, SynConstructorArgs.Pats [$4],vis,rhs parseState 3) + let declPat = SynPat.LongIdent (LongIdentWithDots([mkSynId (rhs parseState 3) "new"], []), None, Some noInferredTypars, SynArgPats.Pats [$4], vis, rhs parseState 3) // Check that 'SynPatForConstructorDecl' matches this correctly assert (match declPat with SynPatForConstructorDecl _ -> true | _ -> false) - [ SynMemberDefn.Member(Binding (None,NormalBinding,false,false,$1,grabXmlDoc(parseState,3),valSynData, declPat,None,expr,m,NoSequencePointAtInvisibleBinding),m) ] } + [ SynMemberDefn.Member(Binding (None, NormalBinding, false, false, $1, grabXmlDoc(parseState, 3), valSynData, declPat, None, expr, m, NoDebugPointAtInvisibleBinding), m) ] } | opt_attributes opt_declVisibility STATIC typeKeyword tyconDefn - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - [ SynMemberDefn.NestedType($5,None,rhs2 parseState 3 5) ] } + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) + [ SynMemberDefn.NestedType($5, None, rhs2 parseState 1 5) ] } /* A 'val' definition in an object type definition */ valDefnDecl: | VAL opt_mutable opt_access ident COLON typ { let mRhs = rhs2 parseState 4 6 - let doc = grabXmlDoc(parseState,4) + let doc = grabXmlDoc(parseState, 4) let mValDecl = rhs2 parseState 1 6 - (fun mLeft attribs isStatic -> - let mValDecl = match mLeft with None -> mValDecl | Some m -> unionRanges m mValDecl - let fld = Field(attribs,isStatic,Some $4,$6,$2,doc,$3,mRhs) + (fun rangeStart attribs isStatic -> + let mValDecl = unionRanges rangeStart mValDecl + let fld = Field(attribs, isStatic, Some $4, $6, $2, doc, $3, mRhs) [ SynMemberDefn.ValField(fld, mValDecl) ]) } /* An auto-property definition in an object type definition */ autoPropsDefnDecl: | VAL opt_mutable opt_access ident opt_typ EQUALS typedSeqExprBlock classMemberSpfnGetSet - { let doc = grabXmlDoc(parseState,5) - let mValDecl = unionRanges (rhs parseState 1) $7.Range - let mGetSetOpt, getSet = $8 - if $2 then errorR(Error(FSComp.SR.parsMutableOnAutoPropertyShouldBeGetSet(),rhs parseState 3)) - (fun attribs isStatic flags -> - [ SynMemberDefn.AutoProperty(attribs, isStatic, $4, $5, getSet, flags, doc, $3, $7, mGetSetOpt, mValDecl) ]) } + { let doc = grabXmlDoc(parseState, 5) + let mGetSetOpt, getSet = $8 + if $2 then + errorR (Error (FSComp.SR.parsMutableOnAutoPropertyShouldBeGetSet (), rhs parseState 3)) + (fun attribs isStatic flags rangeStart -> + let memberRange = unionRanges rangeStart $7.Range + [ SynMemberDefn.AutoProperty(attribs, isStatic, $4, $5, getSet, flags, doc, $3, $7, mGetSetOpt, memberRange) ]) } /* An optional type on an auto-property definition */ @@ -1910,76 +1933,116 @@ opt_typ: | /* EMPTY */ { None } | COLON typ { Some $2 } - + atomicPatternLongIdent: - | GLOBAL DOT pathOp { let (LongIdentWithDots(lid,dotms)) = $3 in (None,LongIdentWithDots(ident(MangledGlobalName,rhs parseState 1)::lid, rhs parseState 2::dotms)) } - | pathOp { (None,$1) } - | access pathOp { (Some($1), $2) } + | UNDERSCORE DOT pathOp + { if not (parseState.LexBuffer.SupportsFeature LanguageFeature.SingleUnderscorePattern) then + raiseParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnexpectedSymbolDot()) + let (LongIdentWithDots(lid, dotms)) = $3 + (None, LongIdentWithDots(ident("_", rhs parseState 1)::lid, rhs parseState 2::dotms)) } + + | GLOBAL DOT pathOp + { let (LongIdentWithDots(lid, dotms)) = $3 + (None, LongIdentWithDots(ident(MangledGlobalName, rhs parseState 1) :: lid, rhs parseState 2 :: dotms)) } + + | pathOp + { (None, $1) } + + | access UNDERSCORE DOT pathOp + { if not (parseState.LexBuffer.SupportsFeature LanguageFeature.SingleUnderscorePattern) then + raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsUnexpectedSymbolDot()) + let (LongIdentWithDots(lid, dotms)) = $4 + (Some($1), LongIdentWithDots(ident("_", rhs parseState 2)::lid, rhs parseState 3::dotms)) } + + | access pathOp + { (Some($1), $2) } opt_access: - | /* EMPTY */ { None } - | access { Some($1) } + | /* EMPTY */ + { None } + + | access + { Some($1) } access: - | PRIVATE { SynAccess.Private } - | PUBLIC { SynAccess.Public } - | INTERNAL { SynAccess.Internal } + | PRIVATE + { SynAccess.Private } + + | PUBLIC + { SynAccess.Public } + + | INTERNAL + { SynAccess.Internal } /* only valid on 'NEW' */ opt_declVisibility: - | access { Some($1) } - | /* EMPTY */ { None } + | access + { Some($1) } + + | /* EMPTY */ + { None } opt_interfaceImplDefn: - | WITH objectImplementationBlock declEnd { Some($2) } - | /* EMPTY */ { None } + | WITH objectImplementationBlock declEnd + { Some($2) } + + | /* EMPTY */ + { None } opt_classDefn: - | WITH classDefnBlock declEnd { $2 } - | /* EMPTY */ { [] } + | WITH classDefnBlock declEnd + { $2 } + + | /* EMPTY */ + { [] } /* An 'inherits' definition in an object type definition */ inheritsDefn: | INHERIT atomTypeNonAtomicDeprecated optBaseSpec { let mDecl = unionRanges (rhs parseState 1) (($2): SynType).Range - SynMemberDefn.Inherit($2,$3,mDecl) } + SynMemberDefn.Inherit($2, $3, mDecl) } | INHERIT atomTypeNonAtomicDeprecated opt_HIGH_PRECEDENCE_APP atomicExprAfterType optBaseSpec { let mDecl = unionRanges (rhs parseState 1) $4.Range - SynMemberDefn.ImplicitInherit($2,$4,$5,mDecl) } + SynMemberDefn.ImplicitInherit($2, $4, $5, mDecl) } | INHERIT ends_coming_soon_or_recover { let mDecl = (rhs parseState 1) if not $2 then errorR(Error(FSComp.SR.parsTypeNameCannotBeEmpty(), mDecl)) - SynMemberDefn.Inherit(SynType.LongIdent(LongIdentWithDots([], [])), None,mDecl) } + SynMemberDefn.Inherit(SynType.LongIdent(LongIdentWithDots([], [])), None, mDecl) } optAsSpec: - | asSpec { Some($1) } - | { None } + | asSpec + { Some($1) } -asSpec: - | AS ident { $2 } + | /* EMPTY */ + { None } +asSpec: + | AS ident + { $2 } optBaseSpec: - | baseSpec { Some($1) } - | { None } + | baseSpec + { Some($1) } + | /* EMPTY */ + { None } baseSpec: | AS ident { if ($2).idText <> "base" then - errorR(Error(FSComp.SR.parsInheritDeclarationsCannotHaveAsBindings(),rhs2 parseState 1 2)) - ident("base",rhs parseState 2) } + errorR(Error(FSComp.SR.parsInheritDeclarationsCannotHaveAsBindings(), rhs2 parseState 1 2)) + ident("base", rhs parseState 2) } | AS BASE - { errorR(Error(FSComp.SR.parsInheritDeclarationsCannotHaveAsBindings(),rhs2 parseState 1 2)) - ident("base",rhs parseState 2) } + { errorR(Error(FSComp.SR.parsInheritDeclarationsCannotHaveAsBindings(), rhs2 parseState 1 2)) + ident("base", rhs parseState 2) } /* The members in an object expression or interface implementation */ @@ -2007,10 +2070,12 @@ objectImplementationMembers: /* One member in an object expression or interface implementation */ objectImplementationMember: | opt_attributes memberOrOverride memberCore opt_ODECLEND - { $3 None OverrideMemberFlags $1 } + { let rangeStart = rhs parseState 1 + $3 None OverrideMemberFlags $1 rangeStart } | opt_attributes memberOrOverride autoPropsDefnDecl opt_ODECLEND - { $3 $1 false OverrideMemberFlags } + { let rangeStart = rhs parseState 1 + $3 $1 false OverrideMemberFlags rangeStart } | opt_attributes memberOrOverride error { [] } @@ -2030,42 +2095,42 @@ tyconDefnOrSpfnSimpleRepr: /* type MyAlias = SomeTypeProvider<@"foo"> is a common error, special-case it */ | opt_attributes opt_declVisibility path LQUOTE STRING recover { errorR(Error(FSComp.SR.parsUnexpectedQuotationOperatorInTypeAliasDidYouMeanVerbatimString(), rhs parseState 4)) - SynTypeDefnSimpleRepr.TypeAbbrev (ParserDetail.ThereWereSignificantParseErrorsSoDoNotTypecheckThisNode, SynType.LongIdent($3), unionRanges (rhs parseState 1) $3.Range) } + SynTypeDefnSimpleRepr.TypeAbbrev (ParserDetail.ErrorRecovery, SynType.LongIdent($3), unionRanges (rhs parseState 1) $3.Range) } /* A type abbreviation */ | opt_attributes opt_declVisibility typ - { if not (isNil $1) then errorR(Error(FSComp.SR.parsAttributesIllegalHere(),rhs parseState 1)) - if Option.isSome $2 then errorR(Error(FSComp.SR.parsTypeAbbreviationsCannotHaveVisibilityDeclarations(),rhs parseState 2)) + { if not (isNil $1) then errorR(Error(FSComp.SR.parsAttributesIllegalHere(), rhs parseState 1)) + if Option.isSome $2 then errorR(Error(FSComp.SR.parsTypeAbbreviationsCannotHaveVisibilityDeclarations(), rhs parseState 2)) SynTypeDefnSimpleRepr.TypeAbbrev (ParserDetail.Ok, $3, unionRanges (rhs parseState 1) $3.Range) } /* A union type definition */ | opt_attributes opt_declVisibility unionTypeRepr - { if not (isNil $1) then errorR(Error(FSComp.SR.parsAttributesIllegalHere(),rhs parseState 1)) + { if not (isNil $1) then errorR(Error(FSComp.SR.parsAttributesIllegalHere(), rhs parseState 1)) let rangesOf3 = $3 |> List.map (function |Choice1Of2(ec)->ec.Range | Choice2Of2(uc)->uc.Range) let mWhole = (rhs2 parseState 1 2, rangesOf3) ||> List.fold unionRanges if $3 |> List.exists (function Choice1Of2 _ -> true | _ -> false) then ( - if Option.isSome $2 then errorR(Error(FSComp.SR.parsEnumTypesCannotHaveVisibilityDeclarations(),rhs parseState 2)); + if Option.isSome $2 then errorR(Error(FSComp.SR.parsEnumTypesCannotHaveVisibilityDeclarations(), rhs parseState 2)); SynTypeDefnSimpleRepr.Enum ($3 |> List.choose (function | Choice1Of2 data -> Some(data) - | Choice2Of2(UnionCase(_,_,_,_,_,m)) -> - errorR(Error(FSComp.SR.parsAllEnumFieldsRequireValues(),m)); None), + | Choice2Of2(UnionCase(_, _, _, _, _, m)) -> + errorR(Error(FSComp.SR.parsAllEnumFieldsRequireValues(), m)); None), mWhole) ) else - SynTypeDefnSimpleRepr.Union ($2, + SynTypeDefnSimpleRepr.Union ($2, $3 |> List.choose (function Choice2Of2 data -> Some(data) | Choice1Of2 _ -> failwith "huh?"), mWhole) } /* A record type definition */ | opt_attributes opt_declVisibility braceFieldDeclList - { if not (isNil $1) then errorR(Error(FSComp.SR.parsAttributesIllegalHere(),rhs parseState 1)) - SynTypeDefnSimpleRepr.Record ($2,$3,lhs parseState) } + { if not (isNil $1) then errorR(Error(FSComp.SR.parsAttributesIllegalHere(), rhs parseState 1)) + SynTypeDefnSimpleRepr.Record ($2, $3, lhs parseState) } /* An inline-assembly type definition, for FSharp.Core library only */ | opt_attributes opt_declVisibility LPAREN inlineAssemblyTyconRepr rparen - { if not (isNil $1) then errorR(Error(FSComp.SR.parsAttributesIllegalHere(),rhs parseState 1)) + { if not (isNil $1) then errorR(Error(FSComp.SR.parsAttributesIllegalHere(), rhs parseState 1)) libraryOnlyError (lhs parseState) - if Option.isSome $2 then errorR(Error(FSComp.SR.parsInlineAssemblyCannotHaveVisibilityDeclarations(),rhs parseState 2)) + if Option.isSome $2 then errorR(Error(FSComp.SR.parsInlineAssemblyCannotHaveVisibilityDeclarations(), rhs parseState 2)) $4 } @@ -2083,9 +2148,9 @@ braceFieldDeclList: anonRecdType: | STRUCT braceBarFieldDeclListCore - { $2,true } + { $2, true } | braceBarFieldDeclListCore - { $1,false } + { $1, false } /* The core of a record type definition */ braceBarFieldDeclListCore: @@ -2103,12 +2168,17 @@ inlineAssemblyTyconRepr: | HASH stringOrKeywordString HASH { libraryOnlyError (lhs parseState) let lhsm = lhs parseState - SynTypeDefnSimpleRepr.LibraryOnlyILAssembly (ParseAssemblyCodeType $2 (rhs parseState 2),lhsm) } + SynTypeDefnSimpleRepr.LibraryOnlyILAssembly (internalParseAssemblyCodeType $2 parseState.LexBuffer.SupportsFeature (rhs parseState 2), lhsm) } classOrInterfaceOrStruct: - | CLASS { TyconClass } - | INTERFACE { TyconInterface } - | STRUCT { TyconStruct } + | CLASS + { TyconClass } + + | INTERFACE + { TyconInterface } + + | STRUCT + { TyconStruct } interfaceMember: | INTERFACE { } @@ -2116,17 +2186,17 @@ interfaceMember: tyconNameAndTyparDecls: | opt_access path - { [], $2.Lid,false,[],$1,grabXmlDoc(parseState,2) } + { [], $2.Lid, false, [], $1, grabXmlDoc(parseState, 2) } | opt_access prefixTyparDecls path - { $2, $3.Lid,false,[],$1,grabXmlDoc(parseState,2) } + { $2, $3.Lid, false, [], $1, grabXmlDoc(parseState, 2) } | opt_access path postfixTyparDecls - { let tps,tpcs = $3 - tps, $2.Lid,true,tpcs,$1,grabXmlDoc(parseState,2) } + { let tps, tpcs = $3 + tps, $2.Lid, true, tpcs, $1, grabXmlDoc(parseState, 2) } prefixTyparDecls: - | typar { [ TyparDecl([],$1) ] } + | typar { [ TyparDecl([], $1) ] } | LPAREN typarDeclList rparen { List.rev $2 } typarDeclList: @@ -2135,101 +2205,111 @@ typarDeclList: typarDecl : | opt_attributes typar - { TyparDecl($1,$2) } + { TyparDecl($1, $2) } /* Any tokens in this grammar must be added to the lex filter rule 'peekAdjacentTypars' */ /* See the F# specification "Lexical analysis of type applications and type parameter definitions" */ postfixTyparDecls: | opt_HIGH_PRECEDENCE_TYAPP LESS typarDeclList opt_typeConstraints GREATER - { if not $2 then warning(Error(FSComp.SR.parsNonAdjacentTypars(),rhs2 parseState 2 5)) + { if not $2 then warning(Error(FSComp.SR.parsNonAdjacentTypars(), rhs2 parseState 2 5)) List.rev $3, $4 } /* Any tokens in this grammar must be added to the lex filter rule 'peekAdjacentTypars' */ /* See the F# specification "Lexical analysis of type applications and type parameter definitions" */ explicitValTyparDeclsCore: | typarDeclList COMMA DOT_DOT - { (List.rev $1,true) } + { (List.rev $1, true) } + | typarDeclList - { (List.rev $1,false) } - | - { ([],false) } + { (List.rev $1, false) } + + | /* EMPTY */ + { ([], false) } explicitValTyparDecls: | opt_HIGH_PRECEDENCE_TYAPP LESS explicitValTyparDeclsCore opt_typeConstraints GREATER - { if not $2 then warning(Error(FSComp.SR.parsNonAdjacentTypars(),rhs2 parseState 2 5)) - let tps,flex = $3 - SynValTyparDecls(tps,flex,$4) } + { if not $2 then warning(Error(FSComp.SR.parsNonAdjacentTypars(), rhs2 parseState 2 5)) + let tps, flex = $3 + SynValTyparDecls(tps, flex, $4) } opt_explicitValTyparDecls: | explicitValTyparDecls { $1 } | - { SynValTyparDecls([],true,[]) } + { SynValTyparDecls([], true, []) } opt_explicitValTyparDecls2: | explicitValTyparDecls { Some $1 } - | + + | /* EMPTY */ { None } /* Any tokens in this grammar must be added to the lex filter rule 'peekAdjacentTypars' */ /* See the F# specification "Lexical analysis of type applications and type parameter definitions" */ opt_typeConstraints: - | + | /* EMPTY */ { [] } + | WHEN typeConstraints { List.rev $2 } /* Any tokens in this grammar must be added to the lex filter rule 'peekAdjacentTypars' */ /* See the F# specification "Lexical analysis of type applications and type parameter definitions" */ typeConstraints: - | typeConstraints AND typeConstraint { $3 :: $1 } - | typeConstraint { [$1] } + | typeConstraints AND typeConstraint + { $3 :: $1 } + + | typeConstraint + { [$1] } /* Any tokens in this grammar must be added to the lex filter rule 'peekAdjacentTypars' */ /* See the F# specification "Lexical analysis of type applications and type parameter definitions" */ typeConstraint: | DEFAULT typar COLON typ - { libraryOnlyError (lhs parseState); WhereTyparDefaultsToType($2,$4,lhs parseState) } + { libraryOnlyError (lhs parseState); WhereTyparDefaultsToType($2, $4, lhs parseState) } | typar COLON_GREATER typ - { WhereTyparSubtypeOfType($1,$3,lhs parseState) } + { WhereTyparSubtypeOfType($1, $3, lhs parseState) } | typar COLON STRUCT - { WhereTyparIsValueType($1,lhs parseState) } + { WhereTyparIsValueType($1, lhs parseState) } | typar COLON IDENT STRUCT - { if $3 <> "not" then reportParseErrorAt (rhs parseState 3) (FSComp.SR.parsUnexpectedIdentifier($3)) - WhereTyparIsReferenceType($1,lhs parseState) } + { if $3 <> "not" then reportParseErrorAt (rhs parseState 3) (FSComp.SR.parsUnexpectedIdentifier($3)) + WhereTyparIsReferenceType($1, lhs parseState) } | typar COLON NULL - { WhereTyparSupportsNull($1,lhs parseState) } + { WhereTyparSupportsNull($1, lhs parseState) } | typar COLON LPAREN classMemberSpfn rparen - { let tp = $1 - WhereTyparSupportsMember([ SynType.Var(tp, tp.Range) ],$4,lhs parseState) } + { let tp = $1 + WhereTyparSupportsMember([ SynType.Var(tp, tp.Range) ], $4, lhs parseState) } | LPAREN typarAlts rparen COLON LPAREN classMemberSpfn rparen - { WhereTyparSupportsMember(List.rev($2),$6,lhs parseState) } + { WhereTyparSupportsMember(List.rev($2), $6, lhs parseState) } | typar COLON DELEGATE typeArgsNoHpaDeprecated - { let _ltm,_gtm,args,_commas,mWhole = $4 in WhereTyparIsDelegate($1, args, unionRanges $1.Range mWhole) } + { let _ltm, _gtm, args, _commas, mWhole = $4 in WhereTyparIsDelegate($1, args, unionRanges $1.Range mWhole) } | typar COLON IDENT typeArgsNoHpaDeprecated - { match $3 with - | "enum" -> let _ltm,_gtm,args,_commas,mWhole = $4 in WhereTyparIsEnum($1, args, unionRanges $1.Range mWhole) - | nm -> raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsUnexpectedIdentifier(nm)) } + { match $3 with + | "enum" -> let _ltm, _gtm, args, _commas, mWhole = $4 in WhereTyparIsEnum($1, args, unionRanges $1.Range mWhole) + | nm -> raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsUnexpectedIdentifier(nm)) } | typar COLON IDENT - { match $3 with - | "comparison" -> WhereTyparIsComparable($1,lhs parseState) - | "equality" -> WhereTyparIsEquatable($1,lhs parseState) - | "unmanaged" -> WhereTyparIsUnmanaged($1,lhs parseState) - | nm -> raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsUnexpectedIdentifier(nm)) } + { match $3 with + | "comparison" -> WhereTyparIsComparable($1, lhs parseState) + | "equality" -> WhereTyparIsEquatable($1, lhs parseState) + | "unmanaged" -> WhereTyparIsUnmanaged($1, lhs parseState) + | nm -> raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsUnexpectedIdentifier(nm)) } typarAlts: - | typarAlts OR appType { $3::$1 } - | appType { [$1] } + | typarAlts OR appType + { $3 :: $1 } + + | appType + { [$1] } /* The core of a union type definition */ unionTypeRepr: @@ -2245,38 +2325,38 @@ unionTypeRepr: { [$1] } barAndgrabXmlDoc : - | BAR { grabXmlDoc(parseState,1) } + | BAR + { grabXmlDoc(parseState, 1) } attrUnionCaseDecls: - | attrUnionCaseDecl barAndgrabXmlDoc attrUnionCaseDecls { (fun xmlDoc -> $1 xmlDoc :: $3 $2) } - | attrUnionCaseDecl { (fun xmlDoc -> [ $1 xmlDoc ]) } + | attrUnionCaseDecl barAndgrabXmlDoc attrUnionCaseDecls + { (fun xmlDoc -> $1 xmlDoc :: $3 $2) } + + | attrUnionCaseDecl + { (fun xmlDoc -> [ $1 xmlDoc ]) } /* The core of a union case definition */ attrUnionCaseDecl: | opt_attributes opt_access unionCaseName opt_OBLOCKSEP - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsUnionCasesCannotHaveVisibilityDeclarations(),rhs parseState 2)) + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsUnionCasesCannotHaveVisibilityDeclarations(), rhs parseState 2)) let mDecl = rhs parseState 3 - (fun xmlDoc -> Choice2Of2 (UnionCase ( $1, $3,UnionCaseFields [],xmlDoc,None,mDecl))) - } + (fun xmlDoc -> Choice2Of2 (UnionCase ( $1, $3, UnionCaseFields [], xmlDoc, None, mDecl))) } | opt_attributes opt_access unionCaseName OF unionCaseRepr opt_OBLOCKSEP - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsUnionCasesCannotHaveVisibilityDeclarations(),rhs parseState 2)) - let mDecl = rhs2 parseState 3 5 - (fun xmlDoc -> Choice2Of2 (UnionCase ( $1, $3,UnionCaseFields $5,xmlDoc,None,mDecl))) - } + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsUnionCasesCannotHaveVisibilityDeclarations(), rhs parseState 2)) + let mDecl = rhs2 parseState 1 5 + (fun xmlDoc -> Choice2Of2 (UnionCase ( $1, $3, UnionCaseFields $5, xmlDoc, None, mDecl))) } | opt_attributes opt_access unionCaseName COLON topType opt_OBLOCKSEP - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsUnionCasesCannotHaveVisibilityDeclarations(),rhs parseState 2)) + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsUnionCasesCannotHaveVisibilityDeclarations(), rhs parseState 2)) libraryOnlyWarning(lhs parseState) - let mDecl = rhs2 parseState 3 5 - (fun xmlDoc -> Choice2Of2 (UnionCase ( $1, $3,UnionCaseFullType $5,xmlDoc,None,mDecl))) - } + let mDecl = rhs2 parseState 1 5 + (fun xmlDoc -> Choice2Of2 (UnionCase ( $1, $3, UnionCaseFullType $5, xmlDoc, None, mDecl))) } | opt_attributes opt_access unionCaseName EQUALS constant opt_OBLOCKSEP - { if Option.isSome $2 then errorR(Error(FSComp.SR.parsEnumFieldsCannotHaveVisibilityDeclarations(),rhs parseState 2)) - let mDecl = rhs2 parseState 3 5 - (fun xmlDoc -> Choice1Of2 (EnumCase ( $1, $3,$5,xmlDoc,mDecl))) - } + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsEnumFieldsCannotHaveVisibilityDeclarations(), rhs parseState 2)) + let mDecl = rhs2 parseState 1 5 + (fun xmlDoc -> Choice1Of2 (EnumCase ( $1, $3, $5, xmlDoc, mDecl))) } /* The name of a union case */ unionCaseName: @@ -2284,39 +2364,45 @@ unionCaseName: { $1 } | LPAREN COLON_COLON rparen - { ident(opNameCons,rhs parseState 2) } + { ident(opNameCons, rhs parseState 2) } | LPAREN LBRACK RBRACK rparen - { ident(opNameNil,rhs2 parseState 2 3) } + { ident(opNameNil, rhs2 parseState 2 3) } firstUnionCaseDeclOfMany: | ident opt_OBLOCKSEP - { Choice2Of2 (UnionCase ( [], $1,UnionCaseFields [],PreXmlDoc.Empty,None,rhs parseState 1)) } + { Choice2Of2 (UnionCase ( [], $1, UnionCaseFields [], PreXmlDoc.Empty, None, rhs parseState 1)) } | ident EQUALS constant opt_OBLOCKSEP - { Choice1Of2 (EnumCase ([],$1,$3,PreXmlDoc.Empty,rhs2 parseState 1 3)) } + { Choice1Of2 (EnumCase ([], $1, $3, PreXmlDoc.Empty, rhs2 parseState 1 3)) } | firstUnionCaseDecl opt_OBLOCKSEP { $1 } firstUnionCaseDecl: | ident OF unionCaseRepr - { Choice2Of2 (UnionCase ( [],$1,UnionCaseFields $3,PreXmlDoc.Empty,None,rhs2 parseState 1 3)) } + { Choice2Of2 (UnionCase ( [], $1, UnionCaseFields $3, PreXmlDoc.Empty, None, rhs2 parseState 1 3)) } | ident EQUALS constant opt_OBLOCKSEP - { Choice1Of2 (EnumCase ([],$1,$3,PreXmlDoc.Empty,rhs2 parseState 1 3)) } + { Choice1Of2 (EnumCase ([], $1, $3, PreXmlDoc.Empty, rhs2 parseState 1 3)) } unionCaseReprElements: - | unionCaseReprElement STAR unionCaseReprElements { $1::$3 } - | unionCaseReprElement %prec prec_toptuptyptail_prefix { [$1] } + | unionCaseReprElement STAR unionCaseReprElements + { $1 :: $3 } + + | unionCaseReprElement %prec prec_toptuptyptail_prefix + { [$1] } unionCaseReprElement: - | ident COLON appType { mkNamedField($1, $3) } - | appType { mkAnonField $1 } + | ident COLON appType + { mkNamedField($1, $3) } + + | appType + { mkAnonField $1 } unionCaseRepr: | braceFieldDeclList - { errorR(Deprecated(FSComp.SR.parsConsiderUsingSeparateRecordType(),lhs parseState)) + { errorR(Deprecated(FSComp.SR.parsConsiderUsingSeparateRecordType(), lhs parseState)) $1 } | unionCaseReprElements @@ -2332,50 +2418,52 @@ recdFieldDeclList: /* A field declaration in a record type */ recdFieldDecl: - | opt_attributes fieldDecl - { let fld = $2 $1 false - let (Field(a,b,c,d,e,f,vis,g)) = fld - if Option.isSome vis then errorR(Error(FSComp.SR.parsRecordFieldsCannotHaveVisibilityDeclarations(),rhs parseState 2)) - Field(a,b,c,d,e,f,None,g) } + | opt_attributes fieldDecl + { let wholeRange = rhs2 parseState 1 2 + let fld = $2 $1 false wholeRange + let (Field (a, b, c, d, e, f, vis, wholeRange)) = fld + if Option.isSome vis then errorR (Error (FSComp.SR.parsRecordFieldsCannotHaveVisibilityDeclarations (), rhs parseState 2)) + Field (a, b, c, d, e, f, None, wholeRange) } /* Part of a field or val declaration in a record type or object type */ fieldDecl: | opt_mutable opt_access ident COLON typ - { let mRhs = rhs2 parseState 3 5 - let xmlDoc = grabXmlDoc(parseState,3) - (fun attrs stat -> Field(attrs, stat,Some $3,$5,$1,xmlDoc,$2,mRhs)) } - + { let xmlDoc = grabXmlDoc (parseState, 3) + fun attrs stat wholeRange -> Field(attrs, stat, Some $3, $5, $1, xmlDoc, $2, wholeRange) } /* An exception definition */ exconDefn: | exconCore opt_classDefn - { SynExceptionDefn($1,$2, ($1.Range,$2) ||> unionRangeWithListBy (fun cd -> cd.Range) ) } + { SynExceptionDefn($1, $2, ($1.Range, $2) ||> unionRangeWithListBy (fun cd -> cd.Range) ) } /* Part of an exception definition */ exceptionAndGrabDoc: - | EXCEPTION { grabXmlDoc(parseState,1) } + | EXCEPTION + { grabXmlDoc(parseState, 1) } /* Part of an exception definition */ exconCore: | exceptionAndGrabDoc opt_attributes opt_access exconIntro exconRepr - { SynExceptionDefnRepr($2,$4,$5,$1,$3,(match $5 with None -> rhs2 parseState 1 4 | Some p -> unionRanges (rangeOfLongIdent p) (rhs2 parseState 1 4))) } + { SynExceptionDefnRepr($2, $4, $5, $1, $3, (match $5 with None -> rhs2 parseState 1 4 | Some p -> unionRanges (rangeOfLongIdent p) (rhs2 parseState 1 4))) } /* Part of an exception definition */ exconIntro: | ident - { UnionCase ( [], $1,UnionCaseFields [],PreXmlDoc.Empty,None,lhs parseState) } + { UnionCase([], $1, UnionCaseFields [], PreXmlDoc.Empty, None, lhs parseState) } | ident OF unionCaseRepr - { UnionCase ( [], $1,UnionCaseFields $3,PreXmlDoc.Empty,None,lhs parseState) } + { UnionCase([], $1, UnionCaseFields $3, PreXmlDoc.Empty, None, lhs parseState) } exconRepr: - | { None } - | EQUALS path { Some ($2.Lid) } + | /* EMPTY */ + { None } + + | EQUALS path + { Some ($2.Lid) } openDecl: | OPEN path { $2 } - /*-------------------------------------------------------------------------*/ /* F# Definitions, Types, Patterns and Expressions */ @@ -2394,18 +2482,18 @@ defnBindings: | Some lastRange -> unionRanges mLetKwd lastRange // The first binding swallows any attributes prior to the 'let' - BindingSetPreAttrs(mLetKwd,isRec,isUse, + BindingSetPreAttrs(mLetKwd, isRec, isUse, (fun attrs vis -> // apply the builder let binds = localBindingsBuilder attrs vis mLetKwd if not isRec && not (isNilOrSingleton binds) then reportParseErrorAt mLetKwd (FSComp.SR.parsLetAndForNonRecBindings()) - [],binds), + [], binds), bindingSetRange) } | cPrototype { let bindRange = lhs parseState - BindingSetPreAttrs(bindRange, false,false,$1,bindRange) } + BindingSetPreAttrs(bindRange, false, false, $1, bindRange) } /* A 'do ...' statement in the non-#light syntax */ @@ -2415,7 +2503,7 @@ doBinding: let mWhole = unionRanges mDoKwd $2.Range // any attributes prior to the 'let' are left free, e.g. become top-level attributes // associated with the module, 'main' function or assembly depending on their target - BindingSetPreAttrs(mDoKwd,false,false,(fun attrs vis -> attrs,[mkSynDoBinding (vis,true,$2,mWhole)]), mWhole) } + BindingSetPreAttrs(mDoKwd, false, false, (fun attrs vis -> attrs, [mkSynDoBinding (vis, true, $2, mWhole)]), mWhole) } /* A 'let ....' binding in the #light syntax */ @@ -2435,12 +2523,12 @@ hardwhiteLetBindings: | Some lastRange -> unionRanges mLetKwd lastRange // the first binding swallow any attributes prior to the 'let' - BindingSetPreAttrs(mLetKwd,isRec,isUse, + BindingSetPreAttrs(mLetKwd, isRec, isUse, (fun attrs vis -> let binds = localBindingsBuilder attrs vis mLetKwd if not isRec && not (isNilOrSingleton binds) then reportParseErrorAt mLetKwd (FSComp.SR.parsLetAndForNonRecBindings()) - [],binds), + [], binds), bindingSetRange), (unionRanges mLetKwd bindingSetRange) } @@ -2449,51 +2537,62 @@ hardwhiteDoBinding: | ODO typedSeqExprBlock hardwhiteDefnBindingsTerminator { let mLetKwd = rhs parseState 1 let bindingSetRange = unionRanges mLetKwd $2.Range - let seqPt = NoSequencePointAtDoBinding + let seqPt = NoDebugPointAtDoBinding // any attributes prior to the 'let' are left free, e.g. become top-level attributes // associated with the module, 'main' function or assembly depending on their target - BindingSetPreAttrs(mLetKwd,false,false,(fun attrs vis -> attrs,[mkSynDoBinding (vis,true,$2,bindingSetRange)]),bindingSetRange), $2 } + BindingSetPreAttrs(mLetKwd, false, false, (fun attrs vis -> attrs, [mkSynDoBinding (vis, true, $2, bindingSetRange)]), bindingSetRange), $2 } /* The bindings in a class type definition */ classDefnBindings: - | defnBindings { $1 } - | doBinding { $1 } - | hardwhiteLetBindings { let b,m = $1 in b } - | hardwhiteDoBinding { fst $1 } + | defnBindings + { $1 } + + | doBinding + { $1 } + + | hardwhiteLetBindings + { let b, m = $1 in b } + + | hardwhiteDoBinding + { fst $1 } /* The terminator for a 'let ....' binding in the #light syntax */ hardwhiteDefnBindingsTerminator: | ODECLEND { (fun _ m -> ()) } + | recover - { (fun kwd m -> reportParseErrorAt m (match kwd with - | "let!" -> FSComp.SR.parsUnmatchedLetBang() - | "use!" -> FSComp.SR.parsUnmatchedUseBang() - | "use" -> FSComp.SR.parsUnmatchedUse() - | _ (*"let" *) -> FSComp.SR.parsUnmatchedLet())) } + { (fun kwd m -> + let msg = + match kwd with + | "let!" -> FSComp.SR.parsUnmatchedLetBang() + | "use!" -> FSComp.SR.parsUnmatchedUseBang() + | "use" -> FSComp.SR.parsUnmatchedUse() + | _ (*"let" *) -> FSComp.SR.parsUnmatchedLet() + reportParseErrorAt m msg) } /* An 'extern' DllImport function definition in C-style syntax */ cPrototype: | EXTERN cRetType opt_access ident opt_HIGH_PRECEDENCE_APP LPAREN cArgs rparen - { let rty,vis,nm,args = $2,$3,$4,$7 - let xmlDoc = grabXmlDoc(parseState,1) + { let rty, vis, nm, args = $2, $3, $4, $7 + let xmlDoc = grabXmlDoc(parseState, 1) let nmm = rhs parseState 3 let argsm = rhs parseState 6 let mBindLhs = lhs parseState let mWhole = lhs parseState let mRhs = lhs parseState - let rhsExpr = SynExpr.App(ExprAtomicFlag.NonAtomic, - false, - SynExpr.Ident(ident("failwith",rhs parseState 6)), - SynExpr.Const(SynConst.String("extern was not given a DllImport attribute",rhs parseState 8),rhs parseState 8), + let rhsExpr = SynExpr.App (ExprAtomicFlag.NonAtomic, + false, + SynExpr.Ident (ident("failwith", rhs parseState 6)), + SynExpr.Const (SynConst.String("extern was not given a DllImport attribute", rhs parseState 8), rhs parseState 8), mRhs) (fun attrs vis -> - let bindingId = SynPat.LongIdent (LongIdentWithDots([nm],[]), None, Some noInferredTypars, SynConstructorArgs.Pats [SynPat.Tuple(false,args,argsm)], vis, nmm) + let bindingId = SynPat.LongIdent (LongIdentWithDots([nm], []), None, Some noInferredTypars, SynArgPats.Pats [SynPat.Tuple(false, args, argsm)], vis, nmm) let binding = mkSynBinding (xmlDoc, bindingId) - (vis, false, false, mBindLhs, NoSequencePointAtInvisibleBinding, Some rty, rhsExpr, mRhs, [], attrs, None) + (vis, false, false, mBindLhs, NoDebugPointAtInvisibleBinding, Some rty, rhsExpr, mRhs, [], attrs, None) [], [binding]) } /* A list of arguments in an 'extern' DllImport function definition */ @@ -2519,42 +2618,42 @@ cMoreArgs: /* A single argument in an 'extern' DllImport function definition */ cArg: | opt_attributes cType - { let m = lhs parseState in SynPat.Typed(SynPat.Wild m,$2,m) |> addAttribs $1 } + { let m = lhs parseState in SynPat.Typed(SynPat.Wild m, $2, m) |> addAttribs $1 } | opt_attributes cType ident - { let m = lhs parseState in SynPat.Typed(SynPat.Named (SynPat.Wild m,$3,false,None,m),$2,m) |> addAttribs $1 } + { let m = lhs parseState in SynPat.Typed(SynPat.Named (SynPat.Wild m, $3, false, None, m), $2, m) |> addAttribs $1 } /* An type in an 'extern' DllImport function definition */ cType: | path { let m = $1.Range - SynType.App(SynType.LongIdent($1),None,[],[],None,false,m) } + SynType.App(SynType.LongIdent($1), None, [], [], None, false, m) } | cType opt_HIGH_PRECEDENCE_APP LBRACK RBRACK { let m = lhs parseState - SynType.App(SynType.LongIdent(LongIdentWithDots([ident("[]",m)],[])),None,[$1],[],None,true,m) } + SynType.App(SynType.LongIdent(LongIdentWithDots([ident("[]", m)], [])), None, [$1], [], None, true, m) } | cType STAR { let m = lhs parseState - SynType.App(SynType.LongIdent(LongIdentWithDots([ident("nativeptr",m)],[])),None,[$1],[],None,true,m) } + SynType.App(SynType.LongIdent(LongIdentWithDots([ident("nativeptr", m)], [])), None, [$1], [], None, true, m) } | cType AMP { let m = lhs parseState - SynType.App(SynType.LongIdent(LongIdentWithDots([ident("byref",m)],[])),None,[$1],[],None,true,m) } + SynType.App(SynType.LongIdent(LongIdentWithDots([ident("byref", m)], [])), None, [$1], [], None, true, m) } | VOID STAR { let m = lhs parseState - SynType.App(SynType.LongIdent(LongIdentWithDots([ident("nativeint",m)],[])),None,[],[],None,true,m) } + SynType.App(SynType.LongIdent(LongIdentWithDots([ident("nativeint", m)], [])), None, [], [], None, true, m) } /* A return type in an 'extern' DllImport function definition */ cRetType: | opt_attributes cType - { SynReturnInfo(($2,SynArgInfo($1,false,None)),rhs parseState 2) } + { SynReturnInfo(($2, SynArgInfo($1, false, None)), rhs parseState 2) } | opt_attributes VOID { let m = rhs parseState 2 - SynReturnInfo((SynType.App(SynType.LongIdent(LongIdentWithDots([ident("unit",m)],[])),None,[],[],None,false,m),SynArgInfo($1,false,None)),m) } + SynReturnInfo((SynType.App(SynType.LongIdent(LongIdentWithDots([ident("unit", m)], [])), None, [], [], None, false, m), SynArgInfo($1, false, None)), m) } localBindings: @@ -2562,7 +2661,7 @@ localBindings: { let (moreBindings, moreBindingRanges) = List.unzip $2 let moreLocalBindingsLastRange = if moreBindingRanges.IsEmpty then None else Some (List.last moreBindingRanges) match $1 with - | Some (localBindingRange,attrLocalBindingBuilder) -> + | Some (localBindingRange, attrLocalBindingBuilder) -> let lastRange = match moreLocalBindingsLastRange with | None -> localBindingRange @@ -2576,7 +2675,7 @@ moreLocalBindings: | AND attr_localBinding moreLocalBindings { let mLetKwd = rhs parseState 1 (match $2 with - | Some (localBindingRange,attrLocalBindingBuilder) -> (attrLocalBindingBuilder [] None mLetKwd false,localBindingRange) :: $3 + | Some (localBindingRange, attrLocalBindingBuilder) -> (attrLocalBindingBuilder [] None mLetKwd false, localBindingRange) :: $3 | None -> $3) } | %prec prec_no_more_attr_bindings @@ -2587,9 +2686,9 @@ moreLocalBindings: attr_localBinding: | opt_attributes localBinding { let attrs2 = $1 - let localBindingRange,localBindingBuilder = $2 + let localBindingRange, localBindingBuilder = $2 let attrLocalBindingBuilder = (fun attrs vis mLetKwd _ -> localBindingBuilder (attrs@attrs2) vis mLetKwd) - Some(localBindingRange,attrLocalBindingBuilder) } + Some(localBindingRange, attrLocalBindingBuilder) } | error { None } @@ -2598,7 +2697,7 @@ attr_localBinding: /* A single binding in an expression or definition */ localBinding: | opt_inline opt_mutable bindingPattern opt_topReturnTypeWithTypeConstraints EQUALS typedExprWithStaticOptimizationsBlock - { let (expr:SynExpr),opts = $6 + { let (expr:SynExpr), opts = $6 let eqm = rhs parseState 5 let mRhs = expr.Range let optReturnType = $4 @@ -2607,34 +2706,34 @@ localBinding: let localBindingBuilder = (fun attrs vis mLetKwd -> let mWhole = unionRanges mLetKwd mRhs - let spBind = if IsControlFlowExpression expr then NoSequencePointAtLetBinding else SequencePointAtBinding(mWhole) - bindingBuilder (vis,$1,$2,mBindLhs,spBind,optReturnType,expr,mRhs,opts,attrs,None)) - localBindingRange,localBindingBuilder } + let spBind = if IsControlFlowExpression expr then NoDebugPointAtLetBinding else DebugPointAtBinding mWhole + bindingBuilder (vis, $1, $2, mBindLhs, spBind, optReturnType, expr, mRhs, opts, attrs, None)) + localBindingRange, localBindingBuilder } | opt_inline opt_mutable bindingPattern opt_topReturnTypeWithTypeConstraints EQUALS error { let mWhole = rhs2 parseState 3 5 let mRhs = rhs parseState 5 let optReturnType = $4 - let bindingBuilder,mBindLhs = $3 + let bindingBuilder, mBindLhs = $3 let localBindingBuilder = (fun attrs vis mLetKwd -> - let spBind = SequencePointAtBinding(unionRanges mLetKwd mRhs) + let spBind = DebugPointAtBinding (unionRanges mLetKwd mRhs) let eqm = rhs parseState 5 let zeroWidthAtEnd = eqm.EndRange - bindingBuilder (vis,$1,$2,mBindLhs,spBind,optReturnType,arbExpr("localBinding1",zeroWidthAtEnd),mRhs,[],attrs,None)) - mWhole,localBindingBuilder } + bindingBuilder (vis, $1, $2, mBindLhs, spBind, optReturnType, arbExpr("localBinding1", zeroWidthAtEnd), mRhs, [], attrs, None)) + mWhole, localBindingBuilder } | opt_inline opt_mutable bindingPattern opt_topReturnTypeWithTypeConstraints recover { if not $5 then reportParseErrorAt (rhs parseState 5) (FSComp.SR.parsUnexpectedEndOfFileDefinition()) let optReturnType = $4 let mWhole = match optReturnType with None -> rhs parseState 3 | Some _ -> rhs2 parseState 3 4 let mRhs = mWhole.EndRange // zero-width range at end of last good token - let bindingBuilder,mBindLhs = $3 + let bindingBuilder, mBindLhs = $3 let localBindingBuilder = (fun attrs vis mLetKwd -> - let spBind = SequencePointAtBinding(unionRanges mLetKwd mRhs) - bindingBuilder (vis,$1,$2,mBindLhs,spBind,optReturnType,arbExpr("localBinding2",mRhs),mRhs,[],attrs,None)) - mWhole,localBindingBuilder } + let spBind = DebugPointAtBinding (unionRanges mLetKwd mRhs) + bindingBuilder (vis, $1, $2, mBindLhs, spBind, optReturnType, arbExpr("localBinding2", mRhs), mRhs, [], attrs, None)) + mWhole, localBindingBuilder } /* A single expression with an optional type annotation, and an optional static optimization block */ @@ -2644,52 +2743,96 @@ typedExprWithStaticOptimizationsBlock: | OBLOCKBEGIN typedExprWithStaticOptimizations recover { if not $3 then reportParseErrorAt (rhs parseState 3) (FSComp.SR.parsUnexpectedEndOfFile()) - let a,b = $2 + let a, b = $2 (exprFromParseError a, b) } | typedExprWithStaticOptimizations { $1 } typedExprWithStaticOptimizations : - | typedSeqExpr opt_staticOptimizations { $1, List.rev $2 } + | typedSeqExpr opt_staticOptimizations + { $1, List.rev $2 } opt_staticOptimizations: - | opt_staticOptimizations staticOptimization { $2 :: $1 } - | { [] } + | opt_staticOptimizations staticOptimization + { $2 :: $1 } + + | /* EMPTY */ + { [] } staticOptimization: - | WHEN staticOptimizationConditions EQUALS typedSeqExprBlock { ($2,$4) } + | WHEN staticOptimizationConditions EQUALS typedSeqExprBlock + { ($2, $4) } staticOptimizationConditions: - | staticOptimizationConditions AND staticOptimizationCondition { $3 :: $1 } - | staticOptimizationCondition { [$1 ] } + | staticOptimizationConditions AND staticOptimizationCondition + { $3 :: $1 } + + | staticOptimizationCondition + { [$1 ] } staticOptimizationCondition: - | typar COLON typ { WhenTyparTyconEqualsTycon($1,$3,lhs parseState) } - | typar STRUCT { WhenTyparIsStruct($1,lhs parseState) } + | typar COLON typ + { WhenTyparTyconEqualsTycon($1, $3, lhs parseState) } + + | typar STRUCT + { WhenTyparIsStruct($1, lhs parseState) } rawConstant: - | INT8 { if snd $1 then errorR(Error(FSComp.SR.lexOutsideEightBitSigned(), lhs parseState)) - SynConst.SByte (fst $1) } - | UINT8 { SynConst.Byte $1 } - | INT16 { if snd $1 then errorR(Error(FSComp.SR.lexOutsideSixteenBitSigned(), lhs parseState)) - SynConst.Int16 (fst $1) } - | UINT16 { SynConst.UInt16 $1 } - | INT32 { if snd $1 then errorR(Error(FSComp.SR.lexOutsideThirtyTwoBitSigned(), lhs parseState)) - SynConst.Int32 (fst $1) } - | UINT32 { SynConst.UInt32 $1 } - | INT64 { if snd $1 then errorR(Error(FSComp.SR.lexOutsideSixtyFourBitSigned(), lhs parseState)) - SynConst.Int64 (fst $1) } - | UINT64 { SynConst.UInt64 $1 } - | NATIVEINT { SynConst.IntPtr $1 } - | UNATIVEINT { SynConst.UIntPtr $1 } - | IEEE32 { SynConst.Single $1 } - | IEEE64 { SynConst.Double $1 } - | CHAR { SynConst.Char $1 } - | DECIMAL { SynConst.Decimal $1 } - | BIGNUM { SynConst.UserNum $1 } - | stringOrKeywordString { SynConst.String ($1,lhs parseState) } - | BYTEARRAY { SynConst.Bytes ($1,lhs parseState) } + | INT8 + { if snd $1 then errorR(Error(FSComp.SR.lexOutsideEightBitSigned(), lhs parseState)) + SynConst.SByte (fst $1) } + + | UINT8 + { SynConst.Byte $1 } + + | INT16 + { if snd $1 then errorR(Error(FSComp.SR.lexOutsideSixteenBitSigned(), lhs parseState)) + SynConst.Int16 (fst $1) } + + | UINT16 + { SynConst.UInt16 $1 } + + | INT32 + { if snd $1 then errorR(Error(FSComp.SR.lexOutsideThirtyTwoBitSigned(), lhs parseState)) + SynConst.Int32 (fst $1) } + + | UINT32 + { SynConst.UInt32 $1 } + + | INT64 + { if snd $1 then errorR(Error(FSComp.SR.lexOutsideSixtyFourBitSigned(), lhs parseState)) + SynConst.Int64 (fst $1) } + + | UINT64 + { SynConst.UInt64 $1 } + + | NATIVEINT + { SynConst.IntPtr $1 } + + | UNATIVEINT + { SynConst.UIntPtr $1 } + + | IEEE32 + { SynConst.Single $1 } + + | IEEE64 + { SynConst.Double $1 } + + | CHAR + { SynConst.Char $1 } + + | DECIMAL + { SynConst.Decimal $1 } + + | BIGNUM + { SynConst.UserNum $1 } + + | stringOrKeywordString + { SynConst.String ($1, lhs parseState) } + + | BYTEARRAY + { SynConst.Bytes ($1, lhs parseState) } rationalConstant: | INT32 INFIX_STAR_DIV_MOD_OP INT32 @@ -2704,11 +2847,13 @@ rationalConstant: if (snd $2) || (snd $4) then errorR(Error(FSComp.SR.lexOutsideThirtyTwoBitSigned(), lhs parseState)) SynRationalConst.Negate(SynRationalConst.Rational(fst $2, fst $4, lhs parseState)) } - | INT32 { if snd $1 then errorR(Error(FSComp.SR.lexOutsideThirtyTwoBitSigned(), lhs parseState)) - SynRationalConst.Integer(fst $1) } + | INT32 + { if snd $1 then errorR(Error(FSComp.SR.lexOutsideThirtyTwoBitSigned(), lhs parseState)) + SynRationalConst.Integer(fst $1) } - | MINUS INT32 { if snd $2 then errorR(Error(FSComp.SR.lexOutsideThirtyTwoBitSigned(), lhs parseState)) - SynRationalConst.Negate(SynRationalConst.Integer(fst $2)) } + | MINUS INT32 + { if snd $2 then errorR(Error(FSComp.SR.lexOutsideThirtyTwoBitSigned(), lhs parseState)) + SynRationalConst.Negate(SynRationalConst.Integer(fst $2)) } atomicUnsignedRationalConstant: | INT32 { if snd $1 then errorR(Error(FSComp.SR.lexOutsideThirtyTwoBitSigned(), lhs parseState)) @@ -2724,238 +2869,316 @@ atomicRationalConstant: { SynRationalConst.Negate($2) } constant: - | rawConstant { $1 } - | rawConstant HIGH_PRECEDENCE_TYAPP measureTypeArg { SynConst.Measure($1, $3) } + | rawConstant + { $1 } + + | rawConstant HIGH_PRECEDENCE_TYAPP measureTypeArg + { SynConst.Measure($1, $3) } bindingPattern: | headBindingPattern - { let xmlDoc = grabXmlDoc(parseState,1) - mkSynBinding (xmlDoc,$1), rhs parseState 1 } + { let xmlDoc = grabXmlDoc(parseState, 1) + mkSynBinding (xmlDoc, $1), rhs parseState 1 } -/* sp = v | sp:typ | attrs sp */ +// 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 - { SynSimplePat.Id ($1,None,false,false,false,rhs parseState 1) } - | QMARK ident - { SynSimplePat.Id ($2,None,false,false,true,rhs parseState 2) } + | ident + { let m = rhs parseState 1 + SynPat.Named(SynPat.Wild m, $1, false, None, m) } + + | QMARK ident + { SynPat.OptionalVal($2, rhs parseState 2) } + | simplePattern COLON typeWithTypeConstraints - { let lhsm = lhs parseState - SynSimplePat.Typed($1,$3,lhsm) } + { SynPat.Typed($1, $3, lhs parseState) } + | attributes simplePattern %prec paren_pat_attribs - { let lhsm = lhs parseState - SynSimplePat.Attrib($2,$1,lhsm) } + { SynPat.Attrib($2, $1, lhs parseState) } simplePatternCommaList: - | simplePattern - { [$1] } - | simplePattern COMMA simplePatternCommaList - { $1 :: $3 } + | simplePattern + { $1 } + + | simplePattern COMMA simplePatternCommaList + { match $3 with + | SynPat.Tuple(_, pats, _) -> SynPat.Tuple(false, $1 :: pats, rhs2 parseState 1 3) + | _ -> SynPat.Tuple(false, [$1; $3], rhs2 parseState 1 3) } simplePatterns: - | LPAREN simplePatternCommaList rparen - { $2 } - | LPAREN rparen - { [] } - | LPAREN simplePatternCommaList recover - { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedParen()) - [] } - | LPAREN error rparen - { (* silent recovery *) [] } - | LPAREN recover - { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedParen()) - [] } + | LPAREN simplePatternCommaList rparen + { let parenPat = SynPat.Paren($2, rhs2 parseState 1 3) + let simplePats, _ = SimplePatsOfPat parseState.SynArgNameGenerator parenPat + simplePats } + + | 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 } headBindingPattern: | headBindingPattern AS ident - { SynPat.Named ($1,$3,false,None,rhs2 parseState 1 3) } + { SynPat.Named ($1, $3, false, None, rhs2 parseState 1 3) } + | headBindingPattern BAR headBindingPattern - { SynPat.Or($1,$3,rhs2 parseState 1 3) } + { SynPat.Or($1, $3, rhs2 parseState 1 3) } + | headBindingPattern COLON_COLON headBindingPattern - { SynPat.LongIdent (LongIdentWithDots(mkSynCaseName (rhs parseState 2) opNameCons,[]), None, None, SynConstructorArgs.Pats [SynPat.Tuple (false,[$1;$3],rhs2 parseState 1 3)],None,lhs parseState) } + { SynPat.LongIdent (LongIdentWithDots(mkSynCaseName (rhs parseState 2) opNameCons, []), None, None, SynArgPats.Pats [SynPat.Tuple (false, [$1;$3], rhs2 parseState 1 3)], None, lhs parseState) } + | tuplePatternElements %prec pat_tuple - { SynPat.Tuple(false,List.rev $1, lhs parseState) } + { SynPat.Tuple(false, List.rev $1, lhs parseState) } + | conjPatternElements %prec pat_conj { SynPat.Ands(List.rev $1, lhs parseState) } + | constrPattern { $1 } tuplePatternElements: | tuplePatternElements COMMA headBindingPattern { $3 :: $1 } + | headBindingPattern COMMA headBindingPattern { $3 :: $1 :: [] } conjPatternElements: | conjPatternElements AMP headBindingPattern - { $3 :: $1 } + { $3 :: $1 } + | headBindingPattern AMP headBindingPattern - { $3 :: $1 :: [] } + { $3 :: $1 :: [] } namePatPairs: - | namePatPair opt_seps { [$1], lhs parseState } - | namePatPair seps namePatPairs { let (rs, _) = $3 in ($1::rs), lhs parseState } + | namePatPair opt_seps + { [$1], lhs parseState } + + | namePatPair seps namePatPairs + { let (rs, _) = $3 in ($1 :: rs), lhs parseState } namePatPair: - | ident EQUALS parenPattern { ($1, $3) } + | ident EQUALS parenPattern + { ($1, $3) } constrPattern: | atomicPatternLongIdent explicitValTyparDecls - { let vis,lid = $1 in SynPat.LongIdent (lid,None,Some $2, SynConstructorArgs.Pats [],vis,lhs parseState) } + { let vis, lid = $1 in SynPat.LongIdent (lid, None, Some $2, SynArgPats.Pats [], vis, lhs parseState) } + | atomicPatternLongIdent opt_explicitValTyparDecls2 atomicPatsOrNamePatPairs %prec pat_app - { let vis,lid = $1 in SynPat.LongIdent (lid,None,$2, $3,vis,lhs parseState) } + { let vis, lid = $1 in SynPat.LongIdent (lid, None, $2, $3, vis, lhs parseState) } + | atomicPatternLongIdent opt_explicitValTyparDecls2 HIGH_PRECEDENCE_PAREN_APP atomicPatsOrNamePatPairs - { let vis,lid = $1 in SynPat.LongIdent (lid,None,$2, $4,vis,lhs parseState) } + { let vis, lid = $1 in SynPat.LongIdent (lid, None, $2, $4, vis, lhs parseState) } + | atomicPatternLongIdent opt_explicitValTyparDecls2 HIGH_PRECEDENCE_BRACK_APP atomicPatsOrNamePatPairs - { let vis,lid = $1 in SynPat.LongIdent (lid,None,$2, $4,vis,lhs parseState) } + { let vis, lid = $1 in SynPat.LongIdent (lid, None, $2, $4, vis, lhs parseState) } + | COLON_QMARK atomTypeOrAnonRecdType %prec pat_isinst - { SynPat.IsInst($2,lhs parseState) } + { SynPat.IsInst($2, lhs parseState) } + | atomicPattern { $1 } atomicPatsOrNamePatPairs: - | LPAREN namePatPairs rparen { SynConstructorArgs.NamePatPairs $2 } - | atomicPatterns { SynConstructorArgs.Pats $1 } + | LPAREN namePatPairs rparen + { SynArgPats.NamePatPairs $2 } + + | atomicPatterns + { SynArgPats.Pats $1 } atomicPatterns: | atomicPattern atomicPatterns %prec pat_args { $1 :: $2 } + | atomicPattern HIGH_PRECEDENCE_BRACK_APP atomicPatterns { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsSuccessivePatternsShouldBeSpacedOrTupled()) $1 :: $3 } + | atomicPattern HIGH_PRECEDENCE_PAREN_APP atomicPatterns { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsSuccessivePatternsShouldBeSpacedOrTupled()) $1 :: $3 } - | atomicPattern { [$1] } + + | atomicPattern + { [$1] } atomicPattern: | quoteExpr - { SynPat.QuoteExpr($1,lhs parseState) } - | CHAR DOT_DOT CHAR { SynPat.DeprecatedCharRange ($1,$3,rhs2 parseState 1 3) } + { SynPat.QuoteExpr($1, lhs parseState) } + + | CHAR DOT_DOT CHAR + { SynPat.DeprecatedCharRange ($1, $3, rhs2 parseState 1 3) } + | LBRACE recordPatternElementsAux rbrace - { let rs,m = $2 in SynPat.Record (rs,m) } + { let rs, m = $2 in SynPat.Record (rs, rhs2 parseState 1 3) } + | LBRACK listPatternElements RBRACK - { SynPat.ArrayOrList(false,$2,lhs parseState) } + { SynPat.ArrayOrList(false, $2, lhs parseState) } + | LBRACK_BAR listPatternElements BAR_RBRACK - { SynPat.ArrayOrList(true,$2, lhs parseState) } + { SynPat.ArrayOrList(true, $2, lhs parseState) } + | UNDERSCORE { SynPat.Wild (lhs parseState) } + | QMARK ident - { SynPat.OptionalVal($2,lhs parseState) } + { SynPat.OptionalVal($2, lhs parseState) } + | atomicPatternLongIdent %prec prec_atompat_pathop - { let vis,lidwd = $1 + { let vis, lidwd = $1 if not (isNilOrSingleton lidwd.Lid) || (String.isUpper (List.head lidwd.Lid).idText) then mkSynPatMaybeVar lidwd vis (lhs parseState) else mkSynPatVar vis (List.head lidwd.Lid) } + | constant - { SynPat.Const ($1,$1.Range (lhs parseState)) } + { SynPat.Const ($1, $1.Range (lhs parseState)) } + | FALSE - { SynPat.Const(SynConst.Bool false,lhs parseState) } + { SynPat.Const(SynConst.Bool false, lhs parseState) } + | TRUE - { SynPat.Const(SynConst.Bool true,lhs parseState) } + { SynPat.Const(SynConst.Bool true, lhs parseState) } + | NULL { SynPat.Null(lhs parseState) } + | LPAREN parenPatternBody rparen { let m = (lhs parseState) - SynPat.Paren($2 m,m) } + SynPat.Paren($2 m, m) } + | LPAREN parenPatternBody recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedParen()) patFromParseError ($2 (rhs2 parseState 1 2)) } + | LPAREN error rparen { (* silent recovery *) SynPat.Wild (lhs parseState) } + | LPAREN recover - { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedParen()) - SynPat.Wild (lhs parseState)} + { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedParen()) + SynPat.Wild (lhs parseState)} + | STRUCT LPAREN tupleParenPatternElements rparen - { SynPat.Tuple(true, List.rev $3,lhs parseState) } + { SynPat.Tuple(true, List.rev $3, lhs parseState) } + | STRUCT LPAREN tupleParenPatternElements recover { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnmatchedParen()); - SynPat.Tuple(true, List.rev $3,lhs parseState) } + SynPat.Tuple(true, List.rev $3, lhs parseState) } + | STRUCT LPAREN error rparen { (* silent recovery *) SynPat.Wild (lhs parseState) } + | STRUCT LPAREN recover { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnmatchedParen()); SynPat.Wild (lhs parseState)} - - parenPatternBody: | parenPattern { (fun m -> $1) } - | - { (fun m -> SynPat.Const(SynConst.Unit,m)) } + + | /* EMPTY */ + { (fun m -> SynPat.Const(SynConst.Unit, m)) } /* This duplicates out 'patterns' in order to give type annotations */ /* the desired precedence w.r.t. patterns, tuple patterns in particular. */ /* Duplication requried to minimize the disturbance to the grammar, */ /* in particular the expected property that "pat" parses the same as */ /* "(pat)"! Here are some examples: */ -/* a,b parses as (a,b) */ -/* (a,b) also parses as (a,b) */ -/* (a,b : t) parses as (a, (b:t)) */ -/* a,b as t parses as ((a,b) as t) */ -/* (a,b as t) also parses as ((a,b) as t) */ -/* a,b | c,d parses as ((a,b) | (c,d)) */ -/* (a,b | c,d) also parses as ((a,b) | (c,d)) */ -/* (a : t,b) parses as ((a:t),b) */ -/* (a : t1,b : t2) parses as ((a:t),(b:t2)) */ -/* (a,b as nm : t) parses as (((a,b) as nm) : t) */ -/* (a,b :: c : t) parses as (((a,b) :: c) : t) */ +/* a, b parses as (a, b) */ +/* (a, b) also parses as (a, b) */ +/* (a, b : t) parses as (a, (b:t)) */ +/* a, b as t parses as ((a, b) as t) */ +/* (a, b as t) also parses as ((a, b) as t) */ +/* a, b | c, d parses as ((a, b) | (c, d)) */ +/* (a, b | c, d) also parses as ((a, b) | (c, d)) */ +/* (a : t, b) parses as ((a:t), b) */ +/* (a : t1, b : t2) parses as ((a:t), (b:t2)) */ +/* (a, b as nm : t) parses as (((a, b) as nm) : t) */ +/* (a, b :: c : t) parses as (((a, b) :: c) : t) */ /* */ /* Probably the most unexpected thing here is that 'as nm' binds the */ /* whole pattern to the left, whereas ': t' binds only the pattern */ /* immediately preceding in the tuple. */ /* */ -/* Also, it is unexpected that '(a,b : t)' in a pattern binds differently to */ -/* '(a,b : t)' in an expression. It's not that easy to solve that without */ +/* Also, it is unexpected that '(a, b : t)' in a pattern binds differently to */ +/* '(a, b : t)' in an expression. It's not that easy to solve that without */ /* duplicating the entire expression grammar, or making a fairly severe breaking change */ /* to the language. */ parenPattern: | parenPattern AS ident - { SynPat.Named ($1,$3,false,None,rhs2 parseState 1 3) } + { SynPat.Named ($1, $3, false, None, rhs2 parseState 1 3) } + | parenPattern BAR parenPattern - { SynPat.Or($1,$3,rhs2 parseState 1 3) } + { SynPat.Or($1, $3, rhs2 parseState 1 3) } + | tupleParenPatternElements - { SynPat.Tuple(false,List.rev $1,lhs parseState) } + { SynPat.Tuple(false, List.rev $1, lhs parseState) } + | conjParenPatternElements - { SynPat.Ands(List.rev $1,rhs2 parseState 1 3) } + { SynPat.Ands(List.rev $1, rhs2 parseState 1 3) } + | parenPattern COLON typeWithTypeConstraints %prec paren_pat_colon { let lhsm = lhs parseState - SynPat.Typed($1,$3,lhsm) } + SynPat.Typed($1, $3, lhsm) } + | attributes parenPattern %prec paren_pat_attribs { let lhsm = lhs parseState - SynPat.Attrib($2,$1,lhsm) } + SynPat.Attrib($2, $1, lhsm) } + | parenPattern COLON_COLON parenPattern - { SynPat.LongIdent (LongIdentWithDots(mkSynCaseName (rhs parseState 2) opNameCons,[]), None, None, SynConstructorArgs.Pats [ SynPat.Tuple (false,[$1;$3],rhs2 parseState 1 3) ],None,lhs parseState) } + { SynPat.LongIdent (LongIdentWithDots(mkSynCaseName (rhs parseState 2) opNameCons, []), None, None, SynArgPats.Pats [ SynPat.Tuple (false, [$1;$3], rhs2 parseState 1 3) ], None, lhs parseState) } + | constrPattern { $1 } tupleParenPatternElements: | tupleParenPatternElements COMMA parenPattern { $3 :: $1 } + | parenPattern COMMA parenPattern { $3 :: $1 :: [] } conjParenPatternElements: | conjParenPatternElements AMP parenPattern { $3 :: $1 } + | parenPattern AMP parenPattern { $3 :: $1 :: [] } recordPatternElementsAux: /* Fix 1190 */ | recordPatternElement opt_seps - { [$1],lhs parseState } + { [$1], lhs parseState } + | recordPatternElement seps recordPatternElementsAux - { let r = $1 in let (rs,dropMark) = $3 in (r :: rs),lhs parseState } + { let r = $1 in let (rs, dropMark) = $3 in (r :: rs), lhs parseState } recordPatternElement: - | path EQUALS parenPattern { (List.frontAndBack $1.Lid,$3) } + | path EQUALS parenPattern { (List.frontAndBack $1.Lid, $3) } -listPatternElements: /* Fix 3569 */ - | +listPatternElements: + | /* EMPTY */ { [] } + | parenPattern opt_seps { [$1] } + | parenPattern seps listPatternElements { $1 :: $3 } @@ -2963,9 +3186,11 @@ listPatternElements: /* Fix 3569 */ typedSeqExprBlock: | OBLOCKBEGIN typedSeqExpr oblockend { $2 } + | OBLOCKBEGIN typedSeqExpr recover { if not $3 then reportParseErrorAt (rhs parseState 3) (FSComp.SR.parsUnexpectedEndOfFileExpression()) exprFromParseError $2 } + | typedSeqExpr { $1 } @@ -2973,81 +3198,111 @@ typedSeqExprBlock: declExprBlock: | OBLOCKBEGIN typedSeqExpr oblockend { $2 } + | declExpr { $1 } /* For some constructs the lex filter can't be sure to insert a matching OBLOCKEND, e.g. "function a -> b | c -> d" all in one line */ /* for these it only inserts a trailing ORIGHT_BLOCK_END */ typedSeqExprBlockR: - | typedSeqExpr ORIGHT_BLOCK_END { $1 } - | typedSeqExpr { $1 } + | typedSeqExpr ORIGHT_BLOCK_END + { $1 } + + | typedSeqExpr + { $1 } typedSeqExpr: - | seqExpr COLON typeWithTypeConstraints { SynExpr.Typed ($1,$3, unionRanges $1.Range $3.Range) } - | seqExpr { $1 } + | seqExpr COLON typeWithTypeConstraints + { SynExpr.Typed ($1, $3, unionRanges $1.Range $3.Range) } + + | seqExpr + { $1 } typedSeqExprEOF: - | typedSeqExpr EOF { checkEndOfFileError $2; $1 } + | typedSeqExpr EOF + { checkEndOfFileError $2; $1 } seqExpr: | declExpr seps seqExpr - { SynExpr.Sequential(SequencePointsAtSeq,true,$1,$3,unionRanges $1.Range $3.Range) } + { SynExpr.Sequential (DebugPointAtSequential.Both, true, $1, $3, unionRanges $1.Range $3.Range) } + | declExpr seps { $1 } + | declExpr %prec SEMICOLON { $1 } + | declExpr THEN seqExpr %prec prec_then_before - { SynExpr.Sequential(SequencePointsAtSeq,false,$1,$3,unionRanges $1.Range $3.Range ) } + { SynExpr.Sequential (DebugPointAtSequential.Both, false, $1, $3, unionRanges $1.Range $3.Range ) } + | declExpr OTHEN OBLOCKBEGIN typedSeqExpr oblockend %prec prec_then_before - { SynExpr.Sequential(SequencePointsAtSeq,false,$1,$4,unionRanges $1.Range $4.Range) } + { SynExpr.Sequential (DebugPointAtSequential.Both, false, $1, $4, unionRanges $1.Range $4.Range) } + | hardwhiteLetBindings %prec prec_args_error - { let hwlb,m = $1 - let mLetKwd,isUse = match hwlb with (BindingSetPreAttrs(m,_,isUse,_,_)) -> m,isUse + { let hwlb, m = $1 + let mLetKwd, isUse = match hwlb with (BindingSetPreAttrs(m, _, isUse, _, _)) -> m, isUse let usedKeyword = if isUse then "use" else "let" - reportParseErrorAt mLetKwd (FSComp.SR.parsExpectedExpressionAfterLet(usedKeyword,usedKeyword)) + reportParseErrorAt mLetKwd (FSComp.SR.parsExpectedExpressionAfterLet(usedKeyword, usedKeyword)) let fauxRange = m.EndRange // zero width range at end of m - mkLocalBindings (m,hwlb,arbExpr("seqExpr",fauxRange)) } + mkLocalBindings (m, hwlb, arbExpr("seqExpr", fauxRange)) } /* Use this as the last terminal when performing error recovery */ /* The contract for using this is that (a) if EOF occurs then the */ /* the using production must report an error and (b) the using production */ /* can report an error anyway if it is helpful, e.g. "unclosed '('" (giving two errors) */ recover: - | error { debugPrint("recovering via error"); true } - | EOF { debugPrint("recovering via EOF"); false } + | error + { debugPrint("recovering via error"); true } + + | EOF + { debugPrint("recovering via EOF"); false } + +moreBinders: + | AND_BANG headBindingPattern EQUALS typedSeqExprBlock IN moreBinders %prec expr_let + { let spBind = DebugPointAtBinding(rhs2 parseState 1 5) (* TODO Pretty sure this is wrong *) + let m = rhs parseState 1 (* TODO Pretty sure this is wrong *) + (spBind, $1, true, $2, $4, m) :: $6 } + | OAND_BANG headBindingPattern EQUALS typedSeqExprBlock hardwhiteDefnBindingsTerminator opt_OBLOCKSEP moreBinders %prec expr_let + { $5 "and!" (rhs parseState 1) // report unterminated error + let spBind = DebugPointAtBinding(rhs2 parseState 1 5) (* TODO Pretty sure this is wrong *) + let m = rhs parseState 1 (* TODO Pretty sure this is wrong *) + (spBind, $1, true, $2, $4, m) :: $7 } + + | %prec prec_no_more_attr_bindings + { [] } declExpr: | defnBindings IN typedSeqExpr %prec expr_let - { mkLocalBindings (unionRanges (rhs2 parseState 1 2) $3.Range,$1,$3) } + { mkLocalBindings (unionRanges (rhs2 parseState 1 2) $3.Range, $1, $3) } | defnBindings IN error %prec expr_let - { mkLocalBindings (rhs2 parseState 1 2,$1,arbExpr("declExpr1",(rhs parseState 3))) } + { mkLocalBindings (rhs2 parseState 1 2, $1, arbExpr("declExpr1", (rhs parseState 3))) } /* FSComp.SR.parsNoMatchingInForLet() -- leave this in for now - it's an unused error string */ | hardwhiteLetBindings typedSeqExprBlock %prec expr_let - { let hwlb,m = $1 - mkLocalBindings (unionRanges m $2.Range,hwlb,$2) } + { let hwlb, m = $1 + mkLocalBindings (unionRanges m $2.Range, hwlb, $2) } | hardwhiteLetBindings error %prec expr_let - { let hwlb,m = $1 - reportParseErrorAt (match hwlb with (BindingSetPreAttrs(m,_,_,_,_)) -> m) (FSComp.SR.parsErrorInReturnForLetIncorrectIndentation()) - mkLocalBindings (m,hwlb,arbExpr("declExpr2",(rhs parseState 2))) } + { let hwlb, m = $1 + reportParseErrorAt (match hwlb with (BindingSetPreAttrs(m, _, _, _, _)) -> m) (FSComp.SR.parsErrorInReturnForLetIncorrectIndentation()) + mkLocalBindings (m, hwlb, arbExpr("declExpr2", (rhs parseState 2))) } | hardwhiteLetBindings OBLOCKSEP typedSeqExprBlock %prec expr_let - { let hwlb,m = $1 + { let hwlb, m = $1 mkLocalBindings (unionRanges m $3.Range, hwlb, $3) } | hardwhiteLetBindings OBLOCKSEP error %prec expr_let - { let hwlb,m = $1 - //reportParseErrorAt (match hwlb with (BindingSetPreAttrs(m,_,_,_,_)) -> m) (FSComp.SR.parsErrorInReturnForLetIncorrectIndentation()) - mkLocalBindings (unionRanges m (rhs parseState 3),hwlb,arbExpr("declExpr3",(rhs parseState 3))) } + { let hwlb, m = $1 + //reportParseErrorAt (match hwlb with (BindingSetPreAttrs(m, _, _, _, _)) -> m) (FSComp.SR.parsErrorInReturnForLetIncorrectIndentation()) + mkLocalBindings (unionRanges m (rhs parseState 3), hwlb, arbExpr("declExpr3", (rhs parseState 3))) } | hardwhiteDoBinding %prec expr_let { let e = snd $1 - SynExpr.Do(e,e.Range) } + SynExpr.Do (e, e.Range) } | anonMatchingExpr %prec expr_function { $1 } @@ -3057,9 +3312,9 @@ declExpr: | MATCH typedSeqExpr withClauses %prec expr_match { let mMatch = (rhs parseState 1) - let mWith,(clauses,mLast) = $3 - let spBind = SequencePointAtBinding(unionRanges mMatch mWith) - SynExpr.Match(spBind, $2,clauses,unionRanges mMatch mLast) } + let mWith, (clauses, mLast) = $3 + let spBind = DebugPointAtBinding(unionRanges mMatch mWith) + SynExpr.Match (spBind, $2, clauses, unionRanges mMatch mLast) } | MATCH typedSeqExpr recover %prec expr_match { if not $3 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedEndOfFileMatch()) @@ -3068,9 +3323,9 @@ declExpr: | MATCH_BANG typedSeqExpr withClauses %prec expr_match { let mMatch = (rhs parseState 1) - let mWith,(clauses,mLast) = $3 - let spBind = SequencePointAtBinding(unionRanges mMatch mWith) - SynExpr.MatchBang(spBind, $2,clauses,unionRanges mMatch mLast) } + let mWith, (clauses, mLast) = $3 + let spBind = DebugPointAtBinding(unionRanges mMatch mWith) + SynExpr.MatchBang (spBind, $2, clauses, unionRanges mMatch mLast) } | MATCH_BANG typedSeqExpr recover %prec expr_match { if not $3 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedEndOfFileMatch()) @@ -3079,13 +3334,13 @@ declExpr: | TRY typedSeqExprBlockR withClauses %prec expr_try { let mTry = (rhs parseState 1) - let spTry = SequencePointAtTry(mTry) - let mWith,(clauses,mLast) = $3 - let spWith = SequencePointAtWith(mWith) + let spTry = DebugPointAtTry.Yes mTry + let mWith, (clauses, mLast) = $3 + let spWith = DebugPointAtWith.Yes mWith let mTryToWith = unionRanges mTry mWith let mWithToLast = unionRanges mWith mLast let mTryToLast = unionRanges mTry mLast - SynExpr.TryWith($2, mTryToWith, clauses,mWithToLast, mTryToLast,spTry,spWith) } + SynExpr.TryWith ($2, mTryToWith, clauses, mWithToLast, mTryToLast, spTry, spWith) } | TRY typedSeqExprBlockR recover %prec expr_try { // Produce approximate expression during error recovery @@ -3095,10 +3350,10 @@ declExpr: | TRY typedSeqExprBlockR FINALLY typedSeqExprBlock %prec expr_try { let mTry = rhs parseState 1 - let spTry = SequencePointAtTry(mTry) - let spFinally = SequencePointAtFinally(rhs parseState 3) + let spTry = DebugPointAtTry.Yes mTry + let spFinally = DebugPointAtFinally.Yes (rhs parseState 3) let mTryToLast = unionRanges mTry $4.Range - SynExpr.TryFinally($2, $4,mTryToLast,spTry,spFinally) } + SynExpr.TryFinally ($2, $4, mTryToLast, spTry, spFinally) } | IF declExpr ifExprCases %prec expr_if { let mIf = (rhs parseState 1) @@ -3116,325 +3371,415 @@ declExpr: { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsIncompleteIf()) // Produce an approximate expression during error recovery. There can still be value in doing this even // for this pathological case. - let m = (rhs parseState 1) + let m = rhs parseState 1 let mEnd = m.EndRange - let spIfToThen = SequencePointAtBinding mEnd - exprFromParseError (SynExpr.IfThenElse(arbExpr("ifGuard1",mEnd),arbExpr("thenBody1",mEnd),None,spIfToThen,true,m,m)) } + let spIfToThen = DebugPointAtBinding mEnd + exprFromParseError (SynExpr.IfThenElse (arbExpr("ifGuard1", mEnd), arbExpr("thenBody1", mEnd), None, spIfToThen, true, m, m)) } | LAZY declExpr %prec expr_lazy - { SynExpr.Lazy($2,unionRanges (rhs parseState 1) $2.Range) } + { SynExpr.Lazy ($2, unionRanges (rhs parseState 1) $2.Range) } | ASSERT declExpr %prec expr_assert - { SynExpr.Assert($2, unionRanges (rhs parseState 1) $2.Range) } + { SynExpr.Assert ($2, unionRanges (rhs parseState 1) $2.Range) } | ASSERT %prec expr_assert { raiseParseErrorAt (rhs parseState 1) (FSComp.SR.parsAssertIsNotFirstClassValue()) } | OLAZY declExprBlock %prec expr_lazy - { SynExpr.Lazy($2,unionRanges (rhs parseState 1) $2.Range) } + { SynExpr.Lazy ($2, unionRanges (rhs parseState 1) $2.Range) } | OASSERT declExprBlock %prec expr_assert - { SynExpr.Assert($2, unionRanges (rhs parseState 1) $2.Range) } + { SynExpr.Assert ($2, unionRanges (rhs parseState 1) $2.Range) } | OASSERT %prec expr_assert { raiseParseErrorAt (rhs parseState 1) (FSComp.SR.parsAssertIsNotFirstClassValue()) } | WHILE declExpr doToken typedSeqExprBlock doneDeclEnd { let mWhileHeader = unionRanges (rhs parseState 1) $2.Range - let spWhile = SequencePointAtWhileLoop mWhileHeader + let spWhile = DebugPointAtWhile.Yes mWhileHeader let mWhileAll = unionRanges (rhs parseState 1) $4.Range - SynExpr.While(spWhile,$2,$4,mWhileAll) } + SynExpr.While (spWhile, $2, $4, mWhileAll) } | WHILE declExpr doToken typedSeqExprBlock recover { if not $5 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedEndOfFileWhile()) let mWhileHeader = unionRanges (rhs parseState 1) $2.Range - let spWhile = SequencePointAtWhileLoop mWhileHeader + let spWhile = DebugPointAtWhile.Yes mWhileHeader let mWhileAll = unionRanges (rhs parseState 1) $4.Range - exprFromParseError (SynExpr.While(spWhile,$2,$4,mWhileAll)) } + exprFromParseError (SynExpr.While (spWhile, $2, $4, mWhileAll)) } | WHILE declExpr doToken error doneDeclEnd { // silent recovery let mWhileHeader = unionRanges (rhs parseState 1) $2.Range - let spWhile = SequencePointAtWhileLoop mWhileHeader + let spWhile = DebugPointAtWhile.Yes mWhileHeader let mWhileBodyArb = unionRanges (rhs parseState 4) (rhs parseState 5) let mWhileAll = unionRanges (rhs parseState 1) (rhs parseState 5) - SynExpr.While(spWhile,$2,arbExpr("whileBody1",mWhileBodyArb),mWhileAll) } + SynExpr.While (spWhile, $2, arbExpr("whileBody1", mWhileBodyArb), mWhileAll) } | WHILE declExpr recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsWhileDoExpected()) let mWhileHeader = unionRanges (rhs parseState 1) $2.Range - let spWhile = SequencePointAtWhileLoop mWhileHeader + let spWhile = DebugPointAtWhile.Yes mWhileHeader let mWhileBodyArb = rhs parseState 3 let mWhileAll = unionRanges (rhs parseState 1) (rhs parseState 3) - exprFromParseError (SynExpr.While(spWhile,$2,arbExpr("whileBody2",mWhileBodyArb),mWhileAll)) } + exprFromParseError (SynExpr.While (spWhile, $2, arbExpr("whileBody2", mWhileBodyArb), mWhileAll)) } | WHILE recover { if not $2 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedEndOfFileWhile()) - arbExpr("whileLoop1",rhs parseState 1) } + arbExpr("whileLoop1", rhs parseState 1) } | WHILE error doneDeclEnd { //silent recovery let mWhileHeader = rhs parseState 1 - let spWhile = SequencePointAtWhileLoop mWhileHeader + let spWhile = DebugPointAtWhile.Yes mWhileHeader let mWhileBodyArb = rhs parseState 3 let mWhileAll = unionRanges (rhs parseState 1) (rhs parseState 3) - exprFromParseError (SynExpr.While(spWhile,arbExpr("whileGuard1",mWhileHeader),arbExpr("whileBody3",mWhileBodyArb),mWhileAll)) } + exprFromParseError (SynExpr.While (spWhile, arbExpr("whileGuard1", mWhileHeader), arbExpr("whileBody3", mWhileBodyArb), mWhileAll)) } | FOR forLoopBinder doToken typedSeqExprBlock doneDeclEnd - { let spBind = SequencePointAtForLoop(rhs2 parseState 1 3) - let (a,b,_) = $2 - SynExpr.ForEach(spBind,SeqExprOnly false,true,a,b,$4,unionRanges (rhs parseState 1) $4.Range) } + { let mForLoopHeader = rhs2 parseState 1 3 + let spBind = DebugPointAtFor.Yes mForLoopHeader + let (a, b, _) = $2 + SynExpr.ForEach (spBind, SeqExprOnly false, true, a, b, $4, unionRanges (rhs parseState 1) $4.Range) } | FOR forLoopBinder doToken typedSeqExprBlock ends_coming_soon_or_recover { if not $5 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedEndOfFileFor()) - let spBind = SequencePointAtForLoop(rhs2 parseState 1 3) - let (a,b,_) = $2 + let mForLoopHeader = rhs2 parseState 1 3 + let spBind = DebugPointAtFor.Yes mForLoopHeader + let (a, b, _) = $2 let mForLoopAll = unionRanges (rhs parseState 1) $4.Range - SynExpr.ForEach(spBind,SeqExprOnly false,true,a,b,$4,mForLoopAll) } + SynExpr.ForEach (spBind, SeqExprOnly false, true, a, b, $4, mForLoopAll) } | FOR forLoopBinder doToken error doneDeclEnd { // Silent recovery let mForLoopHeader = rhs2 parseState 1 3 - let spBind = SequencePointAtForLoop mForLoopHeader - let (a,b,_) = $2 + let spBind = DebugPointAtFor.Yes mForLoopHeader + let (a, b, _) = $2 let mForLoopBodyArb = rhs parseState 5 let mForLoopAll = rhs2 parseState 1 5 - SynExpr.ForEach(spBind,SeqExprOnly false,true,a,b,arbExpr("forLoopBody2a",mForLoopBodyArb),mForLoopAll) } + SynExpr.ForEach (spBind, SeqExprOnly false, true, a, b, arbExpr("forLoopBody2a", mForLoopBodyArb), mForLoopAll) } | FOR forLoopBinder doToken ends_coming_soon_or_recover { if not $4 then reportParseErrorAt (rhs parseState 3) (FSComp.SR.parsExpectedExpressionAfterToken()) let mForLoopHeader = rhs2 parseState 1 3 - let spBind = SequencePointAtForLoop mForLoopHeader - let (a,b,_) = $2 + let spBind = DebugPointAtFor.Yes mForLoopHeader + let (a, b, _) = $2 let mForLoopBodyArb = rhs parseState 3 let mForLoopAll = rhs2 parseState 1 3 - SynExpr.ForEach(spBind,SeqExprOnly false,true,a,b,arbExpr("forLoopBody2",mForLoopBodyArb),mForLoopAll) } + SynExpr.ForEach (spBind, SeqExprOnly false, true, a, b, arbExpr("forLoopBody2", mForLoopBodyArb), mForLoopAll) } | FOR forLoopBinder ends_coming_soon_or_recover - { let (a,b,ok) = $2 + { let (a, b, ok) = $2 if not $3 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsForDoExpected()) let mForLoopHeader = rhs2 parseState 1 3 - let spBind = SequencePointAtForLoop mForLoopHeader + let spBind = DebugPointAtFor.Yes mForLoopHeader let mForLoopBodyArb = rhs parseState 3 let mForLoopAll = rhs2 parseState 1 3 - SynExpr.ForEach(spBind,SeqExprOnly false,true,a,b,arbExpr("forLoopBody1",mForLoopBodyArb),mForLoopAll) } + SynExpr.ForEach (spBind, SeqExprOnly false, true, a, b, arbExpr("forLoopBody1", mForLoopBodyArb), mForLoopAll) } | FOR forLoopRange doToken typedSeqExprBlock doneDeclEnd { let mForLoopHeader = rhs2 parseState 1 3 - let spBind = SequencePointAtForLoop mForLoopHeader - let (a,b,c,d) = $2 + let spBind = DebugPointAtFor.Yes mForLoopHeader + let (a, b, c, d) = $2 let mForLoopAll = unionRanges (rhs parseState 1) $4.Range - SynExpr.For(spBind,a,b,c,d,$4,mForLoopAll) } + SynExpr.For (spBind, a, b, c, d, $4, mForLoopAll) } | FOR forLoopRange doToken typedSeqExprBlock recover { if not $5 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedEndOfFileFor()) // Still produce an expression let mForLoopHeader = rhs2 parseState 1 3 - let spBind = SequencePointAtForLoop mForLoopHeader - let (a,b,c,d) = $2 + let spBind = DebugPointAtFor.Yes mForLoopHeader + let (a, b, c, d) = $2 let mForLoopAll = unionRanges (rhs parseState 1) $4.Range - exprFromParseError (SynExpr.For(spBind,a,b,c,d,$4,mForLoopAll)) } + exprFromParseError (SynExpr.For (spBind, a, b, c, d, $4, mForLoopAll)) } | FOR forLoopRange doToken error doneDeclEnd { // silent recovery let mForLoopHeader = rhs2 parseState 1 3 - let spBind = SequencePointAtForLoop mForLoopHeader - let (a,b,c,d) = $2 + let spBind = DebugPointAtFor.Yes mForLoopHeader + let (a, b, c, d) = $2 let mForLoopBodyArb = rhs parseState 5 let mForLoopAll = rhs2 parseState 1 5 - SynExpr.For(spBind,a,b,c,d,arbExpr("declExpr11",mForLoopBodyArb),mForLoopAll) } + SynExpr.For (spBind, a, b, c, d, arbExpr("declExpr11", mForLoopBodyArb), mForLoopAll) } | FOR forLoopRange doToken recover { if not $4 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedEndOfFileFor()) let mForLoopHeader = rhs2 parseState 1 3 - let spBind = SequencePointAtForLoop mForLoopHeader - let (a,b,c,d) = $2 + let spBind = DebugPointAtFor.Yes mForLoopHeader + let (a, b, c, d) = $2 let mForLoopBodyArb = rhs parseState 3 let mForLoopAll = rhs2 parseState 1 3 - exprFromParseError (SynExpr.For(spBind,a,b,c,d,arbExpr("declExpr11",mForLoopBodyArb),mForLoopAll)) } + exprFromParseError (SynExpr.For (spBind, a, b, c, d, arbExpr("declExpr11", mForLoopBodyArb), mForLoopAll)) } | FOR forLoopRange recover { if not $3 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedEndOfFileFor()) let mForLoopHeader = rhs2 parseState 1 2 - let spBind = SequencePointAtForLoop mForLoopHeader - let (a,b,c,d) = $2 + let spBind = DebugPointAtFor.Yes mForLoopHeader + let (a, b, c, d) = $2 let mForLoopBodyArb = (rhs parseState 2).EndRange let mForLoopAll = rhs2 parseState 1 2 - exprFromParseError (SynExpr.For(spBind,a,b,c,d,arbExpr("declExpr11",mForLoopBodyArb),mForLoopAll)) } + exprFromParseError (SynExpr.For (spBind, a, b, c, d, arbExpr("declExpr11", mForLoopBodyArb), mForLoopAll)) } | FOR error doToken typedSeqExprBlock doneDeclEnd { // silent recovery let mForLoopHeader = rhs2 parseState 1 2 let mForLoopAll = unionRanges (rhs parseState 1) $4.Range - let spBind = SequencePointAtForLoop(mForLoopHeader) - SynExpr.For(spBind,mkSynId mForLoopHeader "_loopVar",arbExpr("startLoopRange1",mForLoopHeader),true,arbExpr("endLoopRange1",rhs parseState 3),$4,mForLoopAll) } - -/* do not include this one - though for fairly bizarre reasons! - If the user has simply typed 'for'as the - start of a variable name, and intellisense parsing - kicks in, then we can't be sure we're parsing a for-loop. The general rule is that you shoudn't - commit to aggressive look-for-a-matching-construct error recovery until - you're sure you're parsing a particular construct. - - This probably affects 'and' as well, but it's hard to change that. - 'for' is a particularly common prefix of identifiers. + let spBind = DebugPointAtFor.Yes mForLoopHeader + SynExpr.For (spBind, mkSynId mForLoopHeader "_loopVar", arbExpr("startLoopRange1", mForLoopHeader), true, arbExpr("endLoopRange1", rhs parseState 3), $4, mForLoopAll) } - | FOR error doneDeclEnd { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsIdentifierExpected()); arbExpr("declExpr12",(lhs parseState)) } -*/ | FOR ends_coming_soon_or_recover { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsIdentifierExpected()) - arbExpr("declExpr12",(rhs parseState 1)) } + arbExpr("declExpr12", (rhs parseState 1)) } | FOR parenPattern error doneDeclEnd { reportParseErrorAt (rhs parseState 3) (FSComp.SR.parsInOrEqualExpected()) let mForLoopHeader = rhs2 parseState 1 2 - let spBind = SequencePointAtForLoop mForLoopHeader + let spBind = DebugPointAtFor.Yes mForLoopHeader let mForLoopBodyArb = rhs parseState 4 let mForLoopAll = rhs2 parseState 1 4 - SynExpr.ForEach(spBind,SeqExprOnly false,true,$2,arbExpr("forLoopCollection",mForLoopHeader),arbExpr("forLoopBody3",mForLoopBodyArb),mForLoopAll) } + SynExpr.ForEach (spBind, SeqExprOnly false, true, $2, arbExpr("forLoopCollection", mForLoopHeader), arbExpr("forLoopBody3", mForLoopBodyArb), mForLoopAll) } | FOR parenPattern recover { if not $3 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedEndOfFileFor()) let mForLoopHeader = rhs2 parseState 1 2 - let spBind = SequencePointAtForLoop mForLoopHeader + let spBind = DebugPointAtFor.Yes mForLoopHeader let mForLoopBodyArb = (rhs parseState 2).EndRange let mForLoopAll = rhs2 parseState 1 2 - exprFromParseError (SynExpr.ForEach(spBind,SeqExprOnly false,true,$2,arbExpr("forLoopCollection",mForLoopHeader),arbExpr("forLoopBody3",mForLoopBodyArb),mForLoopAll)) } + exprFromParseError (SynExpr.ForEach (spBind, SeqExprOnly false, true, $2, arbExpr("forLoopCollection", mForLoopHeader), arbExpr("forLoopBody3", mForLoopBodyArb), mForLoopAll)) } - /* START MONADIC SYNTAX ONLY */ | YIELD declExpr - { SynExpr.YieldOrReturn(($1,not $1),$2, unionRanges (rhs parseState 1) $2.Range) } + { SynExpr.YieldOrReturn (($1, not $1), $2, unionRanges (rhs parseState 1) $2.Range) } | YIELD_BANG declExpr - { SynExpr.YieldOrReturnFrom(($1,not $1), $2, unionRanges (rhs parseState 1) $2.Range) } + { SynExpr.YieldOrReturnFrom (($1, not $1), $2, unionRanges (rhs parseState 1) $2.Range) } + + | YIELD recover + { let mYieldAll = rhs parseState 1 + SynExpr.YieldOrReturn (($1, not $1), arbExpr("yield", mYieldAll), mYieldAll) } + + | YIELD_BANG recover + { let mYieldAll = rhs parseState 1 + SynExpr.YieldOrReturnFrom (($1, not $1), arbExpr("yield!", mYieldAll), mYieldAll) } - | BINDER headBindingPattern EQUALS typedSeqExprBlock IN opt_OBLOCKSEP typedSeqExprBlock %prec expr_let - { let spBind = SequencePointAtBinding(rhs2 parseState 1 5) - let m = unionRanges (rhs parseState 1) $7.Range - SynExpr.LetOrUseBang(spBind,($1 = "use"),true,$2,$4,$7,m) } + | BINDER headBindingPattern EQUALS typedSeqExprBlock IN opt_OBLOCKSEP moreBinders typedSeqExprBlock %prec expr_let + { let spBind = DebugPointAtBinding(rhs2 parseState 1 5) + let m = unionRanges (rhs parseState 1) $8.Range + SynExpr.LetOrUseBang(spBind, ($1 = "use"), true, $2, $4, $7, $8, m) } - | OBINDER headBindingPattern EQUALS typedSeqExprBlock hardwhiteDefnBindingsTerminator opt_OBLOCKSEP typedSeqExprBlock %prec expr_let + | OBINDER headBindingPattern EQUALS typedSeqExprBlock hardwhiteDefnBindingsTerminator opt_OBLOCKSEP moreBinders typedSeqExprBlock %prec expr_let { $5 (if $1 = "use" then "use!" else "let!") (rhs parseState 1) // report unterminated error - let spBind = SequencePointAtBinding(unionRanges (rhs parseState 1) $4.Range) - let m = unionRanges (rhs parseState 1) $7.Range - SynExpr.LetOrUseBang(spBind,($1 = "use"),true,$2,$4,$7,m) } + let spBind = DebugPointAtBinding(unionRanges (rhs parseState 1) $4.Range) + let m = unionRanges (rhs parseState 1) $8.Range + SynExpr.LetOrUseBang(spBind, ($1 = "use"), true, $2, $4, $7, $8, m) } | OBINDER headBindingPattern EQUALS typedSeqExprBlock hardwhiteDefnBindingsTerminator opt_OBLOCKSEP error %prec expr_let { // error recovery that allows intellisense when writing incomplete computation expressions - let spBind = SequencePointAtBinding(unionRanges (rhs parseState 1) $4.Range) + let spBind = DebugPointAtBinding(unionRanges (rhs parseState 1) $4.Range) let mAll = unionRanges (rhs parseState 1) (rhs parseState 7) let m = $4.Range.EndRange // zero-width range - SynExpr.LetOrUseBang(spBind,($1 = "use"),true,$2,$4, SynExpr.ImplicitZero m, mAll) } + SynExpr.LetOrUseBang(spBind, ($1 = "use"), true, $2, $4, [], SynExpr.ImplicitZero m, mAll) } | DO_BANG typedSeqExpr IN opt_OBLOCKSEP typedSeqExprBlock %prec expr_let - { let spBind = NoSequencePointAtDoBinding - SynExpr.LetOrUseBang(spBind,false,true,SynPat.Const(SynConst.Unit,$2.Range),$2,$5, unionRanges (rhs parseState 1) $5.Range) } + { let spBind = NoDebugPointAtDoBinding + SynExpr.LetOrUseBang(spBind, false, true, SynPat.Const(SynConst.Unit, $2.Range), $2, [], $5, unionRanges (rhs parseState 1) $5.Range) } | ODO_BANG typedSeqExprBlock hardwhiteDefnBindingsTerminator %prec expr_let - { SynExpr.DoBang($2, unionRanges (rhs parseState 1) $2.Range) } + { SynExpr.DoBang ($2, unionRanges (rhs parseState 1) $2.Range) } | FOR forLoopBinder opt_OBLOCKSEP arrowThenExprR %prec expr_let - { let spBind = SequencePointAtForLoop(rhs2 parseState 1 2) - let (a,b,_) = $2 in SynExpr.ForEach(spBind,SeqExprOnly true,true,a,b,$4,unionRanges (rhs parseState 1) $4.Range) } + { let spBind = DebugPointAtFor.Yes (rhs2 parseState 1 2) + let (a, b, _) = $2 in SynExpr.ForEach (spBind, SeqExprOnly true, true, a, b, $4, unionRanges (rhs parseState 1) $4.Range) } | FIXED declExpr - { SynExpr.Fixed($2, (unionRanges (rhs parseState 1) $2.Range)) } + { SynExpr.Fixed ($2, (unionRanges (rhs parseState 1) $2.Range)) } | RARROW typedSeqExprBlockR - { errorR(Error(FSComp.SR.parsArrowUseIsLimited(),lhs parseState)) - SynExpr.YieldOrReturn((true,true),$2, (unionRanges (rhs parseState 1) $2.Range)) } - - /* END MONADIC SYNTAX ONLY */ - - | declExpr COLON_QMARK typ { SynExpr.TypeTest($1,$3, unionRanges $1.Range $3.Range) } - | declExpr COLON_GREATER typ { SynExpr.Upcast($1,$3, unionRanges $1.Range $3.Range) } - | declExpr COLON_QMARK_GREATER typ { SynExpr.Downcast($1,$3, unionRanges $1.Range $3.Range) } - - /* NOTE: any change to the "INFIX" tokens (or their definitions) should be reflected in PrettyNaming.IsInfixOperator */ - | declExpr COLON_EQUALS declExpr { mkSynInfix (rhs parseState 2) $1 ":=" $3 } - | minusExpr LARROW declExprBlock { mkSynAssign $1 $3 } -/* | minusExpr LARROW recover { mkSynAssign $1 (arbExpr("assignRhs",rhs parseState 2)) } */ - | tupleExpr %prec expr_tuple { let exprs,commas = $1 in SynExpr.Tuple(false, List.rev exprs, List.rev commas, (commas.Head, exprs) ||> unionRangeWithListBy (fun e -> e.Range) ) } - | declExpr JOIN_IN declExpr { SynExpr.JoinIn($1,rhs parseState 2,$3,unionRanges $1.Range $3.Range) } - | declExpr BAR_BAR declExpr { mkSynInfix (rhs parseState 2) $1 "||" $3 } - | declExpr INFIX_BAR_OP declExpr { mkSynInfix (rhs parseState 2) $1 $2 $3 } - | declExpr OR declExpr { mkSynInfix (rhs parseState 2) $1 "or" $3 } - | declExpr AMP declExpr { mkSynInfix (rhs parseState 2) $1 "&" $3 } - | declExpr AMP_AMP declExpr { mkSynInfix (rhs parseState 2) $1 "&&" $3 } - | declExpr INFIX_AMP_OP declExpr { mkSynInfix (rhs parseState 2) $1 $2 $3 } - | declExpr EQUALS declExpr { mkSynInfix (rhs parseState 2) $1 "=" $3 } - | declExpr INFIX_COMPARE_OP declExpr { mkSynInfix (rhs parseState 2) $1 $2 $3 } - | declExpr DOLLAR declExpr { mkSynInfix (rhs parseState 2) $1 "$" $3 } - | declExpr LESS declExpr { mkSynInfix (rhs parseState 2) $1 "<" $3 } - | declExpr LESS recover { if not $3 then reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("<")) - exprFromParseError (mkSynInfix (rhs parseState 2) $1 "<" (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr GREATER declExpr { mkSynInfix (rhs parseState 2) $1 ">" $3 } - | declExpr INFIX_AT_HAT_OP declExpr { mkSynInfix (rhs parseState 2) $1 $2 $3 } - | declExpr PERCENT_OP declExpr { mkSynInfix (rhs parseState 2) $1 $2 $3 } - | declExpr COLON_COLON declExpr { SynExpr.App (ExprAtomicFlag.NonAtomic, true, mkSynIdGet (rhs parseState 2) opNameCons,SynExpr.Tuple (false,[$1;$3],[rhs parseState 2],unionRanges $1.Range $3.Range),unionRanges $1.Range $3.Range) } - | declExpr PLUS_MINUS_OP declExpr { mkSynInfix (rhs parseState 2) $1 $2 $3 } - | declExpr MINUS declExpr { mkSynInfix (rhs parseState 2) $1 "-" $3 } - | declExpr STAR declExpr { mkSynInfix (rhs parseState 2) $1 "*" $3 } - | declExpr INFIX_STAR_DIV_MOD_OP declExpr { mkSynInfix (rhs parseState 2) $1 $2 $3 } - | declExpr INFIX_STAR_STAR_OP declExpr { mkSynInfix (rhs parseState 2) $1 $2 $3 } - - | declExpr JOIN_IN OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("in")) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 "@in" (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr BAR_BAR OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("||")) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 "||" (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr INFIX_BAR_OP OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr OR OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("or")) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 "or" (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr AMP OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("&")) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 "&" (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr AMP_AMP OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("&&")) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 "&&" (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr INFIX_AMP_OP OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr EQUALS OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("=")) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 "=" (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr INFIX_COMPARE_OP OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr DOLLAR OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("$")) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 "$" (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr LESS OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("<")) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 "<" (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr GREATER OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression(">")) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 ">" (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr INFIX_AT_HAT_OP OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr PERCENT_OP OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr COLON_COLON OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("::")) - SynExpr.App (ExprAtomicFlag.NonAtomic, true, mkSynIdGet (rhs parseState 2) opNameCons,SynExpr.Tuple (false,[$1;(arbExpr("declExprInfix",(rhs parseState 3).StartRange))],[rhs parseState 2],unionRanges $1.Range (rhs parseState 3).StartRange),unionRanges $1.Range (rhs parseState 3).StartRange) } - | declExpr PLUS_MINUS_OP OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr MINUS OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("-")) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 "-" (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr STAR OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("*")) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 "*" (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr INFIX_STAR_DIV_MOD_OP OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } - | declExpr INFIX_STAR_STAR_OP OBLOCKEND_COMING_SOON { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) - exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix",(rhs parseState 3).StartRange))) } + { errorR(Error(FSComp.SR.parsArrowUseIsLimited(), lhs parseState)) + SynExpr.YieldOrReturn ((true, true), $2, (unionRanges (rhs parseState 1) $2.Range)) } + + | declExpr COLON_QMARK typ + { SynExpr.TypeTest ($1, $3, unionRanges $1.Range $3.Range) } + + | declExpr COLON_GREATER typ + { SynExpr.Upcast ($1, $3, unionRanges $1.Range $3.Range) } + + | declExpr COLON_QMARK_GREATER typ + { SynExpr.Downcast ($1, $3, unionRanges $1.Range $3.Range) } + + | declExpr COLON_EQUALS declExpr + { mkSynInfix (rhs parseState 2) $1 ":=" $3 } + + | minusExpr LARROW declExprBlock + { mkSynAssign $1 $3 } + + | tupleExpr %prec expr_tuple + { let exprs, commas = $1 + SynExpr.Tuple (false, List.rev exprs, List.rev commas, (commas.Head, exprs) ||> unionRangeWithListBy (fun e -> e.Range) ) } + + | declExpr JOIN_IN declExpr + { SynExpr.JoinIn ($1, rhs parseState 2, $3, unionRanges $1.Range $3.Range) } + + | declExpr BAR_BAR declExpr + { mkSynInfix (rhs parseState 2) $1 "||" $3 } + + | declExpr INFIX_BAR_OP declExpr + { mkSynInfix (rhs parseState 2) $1 $2 $3 } + + | declExpr OR declExpr + { mkSynInfix (rhs parseState 2) $1 "or" $3 } + + | declExpr AMP declExpr + { mkSynInfix (rhs parseState 2) $1 "&" $3 } + + | declExpr AMP_AMP declExpr + { mkSynInfix (rhs parseState 2) $1 "&&" $3 } + + | declExpr INFIX_AMP_OP declExpr + { mkSynInfix (rhs parseState 2) $1 $2 $3 } + + | declExpr EQUALS declExpr + { mkSynInfix (rhs parseState 2) $1 "=" $3 } + + | declExpr INFIX_COMPARE_OP declExpr + { mkSynInfix (rhs parseState 2) $1 $2 $3 } + + | declExpr DOLLAR declExpr + { mkSynInfix (rhs parseState 2) $1 "$" $3 } + + | declExpr LESS declExpr + { mkSynInfix (rhs parseState 2) $1 "<" $3 } + + | declExpr LESS recover + { if not $3 then reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("<")) + exprFromParseError (mkSynInfix (rhs parseState 2) $1 "<" (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr GREATER declExpr + { mkSynInfix (rhs parseState 2) $1 ">" $3 } + + | declExpr INFIX_AT_HAT_OP declExpr + { mkSynInfix (rhs parseState 2) $1 $2 $3 } + + | declExpr PERCENT_OP declExpr + { mkSynInfix (rhs parseState 2) $1 $2 $3 } + + | declExpr COLON_COLON declExpr + { let tupExpr = SynExpr.Tuple (false, [$1;$3], [rhs parseState 2], unionRanges $1.Range $3.Range) + SynExpr.App (ExprAtomicFlag.NonAtomic, true, mkSynIdGet (rhs parseState 2) opNameCons, tupExpr, unionRanges $1.Range $3.Range) } + + | declExpr PLUS_MINUS_OP declExpr + { mkSynInfix (rhs parseState 2) $1 $2 $3 } + + | declExpr MINUS declExpr + { mkSynInfix (rhs parseState 2) $1 "-" $3 } + + | declExpr STAR declExpr + { mkSynInfix (rhs parseState 2) $1 "*" $3 } + + | declExpr INFIX_STAR_DIV_MOD_OP declExpr + { mkSynInfix (rhs parseState 2) $1 $2 $3 } + + | declExpr INFIX_STAR_STAR_OP declExpr + { mkSynInfix (rhs parseState 2) $1 $2 $3 } + + | declExpr JOIN_IN OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("in")) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 "@in" (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr BAR_BAR OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("||")) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 "||" (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr INFIX_BAR_OP OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr OR OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("or")) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 "or" (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr AMP OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("&")) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 "&" (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr AMP_AMP OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("&&")) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 "&&" (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr INFIX_AMP_OP OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr EQUALS OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("=")) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 "=" (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr INFIX_COMPARE_OP OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr DOLLAR OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("$")) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 "$" (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr LESS OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("<")) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 "<" (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr GREATER OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression(">")) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 ">" (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr INFIX_AT_HAT_OP OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr PERCENT_OP OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr COLON_COLON OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("::")) + let tupExpr = SynExpr.Tuple (false, [$1;(arbExpr("declExprInfix", (rhs parseState 3).StartRange))], [rhs parseState 2], unionRanges $1.Range (rhs parseState 3).StartRange) + SynExpr.App (ExprAtomicFlag.NonAtomic, true, mkSynIdGet (rhs parseState 2) opNameCons, tupExpr, unionRanges $1.Range (rhs parseState 3).StartRange) } + + | declExpr PLUS_MINUS_OP OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr MINUS OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("-")) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 "-" (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr STAR OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression("*")) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 "*" (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr INFIX_STAR_DIV_MOD_OP OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } + + | declExpr INFIX_STAR_STAR_OP OBLOCKEND_COMING_SOON + { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnfinishedExpression($2)) + exprFromParseError(mkSynInfix (rhs parseState 2) $1 $2 (arbExpr("declExprInfix", (rhs parseState 3).StartRange))) } | minusExpr %prec expr_prefix_plus_minus { $1 } dynamicArg: | IDENT - { let con = SynConst.String ($1,rhs parseState 1) - let arg2 = SynExpr.Const (con,con.Range (rhs parseState 1)) + { let con = SynConst.String ($1, rhs parseState 1) + let arg2 = SynExpr.Const (con, con.Range (rhs parseState 1)) arg2 } + | LPAREN typedSeqExpr rparen { $2 } withClauses: | WITH withPatternClauses { rhs parseState 1, $2 } + | OWITH withPatternClauses OEND { rhs parseState 1, $2 } + | OWITH withPatternClauses recover { if not $3 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedEndOfFileWith()) rhs parseState 1, $2 } @@ -3442,16 +3787,19 @@ withClauses: withPatternClauses: | patternClauses { $1 } + | BAR patternClauses - { $2 } + { $2 } + | BAR error - { // silent recovery - let mLast = rhs parseState 1 - [], mLast } + { // silent recovery + let mLast = rhs parseState 1 + [], mLast } + | error - { // silent recovery - let mLast = rhs parseState 1 - [], mLast } + { // silent recovery + let mLast = rhs parseState 1 + [], mLast } patternAndGuard: @@ -3460,33 +3808,38 @@ patternAndGuard: patternClauses: | patternAndGuard patternResult %prec prec_pat_pat_action - { let pat,guard,patm = $1 + { let pat, guard, patm = $1 let mLast = $2.Range - [Clause(pat,guard,$2,patm,SequencePointAtTarget)], mLast } + [Clause(pat, guard, $2, patm, DebugPointForTarget.Yes)], mLast } + | patternAndGuard patternResult BAR patternClauses - { let pat,guard,patm = $1 - let clauses,mLast = $4 - (Clause(pat,guard,$2,patm,SequencePointAtTarget) :: clauses), mLast } + { let pat, guard, patm = $1 + let clauses, mLast = $4 + (Clause(pat, guard, $2, patm, DebugPointForTarget.Yes) :: clauses), mLast } + | patternAndGuard patternResult BAR error - { let pat,guard,patm = $1 + { let pat, guard, patm = $1 let mLast = rhs parseState 3 // silent recovery - [Clause(pat,guard,$2,patm,SequencePointAtTarget)], mLast } + [Clause(pat, guard, $2, patm, DebugPointForTarget.Yes)], mLast } + | patternAndGuard patternResult error - { let pat,guard,patm = $1 + { let pat, guard, patm = $1 let mLast = $2.Range // silent recovery - [Clause(pat,guard,$2,patm,SequencePointAtTarget)], mLast } + [Clause(pat, guard, $2, patm, DebugPointForTarget.Yes)], mLast } + | patternAndGuard error - { let pat,guard,patm = $1 + { let pat, guard, patm = $1 let mLast = rhs parseState 2 // silent recovery - [Clause(pat,guard,SynExpr.Const(SynConst.Unit,mLast.EndRange),patm,SequencePointAtTarget)], mLast } + [Clause(pat, guard, SynExpr.Const (SynConst.Unit, mLast.EndRange), patm, DebugPointForTarget.Yes)], mLast } patternGuard: | WHEN declExpr { Some $2 } - | + + | /* EMPTY */ { None } patternResult: @@ -3495,25 +3848,27 @@ patternResult: ifExprCases: | ifExprThen ifExprElifs - { let exprThen,mThen = $1 + { let exprThen, mThen = $1 (fun exprGuard mIf -> let mIfToThen = unionRanges mIf mThen let lastBranch : SynExpr = match $2 with None -> exprThen | Some e -> e let mIfToEndOfLastBranch = unionRanges mIf lastBranch.Range - let spIfToThen = SequencePointAtBinding(mIfToThen) - SynExpr.IfThenElse(exprGuard,exprThen,$2,spIfToThen,false,mIfToThen,mIfToEndOfLastBranch)) } + let spIfToThen = DebugPointAtBinding(mIfToThen) + SynExpr.IfThenElse (exprGuard, exprThen, $2, spIfToThen, false, mIfToThen, mIfToEndOfLastBranch)) } ifExprThen: | THEN declExpr %prec prec_then_if { $2, rhs parseState 1 } + | OTHEN OBLOCKBEGIN typedSeqExpr oblockend %prec prec_then_if - { $3,rhs parseState 1 } + { $3, rhs parseState 1 } + | OTHEN OBLOCKBEGIN typedSeqExpr recover %prec prec_then_if { if not $4 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedEndOfFileThen()) - exprFromParseError $3,rhs parseState 1 } + exprFromParseError $3, rhs parseState 1 } ifExprElifs: - | + | /* EMPTY */ { None } | ELSE declExpr @@ -3535,18 +3890,18 @@ ifExprElifs: tupleExpr: | tupleExpr COMMA declExpr - { let exprs,commas = $1 in ($3 :: exprs),((rhs parseState 2)::commas) } + { let exprs, commas = $1 in ($3 :: exprs), ((rhs parseState 2) :: commas) } | tupleExpr COMMA ends_coming_soon_or_recover { if not $3 then reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsExpectedExpressionAfterToken()) - let exprs,commas = $1 + let exprs, commas = $1 let zeroWidthAtNextToken = (rhs parseState 3).StartRange - ((arbExpr("tupleExpr1",zeroWidthAtNextToken)) :: exprs), (rhs parseState 2)::commas } + ((arbExpr("tupleExpr1", zeroWidthAtNextToken)) :: exprs), (rhs parseState 2) :: commas } | declExpr COMMA ends_coming_soon_or_recover { if not $3 then reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsExpectedExpressionAfterToken()) let zeroWidthAtNextToken = (rhs parseState 3).StartRange - ((arbExpr("tupleExpr2",zeroWidthAtNextToken)) :: [$1]), [rhs parseState 2] } + ((arbExpr("tupleExpr2", zeroWidthAtNextToken)) :: [$1]), [rhs parseState 2] } | declExpr COMMA declExpr { [$3 ; $1], [rhs parseState 2] } @@ -3568,94 +3923,94 @@ minusExpr: mkSynPrefix (rhs parseState 1) (unionRanges (rhs parseState 1) $2.Range) ("~"+($1)) $2 } | AMP minusExpr - { SynExpr.AddressOf(true,$2,rhs parseState 1,unionRanges (rhs parseState 1) $2.Range) } + { SynExpr.AddressOf (true, $2, rhs parseState 1, unionRanges (rhs parseState 1) $2.Range) } | AMP_AMP minusExpr - { SynExpr.AddressOf(false,$2,rhs parseState 1, unionRanges (rhs parseState 1) $2.Range) } + { SynExpr.AddressOf (false, $2, rhs parseState 1, unionRanges (rhs parseState 1) $2.Range) } | NEW atomTypeNonAtomicDeprecated opt_HIGH_PRECEDENCE_APP atomicExprAfterType - { SynExpr.New(false,$2,$4,unionRanges (rhs parseState 1) $4.Range) } + { SynExpr.New (false, $2, $4, unionRanges (rhs parseState 1) $4.Range) } | NEW atomTypeNonAtomicDeprecated opt_HIGH_PRECEDENCE_APP error - { SynExpr.New(false,$2,arbExpr("minusExpr",(rhs parseState 4)),unionRanges (rhs parseState 1) ($2).Range) } + { SynExpr.New (false, $2, arbExpr("minusExpr", (rhs parseState 4)), unionRanges (rhs parseState 1) ($2).Range) } | NEW error - { arbExpr("minusExpr2",(rhs parseState 1)) } + { arbExpr("minusExpr2", (rhs parseState 1)) } | UPCAST minusExpr - { SynExpr.InferredUpcast($2,unionRanges (rhs parseState 1) $2.Range) } + { SynExpr.InferredUpcast ($2, unionRanges (rhs parseState 1) $2.Range) } | DOWNCAST minusExpr - { SynExpr.InferredDowncast($2,unionRanges (rhs parseState 1) $2.Range)} + { SynExpr.InferredDowncast ($2, unionRanges (rhs parseState 1) $2.Range)} | appExpr { $1 } appExpr: | appExpr argExpr %prec expr_app - { SynExpr.App (ExprAtomicFlag.NonAtomic, false, $1,$2,unionRanges $1.Range $2.Range) } + { SynExpr.App (ExprAtomicFlag.NonAtomic, false, $1, $2, unionRanges $1.Range $2.Range) } | atomicExpr - { let arg,_ = $1 + { let arg, _ = $1 arg } argExpr: | ADJACENT_PREFIX_OP atomicExpr - { let arg2,hpa2 = $2 + { let arg2, hpa2 = $2 if not (IsValidPrefixOperatorUse $1) then reportParseErrorAt arg2.Range (FSComp.SR.parsInvalidPrefixOperator()) if hpa2 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsSuccessiveArgsShouldBeSpacedOrTupled()) mkSynPrefix (rhs parseState 1) (unionRanges (rhs parseState 1) arg2.Range) ("~"+($1)) arg2 } | atomicExpr - { let arg,hpa = $1 + { let arg, hpa = $1 if hpa then reportParseErrorAt arg.Range (FSComp.SR.parsSuccessiveArgsShouldBeSpacedOrTupled()) arg } atomicExpr: | atomicExpr HIGH_PRECEDENCE_BRACK_APP atomicExpr - { let arg1,_ = $1 - let arg2,_ = $3 - SynExpr.App (ExprAtomicFlag.Atomic, false, arg1,arg2,unionRanges arg1.Range arg2.Range),true } + { let arg1, _ = $1 + let arg2, _ = $3 + SynExpr.App (ExprAtomicFlag.Atomic, false, arg1, arg2, unionRanges arg1.Range arg2.Range), true } | atomicExpr HIGH_PRECEDENCE_PAREN_APP atomicExpr - { let arg1,_ = $1 - let arg2,_ = $3 - SynExpr.App (ExprAtomicFlag.Atomic, false, arg1,arg2,unionRanges arg1.Range arg2.Range),true } + { let arg1, _ = $1 + let arg2, _ = $3 + SynExpr.App (ExprAtomicFlag.Atomic, false, arg1, arg2, unionRanges arg1.Range arg2.Range), true } | atomicExpr HIGH_PRECEDENCE_TYAPP typeArgsActual - { let arg1,_ = $1 - let mLessThan,mGreaterThan,_,args,commas,mTypeArgs = $3 + { let arg1, _ = $1 + let mLessThan, mGreaterThan, _, args, commas, mTypeArgs = $3 let mWholeExpr = unionRanges arg1.Range mTypeArgs - SynExpr.TypeApp(arg1, mLessThan, args, commas, mGreaterThan, mTypeArgs, mWholeExpr), false } + SynExpr.TypeApp (arg1, mLessThan, args, commas, mGreaterThan, mTypeArgs, mWholeExpr), false } - | PREFIX_OP atomicExpr - { let arg2,hpa2 = $2 + | PREFIX_OP atomicExpr + { let arg2, hpa2 = $2 if not (IsValidPrefixOperatorUse $1) then reportParseErrorAt arg2.Range (FSComp.SR.parsInvalidPrefixOperator()) - mkSynPrefixPrim (rhs parseState 1) (unionRanges (rhs parseState 1) arg2.Range) $1 arg2,hpa2 } + mkSynPrefixPrim (rhs parseState 1) (unionRanges (rhs parseState 1) arg2.Range) $1 arg2, hpa2 } | atomicExpr DOT atomicExprQualification - { let arg1,hpa1 = $1 - $3 arg1 (lhs parseState) (rhs parseState 2),hpa1 } + { let arg1, hpa1 = $1 + $3 arg1 (lhs parseState) (rhs parseState 2), hpa1 } | BASE DOT atomicExprQualification - { let arg1 = SynExpr.Ident(ident("base",rhs parseState 1)) - $3 arg1 (lhs parseState) (rhs parseState 2),false } + { let arg1 = SynExpr.Ident (ident("base", rhs parseState 1)) + $3 arg1 (lhs parseState) (rhs parseState 2), false } | QMARK nameop - { SynExpr.LongIdent (true,LongIdentWithDots([$2],[]),None,rhs parseState 2),false } + { SynExpr.LongIdent (true, LongIdentWithDots([$2], []), None, rhs parseState 2), false } | atomicExpr QMARK dynamicArg - { let arg1,hpa1 = $1 + { let arg1, hpa1 = $1 mkSynInfix (rhs parseState 2) arg1 "?" $3, hpa1 } | GLOBAL - { SynExpr.Ident (ident(MangledGlobalName,rhs parseState 1)), false } + { SynExpr.Ident (ident(MangledGlobalName, rhs parseState 1)), false } | nameop - { SynExpr.Ident ($1),false } + { SynExpr.Ident ($1), false } | LBRACK listExprElements RBRACK - { $2 (lhs parseState) false,false } + { $2 (lhs parseState) false, false } | LBRACK listExprElements recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedBracket()) @@ -3663,25 +4018,25 @@ atomicExpr: | LBRACK error RBRACK { // silent recovery - SynExpr.ArrayOrList(false,[ ], lhs parseState),false } + SynExpr.ArrayOrList (false, [ ], lhs parseState), false } | LBRACK recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedBracket()) // silent recovery - exprFromParseError (SynExpr.ArrayOrList(false,[ ], rhs parseState 1)),false } + exprFromParseError (SynExpr.ArrayOrList (false, [ ], rhs parseState 1)), false } | STRUCT LPAREN tupleExpr rparen - { let exprs,commas = $3 in SynExpr.Tuple(true, List.rev exprs, List.rev commas, (commas.Head, exprs) ||> unionRangeWithListBy (fun e -> e.Range) ), false } + { let exprs, commas = $3 in SynExpr.Tuple (true, List.rev exprs, List.rev commas, (commas.Head, exprs) ||> unionRangeWithListBy (fun e -> e.Range) ), false } | STRUCT LPAREN tupleExpr recover { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnmatchedBracket()); - let exprs,commas = $3 in SynExpr.Tuple(true, List.rev exprs, List.rev commas, (commas.Head, exprs) ||> unionRangeWithListBy (fun e -> e.Range) ), false } + let exprs, commas = $3 in SynExpr.Tuple (true, List.rev exprs, List.rev commas, (commas.Head, exprs) ||> unionRangeWithListBy (fun e -> e.Range) ), false } | atomicExprAfterType - { $1,false } + { $1, false } atomicExprQualification: - | identOrOp + | identOrOp { let idm = rhs parseState 1 (fun e lhsm dotm -> mkSynDot dotm lhsm e $1) } @@ -3691,102 +4046,144 @@ atomicExprQualification: let fixedLhsm = mkRange lhsm.FileName lhsm.Start dotm.End // previous lhsm is wrong after 'recover' mkSynDotMissing dotm fixedLhsm e) } - | /* empty */ + | /* empty */ { (fun e lhsm dotm -> reportParseErrorAt dotm (FSComp.SR.parsMissingQualificationAfterDot()) let fixedLhsm = mkRange lhsm.FileName lhsm.Start dotm.End // previous lhsm is wrong after 'recover' mkSynDotMissing dotm fixedLhsm e) } - | recover + | recover { (fun e lhsm dotm -> reportParseErrorAt dotm (FSComp.SR.parsMissingQualificationAfterDot()) let fixedLhsm = mkRange lhsm.FileName lhsm.Start dotm.End // previous lhsm is wrong after 'recover' // Include 'e' in the returned expression but throw it away - SynExpr.DiscardAfterMissingQualificationAfterDot(e,fixedLhsm)) } - | LPAREN COLON_COLON rparen DOT INT32 + SynExpr.DiscardAfterMissingQualificationAfterDot (e, fixedLhsm)) } + | LPAREN COLON_COLON rparen DOT INT32 { (fun e lhsm dotm -> libraryOnlyError(lhs parseState) - SynExpr.LibraryOnlyUnionCaseFieldGet (e,mkSynCaseName lhsm opNameCons,(fst $5),lhsm)) } + SynExpr.LibraryOnlyUnionCaseFieldGet (e, mkSynCaseName lhsm opNameCons, (fst $5), lhsm)) } - | LPAREN typedSeqExpr rparen + | LPAREN typedSeqExpr rparen { (fun e lhsm dotm -> mlCompatWarning (FSComp.SR.parsParenFormIsForML()) (lhs parseState) mkSynDotParenGet lhsm dotm e $2) } - | LBRACK typedSeqExpr RBRACK - { (fun e lhsm dotm -> mkSynDotBrackGet lhsm dotm e $2) } - - | LBRACK typedSeqExpr recover + | LBRACK typedSeqExpr recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedBracket()) - (fun e lhsm dotm -> exprFromParseError (mkSynDotBrackGet lhsm dotm e $2)) } + (fun e lhsm dotm -> exprFromParseError (mkSynDotBrackGet lhsm dotm e $2 false)) } - | LBRACK optRangeSeqExpr RBRACK + | LBRACK optRangeSeqExpr RBRACK { (fun e lhsm dotm -> mkSynDotBrackSeqSliceGet lhsm dotm e $2) } - | LBRACK optRangeSeqExpr recover + | LBRACK optRangeSeqExpr recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedBracket()) (fun e lhsm dotm -> exprFromParseError (mkSynDotBrackSeqSliceGet lhsm dotm e $2)) } - | LBRACK error RBRACK + | LBRACK error RBRACK { let mArg = rhs2 parseState 1 3 - (fun e lhsm dotm -> mkSynDotBrackGet lhsm dotm e (arbExpr("indexerExpr1",mArg))) } + (fun e lhsm dotm -> mkSynDotBrackGet lhsm dotm e (arbExpr("indexerExpr1", mArg)) false) } - | LBRACK recover + | LBRACK recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedBracket()) let mArg = (rhs parseState 1).EndRange - (fun e lhsm dotm -> exprFromParseError (mkSynDotBrackGet lhsm dotm e (arbExpr("indexerExpr2",mArg)))) } + (fun e lhsm dotm -> exprFromParseError (mkSynDotBrackGet lhsm dotm e (arbExpr("indexerExpr2", mArg)) false)) } optRangeSeqExpr: - | optRange COMMA optRangeSeqExpr %prec slice_comma { $1::$3 } - | optRange { [$1] } - -optRange: - | declExpr DOT_DOT declExpr - { SynIndexerArg.Two(mkSynOptionalExpr (rhs parseState 1) (Some $1), mkSynOptionalExpr (rhs parseState 3) (Some $3)) } - | declExpr DOT_DOT - { SynIndexerArg.Two(mkSynOptionalExpr (rhs parseState 1) (Some $1), mkSynOptionalExpr (rhs parseState 2) None) } + | optRange COMMA optRangeSeqExpr %prec slice_comma { $1 :: $3 } - | DOT_DOT declExpr - { SynIndexerArg.Two(mkSynOptionalExpr (rhs parseState 1) None, mkSynOptionalExpr (rhs parseState 2) (Some $2)) } + | optRange { [$1] } +optRange: + | rangeDeclExpr DOT_DOT rangeDeclExpr + { SynIndexerArg.Two( + mkSynOptionalExpr (rhs parseState 1) (Some (fst $1)), + (snd $1), + mkSynOptionalExpr (rhs parseState 3) (Some (fst $3)), + (snd $3), + (rhs parseState 1), + (rhs parseState 3)) } + + | rangeDeclExpr DOT_DOT + { SynIndexerArg.Two( + mkSynOptionalExpr (rhs parseState 1) (Some (fst $1)), + (snd $1), + mkSynOptionalExpr (rhs parseState 2) None, + false, + (rhs parseState 1), + (rhs parseState 2)) } + + | DOT_DOT rangeDeclExpr + { SynIndexerArg.Two( + mkSynOptionalExpr (rhs parseState 1) None, + false, + mkSynOptionalExpr (rhs parseState 2) (Some (fst $2)), + (snd $2), + (rhs parseState 2), + (rhs parseState 1)) } + | STAR - { SynIndexerArg.Two(mkSynOptionalExpr (rhs parseState 1) None, mkSynOptionalExpr (rhs parseState 1) None) } - + { SynIndexerArg.Two( + mkSynOptionalExpr (rhs parseState 1) None, + false, + (mkSynOptionalExpr (rhs parseState 1) None), + false, + (rhs parseState 1), + (rhs parseState 1)) } + + | rangeDeclExpr + { SynIndexerArg.One((fst $1), (snd $1), (rhs parseState 1)) } + +rangeDeclExpr: | declExpr %prec slice_expr - { SynIndexerArg.One($1) } + { $1, false } + + | INFIX_AT_HAT_OP declExpr %prec slice_expr + { if not (parseState.LexBuffer.SupportsFeature LanguageFeature.FromEndSlicing) then + raiseParseErrorAt (rhs parseState 1) (FSComp.SR.fromEndSlicingRequiresVFive()) + if $1 <> "^" then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsInvalidPrefixOperator()) + $2, true } /* the start et of atomicExprAfterType must not overlap with the valid postfix tokens of the type syntax, e.g. new List(...) */ atomicExprAfterType: | constant - { SynExpr.Const ($1,$1.Range (lhs parseState)) } + { SynExpr.Const ($1, $1.Range (lhs parseState)) } + | parenExpr { $1 } + | braceExpr { $1 } + | braceBarExpr { $1 } + | NULL - { SynExpr.Null(lhs parseState) } + { SynExpr.Null (lhs parseState) } + | FALSE - { SynExpr.Const(SynConst.Bool false,lhs parseState) } + { SynExpr.Const (SynConst.Bool false, lhs parseState) } + | TRUE - { SynExpr.Const(SynConst.Bool true,lhs parseState) } + { SynExpr.Const (SynConst.Bool true, lhs parseState) } + | quoteExpr { $1 } + | arrayExpr { $1 } + | beginEndExpr { $1 } beginEndExpr: | BEGIN typedSeqExpr END - { SynExpr.Paren($2, rhs parseState 1, Some(rhs parseState 3), rhs2 parseState 1 3) } + { SynExpr.Paren ($2, rhs parseState 1, Some(rhs parseState 3), rhs2 parseState 1 3) } | BEGIN typedSeqExpr recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedBegin()); exprFromParseError $2 } | BEGIN error END - { (* silent recovery *) arbExpr("beginEndExpr",(lhs parseState)) } + { (* silent recovery *) arbExpr("beginEndExpr", (lhs parseState)) } | BEGIN END { mkSynUnit (lhs parseState) } @@ -3794,19 +4191,19 @@ beginEndExpr: quoteExpr: | LQUOTE typedSeqExpr RQUOTE { if $1 <> $3 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsMismatchedQuote(fst $1)) - (SynExpr.Quote(mkSynIdGet (lhs parseState) (CompileOpName (fst $1)), snd $1, $2, false, lhs parseState)) } + (SynExpr.Quote (mkSynIdGet (lhs parseState) (CompileOpName (fst $1)), snd $1, $2, false, lhs parseState)) } | LQUOTE typedSeqExpr recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatched(fst $1)) let mExpr = rhs2 parseState 1 2 - exprFromParseError (SynExpr.Quote(mkSynIdGet (lhs parseState) (CompileOpName (fst $1)),snd $1, $2, false, mExpr)) } + exprFromParseError (SynExpr.Quote (mkSynIdGet (lhs parseState) (CompileOpName (fst $1)), snd $1, $2, false, mExpr)) } | LQUOTE error RQUOTE - { (* silent recovery *) SynExpr.Quote(mkSynIdGet (lhs parseState) (CompileOpName (fst $1)),snd $1, arbExpr("quoteExpr",(rhs parseState 2)), false, lhs parseState) } + { (* silent recovery *) SynExpr.Quote (mkSynIdGet (lhs parseState) (CompileOpName (fst $1)), snd $1, arbExpr("quoteExpr", (rhs parseState 2)), false, lhs parseState) } | LQUOTE recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatched(fst $1)) - exprFromParseError (SynExpr.Quote(mkSynIdGet (lhs parseState) (CompileOpName (fst $1)),snd $1, arbExpr("quoteExpr2",(rhs parseState 1).EndRange), false, rhs parseState 1)) } + exprFromParseError (SynExpr.Quote (mkSynIdGet (lhs parseState) (CompileOpName (fst $1)), snd $1, arbExpr("quoteExpr2", (rhs parseState 1).EndRange), false, rhs parseState 1)) } arrayExpr: | LBRACK_BAR listExprElements BAR_RBRACK @@ -3817,29 +4214,29 @@ arrayExpr: exprFromParseError ($2 (rhs2 parseState 1 2) true) } | LBRACK_BAR error BAR_RBRACK - { (* silent recovery *) SynExpr.ArrayOrList(true,[ ], lhs parseState) } + { (* silent recovery *) SynExpr.ArrayOrList (true, [ ], lhs parseState) } | LBRACK_BAR recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedBracketBar()) (* silent recovery *) - exprFromParseError (SynExpr.ArrayOrList(true,[ ], rhs parseState 1)) } + exprFromParseError (SynExpr.ArrayOrList (true, [ ], rhs parseState 1)) } parenExpr: | LPAREN rparen - { SynExpr.Const(SynConst.Unit,(rhs2 parseState 1 2)) } + { SynExpr.Const (SynConst.Unit, (rhs2 parseState 1 2)) } | LPAREN parenExprBody rparen { let m = rhs2 parseState 1 3 - SynExpr.Paren($2 m, rhs parseState 1, Some(rhs parseState 3), m) } + SynExpr.Paren ($2 m, rhs parseState 1, Some(rhs parseState 3), m) } | LPAREN parenExprBody ends_other_than_rparen_coming_soon_or_recover { if not $3 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedParen()) - let lhsm = unionRangeWithPos (rhs parseState 1) (rhs parseState 3).Start - SynExpr.Paren(exprFromParseError ($2 lhsm), rhs parseState 1, None, lhsm) } + let lhsm = unionRangeWithPos (rhs parseState 1) (rhs parseState 2).End + SynExpr.Paren (exprFromParseError ($2 lhsm), rhs parseState 1, None, lhsm) } | LPAREN error rparen { // silent recovery - SynExpr.Paren(arbExpr("parenExpr1",(rhs parseState 1).EndRange),(rhs parseState 1),Some(rhs parseState 3),(rhs2 parseState 1 3)) } + SynExpr.Paren (arbExpr("parenExpr1", (rhs parseState 1).EndRange), (rhs parseState 1), Some(rhs parseState 3), (rhs2 parseState 1 3)) } | LPAREN TYPE_COMING_SOON { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedParen()) @@ -3857,26 +4254,28 @@ parenExpr: arbExpr("parenExpr2rbcs", lhsm) } | LPAREN OBLOCKEND_COMING_SOON - { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedParen()) - let lhsm = unionRangeWithPos (rhs parseState 1) (rhs parseState 2).Start - arbExpr("parenExpr2obecs", lhsm) } + { let lparenRange = (rhs parseState 1) + reportParseErrorAt lparenRange (FSComp.SR.parsUnmatchedParen()) + SynExpr.Paren(arbExpr("parenExpr2obecs", lparenRange.EndRange), lparenRange, None, lparenRange) } | LPAREN recover %prec prec_atomexpr_lparen_error { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedParen()) - arbExpr("parenExpr2",(lhs parseState)) } + arbExpr("parenExpr2", (lhs parseState)) } // This is really what we should be doing, but it fails because param info expects the range of the expression // to extend all the way over the "recover", to the end of the file if necessary // // let mLeftParen = rhs parseState 1 //let lhsm = if $2 then unionRangeWithPos mLeftParen (rhs parseState 2).Start else mLeftParen - //arbExpr("parenExpr2",lhsm) } + //arbExpr("parenExpr2", lhsm) } parenExprBody: | staticallyKnownHeadTypars COLON LPAREN classMemberSpfn rparen typedSeqExpr - { (fun m -> SynExpr.TraitCall($1,$4,$6,m)) } /* disambiguate: x $a.id(x) */ + { (fun m -> SynExpr.TraitCall ($1, $4, $6, m)) } /* disambiguate: x $a.id(x) */ + | typedSeqExpr { (fun _m -> $1) } + | inlineAssemblyExpr { $1 } @@ -3896,46 +4295,47 @@ staticallyKnownHeadTyparAlts: braceExpr: | LBRACE braceExprBody rbrace - { let m,r = $2 in r (rhs2 parseState 1 3) } + { let m, r = $2 in r (rhs2 parseState 1 3) } | LBRACE braceExprBody recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedBrace()) - let m,r = $2 + let m, r = $2 // Note, we can't use 'exprFromParseError' because the extra syntax node interferes with some syntax-directed transformations for computation expressions r (unionRanges (rhs parseState 1) m) } | LBRACE error rbrace { // silent recovery - arbExpr("braceExpr",rhs2 parseState 1 3) } + arbExpr("braceExpr", rhs2 parseState 1 3) } | LBRACE recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedBrace()) // Note, we can't use 'exprFromParseError' because the extra syntax node interferes with some syntax-directed transformations for computation expressions - SynExpr.Record(None,None,[],rhs parseState 1) } + SynExpr.Record (None, None, [], rhs parseState 1) } | LBRACE rbrace { let m = rhs2 parseState 1 2 - SynExpr.Record(None,None,[],m) } + SynExpr.Record (None, None, [], m) } braceExprBody: | recdExpr - { (lhs parseState), (fun m -> let a,b,c = $1 in SynExpr.Record(a,b,c,m)) } + { (lhs parseState), (fun m -> let a, b, c = $1 in SynExpr.Record (a, b, c, m)) } | objExpr { $1 } | monadicExprInitial - { let m,r = $1 in (m, r false) } + { let m, r = $1 in (m, r false) } listExprElements: | monadicExprInitial - { let m,r = $1 in (fun lhsm isArray -> SynExpr.ArrayOrListOfSeqExpr(isArray, r true m, lhsm)) } + { let m, r = $1 in (fun lhsm isArray -> SynExpr.ArrayOrListOfSeqExpr (isArray, r true m, lhsm)) } + | - { (fun lhsm isArray -> SynExpr.ArrayOrList(isArray,[ ], lhsm)) } + { (fun lhsm isArray -> SynExpr.ArrayOrList (isArray, [ ], lhsm)) } monadicExprInitial: | seqExpr - { $1.Range, (fun isArrayOrList lhsm -> SynExpr.CompExpr(isArrayOrList,ref(isArrayOrList),$1,lhsm)) } + { $1.Range, (fun isArrayOrList lhsm -> SynExpr.CompExpr (isArrayOrList, ref(isArrayOrList), $1, lhsm)) } | rangeSequenceExpr { $1 } @@ -3943,30 +4343,31 @@ monadicExprInitial: rangeSequenceExpr: | declExpr DOT_DOT declExpr { let opm = (rhs parseState 2) - (unionRanges $1.Range $3.Range),(fun _isArray wholem -> + (unionRanges $1.Range $3.Range), (fun _isArray wholem -> // in the case of "{ 1 .. 10 }", we want the range of the expression to include the curlies, that comes from a higher level rule in the grammar, // passed down as 'wholem', so patch up that range here match (mkSynInfix opm $1 ".." $3) with - | SynExpr.App(a,b,c,d,_) -> SynExpr.App(a,b,c,d,wholem) + | SynExpr.App (a, b, c, d, _) -> SynExpr.App (a, b, c, d, wholem) | _ -> failwith "impossible") } + | declExpr DOT_DOT declExpr DOT_DOT declExpr - { (unionRanges $1.Range $5.Range),(fun _isArray wholem -> mkSynTrifix wholem ".. .." $1 $3 $5) } + { (unionRanges $1.Range $5.Range), (fun _isArray wholem -> mkSynTrifix wholem ".. .." $1 $3 $5) } | declExpr DOT_DOT recover { if not $3 then reportParseErrorAt (rhs parseState 3) (FSComp.SR.parsUnexpectedEndOfFileExpression()) let opm = (rhs parseState 2) let e = arbExpr("rangeSeqError1", (rhs parseState 3).StartRange) - (unionRanges $1.Range e.Range),(fun _isArray wholem -> + (unionRanges $1.Range e.Range), (fun _isArray wholem -> // in the case of "{ 1 .. 10 }", we want the range of the expression to include the curlies, that comes from a higher level rule in the grammar, // passed down as 'wholem', so patch up that range here match (mkSynInfix opm $1 ".." e) with - | SynExpr.App(a,b,c,d,_) -> SynExpr.App(a,b,c,d,wholem) + | SynExpr.App (a, b, c, d, _) -> SynExpr.App (a, b, c, d, wholem) | _ -> failwith "impossible") } arrowThenExprR: | RARROW typedSeqExprBlockR - { SynExpr.YieldOrReturn((true,false), $2, unionRanges (rhs parseState 1) $2.Range) } + { SynExpr.YieldOrReturn ((true, false), $2, unionRanges (rhs parseState 1) $2.Range) } forLoopBinder: @@ -3974,53 +4375,57 @@ forLoopBinder: { ($1, $3, true) } | parenPattern IN rangeSequenceExpr - { let m,r = $3 in ($1, r false m, true) } + { let m, r = $3 in ($1, r false m, true) } | parenPattern IN ends_coming_soon_or_recover { if not $3 then reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsExpectedExpressionAfterToken()) - ($1, arbExpr("forLoopBinder",(rhs parseState 2)), false) } + ($1, arbExpr("forLoopBinder", (rhs parseState 2)), false) } | parenPattern ends_coming_soon_or_recover { if not $2 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsInOrEqualExpected()) - ($1, arbExpr("forLoopBinder2",(rhs parseState 1).EndRange), false) } + ($1, arbExpr("forLoopBinder2", (rhs parseState 1).EndRange), false) } forLoopRange: | parenPattern EQUALS declExpr forLoopDirection declExpr - { idOfPat (rhs parseState 1) $1,$3,$4,$5 } + { idOfPat parseState (rhs parseState 1) $1, $3, $4, $5 } | parenPattern EQUALS rangeSequenceExpr { raiseParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnexpectedSymbolEqualsInsteadOfIn()) } forLoopDirection: | TO { true } + | DOWNTO { false } inlineAssemblyExpr: - | HASH stringOrKeywordString opt_inlineAssemblyTypeArg opt_curriedArgExprs opt_inlineAssemblyReturnTypes HASH + | HASH stringOrKeywordString opt_inlineAssemblyTypeArg optCurriedArgExprs optInlineAssemblyReturnTypes HASH { libraryOnlyWarning (lhs parseState) - let s,sm = $2,rhs parseState 2 - (fun m -> SynExpr.LibraryOnlyILAssembly (ParseAssemblyCodeInstructions s sm,$3,List.rev $4,$5,m)) } - -opt_curriedArgExprs: - | opt_curriedArgExprs argExpr %prec expr_args - { $2 :: $1 } + let s, sm = $2, rhs parseState 2 + (fun m -> SynExpr.LibraryOnlyILAssembly (internalParseAssemblyCodeInstructions s parseState.LexBuffer.SupportsFeature sm, $3, List.rev $4, $5, m)) } - | +optCurriedArgExprs: + | optCurriedArgExprs argExpr %prec expr_args + { $2 :: $1 } + + | /* EMPTY */ { [] } opt_atomicExprAfterType: - | + | /* EMPTY */ { None } - | atomicExprAfterType + | atomicExprAfterType { Some($1) } opt_inlineAssemblyTypeArg: - | { [] } - | typeKeyword LPAREN typ rparen { [$3] } + | /* EMPTY */ + { [] } + + | typeKeyword LPAREN typ rparen + { [$3] } -opt_inlineAssemblyReturnTypes: - | +optInlineAssemblyReturnTypes: + | /* EMPTY */ { [] } | COLON typ @@ -4037,14 +4442,15 @@ recdExpr: let l = rebindRanges (dummyField, None) l $6 let (_, _, inheritsSep) = List.head l let bindings = List.tail l - (Some ($2,arg,rhs2 parseState 2 4, inheritsSep, rhs parseState 1), None, bindings) } + (Some ($2, arg, rhs2 parseState 2 4, inheritsSep, rhs parseState 1), None, bindings) } + | recdExprCore - { let a,b = $1 in (None, a, b) } + { let a, b = $1 in (None, a, b) } recdExprCore: | appExpr EQUALS declExprBlock recdExprBindings opt_seps_recd { match $1 with - | LongOrSingleIdent(false, (LongIdentWithDots(_,_) as f),None,m) -> + | LongOrSingleIdent(false, (LongIdentWithDots(_, _) as f), None, m) -> let f = mkRecdField f let l = List.rev $4 let l = rebindRanges (f, Some $3) l $5 @@ -4093,21 +4499,31 @@ recdExprCore: (Some ($1, (rhs parseState 2, None)), l) } opt_seps_recd: - | seps_recd { Some $1 } - | { None } + | seps_recd + { Some $1 } + + | /* EMPTY */ + { None } seps_recd: - | OBLOCKSEP { (rhs parseState 1), None } - | SEMICOLON { let m = (rhs parseState 1) in (m, Some m.End) } - | SEMICOLON OBLOCKSEP { (rhs2 parseState 1 2), Some (rhs parseState 1).End } - | OBLOCKSEP SEMICOLON { (rhs2 parseState 1 2), Some (rhs parseState 2).End } + | OBLOCKSEP + { (rhs parseState 1), None } + | SEMICOLON + { let m = (rhs parseState 1) in (m, Some m.End) } -/* - identifier can start from the underscore -*/ + | SEMICOLON OBLOCKSEP + { (rhs2 parseState 1 2), Some (rhs parseState 1).End } + + | OBLOCKSEP SEMICOLON + { (rhs2 parseState 1 2), Some (rhs parseState 2).End } + + +/* identifier can start from the underscore */ pathOrUnderscore : - | path { mkRecdField $1 } + | path + { mkRecdField $1 } + | UNDERSCORE { let m = rhs parseState 1 reportParseErrorAt m (FSComp.SR.parsUnderscoreInvalidFieldName()) @@ -4116,27 +4532,29 @@ pathOrUnderscore : recdExprBindings: | recdExprBindings seps_recd recdBinding { ($3, Some $2) :: $1 } - | { [] } + + | /* EMPTY */ + { [] } recdBinding: - | pathOrUnderscore EQUALS declExprBlock - { ($1, Some $3) } + | pathOrUnderscore EQUALS declExprBlock + { ($1, Some $3) } - | pathOrUnderscore EQUALS - { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsFieldBinding()) - ($1, None) } + | pathOrUnderscore EQUALS + { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsFieldBinding()) + ($1, None) } - | pathOrUnderscore EQUALS ends_coming_soon_or_recover - { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsFieldBinding()) - ($1, None) } + | pathOrUnderscore EQUALS ends_coming_soon_or_recover + { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsFieldBinding()) + ($1, None) } - | pathOrUnderscore - { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsFieldBinding()) - ($1, None) } + | pathOrUnderscore + { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsFieldBinding()) + ($1, None) } - | pathOrUnderscore ends_coming_soon_or_recover - { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsFieldBinding()) - ($1, None) } + | pathOrUnderscore ends_coming_soon_or_recover + { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsFieldBinding()) + ($1, None) } /* There is a minor conflict between seq { new ty() } // sequence expression with one very odd 'action' expression @@ -4148,33 +4566,35 @@ objExpr: | objExprBaseCall objExprBindings opt_OBLOCKSEP opt_objExprInterfaces { let mNewExpr = rhs parseState 1 let fullRange = match $4 with [] -> (rhs parseState 1) | _ -> (rhs2 parseState 1 4) - fullRange, (fun m -> let (a,b) = $1 in SynExpr.ObjExpr(a,b,$2,$4, mNewExpr, m)) } + fullRange, (fun m -> let (a, b) = $1 in SynExpr.ObjExpr (a, b, $2, $4, mNewExpr, m)) } | objExprBaseCall opt_OBLOCKSEP objExprInterfaces { let mNewExpr = rhs parseState 1 let fullRange = match $3 with [] -> (rhs parseState 1) | _ -> (rhs2 parseState 1 3) - fullRange, (fun m -> let (a,b) = $1 in SynExpr.ObjExpr(a,b,[],$3, mNewExpr, m)) } + fullRange, (fun m -> let (a, b) = $1 in SynExpr.ObjExpr (a, b, [], $3, mNewExpr, m)) } | NEW atomTypeNonAtomicDeprecated { let mNewExpr = rhs parseState 1 - (rhs2 parseState 1 2), (fun m -> let (a,b) = $2,None in SynExpr.ObjExpr(a,b,[],[], mNewExpr, m)) } - + (rhs2 parseState 1 2), (fun m -> let (a, b) = $2, None in SynExpr.ObjExpr (a, b, [], [], mNewExpr, m)) } objExprBaseCall: | NEW atomTypeNonAtomicDeprecated opt_HIGH_PRECEDENCE_APP atomicExprAfterType baseSpec - { ($2, Some($4,Some($5))) } + { ($2, Some($4, Some($5))) } | NEW atomTypeNonAtomicDeprecated opt_HIGH_PRECEDENCE_APP atomicExprAfterType - { ($2, Some($4,None)) } + { ($2, Some($4, None)) } | NEW atomTypeNonAtomicDeprecated - { $2,None } + { $2, None } opt_objExprBindings: - | objExprBindings { $1 } - | { [] } + | objExprBindings + { $1 } + + | /* EMPTY */ + { [] } objExprBindings: | WITH localBindings @@ -4190,9 +4610,9 @@ objExprBindings: | WITH objectImplementationBlock opt_declEnd { $2 |> (List.choose (function - | SynMemberDefn.Member(b,m) -> Some b - | SynMemberDefn.AutoProperty(_,_,_,_,_,_,_,_,_,_,m) -> errorR(Error(FSComp.SR.parsIllegalMemberVarInObjectImplementation(),m)); None - | x -> errorR(Error(FSComp.SR.parsMemberIllegalInObjectImplementation(),x.Range)); None)) } + | SynMemberDefn.Member(b, m) -> Some b + | SynMemberDefn.AutoProperty(_, _, _, _, _, _, _, _, _, _, m) -> errorR(Error(FSComp.SR.parsIllegalMemberVarInObjectImplementation(), m)); None + | x -> errorR(Error(FSComp.SR.parsMemberIllegalInObjectImplementation(), x.Range)); None)) } objExprInterfaces: | objExprInterface opt_objExprInterfaces { $1 :: $2 } @@ -4208,12 +4628,13 @@ opt_objExprInterfaces: { (* silent recovery *) $2 } objExprInterface: - | interfaceMember appType opt_objExprBindings opt_declEnd opt_OBLOCKSEP + | interfaceMember appType opt_objExprBindings opt_declEnd opt_OBLOCKSEP { InterfaceImpl($2, $3, lhs parseState) } braceBarExpr: | STRUCT braceBarExprCore { $2 true } + | braceBarExprCore { $1 false } @@ -4222,36 +4643,36 @@ braceBarExprCore: { let orig, flds = $2 let flds = flds |> List.choose (function - | ((LongIdentWithDots([id],_),_),Some e,_) -> Some (id,e) - | ((LongIdentWithDots([id],_),_),None,_) -> Some (id, arbExpr("anonField",id.idRange)) + | ((LongIdentWithDots([id], _), _), Some e, _) -> Some (id, e) + | ((LongIdentWithDots([id], _), _), None, _) -> Some (id, arbExpr("anonField", id.idRange)) | _ -> reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsInvalidAnonRecdType()); None) let m = rhs2 parseState 1 3 - (fun isStruct -> SynExpr.AnonRecd(isStruct,orig,flds,m)) } + (fun isStruct -> SynExpr.AnonRecd (isStruct, orig, flds, m)) } | LBRACE_BAR recdExprCore recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedBraceBar()) let orig, flds = $2 let flds = flds |> List.choose (function - | ((LongIdentWithDots([id],_),_),Some e,_) -> Some (id,e) - | ((LongIdentWithDots([id],_),_),None,_) -> Some (id, arbExpr("anonField",id.idRange)) + | ((LongIdentWithDots([id], _), _), Some e, _) -> Some (id, e) + | ((LongIdentWithDots([id], _), _), None, _) -> Some (id, arbExpr("anonField", id.idRange)) | _ -> reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsInvalidAnonRecdType()); None) let m = rhs2 parseState 1 2 - (fun isStruct -> SynExpr.AnonRecd(isStruct,orig,flds,m)) } + (fun isStruct -> SynExpr.AnonRecd (isStruct, orig, flds, m)) } | LBRACE_BAR error bar_rbrace { // silent recovery let m = rhs2 parseState 1 3 - (fun _ -> arbExpr("braceBarExpr",m)) } + (fun _ -> arbExpr("braceBarExpr", m)) } | LBRACE_BAR recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedBraceBar()) let m = rhs2 parseState 1 1 - (fun isStruct -> SynExpr.AnonRecd(isStruct,None,[],m)) } + (fun isStruct -> SynExpr.AnonRecd (isStruct, None, [], m)) } | LBRACE_BAR bar_rbrace { let m = rhs2 parseState 1 2 - (fun isStruct -> SynExpr.AnonRecd(isStruct,None,[],m)) } + (fun isStruct -> SynExpr.AnonRecd (isStruct, None, [], m)) } anonLambdaExpr: | FUN atomicPatterns RARROW typedSeqExprBlock @@ -4260,7 +4681,7 @@ anonLambdaExpr: | FUN atomicPatterns RARROW error { let mAll = rhs2 parseState 1 3 - mkSynFunMatchLambdas parseState.SynArgNameGenerator false mAll $2 (arbExpr("anonLambdaExpr1",(rhs parseState 4))) } + mkSynFunMatchLambdas parseState.SynArgNameGenerator false mAll $2 (arbExpr("anonLambdaExpr1", (rhs parseState 4))) } | OFUN atomicPatterns RARROW typedSeqExprBlockR OEND { let mAll = unionRanges (rhs parseState 1) $4.Range @@ -4273,28 +4694,28 @@ anonLambdaExpr: | OFUN atomicPatterns RARROW ORIGHT_BLOCK_END OEND { reportParseErrorAt (rhs2 parseState 1 3) (FSComp.SR.parsMissingFunctionBody()) - mkSynFunMatchLambdas parseState.SynArgNameGenerator false (rhs2 parseState 1 3) $2 (arbExpr("anonLambdaExpr2",(rhs parseState 4))) } + mkSynFunMatchLambdas parseState.SynArgNameGenerator false (rhs2 parseState 1 3) $2 (arbExpr("anonLambdaExpr2", (rhs parseState 4))) } | OFUN atomicPatterns RARROW recover { if not $4 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedEndOfFileFunBody()) - exprFromParseError (mkSynFunMatchLambdas parseState.SynArgNameGenerator false (rhs2 parseState 1 3) $2 (arbExpr("anonLambdaExpr3",(rhs parseState 4)))) } + exprFromParseError (mkSynFunMatchLambdas parseState.SynArgNameGenerator false (rhs2 parseState 1 3) $2 (arbExpr("anonLambdaExpr3", (rhs parseState 4)))) } | OFUN atomicPatterns error OEND - { exprFromParseError (mkSynFunMatchLambdas parseState.SynArgNameGenerator false (rhs2 parseState 1 2) $2 (arbExpr("anonLambdaExpr4",(rhs parseState 3)))) } + { exprFromParseError (mkSynFunMatchLambdas parseState.SynArgNameGenerator false (rhs2 parseState 1 2) $2 (arbExpr("anonLambdaExpr4", (rhs parseState 3)))) } | OFUN error OEND - { exprFromParseError (mkSynFunMatchLambdas parseState.SynArgNameGenerator false (rhs parseState 1) [] (arbExpr("anonLambdaExpr5",(rhs parseState 2)))) } + { exprFromParseError (mkSynFunMatchLambdas parseState.SynArgNameGenerator false (rhs parseState 1) [] (arbExpr("anonLambdaExpr5", (rhs parseState 2)))) } anonMatchingExpr: | FUNCTION withPatternClauses %prec expr_function - { let clauses,mLast = $2 - let mAll = unionRanges (rhs parseState 1) mLast - SynExpr.MatchLambda(false,(rhs parseState 1),clauses,NoSequencePointAtInvisibleBinding,mAll) } + { let clauses, mLast = $2 + let mAll = unionRanges (rhs parseState 1) mLast + SynExpr.MatchLambda (false, (rhs parseState 1), clauses, NoDebugPointAtInvisibleBinding, mAll) } | OFUNCTION withPatternClauses OEND %prec expr_function - { let clauses,mLast = $2 - let mAll = unionRanges (rhs parseState 1) mLast - SynExpr.MatchLambda(false,(rhs parseState 1),clauses,NoSequencePointAtInvisibleBinding,mAll) } + { let clauses, mLast = $2 + let mAll = unionRanges (rhs parseState 1) mLast + SynExpr.MatchLambda (false, (rhs parseState 1), clauses, NoDebugPointAtInvisibleBinding, mAll) } /*--------------------------------------------------------------------------*/ /* TYPE ALGEBRA */ @@ -4304,41 +4725,41 @@ typeWithTypeConstraints: { $1 } | typ WHEN typeConstraints - { SynType.WithGlobalConstraints($1, List.rev $3,lhs parseState) } + { SynType.WithGlobalConstraints($1, List.rev $3, lhs parseState) } topTypeWithTypeConstraints: | topType { $1 } | topType WHEN typeConstraints - { let ty,arity = $1 + { let ty, arity = $1 // nb. it doesn't matter where the constraints go in the structure of the type. - SynType.WithGlobalConstraints(ty,List.rev $3,lhs parseState), arity } + SynType.WithGlobalConstraints(ty, List.rev $3, lhs parseState), arity } opt_topReturnTypeWithTypeConstraints: | { None } | COLON topTypeWithTypeConstraints - { let ty,arity = $2 - let arity = (match arity with SynValInfo([],rmdata)-> rmdata | _ -> SynInfo.unnamedRetVal) - Some (SynReturnInfo((ty,arity),rhs parseState 2)) } + { let ty, arity = $2 + let arity = (match arity with SynValInfo([], rmdata)-> rmdata | _ -> SynInfo.unnamedRetVal) + Some (SynReturnInfo((ty, arity), rhs parseState 2)) } topType: | topTupleType RARROW topType - { let dty,dmdata= $1 - let rty,(SynValInfo(dmdatas,rmdata)) = $3 - SynType.Fun(dty,rty,lhs parseState), (SynValInfo(dmdata::dmdatas, rmdata)) } + { let dty, dmdata= $1 + let rty, (SynValInfo(dmdatas, rmdata)) = $3 + SynType.Fun(dty, rty, lhs parseState), (SynValInfo(dmdata :: dmdatas, rmdata)) } | topTupleType - { let ty,rmdata = $1 in ty, (SynValInfo([],(match rmdata with [md] -> md | _ -> SynInfo.unnamedRetVal))) } + { let ty, rmdata = $1 in ty, (SynValInfo([], (match rmdata with [md] -> md | _ -> SynInfo.unnamedRetVal))) } topTupleType: | topAppType STAR topTupleTypeElements - { let ty,mdata = $1 in let tys,mdatas = List.unzip $3 in (SynType.Tuple(false,List.map (fun ty -> (false,ty)) (ty ::tys), lhs parseState)),(mdata :: mdatas) } + { let ty, mdata = $1 in let tys, mdatas = List.unzip $3 in (SynType.Tuple(false, List.map (fun ty -> (false, ty)) (ty :: tys), lhs parseState)), (mdata :: mdatas) } | topAppType - { let ty,mdata = $1 in ty,[mdata] } + { let ty, mdata = $1 in ty, [mdata] } topTupleTypeElements: | topAppType STAR topTupleTypeElements @@ -4350,31 +4771,31 @@ topTupleTypeElements: topAppType: | attributes appType COLON appType { match $2 with - | SynType.LongIdent(LongIdentWithDots([id],_)) -> $4,SynArgInfo($1,false,Some id) + | SynType.LongIdent(LongIdentWithDots([id], _)) -> $4, SynArgInfo($1, false, Some id) | _ -> raiseParseErrorAt (rhs parseState 2) (FSComp.SR.parsSyntaxErrorInLabeledType()) } | attributes QMARK ident COLON appType - { $5,SynArgInfo($1,true,Some $3) } + { $5, SynArgInfo($1, true, Some $3) } | attributes appType - { ($2,SynArgInfo($1,false,None)) } + { ($2, SynArgInfo($1, false, None)) } | appType COLON appType { match $1 with - | SynType.LongIdent(LongIdentWithDots([id],_)) -> $3,SynArgInfo([],false,Some id) + | SynType.LongIdent(LongIdentWithDots([id], _)) -> $3, SynArgInfo([], false, Some id) | _ -> raiseParseErrorAt (rhs parseState 2) (FSComp.SR.parsSyntaxErrorInLabeledType()) } | QMARK ident COLON appType - { $4,SynArgInfo([],true,Some $2) } + { $4, SynArgInfo([], true, Some $2) } | appType - { $1,SynArgInfo([],false,None) } + { $1, SynArgInfo([], false, None) } /* Any tokens in this grammar must be added to the lex filter rule 'peekAdjacentTypars' */ /* See the F# specification "Lexical analysis of type applications and type parameter definitions" */ typ: | tupleType RARROW typ - { SynType.Fun($1,$3,lhs parseState) } + { SynType.Fun($1, $3, lhs parseState) } | tupleType %prec prec_typ_prefix { $1 } @@ -4385,29 +4806,29 @@ typEOF: tupleType: | appType STAR tupleOrQuotTypeElements - { SynType.Tuple(false,(false,$1) :: $3,lhs parseState) } + { SynType.Tuple(false, (false, $1) :: $3, lhs parseState) } | INFIX_STAR_DIV_MOD_OP tupleOrQuotTypeElements { if $1 <> "/" then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedInfixOperator()); - SynType.Tuple(false,(true, SynType.StaticConstant (SynConst.Int32 1, lhs parseState)):: $2, lhs parseState) } + SynType.Tuple(false, (true, SynType.StaticConstant (SynConst.Int32 1, lhs parseState)) :: $2, lhs parseState) } | appType INFIX_STAR_DIV_MOD_OP tupleOrQuotTypeElements { if $2 <> "/" then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedInfixOperator()); - SynType.Tuple(false,(true,$1) :: $3, lhs parseState) } + SynType.Tuple(false, (true, $1) :: $3, lhs parseState) } | appType %prec prec_tuptyp_prefix { $1 } tupleOrQuotTypeElements: | appType STAR tupleOrQuotTypeElements - { (false,$1) :: $3 } + { (false, $1) :: $3 } | appType INFIX_STAR_DIV_MOD_OP tupleOrQuotTypeElements { if $2 <> "/" then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedInfixOperator()); - (true,$1) :: $3 } + (true, $1) :: $3 } | appType %prec prec_tuptyptail_prefix - { [(false,$1)] } + { [(false, $1)] } appTypeCon: | path %prec prec_atomtyp_path @@ -4427,13 +4848,14 @@ appTypeConPower: appType: | appType arrayTypeSuffix - { SynType.Array($2,$1,lhs parseState) } + { SynType.Array($2, $1, lhs parseState) } | appType HIGH_PRECEDENCE_BRACK_APP arrayTypeSuffix /* only HPA for "name[]" allowed here */ - { SynType.Array($3,$1,lhs parseState) } + { SynType.Array($3, $1, lhs parseState) } | appType appTypeConPower - { SynType.App($2, None, [$1], [], None, true, unionRanges (rhs parseState 1) $2.Range) } /* note: use "rhs parseState 1" to deal with parens in "(int) list" */ + /* note: use "rhs parseState 1" to deal with parens in "(int) list" */ + { SynType.App($2, None, [$1], [], None, true, unionRanges (rhs parseState 1) $2.Range) } | LPAREN appTypePrefixArguments rparen appTypeConPower { let args, commas = $2 @@ -4443,10 +4865,10 @@ appType: | powerType { $1 } - | typar COLON_GREATER typ - { let tp,typ = $1,$3 + | typar COLON_GREATER typ + { let tp, typ = $1, $3 let m = lhs parseState - SynType.WithGlobalConstraints(SynType.Var (tp, rhs parseState 1), [WhereTyparSubtypeOfType(tp,typ,m)],m) } + SynType.WithGlobalConstraints(SynType.Var (tp, rhs parseState 1), [WhereTyparSubtypeOfType(tp, typ, m)], m) } | UNDERSCORE COLON_GREATER typ %prec COLON_GREATER { SynType.HashConstraint($3, lhs parseState) } @@ -4466,17 +4888,17 @@ arrayTypeSuffix: appTypePrefixArguments: | typeArgActual COMMA typeArgActual typeArgListElements - { let typeArgs, commas = $4 in $1 :: $3 :: List.rev typeArgs, (rhs parseState 2)::(List.rev commas) } + { let typeArgs, commas = $4 in $1 :: $3 :: List.rev typeArgs, (rhs parseState 2) :: (List.rev commas) } typeArgListElements: | typeArgListElements COMMA typeArgActual { let typeArgs, commas = $1 - $3 :: typeArgs, (rhs parseState 2)::commas } + $3 :: typeArgs, (rhs parseState 2) :: commas } | typeArgListElements COMMA dummyTypeArg %prec prec_args_error /* NOTE: no "recover" */ { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsMissingTypeArgs()) let typeArgs, commas = $1 - $3 :: typeArgs, (rhs parseState 2)::commas } + $3 :: typeArgs, (rhs parseState 2) :: commas } | { [], [] } @@ -4505,15 +4927,14 @@ atomTypeNonAtomicDeprecated: atomTypeOrAnonRecdType: | atomType { $1 } + | anonRecdType - { let flds,isStruct = $1 + { let flds, isStruct = $1 let flds2 = flds |> List.choose (function - | (Field([],false,Some id,ty,false,_xmldoc,None,_m)) -> Some (id,ty) + | (Field([], false, Some id, ty, false, _xmldoc, None, _m)) -> Some (id, ty) | _ -> reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsInvalidAnonRecdType()); None) - SynType.AnonRecd (isStruct,flds2, rhs parseState 1) } - - + SynType.AnonRecd (isStruct, flds2, rhs parseState 1) } /* Any tokens in this grammar must be added to the lex filter rule 'peekAdjacentTypars' */ /* See the F# specification "Lexical analysis of type applications and type parameter definitions" */ @@ -4535,11 +4956,11 @@ atomType: $2 } | STRUCT LPAREN appType STAR tupleOrQuotTypeElements rparen - { SynType.Tuple(true, (false,$3) :: $5,lhs parseState) } + { SynType.Tuple(true, (false, $3) :: $5, lhs parseState) } | STRUCT LPAREN appType STAR tupleOrQuotTypeElements recover { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnmatchedParen()) - SynType.Tuple(true, (false,$3) :: $5,lhs parseState) } + SynType.Tuple(true, (false, $3) :: $5, lhs parseState) } | STRUCT LPAREN appType STAR recover { reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnmatchedParen()) @@ -4561,38 +4982,37 @@ atomType: SynType.StaticConstant(SynConst.String (null, m), m) } | CONST atomicExpr - { let e,_ = $2 + { let e, _ = $2 SynType.StaticConstantExpr(e, e.Range) } | FALSE - { SynType.StaticConstant(SynConst.Bool false,lhs parseState) } + { SynType.StaticConstant(SynConst.Bool false, lhs parseState) } | TRUE - { SynType.StaticConstant(SynConst.Bool true,lhs parseState) } + { SynType.StaticConstant(SynConst.Bool true, lhs parseState) } | LPAREN error rparen { (* silent recovery *) SynType.Anon (lhs parseState) } | appTypeCon typeArgsNoHpaDeprecated %prec prec_atomtyp_path - { let mLessThan,mGreaterThan,args,commas,mWhole = $2 in SynType.App($1, Some(mLessThan), args, commas, mGreaterThan, false, unionRanges $1.Range mWhole) } + { let mLessThan, mGreaterThan, args, commas, mWhole = $2 in SynType.App($1, Some(mLessThan), args, commas, mGreaterThan, false, unionRanges $1.Range mWhole) } | atomType DOT path %prec prec_atomtyp_get_path { SynType.LongIdentApp($1, $3, None, [], [], None, unionRanges (rhs parseState 1) $3.Range) } | atomType DOT path typeArgsNoHpaDeprecated %prec prec_atomtyp_get_path - { let mLessThan,mGreaterThan,args,commas,mWhole = $4 + { let mLessThan, mGreaterThan, args, commas, mWhole = $4 SynType.LongIdentApp($1, $3, Some(mLessThan), args, commas, mGreaterThan, unionRanges $1.Range mWhole) } | appTypeCon DOT ends_coming_soon_or_recover { if not $3 then reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsExpectedNameAfterToken()) $1 } - typeArgsNoHpaDeprecated: | typeArgsActual { let mLessThan, mGreaterThan, parsedOk, args, commas, mAll = $1 if parsedOk then // if someone has "foo "^" then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnexpectedTypeParameter()); let id = mkSynId (lhs parseState) ($2).idText - Typar(id,HeadTypeStaticReq,false) } - - + Typar(id, HeadTypeStaticReq, false) } ident: | IDENT - { ident($1,rhs parseState 1) } - + { ident($1, rhs parseState 1) } /* A A.B.C path used to an identifier */ path: | GLOBAL - { LongIdentWithDots([ident(MangledGlobalName,rhs parseState 1)],[]) } + { LongIdentWithDots([ident(MangledGlobalName, rhs parseState 1)], []) } | ident - { LongIdentWithDots([$1],[]) } + { LongIdentWithDots([$1], []) } | path DOT ident - { let (LongIdentWithDots(lid,dotms)) = $1 in LongIdentWithDots(lid @ [$3], dotms @ [rhs parseState 2]) } + { let (LongIdentWithDots(lid, dotms)) = $1 in LongIdentWithDots(lid @ [$3], dotms @ [rhs parseState 2]) } | path DOT ends_coming_soon_or_recover { if not $3 then reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsExpectedNameAfterToken()) - let (LongIdentWithDots(lid,dotms)) = $1 in LongIdentWithDots(lid, dotms @ [rhs parseState 2]) } + let (LongIdentWithDots(lid, dotms)) = $1 in LongIdentWithDots(lid, dotms @ [rhs parseState 2]) } /* An operator name, with surrounnding parentheses */ opName: | LPAREN operatorName rparen - { ident(CompileOpName $2,rhs parseState 2) } + { ident(CompileOpName $2, rhs parseState 2) } | LPAREN error rparen - { reportParseErrorAt (lhs parseState) (FSComp.SR.parsErrorParsingAsOperatorName()); ident(CompileOpName "****",rhs parseState 2) } + { reportParseErrorAt (lhs parseState) (FSComp.SR.parsErrorParsingAsOperatorName()); ident(CompileOpName "****", rhs parseState 2) } | LPAREN_STAR_RPAREN - { ident(CompileOpName "*",rhs parseState 1) } + { ident(CompileOpName "*", rhs parseState 1) } /* active pattern name */ | LPAREN activePatternCaseNames BAR rparen { let text = ("|" + String.concat "|" (List.rev $2) + "|") - ident(text,rhs2 parseState 2 3) } + ident(text, rhs2 parseState 2 3) } /* partial active pattern name */ | LPAREN activePatternCaseNames BAR UNDERSCORE BAR rparen { let text = ("|" + String.concat "|" (List.rev $2) + "|_|" ) - ident(text,rhs2 parseState 2 5) } + ident(text, rhs2 parseState 2 5) } /* An operator name, without surrounding parentheses */ operatorName: | PREFIX_OP - { if not (IsValidPrefixOperatorDefinitionName $1) then - reportParseErrorAt (lhs parseState) (FSComp.SR.parsInvalidPrefixOperatorDefinition()); - $1 } + { if not (IsValidPrefixOperatorDefinitionName $1) then + reportParseErrorAt (lhs parseState) (FSComp.SR.parsInvalidPrefixOperatorDefinition()); + $1 } - | INFIX_STAR_STAR_OP { $1 } + | INFIX_STAR_STAR_OP + { $1 } - | INFIX_COMPARE_OP { $1 } + | INFIX_COMPARE_OP + { $1 } - | INFIX_AT_HAT_OP { $1 } + | INFIX_AT_HAT_OP + { $1 } - | INFIX_BAR_OP { $1 } + | INFIX_BAR_OP + { $1 } - | INFIX_AMP_OP { $1 } + | INFIX_AMP_OP + { $1 } - | PLUS_MINUS_OP { $1 } + | PLUS_MINUS_OP + { $1 } - | INFIX_STAR_DIV_MOD_OP { $1 } + | INFIX_STAR_DIV_MOD_OP + { $1 } - | DOLLAR { "$" } + | DOLLAR + { "$" } - | ADJACENT_PREFIX_OP { $1 } + | ADJACENT_PREFIX_OP + { $1 } - | MINUS { "-" } + | MINUS + { "-" } - | STAR { "*" } + | STAR + { "*" } - | EQUALS { "=" } + | EQUALS + { "=" } - | OR { "or" } + | OR + { "or" } - | LESS { "<" } + | LESS + { "<" } - | GREATER { ">" } + | GREATER + { ">" } - | QMARK { "?" } + | QMARK + { "?" } - | AMP { "&" } + | AMP + { "&" } - | AMP_AMP { "&&" } + | AMP_AMP + { "&&" } - | BAR_BAR { "||" } + | BAR_BAR + { "||" } - | COLON_EQUALS { ":=" } + | COLON_EQUALS + { ":=" } | FUNKY_OPERATOR_NAME - { if $1 <> ".[]" && $1 <> ".()" && $1 <> ".()<-" then - deprecatedOperator (lhs parseState); - $1 } + { if $1 <> ".[]" && $1 <> ".()" && $1 <> ".()<-" then + deprecatedOperator (lhs parseState); + $1 } - | PERCENT_OP { $1 } + | PERCENT_OP + { $1 } - | DOT_DOT { ".." } + | DOT_DOT + { ".." } - | DOT_DOT DOT_DOT { ".. .." } + | DOT_DOT DOT_DOT + { ".. .." } | LQUOTE RQUOTE - { if $1 <> $2 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsMismatchedQuotationName(fst $1)); - fst $1 } + { if $1 <> $2 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsMismatchedQuotationName(fst $1)); + fst $1 } /* One part of an active pattern name */ activePatternCaseName: | IDENT - { if not (String.isUpper $1) then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsActivePatternCaseMustBeginWithUpperCase()); - if ($1.IndexOf('|') <> -1) then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsActivePatternCaseContainsPipe()); - $1 } + { if not (String.isUpper $1) then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsActivePatternCaseMustBeginWithUpperCase()); + if ($1.IndexOf('|') <> -1) then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsActivePatternCaseContainsPipe()); + $1 } /* Multiple parts of an active pattern name */ activePatternCaseNames: | BAR activePatternCaseName - { [$2] } + { [$2] } | activePatternCaseNames BAR activePatternCaseName - { $3 :: $1 } + { $3 :: $1 } /* A single item that is an identifier or operator name */ identOrOp: @@ -4871,21 +5310,21 @@ identOrOp: /* Note, only used in atomicPatternLongIdent */ pathOp: | ident - { LongIdentWithDots([$1],[]) } + { LongIdentWithDots([$1], []) } | opName - { LongIdentWithDots([$1],[]) } + { LongIdentWithDots([$1], []) } | ident DOT pathOp - { let (LongIdentWithDots(lid,dotms)) = $3 in LongIdentWithDots($1 :: lid, rhs parseState 2 :: dotms) } + { let (LongIdentWithDots(lid, dotms)) = $3 in LongIdentWithDots($1 :: lid, rhs parseState 2 :: dotms) } | ident DOT error - { (* silent recovery *) LongIdentWithDots([$1],[rhs parseState 2]) } + { (* silent recovery *) LongIdentWithDots([$1], [rhs parseState 2]) } /* nameop is identOrOp not used as part of a path */ nameop: - | identOrOp { $1 } + | identOrOp { $1 } topSeparator: | SEMICOLON { } @@ -4893,7 +5332,7 @@ topSeparator: | OBLOCKSEP { } topSeparators: - | topSeparator { } + | topSeparator { } | topSeparator topSeparators { } opt_topSeparators: diff --git a/src/fcs-fable/src/fsharp/pplex.fsl b/src/fcs-fable/src/fsharp/pplex.fsl index 35d1c7fc3b..fd984c41b4 100644 --- a/src/fcs-fable/src/fsharp/pplex.fsl +++ b/src/fcs-fable/src/fsharp/pplex.fsl @@ -6,9 +6,10 @@ module internal FSharp.Compiler.PPLexer open System -open FSharp.Compiler.Ast open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Lexhelp +open FSharp.Compiler.ParseHelpers +open FSharp.Compiler.SyntaxTree open Internal.Utilities.Text.Lexing diff --git a/src/fcs-fable/src/fsharp/pppars.fsy b/src/fcs-fable/src/fsharp/pppars.fsy index 354fd0ac38..0cd9171ae9 100644 --- a/src/fcs-fable/src/fsharp/pppars.fsy +++ b/src/fcs-fable/src/fsharp/pppars.fsy @@ -1,8 +1,9 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. %{ -open FSharp.Compiler.Ast open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.ParseHelpers +open FSharp.Compiler.SyntaxTree let dummy = IfdefId("DUMMY") diff --git a/src/fcs-fable/src/fsharp/range.fs b/src/fcs-fable/src/fsharp/range.fs index 9375095f0c..ba833646ff 100755 --- a/src/fcs-fable/src/fsharp/range.fs +++ b/src/fcs-fable/src/fsharp/range.fs @@ -5,6 +5,7 @@ module FSharp.Compiler.Range open System open System.IO +open System.Collections.Generic open System.Collections.Concurrent open Microsoft.FSharp.Core.Printf open FSharp.Compiler.AbstractIL.Internal.Library @@ -146,13 +147,13 @@ type FileIndexTable() = // // TO move forward we should eventually introduce a new type NormalizedFileName that tracks this invariant. member t.FileToIndex normalize filePath = - match fileToIndexTable.TryGetValue(filePath) with + match fileToIndexTable.TryGetValue filePath with | true, idx -> idx | _ -> // Try again looking for a normalized entry. let normalizedFilePath = if normalize then normalizeFilePath filePath else filePath - match fileToIndexTable.TryGetValue(normalizedFilePath) with + match fileToIndexTable.TryGetValue normalizedFilePath with | true, idx -> // Record the non-normalized entry if necessary if filePath <> normalizedFilePath then @@ -208,16 +209,16 @@ let fileOfFileIndex idx = fileIndexTable.IndexToFile idx let mkPos l c = pos (l, c) +let unknownFileName = "unknown" +let startupFileName = "startup" +let commandLineArgsFileName = "commandLineArgs" + [] -#if DEBUG -[ {DebugCode}")>] -#else -[] -#endif +[ {DebugCode}")>] type range(code1:int64, code2: int64) = static member Zero = range(0L, 0L) - new (fidx, bl, bc, el, ec) = - let code1 = ((int64 fidx) &&& fileIndexMask) + new (fIdx, bl, bc, el, ec) = + let code1 = ((int64 fIdx) &&& fileIndexMask) ||| ((int64 bc <<< startColumnShift) &&& startColumnMask) ||| ((int64 ec <<< endColumnShift) &&& endColumnMask) let code2 = @@ -225,7 +226,7 @@ type range(code1:int64, code2: int64) = ||| ((int64 (el-bl) <<< heightShift) &&& heightMask) range(code1, code2) - new (fidx, b:pos, e:pos) = range(fidx, b.Line, b.Column, e.Line, e.Column) + new (fIdx, b:pos, e:pos) = range(fIdx, b.Line, b.Column, e.Line, e.Column) member r.StartLine = int32((code2 &&& startLineMask) >>> startLineShift) @@ -249,22 +250,30 @@ type range(code1:int64, code2: int64) = member r.FileName = fileOfFileIndex r.FileIndex + member r.ShortFileName = Path.GetFileName(fileOfFileIndex r.FileIndex) + member r.MakeSynthetic() = range(code1, code2 ||| isSyntheticMask) member r.Code1 = code1 member r.Code2 = code2 -#if DEBUG +#if !FABLE_COMPILER member r.DebugCode = + let name = r.FileName + if name = unknownFileName || name = startupFileName || name = commandLineArgsFileName then name else + try let endCol = r.EndColumn - 1 let startCol = r.StartColumn - 1 - File.ReadAllLines(r.FileName) - |> Seq.skip (r.StartLine - 1) - |> Seq.take (r.EndLine - r.StartLine + 1) - |> String.concat "\n" - |> fun s -> s.Substring(startCol + 1, s.LastIndexOf("\n", StringComparison.Ordinal) + 1 - startCol + endCol) + if FileSystem.IsInvalidPathShim r.FileName then "path invalid: " + r.FileName + elif not (FileSystem.SafeExists r.FileName) then "non existing file: " + r.FileName + else + File.ReadAllLines(r.FileName) + |> Seq.skip (r.StartLine - 1) + |> Seq.take (r.EndLine - r.StartLine + 1) + |> String.concat "\n" + |> fun s -> s.Substring(startCol + 1, s.LastIndexOf("\n", StringComparison.Ordinal) + 1 - startCol + endCol) with e -> e.ToString() #endif @@ -279,6 +288,9 @@ type range(code1:int64, code2: int64) = let mkRange filePath startPos endPos = range (fileIndexOfFileAux true filePath, startPos, endPos) +let equals (r1: range) (r2: range) = + r1.Code1 = r2.Code1 && r1.Code2 = r2.Code2 + let mkFileIndexRange fileIndex startPos endPos = range (fileIndex, startPos, endPos) let posOrder = Order.orderOn (fun (p:pos) -> p.Line, p.Column) (Pair.order (Int32.order, Int32.order)) @@ -290,9 +302,12 @@ let outputPos (os:TextWriter) (m:pos) = fprintf os "(%d,%d)" m.Line m.Column let outputRange (os:TextWriter) (m:range) = fprintf os "%s%a-%a" m.FileName outputPos m.Start outputPos m.End -let posGt (p1:pos) (p2:pos) = (p1.Line > p2.Line || (p1.Line = p2.Line && p1.Column > p2.Column)) +let posGt (p1: pos) (p2: pos) = + let p1Line = p1.Line + let p2Line = p2.Line + p1Line > p2Line || p1Line = p2Line && p1.Column > p2.Column -let posEq (p1:pos) (p2:pos) = (p1.Line = p2.Line && p1.Column = p2.Column) +let posEq (p1: pos) (p2: pos) = p1.Encoding = p2.Encoding let posGeq p1 p2 = posEq p1 p2 || posGt p1 p2 @@ -325,11 +340,11 @@ let rangeN filename line = mkRange filename (mkPos line 0) (mkPos line 0) let pos0 = mkPos 1 0 -let range0 = rangeN "unknown" 1 +let range0 = rangeN unknownFileName 1 -let rangeStartup = rangeN "startup" 1 +let rangeStartup = rangeN startupFileName 1 -let rangeCmdArgs = rangeN "commandLineArgs" 0 +let rangeCmdArgs = rangeN commandLineArgsFileName 0 let trimRangeToLine (r:range) = let startL, startC = r.StartLine, r.StartColumn @@ -378,4 +393,9 @@ module Range = let toFileZ (m:range) = m.FileName, toZ m + let comparer = + { new IEqualityComparer with + member _.Equals(x1, x2) = equals x1 x2 + member _.GetHashCode o = o.GetHashCode() } + diff --git a/src/fcs-fable/src/fsharp/range.fsi b/src/fcs-fable/src/fsharp/range.fsi index 5da9bee549..172ad32c10 100755 --- a/src/fcs-fable/src/fsharp/range.fsi +++ b/src/fcs-fable/src/fsharp/range.fsi @@ -44,6 +44,10 @@ val mkPos : line:int -> column:int -> pos /// Ordering on positions val posOrder : IComparer +val unknownFileName: string +val startupFileName: string +val commandLineArgsFileName: string + /// Represents a range within a known file [] type range = @@ -98,6 +102,8 @@ val mkFileIndexRange : FileIndex -> pos -> pos -> range /// This view hides the use of file indexes and just uses filenames val mkRange : string -> pos -> pos -> range +val equals : range -> range -> bool + /// Reduce a range so it only covers a line val trimRangeToLine : range -> range @@ -194,3 +200,6 @@ module Range = /// Convert a range from one-based line counting (used internally in the F# compiler and in F# error messages) to zero-based line counting (used by Visual Studio) val toFileZ : range -> string * Range01 + + /// Equality comparer for range. + val comparer : IEqualityComparer diff --git a/src/fcs-fable/src/fsharp/service/ExternalSymbol.fs b/src/fcs-fable/src/fsharp/service/ExternalSymbol.fs index c0b4352c47..dc56f50ee2 100644 --- a/src/fcs-fable/src/fsharp/service/ExternalSymbol.fs +++ b/src/fcs-fable/src/fsharp/service/ExternalSymbol.fs @@ -18,14 +18,18 @@ module private Option = /// Represents a type in an external (non F#) assembly. [] type ExternalType = - /// Type defined in non-F# assembly. + /// Type defined in non-F# assembly. | Type of fullName: string * genericArgs: ExternalType list - /// Array of type that is defined in non-F# assembly. + + /// Array of type that is defined in non-F# assembly. | Array of inner: ExternalType - /// Pointer defined in non-F# assembly. + + /// Pointer defined in non-F# assembly. | Pointer of inner: ExternalType - /// Type variable defined in non-F# assembly. + + /// Type variable defined in non-F# assembly. | TypeVar of typeName: string + override this.ToString() = match this with | Type (name, genericArgs) -> @@ -89,6 +93,7 @@ type ExternalSymbol = | Field of typeName: string * name: string | Event of typeName: string * name: string | Property of typeName: string * name: string + override this.ToString () = match this with | Type fullName -> fullName diff --git a/src/fcs-fable/src/fsharp/service/ExternalSymbol.fsi b/src/fcs-fable/src/fsharp/service/ExternalSymbol.fsi index 36d290db4d..0115201012 100644 --- a/src/fcs-fable/src/fsharp/service/ExternalSymbol.fsi +++ b/src/fcs-fable/src/fsharp/service/ExternalSymbol.fsi @@ -2,26 +2,28 @@ namespace FSharp.Compiler.SourceCodeServices -open FSharp.Reflection open FSharp.Compiler.AbstractIL.IL /// Represents a type in an external (non F#) assembly. [] type ExternalType = - /// Type defined in non-F# assembly. + /// Type defined in non-F# assembly. | Type of fullName: string * genericArgs: ExternalType list - /// Array of type that is defined in non-F# assembly. + + /// Array of type that is defined in non-F# assembly. | Array of inner: ExternalType - /// Pointer defined in non-F# assembly. + + /// Pointer defined in non-F# assembly. | Pointer of inner: ExternalType - /// Type variable defined in non-F# assembly. + + /// Type variable defined in non-F# assembly. | TypeVar of typeName: string + override ToString : unit -> string module ExternalType = val internal tryOfILType : string array -> ILType -> ExternalType option - /// Represents the type of a single method parameter [] type ParamTypeSymbol = @@ -32,7 +34,6 @@ type ParamTypeSymbol = module ParamTypeSymbol = val internal tryOfILType : string array -> ILType -> ParamTypeSymbol option val internal tryOfILTypes : string array -> ILType list -> ParamTypeSymbol list option - /// Represents a symbol in an external (non F#) assembly [] @@ -43,5 +44,7 @@ type ExternalSymbol = | Field of typeName: string * name: string | Event of typeName: string * name: string | Property of typeName: string * name: string + override ToString : unit -> string + member internal ToDebuggerDisplay : unit -> string \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/service/FSharpCheckerResults.fs b/src/fcs-fable/src/fsharp/service/FSharpCheckerResults.fs new file mode 100644 index 0000000000..4d5f0153a8 --- /dev/null +++ b/src/fcs-fable/src/fsharp/service/FSharpCheckerResults.fs @@ -0,0 +1,2221 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +// Open up the compiler as an incremental service for parsing, +// type checking and intellisense-like environment-reporting. + +namespace FSharp.Compiler.SourceCodeServices + +open System +open System.Diagnostics +open System.IO +open System.Reflection + +open FSharp.Core.Printf +open FSharp.Compiler +open FSharp.Compiler.AbstractIL +open FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.AccessibilityLogic +open FSharp.Compiler.CompileOps +open FSharp.Compiler.CompileOptions +open FSharp.Compiler.CompilerGlobalState +open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features +open FSharp.Compiler.Layout +open FSharp.Compiler.Lexhelp +open FSharp.Compiler.Lib +open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.Parser +open FSharp.Compiler.ParseHelpers +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.Text +open FSharp.Compiler.Infos +open FSharp.Compiler.InfoReader +open FSharp.Compiler.NameResolution +open FSharp.Compiler.TypeChecker +open FSharp.Compiler.SourceCodeServices.SymbolHelpers + +open Internal.Utilities +open Internal.Utilities.Collections +open FSharp.Compiler.AbstractIL.ILBinaryReader + +[] +module internal FSharpCheckerResultsSettings = + + let getToolTipTextSize = GetEnvInteger "FCS_GetToolTipTextCacheSize" 5 + + let maxTypeCheckErrorsOutOfProjectContext = GetEnvInteger "FCS_MaxErrorsOutOfProjectContext" 3 + + /// Maximum time share for a piece of background work before it should (cooperatively) yield + /// to enable other requests to be serviced. Yielding means returning a continuation function + /// (via an Eventually<_> value of case NotYetDone) that can be called as the next piece of work. + let maxTimeShareMilliseconds = +#if FABLE_COMPILER + 100L +#else + match System.Environment.GetEnvironmentVariable("FCS_MaxTimeShare") with + | null | "" -> 100L + | s -> int64 s +#endif + + // Look for DLLs in the location of the service DLL first. +#if FABLE_COMPILER + let defaultFSharpBinariesDir = "" +#else + let defaultFSharpBinariesDir = FSharpEnvironment.BinFolderOfDefaultFSharpCompiler(Some(Path.GetDirectoryName(typeof.Assembly.Location))).Value +#endif + +[] +type FSharpFindDeclFailureReason = + + // generic reason: no particular information about error + | Unknown of message: string + + // source code file is not available + | NoSourceCode + + // trying to find declaration of ProvidedType without TypeProviderDefinitionLocationAttribute + | ProvidedType of string + + // trying to find declaration of ProvidedMember without TypeProviderDefinitionLocationAttribute + | ProvidedMember of string + +[] +type FSharpFindDeclResult = + + /// declaration not found + reason + | DeclNotFound of FSharpFindDeclFailureReason + + /// found declaration + | DeclFound of range + + /// Indicates an external declaration was found + | ExternalDecl of assembly : string * externalSym : ExternalSymbol + +/// This type is used to describe what was found during the name resolution. +/// (Depending on the kind of the items, we may stop processing or continue to find better items) +[] +type internal NameResResult = + | Members of (ItemWithInst list * DisplayEnv * range) + | Cancel of DisplayEnv * range + | Empty + | TypecheckStaleAndTextChanged + +[] +type ResolveOverloads = +| Yes +| No + +[] +type GetPreciseCompletionListFromExprTypingsResult = + | NoneBecauseTypecheckIsStaleAndTextChanged + | NoneBecauseThereWereTypeErrors + | None + | Some of (ItemWithInst list * DisplayEnv * range) * TType + +type Names = string list + +/// A TypeCheckInfo represents everything we get back from the typecheck of a file. +/// It acts like an in-memory database about the file. +/// It is effectively immutable and not updated: when we re-typecheck we just drop the previous +/// scope object on the floor and make a new one. +[] +type internal TypeCheckInfo + (// Information corresponding to miscellaneous command-line options (--define, etc). + _sTcConfig: TcConfig, + g: TcGlobals, + // The signature of the assembly being checked, up to and including the current file + ccuSigForFile: ModuleOrNamespaceType, + thisCcu: CcuThunk, + tcImports: TcImports, + tcAccessRights: AccessorDomain, + projectFileName: string, + mainInputFileName: string, + sResolutions: TcResolutions, + sSymbolUses: TcSymbolUses, + // This is a name resolution environment to use if no better match can be found. + sFallback: NameResolutionEnv, + loadClosure : LoadClosure option, + reactorOps : IReactorOperations, + textSnapshotInfo:obj option, + implFileOpt: TypedImplFile option, + openDeclarations: OpenDeclaration[]) = + + let textSnapshotInfo = defaultArg textSnapshotInfo null + + // These strings are potentially large and the editor may choose to hold them for a while. + // Use this cache to fold together data tip text results that are the same. + // Is not keyed on 'Names' collection because this is invariant for the current position in + // this unchanged file. Keyed on lineStr though to prevent a change to the currently line + // being available against a stale scope. + let getToolTipTextCache = AgedLookup>(getToolTipTextSize,areSimilar=(fun (x,y) -> x = y)) + + let amap = tcImports.GetImportMap() + let infoReader = new InfoReader(g,amap) + let ncenv = new NameResolver(g,amap,infoReader,NameResolution.FakeInstantiationGenerator) + let cenv = SymbolEnv(g, thisCcu, Some ccuSigForFile, tcImports, amap, infoReader) + + /// Find the most precise naming environment for the given line and column + let GetBestEnvForPos cursorPos = + + let mutable bestSoFar = None + + // Find the most deeply nested enclosing scope that contains given position + sResolutions.CapturedEnvs |> ResizeArray.iter (fun (possm,env,ad) -> + if rangeContainsPos possm cursorPos then + match bestSoFar with + | Some (bestm,_,_) -> + if rangeContainsRange bestm possm then + bestSoFar <- Some (possm,env,ad) + | None -> + bestSoFar <- Some (possm,env,ad)) + + let mostDeeplyNestedEnclosingScope = bestSoFar + + // Look for better subtrees on the r.h.s. of the subtree to the left of where we are + // Should really go all the way down the r.h.s. of the subtree to the left of where we are + // This is all needed when the index is floating free in the area just after the environment we really want to capture + // We guarantee to only refine to a more nested environment. It may not be strictly + // the right environment, but will always be at least as rich + + let mutable bestAlmostIncludedSoFar = None + + sResolutions.CapturedEnvs |> ResizeArray.iter (fun (possm,env,ad) -> + // take only ranges that strictly do not include cursorPos (all ranges that touch cursorPos were processed during 'Strict Inclusion' part) + if rangeBeforePos possm cursorPos && not (posEq possm.End cursorPos) then + let contained = + match mostDeeplyNestedEnclosingScope with + | Some (bestm,_,_) -> rangeContainsRange bestm possm + | None -> true + + if contained then + match bestAlmostIncludedSoFar with + | Some (rightm:range,_,_) -> + if posGt possm.End rightm.End || + (posEq possm.End rightm.End && posGt possm.Start rightm.Start) then + bestAlmostIncludedSoFar <- Some (possm,env,ad) + | _ -> bestAlmostIncludedSoFar <- Some (possm,env,ad)) + + let resEnv = + match bestAlmostIncludedSoFar, mostDeeplyNestedEnclosingScope with + | Some (_,env,ad), None -> env, ad + | Some (_,almostIncludedEnv,ad), Some (_,mostDeeplyNestedEnv,_) + when almostIncludedEnv.eFieldLabels.Count >= mostDeeplyNestedEnv.eFieldLabels.Count -> + almostIncludedEnv,ad + | _ -> + match mostDeeplyNestedEnclosingScope with + | Some (_,env,ad) -> + env,ad + | None -> + sFallback,AccessibleFromSomeFSharpCode + let pm = mkRange mainInputFileName cursorPos cursorPos + + resEnv,pm + + /// The items that come back from ResolveCompletionsInType are a bit + /// noisy. Filter a few things out. + /// + /// e.g. prefer types to constructors for FSharpToolTipText + let FilterItemsForCtors filterCtors (items: ItemWithInst list) = + let items = items |> List.filter (fun item -> match item.Item with (Item.CtorGroup _) when filterCtors = ResolveTypeNamesToTypeRefs -> false | _ -> true) + items + + // Filter items to show only valid & return Some if there are any + let ReturnItemsOfType (items: ItemWithInst list) g denv (m:range) filterCtors hasTextChangedSinceLastTypecheck = + let items = + items + |> RemoveDuplicateItems g + |> RemoveExplicitlySuppressed g + |> FilterItemsForCtors filterCtors + + if not (isNil items) then + if hasTextChangedSinceLastTypecheck(textSnapshotInfo, m) then + NameResResult.TypecheckStaleAndTextChanged // typecheck is stale, wait for second-chance IntelliSense to bring up right result + else + NameResResult.Members (items, denv, m) + else NameResResult.Empty + + let GetCapturedNameResolutions (endOfNamesPos: pos) resolveOverloads = + let filter (endPos: pos) items = + items |> ResizeArray.filter (fun (cnr: CapturedNameResolution) -> + let range = cnr.Range + range.EndLine = endPos.Line && range.EndColumn = endPos.Column) + + match resolveOverloads with + | ResolveOverloads.Yes -> + filter endOfNamesPos sResolutions.CapturedNameResolutions + + | ResolveOverloads.No -> + let items = filter endOfNamesPos sResolutions.CapturedMethodGroupResolutions + if items.Count <> 0 then + items + else + filter endOfNamesPos sResolutions.CapturedNameResolutions + + /// Looks at the exact name resolutions that occurred during type checking + /// If 'membersByResidue' is specified, we look for members of the item obtained + /// from the name resolution and filter them by the specified residue (?) + let GetPreciseItemsFromNameResolution(line, colAtEndOfNames, membersByResidue, filterCtors, resolveOverloads, hasTextChangedSinceLastTypecheck) = + let endOfNamesPos = mkPos line colAtEndOfNames + + // Logic below expects the list to be in reverse order of resolution + let cnrs = GetCapturedNameResolutions endOfNamesPos resolveOverloads |> ResizeArray.toList |> List.rev + + match cnrs, membersByResidue with + + // If we're looking for members using a residue, we'd expect only + // a single item (pick the first one) and we need the residue (which may be "") + | CNR(Item.Types(_,(ty::_)), _, denv, nenv, ad, m)::_, Some _ -> + let items = ResolveCompletionsInType ncenv nenv (ResolveCompletionTargets.All(ConstraintSolver.IsApplicableMethApprox g amap m)) m ad true ty + let items = List.map ItemWithNoInst items + ReturnItemsOfType items g denv m filterCtors hasTextChangedSinceLastTypecheck + + // Value reference from the name resolution. Primarily to disallow "let x.$ = 1" + // In most of the cases, value references can be obtained from expression typings or from environment, + // so we wouldn't have to handle values here. However, if we have something like: + // let varA = "string" + // let varA = if b then 0 else varA. + // then the expression typings get confused (thinking 'varA:int'), so we use name resolution even for usual values. + + | CNR(Item.Value(vref), occurence, denv, nenv, ad, m)::_, Some _ -> + if (occurence = ItemOccurence.Binding || occurence = ItemOccurence.Pattern) then + // Return empty list to stop further lookup - for value declarations + NameResResult.Cancel(denv, m) + else + // If we have any valid items for the value, then return completions for its type now. + // Adjust the type in case this is the 'this' pointer stored in a reference cell. + let ty = StripSelfRefCell(g, vref.BaseOrThisInfo, vref.TauType) + // patch accessibility domain to remove protected members if accessing NormalVal + let ad = + match vref.BaseOrThisInfo, ad with + | ValBaseOrThisInfo.NormalVal, AccessibleFrom(paths, Some tcref) -> + let tcref = generalizedTyconRef tcref + // check that type of value is the same or subtype of tcref + // yes - allow access to protected members + // no - strip ability to access protected members + if FSharp.Compiler.TypeRelations.TypeFeasiblySubsumesType 0 g amap m tcref FSharp.Compiler.TypeRelations.CanCoerce ty then + ad + else + AccessibleFrom(paths, None) + | _ -> ad + + let items = ResolveCompletionsInType ncenv nenv (ResolveCompletionTargets.All(ConstraintSolver.IsApplicableMethApprox g amap m)) m ad false ty + let items = List.map ItemWithNoInst items + ReturnItemsOfType items g denv m filterCtors hasTextChangedSinceLastTypecheck + + // No residue, so the items are the full resolution of the name + | CNR(_, _, denv, _, _, m) :: _, None -> + let items = + cnrs + |> List.map (fun cnr -> cnr.ItemWithInst) + // "into" is special magic syntax, not an identifier or a library call. It is part of capturedNameResolutions as an + // implementation detail of syntax coloring, but we should not report name resolution results for it, to prevent spurious QuickInfo. + |> List.filter (fun item -> match item.Item with Item.CustomOperation(CustomOperations.Into,_,_) -> false | _ -> true) + ReturnItemsOfType items g denv m filterCtors hasTextChangedSinceLastTypecheck + | _, _ -> NameResResult.Empty + + let TryGetTypeFromNameResolution(line, colAtEndOfNames, membersByResidue, resolveOverloads) = + let endOfNamesPos = mkPos line colAtEndOfNames + let items = GetCapturedNameResolutions endOfNamesPos resolveOverloads |> ResizeArray.toList |> List.rev + + match items, membersByResidue with + | CNR(Item.Types(_,(ty::_)),_,_,_,_,_)::_, Some _ -> Some ty + | CNR(Item.Value(vref), occurence,_,_,_,_)::_, Some _ -> + if (occurence = ItemOccurence.Binding || occurence = ItemOccurence.Pattern) then None + else Some (StripSelfRefCell(g, vref.BaseOrThisInfo, vref.TauType)) + | _, _ -> None + + let CollectParameters (methods: MethInfo list) amap m: Item list = + methods + |> List.collect (fun meth -> + match meth.GetParamDatas(amap, m, meth.FormalMethodInst) with + | x::_ -> x |> List.choose(fun (ParamData(_isParamArray, _isInArg, _isOutArg, _optArgInfo, _callerInfo, name, _, ty)) -> + match name with + | Some n -> Some (Item.ArgName(n, ty, Some (ArgumentContainer.Method meth))) + | None -> None + ) + | _ -> [] + ) + + let GetNamedParametersAndSettableFields endOfExprPos hasTextChangedSinceLastTypecheck = + let cnrs = GetCapturedNameResolutions endOfExprPos ResolveOverloads.No |> ResizeArray.toList |> List.rev + let result = + match cnrs with + | CNR(Item.CtorGroup(_, ((ctor::_) as ctors)), _, denv, nenv, ad, m) ::_ -> + let props = ResolveCompletionsInType ncenv nenv ResolveCompletionTargets.SettablePropertiesAndFields m ad false ctor.ApparentEnclosingType + let parameters = CollectParameters ctors amap m + let items = props @ parameters + Some (denv, m, items) + | CNR(Item.MethodGroup(_, methods, _), _, denv, nenv, ad, m) ::_ -> + let props = + methods + |> List.collect (fun meth -> + let retTy = meth.GetFSharpReturnTy(amap, m, meth.FormalMethodInst) + ResolveCompletionsInType ncenv nenv ResolveCompletionTargets.SettablePropertiesAndFields m ad false retTy + ) + let parameters = CollectParameters methods amap m + let items = props @ parameters + Some (denv, m, items) + | _ -> + None + match result with + | None -> + NameResResult.Empty + | Some (denv, m, items) -> + let items = List.map ItemWithNoInst items + ReturnItemsOfType items g denv m TypeNameResolutionFlag.ResolveTypeNamesToTypeRefs hasTextChangedSinceLastTypecheck + + /// finds captured typing for the given position + let GetExprTypingForPosition(endOfExprPos) = + let quals = + sResolutions.CapturedExpressionTypings + |> Seq.filter (fun (ty,nenv,_,m) -> + // We only want expression types that end at the particular position in the file we are looking at. + posEq m.End endOfExprPos && + + // Get rid of function types. True, given a 2-arg curried function "f x y", it is legal to do "(f x).GetType()", + // but you almost never want to do this in practice, and we choose not to offer up any intellisense for + // F# function types. + not (isFunTy nenv.DisplayEnv.g ty)) + |> Seq.toArray + + let thereWereSomeQuals = not (Array.isEmpty quals) + // filter out errors + + let quals = quals + |> Array.filter (fun (ty,nenv,_,_) -> + let denv = nenv.DisplayEnv + not (isTyparTy denv.g ty && (destTyparTy denv.g ty).IsFromError)) + thereWereSomeQuals, quals + + /// obtains captured typing for the given position + /// if type of captured typing is record - returns list of record fields + let GetRecdFieldsForExpr(r : range) = + let _, quals = GetExprTypingForPosition(r.End) + let bestQual = + match quals with + | [||] -> None + | quals -> + quals |> Array.tryFind (fun (_,_,_,rq) -> + ignore(r) // for breakpoint + posEq r.Start rq.Start) + match bestQual with + | Some (ty,nenv,ad,m) when isRecdTy nenv.DisplayEnv.g ty -> + let items = NameResolution.ResolveRecordOrClassFieldsOfType ncenv m ad ty false + Some (items, nenv.DisplayEnv, m) + | _ -> None + + /// Looks at the exact expression types at the position to the left of the + /// residue then the source when it was typechecked. + let GetPreciseCompletionListFromExprTypings(parseResults:FSharpParseFileResults, endOfExprPos, filterCtors, hasTextChangedSinceLastTypecheck: (obj * range -> bool)) = + + let thereWereSomeQuals, quals = GetExprTypingForPosition(endOfExprPos) + + match quals with + | [| |] -> + if thereWereSomeQuals then + GetPreciseCompletionListFromExprTypingsResult.NoneBecauseThereWereTypeErrors + else + GetPreciseCompletionListFromExprTypingsResult.None + | _ -> + let bestQual, textChanged = + match parseResults.ParseTree with + | Some(input) -> + match UntypedParseImpl.GetRangeOfExprLeftOfDot(endOfExprPos,Some(input)) with // TODO we say "colAtEndOfNames" everywhere, but that's not really a good name ("foo . $" hit Ctrl-Space at $) + | Some( exprRange) -> + if hasTextChangedSinceLastTypecheck(textSnapshotInfo, exprRange) then + None, true // typecheck is stale, wait for second-chance IntelliSense to bring up right result + else + // See bug 130733. We have an up-to-date sync parse, and know the exact range of the prior expression. + // The quals all already have the same ending position, so find one with a matching starting position, if it exists. + // If not, then the stale typecheck info does not have a capturedExpressionTyping for this exact expression, and the + // user can wait for typechecking to catch up and second-chance intellisense to give the right result. + let qual = + quals |> Array.tryFind (fun (_,_,_,r) -> + ignore(r) // for breakpoint + posEq exprRange.Start r.Start) + qual, false + | None -> + // TODO In theory I think we should never get to this code path; it would be nice to add an assert. + // In practice, we do get here in some weird cases like "2.0 .. 3.0" and hitting Ctrl-Space in between the two dots of the range operator. + // I wasn't able to track down what was happening in those weird cases, not worth worrying about, it doesn't manifest as a product bug or anything. + None, false + | _ -> None, false + + match bestQual with + | Some bestQual -> + let (ty,nenv,ad,m) = bestQual + let items = ResolveCompletionsInType ncenv nenv (ResolveCompletionTargets.All(ConstraintSolver.IsApplicableMethApprox g amap m)) m ad false ty + let items = items |> List.map ItemWithNoInst + let items = items |> RemoveDuplicateItems g + let items = items |> RemoveExplicitlySuppressed g + let items = items |> FilterItemsForCtors filterCtors + GetPreciseCompletionListFromExprTypingsResult.Some((items,nenv.DisplayEnv,m), ty) + | None -> + if textChanged then GetPreciseCompletionListFromExprTypingsResult.NoneBecauseTypecheckIsStaleAndTextChanged + else GetPreciseCompletionListFromExprTypingsResult.None + + /// Find items in the best naming environment. + let GetEnvironmentLookupResolutions(nenv, ad, m, plid, filterCtors, showObsolete) = + let items = NameResolution.ResolvePartialLongIdent ncenv nenv (ConstraintSolver.IsApplicableMethApprox g amap m) m ad plid showObsolete + let items = items |> List.map ItemWithNoInst + let items = items |> RemoveDuplicateItems g + let items = items |> RemoveExplicitlySuppressed g + let items = items |> FilterItemsForCtors filterCtors + (items, nenv.DisplayEnv, m) + + /// Find items in the best naming environment. + let GetEnvironmentLookupResolutionsAtPosition(cursorPos, plid, filterCtors, showObsolete) = + let (nenv,ad),m = GetBestEnvForPos cursorPos + GetEnvironmentLookupResolutions(nenv, ad, m, plid, filterCtors, showObsolete) + + /// Find record fields in the best naming environment. + let GetClassOrRecordFieldsEnvironmentLookupResolutions(cursorPos, plid) = + let (nenv, ad),m = GetBestEnvForPos cursorPos + let items = NameResolution.ResolvePartialLongIdentToClassOrRecdFields ncenv nenv m ad plid false + let items = items |> List.map ItemWithNoInst + let items = items |> RemoveDuplicateItems g + let items = items |> RemoveExplicitlySuppressed g + items, nenv.DisplayEnv, m + + /// Resolve a location and/or text to items. + // Three techniques are used + // - look for an exact known name resolution from type checking + // - use the known type of an expression, e.g. (expr).Name, to generate an item list + // - lookup an entire name in the name resolution environment, e.g. A.B.Name, to generate an item list + // + // The overall aim is to resolve as accurately as possible based on what we know from type inference + + let GetBaseClassCandidates = function + | Item.ModuleOrNamespaces _ -> true + | Item.Types(_, ty::_) when (isClassTy g ty) && not (isSealedTy g ty) -> true + | _ -> false + + let GetInterfaceCandidates = function + | Item.ModuleOrNamespaces _ -> true + | Item.Types(_, ty::_) when (isInterfaceTy g ty) -> true + | _ -> false + + + // Return only items with the specified name + let FilterDeclItemsByResidue (getItem: 'a -> Item) residue (items: 'a list) = + let attributedResidue = residue + "Attribute" + let nameMatchesResidue name = (residue = name) || (attributedResidue = name) + + items |> List.filter (fun x -> + let item = getItem x + let n1 = item.DisplayName + match item with + | Item.Types _ -> nameMatchesResidue n1 + | Item.CtorGroup (_, meths) -> + nameMatchesResidue n1 || + meths |> List.exists (fun meth -> + let tcref = meth.ApparentEnclosingTyconRef +#if !NO_EXTENSIONTYPING + tcref.IsProvided || +#endif + nameMatchesResidue tcref.DisplayName) + | _ -> residue = n1) + + /// Post-filter items to make sure they have precisely the right name + /// This also checks that there are some remaining results + /// exactMatchResidueOpt = Some _ -- means that we are looking for exact matches + let FilterRelevantItemsBy (getItem: 'a -> Item) (exactMatchResidueOpt : _ option) check (items: 'a list, denv, m) = + + // can throw if type is in located in non-resolved CCU: i.e. bigint if reference to System.Numerics is absent + let safeCheck item = try check item with _ -> false + + // Are we looking for items with precisely the given name? + if not (isNil items) && exactMatchResidueOpt.IsSome then + let items = items |> FilterDeclItemsByResidue getItem exactMatchResidueOpt.Value |> List.filter safeCheck + if not (isNil items) then Some(items, denv, m) else None + else + // When (items = []) we must returns Some([],..) and not None + // because this value is used if we want to stop further processing (e.g. let x.$ = ...) + let items = items |> List.filter safeCheck + Some(items, denv, m) + + /// Post-filter items to make sure they have precisely the right name + /// This also checks that there are some remaining results + let (|FilterRelevantItems|_|) getItem exactMatchResidueOpt orig = + FilterRelevantItemsBy getItem exactMatchResidueOpt (fun _ -> true) orig + + /// Find the first non-whitespace position in a line prior to the given character + let FindFirstNonWhitespacePosition (lineStr: string) i = + if i >= lineStr.Length then None + else + let mutable p = i + while p >= 0 && System.Char.IsWhiteSpace(lineStr.[p]) do + p <- p - 1 + if p >= 0 then Some p else None + + let CompletionItem (ty: ValueOption) (assemblySymbol: ValueOption) (item: ItemWithInst) = + let kind = + match item.Item with + | Item.MethodGroup (_, minfo :: _, _) -> CompletionItemKind.Method minfo.IsExtensionMember + | Item.RecdField _ + | Item.Property _ -> CompletionItemKind.Property + | Item.Event _ -> CompletionItemKind.Event + | Item.ILField _ + | Item.Value _ -> CompletionItemKind.Field + | Item.CustomOperation _ -> CompletionItemKind.CustomOperation + | _ -> CompletionItemKind.Other + + { ItemWithInst = item + MinorPriority = 0 + Kind = kind + IsOwnMember = false + Type = match ty with ValueSome x -> Some x | _ -> None + Unresolved = match assemblySymbol with ValueSome x -> Some x.UnresolvedSymbol | _ -> None } + + let DefaultCompletionItem item = CompletionItem ValueNone ValueNone item + + let getItem (x: ItemWithInst) = x.Item + let GetDeclaredItems (parseResultsOpt: FSharpParseFileResults option, lineStr: string, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, + filterCtors, resolveOverloads, hasTextChangedSinceLastTypecheck, isInRangeOperator, allSymbols: unit -> AssemblySymbol list) = + + // Are the last two chars (except whitespaces) = ".." + let isLikeRangeOp = + match FindFirstNonWhitespacePosition lineStr (colAtEndOfNamesAndResidue - 1) with + | Some x when x >= 1 && lineStr.[x] = '.' && lineStr.[x - 1] = '.' -> true + | _ -> false + + // if last two chars are .. and we are not in range operator context - no completion + if isLikeRangeOp && not isInRangeOperator then None else + + // Try to use the exact results of name resolution during type checking to generate the results + // This is based on position (i.e. colAtEndOfNamesAndResidue). This is not used if a residueOpt is given. + let nameResItems = + match residueOpt with + | None -> GetPreciseItemsFromNameResolution(line, colAtEndOfNamesAndResidue, None, filterCtors,resolveOverloads, hasTextChangedSinceLastTypecheck) + | Some residue -> + // deals with cases when we have spaces between dot and\or identifier, like A . $ + // if this is our case - then we need to locate end position of the name skipping whitespaces + // this allows us to handle cases like: let x . $ = 1 + match lastDotPos |> Option.orElseWith (fun _ -> FindFirstNonWhitespacePosition lineStr (colAtEndOfNamesAndResidue - 1)) with + | Some p when lineStr.[p] = '.' -> + match FindFirstNonWhitespacePosition lineStr (p - 1) with + | Some colAtEndOfNames -> + let colAtEndOfNames = colAtEndOfNames + 1 // convert 0-based to 1-based + GetPreciseItemsFromNameResolution(line, colAtEndOfNames, Some(residue), filterCtors,resolveOverloads, hasTextChangedSinceLastTypecheck) + | None -> NameResResult.Empty + | _ -> NameResResult.Empty + + // Normalize to form A.B.C.D where D is the residue. It may be empty for "A.B.C." + // residueOpt = Some when we are looking for the exact match + let plid, exactMatchResidueOpt = + match origLongIdentOpt, residueOpt with + | None, _ -> [], None + | Some(origLongIdent), Some _ -> origLongIdent, None + | Some(origLongIdent), None -> + System.Diagnostics.Debug.Assert(not (isNil origLongIdent), "origLongIdent is empty") + // note: as above, this happens when we are called for "precise" resolution - (F1 keyword, data tip etc..) + let plid, residue = List.frontAndBack origLongIdent + plid, Some residue + + let pos = mkPos line loc + let (nenv, ad), m = GetBestEnvForPos pos + + let getType() = + match NameResolution.TryToResolveLongIdentAsType ncenv nenv m plid with + | Some x -> tryTcrefOfAppTy g x + | None -> + match lastDotPos |> Option.orElseWith (fun _ -> FindFirstNonWhitespacePosition lineStr (colAtEndOfNamesAndResidue - 1)) with + | Some p when lineStr.[p] = '.' -> + match FindFirstNonWhitespacePosition lineStr (p - 1) with + | Some colAtEndOfNames -> + let colAtEndOfNames = colAtEndOfNames + 1 // convert 0-based to 1-based + match TryGetTypeFromNameResolution(line, colAtEndOfNames, residueOpt, resolveOverloads) with + | Some x -> tryTcrefOfAppTy g x + | _ -> ValueNone + | None -> ValueNone + | _ -> ValueNone + + match nameResItems with + | NameResResult.TypecheckStaleAndTextChanged -> None // second-chance intellisense will try again + | NameResResult.Cancel(denv,m) -> Some([], denv, m) + | NameResResult.Members(FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m)) -> + // lookup based on name resolution results successful + Some (items |> List.map (CompletionItem (getType()) ValueNone), denv, m) + | _ -> + match origLongIdentOpt with + | None -> None + | Some _ -> + + // Try to use the type of the expression on the left to help generate a completion list + let qualItems, thereIsADotInvolved = + match parseResultsOpt with + | None -> + // Note, you will get here if the 'reason' is not CompleteWord/MemberSelect/DisplayMemberList, as those are currently the + // only reasons we do a sync parse to have the most precise and likely-to-be-correct-and-up-to-date info. So for example, + // if you do QuickInfo hovering over A in "f(x).A()", you will only get a tip if typechecking has a name-resolution recorded + // for A, not if merely we know the capturedExpressionTyping of f(x) and you very recently typed ".A()" - in that case, + // you won't won't get a tip until the typechecking catches back up. + GetPreciseCompletionListFromExprTypingsResult.None, false + | Some parseResults -> + + match UntypedParseImpl.TryFindExpressionASTLeftOfDotLeftOfCursor(mkPos line colAtEndOfNamesAndResidue,parseResults.ParseTree) with + | Some(pos,_) -> + GetPreciseCompletionListFromExprTypings(parseResults, pos, filterCtors, hasTextChangedSinceLastTypecheck), true + | None -> + // Can get here in a case like: if "f xxx yyy" is legal, and we do "f xxx y" + // We have no interest in expression typings, those are only useful for dot-completion. We want to fallback + // to "Use an environment lookup as the last resort" below + GetPreciseCompletionListFromExprTypingsResult.None, false + + match qualItems,thereIsADotInvolved with + | GetPreciseCompletionListFromExprTypingsResult.Some(FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m), ty), _ + // Initially we only use the expression typings when looking up, e.g. (expr).Nam or (expr).Name1.Nam + // These come through as an empty plid and residue "". Otherwise we try an environment lookup + // and then return to the qualItems. This is because the expression typings are a little inaccurate, primarily because + // it appears we're getting some typings recorded for non-atomic expressions like "f x" + when isNil plid -> + // lookup based on expression typings successful + Some (items |> List.map (CompletionItem (tryTcrefOfAppTy g ty) ValueNone), denv, m) + | GetPreciseCompletionListFromExprTypingsResult.NoneBecauseThereWereTypeErrors, _ -> + // There was an error, e.g. we have "." and there is an error determining the type of + // In this case, we don't want any of the fallback logic, rather, we want to produce zero results. + None + | GetPreciseCompletionListFromExprTypingsResult.NoneBecauseTypecheckIsStaleAndTextChanged, _ -> + // we want to report no result and let second-chance intellisense kick in + None + | _, true when isNil plid -> + // If the user just pressed '.' after an _expression_ (not a plid), it is never right to show environment-lookup top-level completions. + // The user might by typing quickly, and the LS didn't have an expression type right before the dot yet. + // Second-chance intellisense will bring up the correct list in a moment. + None + | _ -> + // Use an environment lookup as the last resort + let envItems, denv, m = GetEnvironmentLookupResolutions(nenv, ad, m, plid, filterCtors, residueOpt.IsSome) + + let envResult = + match nameResItems, (envItems, denv, m), qualItems with + + // First, use unfiltered name resolution items, if they're not empty + | NameResResult.Members(items, denv, m), _, _ when not (isNil items) -> + // lookup based on name resolution results successful + ValueSome(items |> List.map (CompletionItem (getType()) ValueNone), denv, m) + + // If we have nonempty items from environment that were resolved from a type, then use them... + // (that's better than the next case - here we'd return 'int' as a type) + | _, FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m), _ when not (isNil items) -> + // lookup based on name and environment successful + ValueSome(items |> List.map (CompletionItem (getType()) ValueNone), denv, m) + + // Try again with the qualItems + | _, _, GetPreciseCompletionListFromExprTypingsResult.Some(FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m), ty) -> + ValueSome(items |> List.map (CompletionItem (tryTcrefOfAppTy g ty) ValueNone), denv, m) + + | _ -> ValueNone + + let globalResult = + match origLongIdentOpt with + | None | Some [] -> + let globalItems = + allSymbols() + |> List.filter (fun x -> + not x.Symbol.IsExplicitlySuppressed && + + match x.Symbol with + | :? FSharpMemberOrFunctionOrValue as m when m.IsConstructor && filterCtors = ResolveTypeNamesToTypeRefs -> false + | _ -> true) + + let getItem (x: AssemblySymbol) = x.Symbol.Item + + match globalItems, denv, m with + | FilterRelevantItems getItem exactMatchResidueOpt (globalItemsFiltered, denv, m) when not (isNil globalItemsFiltered) -> + globalItemsFiltered + |> List.map(fun globalItem -> CompletionItem (getType()) (ValueSome globalItem) (ItemWithNoInst globalItem.Symbol.Item)) + |> fun r -> ValueSome(r, denv, m) + | _ -> ValueNone + | _ -> ValueNone // do not return unresolved items after dot + + match envResult, globalResult with + | ValueSome (items, denv, m), ValueSome (gItems,_,_) -> Some (items @ gItems, denv, m) + | ValueSome x, ValueNone -> Some x + | ValueNone, ValueSome y -> Some y + | ValueNone, ValueNone -> None + + + let toCompletionItems (items: ItemWithInst list, denv: DisplayEnv, m: range ) = + items |> List.map DefaultCompletionItem, denv, m + + /// Get the auto-complete items at a particular location. + let GetDeclItemsForNamesAtPosition(ctok: CompilationThreadToken, parseResultsOpt: FSharpParseFileResults option, origLongIdentOpt: string list option, + residueOpt:string option, lastDotPos: int option, line:int, lineStr:string, colAtEndOfNamesAndResidue, filterCtors, resolveOverloads, + getAllSymbols: unit -> AssemblySymbol list, hasTextChangedSinceLastTypecheck: (obj * range -> bool)) + : (CompletionItem list * DisplayEnv * CompletionContext option * range) option = + RequireCompilationThread ctok // the operations in this method need the reactor thread + + let loc = + match colAtEndOfNamesAndResidue with + | pastEndOfLine when pastEndOfLine >= lineStr.Length -> lineStr.Length + | atDot when lineStr.[atDot] = '.' -> atDot + 1 + | atStart when atStart = 0 -> 0 + | otherwise -> otherwise - 1 + + // Look for a "special" completion context + let completionContext = + parseResultsOpt + |> Option.bind (fun x -> x.ParseTree) + |> Option.bind (fun parseTree -> UntypedParseImpl.TryGetCompletionContext(mkPos line colAtEndOfNamesAndResidue, parseTree, lineStr)) + + let res = + match completionContext with + // Invalid completion locations + | Some CompletionContext.Invalid -> None + + // Completion at 'inherit C(...)" + | Some (CompletionContext.Inherit(InheritanceContext.Class, (plid, _))) -> + GetEnvironmentLookupResolutionsAtPosition(mkPos line loc, plid, filterCtors, false) + |> FilterRelevantItemsBy getItem None (getItem >> GetBaseClassCandidates) + |> Option.map toCompletionItems + + // Completion at 'interface ..." + | Some (CompletionContext.Inherit(InheritanceContext.Interface, (plid, _))) -> + GetEnvironmentLookupResolutionsAtPosition(mkPos line loc, plid, filterCtors, false) + |> FilterRelevantItemsBy getItem None (getItem >> GetInterfaceCandidates) + |> Option.map toCompletionItems + + // Completion at 'implement ..." + | Some (CompletionContext.Inherit(InheritanceContext.Unknown, (plid, _))) -> + GetEnvironmentLookupResolutionsAtPosition(mkPos line loc, plid, filterCtors, false) + |> FilterRelevantItemsBy getItem None (getItem >> (fun t -> GetBaseClassCandidates t || GetInterfaceCandidates t)) + |> Option.map toCompletionItems + + // Completion at ' { XXX = ... } " + | Some(CompletionContext.RecordField(RecordContext.New(plid, _))) -> + // { x. } can be either record construction or computation expression. Try to get all visible record fields first + match GetClassOrRecordFieldsEnvironmentLookupResolutions(mkPos line loc, plid) |> toCompletionItems with + | [],_,_ -> + // no record fields found, return completion list as if we were outside any computation expression + GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors,resolveOverloads, hasTextChangedSinceLastTypecheck, false, fun() -> []) + | result -> Some(result) + + // Completion at ' { XXX = ... with ... } " + | Some(CompletionContext.RecordField(RecordContext.CopyOnUpdate(r, (plid, _)))) -> + match GetRecdFieldsForExpr(r) with + | None -> + Some (GetClassOrRecordFieldsEnvironmentLookupResolutions(mkPos line loc, plid)) + |> Option.map toCompletionItems + | Some (items, denv, m) -> + Some (List.map ItemWithNoInst items, denv, m) + |> Option.map toCompletionItems + + // Completion at ' { XXX = ... with ... } " + | Some(CompletionContext.RecordField(RecordContext.Constructor(typeName))) -> + Some(GetClassOrRecordFieldsEnvironmentLookupResolutions(mkPos line loc, [typeName])) + |> Option.map toCompletionItems + + // Completion at ' SomeMethod( ... ) ' with named arguments + | Some(CompletionContext.ParameterList (endPos, fields)) -> + let results = GetNamedParametersAndSettableFields endPos hasTextChangedSinceLastTypecheck + + let declaredItems = + GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors, resolveOverloads, + hasTextChangedSinceLastTypecheck, false, getAllSymbols) + + match results with + | NameResResult.Members(items, denv, m) -> + let filtered = + items + |> RemoveDuplicateItems g + |> RemoveExplicitlySuppressed g + |> List.filter (fun item -> not (fields.Contains item.Item.DisplayName)) + |> List.map (fun item -> + { ItemWithInst = item + Kind = CompletionItemKind.Argument + MinorPriority = 0 + IsOwnMember = false + Type = None + Unresolved = None }) + match declaredItems with + | None -> Some (toCompletionItems (items, denv, m)) + | Some (declItems, declaredDisplayEnv, declaredRange) -> Some (filtered @ declItems, declaredDisplayEnv, declaredRange) + | _ -> declaredItems + + | Some(CompletionContext.AttributeApplication) -> + GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors, resolveOverloads, hasTextChangedSinceLastTypecheck, false, getAllSymbols) + |> Option.map (fun (items, denv, m) -> + items + |> List.filter (fun cItem -> + match cItem.Item with + | Item.ModuleOrNamespaces _ -> true + | _ when IsAttribute infoReader cItem.Item -> true + | _ -> false), denv, m) + + | Some(CompletionContext.OpenDeclaration) -> + GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors, resolveOverloads, hasTextChangedSinceLastTypecheck, false, getAllSymbols) + |> Option.map (fun (items, denv, m) -> + items + |> List.filter (fun x -> + match x.Item with + | Item.ModuleOrNamespaces _ -> true + | Item.Types (_, tcrefs) when tcrefs |> List.exists (fun ty -> isAppTy g ty && isStaticClass g (tcrefOfAppTy g ty)) -> true + | _ -> false), denv, m) + + // Completion at '(x: ...)" + | Some (CompletionContext.PatternType) -> + GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors, resolveOverloads, hasTextChangedSinceLastTypecheck, false, getAllSymbols) + |> Option.map (fun (items, denv, m) -> + items + |> List.filter (fun cItem -> + match cItem.Item with + | Item.ModuleOrNamespaces _ + | Item.Types _ + | Item.UnqualifiedType _ + | Item.ExnCase _ -> true + | _ -> false), denv, m) + + // Other completions + | cc -> + match residueOpt |> Option.bind Seq.tryHead with + | Some ''' -> + // The last token in + // let x = 'E + // is Ident with text "'E", however it's either unfinished char literal or generic parameter. + // We should not provide any completion in the former case, and we don't provide it for the latter one for now + // because providing generic parameters list is context aware, which we don't have here (yet). + None + | _ -> + let isInRangeOperator = (match cc with Some (CompletionContext.RangeOperator) -> true | _ -> false) + GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, + residueOpt, lastDotPos, line, loc, filterCtors, resolveOverloads, + hasTextChangedSinceLastTypecheck, isInRangeOperator, getAllSymbols) + + res |> Option.map (fun (items, denv, m) -> items, denv, completionContext, m) + + /// Return 'false' if this is not a completion item valid in an interface file. + let IsValidSignatureFileItem item = + match item with + | Item.Types _ | Item.ModuleOrNamespaces _ -> true + | _ -> false + + /// Find the most precise display context for the given line and column. + member __.GetBestDisplayEnvForPos cursorPos = GetBestEnvForPos cursorPos + + member __.GetVisibleNamespacesAndModulesAtPosition(cursorPos: pos) : ModuleOrNamespaceRef list = + let (nenv, ad), m = GetBestEnvForPos cursorPos + NameResolution.GetVisibleNamespacesAndModulesAtPoint ncenv nenv m ad + + /// Determines if a long ident is resolvable at a specific point. + member __.IsRelativeNameResolvable(cursorPos: pos, plid: string list, item: Item) : bool = + ErrorScope.Protect + Range.range0 + (fun () -> + /// Find items in the best naming environment. + let (nenv, ad), m = GetBestEnvForPos cursorPos + NameResolution.IsItemResolvable ncenv nenv m ad plid item) + (fun msg -> + Trace.TraceInformation(sprintf "FCS: recovering from error in IsRelativeNameResolvable: '%s'" msg) + false) + + /// Determines if a long ident is resolvable at a specific point. + member scope.IsRelativeNameResolvableFromSymbol(cursorPos: pos, plid: string list, symbol: FSharpSymbol) : bool = + scope.IsRelativeNameResolvable(cursorPos, plid, symbol.Item) + + /// Get the auto-complete items at a location + member __.GetDeclarations (ctok, parseResultsOpt, line, lineStr, partialName, getAllEntities, hasTextChangedSinceLastTypecheck) = + let isInterfaceFile = SourceFileImpl.IsInterfaceFile mainInputFileName + ErrorScope.Protect Range.range0 + (fun () -> + + let declItemsOpt = + GetDeclItemsForNamesAtPosition(ctok, parseResultsOpt, Some partialName.QualifyingIdents, + Some partialName.PartialIdent, partialName.LastDotPos, line, + lineStr, partialName.EndColumn + 1, ResolveTypeNamesToCtors, ResolveOverloads.Yes, + getAllEntities, hasTextChangedSinceLastTypecheck) + + match declItemsOpt with + | None -> FSharpDeclarationListInfo.Empty + | Some (items, denv, ctx, m) -> + let items = if isInterfaceFile then items |> List.filter (fun x -> IsValidSignatureFileItem x.Item) else items + let getAccessibility item = FSharpSymbol.GetAccessibility (FSharpSymbol.Create(cenv, item)) + let currentNamespaceOrModule = + parseResultsOpt + |> Option.bind (fun x -> x.ParseTree) + |> Option.map (fun parsedInput -> UntypedParseImpl.GetFullNameOfSmallestModuleOrNamespaceAtPoint(parsedInput, mkPos line 0)) + let isAttributeApplication = ctx = Some CompletionContext.AttributeApplication + FSharpDeclarationListInfo.Create(infoReader,m,denv,getAccessibility,items,reactorOps,currentNamespaceOrModule,isAttributeApplication)) + (fun msg -> + Trace.TraceInformation(sprintf "FCS: recovering from error in GetDeclarations: '%s'" msg) + FSharpDeclarationListInfo.Error msg) + + /// Get the symbols for auto-complete items at a location + member __.GetDeclarationListSymbols (ctok, parseResultsOpt, line, lineStr, partialName, getAllEntities, hasTextChangedSinceLastTypecheck) = + let isInterfaceFile = SourceFileImpl.IsInterfaceFile mainInputFileName + ErrorScope.Protect Range.range0 + (fun () -> + + let declItemsOpt = + GetDeclItemsForNamesAtPosition(ctok, parseResultsOpt, Some partialName.QualifyingIdents, + Some partialName.PartialIdent, partialName.LastDotPos, line, lineStr, + partialName.EndColumn + 1, ResolveTypeNamesToCtors, ResolveOverloads.Yes, + getAllEntities, hasTextChangedSinceLastTypecheck) + + match declItemsOpt with + | None -> List.Empty + | Some (items, denv, _, m) -> + let items = if isInterfaceFile then items |> List.filter (fun x -> IsValidSignatureFileItem x.Item) else items + + //do filtering like Declarationset + let items = items |> RemoveExplicitlySuppressedCompletionItems g + + // Sort by name. For things with the same name, + // - show types with fewer generic parameters first + // - show types before over other related items - they usually have very useful XmlDocs + let items = + items |> List.sortBy (fun d -> + let n = + match d.Item with + | Item.Types (_,(TType_app(tcref,_) :: _)) -> 1 + tcref.TyparsNoRange.Length + // Put delegate ctors after types, sorted by #typars. RemoveDuplicateItems will remove FakeInterfaceCtor and DelegateCtor if an earlier type is also reported with this name + | Item.FakeInterfaceCtor (TType_app(tcref,_)) + | Item.DelegateCtor (TType_app(tcref,_)) -> 1000 + tcref.TyparsNoRange.Length + // Put type ctors after types, sorted by #typars. RemoveDuplicateItems will remove DefaultStructCtors if a type is also reported with this name + | Item.CtorGroup (_, (cinfo :: _)) -> 1000 + 10 * cinfo.DeclaringTyconRef.TyparsNoRange.Length + | _ -> 0 + (d.Item.DisplayName, n)) + + // Remove all duplicates. We've put the types first, so this removes the DelegateCtor and DefaultStructCtor's. + let items = items |> RemoveDuplicateCompletionItems g + + // Group by compiled name for types, display name for functions + // (We don't want types with the same display name to be grouped as overloads) + let items = + items |> List.groupBy (fun d -> + match d.Item with + | Item.Types (_,(TType_app(tcref,_) :: _)) + | Item.ExnCase tcref -> tcref.LogicalName + | Item.UnqualifiedType(tcref :: _) + | Item.FakeInterfaceCtor (TType_app(tcref,_)) + | Item.DelegateCtor (TType_app(tcref,_)) -> tcref.CompiledName + | Item.CtorGroup (_, (cinfo :: _)) -> + cinfo.ApparentEnclosingTyconRef.CompiledName + | _ -> d.Item.DisplayName) + + // Filter out operators (and list) + let items = + // Check whether this item looks like an operator. + let isOpItem(nm, item: CompletionItem list) = + match item |> List.map (fun x -> x.Item) with + | [Item.Value _] + | [Item.MethodGroup(_,[_],_)] -> IsOperatorName nm + | [Item.UnionCase _] -> IsOperatorName nm + | _ -> false + + let isFSharpList nm = (nm = "[]") // list shows up as a Type and a UnionCase, only such entity with a symbolic name, but want to filter out of intellisense + + items |> List.filter (fun (nm,items) -> not (isOpItem(nm,items)) && not(isFSharpList nm)) + + let items = + // Filter out duplicate names + items |> List.map (fun (_nm,itemsWithSameName) -> + match itemsWithSameName with + | [] -> failwith "Unexpected empty bag" + | items -> + items + |> List.map (fun item -> let symbol = FSharpSymbol.Create(cenv, item.Item) + FSharpSymbolUse(g, denv, symbol, ItemOccurence.Use, m))) + + //end filtering + items) + (fun msg -> + Trace.TraceInformation(sprintf "FCS: recovering from error in GetDeclarationListSymbols: '%s'" msg) + []) + + /// Get the "reference resolution" tooltip for at a location + member __.GetReferenceResolutionStructuredToolTipText(ctok, line,col) = + + RequireCompilationThread ctok // the operations in this method need the reactor thread but the reasons why are not yet grounded + + let pos = mkPos line col + let isPosMatch(pos, ar:AssemblyReference) : bool = + let isRangeMatch = (Range.rangeContainsPos ar.Range pos) + let isNotSpecialRange = not (Range.equals ar.Range rangeStartup) && not (Range.equals ar.Range range0) && not (Range.equals ar.Range rangeCmdArgs) + let isMatch = isRangeMatch && isNotSpecialRange + isMatch + + let dataTipOfReferences() = + let matches = + match loadClosure with + | None -> [] + | Some(loadClosure) -> + loadClosure.References + |> List.map snd + |> List.concat + |> List.filter(fun ar->isPosMatch(pos, ar.originalReference)) + + match matches with + | resolved::_ // Take the first seen + | [resolved] -> + let tip = wordL (TaggedTextOps.tagStringLiteral((resolved.prepareToolTip ()).TrimEnd([|'\n'|]))) + FSharpStructuredToolTipText.FSharpToolTipText [FSharpStructuredToolTipElement.Single(tip, FSharpXmlDoc.None)] + + | [] -> FSharpStructuredToolTipText.FSharpToolTipText [] + + ErrorScope.Protect Range.range0 + dataTipOfReferences + (fun err -> + Trace.TraceInformation(sprintf "FCS: recovering from error in GetReferenceResolutionStructuredToolTipText: '%s'" err) + FSharpToolTipText [FSharpStructuredToolTipElement.CompositionError err]) + + // GetToolTipText: return the "pop up" (or "Quick Info") text given a certain context. + member __.GetStructuredToolTipText(ctok, line, lineStr, colAtEndOfNames, names) = + let Compute() = + ErrorScope.Protect Range.range0 + (fun () -> + let declItemsOpt = + GetDeclItemsForNamesAtPosition(ctok, None, Some names, None, None, + line, lineStr, colAtEndOfNames, ResolveTypeNamesToCtors, + ResolveOverloads.Yes, (fun() -> []), (fun _ -> false)) + + match declItemsOpt with + | None -> FSharpToolTipText [] + | Some(items, denv, _, m) -> + FSharpToolTipText(items |> List.map (fun x -> FormatStructuredDescriptionOfItem false infoReader m denv x.ItemWithInst))) + + (fun err -> + Trace.TraceInformation(sprintf "FCS: recovering from error in GetStructuredToolTipText: '%s'" err) + FSharpToolTipText [FSharpStructuredToolTipElement.CompositionError err]) + + // See devdiv bug 646520 for rationale behind truncating and caching these quick infos (they can be big!) + let key = line,colAtEndOfNames,lineStr + match getToolTipTextCache.TryGet (ctok, key) with + | Some res -> res + | None -> + let res = Compute() + getToolTipTextCache.Put(ctok, key,res) + res + + member __.GetF1Keyword (ctok, line, lineStr, colAtEndOfNames, names) : string option = + ErrorScope.Protect Range.range0 + (fun () -> + + let declItemsOpt = + GetDeclItemsForNamesAtPosition(ctok, None, Some names, None, None, + line, lineStr, colAtEndOfNames, ResolveTypeNamesToCtors, + ResolveOverloads.No, (fun() -> []), (fun _ -> false)) + + match declItemsOpt with + | None -> None + | Some (items: CompletionItem list, _,_, _) -> + match items with + | [] -> None + | [item] -> + GetF1Keyword g item.Item + | _ -> + // handle new Type() + let allTypes, constr, ty = + List.fold + (fun (allTypes,constr,ty) (item: CompletionItem) -> + match item.Item, constr, ty with + | (Item.Types _) as t, _, None -> allTypes, constr, Some t + | (Item.Types _), _, _ -> allTypes, constr, ty + | (Item.CtorGroup _), None, _ -> allTypes, Some item.Item, ty + | _ -> false, None, None) + (true,None,None) items + match allTypes, constr, ty with + | true, Some (Item.CtorGroup(_, _) as item), _ + -> GetF1Keyword g item + | true, _, Some ty + -> GetF1Keyword g ty + | _ -> None + ) + (fun msg -> + Trace.TraceInformation(sprintf "FCS: recovering from error in GetF1Keyword: '%s'" msg) + None) + + member __.GetMethods (ctok, line, lineStr, colAtEndOfNames, namesOpt) = + ErrorScope.Protect Range.range0 + (fun () -> + + let declItemsOpt = + GetDeclItemsForNamesAtPosition(ctok, None, namesOpt, None, None, + line, lineStr, colAtEndOfNames, ResolveTypeNamesToCtors, + ResolveOverloads.No, (fun() -> []), (fun _ -> false)) + + match declItemsOpt with + | None -> FSharpMethodGroup("",[| |]) + | Some (items, denv, _, m) -> + // GetDeclItemsForNamesAtPosition returns Items.Types and Item.CtorGroup for `new T(|)`, + // the Item.Types is not needed here as it duplicates (at best) parameterless ctor. + let ctors = items |> List.filter (fun x -> match x.Item with Item.CtorGroup _ -> true | _ -> false) + let items = + match ctors with + | [] -> items + | ctors -> ctors + FSharpMethodGroup.Create(infoReader, m, denv, items |> List.map (fun x -> x.ItemWithInst))) + (fun msg -> + Trace.TraceInformation(sprintf "FCS: recovering from error in GetMethods: '%s'" msg) + FSharpMethodGroup(msg,[| |])) + + member __.GetMethodsAsSymbols (ctok, line, lineStr, colAtEndOfNames, names) = + ErrorScope.Protect Range.range0 + (fun () -> + let declItemsOpt = + GetDeclItemsForNamesAtPosition (ctok, None, Some names, None, + None, line, lineStr, colAtEndOfNames, + ResolveTypeNamesToCtors, ResolveOverloads.No, + (fun() -> []), (fun _ -> false)) + + match declItemsOpt with + | None | Some ([],_,_,_) -> None + | Some (items, denv, _, m) -> + let allItems = items |> List.collect (fun item -> SymbolHelpers.FlattenItems g m item.Item) + let symbols = allItems |> List.map (fun item -> FSharpSymbol.Create(cenv, item)) + Some (symbols, denv, m) + ) + (fun msg -> + Trace.TraceInformation(sprintf "FCS: recovering from error in GetMethodsAsSymbols: '%s'" msg) + None) + + member __.GetDeclarationLocation (ctok, line, lineStr, colAtEndOfNames, names, preferFlag) = + ErrorScope.Protect Range.range0 + (fun () -> + + let declItemsOpt = + GetDeclItemsForNamesAtPosition (ctok, None, Some names, None, None, + line, lineStr, colAtEndOfNames, ResolveTypeNamesToCtors, + ResolveOverloads.Yes, (fun() -> []), (fun _ -> false)) + + match declItemsOpt with + | None + | Some ([], _, _, _) -> FSharpFindDeclResult.DeclNotFound (FSharpFindDeclFailureReason.Unknown "") + | Some (item :: _, _, _, _) -> + let getTypeVarNames (ilinfo: ILMethInfo) = + let classTypeParams = ilinfo.DeclaringTyconRef.ILTyconRawMetadata.GenericParams |> List.map (fun paramDef -> paramDef.Name) + let methodTypeParams = ilinfo.FormalMethodTypars |> List.map (fun ty -> ty.Name) + classTypeParams @ methodTypeParams |> Array.ofList + + let result = + match item.Item with + | Item.CtorGroup (_, (ILMeth (_,ilinfo,_)) :: _) -> + match ilinfo.MetadataScope with + | ILScopeRef.Assembly assemblyRef -> + let typeVarNames = getTypeVarNames ilinfo + ParamTypeSymbol.tryOfILTypes typeVarNames ilinfo.ILMethodRef.ArgTypes + |> Option.map (fun args -> + let externalSym = ExternalSymbol.Constructor (ilinfo.ILMethodRef.DeclaringTypeRef.FullName, args) + FSharpFindDeclResult.ExternalDecl (assemblyRef.Name, externalSym)) + | _ -> None + + | Item.MethodGroup (name, (ILMeth (_,ilinfo,_)) :: _, _) -> + match ilinfo.MetadataScope with + | ILScopeRef.Assembly assemblyRef -> + let typeVarNames = getTypeVarNames ilinfo + ParamTypeSymbol.tryOfILTypes typeVarNames ilinfo.ILMethodRef.ArgTypes + |> Option.map (fun args -> + let externalSym = ExternalSymbol.Method (ilinfo.ILMethodRef.DeclaringTypeRef.FullName, name, args, ilinfo.ILMethodRef.GenericArity) + FSharpFindDeclResult.ExternalDecl (assemblyRef.Name, externalSym)) + | _ -> None + + | Item.Property (name, ILProp propInfo :: _) -> + let methInfo = + if propInfo.HasGetter then Some propInfo.GetterMethod + elif propInfo.HasSetter then Some propInfo.SetterMethod + else None + + match methInfo with + | Some methInfo -> + match methInfo.MetadataScope with + | ILScopeRef.Assembly assemblyRef -> + let externalSym = ExternalSymbol.Property (methInfo.ILMethodRef.DeclaringTypeRef.FullName, name) + Some (FSharpFindDeclResult.ExternalDecl (assemblyRef.Name, externalSym)) + | _ -> None + | None -> None + + | Item.ILField (ILFieldInfo (typeInfo, fieldDef)) when not typeInfo.TyconRefOfRawMetadata.IsLocalRef -> + match typeInfo.ILScopeRef with + | ILScopeRef.Assembly assemblyRef -> + let externalSym = ExternalSymbol.Field (typeInfo.ILTypeRef.FullName, fieldDef.Name) + Some (FSharpFindDeclResult.ExternalDecl (assemblyRef.Name, externalSym)) + | _ -> None + + | Item.Event (ILEvent (ILEventInfo (typeInfo, eventDef))) when not typeInfo.TyconRefOfRawMetadata.IsLocalRef -> + match typeInfo.ILScopeRef with + | ILScopeRef.Assembly assemblyRef -> + let externalSym = ExternalSymbol.Event (typeInfo.ILTypeRef.FullName, eventDef.Name) + Some (FSharpFindDeclResult.ExternalDecl (assemblyRef.Name, externalSym)) + | _ -> None + + | Item.ImplicitOp(_, {contents = Some(TraitConstraintSln.FSMethSln(_, _vref, _))}) -> + //Item.Value(vref) + None + + | Item.Types (_, TType_app (tr, _) :: _) when tr.IsLocalRef && tr.IsTypeAbbrev -> None + + | Item.Types (_, [ AppTy g (tr, _) ]) when not tr.IsLocalRef -> + match tr.TypeReprInfo, tr.PublicPath with + | TILObjectRepr(TILObjectReprData (ILScopeRef.Assembly assemblyRef, _, _)), Some (PubPath parts) -> + let fullName = parts |> String.concat "." + Some (FSharpFindDeclResult.ExternalDecl (assemblyRef.Name, ExternalSymbol.Type fullName)) + | _ -> None + | _ -> None + match result with + | Some x -> x + | None -> + match rangeOfItem g preferFlag item.Item with + | Some itemRange -> + let projectDir = Filename.directoryName (if projectFileName = "" then mainInputFileName else projectFileName) + let range = fileNameOfItem g (Some projectDir) itemRange item.Item + mkRange range itemRange.Start itemRange.End + |> FSharpFindDeclResult.DeclFound + | None -> + match item.Item with +#if !NO_EXTENSIONTYPING +// provided items may have TypeProviderDefinitionLocationAttribute that binds them to some location + | Item.CtorGroup (name, ProvidedMeth (_)::_ ) + | Item.MethodGroup(name, ProvidedMeth (_)::_, _) + | Item.Property (name, ProvidedProp (_)::_ ) -> FSharpFindDeclFailureReason.ProvidedMember name + | Item.Event ( ProvidedEvent(_) as e ) -> FSharpFindDeclFailureReason.ProvidedMember e.EventName + | Item.ILField ( ProvidedField(_) as f ) -> FSharpFindDeclFailureReason.ProvidedMember f.FieldName + | SymbolHelpers.ItemIsProvidedType g (tcref) -> FSharpFindDeclFailureReason.ProvidedType tcref.DisplayName +#endif + | _ -> FSharpFindDeclFailureReason.Unknown "" + |> FSharpFindDeclResult.DeclNotFound + ) + (fun msg -> + Trace.TraceInformation(sprintf "FCS: recovering from error in GetDeclarationLocation: '%s'" msg) + FSharpFindDeclResult.DeclNotFound (FSharpFindDeclFailureReason.Unknown msg)) + + member __.GetSymbolUseAtLocation (ctok, line, lineStr, colAtEndOfNames, names) = + ErrorScope.Protect Range.range0 + (fun () -> + let declItemsOpt = + GetDeclItemsForNamesAtPosition (ctok, None, Some names, None, None, + line, lineStr, colAtEndOfNames, ResolveTypeNamesToCtors, + ResolveOverloads.Yes, (fun() -> []), (fun _ -> false)) + + match declItemsOpt with + | None | Some ([], _, _, _) -> None + | Some (item :: _, denv, _, m) -> + let symbol = FSharpSymbol.Create(cenv, item.Item) + Some (symbol, denv, m) + ) + (fun msg -> + Trace.TraceInformation(sprintf "FCS: recovering from error in GetSymbolUseAtLocation: '%s'" msg) + None) + + member __.PartialAssemblySignatureForFile = + FSharpAssemblySignature(g, thisCcu, ccuSigForFile, tcImports, None, ccuSigForFile) + + member __.AccessRights = tcAccessRights + + member __.GetReferencedAssemblies() = + [ for x in tcImports.GetImportedAssemblies() do + yield FSharpAssembly(g, tcImports, x.FSharpViewOfMetadata) ] + + member __.GetFormatSpecifierLocationsAndArity() = + sSymbolUses.GetFormatSpecifierLocationsAndArity() + + member __.GetSemanticClassification(range: range option) : struct (range * SemanticClassificationType) [] = + sResolutions.GetSemanticClassification(g, amap, sSymbolUses.GetFormatSpecifierLocationsAndArity(), range) + + /// The resolutions in the file + member __.ScopeResolutions = sResolutions + + /// The uses of symbols in the analyzed file + member __.ScopeSymbolUses = sSymbolUses + + member __.TcGlobals = g + + member __.TcImports = tcImports + + /// The inferred signature of the file + member __.CcuSigForFile = ccuSigForFile + + /// The assembly being analyzed + member __.ThisCcu = thisCcu + + member __.ImplementationFile = implFileOpt + + /// All open declarations in the file, including auto open modules + member __.OpenDeclarations = openDeclarations + + member __.SymbolEnv = cenv + + override __.ToString() = "TypeCheckInfo(" + mainInputFileName + ")" + +type FSharpParsingOptions = + { SourceFiles: string [] + ConditionalCompilationDefines: string list + ErrorSeverityOptions: FSharpErrorSeverityOptions + IsInteractive: bool + LightSyntax: bool option + CompilingFsLib: bool + IsExe: bool } + + member x.LastFileName = + Debug.Assert(not (Array.isEmpty x.SourceFiles), "Parsing options don't contain any file") + Array.last x.SourceFiles + + static member Default = + { SourceFiles = Array.empty + ConditionalCompilationDefines = [] + ErrorSeverityOptions = FSharpErrorSeverityOptions.Default + IsInteractive = false + LightSyntax = None + CompilingFsLib = false + IsExe = false } + + static member FromTcConfig(tcConfig: TcConfig, sourceFiles, isInteractive: bool) = + { SourceFiles = sourceFiles + ConditionalCompilationDefines = tcConfig.conditionalCompilationDefines + ErrorSeverityOptions = tcConfig.errorSeverityOptions + IsInteractive = isInteractive + LightSyntax = tcConfig.light + CompilingFsLib = tcConfig.compilingFslib + IsExe = tcConfig.target.IsExe } + + static member FromTcConfigBuilder(tcConfigB: TcConfigBuilder, sourceFiles, isInteractive: bool) = + { + SourceFiles = sourceFiles + ConditionalCompilationDefines = tcConfigB.conditionalCompilationDefines + ErrorSeverityOptions = tcConfigB.errorSeverityOptions + IsInteractive = isInteractive + LightSyntax = tcConfigB.light + CompilingFsLib = tcConfigB.compilingFslib + IsExe = tcConfigB.target.IsExe + } + +module internal ParseAndCheckFile = + + /// Error handler for parsing & type checking while processing a single file + type ErrorHandler(reportErrors, mainInputFileName, errorSeverityOptions: FSharpErrorSeverityOptions, sourceText: ISourceText, suggestNamesForErrors: bool) = + let mutable options = errorSeverityOptions + let errorsAndWarningsCollector = new ResizeArray<_>() + let mutable errorCount = 0 + + // We'll need number of lines for adjusting error messages at EOF + let fileInfo = sourceText.GetLastCharacterPosition() + + // This function gets called whenever an error happens during parsing or checking + let diagnosticSink sev (exn: PhasedDiagnostic) = + // Sanity check here. The phase of an error should be in a phase known to the language service. + let exn = + if not(exn.IsPhaseInCompile()) then + // Reaching this point means that the error would be sticky if we let it prop up to the language service. + // Assert and recover by replacing phase with one known to the language service. + Trace.TraceInformation(sprintf "The subcategory '%s' seen in an error should not be seen by the language service" (exn.Subcategory())) + { exn with Phase = BuildPhase.TypeCheck } + else exn + if reportErrors then + let report exn = + for ei in ErrorHelpers.ReportError (options, false, mainInputFileName, fileInfo, (exn, sev), suggestNamesForErrors) do + errorsAndWarningsCollector.Add ei + if sev = FSharpErrorSeverity.Error then + errorCount <- errorCount + 1 + + match exn with +#if !NO_EXTENSIONTYPING + | { Exception = (:? TypeProviderError as tpe) } -> tpe.Iter(fun e -> report { exn with Exception = e }) +#endif + | e -> report e + + let errorLogger = + { new ErrorLogger("ErrorHandler") with + member x.DiagnosticSink (exn, isError) = diagnosticSink (if isError then FSharpErrorSeverity.Error else FSharpErrorSeverity.Warning) exn + member x.ErrorCount = errorCount } + + // Public members + member __.ErrorLogger = errorLogger + + member __.CollectedDiagnostics = errorsAndWarningsCollector.ToArray() + + member __.ErrorCount = errorCount + + member __.ErrorSeverityOptions with set opts = options <- opts + + member __.AnyErrors = errorCount > 0 + + let getLightSyntaxStatus fileName options = + let lower = String.lowercase fileName + let lightOnByDefault = List.exists (Filename.checkSuffix lower) FSharpLightSyntaxFileSuffixes + let lightSyntaxStatus = if lightOnByDefault then (options.LightSyntax <> Some false) else (options.LightSyntax = Some true) + LightSyntaxStatus(lightSyntaxStatus, true) + + let createLexerFunction fileName options lexbuf (errHandler: ErrorHandler) = + let lightSyntaxStatus = getLightSyntaxStatus fileName options + + // If we're editing a script then we define INTERACTIVE otherwise COMPILED. + // Since this parsing for intellisense we always define EDITING. + let defines = (SourceFileImpl.AdditionalDefinesForUseInEditor options.IsInteractive) @ options.ConditionalCompilationDefines + + // Note: we don't really attempt to intern strings across a large scope. + let lexResourceManager = new Lexhelp.LexResourceManager() + + // When analyzing files using ParseOneFile, i.e. for the use of editing clients, we do not apply line directives. + // TODO(pathmap): expose PathMap on the service API, and thread it through here + let lexargs = mkLexargs(fileName, defines, lightSyntaxStatus, lexResourceManager, [], errHandler.ErrorLogger, PathMap.empty) + let lexargs = { lexargs with applyLineDirectives = false } + + let tokenizer = LexFilter.LexFilter(lightSyntaxStatus, options.CompilingFsLib, Lexer.token lexargs true, lexbuf) + tokenizer.Lexer + + // Public callers are unable to answer LanguageVersion feature support questions. + // External Tools including the VS IDE will enable the default LanguageVersion + let isFeatureSupported (_featureId:LanguageFeature) = true + + let createLexbuf sourceText isFeatureSupported = + UnicodeLexing.SourceTextAsLexbuf(isFeatureSupported, sourceText) + + let matchBraces(sourceText: ISourceText, fileName, options: FSharpParsingOptions, userOpName: string, suggestNamesForErrors: bool) = + let delayedLogger = CapturingErrorLogger("matchBraces") + use _unwindEL = PushErrorLoggerPhaseUntilUnwind (fun _ -> delayedLogger) + use _unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse + + Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "matchBraces", fileName) + + // Make sure there is an ErrorLogger installed whenever we do stuff that might record errors, even if we ultimately ignore the errors + let delayedLogger = CapturingErrorLogger("matchBraces") + use _unwindEL = PushErrorLoggerPhaseUntilUnwind (fun _ -> delayedLogger) + use _unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse + + let matchingBraces = new ResizeArray<_>() + Lexhelp.usingLexbufForParsing(createLexbuf sourceText isFeatureSupported, fileName) (fun lexbuf -> + let errHandler = ErrorHandler(false, fileName, options.ErrorSeverityOptions, sourceText, suggestNamesForErrors) + let lexfun = createLexerFunction fileName options lexbuf errHandler + let parenTokensBalance t1 t2 = + match t1, t2 with + | (LPAREN, RPAREN) + | (LPAREN, RPAREN_IS_HERE) + | (LBRACE, RBRACE) + | (LBRACE, RBRACE_IS_HERE) + | (SIG, END) + | (STRUCT, END) + | (LBRACK_BAR, BAR_RBRACK) + | (LBRACK, RBRACK) + | (LBRACK_LESS, GREATER_RBRACK) + | (BEGIN, END) -> true + | (LQUOTE q1, RQUOTE q2) -> q1 = q2 + | _ -> false + let rec matchBraces stack = + match lexfun lexbuf, stack with + | tok2, ((tok1, m1) :: stack') when parenTokensBalance tok1 tok2 -> + matchingBraces.Add(m1, lexbuf.LexemeRange) + matchBraces stack' + | ((LPAREN | LBRACE | LBRACK | LBRACK_BAR | LQUOTE _ | LBRACK_LESS) as tok), _ -> + matchBraces ((tok, lexbuf.LexemeRange) :: stack) + | (EOF _ | LEX_FAILURE _), _ -> () + | _ -> matchBraces stack + matchBraces []) + matchingBraces.ToArray() + + let parseFile(sourceText: ISourceText, fileName, options: FSharpParsingOptions, userOpName: string, suggestNamesForErrors: bool) = + Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "parseFile", fileName) + let errHandler = new ErrorHandler(true, fileName, options.ErrorSeverityOptions, sourceText, suggestNamesForErrors) + use unwindEL = PushErrorLoggerPhaseUntilUnwind (fun _oldLogger -> errHandler.ErrorLogger) + use unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse + + let parseResult = + Lexhelp.usingLexbufForParsing(createLexbuf sourceText isFeatureSupported, fileName) (fun lexbuf -> + let lexfun = createLexerFunction fileName options lexbuf errHandler + let isLastCompiland = + fileName.Equals(options.LastFileName, StringComparison.CurrentCultureIgnoreCase) || + CompileOps.IsScript(fileName) + let isExe = options.IsExe + try Some (ParseInput(lexfun, errHandler.ErrorLogger, lexbuf, None, fileName, (isLastCompiland, isExe))) + with e -> + errHandler.ErrorLogger.StopProcessingRecovery e Range.range0 // don't re-raise any exceptions, we must return None. + None) + errHandler.CollectedDiagnostics, parseResult, errHandler.AnyErrors + + +#if !FABLE_COMPILER + let ApplyLoadClosure(tcConfig, parsedMainInput, mainInputFileName, loadClosure: LoadClosure option, tcImports: TcImports, backgroundDiagnostics) = + + // If additional references were brought in by the preprocessor then we need to process them + match loadClosure with + | Some loadClosure -> + // Play unresolved references for this file. + tcImports.ReportUnresolvedAssemblyReferences(loadClosure.UnresolvedReferences) + + // If there was a loadClosure, replay the errors and warnings from resolution, excluding parsing + loadClosure.LoadClosureRootFileDiagnostics |> List.iter diagnosticSink + + let fileOfBackgroundError err = (match GetRangeOfDiagnostic (fst err) with Some m-> m.FileName | None -> null) + let sameFile file hashLoadInFile = + (0 = String.Compare(hashLoadInFile, file, StringComparison.OrdinalIgnoreCase)) + + // walk the list of #loads and keep the ones for this file. + let hashLoadsInFile = + loadClosure.SourceFiles + |> List.filter(fun (_,ms) -> ms<>[]) // #loaded file, ranges of #load + + let hashLoadBackgroundDiagnostics, otherBackgroundDiagnostics = + backgroundDiagnostics + |> Array.partition (fun backgroundError -> + hashLoadsInFile + |> List.exists (fst >> sameFile (fileOfBackgroundError backgroundError))) + + // Create single errors for the #load-ed files. + // Group errors and warnings by file name. + let hashLoadBackgroundDiagnosticsGroupedByFileName = + hashLoadBackgroundDiagnostics + |> Array.map(fun err -> fileOfBackgroundError err,err) + |> Array.groupBy fst // fileWithErrors, error list + + // Join the sets and report errors. + // It is by-design that these messages are only present in the language service. A true build would report the errors at their + // spots in the individual source files. + for (fileOfHashLoad, rangesOfHashLoad) in hashLoadsInFile do + for (file, errorGroupedByFileName) in hashLoadBackgroundDiagnosticsGroupedByFileName do + if sameFile file fileOfHashLoad then + for rangeOfHashLoad in rangesOfHashLoad do // Handle the case of two #loads of the same file + let diagnostics = errorGroupedByFileName |> Array.map(fun (_,(pe,f)) -> pe.Exception,f) // Strip the build phase here. It will be replaced, in total, with TypeCheck + let errors = [ for (err,sev) in diagnostics do if sev = FSharpErrorSeverity.Error then yield err ] + let warnings = [ for (err,sev) in diagnostics do if sev = FSharpErrorSeverity.Warning then yield err ] + + let message = HashLoadedSourceHasIssues(warnings,errors,rangeOfHashLoad) + if errors=[] then warning(message) + else errorR(message) + + // Replay other background errors. + for (phasedError,sev) in otherBackgroundDiagnostics do + if sev = FSharpErrorSeverity.Warning then + warning phasedError.Exception + else errorR phasedError.Exception + + | None -> + // For non-scripts, check for disallow #r and #load. + ApplyMetaCommandsFromInputToTcConfig (tcConfig, parsedMainInput,Path.GetDirectoryName mainInputFileName) |> ignore +#endif //!FABLE_COMPILER + + // Type check a single file against an initial context, gleaning both errors and intellisense information. + let CheckOneFile + (parseResults: FSharpParseFileResults, + sourceText: ISourceText, + mainInputFileName: string, + projectFileName: string, + tcConfig: TcConfig, + tcGlobals: TcGlobals, + tcImports: TcImports, + tcState: TcState, + moduleNamesDict: ModuleNamesDict, + loadClosure: LoadClosure option, + // These are the errors and warnings seen by the background compiler for the entire antecedent + backgroundDiagnostics: (PhasedDiagnostic * FSharpErrorSeverity)[], + reactorOps: IReactorOperations, + // Used by 'FSharpDeclarationListInfo' to check the IncrementalBuilder is still alive. + textSnapshotInfo : obj option, + userOpName: string, + suggestNamesForErrors: bool) = +#if !FABLE_COMPILER + async { +#endif + use _logBlock = Logger.LogBlock LogCompilerFunctionId.Service_CheckOneFile + + match parseResults.ParseTree with + // When processing the following cases, we don't need to type-check +#if FABLE_COMPILER + | None -> [||], Result.Error() +#else + | None -> return [||], Result.Error() +#endif + + // Run the type checker... + | Some parsedMainInput -> + + // Initialize the error handler + let errHandler = new ErrorHandler(true, mainInputFileName, tcConfig.errorSeverityOptions, sourceText, suggestNamesForErrors) + + use _unwindEL = PushErrorLoggerPhaseUntilUnwind (fun _oldLogger -> errHandler.ErrorLogger) + use _unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.TypeCheck + +#if !FABLE_COMPILER + // Apply nowarns to tcConfig (may generate errors, so ensure errorLogger is installed) + let tcConfig = ApplyNoWarnsToTcConfig (tcConfig, parsedMainInput,Path.GetDirectoryName mainInputFileName) +#endif + + // update the error handler with the modified tcConfig + errHandler.ErrorSeverityOptions <- tcConfig.errorSeverityOptions + + // Play background errors and warnings for this file. + for (err,sev) in backgroundDiagnostics do + diagnosticSink (err, (sev = FSharpErrorSeverity.Error)) + +#if !FABLE_COMPILER + // If additional references were brought in by the preprocessor then we need to process them + ApplyLoadClosure(tcConfig, parsedMainInput, mainInputFileName, loadClosure, tcImports, backgroundDiagnostics) +#endif + + // A problem arises with nice name generation, which really should only + // be done in the backend, but is also done in the typechecker for better or worse. + // If we don't do this the NNG accumulates data and we get a memory leak. + tcState.NiceNameGenerator.Reset() + + // Typecheck the real input. + let sink = TcResultsSinkImpl(tcGlobals, sourceText = sourceText) + +#if FABLE_COMPILER + ignore userOpName + let resOpt = + try + let ctok = AssumeCompilationThreadWithoutEvidence() + let checkForErrors() = (parseResults.ParseHadErrors || errHandler.ErrorCount > 0) + let parsedMainInput, _moduleNamesDict = DeduplicateParsedInputModuleName moduleNamesDict parsedMainInput + let result = + TypeCheckOneInputAndFinishEventually(checkForErrors, tcConfig, tcImports, tcGlobals, None, TcResultsSink.WithSink sink, tcState, parsedMainInput) + |> Eventually.force ctok + Some result + with + | e -> + errorR e + let mty = Construct.NewEmptyModuleOrNamespaceType Namespace + Some((tcState.TcEnvFromSignatures, EmptyTopAttrs, [], [ mty ]), tcState) +#else //!FABLE_COMPILER + + let! ct = Async.CancellationToken + + let! resOpt = + async { + try + let checkForErrors() = (parseResults.ParseHadErrors || errHandler.ErrorCount > 0) + + let parsedMainInput, _moduleNamesDict = DeduplicateParsedInputModuleName moduleNamesDict parsedMainInput + + // Typecheck is potentially a long running operation. We chop it up here with an Eventually continuation and, at each slice, give a chance + // for the client to claim the result as obsolete and have the typecheck abort. + + let! result = + TypeCheckOneInputAndFinishEventually(checkForErrors, tcConfig, tcImports, tcGlobals, None, TcResultsSink.WithSink sink, tcState, parsedMainInput) + |> Eventually.repeatedlyProgressUntilDoneOrTimeShareOverOrCanceled maxTimeShareMilliseconds ct (fun ctok f -> f ctok) + |> Eventually.forceAsync + (fun work -> + reactorOps.EnqueueAndAwaitOpAsync(userOpName, "CheckOneFile.Fragment", mainInputFileName, + fun ctok -> + // This work is not cancellable + let res = + // Reinstall the compilation globals each time we start or restart + use unwind = new CompilationGlobalsScope (errHandler.ErrorLogger, BuildPhase.TypeCheck) + work ctok + cancellable.Return(res) + )) + + return result + with e -> + errorR e + let mty = Construct.NewEmptyModuleOrNamespaceType Namespace + return Some((tcState.TcEnvFromSignatures, EmptyTopAttrs, [], [ mty ]), tcState) + } +#endif //!FABLE_COMPILER + + let errors = errHandler.CollectedDiagnostics + + let res = + match resOpt with + | Some ((tcEnvAtEnd, _, implFiles, ccuSigsForFiles), tcState) -> + TypeCheckInfo(tcConfig, tcGlobals, + List.head ccuSigsForFiles, + tcState.Ccu, + tcImports, + tcEnvAtEnd.AccessRights, + projectFileName, + mainInputFileName, + sink.GetResolutions(), + sink.GetSymbolUses(), + tcEnvAtEnd.NameEnv, + loadClosure, + reactorOps, + textSnapshotInfo, + List.tryHead implFiles, + sink.GetOpenDeclarations()) + |> Result.Ok + | None -> + Result.Error() +#if FABLE_COMPILER + errors, res +#else + return errors, res + } +#endif + + +[] +type FSharpProjectContext(thisCcu: CcuThunk, assemblies: FSharpAssembly list, ad: AccessorDomain) = + + /// Get the assemblies referenced + member __.GetReferencedAssemblies() = assemblies + + member __.AccessibilityRights = FSharpAccessibilityRights(thisCcu, ad) + + +[] +/// A live object of this type keeps the background corresponding background builder (and type providers) alive (through reference-counting). +// +// There is an important property of all the objects returned by the methods of this type: they do not require +// the corresponding background builder to be alive. That is, they are simply plain-old-data through pre-formatting of all result text. +type FSharpCheckFileResults + (filename: string, + errors: FSharpErrorInfo[], + scopeOptX: TypeCheckInfo option, + dependencyFiles: string[], + builderX: IncrementalBuilder option, + reactorOpsX:IReactorOperations, + keepAssemblyContents: bool) = + + // This may be None initially + let mutable details = match scopeOptX with None -> None | Some scopeX -> Some (scopeX, builderX, reactorOpsX) + + // Run an operation that needs to access a builder and be run in the reactor thread + let reactorOp userOpName opName dflt f = + async { + match details with + | None -> + return dflt + | Some (scope, _, reactor) -> + // Increment the usage count to ensure the builder doesn't get released while running operations asynchronously. + let! res = reactor.EnqueueAndAwaitOpAsync(userOpName, opName, filename, fun ctok -> f ctok scope |> cancellable.Return) + return res + } + + // Run an operation that can be called from any thread + let threadSafeOp dflt f = + match details with + | None -> dflt() + | Some (scope, _builderOpt, _ops) -> f scope + + member __.Errors = errors + + member __.HasFullTypeCheckInfo = details.IsSome + +#if !FABLE_COMPILER + member info.TryGetCurrentTcImports () = + match builderX with + | Some builder -> builder.TryGetCurrentTcImports () + | _ -> None +#endif + + /// Intellisense autocompletions + member __.GetDeclarationListInfo(parseResultsOpt, line, lineStr, partialName, ?getAllEntities, ?hasTextChangedSinceLastTypecheck, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + let getAllEntities = defaultArg getAllEntities (fun() -> []) + let hasTextChangedSinceLastTypecheck = defaultArg hasTextChangedSinceLastTypecheck (fun _ -> false) + reactorOp userOpName "GetDeclarations" FSharpDeclarationListInfo.Empty (fun ctok scope -> + scope.GetDeclarations(ctok, parseResultsOpt, line, lineStr, partialName, getAllEntities, hasTextChangedSinceLastTypecheck)) + + member __.GetDeclarationListSymbols(parseResultsOpt, line, lineStr, partialName, ?getAllEntities, ?hasTextChangedSinceLastTypecheck, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + let hasTextChangedSinceLastTypecheck = defaultArg hasTextChangedSinceLastTypecheck (fun _ -> false) + let getAllEntities = defaultArg getAllEntities (fun() -> []) + reactorOp userOpName "GetDeclarationListSymbols" List.empty (fun ctok scope -> + scope.GetDeclarationListSymbols(ctok, parseResultsOpt, line, lineStr, partialName, getAllEntities, hasTextChangedSinceLastTypecheck)) + + /// Resolve the names at the given location to give a data tip + member __.GetStructuredToolTipText(line, colAtEndOfNames, lineStr, names, tokenTag, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + let dflt = FSharpToolTipText [] + match tokenTagToTokenId tokenTag with + | TOKEN_IDENT -> + reactorOp userOpName "GetStructuredToolTipText" dflt (fun ctok scope -> + scope.GetStructuredToolTipText(ctok, line, lineStr, colAtEndOfNames, names)) + | TOKEN_STRING | TOKEN_STRING_TEXT -> + reactorOp userOpName "GetReferenceResolutionToolTipText" dflt (fun ctok scope -> + scope.GetReferenceResolutionStructuredToolTipText(ctok, line, colAtEndOfNames) ) + | _ -> + async.Return dflt + + member info.GetToolTipText(line, colAtEndOfNames, lineStr, names, tokenTag, userOpName) = + info.GetStructuredToolTipText(line, colAtEndOfNames, lineStr, names, tokenTag, ?userOpName=userOpName) + |> Tooltips.Map Tooltips.ToFSharpToolTipText + + member __.GetF1Keyword (line, colAtEndOfNames, lineStr, names, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + reactorOp userOpName "GetF1Keyword" None (fun ctok scope -> + scope.GetF1Keyword (ctok, line, lineStr, colAtEndOfNames, names)) + + // Resolve the names at the given location to a set of methods + member __.GetMethods(line, colAtEndOfNames, lineStr, names, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + let dflt = FSharpMethodGroup("",[| |]) + reactorOp userOpName "GetMethods" dflt (fun ctok scope -> + scope.GetMethods (ctok, line, lineStr, colAtEndOfNames, names)) + + member __.GetDeclarationLocation (line, colAtEndOfNames, lineStr, names, ?preferFlag, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + let dflt = FSharpFindDeclResult.DeclNotFound (FSharpFindDeclFailureReason.Unknown "") + reactorOp userOpName "GetDeclarationLocation" dflt (fun ctok scope -> + scope.GetDeclarationLocation (ctok, line, lineStr, colAtEndOfNames, names, preferFlag)) + + member __.GetSymbolUseAtLocation (line, colAtEndOfNames, lineStr, names, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + reactorOp userOpName "GetSymbolUseAtLocation" None (fun ctok scope -> + scope.GetSymbolUseAtLocation (ctok, line, lineStr, colAtEndOfNames, names) + |> Option.map (fun (sym,denv,m) -> FSharpSymbolUse(scope.TcGlobals,denv,sym,ItemOccurence.Use,m))) + + member __.GetMethodsAsSymbols (line, colAtEndOfNames, lineStr, names, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + reactorOp userOpName "GetMethodsAsSymbols" None (fun ctok scope -> + scope.GetMethodsAsSymbols (ctok, line, lineStr, colAtEndOfNames, names) + |> Option.map (fun (symbols,denv,m) -> + symbols |> List.map (fun sym -> FSharpSymbolUse(scope.TcGlobals,denv,sym,ItemOccurence.Use,m)))) + + member __.GetSymbolAtLocation (line, colAtEndOfNames, lineStr, names, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + reactorOp userOpName "GetSymbolAtLocation" None (fun ctok scope -> + scope.GetSymbolUseAtLocation (ctok, line, lineStr, colAtEndOfNames, names) + |> Option.map (fun (sym,_,_) -> sym)) + + member info.GetFormatSpecifierLocations() = + info.GetFormatSpecifierLocationsAndArity() |> Array.map fst + + member __.GetFormatSpecifierLocationsAndArity() = + threadSafeOp + (fun () -> [| |]) + (fun scope -> + // This operation is not asynchronous - GetFormatSpecifierLocationsAndArity can be run on the calling thread + scope.GetFormatSpecifierLocationsAndArity()) + + member __.GetSemanticClassification(range: range option) = + threadSafeOp + (fun () -> [| |]) + (fun scope -> + // This operation is not asynchronous - GetSemanticClassification can be run on the calling thread + scope.GetSemanticClassification(range)) + + member __.PartialAssemblySignature = + threadSafeOp + (fun () -> failwith "not available") + (fun scope -> + // This operation is not asynchronous - PartialAssemblySignature can be run on the calling thread + scope.PartialAssemblySignatureForFile) + + member __.ProjectContext = + threadSafeOp + (fun () -> failwith "not available") + (fun scope -> + // This operation is not asynchronous - GetReferencedAssemblies can be run on the calling thread + FSharpProjectContext(scope.ThisCcu, scope.GetReferencedAssemblies(), scope.AccessRights)) + + member __.DependencyFiles = dependencyFiles + + member __.GetAllUsesOfAllSymbolsInFile() = + threadSafeOp + (fun () -> [| |]) + (fun scope -> + let cenv = scope.SymbolEnv + [| for symbolUseChunk in scope.ScopeSymbolUses.AllUsesOfSymbols do + for symbolUse in symbolUseChunk do + if symbolUse.ItemOccurence <> ItemOccurence.RelatedText then + let symbol = FSharpSymbol.Create(cenv, symbolUse.Item) + yield FSharpSymbolUse(scope.TcGlobals, symbolUse.DisplayEnv, symbol, symbolUse.ItemOccurence, symbolUse.Range) |]) + |> async.Return + + member __.GetUsesOfSymbolInFile(symbol:FSharpSymbol) = + threadSafeOp + (fun () -> [| |]) + (fun scope -> + [| for symbolUse in scope.ScopeSymbolUses.GetUsesOfSymbol(symbol.Item) |> Seq.distinctBy (fun symbolUse -> symbolUse.ItemOccurence, symbolUse.Range) do + if symbolUse.ItemOccurence <> ItemOccurence.RelatedText then + yield FSharpSymbolUse(scope.TcGlobals, symbolUse.DisplayEnv, symbol, symbolUse.ItemOccurence, symbolUse.Range) |]) + |> async.Return + + member __.GetVisibleNamespacesAndModulesAtPoint(pos: pos) = + threadSafeOp + (fun () -> [| |]) + (fun scope -> scope.GetVisibleNamespacesAndModulesAtPosition(pos) |> List.toArray) + |> async.Return + + member __.IsRelativeNameResolvable(pos: pos, plid: string list, item: Item, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + reactorOp userOpName "IsRelativeNameResolvable" true (fun ctok scope -> + RequireCompilationThread ctok + scope.IsRelativeNameResolvable(pos, plid, item)) + + member __.IsRelativeNameResolvableFromSymbol(pos: pos, plid: string list, symbol: FSharpSymbol, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + reactorOp userOpName "IsRelativeNameResolvableFromSymbol" true (fun ctok scope -> + RequireCompilationThread ctok + scope.IsRelativeNameResolvableFromSymbol(pos, plid, symbol)) + + member __.GetDisplayContextForPos(pos: pos) : Async = + let userOpName = "CodeLens" + reactorOp userOpName "GetDisplayContextAtPos" None (fun ctok scope -> + DoesNotRequireCompilerThreadTokenAndCouldPossiblyBeMadeConcurrent ctok + let (nenv, _), _ = scope.GetBestDisplayEnvForPos pos + Some(FSharpDisplayContext(fun _ -> nenv.DisplayEnv))) + + member __.ImplementationFile = + if not keepAssemblyContents then invalidOp "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" + scopeOptX + |> Option.map (fun scope -> + let cenv = SymbolEnv(scope.TcGlobals, scope.ThisCcu, Some scope.CcuSigForFile, scope.TcImports) + scope.ImplementationFile |> Option.map (fun implFile -> FSharpImplementationFileContents(cenv, implFile))) + |> Option.defaultValue None + + member __.OpenDeclarations = + scopeOptX + |> Option.map (fun scope -> + let cenv = scope.SymbolEnv + scope.OpenDeclarations |> Array.map (fun x -> FSharpOpenDeclaration(x.LongId, x.Range, (x.Modules |> List.map (fun x -> FSharpEntity(cenv, x))), x.AppliedScope, x.IsOwnNamespace))) + |> Option.defaultValue [| |] + + override __.ToString() = "FSharpCheckFileResults(" + filename + ")" + + static member MakeEmpty(filename: string, creationErrors: FSharpErrorInfo[], reactorOps, keepAssemblyContents) = + FSharpCheckFileResults (filename, creationErrors, None, [| |], None, reactorOps, keepAssemblyContents) + + static member JoinErrors(isIncompleteTypeCheckEnvironment, + creationErrors: FSharpErrorInfo[], + parseErrors: FSharpErrorInfo[], + tcErrors: FSharpErrorInfo[]) = + [| yield! creationErrors + yield! parseErrors + if isIncompleteTypeCheckEnvironment then + yield! Seq.truncate maxTypeCheckErrorsOutOfProjectContext tcErrors + else + yield! tcErrors |] + + static member Make + (mainInputFileName: string, + projectFileName, + tcConfig, tcGlobals, + isIncompleteTypeCheckEnvironment: bool, + builder: IncrementalBuilder, + dependencyFiles, + creationErrors: FSharpErrorInfo[], + parseErrors: FSharpErrorInfo[], + tcErrors: FSharpErrorInfo[], + reactorOps, + keepAssemblyContents, + ccuSigForFile, + thisCcu, tcImports, tcAccessRights, + sResolutions, sSymbolUses, + sFallback, loadClosure, + implFileOpt, + openDeclarations) = + + let tcFileInfo = + TypeCheckInfo(tcConfig, tcGlobals, ccuSigForFile, thisCcu, tcImports, tcAccessRights, + projectFileName, mainInputFileName, sResolutions, sSymbolUses, + sFallback, loadClosure, reactorOps, + None, implFileOpt, openDeclarations) + + let errors = FSharpCheckFileResults.JoinErrors(isIncompleteTypeCheckEnvironment, creationErrors, parseErrors, tcErrors) + FSharpCheckFileResults (mainInputFileName, errors, Some tcFileInfo, dependencyFiles, Some builder, reactorOps, keepAssemblyContents) + +#if !FABLE_COMPILER + static member CheckOneFile + (parseResults: FSharpParseFileResults, + sourceText: ISourceText, + mainInputFileName: string, + projectFileName: string, + tcConfig: TcConfig, + tcGlobals: TcGlobals, + tcImports: TcImports, + tcState: TcState, + moduleNamesDict: ModuleNamesDict, + loadClosure: LoadClosure option, + backgroundDiagnostics: (PhasedDiagnostic * FSharpErrorSeverity)[], + reactorOps: IReactorOperations, + textSnapshotInfo : obj option, + userOpName: string, + isIncompleteTypeCheckEnvironment: bool, + builder: IncrementalBuilder, + dependencyFiles: string[], + creationErrors: FSharpErrorInfo[], + parseErrors: FSharpErrorInfo[], + keepAssemblyContents: bool, + suggestNamesForErrors: bool) = + async { + let! tcErrors, tcFileInfo = + ParseAndCheckFile.CheckOneFile + (parseResults, sourceText, mainInputFileName, projectFileName, tcConfig, tcGlobals, tcImports, + tcState, moduleNamesDict, loadClosure, backgroundDiagnostics, reactorOps, + textSnapshotInfo, userOpName, suggestNamesForErrors) + match tcFileInfo with + | Result.Error () -> + return FSharpCheckFileAnswer.Aborted + | Result.Ok tcFileInfo -> + let errors = FSharpCheckFileResults.JoinErrors(isIncompleteTypeCheckEnvironment, creationErrors, parseErrors, tcErrors) + let results = FSharpCheckFileResults (mainInputFileName, errors, Some tcFileInfo, dependencyFiles, Some builder, reactorOps, keepAssemblyContents) + return FSharpCheckFileAnswer.Succeeded(results) + } +#endif + +and [] FSharpCheckFileAnswer = + | Aborted + | Succeeded of FSharpCheckFileResults + + +[] +// 'details' is an option because the creation of the tcGlobals etc. for the project may have failed. +type FSharpCheckProjectResults + (projectFileName:string, + tcConfigOption: TcConfig option, + keepAssemblyContents: bool, + errors: FSharpErrorInfo[], + details:(TcGlobals * TcImports * CcuThunk * ModuleOrNamespaceType * TcSymbolUses list * + TopAttribs option * CompileOps.IRawFSharpAssemblyData option * ILAssemblyRef * + AccessorDomain * TypedImplFile list option * string[]) option) = + + let getDetails() = + match details with + | None -> invalidOp ("The project has no results due to critical errors in the project options. Check the HasCriticalErrors before accessing the detailed results. Errors: " + String.concat "\n" [ for e in errors -> e.Message ]) + | Some d -> d + + let getTcConfig() = + match tcConfigOption with + | None -> invalidOp ("The project has no results due to critical errors in the project options. Check the HasCriticalErrors before accessing the detailed results. Errors: " + String.concat "\n" [ for e in errors -> e.Message ]) + | Some d -> d + + member __.Errors = errors + + member __.HasCriticalErrors = details.IsNone + + member __.AssemblySignature = + let (tcGlobals, tcImports, thisCcu, ccuSig, _tcSymbolUses, topAttribs, _tcAssemblyData, _ilAssemRef, _ad, _tcAssemblyExpr, _dependencyFiles) = getDetails() + FSharpAssemblySignature(tcGlobals, thisCcu, ccuSig, tcImports, topAttribs, ccuSig) + + member __.TypedImplementationFiles = + if not keepAssemblyContents then invalidOp "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" + let (tcGlobals, tcImports, thisCcu, _ccuSig, _tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, tcAssemblyExpr, _dependencyFiles) = getDetails() + let mimpls = + match tcAssemblyExpr with + | None -> [] + | Some mimpls -> mimpls + tcGlobals, thisCcu, tcImports, mimpls + + member info.AssemblyContents = + if not keepAssemblyContents then invalidOp "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" + let (tcGlobals, tcImports, thisCcu, ccuSig, _tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, tcAssemblyExpr, _dependencyFiles) = getDetails() + let mimpls = + match tcAssemblyExpr with + | None -> [] + | Some mimpls -> mimpls + FSharpAssemblyContents(tcGlobals, thisCcu, Some ccuSig, tcImports, mimpls) + + member __.GetOptimizedAssemblyContents() = + if not keepAssemblyContents then invalidOp "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" + let (tcGlobals, tcImports, thisCcu, ccuSig, _tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, tcAssemblyExpr, _dependencyFiles) = getDetails() + let mimpls = + match tcAssemblyExpr with + | None -> [] + | Some mimpls -> mimpls + let outfile = "" // only used if tcConfig.writeTermsToFiles is true + let importMap = tcImports.GetImportMap() + let optEnv0 = GetInitialOptimizationEnv (tcImports, tcGlobals) + let tcConfig = getTcConfig() + let optimizedImpls, _optimizationData, _ = ApplyAllOptimizations (tcConfig, tcGlobals, (LightweightTcValForUsingInBuildMethodCall tcGlobals), outfile, importMap, false, optEnv0, thisCcu, mimpls) + let mimpls = + match optimizedImpls with + | TypedAssemblyAfterOptimization files -> + files |> List.map fst + + FSharpAssemblyContents(tcGlobals, thisCcu, Some ccuSig, tcImports, mimpls) + + // Not, this does not have to be a SyncOp, it can be called from any thread + member __.GetUsesOfSymbol(symbol:FSharpSymbol) = + let (tcGlobals, _tcImports, _thisCcu, _ccuSig, tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, _tcAssemblyExpr, _dependencyFiles) = getDetails() + + tcSymbolUses + |> Seq.collect (fun r -> r.GetUsesOfSymbol symbol.Item) + |> Seq.distinctBy (fun symbolUse -> symbolUse.ItemOccurence, symbolUse.Range) + |> Seq.filter (fun symbolUse -> symbolUse.ItemOccurence <> ItemOccurence.RelatedText) + |> Seq.map (fun symbolUse -> FSharpSymbolUse(tcGlobals, symbolUse.DisplayEnv, symbol, symbolUse.ItemOccurence, symbolUse.Range)) + |> Seq.toArray + |> async.Return + + // Not, this does not have to be a SyncOp, it can be called from any thread + member __.GetAllUsesOfAllSymbols() = + let (tcGlobals, tcImports, thisCcu, ccuSig, tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, _tcAssemblyExpr, _dependencyFiles) = getDetails() + let cenv = SymbolEnv(tcGlobals, thisCcu, Some ccuSig, tcImports) + + [| for r in tcSymbolUses do + for symbolUseChunk in r.AllUsesOfSymbols do + for symbolUse in symbolUseChunk do + if symbolUse.ItemOccurence <> ItemOccurence.RelatedText then + let symbol = FSharpSymbol.Create(cenv, symbolUse.Item) + yield FSharpSymbolUse(tcGlobals, symbolUse.DisplayEnv, symbol, symbolUse.ItemOccurence, symbolUse.Range) |] + |> async.Return + + member __.ProjectContext = + let (tcGlobals, tcImports, thisCcu, _ccuSig, _tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, ad, _tcAssemblyExpr, _dependencyFiles) = getDetails() + let assemblies = + [ for x in tcImports.GetImportedAssemblies() do + yield FSharpAssembly(tcGlobals, tcImports, x.FSharpViewOfMetadata) ] + FSharpProjectContext(thisCcu, assemblies, ad) + + member __.RawFSharpAssemblyData = + let (_tcGlobals, _tcImports, _thisCcu, _ccuSig, _tcSymbolUses, _topAttribs, tcAssemblyData, _ilAssemRef, _ad, _tcAssemblyExpr, _dependencyFiles) = getDetails() + tcAssemblyData + + member __.DependencyFiles = + let (_tcGlobals, _tcImports, _thisCcu, _ccuSig, _tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, _tcAssemblyExpr, dependencyFiles) = getDetails() + dependencyFiles + + member __.AssemblyFullName = + let (_tcGlobals, _tcImports, _thisCcu, _ccuSig, _tcSymbolUses, _topAttribs, _tcAssemblyData, ilAssemRef, _ad, _tcAssemblyExpr, _dependencyFiles) = getDetails() + ilAssemRef.QualifiedName + + override __.ToString() = "FSharpCheckProjectResults(" + projectFileName + ")" + +#if !FABLE_COMPILER + +type FsiInteractiveChecker(legacyReferenceResolver, + reactorOps: IReactorOperations, + tcConfig: TcConfig, + tcGlobals, + tcImports, + tcState) = + + let keepAssemblyContents = false + + member __.ParseAndCheckInteraction (ctok, sourceText: ISourceText, ?userOpName: string) = + async { + let userOpName = defaultArg userOpName "Unknown" + let filename = Path.Combine(tcConfig.implicitIncludeDir, "stdin.fsx") + let suggestNamesForErrors = true // Will always be true, this is just for readability + // Note: projectSourceFiles is only used to compute isLastCompiland, and is ignored if Build.IsScript(mainInputFileName) is true (which it is in this case). + let parsingOptions = FSharpParsingOptions.FromTcConfig(tcConfig, [| filename |], true) + let parseErrors, parseTreeOpt, anyErrors = ParseAndCheckFile.parseFile (sourceText, filename, parsingOptions, userOpName, suggestNamesForErrors) + let dependencyFiles = [| |] // interactions have no dependencies + let parseResults = FSharpParseFileResults(parseErrors, parseTreeOpt, parseHadErrors = anyErrors, dependencyFiles = dependencyFiles) + + let backgroundDiagnostics = [| |] + let reduceMemoryUsage = ReduceMemoryFlag.Yes + let assumeDotNetFramework = tcConfig.primaryAssembly = PrimaryAssembly.Mscorlib + + let applyCompilerOptions tcConfigB = + let fsiCompilerOptions = CompileOptions.GetCoreFsiCompilerOptions tcConfigB + CompileOptions.ParseCompilerOptions (ignore, fsiCompilerOptions, [ ]) + + let loadClosure = + LoadClosure.ComputeClosureOfScriptText(ctok, legacyReferenceResolver, defaultFSharpBinariesDir, + filename, sourceText, CodeContext.Editing, + tcConfig.useSimpleResolution, tcConfig.useFsiAuxLib, + tcConfig.useSdkRefs, new Lexhelp.LexResourceManager(), + applyCompilerOptions, assumeDotNetFramework, + tryGetMetadataSnapshot=(fun _ -> None), reduceMemoryUsage=reduceMemoryUsage) + + let! tcErrors, tcFileInfo = + ParseAndCheckFile.CheckOneFile + (parseResults, sourceText, filename, "project", + tcConfig, tcGlobals, tcImports, tcState, + Map.empty, Some loadClosure, backgroundDiagnostics, + reactorOps, None, userOpName, suggestNamesForErrors) + + return + match tcFileInfo with + | Result.Ok tcFileInfo -> + let errors = [| yield! parseErrors; yield! tcErrors |] + let typeCheckResults = FSharpCheckFileResults (filename, errors, Some tcFileInfo, dependencyFiles, None, reactorOps, false) + let projectResults = + FSharpCheckProjectResults (filename, Some tcConfig, + keepAssemblyContents, errors, + Some(tcGlobals, tcImports, tcFileInfo.ThisCcu, tcFileInfo.CcuSigForFile, + [tcFileInfo.ScopeSymbolUses], None, None, mkSimpleAssemblyRef "stdin", + tcState.TcEnvFromImpls.AccessRights, None, dependencyFiles)) + + parseResults, typeCheckResults, projectResults + + | Result.Error () -> + failwith "unexpected aborted" + } + +#endif diff --git a/src/fcs-fable/src/fsharp/service/FSharpCheckerResults.fsi b/src/fcs-fable/src/fsharp/service/FSharpCheckerResults.fsi new file mode 100644 index 0000000000..48a1800afd --- /dev/null +++ b/src/fcs-fable/src/fsharp/service/FSharpCheckerResults.fsi @@ -0,0 +1,468 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +namespace FSharp.Compiler.SourceCodeServices + +open FSharp.Compiler +open FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.AccessibilityLogic +open FSharp.Compiler.CompileOps +open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.NameResolution +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.Text +open FSharp.Compiler.TypeChecker + +/// Represents the reason why the GetDeclarationLocation operation failed. +[] +type public FSharpFindDeclFailureReason = + + /// Generic reason: no particular information about error apart from a message + | Unknown of message: string + + /// Source code file is not available + | NoSourceCode + + /// Trying to find declaration of ProvidedType without TypeProviderDefinitionLocationAttribute + | ProvidedType of string + + /// Trying to find declaration of ProvidedMember without TypeProviderDefinitionLocationAttribute + | ProvidedMember of string + +/// Represents the result of the GetDeclarationLocation operation. +[] +type public FSharpFindDeclResult = + + /// Indicates a declaration location was not found, with an additional reason + | DeclNotFound of FSharpFindDeclFailureReason + + /// Indicates a declaration location was found + | DeclFound of range + + /// Indicates an external declaration was found + | ExternalDecl of assembly : string * externalSym : ExternalSymbol + +/// Represents the checking context implied by the ProjectOptions +[] +type public FSharpProjectContext = + + /// Get the resolution and full contents of the assemblies referenced by the project options + member GetReferencedAssemblies : unit -> FSharpAssembly list + + /// Get the accessibility rights for this project context w.r.t. InternalsVisibleTo attributes granting access to other assemblies + member AccessibilityRights : FSharpAccessibilityRights + +/// Options used to determine active --define conditionals and other options relevant to parsing files in a project +type public FSharpParsingOptions = + { + SourceFiles: string[] + ConditionalCompilationDefines: string list + ErrorSeverityOptions: FSharpErrorSeverityOptions + IsInteractive: bool + LightSyntax: bool option + CompilingFsLib: bool + IsExe: bool + } + static member Default: FSharpParsingOptions + + static member internal FromTcConfig: tcConfig: TcConfig * sourceFiles: string[] * isInteractive: bool -> FSharpParsingOptions + + static member internal FromTcConfigBuilder: tcConfigB: TcConfigBuilder * sourceFiles: string[] * isInteractive: bool -> FSharpParsingOptions + +[] +type internal TypeCheckInfo = + internal new : + tcConfig: TcConfig * + tcGlobals: TcGlobals * + ccuSigForFile: ModuleOrNamespaceType * + thisCcu: CcuThunk * + tcImports: TcImports * + tcAccessRights: AccessorDomain * + projectFileName: string * + mainInputFileName: string * + sResolutions: TcResolutions * + sSymbolUses: TcSymbolUses * + sFallback: NameResolutionEnv * + loadClosure : LoadClosure option * + reactorOps : IReactorOperations * + textSnapshotInfo: obj option * + implFileOpt: TypedImplFile option * + openDeclarations: OpenDeclaration[] + -> TypeCheckInfo + member ScopeResolutions: TcResolutions + member ScopeSymbolUses: TcSymbolUses + member TcGlobals: TcGlobals + member TcImports: TcImports + member CcuSigForFile: ModuleOrNamespaceType + member ThisCcu: CcuThunk + member ImplementationFile: TypedImplFile option + +/// A handle to the results of CheckFileInProject. +[] +type public FSharpCheckFileResults = + internal new : + filename: string * + errors: FSharpErrorInfo[] * + scopeOptX: TypeCheckInfo option * + dependencyFiles: string[] * + builderX: IncrementalBuilder option * + reactorOpsX: IReactorOperations * + keepAssemblyContents: bool + -> FSharpCheckFileResults + + /// The errors returned by parsing a source file. + member Errors : FSharpErrorInfo[] + + /// Get a view of the contents of the assembly up to and including the file just checked + member PartialAssemblySignature : FSharpAssemblySignature + + /// Get the resolution of the ProjectOptions + member ProjectContext : FSharpProjectContext + + /// Indicates whether type checking successfully occurred with some results returned. If false, indicates that + /// an unrecoverable error in earlier checking/parsing/resolution steps. + member HasFullTypeCheckInfo: bool + +#if !FABLE_COMPILER + /// Tries to get the current successful TcImports. This is only used in testing. Do not use it for other stuff. + member internal TryGetCurrentTcImports: unit -> TcImports option +#endif + + /// Indicates the set of files which must be watched to accurately track changes that affect these results, + /// Clients interested in reacting to updates to these files should watch these files and take actions as described + /// in the documentation for compiler service. + member DependencyFiles : string[] + + /// Get the items for a declaration list + /// + /// + /// If this is present, it is used to filter declarations based on location in the + /// parse tree, specifically at 'open' declarations, 'inherit' of class or interface + /// 'record field' locations and r.h.s. of 'range' operator a..b + /// + /// The line number where the completion is happening + /// + /// Partial long name. QuickParse.GetPartialLongNameEx can be used to get it. + /// + /// + /// The text of the line where the completion is happening. This is only used to make a couple + /// of adhoc corrections to completion accuracy (e.g. checking for "..") + /// + /// + /// Function that returns all entities from current and referenced assemblies. + /// + /// + /// If text has been used from a captured name resolution from the typecheck, then + /// callback to the client to check if the text has changed. If it has, then give up + /// and assume that we're going to repeat the operation later on. + /// + /// An optional string used for tracing compiler operations associated with this request. + member GetDeclarationListInfo : ParsedFileResultsOpt:FSharpParseFileResults option * line: int * lineText:string * partialName: PartialLongName * ?getAllEntities: (unit -> AssemblySymbol list) * ?hasTextChangedSinceLastTypecheck: (obj * range -> bool) * ?userOpName: string -> Async + + /// Get the items for a declaration list in FSharpSymbol format + /// + /// + /// If this is present, it is used to filter declarations based on location in the + /// parse tree, specifically at 'open' declarations, 'inherit' of class or interface + /// 'record field' locations and r.h.s. of 'range' operator a..b + /// + /// The line number where the completion is happening + /// + /// Partial long name. QuickParse.GetPartialLongNameEx can be used to get it. + /// + /// + /// The text of the line where the completion is happening. This is only used to make a couple + /// of adhoc corrections to completion accuracy (e.g. checking for "..") + /// + /// + /// Function that returns all entities from current and referenced assemblies. + /// + /// + /// If text has been used from a captured name resolution from the typecheck, then + /// callback to the client to check if the text has changed. If it has, then give up + /// and assume that we're going to repeat the operation later on. + /// + /// An optional string used for tracing compiler operations associated with this request. + member GetDeclarationListSymbols : ParsedFileResultsOpt:FSharpParseFileResults option * line: int * lineText:string * partialName: PartialLongName * ?getAllEntities: (unit -> AssemblySymbol list) * ?hasTextChangedSinceLastTypecheck: (obj * range -> bool) * ?userOpName: string -> Async + + /// Compute a formatted tooltip for the given location + /// + /// The line number where the information is being requested. + /// The column number at the end of the identifiers where the information is being requested. + /// The text of the line where the information is being requested. + /// The identifiers at the location where the information is being requested. + /// Used to discriminate between 'identifiers', 'strings' and others. For strings, an attempt is made to give a tooltip for a #r "..." location. Use a value from FSharpTokenInfo.Tag, or FSharpTokenTag.Identifier, unless you have other information available. + /// An optional string used for tracing compiler operations associated with this request. + member GetStructuredToolTipText : line:int * colAtEndOfNames:int * lineText:string * names:string list * tokenTag:int * ?userOpName: string -> Async + + /// Compute a formatted tooltip for the given location + /// + /// The line number where the information is being requested. + /// The column number at the end of the identifiers where the information is being requested. + /// The text of the line where the information is being requested. + /// The identifiers at the location where the information is being requested. + /// Used to discriminate between 'identifiers', 'strings' and others. For strings, an attempt is made to give a tooltip for a #r "..." location. Use a value from FSharpTokenInfo.Tag, or FSharpTokenTag.Identifier, unless you have other information available. + /// An optional string used for tracing compiler operations associated with this request. + member GetToolTipText : line:int * colAtEndOfNames:int * lineText:string * names:string list * tokenTag:int * ?userOpName: string -> Async + + /// Compute the Visual Studio F1-help key identifier for the given location, based on name resolution results + /// + /// The line number where the information is being requested. + /// The column number at the end of the identifiers where the information is being requested. + /// The text of the line where the information is being requested. + /// The identifiers at the location where the information is being requested. + /// An optional string used for tracing compiler operations associated with this request. + member GetF1Keyword : line:int * colAtEndOfNames:int * lineText:string * names:string list * ?userOpName: string -> Async + + + /// Compute a set of method overloads to show in a dialog relevant to the given code location. + /// + /// The line number where the information is being requested. + /// The column number at the end of the identifiers where the information is being requested. + /// The text of the line where the information is being requested. + /// The identifiers at the location where the information is being requested. + /// An optional string used for tracing compiler operations associated with this request. + member GetMethods : line:int * colAtEndOfNames:int * lineText:string * names:string list option * ?userOpName: string -> Async + + /// Compute a set of method overloads to show in a dialog relevant to the given code location. The resulting method overloads are returned as symbols. + /// The line number where the information is being requested. + /// The column number at the end of the identifiers where the information is being requested. + /// The text of the line where the information is being requested. + /// The identifiers at the location where the information is being requested. + /// An optional string used for tracing compiler operations associated with this request. + member GetMethodsAsSymbols : line:int * colAtEndOfNames:int * lineText:string * names:string list * ?userOpName: string -> Async + + /// Resolve the names at the given location to the declaration location of the corresponding construct. + /// + /// The line number where the information is being requested. + /// The column number at the end of the identifiers where the information is being requested. + /// The text of the line where the information is being requested. + /// The identifiers at the location where the information is being requested. + /// If not given, then get the location of the symbol. If false, then prefer the location of the corresponding symbol in the implementation of the file (rather than the signature if present). If true, prefer the location of the corresponding symbol in the signature of the file (rather than the implementation). + /// An optional string used for tracing compiler operations associated with this request. + member GetDeclarationLocation : line:int * colAtEndOfNames:int * lineText:string * names:string list * ?preferFlag:bool * ?userOpName: string -> Async + + /// Resolve the names at the given location to a use of symbol. + /// + /// The line number where the information is being requested. + /// The column number at the end of the identifiers where the information is being requested. + /// The text of the line where the information is being requested. + /// The identifiers at the location where the information is being requested. + /// An optional string used for tracing compiler operations associated with this request. + member GetSymbolUseAtLocation : line:int * colAtEndOfNames:int * lineText:string * names:string list * ?userOpName: string -> Async + + /// Get any extra colorization info that is available after the typecheck + member GetSemanticClassification : range option -> struct (range * SemanticClassificationType)[] + + /// Get the locations of format specifiers + [] + member GetFormatSpecifierLocations : unit -> range[] + + /// Get the locations of and number of arguments associated with format specifiers + member GetFormatSpecifierLocationsAndArity : unit -> (range*int)[] + + /// Get all textual usages of all symbols throughout the file + member GetAllUsesOfAllSymbolsInFile : unit -> Async + + /// Get the textual usages that resolved to the given symbol throughout the file + member GetUsesOfSymbolInFile : symbol:FSharpSymbol -> Async + + member internal GetVisibleNamespacesAndModulesAtPoint : pos -> Async + + /// Find the most precise display environment for the given line and column. + member GetDisplayContextForPos : pos : pos -> Async + + /// Determines if a long ident is resolvable at a specific point. + /// An optional string used for tracing compiler operations associated with this request. + member internal IsRelativeNameResolvable: cursorPos : pos * plid : string list * item: Item * ?userOpName: string -> Async + + /// Determines if a long ident is resolvable at a specific point. + /// An optional string used for tracing compiler operations associated with this request. + member IsRelativeNameResolvableFromSymbol: cursorPos : pos * plid : string list * symbol: FSharpSymbol * ?userOpName: string -> Async + + /// Represents complete typechecked implementation file, including its typechecked signatures if any. + member ImplementationFile: FSharpImplementationFileContents option + + /// Open declarations in the file, including auto open modules. + member OpenDeclarations: FSharpOpenDeclaration[] + + /// Internal constructor + static member internal MakeEmpty : + filename: string * + creationErrors: FSharpErrorInfo[] * + reactorOps: IReactorOperations * + keepAssemblyContents: bool + -> FSharpCheckFileResults + + /// Internal constructor + static member internal Make: + mainInputFileName: string * + projectFileName: string * + tcConfig: TcConfig * + tcGlobals: TcGlobals * + isIncompleteTypeCheckEnvironment: bool * + builder: IncrementalBuilder * + dependencyFiles: string[] * + creationErrors: FSharpErrorInfo[] * + parseErrors: FSharpErrorInfo[] * + tcErrors: FSharpErrorInfo[] * + reactorOps : IReactorOperations * + keepAssemblyContents: bool * + ccuSigForFile: ModuleOrNamespaceType * + thisCcu: CcuThunk * + tcImports: TcImports * + tcAccessRights: AccessorDomain * + sResolutions: TcResolutions * + sSymbolUses: TcSymbolUses * + sFallback: NameResolutionEnv * + loadClosure : LoadClosure option * + implFileOpt: TypedImplFile option * + openDeclarations: OpenDeclaration[] + -> FSharpCheckFileResults + +#if !FABLE_COMPILER + /// Internal constructor - check a file and collect errors + static member internal CheckOneFile: + parseResults: FSharpParseFileResults * + sourceText: ISourceText * + mainInputFileName: string * + projectFileName: string * + tcConfig: TcConfig * + tcGlobals: TcGlobals * + tcImports: TcImports * + tcState: TcState * + moduleNamesDict: ModuleNamesDict * + loadClosure: LoadClosure option * + backgroundDiagnostics: (PhasedDiagnostic * FSharpErrorSeverity)[] * + reactorOps: IReactorOperations * + textSnapshotInfo : obj option * + userOpName: string * + isIncompleteTypeCheckEnvironment: bool * + builder: IncrementalBuilder * + dependencyFiles: string[] * + creationErrors:FSharpErrorInfo[] * + parseErrors:FSharpErrorInfo[] * + keepAssemblyContents: bool * + suggestNamesForErrors: bool + -> Async +#endif + +/// The result of calling TypeCheckResult including the possibility of abort and background compiler not caught up. +and [] public FSharpCheckFileAnswer = + /// Aborted because cancellation caused an abandonment of the operation + | Aborted + + /// Success + | Succeeded of FSharpCheckFileResults + +/// A handle to the results of CheckFileInProject. +[] +type public FSharpCheckProjectResults = + + /// The errors returned by processing the project + member Errors: FSharpErrorInfo[] + + /// Get a view of the overall signature of the assembly. Only valid to use if HasCriticalErrors is false. + member AssemblySignature: FSharpAssemblySignature + + /// Get a view of the overall contents of the assembly. Only valid to use if HasCriticalErrors is false. + member AssemblyContents: FSharpAssemblyContents + + /// Get an optimized view of the overall contents of the assembly. Only valid to use if HasCriticalErrors is false. + member GetOptimizedAssemblyContents: unit -> FSharpAssemblyContents + + /// Get the resolution of the ProjectOptions + member ProjectContext: FSharpProjectContext + + /// Get the textual usages that resolved to the given symbol throughout the project + member GetUsesOfSymbol: symbol:FSharpSymbol -> Async + + /// Get all textual usages of all symbols throughout the project + member GetAllUsesOfAllSymbols: unit -> Async + + /// Indicates if critical errors existed in the project options + member HasCriticalErrors: bool + + /// Indicates the set of files which must be watched to accurately track changes that affect these results, + /// Clients interested in reacting to updates to these files should watch these files and take actions as described + /// in the documentation for compiler service. + member DependencyFiles: string[] + + member internal RawFSharpAssemblyData : IRawFSharpAssemblyData option + + // Internal constructor. + internal new : + projectFileName:string * + tcConfigOption: TcConfig option * + keepAssemblyContents: bool * + errors: FSharpErrorInfo[] * + details:(TcGlobals * TcImports * CcuThunk * ModuleOrNamespaceType * TcSymbolUses list * TopAttribs option * IRawFSharpAssemblyData option * ILAssemblyRef * AccessorDomain * TypedImplFile list option * string[]) option + -> FSharpCheckProjectResults + +module internal ParseAndCheckFile = + + val parseFile: + sourceText: ISourceText * + fileName: string * + options: FSharpParsingOptions * + userOpName: string * + suggestNamesForErrors: bool + -> FSharpErrorInfo[] * ParsedInput option * bool + + val matchBraces: + sourceText: ISourceText * + fileName: string * + options: FSharpParsingOptions * + userOpName: string * + suggestNamesForErrors: bool + -> (range * range)[] + +#if FABLE_COMPILER + val CheckOneFile: + parseResults: FSharpParseFileResults * + sourceText: ISourceText * + mainInputFileName: string * + projectFileName: string * + tcConfig: TcConfig * + tcGlobals: TcGlobals * + tcImports: TcImports * + tcState: TcState * + moduleNamesDict: ModuleNamesDict * + loadClosure: LoadClosure option * + backgroundDiagnostics: (PhasedDiagnostic * FSharpErrorSeverity)[] * + reactorOps: IReactorOperations * + textSnapshotInfo : obj option * + userOpName: string * + suggestNamesForErrors: bool + -> FSharpErrorInfo[] * Result +#endif + +#if !FABLE_COMPILER + +// An object to typecheck source in a given typechecking environment. +// Used internally to provide intellisense over F# Interactive. +type internal FsiInteractiveChecker = + internal new: + ReferenceResolver.Resolver * + ops: IReactorOperations * + tcConfig: TcConfig * + tcGlobals: TcGlobals * + tcImports: TcImports * + tcState: TcState + -> FsiInteractiveChecker + + member internal ParseAndCheckInteraction : + ctok: CompilationThreadToken * + sourceText:ISourceText * + ?userOpName: string + -> Async + +#endif + +module internal FSharpCheckerResultsSettings = + val defaultFSharpBinariesDir: string + + val maxTimeShareMilliseconds : int64 \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/service/IncrementalBuild.fs b/src/fcs-fable/src/fsharp/service/IncrementalBuild.fs index 55e67bcd7c..0725326871 100755 --- a/src/fcs-fable/src/fsharp/service/IncrementalBuild.fs +++ b/src/fcs-fable/src/fsharp/service/IncrementalBuild.fs @@ -4,27 +4,28 @@ namespace FSharp.Compiler open System -open System.Collections.Concurrent open System.Collections.Generic open System.IO open System.Threading + open FSharp.Compiler -open FSharp.Compiler.NameResolution -open FSharp.Compiler.Tastops -open FSharp.Compiler.Lib open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.ILBinaryReader open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.CompileOps open FSharp.Compiler.CompileOptions -open FSharp.Compiler.Ast open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.TcGlobals -open FSharp.Compiler.TypeChecker -open FSharp.Compiler.Tast +open FSharp.Compiler.Lib +open FSharp.Compiler.NameResolution open FSharp.Compiler.Range open FSharp.Compiler.SourceCodeServices +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypeChecker +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps + open Internal.Utilities.Collections #if !FABLE_COMPILER @@ -128,10 +129,10 @@ module internal IncrementalBuild = | VectorBuildRule ve -> ve.Name // Ids of exprs - let nextid = ref 999 // Number ids starting with 1000 to discern them + let mutable nextid = 999 // Number ids starting with 1000 to discern them let NextId() = - nextid:=!nextid+1 - Id(!nextid) + nextid <- nextid + 1 + Id(nextid) type INode = abstract Name: string @@ -184,8 +185,8 @@ module internal IncrementalBuild = // Create the rules. let createRules() = - { RuleList = names |> List.map (function NamedVectorOutput(v) -> v.Name, VectorBuildRule(v.Expr) - | NamedScalarOutput(s) -> s.Name, ScalarBuildRule(s.Expr)) } + { RuleList = names |> List.map (function NamedVectorOutput v -> v.Name, VectorBuildRule(v.Expr) + | NamedScalarOutput s -> s.Name, ScalarBuildRule(s.Expr)) } // Ensure that all names are unique. let ensureUniqueNames (expr: BuildRuleExpr) (acc: Map) = @@ -232,17 +233,17 @@ module internal IncrementalBuild = | Available of obj * DateTime * InputSignature /// Get the available result. Throw an exception if not available. - member x.GetAvailable() = match x with Available(o, _, _) ->o | _ -> failwith "No available result" + member x.GetAvailable() = match x with Available (o, _, _) ->o | _ -> failwith "No available result" /// Get the time stamp if available. Otherwise MaxValue. - member x.Timestamp = match x with Available(_, ts, _) -> ts | InProgress(_, ts) -> ts | _ -> DateTime.MaxValue + member x.Timestamp = match x with Available (_, ts, _) -> ts | InProgress(_, ts) -> ts | _ -> DateTime.MaxValue /// Get the time stamp if available. Otherwise MaxValue. - member x.InputSignature = match x with Available(_, _, signature) -> signature | _ -> UnevaluatedInput + member x.InputSignature = match x with Available (_, _, signature) -> signature | _ -> UnevaluatedInput member x.ResultIsInProgress = match x with | InProgress _ -> true | _ -> false member x.GetInProgressContinuation ctok = match x with | InProgress (f, _) -> f ctok | _ -> failwith "not in progress" - member x.TryGetAvailable() = match x with | InProgress _ | NotAvailable -> None | Available(obj, dt, i) -> Some (obj, dt, i) + member x.TryGetAvailable() = match x with | InProgress _ | NotAvailable -> None | Available (obj, dt, i) -> Some (obj, dt, i) /// An immutable sparse vector of results. type ResultVector(size, zeroElementTimestamp, map) = @@ -252,12 +253,12 @@ module internal IncrementalBuild = | None->NotAvailable let asList = lazy List.map (fun i->i, get i) [0..size-1] - static member OfSize(size) = ResultVector(size, DateTime.MinValue, Map.empty) + static member OfSize size = ResultVector(size, DateTime.MinValue, Map.empty) member rv.Size = size member rv.Get slot = get slot - member rv.Resize(newsize) = - if size<>newsize then - ResultVector(newsize, zeroElementTimestamp, map |> Map.filter(fun s _ -> s < newsize)) + member rv.Resize newSize = + if size<>newSize then + ResultVector(newSize, zeroElementTimestamp, map |> Map.filter(fun s _ -> s < newSize)) else rv member rv.Set(slot, value) = @@ -268,7 +269,7 @@ module internal IncrementalBuild = ResultVector(size, zeroElementTimestamp, Map.add slot value map) member rv.MaxTimestamp() = - let maximize (lasttimestamp: DateTime) (_, result: Result) = max lasttimestamp result.Timestamp + let maximize (lastTimestamp: DateTime) (_, result: Result) = max lastTimestamp result.Timestamp List.fold maximize zeroElementTimestamp (asList.Force()) member rv.Signature() = @@ -301,7 +302,7 @@ module internal IncrementalBuild = | VectorAction of Id * (*taskname*)string * DateTime * InputSignature * (CompilationThreadToken -> Cancellable) | ResizeResultAction of Id * (*slotcount*) int /// Execute one action and return a corresponding result. - member action.Execute(ctok) = + member action.Execute ctok = cancellable { match action with | IndexedAction(id, _taskname, slot, slotcount, timestamp, func) -> let res = func ctok in return IndexedResult(id, slot, slotcount, res, timestamp) @@ -354,7 +355,7 @@ module internal IncrementalBuild = | VectorInput(id, _) ->if seek=id then Some (VectorBuildRule ve) else None | VectorScanLeft(id, _, a, i, _) -> if seek=id then Some (VectorBuildRule ve) else - let result = scalarExprOfId(a) + let result = scalarExprOfId a match result with Some _ -> result | None->vectorExprOfId i | VectorMap(id, _, i, _) ->if seek=id then Some (VectorBuildRule ve) else vectorExprOfId i | VectorStamp (id, _, i, _) ->if seek=id then Some (VectorBuildRule ve) else vectorExprOfId i @@ -371,7 +372,7 @@ module internal IncrementalBuild = | ScalarBuildRule se ->scalarExprOfId se | VectorBuildRule ve ->vectorExprOfId ve - let exprs = bt.Rules.RuleList |> List.map (fun(_, root) ->exprOfId(root)) |> List.filter Option.isSome + let exprs = bt.Rules.RuleList |> List.map (fun(_, root) ->exprOfId root) |> List.filter Option.isSome match exprs with | Some expr :: _ -> expr | _ -> failwith (sprintf "GetExprById did not find an expression for Id") @@ -418,24 +419,24 @@ module internal IncrementalBuild = /// Get the maximum build stamp for an output. let MaxTimestamp(bt: PartialBuild, id) = match bt.Results.TryFind id with - | Some resultset -> - match resultset with - | ScalarResult(rs) -> rs.Timestamp + | Some resultSet -> + match resultSet with + | ScalarResult rs -> rs.Timestamp | VectorResult rv -> rv.MaxTimestamp() | None -> DateTime.MaxValue let Signature(bt: PartialBuild, id) = match bt.Results.TryFind id with - | Some resultset -> - match resultset with - | ScalarResult(rs) -> rs.InputSignature + | Some resultSet -> + match resultSet with + | ScalarResult rs -> rs.InputSignature | VectorResult rv -> rv.Signature() | None -> UnevaluatedInput /// Get all the results for the given expr. let AllResultsOfExpr extractor (bt: PartialBuild) (expr: VectorBuildRule) = let GetAvailable (rv: ResultVector) = - let Extract acc (_, result) = (extractor result)::acc + let Extract acc (_, result) = (extractor result) :: acc List.rev (rv.FoldLeft Extract []) let GetVectorResultById id = match bt.Results.TryFind id with @@ -461,7 +462,7 @@ module internal IncrementalBuild = let AvailableAllResultsOfExpr bt expr = let msg = "Expected all results to be available" - AllResultsOfExpr (function Available(o, _, _) -> o | _ -> failwith msg) bt expr + AllResultsOfExpr (function Available (o, _, _) -> o | _ -> failwith msg) bt expr /// Bind a set of build rules to a set of input values. let ToBound(buildRules: BuildRules, inputs: BuildInput list) = @@ -474,7 +475,7 @@ module internal IncrementalBuild = match input with | BuildInput.Scalar (node, value) -> if node.Name = n then - yield ScalarResult(Available(value, now, BoundInputScalar)) + yield ScalarResult(Available (value, now, BoundInputScalar)) | _ -> () ] List.foldBack (Map.add id) matches results | ScalarMap(_, _, se, _) ->applyScalarExpr(se, results) @@ -488,7 +489,7 @@ module internal IncrementalBuild = | BuildInput.Scalar _ -> () | BuildInput.Vector (node, values) -> if node.Name = n then - let results = values|>List.mapi(fun i value->i, Available(value, now, BoundInputVector)) + let results = values|>List.mapi(fun i value->i, Available (value, now, BoundInputVector)) yield VectorResult(ResultVector(values.Length, DateTime.MinValue, results|>Map.ofList)) ] List.foldBack (Map.add id) matches results | VectorScanLeft(_, _, a, i, _) ->ApplyVectorExpr(i, applyScalarExpr(a, results)) @@ -517,9 +518,9 @@ module internal IncrementalBuild = seen.[id] <- true false - let shouldEvaluate(bt, currentsig: InputSignature, id) = - if currentsig.IsEvaluated then - currentsig <> Signature(bt, id) + let shouldEvaluate(bt, currentSig: InputSignature, id) = + if currentSig.IsEvaluated then + currentSig <> Signature(bt, id) else false /// Make sure the result vector saved matches the size of expr @@ -557,24 +558,24 @@ module internal IncrementalBuild = let inputResult = GetVectorExprResult (bt, inputExpr, slot) match accumulatorResult, inputResult with - | Available(accumulator, accumulatortimesamp, _accumulatorInputSig), Available(input, inputtimestamp, _inputSig) -> - let inputtimestamp = max inputtimestamp accumulatortimesamp - let prevoutput = GetVectorExprResult (bt, ve, slot) - let outputtimestamp = prevoutput.Timestamp + | Available (accumulator, accumulatorTimestamp, _accumulatorInputSig), Available (input, inputTimestamp, _inputSig) -> + let inputTimestamp = max inputTimestamp accumulatorTimestamp + let prevOutput = GetVectorExprResult (bt, ve, slot) + let outputTimestamp = prevOutput.Timestamp let scanOpOpt = - if inputtimestamp <> outputtimestamp then + if inputTimestamp <> outputTimestamp then Some (fun ctok -> func ctok accumulator input) - elif prevoutput.ResultIsInProgress then - Some prevoutput.GetInProgressContinuation + elif prevOutput.ResultIsInProgress then + Some prevOutput.GetInProgressContinuation else // up-to-date and complete, no work required None match scanOpOpt with - | Some scanOp -> Some (actionFunc (IndexedAction(id, taskname, slot, cardinality, inputtimestamp, scanOp)) acc) + | Some scanOp -> Some (actionFunc (IndexedAction(id, taskname, slot, cardinality, inputTimestamp, scanOp)) acc) | None -> None | _ -> None - match ([0..limit-1]|>List.tryPick Scan) with Some (acc) ->acc | None->acc + match ([0..limit-1]|>List.tryPick Scan) with Some acc ->acc | None->acc | None -> acc // Check each slot for an action that may be performed. @@ -586,19 +587,19 @@ module internal IncrementalBuild = | Some cardinality -> if cardinality=0 then // For vector length zero, just propagate the prior timestamp. - let inputtimestamp = MaxTimestamp(bt, inputExpr.Id) - let outputtimestamp = MaxTimestamp(bt, id) - if inputtimestamp <> outputtimestamp then - actionFunc (VectorAction(id, taskname, inputtimestamp, EmptyTimeStampedInput inputtimestamp, fun _ -> cancellable.Return [||])) acc + let inputTimestamp = MaxTimestamp(bt, inputExpr.Id) + let outputTimestamp = MaxTimestamp(bt, id) + if inputTimestamp <> outputTimestamp then + actionFunc (VectorAction(id, taskname, inputTimestamp, EmptyTimeStampedInput inputTimestamp, fun _ -> cancellable.Return [||])) acc else acc else let MapResults acc slot = - let inputtimestamp = GetVectorExprResult(bt, inputExpr, slot).Timestamp - let outputtimestamp = GetVectorExprResult(bt, ve, slot).Timestamp - if inputtimestamp <> outputtimestamp then + let inputTimestamp = GetVectorExprResult(bt, inputExpr, slot).Timestamp + let outputTimestamp = GetVectorExprResult(bt, ve, slot).Timestamp + if inputTimestamp <> outputTimestamp then let OneToOneOp ctok = Eventually.Done (func ctok (GetVectorExprResult(bt, inputExpr, slot).GetAvailable())) - actionFunc (IndexedAction(id, taskname, slot, cardinality, inputtimestamp, OneToOneOp)) acc + actionFunc (IndexedAction(id, taskname, slot, cardinality, inputTimestamp, OneToOneOp)) acc else acc match optSlot with | None -> @@ -617,20 +618,20 @@ module internal IncrementalBuild = | Some cardinality -> if cardinality=0 then // For vector length zero, just propagate the prior timestamp. - let inputtimestamp = MaxTimestamp(bt, inputExpr.Id) - let outputtimestamp = MaxTimestamp(bt, id) - if inputtimestamp <> outputtimestamp then - actionFunc (VectorAction(id, taskname, inputtimestamp, EmptyTimeStampedInput inputtimestamp, fun _ -> cancellable.Return [||])) acc + let inputTimestamp = MaxTimestamp(bt, inputExpr.Id) + let outputTimestamp = MaxTimestamp(bt, id) + if inputTimestamp <> outputTimestamp then + actionFunc (VectorAction(id, taskname, inputTimestamp, EmptyTimeStampedInput inputTimestamp, fun _ -> cancellable.Return [||])) acc else acc else let checkStamp acc slot = - let inputresult = GetVectorExprResult (bt, inputExpr, slot) - match inputresult with - | Available(ires, _, _) -> - let oldtimestamp = GetVectorExprResult(bt, ve, slot).Timestamp - let newtimestamp = func cache ctok ires - if newtimestamp <> oldtimestamp then - actionFunc (IndexedAction(id, taskname, slot, cardinality, newtimestamp, fun _ -> Eventually.Done ires)) acc + let inputResult = GetVectorExprResult (bt, inputExpr, slot) + match inputResult with + | Available (ires, _, _) -> + let oldTimestamp = GetVectorExprResult(bt, ve, slot).Timestamp + let newTimestamp = func cache ctok ires + if newTimestamp <> oldTimestamp then + actionFunc (IndexedAction(id, taskname, slot, cardinality, newTimestamp, fun _ -> Eventually.Done ires)) acc else acc | _ -> acc match optSlot with @@ -644,11 +645,11 @@ module internal IncrementalBuild = | VectorMultiplex(id, taskname, inputExpr, func) -> let acc = match GetScalarExprResult (bt, inputExpr) with - | Available(inp, inputtimestamp, inputsig) -> - let outputtimestamp = MaxTimestamp(bt, id) - if inputtimestamp <> outputtimestamp then + | Available (inp, inputTimestamp, inputsig) -> + let outputTimestamp = MaxTimestamp(bt, id) + if inputTimestamp <> outputTimestamp then let MultiplexOp ctok = func ctok inp |> cancellable.Return - actionFunc (VectorAction(id, taskname, inputtimestamp, inputsig, MultiplexOp)) acc + actionFunc (VectorAction(id, taskname, inputTimestamp, inputsig, MultiplexOp)) acc else acc | _ -> acc visitScalar inputExpr acc @@ -661,16 +662,16 @@ module internal IncrementalBuild = | ScalarDemultiplex (id, taskname, inputExpr, func) -> let acc = match GetVectorExprResultVector (bt, inputExpr) with - | Some inputresult -> - let currentsig = inputresult.Signature() - if shouldEvaluate(bt, currentsig, id) then - let inputtimestamp = MaxTimestamp(bt, inputExpr.Id) + | Some inputResult -> + let currentSig = inputResult.Signature() + if shouldEvaluate(bt, currentSig, id) then + let inputTimestamp = MaxTimestamp(bt, inputExpr.Id) let DemultiplexOp ctok = cancellable { let input = AvailableAllResultsOfExpr bt inputExpr |> List.toArray return! func ctok input } - actionFunc (ScalarAction(id, taskname, inputtimestamp, currentsig, DemultiplexOp)) acc + actionFunc (ScalarAction(id, taskname, inputTimestamp, currentSig, DemultiplexOp)) acc else acc | None -> acc @@ -679,11 +680,11 @@ module internal IncrementalBuild = | ScalarMap (id, taskname, inputExpr, func) -> let acc = match GetScalarExprResult (bt, inputExpr) with - | Available(inp, inputtimestamp, inputsig) -> - let outputtimestamp = MaxTimestamp(bt, id) - if inputtimestamp <> outputtimestamp then + | Available (inp, inputTimestamp, inputsig) -> + let outputTimestamp = MaxTimestamp(bt, id) + if inputTimestamp <> outputTimestamp then let MapOp ctok = func ctok inp |> cancellable.Return - actionFunc (ScalarAction(id, taskname, inputtimestamp, inputsig, MapOp)) acc + actionFunc (ScalarAction(id, taskname, inputTimestamp, inputsig, MapOp)) acc else acc | _ -> acc @@ -710,7 +711,7 @@ module internal IncrementalBuild = | Some cardinality -> let CheckStamp acc slot = match GetVectorExprResult (bt, inputExpr, slot) with - | Available(ires, _, _) -> max acc (func cache ctok ires) + | Available (ires, _, _) -> max acc (func cache ctok ires) | _ -> acc [0..cardinality-1] |> List.fold CheckStamp acc | None -> acc @@ -725,16 +726,16 @@ module internal IncrementalBuild = | Some resultSet -> match resultSet with | VectorResult rv -> - let rv = rv.Resize(slotcount) + let rv = rv.Resize slotcount let results = Map.add id (VectorResult rv) bt.Results PartialBuild(bt.Rules, results) | _ -> failwith "Unexpected" | None -> failwith "Unexpected" | ScalarValuedResult(id, value, timestamp, inputsig) -> - PartialBuild(bt.Rules, Map.add id (ScalarResult(Available(value, timestamp, inputsig))) bt.Results) + PartialBuild(bt.Rules, Map.add id (ScalarResult(Available (value, timestamp, inputsig))) bt.Results) | VectorValuedResult(id, values, timestamp, inputsig) -> let Append acc slot = - Map.add slot (Available(values.[slot], timestamp, inputsig)) acc + Map.add slot (Available (values.[slot], timestamp, inputsig)) acc let results = [0..values.Length-1]|>List.fold Append Map.empty let results = VectorResult(ResultVector(values.Length, timestamp, results)) let bt = PartialBuild(bt.Rules, Map.add id results bt.Results) @@ -752,11 +753,11 @@ module internal IncrementalBuild = let result = match value with | Eventually.Done res -> - Available(res, timestamp, IndexedValueElement timestamp) + Available (res, timestamp, IndexedValueElement timestamp) | Eventually.NotYetDone f -> InProgress (f, timestamp) let results = rv.Resize(slotcount).Set(index, result) - PartialBuild(bt.Rules, Map.add id (VectorResult(results)) bt.Results) + PartialBuild(bt.Rules, Map.add id (VectorResult results) bt.Results) | _ -> failwith "Unexpected" let mutable injectCancellationFault = false @@ -767,7 +768,7 @@ module internal IncrementalBuild = /// Apply the result, and call the 'save' function to update the build. let ExecuteApply (ctok: CompilationThreadToken) save (action: Action) bt = cancellable { - let! actionResult = action.Execute(ctok) + let! actionResult = action.Execute ctok let newBt = ApplyResult(actionResult, bt) save ctok newBt return newBt @@ -784,10 +785,10 @@ module internal IncrementalBuild = if gen>5000 then failwith "Infinite loop in incremental builder?" #endif - let worklist = CollectActions cache target bt + let workList = CollectActions cache target bt let! newBt = - (bt, worklist) ||> Cancellable.fold (fun bt action -> + (bt, workList) ||> Cancellable.fold (fun bt action -> if injectCancellationFault then Cancellable.canceled() else @@ -802,10 +803,10 @@ module internal IncrementalBuild = cancellable { // REVIEW: we're building up the whole list of actions on the fringe of the work tree, // executing one thing and then throwing the list away. What about saving the list inside the Build instance? - let worklist = CollectActions cache target bt + let workList = CollectActions cache target bt - match worklist with - | action::_ -> + match workList with + | action :: _ -> let! res = ExecuteApply ctok save action bt return Some res | _ -> @@ -824,8 +825,8 @@ module internal IncrementalBuild = /// Check if an output is up-to-date and ready let IsReady cache target bt = - let worklist = CollectActions cache target bt - worklist.IsEmpty + let workList = CollectActions cache target bt + workList.IsEmpty /// Check if an output is up-to-date and ready let MaxTimeStampInDependencies cache ctok target bt = @@ -838,7 +839,7 @@ module internal IncrementalBuild = match bt.Results.TryFind se.Id with | Some result -> match result with - | ScalarResult(sr) -> + | ScalarResult sr -> match sr.TryGetAvailable() with | Some (r, timestamp, _) -> Some (downcast r, timestamp) | None -> None @@ -872,7 +873,7 @@ module internal IncrementalBuild = | VectorResult rv -> let MatchNames acc (slot, result) = match result with - | Available(o, _, _) -> + | Available (o, _, _) -> let o = o :?> 'T if found o then Some slot else acc | _ -> acc @@ -961,11 +962,11 @@ module internal IncrementalBuild = /// Declare a named scalar output. member b.DeclareScalarOutput(output: Scalar<'T>)= - outputs <- NamedScalarOutput(output) :: outputs + outputs <- NamedScalarOutput output :: outputs /// Declare a named vector output. member b.DeclareVectorOutput(output: Vector<'T>)= - outputs <- NamedVectorOutput(output) :: outputs + outputs <- NamedVectorOutput output :: outputs /// Set the concrete inputs for this build member b.GetInitialPartialBuild(inputs: BuildInput list) = @@ -989,7 +990,7 @@ type IncrementalBuilder() = -// Record the most recent IncrementalBuilder events, so we can more easily unittest/debug the +// Record the most recent IncrementalBuilder events, so we can more easily unit test/debug the // 'incremental' behavior of the product. module IncrementalBuilderEventTesting = @@ -1028,7 +1029,7 @@ module IncrementalBuilderEventTesting = // ++GLOBAL MUTABLE STATE FOR TESTING++ let MRU = new FixedLengthMRU() - let GetMostRecentIncrementalBuildEvents(n) = MRU.MostRecentList(n) + let GetMostRecentIncrementalBuildEvents n = MRU.MostRecentList n let GetCurrentIncrementalBuildEventNum() = MRU.CurrentEventNum module Tc = FSharp.Compiler.TypeChecker @@ -1065,23 +1066,29 @@ type TypeCheckAccumulator = tcModuleNamesDict: ModuleNamesDict /// Accumulated errors, last file first - tcErrorsRev:(PhasedDiagnostic * FSharpErrorSeverity)[] list } + tcErrorsRev:(PhasedDiagnostic * FSharpErrorSeverity)[] list + + /// If enabled, stores a linear list of ranges and strings that identify an Item(symbol) in a file. Used for background find all references. + itemKeyStore: ItemKeyStore option + + /// If enabled, holds semantic classification information for Item(symbol)s in a file. + semanticClassification: struct (range * SemanticClassificationType) [] } /// Global service state -type FrameworkImportsCacheKey = (*resolvedpath*)string list * string * (*TargetFrameworkDirectories*)string list* (*fsharpBinaries*)string +type FrameworkImportsCacheKey = (*resolvedpath*)string list * string * (*TargetFrameworkDirectories*)string list * (*fsharpBinaries*)string * (*langVersion*)decimal -/// Represents a cache of 'framework' references that can be shared betweeen multiple incremental builds +/// Represents a cache of 'framework' references that can be shared between multiple incremental builds type FrameworkImportsCache(keepStrongly) = // Mutable collection protected via CompilationThreadToken let frameworkTcImportsCache = AgedLookup(keepStrongly, areSimilar=(fun (x, y) -> x = y)) /// Reduce the size of the cache in low-memory scenarios - member __.Downsize(ctok) = frameworkTcImportsCache.Resize(ctok, keepStrongly=0) + member __.Downsize ctok = frameworkTcImportsCache.Resize(ctok, keepStrongly=0) /// Clear the cache - member __.Clear(ctok) = frameworkTcImportsCache.Clear(ctok) + member __.Clear ctok = frameworkTcImportsCache.Clear ctok /// This function strips the "System" assemblies from the tcConfig and returns a age-cached TcImports for them. member __.Get(ctok, tcConfig: TcConfig) = @@ -1100,15 +1107,16 @@ type FrameworkImportsCache(keepStrongly) = // The data elements in this key are very important. There should be nothing else in the TcConfig that logically affects // the import of a set of framework DLLs into F# CCUs. That is, the F# CCUs that result from a set of DLLs (including // FSharp.Core.dll and mscorlib.dll) must be logically invariant of all the other compiler configuration parameters. - let key = (frameworkDLLsKey, - tcConfig.primaryAssembly.Name, - tcConfig.GetTargetFrameworkDirectories(), - tcConfig.fsharpBinariesDir) + let key = (frameworkDLLsKey, + tcConfig.primaryAssembly.Name, + tcConfig.GetTargetFrameworkDirectories(), + tcConfig.fsharpBinariesDir, + tcConfig.langVersion.SpecifiedVersion) - match frameworkTcImportsCache.TryGet (ctok, key) with + match frameworkTcImportsCache.TryGet (ctok, key) with | Some res -> return res | None -> - let tcConfigP = TcConfigProvider.Constant(tcConfig) + let tcConfigP = TcConfigProvider.Constant tcConfig let! ((tcGlobals, tcImports) as res) = TcImports.BuildFrameworkTcImports (ctok, tcConfigP, frameworkDLLs, nonFrameworkResolutions) frameworkTcImportsCache.Put(ctok, key, res) return tcGlobals, tcImports @@ -1157,7 +1165,11 @@ type PartialCheckResults = LatestImplementationFile: TypedImplFile option - LastestCcuSigForFile: ModuleOrNamespaceType option } + LatestCcuSigForFile: ModuleOrNamespaceType option + + ItemKeyStore: ItemKeyStore option + + SemanticClassification: struct (range * SemanticClassificationType) [] } member x.TcErrors = Array.concat (List.rev x.TcErrorsRev) member x.TcSymbolUses = List.rev x.TcSymbolUsesRev @@ -1177,14 +1189,16 @@ type PartialCheckResults = ModuleNamesDict = tcAcc.tcModuleNamesDict TimeStamp = timestamp LatestImplementationFile = tcAcc.latestImplFile - LastestCcuSigForFile = tcAcc.latestCcuSigForFile } + LatestCcuSigForFile = tcAcc.latestCcuSigForFile + ItemKeyStore = tcAcc.itemKeyStore + SemanticClassification = tcAcc.semanticClassification } [] module Utilities = let TryFindFSharpStringAttribute tcGlobals attribSpec attribs = match TryFindFSharpAttribute tcGlobals attribSpec attribs with - | Some (Attrib(_, _, [ AttribStringArg(s) ], _, _, _, _)) -> Some s + | Some (Attrib(_, _, [ AttribStringArg s ], _, _, _, _)) -> Some s | _ -> None /// The implementation of the information needed by TcImports in CompileOps.fs for an F# assembly reference. @@ -1223,16 +1237,19 @@ type RawFSharpAssemblyDataBackedByLanguageService (tcConfig, tcGlobals, tcState: /// Manages an incremental build graph for the build of a single F# project type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInputs, nonFrameworkResolutions, unresolvedReferences, tcConfig: TcConfig, projectDirectory, outfile, - assemblyName, niceNameGen: Ast.NiceNameGenerator, lexResourceManager, + assemblyName, niceNameGen: NiceNameGenerator, lexResourceManager, sourceFiles, loadClosureOpt: LoadClosure option, - keepAssemblyContents, keepAllBackgroundResolutions, maxTimeShareMilliseconds) = + keepAssemblyContents, keepAllBackgroundResolutions, maxTimeShareMilliseconds, keepAllBackgroundSymbolUses, enableBackgroundItemKeyStoreAndSemanticClassification) = - let tcConfigP = TcConfigProvider.Constant(tcConfig) - let importsInvalidated = new Event() + let tcConfigP = TcConfigProvider.Constant tcConfig let fileParsed = new Event() let beforeFileChecked = new Event() let fileChecked = new Event() let projectChecked = new Event() +#if !NO_EXTENSIONTYPING + let importsInvalidatedByTypeProvider = new Event() +#endif + let mutable currentTcImportsOpt = None // Check for the existence of loaded sources and prepend them to the sources list if present. let sourceFiles = tcConfig.GetAvailableLoadedSources() @ (sourceFiles |>List.map (fun s -> rangeStartup, s)) @@ -1247,8 +1264,8 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput 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(projectDirectory, referenceText) + if not(FileSystem.IsInvalidPathShim referenceText) then + let file = if FileSystem.IsPathRootedShim referenceText then referenceText else Path.Combine(projectDirectory, referenceText) yield file for r in nonFrameworkResolutions do @@ -1259,27 +1276,6 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput for (_, f, _) in sourceFiles do yield f |] - // The IncrementalBuilder needs to hold up to one item that needs to be disposed, which is the tcImports for the incremental - // build. - let mutable cleanupItem = None: TcImports option - let disposeCleanupItem() = - match cleanupItem with - | None -> () - | Some item -> - cleanupItem <- None - dispose item - - let setCleanupItem x = - assert cleanupItem.IsNone - cleanupItem <- Some x - - let mutable disposed = false - let assertNotDisposed() = - if disposed then - System.Diagnostics.Debug.Assert(false, "IncrementalBuild object has already been disposed!") - - let mutable referenceCount = 0 - //---------------------------------------------------- // START OF BUILD TASK FUNCTIONS @@ -1287,14 +1283,12 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput /// /// Get the timestamp of the given file name. let StampFileNameTask (cache: TimeStampCache) _ctok (_m: range, filename: string, _isLastCompiland) = - assertNotDisposed() cache.GetFileTimeStamp filename /// This is a build task function that gets placed into the build rules as the computation for a VectorMap /// /// Parse the given file and return the given input. let ParseTask ctok (sourceRange: range, filename: string, isLastCompiland) = - assertNotDisposed() DoesNotRequireCompilerThreadTokenAndCouldPossiblyBeMadeConcurrent ctok let errorLogger = CompilationErrorLogger("ParseTask", tcConfig.errorSeverityOptions) @@ -1304,7 +1298,7 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput try IncrementalBuilderEventTesting.MRU.Add(IncrementalBuilderEventTesting.IBEParsed filename) let input = ParseOneInputFile(tcConfig, lexResourceManager, [], filename, isLastCompiland, errorLogger, (*retryLocked*)true) - fileParsed.Trigger (filename) + fileParsed.Trigger filename input, sourceRange, filename, errorLogger.GetErrors () with exn -> @@ -1317,7 +1311,6 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput /// /// Timestamps of referenced assemblies are taken from the file's timestamp. let StampReferencedAssemblyTask (cache: TimeStampCache) ctok (_ref, timeStamper) = - assertNotDisposed() timeStamper cache ctok @@ -1326,7 +1319,6 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput // Link all the assemblies together and produce the input typecheck accumulator let CombineImportedAssembliesTask ctok _ : Cancellable = cancellable { - assertNotDisposed() let errorLogger = CompilationErrorLogger("CombineImportedAssembliesTask", tcConfig.errorSeverityOptions) // Return the disposable object that cleans up use _holder = new CompilationGlobalsScope(errorLogger, BuildPhase.Parameter) @@ -1334,28 +1326,34 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput let! tcImports = cancellable { try - // We dispose any previous tcImports, for the case where a dependency changed which caused this part - // of the partial build to be re-evaluated. - disposeCleanupItem() - let! tcImports = TcImports.BuildNonFrameworkTcImports(ctok, tcConfigP, tcGlobals, frameworkTcImports, nonFrameworkResolutions, unresolvedReferences) #if !NO_EXTENSIONTYPING 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. - ccu.Deref.InvalidateEvent.Add(fun msg -> importsInvalidated.Trigger msg)) + // + // 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 msg -> + match capturedImportsInvalidated.TryGetTarget() with + | true, tg -> tg.Trigger msg + | _ -> ())) #endif - - - // The tcImports must be cleaned up if this builder ever gets disposed. We also dispose any previous - // tcImports should we be re-creating an entry because a dependency changed which caused this part - // of the partial build to be re-evaluated. - setCleanupItem tcImports - + currentTcImportsOpt <- Some tcImports return tcImports with e -> System.Diagnostics.Debug.Assert(false, sprintf "Could not BuildAllReferencedDllTcImports %A" e) - errorLogger.Warning(e) + errorLogger.Warning e return frameworkTcImports } @@ -1384,22 +1382,23 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput latestCcuSigForFile=None tcDependencyFiles=basicDependencies tcErrorsRev = [ initialErrors ] - tcModuleNamesDict = Map.empty } + tcModuleNamesDict = Map.empty + itemKeyStore = None + semanticClassification = [||] } return tcAcc } /// This is a build task function that gets placed into the build rules as the computation for a Vector.ScanLeft /// /// Type check all files. let TypeCheckTask ctok (tcAcc: TypeCheckAccumulator) input: Eventually = - assertNotDisposed() match input with | Some input, _sourceRange, filename, parseErrors-> IncrementalBuilderEventTesting.MRU.Add(IncrementalBuilderEventTesting.IBETypechecked filename) let capturingErrorLogger = CompilationErrorLogger("TypeCheckTask", tcConfig.errorSeverityOptions) - let errorLogger = GetErrorLoggerFilteringByScopedPragmas(false, GetScopedPragmasForInput(input), capturingErrorLogger) + let errorLogger = GetErrorLoggerFilteringByScopedPragmas(false, GetScopedPragmasForInput input, capturingErrorLogger) let fullComputation = eventually { - beforeFileChecked.Trigger (filename) + beforeFileChecked.Trigger filename ApplyMetaCommandsFromInputToTcConfig (tcConfig, input, Path.GetDirectoryName filename) |> ignore let sink = TcResultsSinkImpl(tcAcc.tcGlobals) @@ -1420,11 +1419,29 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput let implFile = if keepAssemblyContents then implFile else None let tcResolutions = if keepAllBackgroundResolutions then sink.GetResolutions() else TcResolutions.Empty let tcEnvAtEndOfFile = (if keepAllBackgroundResolutions then tcEnvAtEndOfFile else tcState.TcEnvFromImpls) - let tcSymbolUses = sink.GetSymbolUses() + let tcSymbolUses = if keepAllBackgroundSymbolUses then sink.GetSymbolUses() else TcSymbolUses.Empty + + // Build symbol keys + let itemKeyStore, semanticClassification = + if enableBackgroundItemKeyStoreAndSemanticClassification then + let sResolutions = sink.GetResolutions() + let builder = ItemKeyStoreBuilder() + let preventDuplicates = HashSet({ new IEqualityComparer with + member _.Equals((s1, e1): struct(pos * pos), (s2, e2): struct(pos * pos)) = Range.posEq s1 s2 && Range.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(), sResolutions.GetSemanticClassification(tcAcc.tcGlobals, tcAcc.tcImports.GetImportMap(), sink.GetFormatSpecifierLocations(), None) + else + None, [||] RequireCompilationThread ctok // Note: events get raised on the CompilationThread - fileChecked.Trigger (filename) + fileChecked.Trigger filename let newErrors = Array.append parseErrors (capturingErrorLogger.GetErrors()) return {tcAcc with tcState=tcState tcEnvAtEndOfFile=tcEnvAtEndOfFile @@ -1436,7 +1453,9 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput tcOpenDeclarationsRev = sink.GetOpenDeclarations() :: tcAcc.tcOpenDeclarationsRev tcErrorsRev = newErrors :: tcAcc.tcErrorsRev tcModuleNamesDict = moduleNamesDict - tcDependencyFiles = filename :: tcAcc.tcDependencyFiles } + tcDependencyFiles = filename :: tcAcc.tcDependencyFiles + itemKeyStore = itemKeyStore + semanticClassification = semanticClassification } } // Run part of the Eventually<_> computation until a timeout is reached. If not complete, @@ -1463,7 +1482,6 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput /// Finish up the typechecking to produce outputs for the rest of the compilation process let FinalizeTypeCheckTask ctok (tcStates: TypeCheckAccumulator[]) = cancellable { - assertNotDisposed() DoesNotRequireCompilerThreadTokenAndCouldPossiblyBeMadeConcurrent ctok let errorLogger = CompilationErrorLogger("CombineImportedAssembliesTask", tcConfig.errorSeverityOptions) @@ -1575,28 +1593,14 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput BuildInput.VectorInput (referencedAssembliesNode, nonFrameworkAssemblyInputs) ] // This is the initial representation of progress through the build, i.e. we have made no progress. - let mutable partialBuild = buildDescription.GetInitialPartialBuild (buildInputs) + let mutable partialBuild = buildDescription.GetInitialPartialBuild buildInputs let SavePartialBuild (ctok: CompilationThreadToken) b = RequireCompilationThread ctok // modifying state partialBuild <- b let MaxTimeStampInDependencies cache (ctok: CompilationThreadToken) (output: INode) = - IncrementalBuild.MaxTimeStampInDependencies cache ctok output.Name partialBuild - - member this.IncrementUsageCount() = - assertNotDisposed() - System.Threading.Interlocked.Increment(&referenceCount) |> ignore - { new System.IDisposable with member __.Dispose() = this.DecrementUsageCount() } - - member __.DecrementUsageCount() = - assertNotDisposed() - let currentValue = System.Threading.Interlocked.Decrement(&referenceCount) - if currentValue = 0 then - disposed <- true - disposeCleanupItem() - - member __.IsAlive = referenceCount > 0 + IncrementalBuild.MaxTimeStampInDependencies cache ctok output.Name partialBuild member __.TcConfig = tcConfig @@ -1608,24 +1612,17 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput member __.ProjectChecked = projectChecked.Publish - member __.ImportedCcusInvalidated = importsInvalidated.Publish - - member __.AllDependenciesDeprecated = allDependencies - #if !NO_EXTENSIONTYPING - member __.ThereAreLiveTypeProviders = - let liveTPs = - match cleanupItem with - | None -> [] - | Some tcImports -> [for ia in tcImports.GetImportedAssemblies() do yield! ia.TypeProviders] - match liveTPs with - | [] -> false - | _ -> true + member __.ImportsInvalidatedByTypeProvider = importsInvalidatedByTypeProvider.Publish #endif + member __.TryGetCurrentTcImports () = currentTcImportsOpt + + member __.AllDependenciesDeprecated = allDependencies + member __.Step (ctok: CompilationThreadToken) = cancellable { - let cache = TimeStampCache(defaultTimeStamp) // One per step + let cache = TimeStampCache defaultTimeStamp // One per step let! res = IncrementalBuild.Step cache ctok SavePartialBuild (Target(tcStatesNode, None)) partialBuild match res with | None -> @@ -1635,7 +1632,7 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput return true } - member builder.GetCheckResultsBeforeFileInProjectEvenIfStale (filename): PartialCheckResults option = + member builder.GetCheckResultsBeforeFileInProjectEvenIfStale filename: PartialCheckResults option = let slotOfFile = builder.GetSlotOfFileName filename let result = match slotOfFile with @@ -1647,16 +1644,16 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput | _ -> None - member builder.AreCheckResultsBeforeFileInProjectReady (filename) = + member builder.AreCheckResultsBeforeFileInProjectReady filename = let slotOfFile = builder.GetSlotOfFileName filename - let cache = TimeStampCache(defaultTimeStamp) + let cache = TimeStampCache defaultTimeStamp match slotOfFile with | (*first file*) 0 -> IncrementalBuild.IsReady cache (Target(initialTcAccNode, None)) partialBuild | _ -> IncrementalBuild.IsReady cache (Target(tcStatesNode, Some (slotOfFile-1))) partialBuild member __.GetCheckResultsBeforeSlotInProject (ctok: CompilationThreadToken, slotOfFile) = cancellable { - let cache = TimeStampCache(defaultTimeStamp) + let cache = TimeStampCache defaultTimeStamp let! result = cancellable { match slotOfFile with @@ -1686,7 +1683,7 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput member __.GetCheckResultsAndImplementationsForProject(ctok: CompilationThreadToken) = cancellable { - let cache = TimeStampCache(defaultTimeStamp) + let cache = TimeStampCache defaultTimeStamp let! build = IncrementalBuild.Eval cache ctok SavePartialBuild finalizedTypeCheckNode partialBuild match GetScalarResult(finalizedTypeCheckNode, build) with | Some ((ilAssemRef, tcAssemblyDataOpt, tcAssemblyExprOpt, tcAcc), timestamp) -> @@ -1698,7 +1695,7 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput ((build.Results :> IDictionary<_, _>).Keys |> Seq.toArray), brname, build.Results.ContainsKey brname, - build.Results.TryFind brname |> Option.map (function ScalarResult(sr) -> Some(sr.TryGetAvailable().IsSome) | _ -> None)) + build.Results.TryFind brname |> Option.map (function ScalarResult sr -> Some(sr.TryGetAvailable().IsSome) | _ -> None)) let msg = sprintf "Build was not evaluated, expected the results to be ready after 'Eval' (GetCheckResultsAndImplementationsForProject, data = %A)." data return! failwith msg } @@ -1713,7 +1710,7 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput let CompareFileNames (_, f2, _) = let result = String.Compare(filename, f2, StringComparison.CurrentCultureIgnoreCase)=0 - || String.Compare(FileSystem.GetFullPathShim(filename), FileSystem.GetFullPathShim(f2), StringComparison.CurrentCultureIgnoreCase)=0 + || String.Compare(FileSystem.GetFullPathShim filename, FileSystem.GetFullPathShim f2, StringComparison.CurrentCultureIgnoreCase)=0 result match TryGetSlotByInput(fileNamesNode, partialBuild, CompareFileNames) with | Some slot -> slot @@ -1733,7 +1730,7 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput match GetVectorResultBySlot(stampedFileNamesNode, slotOfFile, partialBuild) with | Some (results, _) -> return results | None -> - let cache = TimeStampCache(defaultTimeStamp) + let cache = TimeStampCache defaultTimeStamp let! build = IncrementalBuild.EvalUpTo cache ctok SavePartialBuild (stampedFileNamesNode, slotOfFile) partialBuild match GetVectorResultBySlot(stampedFileNamesNode, slotOfFile, build) with | Some (results, _) -> return results @@ -1747,17 +1744,16 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput /// CreateIncrementalBuilder (for background type checking). Note that fsc.fs also /// creates an incremental builder used by the command line compiler. - static member TryCreateBackgroundBuilderForProjectOptions - (ctok, legacyReferenceResolver, defaultFSharpBinariesDir, - frameworkTcImportsCache: FrameworkImportsCache, - loadClosureOpt: LoadClosure option, - sourceFiles: string list, - commandLineArgs: string list, - projectReferences, projectDirectory, - useScriptResolutionRules, keepAssemblyContents, - keepAllBackgroundResolutions, maxTimeShareMilliseconds, - tryGetMetadataSnapshot) = - + static member TryCreateBackgroundBuilderForProjectOptions + (ctok, legacyReferenceResolver, defaultFSharpBinariesDir, + frameworkTcImportsCache: FrameworkImportsCache, + loadClosureOpt: LoadClosure option, + sourceFiles: string list, + commandLineArgs: string list, + projectReferences, projectDirectory, + useScriptResolutionRules, keepAssemblyContents, + keepAllBackgroundResolutions, maxTimeShareMilliseconds, + tryGetMetadataSnapshot, suggestNamesForErrors, keepAllBackgroundSymbolUses, enableBackgroundItemKeyStoreAndSemanticClassification) = let useSimpleResolutionSwitch = "--simpleresolution" cancellable { @@ -1778,9 +1774,9 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput /// Create a type-check configuration let tcConfigB, sourceFilesNew = - let getSwitchValue switchstring = - match commandLineArgs |> Seq.tryFindIndex(fun s -> s.StartsWithOrdinal(switchstring)) with - | Some idx -> Some(commandLineArgs.[idx].Substring(switchstring.Length)) + let getSwitchValue switchString = + match commandLineArgs |> Seq.tryFindIndex(fun s -> s.StartsWithOrdinal switchString) with + | Some idx -> Some(commandLineArgs.[idx].Substring(switchString.Length)) | _ -> None // see also fsc.fs: runFromCommandLineToImportingAssemblies(), as there are many similarities to where the PS creates a tcConfigB @@ -1789,7 +1785,7 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput defaultFSharpBinariesDir, implicitIncludeDir=projectDirectory, reduceMemoryUsage=ReduceMemoryFlag.Yes, - isInteractive=false, + isInteractive=useScriptResolutionRules, isInvalidationSupported=true, defaultCopyFSharpCore=CopyFSharpCoreFlag.No, tryGetMetadataSnapshot=tryGetMetadataSnapshot) @@ -1798,21 +1794,26 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput tcConfigB.conditionalCompilationDefines <- let define = if useScriptResolutionRules then "INTERACTIVE" else "COMPILED" - define::tcConfigB.conditionalCompilationDefines + define :: tcConfigB.conditionalCompilationDefines tcConfigB.projectReferences <- projectReferences -#if COMPILER_SERVICE_ASSUMES_DOTNETCORE_COMPILATION - tcConfigB.useSimpleResolution <- true // turn off msbuild resolution -#else tcConfigB.useSimpleResolution <- (getSwitchValue useSimpleResolutionSwitch) |> Option.isSome -#endif + // Apply command-line arguments and collect more source files if they are in the arguments let sourceFilesNew = ApplyCommandLineArgs(tcConfigB, sourceFiles, commandLineArgs) // Never open PDB files for the language service, even if --standalone is specified tcConfigB.openDebugInformationForLaterStaticLinking <- false + tcConfigB.compilationThread <- + { new ICompilationThread with + member __.EnqueueWork work = + Reactor.Singleton.EnqueueOp ("Unknown", "ICompilationThread.EnqueueWork", "work", fun ctok -> + work ctok + ) + } + tcConfigB, sourceFilesNew match loadClosureOpt with @@ -1833,11 +1834,9 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput | None -> () let tcConfig = TcConfig.Create(tcConfigB, validate=true) - let niceNameGen = NiceNameGenerator() - let outfile, _, assemblyName = tcConfigB.DecideNames sourceFilesNew - + // Resolve assemblies and create the framework TcImports. This is done when constructing the // builder itself, rather than as an incremental task. This caches a level of "system" references. No type providers are // included in these references. @@ -1863,7 +1862,7 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput [ for r in nonFrameworkResolutions do let fileName = r.resolvedPath - yield (Choice1Of2 fileName, (fun (cache: TimeStampCache) _ctokk -> cache.GetFileTimeStamp fileName)) + yield (Choice1Of2 fileName, (fun (cache: TimeStampCache) _ctok -> cache.GetFileTimeStamp fileName)) for pr in projectReferences do yield Choice2Of2 pr, (fun (cache: TimeStampCache) ctok -> cache.GetProjectReferenceTimeStamp (pr, ctok)) ] @@ -1874,7 +1873,9 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput resourceManager, sourceFilesNew, loadClosureOpt, keepAssemblyContents=keepAssemblyContents, keepAllBackgroundResolutions=keepAllBackgroundResolutions, - maxTimeShareMilliseconds=maxTimeShareMilliseconds) + maxTimeShareMilliseconds=maxTimeShareMilliseconds, + keepAllBackgroundSymbolUses=keepAllBackgroundSymbolUses, + enableBackgroundItemKeyStoreAndSemanticClassification=enableBackgroundItemKeyStoreAndSemanticClassification) return Some builder with e -> errorRecoveryNoRange e @@ -1886,20 +1887,13 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput | Some builder -> let errorSeverityOptions = builder.TcConfig.errorSeverityOptions let errorLogger = CompilationErrorLogger("IncrementalBuilderCreation", errorSeverityOptions) - delayedLogger.CommitDelayedDiagnostics(errorLogger) + delayedLogger.CommitDelayedDiagnostics errorLogger errorLogger.GetErrors() |> Array.map (fun (d, severity) -> d, severity = FSharpErrorSeverity.Error) | _ -> Array.ofList delayedLogger.Diagnostics - |> Array.map (fun (d, isError) -> FSharpErrorInfo.CreateFromException(d, isError, range.Zero)) + |> Array.map (fun (d, isError) -> FSharpErrorInfo.CreateFromException(d, isError, range.Zero, suggestNamesForErrors)) return builderOpt, diagnostics } - static member KeepBuilderAlive (builderOpt: IncrementalBuilder option) = - match builderOpt with - | Some builder -> builder.IncrementUsageCount() - | None -> { new System.IDisposable with member __.Dispose() = () } - - member __.IsBeingKeptAliveApartFromCacheEntry = (referenceCount >= 2) - -#endif //!FABLE_COMPILER \ No newline at end of file +#endif //!FABLE_COMPILER diff --git a/src/fcs-fable/src/fsharp/service/IncrementalBuild.fsi b/src/fcs-fable/src/fsharp/service/IncrementalBuild.fsi index 3f3a8e6ab4..eb7871cae5 100755 --- a/src/fcs-fable/src/fsharp/service/IncrementalBuild.fsi +++ b/src/fcs-fable/src/fsharp/service/IncrementalBuild.fsi @@ -3,16 +3,18 @@ namespace FSharp.Compiler open System + open FSharp.Compiler -open FSharp.Compiler.Range -open FSharp.Compiler.ErrorLogger open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.TcGlobals open FSharp.Compiler.CompileOps +open FSharp.Compiler.ErrorLogger open FSharp.Compiler.NameResolution -open FSharp.Compiler.Tast +open FSharp.Compiler.Range open FSharp.Compiler.SourceCodeServices +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypedTree #if FABLE_COMPILER // stub @@ -27,8 +29,11 @@ type internal IncrementalBuilder = /// Lookup the global static cache for building the FrameworkTcImports type internal FrameworkImportsCache = new : size: int -> FrameworkImportsCache + member Get : CompilationThreadToken * TcConfig -> Cancellable + member Clear: CompilationThreadToken -> unit + member Downsize: CompilationThreadToken -> unit /// Used for unit testing @@ -44,10 +49,14 @@ module internal IncrementalBuilderEventTesting = /// Represents the state in the incremental graph associated with checking a file type internal PartialCheckResults = - { /// This field is None if a major unrecovered error occurred when preparing the initial state + { + /// This field is None if a major unrecovered error occurred when preparing the initial state TcState : TcState + TcImports: TcImports + TcGlobals: TcGlobals + TcConfig: TcConfig /// This field is None if a major unrecovered error occurred when preparing the initial state @@ -70,7 +79,7 @@ type internal PartialCheckResults = TcDependencyFiles: string list - /// Represents the collected attributes to apply to the module of assuembly generates + /// Represents the collected attributes to apply to the module of assembly generates TopAttribs: TypeChecker.TopAttribs option TimeStamp: DateTime @@ -80,7 +89,14 @@ type internal PartialCheckResults = LatestImplementationFile: TypedImplFile option /// Represents latest inferred signature contents. - LastestCcuSigForFile: ModuleOrNamespaceType option} + LatestCcuSigForFile: ModuleOrNamespaceType option + + /// If enabled, stores a linear list of ranges and strings that identify an Item(symbol) in a file. Used for background find all references. + ItemKeyStore: ItemKeyStore option + + /// If enabled, holds semantic classification information for Item(symbol)s in a file. + SemanticClassification: struct (range * SemanticClassificationType) [] + } member TcErrors: (PhasedDiagnostic * FSharpErrorSeverity)[] @@ -90,9 +106,6 @@ type internal PartialCheckResults = [] type internal IncrementalBuilder = - /// Check if the builder is not disposed - member IsAlive : bool - /// The TcConfig passed in to the builder creation. member TcConfig : TcConfig @@ -114,15 +127,17 @@ type internal IncrementalBuilder = /// overall analysis results for the project will be quick. member ProjectChecked : IEvent +#if !NO_EXTENSIONTYPING /// Raised when a type provider invalidates the build. - member ImportedCcusInvalidated : IEvent + member ImportsInvalidatedByTypeProvider : IEvent +#endif + + /// Tries to get the current successful TcImports. This is only used in testing. Do not use it for other stuff. + member TryGetCurrentTcImports : unit -> TcImports option /// The list of files the build depends on member AllDependenciesDeprecated : string[] -#if !NO_EXTENSIONTYPING - /// Whether there are any 'live' type providers that may need a refresh when a project is Cleaned - member ThereAreLiveTypeProviders : bool -#endif + /// Perform one step in the F# build. Return true if the background work is finished. member Step : CompilationThreadToken -> Cancellable @@ -170,18 +185,11 @@ type internal IncrementalBuilder = /// Await the untyped parse results for a particular slot in the vector of parse results. /// /// This may be a marginally long-running operation (parses are relatively quick, only one file needs to be parsed) - member GetParseResultsForFile : CompilationThreadToken * filename:string -> Cancellable - - static member TryCreateBackgroundBuilderForProjectOptions : CompilationThreadToken * ReferenceResolver.Resolver * defaultFSharpBinariesDir: string * FrameworkImportsCache * scriptClosureOptions:LoadClosure option * sourceFiles:string list * commandLineArgs:string list * projectReferences: IProjectReference list * projectDirectory:string * useScriptResolutionRules:bool * keepAssemblyContents: bool * keepAllBackgroundResolutions: bool * maxTimeShareMilliseconds: int64 * tryGetMetadataSnapshot: ILBinaryReader.ILReaderTryGetMetadataSnapshot -> Cancellable - - /// Increment the usage count on the IncrementalBuilder by 1. This initial usage count is 0 so immediately after creation - /// a call to KeepBuilderAlive should be made. The returns an IDisposable which will - /// decrement the usage count and dispose if the usage count goes to zero - static member KeepBuilderAlive : IncrementalBuilder option -> IDisposable + member GetParseResultsForFile : CompilationThreadToken * filename:string -> Cancellable - member IsBeingKeptAliveApartFromCacheEntry : bool + static member TryCreateBackgroundBuilderForProjectOptions : CompilationThreadToken * ReferenceResolver.Resolver * defaultFSharpBinariesDir: string * FrameworkImportsCache * scriptClosureOptions:LoadClosure option * sourceFiles:string list * commandLineArgs:string list * projectReferences: IProjectReference list * projectDirectory:string * useScriptResolutionRules:bool * keepAssemblyContents: bool * keepAllBackgroundResolutions: bool * maxTimeShareMilliseconds: int64 * tryGetMetadataSnapshot: ILBinaryReader.ILReaderTryGetMetadataSnapshot * suggestNamesForErrors: bool * keepAllBackgroundSymbolUses: bool * enableBackgroundItemKeyStoreAndSemanticClassification: bool -> Cancellable -/// Generalized Incremental Builder. This is exposed only for unittesting purposes. +/// Generalized Incremental Builder. This is exposed only for unit testing purposes. module internal IncrementalBuild = type INode = abstract Name: string @@ -263,10 +271,13 @@ module internal IncrementalBuild = /// Only required for unit testing. type BuildDescriptionScope = new : unit -> BuildDescriptionScope + /// Declare a named scalar output. member DeclareScalarOutput : output:Scalar<'T> -> unit + /// Declare a named vector output. member DeclareVectorOutput : output:Vector<'T> -> unit + /// Set the concrete inputs for this build. member GetInitialPartialBuild : vectorinputs: BuildInput list -> PartialBuild diff --git a/src/fcs-fable/src/fsharp/service/ItemKey.fs b/src/fcs-fable/src/fsharp/service/ItemKey.fs new file mode 100644 index 0000000000..82889352f6 --- /dev/null +++ b/src/fcs-fable/src/fsharp/service/ItemKey.fs @@ -0,0 +1,452 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +namespace FSharp.Compiler.SourceCodeServices + +open System +open System.IO +open System.IO.MemoryMappedFiles +open System.Reflection.Metadata + +open FSharp.NativeInterop + +open FSharp.Compiler +open FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler.Infos +open FSharp.Compiler.NameResolution +open FSharp.Compiler.Range +open FSharp.Compiler.TypedTree + +#nowarn "9" + +/// These tags are used to create unique item key strings to decrease possible key string collisions when the Items are actually completely different. +[] +module ItemKeyTags = + + [] + let entityRef = "#E#" + + [] + let typeTuple = "#T#" + + [] + let typeAnonymousRecord = "#N#" + + [] + let typeFunction = "#F#" + + [] + let typeMeasure = "#M#" + + [] + let typeUnionCase = "#U#" + + [] + let typeMeasureVar = "#p#" + + [] + let typeMeasureCon = "#c#" + + [] + let typeMeasureProd = "#r#" + + [] + let typeMeasureInv = "#i#" + + [] + let typeMeasureOne = "#1#" + + [] + let typeMeasureRationalPower = "#z#" + + [] + let itemValueMember = "m$" + + [] + let itemValue = "v$" + + [] + let itemUnionCase = "u$" + + [] + let itemActivePattern = "r$" + + [] + let itemExnCase = "e$" + + [] + let itemRecordField = "d$" + + [] + let itemAnonymousRecordField = "a$" + + [] + let itemNewDef = "n$" + + [] + let itemILField = "l$" + + [] + let itemEvent = "t$" + + [] + let itemProperty = "p$" + + [] + let itemTypeVar = "y$" + + [] + let itemModuleOrNamespace = "o$" + + [] + let itemDelegateCtor = "g$" + +[] +type ItemKeyStore(mmf: MemoryMappedFile, length) = + + let mutable isDisposed = false + let checkDispose() = + if isDisposed then + raise (ObjectDisposedException("ItemKeyStore")) + + member _.ReadRange(reader: byref) = + let startLine = reader.ReadInt32() + let startColumn = reader.ReadInt32() + let endLine = reader.ReadInt32() + let endColumn = reader.ReadInt32() + let fileIndex = reader.ReadInt32() + + let posStart = mkPos startLine startColumn + let posEnd = mkPos endLine endColumn + mkFileIndexRange fileIndex posStart posEnd + + member _.ReadKeyString(reader: byref) = + let size = reader.ReadInt32() + let keyString = ReadOnlySpan(reader.CurrentPointer |> NativePtr.toVoidPtr, size) + reader.Offset <- reader.Offset + size + keyString + + member this.ReadFirstKeyString() = + use view = mmf.CreateViewAccessor(0L, length) + let mutable reader = BlobReader(view.SafeMemoryMappedViewHandle.DangerousGetHandle() |> NativePtr.ofNativeInt, int length) + this.ReadRange &reader |> ignore + let bytes = (this.ReadKeyString &reader).ToArray() + ReadOnlySpan.op_Implicit bytes + + member this.FindAll(item: Item) = + checkDispose () + + let builder = ItemKeyStoreBuilder() + builder.Write(Range.range0, item) + match builder.TryBuildAndReset() with + | None -> Seq.empty + | Some(singleStore : ItemKeyStore) -> + let keyString1 = singleStore.ReadFirstKeyString() + (singleStore :> IDisposable).Dispose() + + let results = ResizeArray() + + use view = mmf.CreateViewAccessor(0L, length) + let mutable reader = BlobReader(view.SafeMemoryMappedViewHandle.DangerousGetHandle() |> NativePtr.ofNativeInt, int length) + + reader.Offset <- 0 + while reader.Offset < reader.Length do + let m = this.ReadRange &reader + let keyString2 = this.ReadKeyString &reader + if keyString1.SequenceEqual keyString2 then + results.Add m + + results :> range seq + + interface IDisposable with + + member _.Dispose() = + isDisposed <- true + mmf.Dispose() + +and [] ItemKeyStoreBuilder() = + + let b = BlobBuilder() + + let writeChar (c: char) = + b.WriteUInt16(uint16 c) + + let writeUInt16 (i: uint16) = + b.WriteUInt16 i + + let writeInt32 (i: int) = + b.WriteInt32 i + + let writeInt64 (i: int64) = + b.WriteInt64 i + + let writeString (str: string) = + b.WriteUTF16 str + + let writeRange (m: Range.range) = + b.WriteInt32(m.StartLine) + b.WriteInt32(m.StartColumn) + b.WriteInt32(m.EndLine) + b.WriteInt32(m.EndColumn) + b.WriteInt32(m.FileIndex) + + let writeEntityRef (eref: EntityRef) = + writeString ItemKeyTags.entityRef + writeString eref.CompiledName + eref.CompilationPath.MangledPath + |> List.iter (fun str -> writeString str) + + let rec writeILType (ilty: ILType) = + match ilty with + | ILType.TypeVar n -> writeString "!"; writeUInt16 n + | ILType.Modified (_, _, ty2) -> writeILType ty2 + | ILType.Array (ILArrayShape s, ty) -> + writeILType ty + writeString "[" + writeInt32 (s.Length-1) + writeString "]" + | ILType.Value tr + | ILType.Boxed tr -> + tr.TypeRef.Enclosing + |> List.iter (fun x -> + writeString x + writeChar '.') + writeChar '.' + writeString tr.TypeRef.Name + | ILType.Void -> + writeString "void" + | ILType.Ptr ty -> + writeString "ptr<" + writeILType ty + writeChar '>' + | ILType.Byref ty -> + writeString "byref<" + writeILType ty + writeChar '>' + | ILType.FunctionPointer mref -> + mref.ArgTypes + |> List.iter (fun x -> + writeILType x) + writeILType mref.ReturnType + + let rec writeType (ty: TType) = + match ty with + | TType_forall (_, ty) -> + writeType ty + | TType_app (tcref, _) -> + writeEntityRef tcref + | TType_tuple (_, tinst) -> + writeString ItemKeyTags.typeTuple + tinst |> List.iter writeType + | TType_anon (anonInfo, tinst) -> + writeString ItemKeyTags.typeAnonymousRecord + writeString anonInfo.ILTypeRef.BasicQualifiedName + tinst |> List.iter writeType + | TType_fun (d, r) -> + writeString ItemKeyTags.typeFunction + writeType d + writeType r + | TType_measure ms -> + writeString ItemKeyTags.typeMeasure + writeMeasure ms + | TType_var tp -> + writeTypar tp + | TType_ucase (uc, _) -> + match uc with + | UnionCaseRef.UnionCaseRef(tcref, nm) -> + writeString ItemKeyTags.typeUnionCase + writeEntityRef tcref + writeString nm + + and writeMeasure (ms: Measure) = + match ms with + | Measure.Var typar -> + writeString ItemKeyTags.typeMeasureVar + writeTypar typar + | Measure.Con tcref -> + writeString ItemKeyTags.typeMeasureCon + writeEntityRef tcref + | Measure.Prod(ms1, ms2) -> + writeString ItemKeyTags.typeMeasureProd + writeMeasure ms1 + writeMeasure ms2 + | Measure.Inv ms -> + writeString ItemKeyTags.typeMeasureInv + writeMeasure ms + | Measure.One -> + writeString ItemKeyTags.typeMeasureOne + | Measure.RationalPower _ -> + writeString ItemKeyTags.typeMeasureRationalPower + + and writeTypar (typar: Typar) = + match typar.Solution with + | Some ty -> writeType ty + | _ -> writeInt64 typar.Stamp + + let writeValRef (vref: ValRef) = + match vref.MemberInfo with + | Some memberInfo -> + writeString "m$" + writeEntityRef memberInfo.ApparentEnclosingEntity + writeString vref.LogicalName + writeType vref.Type + | _ -> + writeString "v$" + writeString vref.LogicalName + writeType vref.Type + match vref.DeclaringEntity with + | ParentNone -> writeChar '%' + | Parent eref -> writeEntityRef eref + + member _.Write (m: Range.range, item: Item) = + writeRange m + + let fixup = b.ReserveBytes 4 |> BlobWriter + + let preCount = b.Count + + match item with + | Item.Value vref -> + match vref.MemberInfo with + | Some memberInfo -> + writeString ItemKeyTags.itemValueMember + writeEntityRef memberInfo.ApparentEnclosingEntity + writeString vref.LogicalName + writeType vref.Type + | _ -> + writeString ItemKeyTags.itemValue + writeValRef vref + + | Item.UnionCase(info, _) -> + writeString ItemKeyTags.typeUnionCase + writeEntityRef info.TyconRef + writeString info.Name + + | Item.ActivePatternResult(info, _, _, _) -> + writeString ItemKeyTags.itemActivePattern + info.ActiveTagsWithRanges + |> List.iter (fun (nm, _) -> + writeString nm) + + | Item.ActivePatternCase elemRef -> + writeString ItemKeyTags.itemActivePattern + elemRef.ActivePatternInfo.ActiveTagsWithRanges + |> List.iter (fun (nm, _) -> writeString nm) + + | Item.ExnCase tcref -> + writeString ItemKeyTags.itemExnCase + writeEntityRef tcref + + | Item.RecdField info -> + writeString ItemKeyTags.itemRecordField + writeEntityRef info.TyconRef + writeString info.Name + writeType info.FieldType + + | Item.UnionCaseField(info, fieldIndex) -> + writeString ItemKeyTags.typeUnionCase + writeEntityRef info.TyconRef + writeString info.Name + writeInt32 fieldIndex + + | Item.AnonRecdField(info, tys, i, _) -> + writeString ItemKeyTags.itemAnonymousRecordField + writeString info.ILTypeRef.BasicQualifiedName + tys |> List.iter writeType + writeInt32 i + + | Item.NewDef ident -> + writeString ItemKeyTags.itemNewDef + writeString ident.idText + + | Item.ILField info -> + writeString ItemKeyTags.itemILField + writeString info.ILTypeRef.BasicQualifiedName + writeString info.FieldName + + | Item.Event info -> + writeString ItemKeyTags.itemEvent + writeString info.EventName + writeEntityRef info.DeclaringTyconRef + + | Item.Property(nm, infos) -> + writeString ItemKeyTags.itemProperty + writeString nm + infos + |> List.iter (fun info -> writeEntityRef info.DeclaringTyconRef) + + | Item.TypeVar(nm, typar) -> + writeString ItemKeyTags.itemTypeVar + writeString nm + writeTypar typar + + | Item.Types(_, [ty]) -> + writeType ty + + | Item.UnqualifiedType [tcref] -> + writeEntityRef tcref + + | Item.MethodGroup(_, [info], _) + | Item.CtorGroup(_, [info]) -> + match info with + | FSMeth(_, _, vref, _) -> + writeValRef vref + | ILMeth(_, info, _) -> + info.ILMethodRef.ArgTypes + |> List.iter writeILType + writeILType info.ILMethodRef.ReturnType + writeString info.ILName + writeType info.ApparentEnclosingType + | _ -> + writeString "m$" + writeEntityRef info.DeclaringTyconRef + writeString info.LogicalName + + | Item.ModuleOrNamespaces [x] -> + writeString ItemKeyTags.itemModuleOrNamespace + x.CompilationPath.DemangledPath + |> List.iter (fun x -> + writeString x + writeString ".") + writeString x.LogicalName + + | Item.DelegateCtor ty -> + writeString ItemKeyTags.itemDelegateCtor + writeType ty + + | Item.MethodGroup _ -> () + | Item.CtorGroup _ -> () + | Item.FakeInterfaceCtor _ -> () + | Item.Types _ -> () + | Item.CustomOperation _ -> () + | Item.CustomBuilder _ -> () + | Item.ModuleOrNamespaces _ -> () + | Item.ImplicitOp _ -> () + | Item.ArgName _ -> () + | Item.SetterArg _ -> () + | Item.UnqualifiedType _ -> () + + let postCount = b.Count + + fixup.WriteInt32(postCount - preCount) + + member _.TryBuildAndReset() = + if b.Count > 0 then + let length = int64 b.Count + let mmf = + let mmf = + MemoryMappedFile.CreateNew( + null, + length, + MemoryMappedFileAccess.ReadWrite, + MemoryMappedFileOptions.None, + HandleInheritability.None) + use stream = mmf.CreateViewStream(0L, length, MemoryMappedFileAccess.ReadWrite) + b.WriteContentTo stream + mmf + + b.Clear() + + Some(new ItemKeyStore(mmf, length)) + else + b.Clear() + None \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/service/ItemKey.fsi b/src/fcs-fable/src/fsharp/service/ItemKey.fsi new file mode 100644 index 0000000000..ce69297390 --- /dev/null +++ b/src/fcs-fable/src/fsharp/service/ItemKey.fsi @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +namespace FSharp.Compiler.SourceCodeServices + +open System + +open FSharp.Compiler.NameResolution +open FSharp.Compiler.Range + +/// Stores a list of item key strings and their ranges in a memory mapped file. +[] +type internal ItemKeyStore = + interface IDisposable + + member FindAll: Item -> range seq + +/// A builder that will build an item key store based on the written Item and its associated range. +[] +type internal ItemKeyStoreBuilder = + + new: unit -> ItemKeyStoreBuilder + + member Write: range * Item -> unit + + member TryBuildAndReset: unit -> ItemKeyStore option \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/service/QuickParse.fs b/src/fcs-fable/src/fsharp/service/QuickParse.fs index 9e962ac302..887e97e2ec 100644 --- a/src/fcs-fable/src/fsharp/service/QuickParse.fs +++ b/src/fcs-fable/src/fsharp/service/QuickParse.fs @@ -8,7 +8,8 @@ open FSharp.Compiler.SourceCodeServices /// Qualified long name. type PartialLongName = - { /// Qualifying idents, prior to the last dot, not including the last part. + { + /// Qualifying idents, prior to the last dot, not including the last part. QualifyingIdents: string list /// Last part of long ident. @@ -20,10 +21,10 @@ type PartialLongName = /// Position of the last dot. LastDotPos: int option } - /// Empty patial long name. + /// Empty partial long name. static member Empty(endColumn: int) = { QualifyingIdents = []; PartialIdent = ""; EndColumn = endColumn; LastDotPos = None } -/// Methods for cheaply and innacurately parsing F#. +/// Methods for cheaply and inaccurately parsing F#. /// /// These methods are very old and are mostly to do with extracting "long identifier islands" /// A.B.C @@ -58,7 +59,7 @@ module QuickParse = // Utility function that recognizes whether a name is valid active pattern name // Extracts the 'core' part without surrounding bars and checks whether it contains some identifier - // (Note, this doesn't have to be precise, because this is checked by backround compiler, + // (Note, this doesn't have to be precise, because this is checked by background compiler, // but it has to be good enough to distinguish operators and active pattern names) let private isValidActivePatternName (name: string) = @@ -152,7 +153,7 @@ module QuickParse = /// In general, only identifiers composed from upper/lower letters and '.' are supported, but there /// are a couple of explicitly handled exceptions to allow some common scenarios: /// - When the name contains only letters and '|' symbol, it may be an active pattern, so we - /// treat it as a valid identifier - e.g. let ( |Identitiy| ) a = a + /// treat it as a valid identifier - e.g. let ( |Identity| ) a = a /// (but other identifiers that include '|' are not allowed - e.g. '||' operator) /// - It searches for double tick (``) to see if the identifier could be something like ``a b`` /// @@ -186,7 +187,7 @@ module QuickParse = let IsDot pos = lineStr.[pos] = '.' let rec InLeadingIdentifier(pos,right,(prior,residue)) = - let PushName() = ((lineStr.Substring(pos+1,right-pos-1))::prior),residue + let PushName() = ((lineStr.Substring(pos+1,right-pos-1)) :: prior),residue if pos < 0 then PushName() elif IsIdentifierPartCharacter pos then InLeadingIdentifier(pos-1,right,(prior,residue)) elif IsDot pos then InLeadingIdentifier(pos-1,pos,PushName()) @@ -231,7 +232,7 @@ module QuickParse = let rec SkipWhitespaceBeforeDotIdentifier(pos, ident, current, throwAwayNext, lastDotPos) = if pos > index then PartialLongName.Empty(index) // we're in whitespace after an identifier, if this is where the cursor is, there is no PLID here elif IsWhitespace pos then SkipWhitespaceBeforeDotIdentifier(pos+1,ident,current,throwAwayNext,lastDotPos) - elif IsDot pos then AtStartOfIdentifier(pos+1,ident::current,throwAwayNext, Some pos) + elif IsDot pos then AtStartOfIdentifier(pos+1,ident :: current,throwAwayNext, Some pos) elif IsStartOfComment pos then EatComment(1, pos + 1, EatCommentCallContext.SkipWhiteSpaces(ident, current, throwAwayNext), lastDotPos) else AtStartOfIdentifier(pos,[],false,None) // Throw away what we have and start over. @@ -269,7 +270,7 @@ module QuickParse = if IsIdentifierPartCharacter pos then InUnquotedIdentifier(left,pos+1,current,throwAwayNext,lastDotPos) elif IsDot pos then let ident = lineStr.Substring(left,pos-left) - AtStartOfIdentifier(pos+1,ident::current,throwAwayNext, Some pos) + AtStartOfIdentifier(pos+1,ident :: current,throwAwayNext, Some pos) elif IsWhitespace pos || IsStartOfComment pos then let ident = lineStr.Substring(left,pos-left) SkipWhitespaceBeforeDotIdentifier(pos, ident, current, throwAwayNext, lastDotPos) @@ -310,7 +311,7 @@ module QuickParse = elif IsDot pos then if pos = 0 then // dot on first char of line, currently treat it like empty identifier to the left - AtStartOfIdentifier(pos+1,""::current,throwAwayNext, Some pos) + AtStartOfIdentifier(pos+1,"":: current,throwAwayNext, Some pos) elif not (pos > 0 && (IsIdentifierPartCharacter(pos-1) || IsWhitespace(pos-1))) then // it's not dots as part.of.a.long.ident, it's e.g. the range operator (..), or some other multi-char operator ending in dot if lineStr.[pos-1] = ')' then @@ -322,7 +323,7 @@ module QuickParse = else AtStartOfIdentifier(pos+1,[],false,None) // Throw away what we have and start over. else - AtStartOfIdentifier(pos+1,""::current,throwAwayNext, Some pos) + AtStartOfIdentifier(pos+1,"":: current,throwAwayNext, Some pos) else AtStartOfIdentifier(pos+1,[],throwAwayNext, None) let partialLongName = AtStartOfIdentifier(0, [], false, None) diff --git a/src/fcs-fable/src/fsharp/service/QuickParse.fsi b/src/fcs-fable/src/fsharp/service/QuickParse.fsi index 5f78dbefd2..0201f846ad 100644 --- a/src/fcs-fable/src/fsharp/service/QuickParse.fsi +++ b/src/fcs-fable/src/fsharp/service/QuickParse.fsi @@ -2,12 +2,12 @@ namespace FSharp.Compiler -open System open FSharp.Compiler.SourceCodeServices /// Qualified long name. type public PartialLongName = - { /// Qualifying idents, prior to the last dot, not including the last part. + { + /// Qualifying idents, prior to the last dot, not including the last part. QualifyingIdents: string list /// Last part of long ident. @@ -17,12 +17,13 @@ type public PartialLongName = EndColumn: int /// Position of the last dot. - LastDotPos: int option } + LastDotPos: int option + } - /// Empty patial long name. + /// Empty partial long name. static member Empty: endColumn: int -> PartialLongName -/// Methods for cheaply and innacurately parsing F#. +/// Methods for cheaply and inaccurately parsing F#. /// /// These methods are very old and are mostly to do with extracting "long identifier islands" /// A.B.C @@ -39,6 +40,7 @@ type public PartialLongName = /// below is inaccurate for long identifier chains involving ``...`` identifiers. And there are special cases /// for active pattern names and so on. module public QuickParse = + /// Puts us after the last character. val MagicalAdjustmentConstant : int @@ -57,7 +59,7 @@ module public QuickParse = /// In general, only identifiers composed from upper/lower letters and '.' are supported, but there /// are a couple of explicitly handled exceptions to allow some common scenarios: /// - When the name contains only letters and '|' symbol, it may be an active pattern, so we - /// treat it as a valid identifier - e.g. let ( |Identitiy| ) a = a + /// treat it as a valid identifier - e.g. let ( |Identity| ) a = a /// (but other identifiers that include '|' are not allowed - e.g. '||' operator) /// - It searches for double tick (``) to see if the identifier could be something like ``a b`` /// diff --git a/src/fcs-fable/src/fsharp/service/Reactor.fs b/src/fcs-fable/src/fsharp/service/Reactor.fs index 807e5f6248..54e7b1731a 100755 --- a/src/fcs-fable/src/fsharp/service/Reactor.fs +++ b/src/fcs-fable/src/fsharp/service/Reactor.fs @@ -1,13 +1,14 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. namespace FSharp.Compiler.SourceCodeServices + open System open System.Diagnostics open System.Globalization open System.Threading -open Microsoft.FSharp.Control -open FSharp.Compiler.Lib + open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.Lib /// Represents the capability to schedule work in the compiler service operations queue for the compilation thread type internal IReactorOperations = @@ -20,10 +21,13 @@ type internal IReactorOperations = type internal ReactorCommands = /// Kick off a build. | SetBackgroundOp of ( (* userOpName: *) string * (* opName: *) string * (* opArg: *) string * (CompilationThreadToken -> CancellationToken -> bool)) option + /// Do some work not synchronized in the mailbox. | Op of userOpName: string * opName: string * opArg: string * CancellationToken * (CompilationThreadToken -> unit) * (unit -> unit) + /// Finish the background building | WaitForBackgroundOpCompletion of AsyncReplyChannel + /// Finish all the queued ops | CompleteAllQueuedOps of AsyncReplyChannel @@ -36,8 +40,8 @@ type Reactor() = let mutable pauseBeforeBackgroundWork = pauseBeforeBackgroundWorkDefault // We need to store the culture for the VS thread that is executing now, - // so that when the reactor picks up a thread from the threadpool we can set the culture - let culture = new CultureInfo(CultureInfo.CurrentUICulture.Name) + // so that when the reactor picks up a thread from the thread pool we can set the culture + let mutable culture = CultureInfo(CultureInfo.CurrentUICulture.Name) let mutable bgOpCts = new CancellationTokenSource() /// Mailbox dispatch function. @@ -66,11 +70,7 @@ type Reactor() = Trace.TraceInformation("Reactor: {0:n3} pausing {1} milliseconds", DateTime.Now.TimeOfDay.TotalSeconds, pauseBeforeBackgroundWork) pauseBeforeBackgroundWork return! inbox.TryReceive(timeout) } -#if FX_RESHAPED_GLOBALIZATION - CultureInfo.CurrentUICulture <- culture -#else Thread.CurrentThread.CurrentUICulture <- culture -#endif match msg with | Some (SetBackgroundOp bgOpOpt) -> //Trace.TraceInformation("Reactor: --> set background op, remaining {0}", inbox.CurrentQueueLength) @@ -137,6 +137,17 @@ type Reactor() = Debug.Assert(false, String.Format("unexpected failure in reactor loop {0}, restarting", e)) } + member __.SetPreferredUILang(preferredUiLang: string option) = + match preferredUiLang with + | Some s -> + culture <- CultureInfo s +#if FX_RESHAPED_GLOBALIZATION + CultureInfo.CurrentUICulture <- culture +#else + Thread.CurrentThread.CurrentUICulture <- culture +#endif + | None -> () + // [Foreground Mailbox Accessors] ----------------------------------------------------------- member r.SetBackgroundOp(bgOpOpt) = Trace.TraceInformation("Reactor: {0:n3} enqueue start background, length {1}", DateTime.Now.TimeOfDay.TotalSeconds, builder.CurrentQueueLength) diff --git a/src/fcs-fable/src/fsharp/service/Reactor.fsi b/src/fcs-fable/src/fsharp/service/Reactor.fsi index e2037a18f5..fe515e100a 100755 --- a/src/fcs-fable/src/fsharp/service/Reactor.fsi +++ b/src/fcs-fable/src/fsharp/service/Reactor.fsi @@ -25,6 +25,9 @@ type internal IReactorOperations = [] type internal Reactor = + /// Allows to specify the language for error messages + member SetPreferredUILang : string option -> unit + /// Set the background building function, which is called repeatedly /// until it returns 'false'. If None then no background operation is used. member SetBackgroundOp : ( (* userOpName:*) string * (* opName: *) string * (* opArg: *) string * (CompilationThreadToken -> CancellationToken -> bool)) option -> unit diff --git a/src/fcs-fable/src/fsharp/service/SemanticClassification.fs b/src/fcs-fable/src/fsharp/service/SemanticClassification.fs new file mode 100644 index 0000000000..0001372460 --- /dev/null +++ b/src/fcs-fable/src/fsharp/service/SemanticClassification.fs @@ -0,0 +1,185 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +namespace FSharp.Compiler.SourceCodeServices + +open System.Diagnostics +open System.Collections.Generic +#if !FABLE_COMPILER +open System.Collections.Immutable +#endif + +open FSharp.Compiler +open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.Infos +open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Lib +open FSharp.Compiler.NameResolution +open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.Range +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.SourceCodeServices.SymbolHelpers + +[] +type SemanticClassificationType = + | ReferenceType + | ValueType + | UnionCase + | Function + | Property + | MutableVar + | Module + | Printf + | ComputationExpression + | IntrinsicFunction + | Enumeration + | Interface + | TypeArgument + | Operator + | Disposable + +[] +module TcResolutionsExtensions = + + let (|CNR|) (cnr:CapturedNameResolution) = + (cnr.Item, cnr.ItemOccurence, cnr.DisplayEnv, cnr.NameResolutionEnv, cnr.AccessorDomain, cnr.Range) + + type TcResolutions with + + member sResolutions.GetSemanticClassification(g: TcGlobals, amap: Import.ImportMap, formatSpecifierLocations: (range * int) [], range: range option) : struct(range * SemanticClassificationType) [] = + ErrorScope.Protect Range.range0 + (fun () -> + let (|LegitTypeOccurence|_|) = function + | ItemOccurence.UseInType + | ItemOccurence.UseInAttribute + | ItemOccurence.Use _ + | ItemOccurence.Binding _ + | ItemOccurence.Pattern _ -> Some() + | _ -> None + + let (|OptionalArgumentAttribute|_|) ttype = + match ttype with + | TType.TType_app(tref, _) when tref.Stamp = g.attrib_OptionalArgumentAttribute.TyconRef.Stamp -> Some() + | _ -> None + + let (|KeywordIntrinsicValue|_|) (vref: ValRef) = + if valRefEq g g.raise_vref vref || + valRefEq g g.reraise_vref vref || + valRefEq g g.typeof_vref vref || + valRefEq g g.typedefof_vref vref || + valRefEq g g.sizeof_vref vref || + valRefEq g g.nameof_vref vref then Some() + else None + + let (|EnumCaseFieldInfo|_|) (rfinfo : RecdFieldInfo) = + match rfinfo.TyconRef.TypeReprInfo with + | TFSharpObjectRepr x -> + match x.fsobjmodel_kind with + | TTyconEnum -> Some () + | _ -> None + | _ -> None + + let resolutions = + match range with + | Some range -> + sResolutions.CapturedNameResolutions + |> Seq.filter (fun cnr -> rangeContainsPos range cnr.Range.Start || rangeContainsPos range cnr.Range.End) + | None -> + sResolutions.CapturedNameResolutions :> seq<_> + + let isDisposableTy (ty: TType) = + protectAssemblyExplorationNoReraise false false (fun () -> Infos.ExistsHeadTypeInEntireHierarchy g amap range0 ty g.tcref_System_IDisposable) + + let isStructTyconRef (tyconRef: TyconRef) = + let ty = generalizedTyconRef tyconRef + let underlyingTy = stripTyEqnsAndMeasureEqns g ty + isStructTy g underlyingTy + + let isValRefMutable (vref: ValRef) = + // Mutable values, ref cells, and non-inref byrefs are mutable. + vref.IsMutable + || isRefCellTy g vref.Type + || (isByrefTy g vref.Type && not (isInByrefTy g vref.Type)) + + let isRecdFieldMutable (rfinfo: RecdFieldInfo) = + (rfinfo.RecdField.IsMutable && rfinfo.LiteralValue.IsNone) + || isRefCellTy g rfinfo.RecdField.FormalType + + let duplicates = HashSet(Range.comparer) + +#if FABLE_COMPILER + let results = ResizeArray<_>() +#else + let results = ImmutableArray.CreateBuilder() +#endif + let inline add m typ = + if duplicates.Add m then + results.Add struct(m, typ) + resolutions + |> Seq.iter (fun cnr -> + match cnr.Item, cnr.ItemOccurence, cnr.DisplayEnv, cnr.NameResolutionEnv, cnr.AccessorDomain, cnr.Range with + // 'seq' in 'seq { ... }' gets colored as keywords + | (Item.Value vref), ItemOccurence.Use, _, _, _, m when valRefEq g g.seq_vref vref -> + add m SemanticClassificationType.ComputationExpression + | (Item.Value vref), _, _, _, _, m when isValRefMutable vref -> + add m SemanticClassificationType.MutableVar + | Item.Value KeywordIntrinsicValue, ItemOccurence.Use, _, _, _, m -> + add m SemanticClassificationType.IntrinsicFunction + | (Item.Value vref), _, _, _, _, m when isFunction g vref.Type -> + if valRefEq g g.range_op_vref vref || valRefEq g g.range_step_op_vref vref then + () + elif vref.IsPropertyGetterMethod || vref.IsPropertySetterMethod then + add m SemanticClassificationType.Property + elif IsOperatorName vref.DisplayName then + add m SemanticClassificationType.Operator + else + add m SemanticClassificationType.Function + | Item.RecdField rfinfo, _, _, _, _, m when isRecdFieldMutable rfinfo -> + add m SemanticClassificationType.MutableVar + | Item.RecdField rfinfo, _, _, _, _, m when isFunction g rfinfo.FieldType -> + add m SemanticClassificationType.Function + | Item.RecdField EnumCaseFieldInfo, _, _, _, _, m -> + add m SemanticClassificationType.Enumeration + | Item.MethodGroup _, _, _, _, _, m -> + add m SemanticClassificationType.Function + // custom builders, custom operations get colored as keywords + | (Item.CustomBuilder _ | Item.CustomOperation _), ItemOccurence.Use, _, _, _, m -> + add m SemanticClassificationType.ComputationExpression + // types get colored as types when they occur in syntactic types or custom attributes + // type variables get colored as types when they occur in syntactic types custom builders, custom operations get colored as keywords + | Item.Types (_, [OptionalArgumentAttribute]), LegitTypeOccurence, _, _, _, _ -> () + | Item.CtorGroup(_, [MethInfo.FSMeth(_, OptionalArgumentAttribute, _, _)]), LegitTypeOccurence, _, _, _, _ -> () + | Item.Types(_, types), LegitTypeOccurence, _, _, _, m when types |> List.exists (isInterfaceTy g) -> + add m SemanticClassificationType.Interface + | Item.Types(_, types), LegitTypeOccurence, _, _, _, m when types |> List.exists (isStructTy g) -> + add m SemanticClassificationType.ValueType + | Item.Types(_, TType_app(tyconRef, TType_measure _ :: _) :: _), LegitTypeOccurence, _, _, _, m when isStructTyconRef tyconRef -> + add m SemanticClassificationType.ValueType + | Item.Types(_, types), LegitTypeOccurence, _, _, _, m when types |> List.exists isDisposableTy -> + add m SemanticClassificationType.Disposable + | Item.Types _, LegitTypeOccurence, _, _, _, m -> + add m SemanticClassificationType.ReferenceType + | (Item.TypeVar _ ), LegitTypeOccurence, _, _, _, m -> + add m SemanticClassificationType.TypeArgument + | Item.UnqualifiedType tyconRefs, LegitTypeOccurence, _, _, _, m -> + if tyconRefs |> List.exists (fun tyconRef -> tyconRef.Deref.IsStructOrEnumTycon) then + add m SemanticClassificationType.ValueType + else add m SemanticClassificationType.ReferenceType + | Item.CtorGroup(_, minfos), LegitTypeOccurence, _, _, _, m -> + if minfos |> List.exists (fun minfo -> isStructTy g minfo.ApparentEnclosingType) then + add m SemanticClassificationType.ValueType + else add m SemanticClassificationType.ReferenceType + | Item.ExnCase _, LegitTypeOccurence, _, _, _, m -> + add m SemanticClassificationType.ReferenceType + | Item.ModuleOrNamespaces refs, LegitTypeOccurence, _, _, _, m when refs |> List.exists (fun x -> x.IsModule) -> + add m SemanticClassificationType.Module + | (Item.ActivePatternCase _ | Item.UnionCase _ | Item.ActivePatternResult _), _, _, _, _, m -> + add m SemanticClassificationType.UnionCase + | _ -> ()) + results.AddRange(formatSpecifierLocations |> Array.map (fun (m, _) -> struct(m, SemanticClassificationType.Printf))) + results.ToArray() + ) + (fun msg -> + Trace.TraceInformation(sprintf "FCS: recovering from error in GetSemanticClassification: '%s'" msg) + Array.empty) \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/service/SemanticClassification.fsi b/src/fcs-fable/src/fsharp/service/SemanticClassification.fsi new file mode 100644 index 0000000000..ff0e89a29f --- /dev/null +++ b/src/fcs-fable/src/fsharp/service/SemanticClassification.fsi @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +namespace FSharp.Compiler.SourceCodeServices + +open FSharp.Compiler +open FSharp.Compiler.AccessibilityLogic +open FSharp.Compiler.Import +open FSharp.Compiler.NameResolution +open FSharp.Compiler.Range +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.TcGlobals + +/// A kind that determines what range in a source's text is semantically classified as after type-checking. +[] +type SemanticClassificationType = + | ReferenceType + | ValueType + | UnionCase + | Function + | Property + | MutableVar + | Module + | Printf + | ComputationExpression + | IntrinsicFunction + | Enumeration + | Interface + | TypeArgument + | Operator + | Disposable + +/// Extension methods for the TcResolutions type. +[] +module internal TcResolutionsExtensions = + + val (|CNR|) : cnr: CapturedNameResolution -> (Item * ItemOccurence * DisplayEnv * NameResolutionEnv * AccessorDomain * range) + + type TcResolutions with + + member GetSemanticClassification: g: TcGlobals * amap: ImportMap * formatSpecifierLocations: (range * int) [] * range: range option -> struct(range * SemanticClassificationType) [] \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/service/ServiceAnalysis.fs b/src/fcs-fable/src/fsharp/service/ServiceAnalysis.fs index f66d372bc2..d71ee6a0b8 100644 --- a/src/fcs-fable/src/fsharp/service/ServiceAnalysis.fs +++ b/src/fcs-fable/src/fsharp/service/ServiceAnalysis.fs @@ -3,7 +3,6 @@ namespace FSharp.Compiler.SourceCodeServices open FSharp.Compiler -open FSharp.Compiler.Ast open FSharp.Compiler.Range open FSharp.Compiler.PrettyNaming open System.Collections.Generic @@ -99,17 +98,30 @@ module UnusedOpens = | :? FSharpMemberOrFunctionOrValue as fv when fv.IsExtensionMember -> // Extension members should be taken into account even though they have a prefix (as they do most of the time) true + | :? FSharpMemberOrFunctionOrValue as fv when not fv.IsModuleValueOrMember -> // Local values can be ignored false + | :? FSharpMemberOrFunctionOrValue when su.IsFromDefinition -> // Value definitions should be ignored false + | :? FSharpGenericParameter -> // Generic parameters can be ignored, they never come into scope via 'open' false + | :? FSharpUnionCase when su.IsFromDefinition -> false + + | :? FSharpField as field when + field.DeclaringEntity.IsSome && field.DeclaringEntity.Value.IsFSharpRecord -> + // Record fields are used in name resolution + true + + | :? FSharpField as field when field.IsUnionCaseField -> + false + | _ -> // For the rest of symbols we pick only those which are the first part of a long ident, because it's they which are // contained in opened namespaces / modules. For example, we pick `IO` from long ident `IO.File.OpenWrite` because @@ -193,7 +205,7 @@ module UnusedOpens = let filterOpenStatements (symbolUses1: FSharpSymbolUse[], symbolUses2: FSharpSymbolUse[]) openStatements = async { // the key is a namespace or module, the value is a list of FSharpSymbolUse range of symbols defined in the - // namespace or module. So, it's just symbol uses ranges groupped by namespace or module where they are _defined_. + // namespace or module. So, it's just symbol uses ranges grouped by namespace or module where they are _defined_. let symbolUsesRangesByDeclaringEntity = Dictionary(entityHash) for symbolUse in symbolUses1 do match symbolUse.Symbol with @@ -217,4 +229,120 @@ module UnusedOpens = let symbolUses = splitSymbolUses symbolUses let openStatements = getOpenStatements checkFileResults.OpenDeclarations return! filterOpenStatements symbolUses openStatements + } + +module SimplifyNames = + type SimplifiableRange = + { + Range: range + RelativeName: string + } + + let getPlidLength (plid: string list) = (plid |> List.sumBy String.length) + plid.Length + + let getSimplifiableNames (checkFileResults: FSharpCheckFileResults, getSourceLineStr: int -> string) : Async = + async { + let result = ResizeArray() + let! symbolUses = checkFileResults.GetAllUsesOfAllSymbolsInFile() + let symbolUses = + symbolUses + |> Array.filter (fun symbolUse -> not symbolUse.IsFromOpenStatement) + |> Array.Parallel.map (fun symbolUse -> + let lineStr = getSourceLineStr symbolUse.RangeAlternate.StartLine + // for `System.DateTime.Now` it returns ([|"System"; "DateTime"|], "Now") + let partialName = QuickParse.GetPartialLongNameEx(lineStr, symbolUse.RangeAlternate.EndColumn - 1) + // `symbolUse.RangeAlternate.Start` does not point to the start of plid, it points to start of `name`, + // so we have to calculate plid's start ourselves. + let plidStartCol = symbolUse.RangeAlternate.EndColumn - partialName.PartialIdent.Length - (getPlidLength partialName.QualifyingIdents) + symbolUse, partialName.QualifyingIdents, plidStartCol, partialName.PartialIdent) + |> Array.filter (fun (_, plid, _, name) -> name <> "" && not (List.isEmpty plid)) + |> Array.groupBy (fun (symbolUse, _, plidStartCol, _) -> symbolUse.RangeAlternate.StartLine, plidStartCol) + |> Array.map (fun (_, xs) -> xs |> Array.maxBy (fun (symbolUse, _, _, _) -> symbolUse.RangeAlternate.EndColumn)) + + for symbolUse, plid, plidStartCol, name in symbolUses do + if not symbolUse.IsFromDefinition then + let posAtStartOfName = + let r = symbolUse.RangeAlternate + if r.StartLine = r.EndLine then Range.mkPos r.StartLine (r.EndColumn - name.Length) + else r.Start + + let getNecessaryPlid (plid: string list) : Async = + let rec loop (rest: string list) (current: string list) = + async { + match rest with + | [] -> return current + | headIdent :: restPlid -> + let! res = checkFileResults.IsRelativeNameResolvableFromSymbol(posAtStartOfName, current, symbolUse.Symbol) + if res then return current + else return! loop restPlid (headIdent :: current) + } + loop (List.rev plid) [] + + let! necessaryPlid = getNecessaryPlid plid + + match necessaryPlid with + | necessaryPlid when necessaryPlid = plid -> () + | necessaryPlid -> + let r = symbolUse.RangeAlternate + let necessaryPlidStartCol = r.EndColumn - name.Length - (getPlidLength necessaryPlid) + + let unnecessaryRange = + Range.mkRange r.FileName (Range.mkPos r.StartLine plidStartCol) (Range.mkPos r.EndLine necessaryPlidStartCol) + + let relativeName = (String.concat "." plid) + "." + name + result.Add({Range = unnecessaryRange; RelativeName = relativeName}) + + return List.ofSeq result + } + +module UnusedDeclarations = + let isPotentiallyUnusedDeclaration (symbol: FSharpSymbol) : bool = + + match symbol with + + // Determining that a record, DU or module is used anywhere requires inspecting all their enclosed entities (fields, cases and func / vals) + // for usages, which is too expensive to do. Hence we never gray them out. + | :? FSharpEntity as e when e.IsFSharpRecord || e.IsFSharpUnion || e.IsInterface || e.IsFSharpModule || e.IsClass || e.IsNamespace -> false + + // FCS returns inconsistent results for override members; we're skipping these symbols. + | :? FSharpMemberOrFunctionOrValue as f when + f.IsOverrideOrExplicitInterfaceImplementation || + f.IsBaseValue || + f.IsConstructor -> false + + // Usage of DU case parameters does not give any meaningful feedback; we never gray them out. + | :? FSharpParameter -> false + | _ -> true + + let getUnusedDeclarationRanges (symbolsUses: FSharpSymbolUse[]) (isScript: bool) = + let definitions = + symbolsUses + |> Array.filter (fun su -> + su.IsFromDefinition && + su.Symbol.DeclarationLocation.IsSome && + (isScript || su.IsPrivateToFile) && + not (su.Symbol.DisplayName.StartsWith "_") && + isPotentiallyUnusedDeclaration su.Symbol) + + let usages = + let usages = + symbolsUses + |> Array.filter (fun su -> not su.IsFromDefinition) + |> Array.choose (fun su -> su.Symbol.DeclarationLocation) + HashSet(usages) + + let unusedRanges = + definitions + |> Array.map (fun defSu -> defSu, usages.Contains defSu.Symbol.DeclarationLocation.Value) + |> Array.groupBy (fun (defSu, _) -> defSu.RangeAlternate) + |> Array.filter (fun (_, defSus) -> defSus |> Array.forall (fun (_, isUsed) -> not isUsed)) + |> Array.map (fun (m, _) -> m) + + Array.toList unusedRanges + + let getUnusedDeclarations(checkFileResults: FSharpCheckFileResults, isScriptFile: bool) : Async = + async { + let! allSymbolUsesInFile = checkFileResults.GetAllUsesOfAllSymbolsInFile() + let unusedRanges = getUnusedDeclarationRanges allSymbolUsesInFile isScriptFile + return unusedRanges } \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/service/ServiceAnalysis.fsi b/src/fcs-fable/src/fsharp/service/ServiceAnalysis.fsi index 8d97644389..9d09c5e3e9 100644 --- a/src/fcs-fable/src/fsharp/service/ServiceAnalysis.fsi +++ b/src/fcs-fable/src/fsharp/service/ServiceAnalysis.fsi @@ -2,10 +2,31 @@ namespace FSharp.Compiler.SourceCodeServices -open FSharp.Compiler.Ast open FSharp.Compiler.NameResolution open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree module public UnusedOpens = + /// Get all unused open declarations in a file - val getUnusedOpens : checkFileResults: FSharpCheckFileResults * getSourceLineStr: (int -> string) -> Async \ No newline at end of file + val getUnusedOpens : checkFileResults: FSharpCheckFileResults * getSourceLineStr: (int -> string) -> Async + +module public SimplifyNames = + + /// Data for use in finding unnecessarily-qualified names and generating diagnostics to simplify them + type SimplifiableRange = + { + /// The range of a name that can be simplified + Range: range + + /// The relative name that can be applied to a simplifiable name + RelativeName: string + } + + /// Get all ranges that can be simplified in a file + val getSimplifiableNames : checkFileResults: FSharpCheckFileResults * getSourceLineStr: (int -> string) -> Async + +module public UnusedDeclarations = + + /// Get all unused declarations in a file + val getUnusedDeclarations : checkFileResults: FSharpCheckFileResults * isScriptFile: bool -> Async diff --git a/src/fcs-fable/src/fsharp/service/ServiceAssemblyContent.fs b/src/fcs-fable/src/fsharp/service/ServiceAssemblyContent.fs index ec9cc20be2..0349ef74ef 100644 --- a/src/fcs-fable/src/fsharp/service/ServiceAssemblyContent.fs +++ b/src/fcs-fable/src/fsharp/service/ServiceAssemblyContent.fs @@ -11,14 +11,19 @@ open System open System.Collections.Generic open FSharp.Compiler -open FSharp.Compiler.Ast -open FSharp.Compiler.Range open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps type ShortIdent = string + type Idents = ShortIdent[] + type MaybeUnresolvedIdent = { Ident: ShortIdent; Resolved: bool } + type MaybeUnresolvedIdents = MaybeUnresolvedIdent[] + type IsAutoOpen = bool [] @@ -113,6 +118,7 @@ type AssemblySymbol = Symbol: FSharpSymbol Kind: LookupType -> EntityKind UnresolvedSymbol: UnresolvedSymbol } + override x.ToString() = sprintf "%A" x type AssemblyPath = string @@ -125,6 +131,7 @@ type Parent = AutoOpen: Idents option WithModuleSuffix: Idents option IsModule: bool } + static member Empty = { Namespace = None ThisRequiresQualifiedAccess = fun _ -> None @@ -132,6 +139,7 @@ type Parent = AutoOpen = None WithModuleSuffix = None IsModule = true } + static member RewriteParentIdents (parentIdents: Idents option) (idents: Idents) = match parentIdents with | Some p when p.Length <= idents.Length -> @@ -239,16 +247,16 @@ module AssemblyContentProvider = |> Seq.filter (fun x -> not x.IsInstanceMember && not x.IsPropertyGetterMethod && not x.IsPropertySetterMethod) |> Seq.collect (fun func -> let processIdents fullName idents = - let cleanedIdentes = parent.FixParentModuleSuffix idents + let cleanedIdents = parent.FixParentModuleSuffix idents { FullName = fullName - CleanedIdents = cleanedIdentes + CleanedIdents = cleanedIdents Namespace = ns NearestRequireQualifiedAccessParent = parent.ThisRequiresQualifiedAccess true |> Option.map parent.FixParentModuleSuffix TopRequireQualifiedAccessParent = topRequireQualifiedAccessParent AutoOpenParent = autoOpenParent Symbol = func Kind = fun _ -> EntityKind.FunctionOrValue func.IsActivePattern - UnresolvedSymbol = unresolvedSymbol topRequireQualifiedAccessParent cleanedIdentes fullName } + UnresolvedSymbol = unresolvedSymbol topRequireQualifiedAccessParent cleanedIdents fullName } [ yield! func.TryGetFullDisplayName() |> Option.map (fun fullDisplayName -> processIdents func.FullName (fullDisplayName.Split '.')) @@ -354,7 +362,7 @@ module AssemblyContentProvider = #endif | [], _ -> [] | assemblies, Some fileName -> - let fileWriteTime = FileInfo(fileName).LastWriteTime + let fileWriteTime = FileSystem.GetLastWriteTimeShim(fileName) withCache <| fun cache -> match contentType, cache.TryGet fileName with | _, Some entry @@ -493,20 +501,18 @@ type OpenStatementInsertionPoint = | Nearest module ParsedInput = - open FSharp.Compiler - open FSharp.Compiler.Ast /// An recursive pattern that collect all sequential expressions to avoid StackOverflowException let rec (|Sequentials|_|) = function - | SynExpr.Sequential(_, _, e, Sequentials es, _) -> - Some(e::es) - | SynExpr.Sequential(_, _, e1, e2, _) -> + | SynExpr.Sequential (_, _, e, Sequentials es, _) -> + Some(e :: es) + | SynExpr.Sequential (_, _, e1, e2, _) -> Some [e1; e2] | _ -> None let (|ConstructorPats|) = function - | SynConstructorArgs.Pats ps -> ps - | SynConstructorArgs.NamePatPairs(xs, _) -> List.map snd xs + | SynArgPats.Pats ps -> ps + | SynArgPats.NamePatPairs(xs, _) -> List.map snd xs /// Returns all `Ident`s and `LongIdent`s found in an untyped AST. let getLongIdents (input: ParsedInput option) : IDictionary = @@ -528,10 +534,10 @@ module ParsedInput = let addIdent (ident: Ident) = identsByEndPos.[ident.idRange.End] <- [ident] - let rec walkImplFileInput (ParsedImplFileInput(modules = moduleOrNamespaceList)) = + let rec walkImplFileInput (ParsedImplFileInput (modules = moduleOrNamespaceList)) = List.iter walkSynModuleOrNamespace moduleOrNamespaceList - and walkSynModuleOrNamespace (SynModuleOrNamespace(_, _, _, decls, _, attrs, _, _)) = + and walkSynModuleOrNamespace (SynModuleOrNamespace(_, _, _, decls, _, Attributes attrs, _, _)) = List.iter walkAttribute attrs List.iter walkSynModuleDecl decls @@ -539,7 +545,7 @@ module ParsedInput = addLongIdentWithDots attr.TypeName walkExpr attr.ArgExpr - and walkTyparDecl (SynTyparDecl.TyparDecl (attrs, typar)) = + and walkTyparDecl (SynTyparDecl.TyparDecl (Attributes attrs, typar)) = List.iter walkAttribute attrs walkTypar typar @@ -566,7 +572,7 @@ module ParsedInput = | SynPat.Typed (pat, t, _) -> walkPat pat walkType t - | SynPat.Attrib (pat, attrs, _) -> + | SynPat.Attrib (pat, Attributes attrs, _) -> walkPat pat List.iter walkAttribute attrs | SynPat.Or (pat1, pat2, _) -> List.iter walkPat [pat1; pat2] @@ -584,7 +590,7 @@ module ParsedInput = and walkTypar (Typar (_, _, _)) = () - and walkBinding (SynBinding.Binding (_, _, _, _, attrs, _, _, pat, returnInfo, e, _, _)) = + and walkBinding (SynBinding.Binding (_, _, _, _, Attributes attrs, _, _, pat, returnInfo, e, _, _)) = List.iter walkAttribute attrs walkPat pat walkExpr e @@ -593,8 +599,8 @@ module ParsedInput = and walkInterfaceImpl (InterfaceImpl(_, bindings, _)) = List.iter walkBinding bindings and walkIndexerArg = function - | SynIndexerArg.One e -> walkExpr e - | SynIndexerArg.Two (e1, e2) -> List.iter walkExpr [e1; e2] + | SynIndexerArg.One (e, _, _) -> walkExpr e + | SynIndexerArg.Two (e1, _, e2, _, _, _) -> List.iter walkExpr [e1; e2] and walkType = function | SynType.Array (_, t, _) @@ -654,7 +660,7 @@ module ParsedInput = addLongIdentWithDots ident e |> Option.iter walkExpr) | SynExpr.Ident ident -> addIdent ident - | SynExpr.ObjExpr(ty, argOpt, bindings, ifaces, _, _) -> + | SynExpr.ObjExpr (ty, argOpt, bindings, ifaces, _, _) -> argOpt |> Option.iter (fun (e, ident) -> walkExpr e ident |> Option.iter addIdent) @@ -707,9 +713,13 @@ module ParsedInput = addLongIdentWithDots ident List.iter walkExpr [e1; e2; e3] | SynExpr.JoinIn (e1, _, e2, _) -> List.iter walkExpr [e1; e2] - | SynExpr.LetOrUseBang (_, _, _, pat, e1, e2, _) -> + | SynExpr.LetOrUseBang (_, _, _, pat, e1, es, e2, _) -> walkPat pat - List.iter walkExpr [e1; e2] + walkExpr e1 + for (_,_,_,patAndBang,eAndBang,_) in es do + walkPat patAndBang + walkExpr eAndBang + walkExpr e2 | SynExpr.TraitCall (ts, sign, e, _) -> List.iter walkTypar ts walkMemberSig sign @@ -728,7 +738,7 @@ module ParsedInput = | SynMeasure.Anon _ -> () and walkSimplePat = function - | SynSimplePat.Attrib (pat, attrs, _) -> + | SynSimplePat.Attrib (pat, Attributes attrs, _) -> walkSimplePat pat List.iter walkAttribute attrs | SynSimplePat.Typed(pat, t, _) -> @@ -736,15 +746,15 @@ module ParsedInput = walkType t | _ -> () - and walkField (SynField.Field(attrs, _, _, t, _, _, _, _)) = + and walkField (SynField.Field(Attributes attrs, _, _, t, _, _, _, _)) = List.iter walkAttribute attrs walkType t - and walkValSig (SynValSig.ValSpfn(attrs, _, _, t, SynValInfo(argInfos, argInfo), _, _, _, _, _, _)) = + and walkValSig (SynValSig.ValSpfn(Attributes attrs, _, _, t, SynValInfo(argInfos, argInfo), _, _, _, _, _, _)) = List.iter walkAttribute attrs walkType t argInfo :: (argInfos |> List.concat) - |> List.map (fun (SynArgInfo(attrs, _, _)) -> attrs) + |> List.map (fun (SynArgInfo(Attributes attrs, _, _)) -> attrs) |> List.concat |> List.iter walkAttribute @@ -767,9 +777,9 @@ module ParsedInput = and walkMember = function | SynMemberDefn.AbstractSlot (valSig, _, _) -> walkValSig valSig | SynMemberDefn.Member (binding, _) -> walkBinding binding - | SynMemberDefn.ImplicitCtor (_, attrs, pats, _, _) -> + | SynMemberDefn.ImplicitCtor (_, Attributes attrs, SynSimplePats.SimplePats(simplePats, _), _, _) -> List.iter walkAttribute attrs - List.iter walkSimplePat pats + List.iter walkSimplePat simplePats | SynMemberDefn.ImplicitInherit (t, e, _, _) -> walkType t; walkExpr e | SynMemberDefn.LetBindings (bindings, _, _, _) -> List.iter walkBinding bindings | SynMemberDefn.Interface (t, members, _) -> @@ -778,19 +788,19 @@ module ParsedInput = | SynMemberDefn.Inherit (t, _, _) -> walkType t | SynMemberDefn.ValField (field, _) -> walkField field | SynMemberDefn.NestedType (tdef, _, _) -> walkTypeDefn tdef - | SynMemberDefn.AutoProperty (attrs, _, _, t, _, _, _, _, e, _, _) -> + | SynMemberDefn.AutoProperty (Attributes attrs, _, _, t, _, _, _, _, e, _, _) -> List.iter walkAttribute attrs Option.iter walkType t walkExpr e | _ -> () - and walkEnumCase (EnumCase(attrs, _, _, _, _)) = List.iter walkAttribute attrs + and walkEnumCase (EnumCase(Attributes attrs, _, _, _, _)) = List.iter walkAttribute attrs and walkUnionCaseType = function | SynUnionCaseType.UnionCaseFields fields -> List.iter walkField fields | SynUnionCaseType.UnionCaseFullType (t, _) -> walkType t - and walkUnionCase (SynUnionCase.UnionCase (attrs, _, t, _, _, _)) = + and walkUnionCase (SynUnionCase.UnionCase (Attributes attrs, _, t, _, _, _)) = List.iter walkAttribute attrs walkUnionCaseType t @@ -801,7 +811,7 @@ module ParsedInput = | SynTypeDefnSimpleRepr.TypeAbbrev (_, t, _) -> walkType t | _ -> () - and walkComponentInfo isTypeExtensionOrAlias (ComponentInfo(attrs, typars, constraints, longIdent, _, _, _, _)) = + and walkComponentInfo isTypeExtensionOrAlias (ComponentInfo(Attributes attrs, typars, constraints, longIdent, _, _, _, _)) = List.iter walkAttribute attrs List.iter walkTyparDecl typars List.iter walkTypeConstraint constraints @@ -838,7 +848,7 @@ module ParsedInput = | SynModuleDecl.Let (_, bindings, _) -> List.iter walkBinding bindings | SynModuleDecl.DoExpr (_, expr, _) -> walkExpr expr | SynModuleDecl.Types (types, _) -> List.iter walkTypeDefn types - | SynModuleDecl.Attributes (attrs, _) -> List.iter walkAttribute attrs + | SynModuleDecl.Attributes (Attributes attrs, _) -> List.iter walkAttribute attrs | _ -> () match input with @@ -864,8 +874,8 @@ module ParsedInput = // Based on an initial review, no diagnostics should be generated. However the code should be checked more closely. use _ignoreAllDiagnostics = new ErrorScope() - let result: (Scope * pos * (* finished *) bool) option ref = ref None - let ns: string[] option ref = ref None + let mutable result = None + let mutable ns = None let modules = ResizeArray() let inline longIdentToIdents ident = ident |> Seq.map (fun x -> string x) |> Seq.toArray @@ -877,17 +887,17 @@ module ParsedInput = let doRange kind (scope: LongIdent) line col = if line <= currentLine then - match !result, insertionPoint with + match result, insertionPoint with | None, _ -> - result := Some ({ Idents = longIdentToIdents scope; Kind = kind }, mkPos line col, false) + result <- Some ({ Idents = longIdentToIdents scope; Kind = kind }, mkPos line col, false) | Some (_, _, true), _ -> () | Some (oldScope, oldPos, false), OpenStatementInsertionPoint.TopLevel when kind <> OpenDeclaration -> - result := Some (oldScope, oldPos, true) + result <- Some (oldScope, oldPos, true) | Some (oldScope, oldPos, _), _ -> match kind, oldScope.Kind with | (Namespace | NestedModule | TopModule), OpenDeclaration | _ when oldPos.Line <= line -> - result := + result <- Some ({ Idents = match scope with | [] -> oldScope.Idents @@ -897,7 +907,7 @@ module ParsedInput = false) | _ -> () - let getMinColumn (decls: SynModuleDecls) = + let getMinColumn decls = match decls with | [] -> None | firstDecl :: _ -> @@ -913,18 +923,18 @@ module ParsedInput = |> Option.map (fun r -> r.StartColumn) - let rec walkImplFileInput (ParsedImplFileInput(modules = moduleOrNamespaceList)) = + let rec walkImplFileInput (ParsedImplFileInput (modules = moduleOrNamespaceList)) = List.iter (walkSynModuleOrNamespace []) moduleOrNamespaceList and walkSynModuleOrNamespace (parent: LongIdent) (SynModuleOrNamespace(ident, _, kind, decls, _, _, _, range)) = if range.EndLine >= currentLine then let isModule = kind.IsModule match isModule, parent, ident with - | false, _, _ -> ns := Some (longIdentToIdents ident) + | false, _, _ -> ns <- Some (longIdentToIdents ident) // top level module with "inlined" namespace like Ns1.Ns2.TopModule | true, [], _f :: _s :: _ -> let ident = longIdentToIdents ident - ns := Some (ident.[0..ident.Length - 2]) + ns <- Some (ident.[0..ident.Length - 2]) | _ -> () let fullIdent = parent @ ident @@ -950,8 +960,8 @@ module ParsedInput = let fullIdent = parent @ ident addModule (fullIdent, range) if range.EndLine >= currentLine then - let moduleBodyIdentation = getMinColumn decls |> Option.defaultValue (range.StartColumn + 4) - doRange NestedModule fullIdent range.StartLine moduleBodyIdentation + let moduleBodyIndentation = getMinColumn decls |> Option.defaultValue (range.StartColumn + 4) + doRange NestedModule fullIdent range.StartLine moduleBodyIndentation List.iter (walkSynModuleDecl fullIdent) decls | SynModuleDecl.Open (_, range) -> doRange OpenDeclaration [] range.EndLine (range.StartColumn - 5) | SynModuleDecl.HashDirective (_, range) -> doRange HashDirective [] range.EndLine range.StartColumn @@ -962,9 +972,9 @@ module ParsedInput = | ParsedInput.ImplFile input -> walkImplFileInput input let res = - !result + result |> Option.map (fun (scope, pos, _) -> - let ns = !ns |> Option.map longIdentToIdents + let ns = ns |> Option.map longIdentToIdents scope, ns, mkPos (pos.Line + 1) pos.Column) let modules = @@ -1010,9 +1020,9 @@ module ParsedInput = if ctx.Pos.Line > 1 then // it's an implicit module without any open declarations let line = getLineStr (ctx.Pos.Line - 2) - let isImpliciteTopLevelModule = + let isImplicitTopLevelModule = not (line.StartsWithOrdinal("module") && not (line.EndsWithOrdinal("="))) - if isImpliciteTopLevelModule then 1 else ctx.Pos.Line + if isImplicitTopLevelModule then 1 else ctx.Pos.Line else 1 | ScopeKind.Namespace -> // for namespaces the start line is start line of the first nested entity diff --git a/src/fcs-fable/src/fsharp/service/ServiceAssemblyContent.fsi b/src/fcs-fable/src/fsharp/service/ServiceAssemblyContent.fsi index 6359c10365..8174bc3ace 100644 --- a/src/fcs-fable/src/fsharp/service/ServiceAssemblyContent.fsi +++ b/src/fcs-fable/src/fsharp/service/ServiceAssemblyContent.fsi @@ -6,8 +6,8 @@ namespace FSharp.Compiler.SourceCodeServices open System open System.Collections.Generic -open FSharp.Compiler open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree /// Assembly content type. type public AssemblyContentType = @@ -41,40 +41,55 @@ type public AssemblyPath = string /// Represents type, module, member, function or value in a compiled assembly. [] type public AssemblySymbol = - { /// Full entity name as it's seen in compiled code (raw FSharpEntity.FullName, FSharpValueOrFunction.FullName). + { + /// Full entity name as it's seen in compiled code (raw FSharpEntity.FullName, FSharpValueOrFunction.FullName). FullName: string + /// Entity name parts with removed module suffixes (Ns.M1Module.M2Module.M3.entity -> Ns.M1.M2.M3.entity) - /// and replaced compiled names with display names (FSharpEntity.DisplayName, FSharpValueOrFucntion.DisplayName). + /// and replaced compiled names with display names (FSharpEntity.DisplayName, FSharpValueOrFunction.DisplayName). /// Note: *all* parts are cleaned, not the last one. CleanedIdents: Idents + /// `FSharpEntity.Namespace`. Namespace: Idents option + /// The most narrative parent module that has `RequireQualifiedAccess` attribute. NearestRequireQualifiedAccessParent: Idents option + /// Parent module that has the largest scope and has `RequireQualifiedAccess` attribute. TopRequireQualifiedAccessParent: Idents option + /// Parent module that has `AutoOpen` attribute. AutoOpenParent: Idents option + Symbol: FSharpSymbol + /// Function that returns `EntityKind` based of given `LookupKind`. Kind: LookupType -> EntityKind + /// Cache display name and namespace, used for completion. - UnresolvedSymbol: UnresolvedSymbol } + UnresolvedSymbol: UnresolvedSymbol + } /// `RawEntity` list retrieved from an assembly. type internal AssemblyContentCacheEntry = - { /// Assembly file last write time. + { + /// Assembly file last write time. FileWriteTime: DateTime + /// Content type used to get assembly content. ContentType: AssemblyContentType + /// Assembly content. - Symbols: AssemblySymbol list } + Symbols: AssemblySymbol list + } /// Assembly content cache. [] type public IAssemblyContentCache = /// Try get an assembly cached content. abstract TryGet: AssemblyPath -> AssemblyContentCacheEntry option + /// Store an assembly content. abstract Set: AssemblyPath -> AssemblyContentCacheEntry -> unit @@ -82,36 +97,45 @@ type public IAssemblyContentCache = type public EntityCache = interface IAssemblyContentCache new : unit -> EntityCache + /// Clears the cache. member Clear : unit -> unit + /// Performs an operation on the cache in thread safe manner. member Locking : (IAssemblyContentCache -> 'T) -> 'T -/// Lond identifier (i.e. it may contain dots). +/// Long identifier (i.e. it may contain dots). type public StringLongIdent = string -/// Helper data structure representing a symbol, sutable for implementing unresolved identifiers resolution code fixes. +/// Helper data structure representing a symbol, suitable for implementing unresolved identifiers resolution code fixes. type public Entity = - { /// Full name, relative to the current scope. + { + /// Full name, relative to the current scope. FullRelativeName: StringLongIdent + /// Ident parts needed to append to the current ident to make it resolvable in current scope. Qualifier: StringLongIdent + /// Namespace that is needed to open to make the entity resolvable in the current scope. Namespace: StringLongIdent option + /// Full display name (i.e. last ident plus modules with `RequireQualifiedAccess` attribute prefixed). Name: StringLongIdent + /// Last part of the entity's full name. - LastIdent: string } + LastIdent: string + } #if !FABLE_COMPILER /// Provides assembly content. module public AssemblyContentProvider = + /// Given a `FSharpAssemblySignature`, returns assembly content. val getAssemblySignatureContent : AssemblyContentType -> FSharpAssemblySignature -> AssemblySymbol list /// Returns (possibly cached) assembly content. val getAssemblyContent : - withCache: ((IAssemblyContentCache -> AssemblySymbol list) -> AssemblySymbol list) + withCache: ((IAssemblyContentCache -> AssemblySymbol list) -> AssemblySymbol list) -> contentType: AssemblyContentType -> fileName: string option -> assemblies: FSharpAssembly list @@ -128,10 +152,13 @@ type public ScopeKind = /// Insert open namespace context. type public InsertContext = - { /// Current scope kind. + { + /// Current scope kind. ScopeKind: ScopeKind + /// Current position (F# compiler line number). - Pos: pos } + Pos: pos + } /// Where open statements should be added. type public OpenStatementInsertionPoint = @@ -144,15 +171,15 @@ module public ParsedInput = /// Returns `InsertContext` based on current position and symbol idents. val tryFindInsertionContext : currentLine: int -> - ast: Ast.ParsedInput -> MaybeUnresolvedIdents -> + ast: ParsedInput -> MaybeUnresolvedIdents -> insertionPoint: OpenStatementInsertionPoint -> (( (* requiresQualifiedAccessParent: *) Idents option * (* autoOpenParent: *) Idents option * (* entityNamespace *) Idents option * (* entity: *) Idents) -> (Entity * InsertContext)[]) /// Returns `InsertContext` based on current position and symbol idents. - val findNearestPointToInsertOpenDeclaration : currentLine: int -> ast: Ast.ParsedInput -> entity: Idents -> insertionPoint: OpenStatementInsertionPoint -> InsertContext + val findNearestPointToInsertOpenDeclaration : currentLine: int -> ast: ParsedInput -> entity: Idents -> insertionPoint: OpenStatementInsertionPoint -> InsertContext - /// Returns lond identifier at position. - val getLongIdentAt : ast: Ast.ParsedInput -> pos: Range.pos -> Ast.LongIdent option + /// Returns long identifier at position. + val getLongIdentAt : ast: ParsedInput -> pos: pos -> LongIdent option /// Corrects insertion line number based on kind of scope and text surrounding the insertion point. val adjustInsertionPoint : getLineStr: (int -> string) -> ctx: InsertContext -> pos diff --git a/src/fcs-fable/src/fsharp/service/ServiceCompilerDiagnostics.fs b/src/fcs-fable/src/fsharp/service/ServiceCompilerDiagnostics.fs new file mode 100644 index 0000000000..008cb327bb --- /dev/null +++ b/src/fcs-fable/src/fsharp/service/ServiceCompilerDiagnostics.fs @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +namespace FSharp.Compiler.SourceCodeServices + +type DiagnosticKind = + | AddIndexerDot + | ReplaceWithSuggestion of suggestion:string + +[] +module CompilerDiagnostics = + let getErrorMessage diagnosticKind = + match diagnosticKind with + | AddIndexerDot -> FSComp.SR.addIndexerDot() + | ReplaceWithSuggestion s -> FSComp.SR.replaceWithSuggestion(s) \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/service/ServiceCompilerDiagnostics.fsi b/src/fcs-fable/src/fsharp/service/ServiceCompilerDiagnostics.fsi new file mode 100644 index 0000000000..4916b2c2f6 --- /dev/null +++ b/src/fcs-fable/src/fsharp/service/ServiceCompilerDiagnostics.fsi @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +namespace FSharp.Compiler.SourceCodeServices + +/// Supported kinds of diagnostics by this service. +type DiagnosticKind = + | AddIndexerDot + | ReplaceWithSuggestion of suggestion:string + +/// Exposes compiler diagnostic error messages. +module CompilerDiagnostics = + /// Given a DiagnosticKind, returns the string representing the error message for that diagnostic. + val getErrorMessage: diagnosticKind: DiagnosticKind -> string \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/service/ServiceConstants.fs b/src/fcs-fable/src/fsharp/service/ServiceConstants.fs old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/fsharp/service/ServiceDeclarationLists.fs b/src/fcs-fable/src/fsharp/service/ServiceDeclarationLists.fs index caac3ee8f8..9f340f1e4f 100644 --- a/src/fcs-fable/src/fsharp/service/ServiceDeclarationLists.fs +++ b/src/fcs-fable/src/fsharp/service/ServiceDeclarationLists.fs @@ -8,21 +8,20 @@ namespace FSharp.Compiler.SourceCodeServices open FSharp.Compiler -open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Diagnostics open FSharp.Compiler.AccessibilityLogic open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Infos +open FSharp.Compiler.InfoReader open FSharp.Compiler.Layout open FSharp.Compiler.Layout.TaggedTextOps open FSharp.Compiler.Lib +open FSharp.Compiler.NameResolution open FSharp.Compiler.PrettyNaming open FSharp.Compiler.Range -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops -open FSharp.Compiler.Infos -open FSharp.Compiler.NameResolution -open FSharp.Compiler.InfoReader +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps [] module EnvMisc3 = @@ -228,7 +227,7 @@ module internal DescriptionListsImpl = | [] -> // handles cases like 'let foo = List.map' getPrettyParamsOfTypes() - | firstCurriedArgInfo::_ -> + | firstCurriedArgInfo :: _ -> // result 'paramDatas' collection corresponds to the first argument of curried function // i.e. let func (a : int) (b : int) = a + b // paramDatas will contain information about a and retTy will be: int -> int @@ -385,7 +384,7 @@ module internal DescriptionListsImpl = /// Find the glyph for the given type representation. let typeToGlyph ty = - match tryDestAppTy denv.g ty with + match tryTcrefOfAppTy denv.g ty with | ValueSome tcref -> tcref.TypeReprInfo |> reprToGlyph | _ -> if isStructTupleTy denv.g ty then FSharpGlyph.Struct @@ -403,12 +402,13 @@ module internal DescriptionListsImpl = if isFunction denv.g vref.Type then FSharpGlyph.Method elif vref.LiteralValue.IsSome then FSharpGlyph.Constant else FSharpGlyph.Variable - | Item.Types(_, ty::_) -> typeToGlyph (stripTyEqns denv.g ty) + | Item.Types(_, ty :: _) -> typeToGlyph (stripTyEqns denv.g ty) | Item.UnionCase _ | Item.ActivePatternCase _ -> FSharpGlyph.EnumMember | Item.ExnCase _ -> FSharpGlyph.Exception | Item.AnonRecdField _ -> FSharpGlyph.Field | Item.RecdField _ -> FSharpGlyph.Field + | Item.UnionCaseField _ -> FSharpGlyph.Field | Item.ILField _ -> FSharpGlyph.Field | Item.Event _ -> FSharpGlyph.Event | Item.Property _ -> FSharpGlyph.Property @@ -437,7 +437,7 @@ module internal DescriptionListsImpl = elif tydef.IsStruct then FSharpGlyph.Struct else FSharpGlyph.Class else FSharpGlyph.Class - | Item.ModuleOrNamespaces(modref::_) -> + | Item.ModuleOrNamespaces(modref :: _) -> if modref.IsNamespace then FSharpGlyph.NameSpace else FSharpGlyph.Module | Item.ArgName _ -> FSharpGlyph.Variable | Item.SetterArg _ -> FSharpGlyph.Variable @@ -495,19 +495,12 @@ type FSharpDeclarationListItem(name: string, nameInCode: string, fullName: strin member __.StructuredDescriptionTextAsync = let userOpName = "ToolTip" match _info with - | Choice1Of2 (items: CompletionItem list, infoReader, m, denv, reactor:IReactorOperations, checkAlive) -> + | Choice1Of2 (items: CompletionItem list, infoReader, m, denv, reactor:IReactorOperations) -> // reactor causes the lambda to execute on the background compiler thread, through the Reactor reactor.EnqueueAndAwaitOpAsync (userOpName, "StructuredDescriptionTextAsync", name, fun ctok -> RequireCompilationThread ctok - // This is where we do some work which may touch TAST data structures owned by the IncrementalBuilder - infoReader, item etc. - // It is written to be robust to a disposal of an IncrementalBuilder, in which case it will just return the empty string. - // It is best to think of this as a "weak reference" to the IncrementalBuilder, i.e. this code is written to be robust to its - // disposal. Yes, you are right to scratch your head here, but this is ok. - cancellable.Return( - if checkAlive() then - FSharpToolTipText(items |> List.map (fun x -> SymbolHelpers.FormatStructuredDescriptionOfItem true infoReader m denv x.ItemWithInst)) - else - FSharpToolTipText [ FSharpStructuredToolTipElement.Single(wordL (tagText (FSComp.SR.descriptionUnavailable())), FSharpXmlDoc.None) ])) + cancellable.Return(FSharpToolTipText(items |> List.map (fun x -> SymbolHelpers.FormatStructuredDescriptionOfItem true infoReader m denv x.ItemWithInst))) + ) | Choice2Of2 result -> async.Return result @@ -564,7 +557,7 @@ type FSharpDeclarationListInfo(declarations: FSharpDeclarationListItem[], isForT member __.IsError = isError // Make a 'Declarations' object for a set of selected items - static member Create(infoReader:InfoReader, m:range, denv, getAccessibility, items: CompletionItem list, reactor:IReactorOperations, currentNamespaceOrModule: string[] option, isAttributeApplicationContext: bool, checkAlive:(unit -> bool)) = + static member Create(infoReader:InfoReader, m: range, denv, getAccessibility, items: CompletionItem list, reactor: IReactorOperations, currentNamespaceOrModule: string[] option, isAttributeApplicationContext: bool) = let g = infoReader.g let isForType = items |> List.exists (fun x -> x.Type.IsSome) let items = items |> SymbolHelpers.RemoveExplicitlySuppressedCompletionItems g @@ -628,21 +621,27 @@ type FSharpDeclarationListInfo(declarations: FSharpDeclarationListItem[], isForT // Filter out operators, active patterns (as values) and the empty list let items = // Check whether this item looks like an operator. - let isOperatorItem(name, items: CompletionItem list) = - match items |> List.map (fun x -> x.Item) with - | [Item.Value _ | Item.MethodGroup _ | Item.UnionCase _] -> IsOperatorName name + let isOperatorItem name (items: CompletionItem list) = + match items with + | [item] -> + match item.Item with + | Item.Value _ | Item.MethodGroup _ | Item.UnionCase _ -> IsOperatorName name + | _ -> false | _ -> false - + let isActivePatternItem (items: CompletionItem list) = - match items |> List.map (fun x -> x.Item) with - | [Item.Value vref] -> IsActivePatternName vref.CompiledName + match items with + | [item] -> + match item.Item with + | Item.Value vref -> IsActivePatternName vref.CoreDisplayName + | _ -> false | _ -> false - + items |> List.filter (fun (displayName, items) -> - not (isOperatorItem(displayName, items)) && + not (isOperatorItem displayName items) && not (displayName = "[]") && // list shows up as a Type and a UnionCase, only such entity with a symbolic name, but want to filter out of intellisense not (isActivePatternItem items)) - + let decls = items |> List.map (fun (displayName, itemsWithSameFullName) -> @@ -702,7 +701,7 @@ type FSharpDeclarationListInfo(declarations: FSharpDeclarationListItem[], isForT | ns -> Some (System.String.Join(".", ns))) FSharpDeclarationListItem( - name, nameInCode, fullName, glyph, Choice1Of2 (items, infoReader, m, denv, reactor, checkAlive), getAccessibility item.Item, + name, nameInCode, fullName, glyph, Choice1Of2 (items, infoReader, m, denv, reactor), getAccessibility item.Item, item.Kind, item.IsOwnMember, item.MinorPriority, item.Unresolved.IsNone, namespaceToOpen)) new FSharpDeclarationListInfo(Array.ofList decls, isForType, false) diff --git a/src/fcs-fable/src/fsharp/service/ServiceDeclarationLists.fsi b/src/fcs-fable/src/fsharp/service/ServiceDeclarationLists.fsi index 1d9ddcd2f1..6480618fe0 100644 --- a/src/fcs-fable/src/fsharp/service/ServiceDeclarationLists.fsi +++ b/src/fcs-fable/src/fsharp/service/ServiceDeclarationLists.fsi @@ -1,15 +1,12 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -//---------------------------------------------------------------------------- -// API for declaration lists and method overload lists - +/// API for declaration lists and method overload lists namespace FSharp.Compiler.SourceCodeServices -open FSharp.Compiler.Range open FSharp.Compiler.NameResolution open FSharp.Compiler.InfoReader -open FSharp.Compiler.Tastops - +open FSharp.Compiler.Range +open FSharp.Compiler.TypedTreeOps [] /// Represents a declaration in F# source code, with information attached ready for display by an editor. @@ -69,7 +66,7 @@ type public FSharpDeclarationListInfo = member IsError : bool // Implementation details used by other code in the compiler - static member internal Create : infoReader:InfoReader * m:range * denv:DisplayEnv * getAccessibility:(Item -> FSharpAccessibility option) * items:CompletionItem list * reactor:IReactorOperations * currentNamespace:string[] option * isAttributeApplicationContex:bool * checkAlive:(unit -> bool) -> FSharpDeclarationListInfo + static member internal Create : infoReader:InfoReader * m:range * denv:DisplayEnv * getAccessibility:(Item -> FSharpAccessibility option) * items:CompletionItem list * reactor:IReactorOperations * currentNamespace:string[] option * isAttributeApplicationContex:bool -> FSharpDeclarationListInfo static member internal Error : message:string -> FSharpDeclarationListInfo diff --git a/src/fcs-fable/src/fsharp/service/ServiceErrorResolutionHints.fs b/src/fcs-fable/src/fsharp/service/ServiceErrorResolutionHints.fs new file mode 100644 index 0000000000..79b4ad79e3 --- /dev/null +++ b/src/fcs-fable/src/fsharp/service/ServiceErrorResolutionHints.fs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +namespace FSharp.Compiler.SourceCodeServices + +open FSharp.Compiler.ErrorResolutionHints + +module ErrorResolutionHints = + + let getSuggestedNames (suggestionsF: FSharp.Compiler.ErrorLogger.Suggestions) (unresolvedIdentifier: string) = + let buffer = SuggestionBuffer(unresolvedIdentifier) + if buffer.Disabled then + Seq.empty + else + suggestionsF buffer.Add + buffer :> seq \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/service/ServiceErrorResolutionHints.fsi b/src/fcs-fable/src/fsharp/service/ServiceErrorResolutionHints.fsi new file mode 100644 index 0000000000..0d6b45fdcb --- /dev/null +++ b/src/fcs-fable/src/fsharp/service/ServiceErrorResolutionHints.fsi @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +namespace FSharp.Compiler.SourceCodeServices + +/// Exposes the string distance algorithm used to suggest names for mistyped identifiers. +module ErrorResolutionHints = + + /// Given a set of names, uses and a string representing an unresolved identifier, + /// returns a list of suggested names if there are any feasible candidates. + val getSuggestedNames: suggestionsF: ((string -> unit) -> unit) -> unresolvedIdentifier: string -> seq diff --git a/src/fcs-fable/src/fsharp/service/ServiceInterfaceStubGenerator.fs b/src/fcs-fable/src/fsharp/service/ServiceInterfaceStubGenerator.fs index e4a2bc7e02..8342085a1c 100644 --- a/src/fcs-fable/src/fsharp/service/ServiceInterfaceStubGenerator.fs +++ b/src/fcs-fable/src/fsharp/service/ServiceInterfaceStubGenerator.fs @@ -4,12 +4,12 @@ namespace FSharp.Compiler.SourceCodeServices open System open System.Diagnostics -open System.Collections.Generic + open FSharp.Compiler -open FSharp.Compiler.Ast +open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.Range open FSharp.Compiler.SourceCodeServices -open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.SyntaxTree #if !FX_NO_INDENTED_TEXT_WRITER [] @@ -17,7 +17,6 @@ module internal CodeGenerationUtils = open System.IO open System.CodeDom.Compiler - type ColumnIndentedTextWriter() = let stringWriter = new StringWriter() let indentWriter = new IndentedTextWriter(stringWriter, " ") @@ -53,17 +52,17 @@ module internal CodeGenerationUtils = indentWriter.Dispose() let (|IndexerArg|) = function - | SynIndexerArg.Two(e1, e2) -> [e1; e2] - | SynIndexerArg.One e -> [e] + | SynIndexerArg.Two(e1, _, e2, _, _, _) -> [e1; e2] + | SynIndexerArg.One (e, _, _) -> [e] let (|IndexerArgList|) xs = List.collect (|IndexerArg|) xs /// An recursive pattern that collect all sequential expressions to avoid StackOverflowException let rec (|Sequentials|_|) = function - | SynExpr.Sequential(_, _, e, Sequentials es, _) -> - Some(e::es) - | SynExpr.Sequential(_, _, e1, e2, _) -> + | SynExpr.Sequential (_, _, e, Sequentials es, _) -> + Some(e :: es) + | SynExpr.Sequential (_, _, e1, e2, _) -> Some [e1; e2] | _ -> None @@ -102,7 +101,7 @@ module internal CodeGenerationUtils = /// Capture information about an interface in ASTs [] -type internal InterfaceData = +type InterfaceData = | Interface of SynType * SynMemberDefns option | ObjExpr of SynType * SynBinding list member x.Range = @@ -168,7 +167,7 @@ type internal InterfaceData = | _ -> [||] -module internal InterfaceStubGenerator = +module InterfaceStubGenerator = [] type internal Context = { @@ -667,7 +666,7 @@ module internal InterfaceStubGenerator = /// Find corresponding interface declaration at a given position let tryFindInterfaceDeclaration (pos: pos) (parsedInput: ParsedInput) = - let rec walkImplFileInput (ParsedImplFileInput(modules = moduleOrNamespaceList)) = + let rec walkImplFileInput (ParsedImplFileInput (modules = moduleOrNamespaceList)) = List.tryPick walkSynModuleOrNamespace moduleOrNamespaceList and walkSynModuleOrNamespace(SynModuleOrNamespace(decls = decls; range = range)) = @@ -753,28 +752,28 @@ module internal InterfaceStubGenerator = None else match expr with - | SynExpr.Quote(synExpr1, _, synExpr2, _, _range) -> + | SynExpr.Quote (synExpr1, _, synExpr2, _, _range) -> List.tryPick walkExpr [synExpr1; synExpr2] - | SynExpr.Const(_synConst, _range) -> + | SynExpr.Const (_synConst, _range) -> None - | SynExpr.Paren(synExpr, _, _, _parenRange) -> + | SynExpr.Paren (synExpr, _, _, _parenRange) -> walkExpr synExpr - | SynExpr.Typed(synExpr, _synType, _range) -> + | SynExpr.Typed (synExpr, _synType, _range) -> walkExpr synExpr - | SynExpr.Tuple(_, synExprList, _, _range) - | SynExpr.ArrayOrList(_, synExprList, _range) -> + | SynExpr.Tuple (_, synExprList, _, _range) + | SynExpr.ArrayOrList (_, synExprList, _range) -> List.tryPick walkExpr synExprList - | SynExpr.Record(_inheritOpt, _copyOpt, fields, _range) -> + | SynExpr.Record (_inheritOpt, _copyOpt, fields, _range) -> List.tryPick (fun (_, e, _) -> Option.bind walkExpr e) fields - | SynExpr.New(_, _synType, synExpr, _range) -> + | SynExpr.New (_, _synType, synExpr, _range) -> walkExpr synExpr - | SynExpr.ObjExpr(ty, baseCallOpt, binds, ifaces, _range1, _range2) -> + | SynExpr.ObjExpr (ty, baseCallOpt, binds, ifaces, _range1, _range2) -> match baseCallOpt with | None -> if rangeContainsPos ty.Range pos then @@ -788,128 +787,134 @@ module internal InterfaceStubGenerator = // Ignore object expressions of normal objects None - | SynExpr.While(_sequencePointInfoForWhileLoop, synExpr1, synExpr2, _range) -> + | SynExpr.While (_sequencePointInfoForWhileLoop, synExpr1, synExpr2, _range) -> List.tryPick walkExpr [synExpr1; synExpr2] - | SynExpr.ForEach(_sequencePointInfoForForLoop, _seqExprOnly, _isFromSource, _synPat, synExpr1, synExpr2, _range) -> + | SynExpr.ForEach (_sequencePointInfoForForLoop, _seqExprOnly, _isFromSource, _synPat, synExpr1, synExpr2, _range) -> List.tryPick walkExpr [synExpr1; synExpr2] - | SynExpr.For(_sequencePointInfoForForLoop, _ident, synExpr1, _, synExpr2, synExpr3, _range) -> + | SynExpr.For (_sequencePointInfoForForLoop, _ident, synExpr1, _, synExpr2, synExpr3, _range) -> List.tryPick walkExpr [synExpr1; synExpr2; synExpr3] - | SynExpr.ArrayOrListOfSeqExpr(_, synExpr, _range) -> + | SynExpr.ArrayOrListOfSeqExpr (_, synExpr, _range) -> walkExpr synExpr - | SynExpr.CompExpr(_, _, synExpr, _range) -> + | SynExpr.CompExpr (_, _, synExpr, _range) -> walkExpr synExpr - | SynExpr.Lambda(_, _, _synSimplePats, synExpr, _range) -> + | SynExpr.Lambda (_, _, _synSimplePats, synExpr, _range) -> walkExpr synExpr - | SynExpr.MatchLambda(_isExnMatch, _argm, synMatchClauseList, _spBind, _wholem) -> + | SynExpr.MatchLambda (_isExnMatch, _argm, synMatchClauseList, _spBind, _wholem) -> synMatchClauseList |> List.tryPick (fun (Clause(_, _, e, _, _)) -> walkExpr e) - | SynExpr.Match(_sequencePointInfoForBinding, synExpr, synMatchClauseList, _range) -> + | SynExpr.Match (_sequencePointInfoForBinding, synExpr, synMatchClauseList, _range) -> walkExpr synExpr |> Option.orElse (synMatchClauseList |> List.tryPick (fun (Clause(_, _, e, _, _)) -> walkExpr e)) - | SynExpr.Lazy(synExpr, _range) -> + | SynExpr.Lazy (synExpr, _range) -> walkExpr synExpr - | SynExpr.Do(synExpr, _range) -> + | SynExpr.Do (synExpr, _range) -> walkExpr synExpr - | SynExpr.Assert(synExpr, _range) -> + | SynExpr.Assert (synExpr, _range) -> walkExpr synExpr - | SynExpr.App(_exprAtomicFlag, _isInfix, synExpr1, synExpr2, _range) -> + | SynExpr.App (_exprAtomicFlag, _isInfix, synExpr1, synExpr2, _range) -> List.tryPick walkExpr [synExpr1; synExpr2] - | SynExpr.TypeApp(synExpr, _, _synTypeList, _commas, _, _, _range) -> + | SynExpr.TypeApp (synExpr, _, _synTypeList, _commas, _, _, _range) -> walkExpr synExpr - | SynExpr.LetOrUse(_, _, synBindingList, synExpr, _range) -> + | SynExpr.LetOrUse (_, _, synBindingList, synExpr, _range) -> Option.orElse (List.tryPick walkBinding synBindingList) (walkExpr synExpr) - | SynExpr.TryWith(synExpr, _range, _synMatchClauseList, _range2, _range3, _sequencePointInfoForTry, _sequencePointInfoForWith) -> + | SynExpr.TryWith (synExpr, _range, _synMatchClauseList, _range2, _range3, _sequencePointInfoForTry, _sequencePointInfoForWith) -> walkExpr synExpr - | SynExpr.TryFinally(synExpr1, synExpr2, _range, _sequencePointInfoForTry, _sequencePointInfoForFinally) -> + | SynExpr.TryFinally (synExpr1, synExpr2, _range, _sequencePointInfoForTry, _sequencePointInfoForFinally) -> List.tryPick walkExpr [synExpr1; synExpr2] | Sequentials exprs -> List.tryPick walkExpr exprs - | SynExpr.IfThenElse(synExpr1, synExpr2, synExprOpt, _sequencePointInfoForBinding, _isRecovery, _range, _range2) -> + | SynExpr.IfThenElse (synExpr1, synExpr2, synExprOpt, _sequencePointInfoForBinding, _isRecovery, _range, _range2) -> match synExprOpt with | Some synExpr3 -> List.tryPick walkExpr [synExpr1; synExpr2; synExpr3] | None -> List.tryPick walkExpr [synExpr1; synExpr2] - | SynExpr.Ident(_ident) -> + | SynExpr.Ident (_ident) -> None - | SynExpr.LongIdent(_, _longIdent, _altNameRefCell, _range) -> + | SynExpr.LongIdent (_, _longIdent, _altNameRefCell, _range) -> None - | SynExpr.LongIdentSet(_longIdent, synExpr, _range) -> + | SynExpr.LongIdentSet (_longIdent, synExpr, _range) -> walkExpr synExpr - | SynExpr.DotGet(synExpr, _dotm, _longIdent, _range) -> + | SynExpr.DotGet (synExpr, _dotm, _longIdent, _range) -> walkExpr synExpr - | SynExpr.DotSet(synExpr1, _longIdent, synExpr2, _range) -> + | SynExpr.DotSet (synExpr1, _longIdent, synExpr2, _range) -> List.tryPick walkExpr [synExpr1; synExpr2] - | SynExpr.Set(synExpr1, synExpr2, _range) -> + | SynExpr.Set (synExpr1, synExpr2, _range) -> List.tryPick walkExpr [synExpr1; synExpr2] - | SynExpr.DotIndexedGet(synExpr, IndexerArgList synExprList, _range, _range2) -> + | SynExpr.DotIndexedGet (synExpr, IndexerArgList synExprList, _range, _range2) -> Option.orElse (walkExpr synExpr) (List.tryPick walkExpr synExprList) - | SynExpr.DotIndexedSet(synExpr1, IndexerArgList synExprList, synExpr2, _, _range, _range2) -> + | SynExpr.DotIndexedSet (synExpr1, IndexerArgList synExprList, synExpr2, _, _range, _range2) -> [ yield synExpr1 yield! synExprList yield synExpr2 ] |> List.tryPick walkExpr - | SynExpr.JoinIn(synExpr1, _range, synExpr2, _range2) -> + | SynExpr.JoinIn (synExpr1, _range, synExpr2, _range2) -> List.tryPick walkExpr [synExpr1; synExpr2] - | SynExpr.NamedIndexedPropertySet(_longIdent, synExpr1, synExpr2, _range) -> + | SynExpr.NamedIndexedPropertySet (_longIdent, synExpr1, synExpr2, _range) -> List.tryPick walkExpr [synExpr1; synExpr2] - | SynExpr.DotNamedIndexedPropertySet(synExpr1, _longIdent, synExpr2, synExpr3, _range) -> + | SynExpr.DotNamedIndexedPropertySet (synExpr1, _longIdent, synExpr2, synExpr3, _range) -> List.tryPick walkExpr [synExpr1; synExpr2; synExpr3] - | SynExpr.TypeTest(synExpr, _synType, _range) - | SynExpr.Upcast(synExpr, _synType, _range) - | SynExpr.Downcast(synExpr, _synType, _range) -> + | SynExpr.TypeTest (synExpr, _synType, _range) + | SynExpr.Upcast (synExpr, _synType, _range) + | SynExpr.Downcast (synExpr, _synType, _range) -> walkExpr synExpr - | SynExpr.InferredUpcast(synExpr, _range) - | SynExpr.InferredDowncast(synExpr, _range) -> + | SynExpr.InferredUpcast (synExpr, _range) + | SynExpr.InferredDowncast (synExpr, _range) -> walkExpr synExpr - | SynExpr.AddressOf(_, synExpr, _range, _range2) -> + | SynExpr.AddressOf (_, synExpr, _range, _range2) -> walkExpr synExpr - | SynExpr.TraitCall(_synTyparList, _synMemberSig, synExpr, _range) -> + | SynExpr.TraitCall (_synTyparList, _synMemberSig, synExpr, _range) -> walkExpr synExpr - | SynExpr.Null(_range) - | SynExpr.ImplicitZero(_range) -> + | SynExpr.Null (_range) + | SynExpr.ImplicitZero (_range) -> None - | SynExpr.YieldOrReturn(_, synExpr, _range) - | SynExpr.YieldOrReturnFrom(_, synExpr, _range) - | SynExpr.DoBang(synExpr, _range) -> + | SynExpr.YieldOrReturn (_, synExpr, _range) + | SynExpr.YieldOrReturnFrom (_, synExpr, _range) + | SynExpr.DoBang (synExpr, _range) -> walkExpr synExpr - | SynExpr.LetOrUseBang(_sequencePointInfoForBinding, _, _, _synPat, synExpr1, synExpr2, _range) -> - List.tryPick walkExpr [synExpr1; synExpr2] + | SynExpr.LetOrUseBang (_sequencePointInfoForBinding, _, _, _synPat, synExpr1, synExprAndBangs, synExpr2, _range) -> + [ + yield synExpr1 + for (_,_,_,_,eAndBang,_) in synExprAndBangs do + yield eAndBang + yield synExpr2 + ] + |> List.tryPick walkExpr | SynExpr.LibraryOnlyILAssembly _ | SynExpr.LibraryOnlyStaticOptimization _ | SynExpr.LibraryOnlyUnionCaseFieldGet _ | SynExpr.LibraryOnlyUnionCaseFieldSet _ -> None - | SynExpr.ArbitraryAfterError(_debugStr, _range) -> + | SynExpr.ArbitraryAfterError (_debugStr, _range) -> None - | SynExpr.FromParseError(synExpr, _range) - | SynExpr.DiscardAfterMissingQualificationAfterDot(synExpr, _range) -> + | SynExpr.FromParseError (synExpr, _range) + | SynExpr.DiscardAfterMissingQualificationAfterDot (synExpr, _range) -> walkExpr synExpr | _ -> None diff --git a/src/fcs-fable/src/fsharp/service/ServiceInterfaceStubGenerator.fsi b/src/fcs-fable/src/fsharp/service/ServiceInterfaceStubGenerator.fsi index 49a0da63d3..6f4ed525f5 100644 --- a/src/fcs-fable/src/fsharp/service/ServiceInterfaceStubGenerator.fsi +++ b/src/fcs-fable/src/fsharp/service/ServiceInterfaceStubGenerator.fsi @@ -2,25 +2,20 @@ namespace FSharp.Compiler.SourceCodeServices -open System -open System.Diagnostics -open System.Collections.Generic -open FSharp.Compiler -open FSharp.Compiler.Ast open FSharp.Compiler.Range open FSharp.Compiler.SourceCodeServices -open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.SyntaxTree #if !FX_NO_INDENTED_TEXT_WRITER /// Capture information about an interface in ASTs [] -type internal InterfaceData = +type InterfaceData = | Interface of SynType * SynMemberDefns option | ObjExpr of SynType * SynBinding list member Range : range member TypeParameters : string[] -module internal InterfaceStubGenerator = +module InterfaceStubGenerator = /// Get members in the decreasing order of inheritance chain val getInterfaceMembers : FSharpEntity -> seq> diff --git a/src/fcs-fable/src/fsharp/service/ServiceLexing.fs b/src/fcs-fable/src/fsharp/service/ServiceLexing.fs old mode 100755 new mode 100644 index 93ebc981ad..e0ce82d925 --- a/src/fcs-fable/src/fsharp/service/ServiceLexing.fs +++ b/src/fcs-fable/src/fsharp/service/ServiceLexing.fs @@ -8,20 +8,25 @@ namespace FSharp.Compiler.SourceCodeServices open System open System.Collections.Generic -open FSharp.Compiler.AbstractIL.Internal -open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler -open FSharp.Compiler.Parser -open FSharp.Compiler.Range -open FSharp.Compiler.Ast + +open FSharp.Compiler +open FSharp.Compiler.AbstractIL.Internal +open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features open FSharp.Compiler.Lexhelp open FSharp.Compiler.Lib +open FSharp.Compiler.Parser +open FSharp.Compiler.ParseHelpers +open FSharp.Compiler.Range + +open Internal.Utilities type Position = int * int + type Range = Position * Position -module FSharpTokenTag = +module FSharpTokenTag = let Identifier = tagOfToken (IDENT "a") let String = tagOfToken (STRING "a") @@ -52,6 +57,7 @@ module FSharpTokenTag = let COMMA = tagOfToken COMMA let DOT = tagOfToken DOT let DOT_DOT = tagOfToken DOT_DOT + let DOT_DOT_HAT = tagOfToken DOT_DOT_HAT let INT32_DOT_DOT = tagOfToken (INT32_DOT_DOT(0, true)) let UNDERSCORE = tagOfToken UNDERSCORE let BAR = tagOfToken BAR @@ -83,11 +89,11 @@ module FSharpTokenTag = let WITH = tagOfToken WITH let OWITH = tagOfToken OWITH - + /// This corresponds to a token categorization originally used in Visual Studio 2003. -/// +/// /// NOTE: This corresponds to a token categorization originally used in Visual Studio 2003 and the original Babel source code. -/// It is not clear it is a primary logical classification that should be being used in the +/// It is not clear it is a primary logical classification that should be being used in the /// more recent language service work. type FSharpTokenColorKind = | Default = 0 @@ -104,27 +110,27 @@ type FSharpTokenColorKind = | Punctuation = 11 /// Categorize an action the editor should take in response to a token, e.g. brace matching -/// +/// /// NOTE: This corresponds to a token categorization originally used in Visual Studio 2003 and the original Babel source code. -/// It is not clear it is a primary logical classification that should be being used in the +/// It is not clear it is a primary logical classification that should be being used in the /// more recent language service work. type FSharpTokenTriggerClass = | None = 0x00000000 | MemberSelect = 0x00000001 - | MatchBraces = 0x00000002 + | MatchBraces = 0x00000002 | ChoiceSelect = 0x00000004 | MethodTip = 0x000000F0 | ParamStart = 0x00000010 | ParamNext = 0x00000020 | ParamEnd = 0x00000040 - - + + /// This corresponds to a token categorization originally used in Visual Studio 2003. -/// +/// /// NOTE: This corresponds to a token categorization originally used in Visual Studio 2003 and the original Babel source code. -/// It is not clear it is a primary logical classification that should be being used in the +/// It is not clear it is a primary logical classification that should be being used in the /// more recent language service work. -type FSharpTokenCharKind = +type FSharpTokenCharKind = | Default = 0x00000000 | Text = 0x00000000 | Keyword = 0x00000001 @@ -135,7 +141,7 @@ type FSharpTokenCharKind = | Delimiter = 0x00000006 | WhiteSpace = 0x00000008 | LineComment = 0x00000009 - | Comment = 0x0000000A + | Comment = 0x0000000A /// Information about a particular token from the tokenizer @@ -153,52 +159,51 @@ type FSharpTokenInfo = { // Babel flags //-------------------------------------------------------------------------- -module internal TokenClassifications = +module internal TokenClassifications = //---------------------------------------------------------------------------- - //From tokens to flags + //From tokens to flags //-------------------------------------------------------------------------- - let tokenInfo token = - match token with - | IDENT s - -> - if s.Length <= 0 then + let tokenInfo token = + match token with + | IDENT s -> + if s.Length <= 0 then System.Diagnostics.Debug.Assert(false, "BUG: Received zero length IDENT token.") // This is related to 4783. Recover by treating as lower case identifier. - (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) - else + (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) + else if System.Char.ToUpperInvariant s.[0] = s.[0] then (FSharpTokenColorKind.UpperIdentifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) else - (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) + (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) // 'in' when used in a 'join' in a query expression | JOIN_IN -> - (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) + (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) | DECIMAL _ - | BIGNUM _ | INT8 _ | UINT8 _ | INT16 _ | UINT16 _ | INT32 _ | UINT32 _ | INT64 _ | UINT64 _ - | UNATIVEINT _ | NATIVEINT _ | IEEE32 _ | IEEE64 _ - -> (FSharpTokenColorKind.Number, FSharpTokenCharKind.Literal, FSharpTokenTriggerClass.None) + | BIGNUM _ | INT8 _ | UINT8 _ | INT16 _ | UINT16 _ | INT32 _ | UINT32 _ | INT64 _ | UINT64 _ + | UNATIVEINT _ | NATIVEINT _ | IEEE32 _ | IEEE64 _ -> + (FSharpTokenColorKind.Number, FSharpTokenCharKind.Literal, FSharpTokenTriggerClass.None) - | INT32_DOT_DOT _ - // This will color the whole "1.." expression in a 'number' color + | INT32_DOT_DOT _ -> + // This will color the whole "1.." expression in a 'number' color // (this isn't entirely correct, but it'll work for now - see bug 3727) - -> (FSharpTokenColorKind.Number, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.None) - + (FSharpTokenColorKind.Number, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.None) + | INFIX_STAR_DIV_MOD_OP ("mod" | "land" | "lor" | "lxor") - | INFIX_STAR_STAR_OP ("lsl" | "lsr" | "asr") - -> (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) + | INFIX_STAR_STAR_OP ("lsl" | "lsr" | "asr") -> + (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) | LPAREN_STAR_RPAREN - | DOLLAR | COLON_GREATER | COLON_COLON - | PERCENT_OP _ | PLUS_MINUS_OP _ | PREFIX_OP _ | COLON_QMARK_GREATER + | DOLLAR | COLON_GREATER | COLON_COLON + | PERCENT_OP _ | PLUS_MINUS_OP _ | PREFIX_OP _ | COLON_QMARK_GREATER | AMP | AMP_AMP | BAR_BAR | QMARK | QMARK_QMARK | COLON_QMARK - | HIGH_PRECEDENCE_TYAPP + | HIGH_PRECEDENCE_TYAPP | COLON_EQUALS | EQUALS | RQUOTE_DOT _ - | MINUS | ADJACENT_PREFIX_OP _ - -> (FSharpTokenColorKind.Operator, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.None) - + | MINUS | ADJACENT_PREFIX_OP _ -> + (FSharpTokenColorKind.Operator, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.None) + | INFIX_COMPARE_OP _ // This is a whole family: .< .> .= .!= .$ | FUNKY_OPERATOR_NAME _ // This is another whole family, including: .[] and .() //| INFIX_AT_HAT_OP _ @@ -209,114 +214,121 @@ module internal TokenClassifications = | INFIX_AMP_OP _ -> (FSharpTokenColorKind.Operator, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.None) - | DOT_DOT - -> + | DOT_DOT | DOT_DOT_HAT -> (FSharpTokenColorKind.Operator, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.MemberSelect) - | COMMA - -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.ParamNext) - - | DOT - -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.MemberSelect) - - | BAR - -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None (* FSharpTokenTriggerClass.ChoiceSelect *)) - - | HASH | STAR | SEMICOLON | SEMICOLON_SEMICOLON | COLON - -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None) - - | QUOTE | UNDERSCORE - | INFIX_AT_HAT_OP _ - -> (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) - - | LESS _ - -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.ParamStart) // for type provider static arguments - | GREATER _ - -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.ParamEnd) // for type provider static arguments - - | LPAREN - // We need 'ParamStart' to trigger the 'GetDeclarations' method to show param info automatically - // this is needed even if we don't use MPF for determining information about params - -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.ParamStart ||| FSharpTokenTriggerClass.MatchBraces) - - | RPAREN | RPAREN_COMING_SOON | RPAREN_IS_HERE - -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.ParamEnd ||| FSharpTokenTriggerClass.MatchBraces) - - | LBRACK_LESS - -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None ) - - | LQUOTE _ | LBRACK | LBRACE | LBRACK_BAR | LBRACE_BAR - -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.MatchBraces ) - - | GREATER_RBRACK | GREATER_BAR_RBRACK - -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None ) - - | RQUOTE _ | RBRACK | RBRACE | RBRACE_COMING_SOON | RBRACE_IS_HERE | BAR_RBRACK | BAR_RBRACE - -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.MatchBraces ) - + | COMMA -> + (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.ParamNext) + + | DOT -> + (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.MemberSelect) + + | BAR -> + (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None (* FSharpTokenTriggerClass.ChoiceSelect *)) + + | HASH | STAR | SEMICOLON | SEMICOLON_SEMICOLON | COLON -> + (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None) + + | QUOTE | UNDERSCORE + | INFIX_AT_HAT_OP _ -> + (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) + + | LESS _ -> + (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.ParamStart) // for type provider static arguments + + | GREATER _ -> + (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.ParamEnd) // for type provider static arguments + + | LPAREN -> + // We need 'ParamStart' to trigger the 'GetDeclarations' method to show param info automatically + // this is needed even if we don't use MPF for determining information about params + (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.ParamStart ||| FSharpTokenTriggerClass.MatchBraces) + + | RPAREN | RPAREN_COMING_SOON | RPAREN_IS_HERE -> + (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.ParamEnd ||| FSharpTokenTriggerClass.MatchBraces) + + | LBRACK_LESS -> + (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None ) + + | LQUOTE _ | LBRACK | LBRACE | LBRACK_BAR | LBRACE_BAR -> + (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.MatchBraces ) + + | GREATER_RBRACK | GREATER_BAR_RBRACK -> + (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None ) + + | RQUOTE _ | RBRACK | RBRACE | RBRACE_COMING_SOON | RBRACE_IS_HERE | BAR_RBRACK | BAR_RBRACE -> + (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.MatchBraces ) + | PUBLIC | PRIVATE | INTERNAL | BASE | GLOBAL | CONSTRAINT | INSTANCE | DELEGATE | INHERIT|CONSTRUCTOR|DEFAULT|OVERRIDE|ABSTRACT|CLASS | MEMBER | STATIC | NAMESPACE - | OASSERT | OLAZY | ODECLEND | OBLOCKSEP | OEND | OBLOCKBEGIN | ORIGHT_BLOCK_END - | OBLOCKEND | OBLOCKEND_COMING_SOON | OBLOCKEND_IS_HERE | OTHEN | OELSE | OLET(_) - | OBINDER _ | BINDER _ | ODO | OWITH | OFUNCTION | OFUN | ORESET | ODUMMY _ | DO_BANG + | OASSERT | OLAZY | ODECLEND | OBLOCKSEP | OEND | OBLOCKBEGIN | ORIGHT_BLOCK_END + | OBLOCKEND | OBLOCKEND_COMING_SOON | OBLOCKEND_IS_HERE | OTHEN | OELSE | OLET(_) + | OBINDER _ | OAND_BANG _ | BINDER _ | ODO | OWITH | OFUNCTION | OFUN | ORESET | ODUMMY _ | DO_BANG | ODO_BANG | YIELD _ | YIELD_BANG _ | OINTERFACE_MEMBER - | ELIF | RARROW | LARROW | SIG | STRUCT + | ELIF | RARROW | LARROW | SIG | STRUCT | UPCAST | DOWNCAST | NULL | RESERVED | MODULE | AND | AS | ASSERT | ASR | DOWNTO | EXCEPTION | FALSE | FOR | FUN | FUNCTION | FINALLY | LAZY | MATCH | MATCH_BANG | MUTABLE | NEW | OF | OPEN | OR | VOID | EXTERN | INTERFACE | REC | TO | TRUE | TRY | TYPE | VAL | INLINE | WHEN | WHILE | WITH - | IF | THEN | ELSE | DO | DONE | LET(_) | IN (*| NAMESPACE*) | CONST + | IF | THEN | ELSE | DO | DONE | LET _ | AND_BANG _ | IN | CONST | HIGH_PRECEDENCE_PAREN_APP | FIXED | HIGH_PRECEDENCE_BRACK_APP - | TYPE_COMING_SOON | TYPE_IS_HERE | MODULE_COMING_SOON | MODULE_IS_HERE - -> (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) - - | BEGIN - -> (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) - - | END - -> (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) + | TYPE_COMING_SOON | TYPE_IS_HERE | MODULE_COMING_SOON | MODULE_IS_HERE -> + (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) + + | BEGIN -> + (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) + + | END -> + (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) + | HASH_LIGHT _ | HASH_LINE _ | HASH_IF _ | HASH_ELSE _ - | HASH_ENDIF _ -> + | HASH_ENDIF _ -> (FSharpTokenColorKind.PreprocessorKeyword, FSharpTokenCharKind.WhiteSpace, FSharpTokenTriggerClass.None) - | INACTIVECODE _ -> + + | INACTIVECODE _ -> (FSharpTokenColorKind.InactiveCode, FSharpTokenCharKind.WhiteSpace, FSharpTokenTriggerClass.None) - + | LEX_FAILURE _ - | WHITESPACE _ -> + | WHITESPACE _ -> (FSharpTokenColorKind.Default, FSharpTokenCharKind.WhiteSpace, FSharpTokenTriggerClass.None) - | COMMENT _ -> + | COMMENT _ -> (FSharpTokenColorKind.Comment, FSharpTokenCharKind.Comment, FSharpTokenTriggerClass.None) - | LINE_COMMENT _ -> + + | LINE_COMMENT _ -> (FSharpTokenColorKind.Comment, FSharpTokenCharKind.LineComment, FSharpTokenTriggerClass.None) - | STRING_TEXT _ -> + + | STRING_TEXT _ -> (FSharpTokenColorKind.String, FSharpTokenCharKind.String, FSharpTokenTriggerClass.None) - | KEYWORD_STRING _ -> + + | KEYWORD_STRING _ -> (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) + | BYTEARRAY _ | STRING _ - | CHAR _ (* bug://2863 asks to color 'char' as "string" *) - -> (FSharpTokenColorKind.String, FSharpTokenCharKind.String, FSharpTokenTriggerClass.None) + | CHAR _ -> + (FSharpTokenColorKind.String, FSharpTokenCharKind.String, FSharpTokenTriggerClass.None) + | EOF _ -> failwith "tokenInfo" -module internal TestExpose = +module internal TestExpose = let TokenInfo tok = TokenClassifications.tokenInfo tok - + //---------------------------------------------------------------------------- // Lexer states encoded to/from integers //-------------------------------------------------------------------------- [] -type FSharpTokenizerLexState = +type FSharpTokenizerLexState = { PosBits: int64 OtherBits: int64 } static member Initial = { PosBits = 0L; OtherBits = 0L } member this.Equals (other: FSharpTokenizerLexState) = (this.PosBits = other.PosBits) && (this.OtherBits = other.OtherBits) - override this.Equals (obj: obj) = match obj with :? FSharpTokenizerLexState as other -> this.Equals(other) | _ -> false + override this.Equals (obj: obj) = match obj with :? FSharpTokenizerLexState as other -> this.Equals other | _ -> false override this.GetHashCode () = hash this.PosBits + hash this.OtherBits type FSharpTokenizerColorState = @@ -333,23 +345,23 @@ type FSharpTokenizerColorState = | EndLineThenToken = 12 | TripleQuoteString = 13 | TripleQuoteStringInComment = 14 - | InitialState = 0 - + | InitialState = 0 + -module internal LexerStateEncoding = +module internal LexerStateEncoding = - let computeNextLexState token (prevLexcont: LexerWhitespaceContinuation) = - match token with + let computeNextLexState token (prevLexcont: LexerWhitespaceContinuation) = + match token with | HASH_LINE s | HASH_LIGHT s | HASH_IF(_, _, s) | HASH_ELSE(_, _, s) | HASH_ENDIF(_, _, s) | INACTIVECODE s - | WHITESPACE s - | COMMENT s - | LINE_COMMENT s - | STRING_TEXT s + | WHITESPACE s + | COMMENT s + | LINE_COMMENT s + | STRING_TEXT s | EOF s -> s | BYTEARRAY _ | STRING _ -> LexCont.Token(prevLexcont.LexerIfdefStack) | _ -> prevLexcont @@ -362,10 +374,10 @@ module internal LexerStateEncoding = let hardwhiteNumBits = 1 let ifdefstackCountNumBits = 8 let ifdefstackNumBits = 24 // 0 means if, 1 means else - let _ = assert (lexstateNumBits - + ncommentsNumBits - + hardwhiteNumBits - + ifdefstackCountNumBits + let _ = assert (lexstateNumBits + + ncommentsNumBits + + hardwhiteNumBits + + ifdefstackCountNumBits + ifdefstackNumBits <= 64) let lexstateStart = 0 @@ -373,7 +385,7 @@ module internal LexerStateEncoding = let hardwhitePosStart = lexstateNumBits+ncommentsNumBits let ifdefstackCountStart = lexstateNumBits+ncommentsNumBits+hardwhiteNumBits let ifdefstackStart = lexstateNumBits+ncommentsNumBits+hardwhiteNumBits+ifdefstackCountNumBits - + let lexstateMask = Bits.mask64 lexstateStart lexstateNumBits let ncommentsMask = Bits.mask64 ncommentsStart ncommentsNumBits let hardwhitePosMask = Bits.mask64 hardwhitePosStart hardwhiteNumBits @@ -389,17 +401,17 @@ module internal LexerStateEncoding = let inline lexStateOfColorState (state: FSharpTokenizerColorState) = (int64 state <<< lexstateStart) &&& lexstateMask - let encodeLexCont (colorState: FSharpTokenizerColorState) ncomments (b: pos) ifdefStack light = + let encodeLexCont (colorState: FSharpTokenizerColorState) ncomments (b: pos) ifdefStack light = let mutable ifdefStackCount = 0 let mutable ifdefStackBits = 0 for ifOrElse in ifdefStack do - match ifOrElse with + match ifOrElse with | (IfDefIf, _) -> () - | (IfDefElse, _) -> + | (IfDefElse, _) -> ifdefStackBits <- (ifdefStackBits ||| (1 <<< ifdefStackCount)) ifdefStackCount <- ifdefStackCount + 1 - let bits = + let bits = lexStateOfColorState colorState ||| ((ncomments <<< ncommentsStart) &&& ncommentsMask) ||| ((int64 (bitOfBool light) <<< hardwhitePosStart) &&& hardwhitePosMask) @@ -407,125 +419,124 @@ module internal LexerStateEncoding = ||| ((int64 ifdefStackBits <<< ifdefstackStart) &&& ifdefstackMask) { PosBits = b.Encoding OtherBits = bits } - - let decodeLexCont (state: FSharpTokenizerLexState) = + + let decodeLexCont (state: FSharpTokenizerLexState) = let mutable ifDefs = [] let bits = state.OtherBits - let ifdefStackCount = (int32) ((bits &&& ifdefstackCountMask) >>> ifdefstackCountStart) - if ifdefStackCount>0 then - let ifdefStack = (int32) ((bits &&& ifdefstackMask) >>> ifdefstackStart) + let ifdefStackCount = int32 ((bits &&& ifdefstackCountMask) >>> ifdefstackCountStart) + if ifdefStackCount>0 then + let ifdefStack = int32 ((bits &&& ifdefstackMask) >>> ifdefstackStart) for i in 1..ifdefStackCount do let bit = ifdefStackCount-i let mask = 1 <<< bit let ifDef = (if ifdefStack &&& mask = 0 then IfDefIf else IfDefElse) - ifDefs<-(ifDef, range0)::ifDefs + ifDefs <- (ifDef, range0) :: ifDefs colorStateOfLexState state, int32 ((bits &&& ncommentsMask) >>> ncommentsStart), pos.Decode state.PosBits, ifDefs, boolOfBit ((bits &&& hardwhitePosMask) >>> hardwhitePosStart) - let encodeLexInt lightSyntaxStatus (lexcont: LexerWhitespaceContinuation) = - let tag, n1, p1, ifd = - match lexcont with - | LexCont.Token ifd -> FSharpTokenizerColorState.Token, 0L, pos0, ifd - | LexCont.IfDefSkip (ifd, n, m) -> FSharpTokenizerColorState.IfDefSkip, int64 n, m.Start, ifd + let encodeLexInt lightSyntaxStatus (lexcont: LexerWhitespaceContinuation) = + let tag, n1, p1, ifd = + match lexcont with + | LexCont.Token ifd -> FSharpTokenizerColorState.Token, 0L, pos0, ifd + | LexCont.IfDefSkip (ifd, n, m) -> FSharpTokenizerColorState.IfDefSkip, int64 n, m.Start, ifd | LexCont.EndLine(LexerEndlineContinuation.Skip(ifd, n, m)) -> FSharpTokenizerColorState.EndLineThenSkip, int64 n, m.Start, ifd - | LexCont.EndLine(LexerEndlineContinuation.Token(ifd)) -> FSharpTokenizerColorState.EndLineThenToken, 0L, pos0, ifd - | LexCont.String (ifd, m) -> FSharpTokenizerColorState.String, 0L, m.Start, ifd - | LexCont.Comment (ifd, n, m) -> FSharpTokenizerColorState.Comment, int64 n, m.Start, ifd - | LexCont.SingleLineComment (ifd, n, m) -> FSharpTokenizerColorState.SingleLineComment, int64 n, m.Start, ifd - | LexCont.StringInComment (ifd, n, m) -> FSharpTokenizerColorState.StringInComment, int64 n, m.Start, ifd - | LexCont.VerbatimStringInComment (ifd, n, m) -> FSharpTokenizerColorState.VerbatimStringInComment, int64 n, m.Start, ifd - | LexCont.TripleQuoteStringInComment (ifd, n, m) -> FSharpTokenizerColorState.TripleQuoteStringInComment, int64 n, m.Start, ifd - | LexCont.MLOnly (ifd, m) -> FSharpTokenizerColorState.CamlOnly, 0L, m.Start, ifd - | LexCont.VerbatimString (ifd, m) -> FSharpTokenizerColorState.VerbatimString, 0L, m.Start, ifd - | LexCont.TripleQuoteString (ifd, m) -> FSharpTokenizerColorState.TripleQuoteString, 0L, m.Start, ifd + | LexCont.EndLine(LexerEndlineContinuation.Token ifd) -> FSharpTokenizerColorState.EndLineThenToken, 0L, pos0, ifd + | LexCont.String (ifd, m) -> FSharpTokenizerColorState.String, 0L, m.Start, ifd + | LexCont.Comment (ifd, n, m) -> FSharpTokenizerColorState.Comment, int64 n, m.Start, ifd + | LexCont.SingleLineComment (ifd, n, m) -> FSharpTokenizerColorState.SingleLineComment, int64 n, m.Start, ifd + | LexCont.StringInComment (ifd, n, m) -> FSharpTokenizerColorState.StringInComment, int64 n, m.Start, ifd + | LexCont.VerbatimStringInComment (ifd, n, m) -> FSharpTokenizerColorState.VerbatimStringInComment, int64 n, m.Start, ifd + | LexCont.TripleQuoteStringInComment (ifd, n, m) -> FSharpTokenizerColorState.TripleQuoteStringInComment, int64 n, m.Start, ifd + | LexCont.MLOnly (ifd, m) -> FSharpTokenizerColorState.CamlOnly, 0L, m.Start, ifd + | LexCont.VerbatimString (ifd, m) -> FSharpTokenizerColorState.VerbatimString, 0L, m.Start, ifd + | LexCont.TripleQuoteString (ifd, m) -> FSharpTokenizerColorState.TripleQuoteString, 0L, m.Start, ifd encodeLexCont tag n1 p1 ifd lightSyntaxStatus - - - let decodeLexInt (state: FSharpTokenizerLexState) = - let tag, n1, p1, ifd, lightSyntaxStatusInital = decodeLexCont state - let lexcont = - match tag with - | FSharpTokenizerColorState.Token -> LexCont.Token ifd - | FSharpTokenizerColorState.IfDefSkip -> LexCont.IfDefSkip (ifd, n1, mkRange "file" p1 p1) - | FSharpTokenizerColorState.String -> LexCont.String (ifd, mkRange "file" p1 p1) - | FSharpTokenizerColorState.Comment -> LexCont.Comment (ifd, n1, mkRange "file" p1 p1) - | FSharpTokenizerColorState.SingleLineComment -> LexCont.SingleLineComment (ifd, n1, mkRange "file" p1 p1) - | FSharpTokenizerColorState.StringInComment -> LexCont.StringInComment (ifd, n1, mkRange "file" p1 p1) - | FSharpTokenizerColorState.VerbatimStringInComment -> LexCont.VerbatimStringInComment (ifd, n1, mkRange "file" p1 p1) + + + let decodeLexInt (state: FSharpTokenizerLexState) = + let tag, n1, p1, ifd, lightSyntaxStatusInitial = decodeLexCont state + let lexcont = + match tag with + | FSharpTokenizerColorState.Token -> LexCont.Token ifd + | FSharpTokenizerColorState.IfDefSkip -> LexCont.IfDefSkip (ifd, n1, mkRange "file" p1 p1) + | FSharpTokenizerColorState.String -> LexCont.String (ifd, mkRange "file" p1 p1) + | FSharpTokenizerColorState.Comment -> LexCont.Comment (ifd, n1, mkRange "file" p1 p1) + | FSharpTokenizerColorState.SingleLineComment -> LexCont.SingleLineComment (ifd, n1, mkRange "file" p1 p1) + | FSharpTokenizerColorState.StringInComment -> LexCont.StringInComment (ifd, n1, mkRange "file" p1 p1) + | FSharpTokenizerColorState.VerbatimStringInComment -> LexCont.VerbatimStringInComment (ifd, n1, mkRange "file" p1 p1) | FSharpTokenizerColorState.TripleQuoteStringInComment -> LexCont.TripleQuoteStringInComment (ifd, n1, mkRange "file" p1 p1) - | FSharpTokenizerColorState.CamlOnly -> LexCont.MLOnly (ifd, mkRange "file" p1 p1) - | FSharpTokenizerColorState.VerbatimString -> LexCont.VerbatimString (ifd, mkRange "file" p1 p1) - | FSharpTokenizerColorState.TripleQuoteString -> LexCont.TripleQuoteString (ifd, mkRange "file" p1 p1) - | FSharpTokenizerColorState.EndLineThenSkip -> LexCont.EndLine(LexerEndlineContinuation.Skip(ifd, n1, mkRange "file" p1 p1)) - | FSharpTokenizerColorState.EndLineThenToken -> LexCont.EndLine(LexerEndlineContinuation.Token(ifd)) - | _ -> LexCont.Token [] - lightSyntaxStatusInital, lexcont - - let callLexCont lexcont args skip lexbuf = - let argsWithIfDefs ifd = - if !args.ifdefStack = ifd then + | FSharpTokenizerColorState.CamlOnly -> LexCont.MLOnly (ifd, mkRange "file" p1 p1) + | FSharpTokenizerColorState.VerbatimString -> LexCont.VerbatimString (ifd, mkRange "file" p1 p1) + | FSharpTokenizerColorState.TripleQuoteString -> LexCont.TripleQuoteString (ifd, mkRange "file" p1 p1) + | FSharpTokenizerColorState.EndLineThenSkip -> LexCont.EndLine(LexerEndlineContinuation.Skip(ifd, n1, mkRange "file" p1 p1)) + | FSharpTokenizerColorState.EndLineThenToken -> LexCont.EndLine(LexerEndlineContinuation.Token ifd) + | _ -> LexCont.Token [] + lightSyntaxStatusInitial, lexcont + + let callLexCont lexcont args skip lexbuf = + let argsWithIfDefs ifd = + if args.ifdefStack = ifd then args - else - {args with ifdefStack = ref ifd} - match lexcont with - | LexCont.EndLine cont -> Lexer.endline cont args skip lexbuf - | LexCont.Token ifd -> Lexer.token (argsWithIfDefs ifd) skip lexbuf - | LexCont.IfDefSkip (ifd, n, m) -> Lexer.ifdefSkip n m (argsWithIfDefs ifd) skip lexbuf - // Q: What's this magic 100 number for? Q: it's just an initial buffer size. - | LexCont.String (ifd, m) -> Lexer.string (ByteBuffer.Create 100, defaultStringFinisher, m, (argsWithIfDefs ifd)) skip lexbuf - | LexCont.Comment (ifd, n, m) -> Lexer.comment (n, m, (argsWithIfDefs ifd)) skip lexbuf + else + {args with ifdefStack = ifd} + match lexcont with + | LexCont.EndLine cont -> Lexer.endline cont args skip lexbuf + | LexCont.Token ifd -> Lexer.token (argsWithIfDefs ifd) skip lexbuf + | LexCont.IfDefSkip (ifd, n, m) -> Lexer.ifdefSkip n m (argsWithIfDefs ifd) skip lexbuf + // Q: What's this magic 100 number for? Q: it's just an initial buffer size. + | LexCont.String (ifd, m) -> Lexer.string (ByteBuffer.Create 100, defaultStringFinisher, m, (argsWithIfDefs ifd)) skip lexbuf + | LexCont.Comment (ifd, n, m) -> Lexer.comment (n, m, (argsWithIfDefs ifd)) skip lexbuf // The first argument is 'None' because we don't need XML comments when called from VS - | LexCont.SingleLineComment (ifd, n, m) -> Lexer.singleLineComment (None, n, m, (argsWithIfDefs ifd)) skip lexbuf - | LexCont.StringInComment (ifd, n, m) -> Lexer.stringInComment n m (argsWithIfDefs ifd) skip lexbuf - | LexCont.VerbatimStringInComment (ifd, n, m) -> Lexer.verbatimStringInComment n m (argsWithIfDefs ifd) skip lexbuf + | LexCont.SingleLineComment (ifd, n, m) -> Lexer.singleLineComment (None, n, m, (argsWithIfDefs ifd)) skip lexbuf + | LexCont.StringInComment (ifd, n, m) -> Lexer.stringInComment n m (argsWithIfDefs ifd) skip lexbuf + | LexCont.VerbatimStringInComment (ifd, n, m) -> Lexer.verbatimStringInComment n m (argsWithIfDefs ifd) skip lexbuf | LexCont.TripleQuoteStringInComment (ifd, n, m) -> Lexer.tripleQuoteStringInComment n m (argsWithIfDefs ifd) skip lexbuf - | LexCont.MLOnly (ifd, m) -> Lexer.mlOnly m (argsWithIfDefs ifd) skip lexbuf - | LexCont.VerbatimString (ifd, m) -> Lexer.verbatimString (ByteBuffer.Create 100, defaultStringFinisher, m, (argsWithIfDefs ifd)) skip lexbuf - | LexCont.TripleQuoteString (ifd, m) -> Lexer.tripleQuoteString (ByteBuffer.Create 100, defaultStringFinisher, m, (argsWithIfDefs ifd)) skip lexbuf + | LexCont.MLOnly (ifd, m) -> Lexer.mlOnly m (argsWithIfDefs ifd) skip lexbuf + | LexCont.VerbatimString (ifd, m) -> Lexer.verbatimString (ByteBuffer.Create 100, defaultStringFinisher, m, (argsWithIfDefs ifd)) skip lexbuf + | LexCont.TripleQuoteString (ifd, m) -> Lexer.tripleQuoteString (ByteBuffer.Create 100, defaultStringFinisher, m, (argsWithIfDefs ifd)) skip lexbuf //---------------------------------------------------------------------------- // Colorization //---------------------------------------------------------------------------- // Information beyond just tokens that can be derived by looking at just a single line. -// For example metacommands like #load. +// For example meta commands like #load. type SingleLineTokenState = | BeforeHash = 0 | NoFurtherMatchPossible = 1 - + /// Split a line into tokens and attach information about the tokens. This information is used by Visual Studio. [] type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, - maxLength: int option, - filename : Option, - lexArgsLightOn : lexargs, - lexArgsLightOff : lexargs - ) = - - let skip = false // don't skip whitespace in the lexer - + maxLength: int option, + filename: Option, + lexArgsLightOn: lexargs, + lexArgsLightOff: lexargs) = + + let skip = false // don't skip whitespace in the lexer + let mutable singleLineTokenState = SingleLineTokenState.BeforeHash let fsx = match filename with | None -> false - | Some(value) -> CompileOps.IsScript(value) + | Some value -> CompileOps.IsScript value // ---------------------------------------------------------------------------------- // This implements post-processing of #directive tokens - not very elegant, but it works... // We get the whole " #if IDENT // .. .. " thing as a single token from the lexer, // so we need to split it into tokens that are used by VS for colorization - - // Stack for tokens that are split during postprocessing + + // Stack for tokens that are split during postprocessing #if FABLE_COMPILER let tokenStack = Internal.Utilities.Text.Parsing.Stack<_>(31) #else let mutable tokenStack = new Stack<_>() #endif - let delayToken tok = tokenStack.Push(tok) + let delayToken tok = tokenStack.Push tok // Process: anywhite* # let processDirective (str: string) directiveLength delay cont = @@ -537,15 +548,15 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, if (hashIdx <> 0) then delay(WHITESPACE cont, 0, hashIdx - 1) delay(HASH_IF(range0, "", cont), hashIdx, hashIdx + directiveLength) hashIdx + directiveLength + 1 - + // Process: anywhite* ("//" [^'\n''\r']*)? - let processWhiteAndComment (str: string) offset delay cont = + let processWhiteAndComment (str: string) offset delay cont = let rest = str.Substring(offset, str.Length - offset) let comment = rest.IndexOf('/') let spaceLength = if comment = -1 then rest.Length else comment if (spaceLength > 0) then delay(WHITESPACE cont, offset, offset + spaceLength - 1) - if (comment <> -1) then delay(COMMENT(cont), offset + comment, offset + rest.Length - 1) - + if (comment <> -1) then delay(COMMENT cont, offset + comment, offset + rest.Length - 1) + // Split a directive line from lexer into tokens usable in VS let processDirectiveLine ofs f = let delayed = new ResizeArray<_>() @@ -553,91 +564,91 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, // delay all the tokens and return the remaining one for i = delayed.Count - 1 downto 1 do delayToken delayed.[i] delayed.[0] - + // Split the following line: // anywhite* ("#else"|"#endif") anywhite* ("//" [^'\n''\r']*)? - let processHashEndElse ofs (str: string) length cont = + let processHashEndElse ofs (str: string) length cont = processDirectiveLine ofs (fun delay -> // Process: anywhite* "#else" / anywhite* "#endif" let offset = processDirective str length delay cont // Process: anywhite* ("//" [^'\n''\r']*)? - processWhiteAndComment str offset delay cont ) - + processWhiteAndComment str offset delay cont ) + // Split the following line: // anywhite* "#if" anywhite+ ident anywhite* ("//" [^'\n''\r']*)? let processHashIfLine ofs (str: string) cont = let With n m = if (n < 0) then m else n processDirectiveLine ofs (fun delay -> // Process: anywhite* "#if" - let offset = processDirective str 2 delay cont + let offset = processDirective str 2 delay cont // Process: anywhite+ ident - let rest, spaces = - let w = str.Substring(offset) + let rest, spaces = + let w = str.Substring offset let r = w.TrimStart [| ' '; '\t' |] - r, w.Length - r.Length - let beforeIdent = offset + spaces - let identLength = With (rest.IndexOfAny([| '/'; '\t'; ' ' |])) rest.Length - delay(WHITESPACE cont, offset, beforeIdent - 1) - delay(IDENT(rest.Substring(0, identLength)), beforeIdent, beforeIdent + identLength - 1) + r, w.Length - r.Length + let beforeIdent = offset + spaces + let identLength = With (rest.IndexOfAny([| '/'; '\t'; ' ' |])) rest.Length + delay(WHITESPACE cont, offset, beforeIdent - 1) + delay(IDENT(rest.Substring(0, identLength)), beforeIdent, beforeIdent + identLength - 1) // Process: anywhite* ("//" [^'\n''\r']*)? let offset = beforeIdent + identLength processWhiteAndComment str offset delay cont ) - + // ---------------------------------------------------------------------------------- - - do match filename with + + do match filename with | None -> lexbuf.EndPos <- Internal.Utilities.Text.Lexing.Position.Empty - | Some(value) -> resetLexbufPos value lexbuf - - member x.ScanToken(lexintInitial) : FSharpTokenInfo option * FSharpTokenizerLexState = + | Some value -> resetLexbufPos value lexbuf + + member x.ScanToken lexintInitial: FSharpTokenInfo option * FSharpTokenizerLexState = use unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse use unwindEL = PushErrorLoggerPhaseUntilUnwind (fun _ -> DiscardErrorsLogger) - let lightSyntaxStatusInital, lexcontInitial = LexerStateEncoding.decodeLexInt lexintInitial - let lightSyntaxStatus = LightSyntaxStatus(lightSyntaxStatusInital, false) + let lightSyntaxStatusInitial, lexcontInitial = LexerStateEncoding.decodeLexInt lexintInitial + let lightSyntaxStatus = LightSyntaxStatus(lightSyntaxStatusInitial, false) // Build the arguments to the lexer function - let lexargs = if lightSyntaxStatusInital then lexArgsLightOn else lexArgsLightOff + let lexargs = if lightSyntaxStatusInitial then lexArgsLightOn else lexArgsLightOff - let GetTokenWithPosition(lexcontInitial) = + let GetTokenWithPosition lexcontInitial = // Column of token - let ColumnsOfCurrentToken() = - let leftp = lexbuf.StartPos - let rightp = lexbuf.EndPos - let leftc = leftp.Column - let rightc = - match maxLength with + let ColumnsOfCurrentToken() = + let leftp = lexbuf.StartPos + let rightp = lexbuf.EndPos + let leftc = leftp.Column + let rightc = + match maxLength with | Some mx when rightp.Line > leftp.Line -> mx - | _ -> rightp.Column - let rightc = rightc - 1 + | _ -> rightp.Column + let rightc = rightc - 1 leftc, rightc - // Get the token & position - either from a stack or from the lexer - try + // Get the token & position - either from a stack or from the lexer + try if (tokenStack.Count > 0) then true, tokenStack.Pop() - else - // Choose which lexer entrypoint to call and call it - let token = LexerStateEncoding.callLexCont lexcontInitial lexargs skip lexbuf + else + // Choose which lexer entry point to call and call it + let token = LexerStateEncoding.callLexCont lexcontInitial lexargs skip lexbuf let leftc, rightc = ColumnsOfCurrentToken() - + // Splits tokens like ">." into multiple tokens - this duplicates behavior from the 'lexfilter' // which cannot be (easily) used from the language service. The rules here are not always valid, - // because sometimes token shouldn't be split. However it is just for colorization & + // because sometimes token shouldn't be split. However it is just for colorization & // for VS (which needs to recognize when user types "."). match token with - | HASH_IF(m, lineStr, cont) when lineStr <> "" -> + | HASH_IF (m, lineStr, cont) when lineStr <> "" -> false, processHashIfLine m.StartColumn lineStr cont - | HASH_ELSE(m, lineStr, cont) when lineStr <> "" -> - false, processHashEndElse m.StartColumn lineStr 4 cont - | HASH_ENDIF(m, lineStr, cont) when lineStr <> "" -> + | HASH_ELSE (m, lineStr, cont) when lineStr <> "" -> + false, processHashEndElse m.StartColumn lineStr 4 cont + | HASH_ENDIF (m, lineStr, cont) when lineStr <> "" -> false, processHashEndElse m.StartColumn lineStr 5 cont - | RQUOTE_DOT (s, raw) -> + | RQUOTE_DOT (s, raw) -> delayToken(DOT, rightc, rightc) false, (RQUOTE (s, raw), leftc, rightc - 1) - | INFIX_COMPARE_OP (LexFilter.TyparsCloseOp(greaters, afterOp) as opstr) -> + | INFIX_COMPARE_OP (LexFilter.TyparsCloseOp(greaters, afterOp) as opstr) -> match afterOp with | None -> () | Some tok -> delayToken(tok, leftc + greaters.Length, rightc) @@ -646,58 +657,58 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, false, (greaters.[0] false, leftc, rightc - opstr.Length + 1) // break up any operators that start with '.' so that we can get auto-popup-completion for e.g. "x.+1" when typing the dot | INFIX_STAR_STAR_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(INFIX_STAR_STAR_OP(opstr.Substring(1)), leftc+1, rightc) + delayToken(INFIX_STAR_STAR_OP(opstr.Substring 1), leftc+1, rightc) false, (DOT, leftc, leftc) | PLUS_MINUS_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(PLUS_MINUS_OP(opstr.Substring(1)), leftc+1, rightc) + delayToken(PLUS_MINUS_OP(opstr.Substring 1), leftc+1, rightc) false, (DOT, leftc, leftc) | INFIX_COMPARE_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(INFIX_COMPARE_OP(opstr.Substring(1)), leftc+1, rightc) + delayToken(INFIX_COMPARE_OP(opstr.Substring 1), leftc+1, rightc) false, (DOT, leftc, leftc) | INFIX_AT_HAT_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(INFIX_AT_HAT_OP(opstr.Substring(1)), leftc+1, rightc) + delayToken(INFIX_AT_HAT_OP(opstr.Substring 1), leftc+1, rightc) false, (DOT, leftc, leftc) | INFIX_BAR_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(INFIX_BAR_OP(opstr.Substring(1)), leftc+1, rightc) + delayToken(INFIX_BAR_OP(opstr.Substring 1), leftc+1, rightc) false, (DOT, leftc, leftc) | PREFIX_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(PREFIX_OP(opstr.Substring(1)), leftc+1, rightc) + delayToken(PREFIX_OP(opstr.Substring 1), leftc+1, rightc) false, (DOT, leftc, leftc) | INFIX_STAR_DIV_MOD_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(INFIX_STAR_DIV_MOD_OP(opstr.Substring(1)), leftc+1, rightc) + delayToken(INFIX_STAR_DIV_MOD_OP(opstr.Substring 1), leftc+1, rightc) false, (DOT, leftc, leftc) | INFIX_AMP_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(INFIX_AMP_OP(opstr.Substring(1)), leftc+1, rightc) + delayToken(INFIX_AMP_OP(opstr.Substring 1), leftc+1, rightc) false, (DOT, leftc, leftc) | ADJACENT_PREFIX_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(ADJACENT_PREFIX_OP(opstr.Substring(1)), leftc+1, rightc) + delayToken(ADJACENT_PREFIX_OP(opstr.Substring 1), leftc+1, rightc) false, (DOT, leftc, leftc) | FUNKY_OPERATOR_NAME opstr when opstr.StartsWithOrdinal(".") -> - delayToken(FUNKY_OPERATOR_NAME(opstr.Substring(1)), leftc+1, rightc) + delayToken(FUNKY_OPERATOR_NAME(opstr.Substring 1), leftc+1, rightc) false, (DOT, leftc, leftc) | _ -> false, (token, leftc, rightc) with - | e -> false, (EOF LexerStateEncoding.revertToDefaultLexCont, 0, 0) // REVIEW: report lex failure here - + | e -> false, (EOF LexerStateEncoding.revertToDefaultLexCont, 0, 0) // REVIEW: report lex failure here + // Grab a token - let isCached, (token, leftc, rightc) = GetTokenWithPosition(lexcontInitial) - + let isCached, (token, leftc, rightc) = GetTokenWithPosition lexcontInitial + // Check for end-of-string and failure - let tokenDataOption, lexcontFinal, tokenTag = - match token with - | EOF lexcont -> + let tokenDataOption, lexcontFinal, tokenTag = + match token with + | EOF lexcont -> // End of text! No more tokens. - None, lexcont, 0 - | LEX_FAILURE _ -> + None, lexcont, 0 + | LEX_FAILURE _ -> None, LexerStateEncoding.revertToDefaultLexCont, 0 | _ -> // Get the information about the token - let (colorClass, charClass, triggerClass) = TokenClassifications.tokenInfo token - let lexcontFinal = + let (colorClass, charClass, triggerClass) = TokenClassifications.tokenInfo token + let lexcontFinal = // If we're using token from cache, we don't move forward with lexing - if isCached then lexcontInitial else LexerStateEncoding.computeNextLexState token lexcontInitial - let tokenTag = tagOfToken token - let fullMatchedLength = lexbuf.EndPos.AbsoluteOffset - lexbuf.StartPos.AbsoluteOffset + if isCached then lexcontInitial else LexerStateEncoding.computeNextLexState token lexcontInitial + let tokenTag = tagOfToken token + let fullMatchedLength = lexbuf.EndPos.AbsoluteOffset - lexbuf.StartPos.AbsoluteOffset let tokenData = { TokenName = token_to_string token LeftColumn=leftc @@ -706,87 +717,727 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, CharClass=charClass FSharpTokenTriggerClass=triggerClass Tag=tokenTag - FullMatchedLength=fullMatchedLength} - Some(tokenData), lexcontFinal, tokenTag - - // Get the final lex int and color state - let FinalState(lexcontFinal) = - LexerStateEncoding.encodeLexInt lightSyntaxStatus.Status lexcontFinal - + FullMatchedLength=fullMatchedLength} + Some tokenData, lexcontFinal, tokenTag + + // Get the final lex int and color state + let FinalState lexcontFinal = + LexerStateEncoding.encodeLexInt lightSyntaxStatus.Status lexcontFinal + // Check for patterns like #-IDENT and see if they look like meta commands for .fsx files. If they do then merge them into a single token. - let tokenDataOption, lexintFinal = - let lexintFinal = FinalState(lexcontFinal) - match tokenDataOption, singleLineTokenState, tokenTagToTokenId tokenTag with - | Some(tokenData), SingleLineTokenState.BeforeHash, TOKEN_HASH -> + let tokenDataOption, lexintFinal = + let lexintFinal = FinalState lexcontFinal + match tokenDataOption, singleLineTokenState, tokenTagToTokenId tokenTag with + | Some tokenData, SingleLineTokenState.BeforeHash, TOKEN_HASH -> // Don't allow further matches. singleLineTokenState <- SingleLineTokenState.NoFurtherMatchPossible // Peek at the next token - let isCached, (nextToken, _, rightc) = GetTokenWithPosition(lexcontInitial) - match nextToken with - | IDENT possibleMetacommand -> - match fsx, possibleMetacommand with + let isCached, (nextToken, _, rightc) = GetTokenWithPosition lexcontInitial + match nextToken with + | IDENT possibleMetaCommand -> + match fsx, possibleMetaCommand with // These are for script (.fsx and .fsscript) files. - | true, "r" - | true, "reference" - | true, "I" - | true, "load" - | true, "time" - | true, "dbgbreak" - | true, "cd" + | true, "r" + | true, "reference" + | true, "I" + | true, "load" + | true, "time" + | true, "dbgbreak" + | true, "cd" #if DEBUG - | true, "terms" - | true, "types" - | true, "savedll" - | true, "nosavedll" + | true, "terms" + | true, "types" + | true, "savedll" + | true, "nosavedll" #endif - | true, "silentCd" - | true, "q" - | true, "quit" - | true, "help" + | true, "silentCd" + | true, "q" + | true, "quit" + | true, "help" // These are for script and non-script - | _, "nowarn" -> + | _, "nowarn" -> // Merge both tokens into one. - let lexcontFinal = if (isCached) then lexcontInitial else LexerStateEncoding.computeNextLexState token lexcontInitial - let tokenData = {tokenData with RightColumn=rightc;ColorClass=FSharpTokenColorKind.PreprocessorKeyword;CharClass=FSharpTokenCharKind.Keyword;FSharpTokenTriggerClass=FSharpTokenTriggerClass.None} - let lexintFinal = FinalState(lexcontFinal) - Some(tokenData), lexintFinal + let lexcontFinal = if isCached then lexcontInitial else LexerStateEncoding.computeNextLexState token lexcontInitial + let tokenData = {tokenData with RightColumn=rightc;ColorClass=FSharpTokenColorKind.PreprocessorKeyword;CharClass=FSharpTokenCharKind.Keyword;FSharpTokenTriggerClass=FSharpTokenTriggerClass.None} + let lexintFinal = FinalState lexcontFinal + Some tokenData, lexintFinal | _ -> tokenDataOption, lexintFinal | _ -> tokenDataOption, lexintFinal - | _, SingleLineTokenState.BeforeHash, TOKEN_WHITESPACE -> + | _, SingleLineTokenState.BeforeHash, TOKEN_WHITESPACE -> // Allow leading whitespace. tokenDataOption, lexintFinal - | _ -> + | _ -> singleLineTokenState <- SingleLineTokenState.NoFurtherMatchPossible tokenDataOption, lexintFinal - + tokenDataOption, lexintFinal - static member ColorStateOfLexState(lexState: FSharpTokenizerLexState) = + static member ColorStateOfLexState(lexState: FSharpTokenizerLexState) = LexerStateEncoding.colorStateOfLexState lexState - static member LexStateOfColorState(colorState: FSharpTokenizerColorState) = + static member LexStateOfColorState(colorState: FSharpTokenizerColorState) = { PosBits = 0L; OtherBits = LexerStateEncoding.lexStateOfColorState colorState } [] -type FSharpSourceTokenizer(defineConstants : string list, filename : string option) = - let lexResourceManager = new Lexhelp.LexResourceManager() - - let lexArgsLightOn = mkLexargs(filename, defineConstants, LightSyntaxStatus(true, false), lexResourceManager, ref [], DiscardErrorsLogger) - let lexArgsLightOff = mkLexargs(filename, defineConstants, LightSyntaxStatus(false, false), lexResourceManager, ref [], DiscardErrorsLogger) - - member this.CreateLineTokenizer(lineText: string) = - let lexbuf = UnicodeLexing.StringAsLexbuf lineText +type FSharpSourceTokenizer(defineConstants: string list, filename: string option) = + + // Public callers are unable to answer LanguageVersion feature support questions. + // External Tools including the VS IDE will enable the default LanguageVersion + let isFeatureSupported (_featureId:LanguageFeature) = true + + let lexResourceManager = new Lexhelp.LexResourceManager() + + let lexArgsLightOn = mkLexargs(filename, defineConstants, LightSyntaxStatus(true, false), lexResourceManager, [], DiscardErrorsLogger, PathMap.empty) + let lexArgsLightOff = mkLexargs(filename, defineConstants, LightSyntaxStatus(false, false), lexResourceManager, [], DiscardErrorsLogger, PathMap.empty) + + member this.CreateLineTokenizer(lineText: string) = + let lexbuf = UnicodeLexing.StringAsLexbuf(isFeatureSupported, lineText) FSharpLineTokenizer(lexbuf, Some lineText.Length, filename, lexArgsLightOn, lexArgsLightOff) - - member this.CreateBufferTokenizer(bufferFiller) = - let lexbuf = UnicodeLexing.FunctionAsLexbuf bufferFiller + member this.CreateBufferTokenizer bufferFiller = + let lexbuf = UnicodeLexing.FunctionAsLexbuf(isFeatureSupported, bufferFiller) FSharpLineTokenizer(lexbuf, None, filename, lexArgsLightOn, lexArgsLightOff) module Keywords = open FSharp.Compiler.Lexhelp.Keywords + let DoesIdentifierNeedQuotation s = DoesIdentifierNeedQuotation s let QuoteIdentifierIfNeeded s = QuoteIdentifierIfNeeded s let NormalizeIdentifierBackticks s = NormalizeIdentifierBackticks s let KeywordsWithDescription = keywordsWithDescription +module Lexer = + + open System.Threading + open FSharp.Compiler.Features + open FSharp.Compiler.Lexhelp + open FSharp.Compiler.Parser + open FSharp.Compiler.Range + open FSharp.Compiler.SyntaxTree + open FSharp.Compiler.Text + open FSharp.Compiler.UnicodeLexing + open Internal.Utilities + + [] + type FSharpLexerFlags = + | Default = 0x11011 + | LightSyntaxOn = 0x00001 + | Compiling = 0x00010 + | CompilingFSharpCore = 0x00110 + | SkipTrivia = 0x01000 + | UseLexFilter = 0x10000 + + [] + type FSharpSyntaxTokenKind = + | None + | HashIf + | HashElse + | HashEndIf + | CommentTrivia + | WhitespaceTrivia + | HashLine + | HashLight + | InactiveCode + | LineCommentTrivia + | StringText + | Fixed + | OffsideInterfaceMember + | OffsideBlockEnd + | OffsideRightBlockEnd + | OffsideDeclEnd + | OffsideEnd + | OffsideBlockSep + | OffsideBlockBegin + | OffsideReset + | OffsideFun + | OffsideFunction + | OffsideWith + | OffsideElse + | OffsideThen + | OffsideDoBang + | OffsideDo + | OffsideBinder + | OffsideLet + | HighPrecedenceTypeApp + | HighPrecedenceParenthesisApp + | HighPrecedenceBracketApp + | Extern + | Void + | Public + | Private + | Internal + | Global + | Static + | Member + | Class + | Abstract + | Override + | Default + | Constructor + | Inherit + | GreaterRightBracket + | Struct + | Sig + | Bar + | RightBracket + | RightBrace + | Minus + | Dollar + | BarRightBracket + | BarRightBrace + | Underscore + | Semicolon + | SemicolonSemicolon + | LeftArrow + | Equals + | LeftBracket + | LeftBracketBar + | LeftBraceBar + | LeftBracketLess + | LeftBrace + | QuestionMark + | QuestionMarkQuestionMark + | Dot + | Colon + | ColonColon + | ColonGreater + | ColonQuestionMark + | ColonQuestionMarkGreater + | ColonEquals + | When + | While + | With + | Hash + | Ampersand + | AmpersandAmpersand + | Quote + | LeftParenthesis + | RightParenthesis + | Star + | Comma + | RightArrow + | GreaterBarRightBracket + | LeftParenthesisStarRightParenthesis + | Open + | Or + | Rec + | Then + | To + | True + | Try + | Type + | Val + | Inline + | Interface + | Instance + | Const + | Lazy + | OffsideLazy + | Match + | MatchBang + | Mutable + | New + | Of + | Exception + | False + | For + | Fun + | Function + | If + | In + | JoinIn + | Finally + | DoBang + | And + | As + | Assert + | OffsideAssert + | Begin + | Do + | Done + | DownTo + | Else + | Elif + | End + | DotDot + | DotDotHat + | BarBar + | Upcast + | Downcast + | Null + | Reserved + | Module + | Namespace + | Delegate + | Constraint + | Base + | LeftQuote + | RightQuote + | RightQuoteDot + | PercentOperator + | Binder + | Less + | Greater + | Let + | Yield + | YieldBang + | BigNumber + | Decimal + | Char + | Ieee64 + | Ieee32 + | NativeInt + | UNativeInt + | UInt64 + | UInt32 + | UInt16 + | UInt8 + | Int64 + | Int32 + | Int32DotDot + | Int16 + | Int8 + | FunkyOperatorName + | AdjacentPrefixOperator + | PlusMinusOperator + | InfixAmpersandOperator + | InfixStarDivideModuloOperator + | PrefixOperator + | InfixBarOperator + | InfixAtHatOperator + | InfixCompareOperator + | InfixStarStarOperator + | Identifier + | KeywordString + | String + | ByteArray + | Asr + | InfixAsr + | InfixLand + | InfixLor + | InfixLsl + | InfixLsr + | InfixLxor + | InfixMod + + [] + type FSharpSyntaxToken = + + val private tok: Parser.token + val private tokRange: range + + new (tok, tokRange) = { tok = tok; tokRange = tokRange } + + member this.Range = this.tokRange + + member this.Kind = + match this.tok with + | ASR -> FSharpSyntaxTokenKind.Asr + | INFIX_STAR_STAR_OP "asr" -> FSharpSyntaxTokenKind.Asr + | INFIX_STAR_DIV_MOD_OP "land" -> FSharpSyntaxTokenKind.InfixLand + | INFIX_STAR_DIV_MOD_OP "lor" -> FSharpSyntaxTokenKind.InfixLor + | INFIX_STAR_STAR_OP "lsl" -> FSharpSyntaxTokenKind.InfixLsl + | INFIX_STAR_STAR_OP "lsr" -> FSharpSyntaxTokenKind.InfixLsr + | INFIX_STAR_DIV_MOD_OP "lxor" -> FSharpSyntaxTokenKind.InfixLxor + | INFIX_STAR_DIV_MOD_OP "mod" -> FSharpSyntaxTokenKind.InfixMod + | HASH_IF _ -> FSharpSyntaxTokenKind.HashIf + | HASH_ELSE _ -> FSharpSyntaxTokenKind.HashElse + | HASH_ENDIF _ -> FSharpSyntaxTokenKind.HashEndIf + | COMMENT _ -> FSharpSyntaxTokenKind.CommentTrivia + | WHITESPACE _ -> FSharpSyntaxTokenKind.WhitespaceTrivia + | HASH_LINE _ -> FSharpSyntaxTokenKind.HashLine + | HASH_LIGHT _ -> FSharpSyntaxTokenKind.HashLight + | INACTIVECODE _ -> FSharpSyntaxTokenKind.InactiveCode + | LINE_COMMENT _ -> FSharpSyntaxTokenKind.LineCommentTrivia + | STRING_TEXT _ -> FSharpSyntaxTokenKind.StringText + | FIXED -> FSharpSyntaxTokenKind.Fixed + | OINTERFACE_MEMBER -> FSharpSyntaxTokenKind.OffsideInterfaceMember + | OBLOCKEND -> FSharpSyntaxTokenKind.OffsideBlockEnd + | ORIGHT_BLOCK_END -> FSharpSyntaxTokenKind.OffsideRightBlockEnd + | ODECLEND -> FSharpSyntaxTokenKind.OffsideDeclEnd + | OEND -> FSharpSyntaxTokenKind.OffsideEnd + | OBLOCKSEP -> FSharpSyntaxTokenKind.OffsideBlockSep + | OBLOCKBEGIN -> FSharpSyntaxTokenKind.OffsideBlockBegin + | ORESET -> FSharpSyntaxTokenKind.OffsideReset + | OFUN -> FSharpSyntaxTokenKind.OffsideFun + | OFUNCTION -> FSharpSyntaxTokenKind.OffsideFunction + | OWITH -> FSharpSyntaxTokenKind.OffsideWith + | OELSE -> FSharpSyntaxTokenKind.OffsideElse + | OTHEN -> FSharpSyntaxTokenKind.OffsideThen + | ODO_BANG -> FSharpSyntaxTokenKind.OffsideDoBang + | ODO -> FSharpSyntaxTokenKind.OffsideDo + | OBINDER _ -> FSharpSyntaxTokenKind.OffsideBinder + | OLET _ -> FSharpSyntaxTokenKind.OffsideLet + | HIGH_PRECEDENCE_TYAPP -> FSharpSyntaxTokenKind.HighPrecedenceTypeApp + | HIGH_PRECEDENCE_PAREN_APP -> FSharpSyntaxTokenKind.HighPrecedenceParenthesisApp + | HIGH_PRECEDENCE_BRACK_APP -> FSharpSyntaxTokenKind.HighPrecedenceBracketApp + | EXTERN -> FSharpSyntaxTokenKind.Extern + | VOID -> FSharpSyntaxTokenKind.Void + | PUBLIC -> FSharpSyntaxTokenKind.Public + | PRIVATE -> FSharpSyntaxTokenKind.Private + | INTERNAL -> FSharpSyntaxTokenKind.Internal + | GLOBAL -> FSharpSyntaxTokenKind.Global + | STATIC -> FSharpSyntaxTokenKind.Static + | MEMBER -> FSharpSyntaxTokenKind.Member + | CLASS -> FSharpSyntaxTokenKind.Class + | ABSTRACT -> FSharpSyntaxTokenKind.Abstract + | OVERRIDE -> FSharpSyntaxTokenKind.Override + | DEFAULT -> FSharpSyntaxTokenKind.Default + | CONSTRUCTOR -> FSharpSyntaxTokenKind.Constructor + | INHERIT -> FSharpSyntaxTokenKind.Inherit + | GREATER_RBRACK -> FSharpSyntaxTokenKind.GreaterRightBracket + | STRUCT -> FSharpSyntaxTokenKind.Struct + | SIG -> FSharpSyntaxTokenKind.Sig + | BAR -> FSharpSyntaxTokenKind.Bar + | RBRACK -> FSharpSyntaxTokenKind.RightBracket + | RBRACE -> FSharpSyntaxTokenKind.RightBrace + | MINUS -> FSharpSyntaxTokenKind.Minus + | DOLLAR -> FSharpSyntaxTokenKind.Dollar + | BAR_RBRACK -> FSharpSyntaxTokenKind.BarRightBracket + | BAR_RBRACE -> FSharpSyntaxTokenKind.BarRightBrace + | UNDERSCORE -> FSharpSyntaxTokenKind.Underscore + | SEMICOLON_SEMICOLON -> FSharpSyntaxTokenKind.SemicolonSemicolon + | LARROW -> FSharpSyntaxTokenKind.LeftArrow + | EQUALS -> FSharpSyntaxTokenKind.Equals + | LBRACK -> FSharpSyntaxTokenKind.LeftBracket + | LBRACK_BAR -> FSharpSyntaxTokenKind.LeftBracketBar + | LBRACE_BAR -> FSharpSyntaxTokenKind.LeftBraceBar + | LBRACK_LESS -> FSharpSyntaxTokenKind.LeftBracketLess + | LBRACE -> FSharpSyntaxTokenKind.LeftBrace + | QMARK -> FSharpSyntaxTokenKind.QuestionMark + | QMARK_QMARK -> FSharpSyntaxTokenKind.QuestionMarkQuestionMark + | DOT -> FSharpSyntaxTokenKind.Dot + | COLON -> FSharpSyntaxTokenKind.Colon + | COLON_COLON -> FSharpSyntaxTokenKind.ColonColon + | COLON_GREATER -> FSharpSyntaxTokenKind.ColonGreater + | COLON_QMARK_GREATER -> FSharpSyntaxTokenKind.ColonQuestionMarkGreater + | COLON_QMARK -> FSharpSyntaxTokenKind.ColonQuestionMark + | COLON_EQUALS -> FSharpSyntaxTokenKind.ColonEquals + | SEMICOLON -> FSharpSyntaxTokenKind.SemicolonSemicolon + | WHEN -> FSharpSyntaxTokenKind.When + | WHILE -> FSharpSyntaxTokenKind.While + | WITH -> FSharpSyntaxTokenKind.With + | HASH -> FSharpSyntaxTokenKind.Hash + | AMP -> FSharpSyntaxTokenKind.Ampersand + | AMP_AMP -> FSharpSyntaxTokenKind.AmpersandAmpersand + | QUOTE -> FSharpSyntaxTokenKind.RightQuote + | LPAREN -> FSharpSyntaxTokenKind.LeftParenthesis + | RPAREN -> FSharpSyntaxTokenKind.RightParenthesis + | STAR -> FSharpSyntaxTokenKind.Star + | COMMA -> FSharpSyntaxTokenKind.Comma + | RARROW -> FSharpSyntaxTokenKind.RightArrow + | GREATER_BAR_RBRACK -> FSharpSyntaxTokenKind.GreaterBarRightBracket + | LPAREN_STAR_RPAREN -> FSharpSyntaxTokenKind.LeftParenthesisStarRightParenthesis + | OPEN -> FSharpSyntaxTokenKind.Open + | OR -> FSharpSyntaxTokenKind.Or + | REC -> FSharpSyntaxTokenKind.Rec + | THEN -> FSharpSyntaxTokenKind.Then + | TO -> FSharpSyntaxTokenKind.To + | TRUE -> FSharpSyntaxTokenKind.True + | TRY -> FSharpSyntaxTokenKind.Try + | TYPE -> FSharpSyntaxTokenKind.Type + | VAL -> FSharpSyntaxTokenKind.Val + | INLINE -> FSharpSyntaxTokenKind.Inline + | INTERFACE -> FSharpSyntaxTokenKind.Interface + | INSTANCE -> FSharpSyntaxTokenKind.Instance + | CONST -> FSharpSyntaxTokenKind.Const + | LAZY -> FSharpSyntaxTokenKind.Lazy + | OLAZY -> FSharpSyntaxTokenKind.OffsideLazy + | MATCH -> FSharpSyntaxTokenKind.Match + | MATCH_BANG -> FSharpSyntaxTokenKind.MatchBang + | MUTABLE -> FSharpSyntaxTokenKind.Mutable + | NEW -> FSharpSyntaxTokenKind.New + | OF -> FSharpSyntaxTokenKind.Of + | EXCEPTION -> FSharpSyntaxTokenKind.Exception + | FALSE -> FSharpSyntaxTokenKind.False + | FOR -> FSharpSyntaxTokenKind.For + | FUN -> FSharpSyntaxTokenKind.Fun + | FUNCTION -> FSharpSyntaxTokenKind.Function + | IF -> FSharpSyntaxTokenKind.If + | IN -> FSharpSyntaxTokenKind.In + | JOIN_IN -> FSharpSyntaxTokenKind.JoinIn + | FINALLY -> FSharpSyntaxTokenKind.Finally + | DO_BANG -> FSharpSyntaxTokenKind.DoBang + | AND -> FSharpSyntaxTokenKind.And + | AS -> FSharpSyntaxTokenKind.As + | ASSERT -> FSharpSyntaxTokenKind.Assert + | OASSERT -> FSharpSyntaxTokenKind.OffsideAssert + | BEGIN -> FSharpSyntaxTokenKind.Begin + | DO -> FSharpSyntaxTokenKind.Do + | DONE -> FSharpSyntaxTokenKind.Done + | DOWNTO -> FSharpSyntaxTokenKind.DownTo + | ELSE -> FSharpSyntaxTokenKind.Else + | ELIF -> FSharpSyntaxTokenKind.Elif + | END -> FSharpSyntaxTokenKind.End + | DOT_DOT -> FSharpSyntaxTokenKind.DotDot + | DOT_DOT_HAT -> FSharpSyntaxTokenKind.DotDotHat + | BAR_BAR -> FSharpSyntaxTokenKind.BarBar + | UPCAST -> FSharpSyntaxTokenKind.Upcast + | DOWNCAST -> FSharpSyntaxTokenKind.Downcast + | NULL -> FSharpSyntaxTokenKind.Null + | RESERVED -> FSharpSyntaxTokenKind.Reserved + | MODULE -> FSharpSyntaxTokenKind.Module + | NAMESPACE -> FSharpSyntaxTokenKind.Namespace + | DELEGATE -> FSharpSyntaxTokenKind.Delegate + | CONSTRAINT -> FSharpSyntaxTokenKind.Constraint + | BASE -> FSharpSyntaxTokenKind.Base + | LQUOTE _ -> FSharpSyntaxTokenKind.LeftQuote + | RQUOTE _ -> FSharpSyntaxTokenKind.RightQuote + | RQUOTE_DOT _ -> FSharpSyntaxTokenKind.RightQuoteDot + | PERCENT_OP _ -> FSharpSyntaxTokenKind.PercentOperator + | BINDER _ -> FSharpSyntaxTokenKind.Binder + | LESS _ -> FSharpSyntaxTokenKind.Less + | GREATER _ -> FSharpSyntaxTokenKind.Greater + | LET _ -> FSharpSyntaxTokenKind.Let + | YIELD _ -> FSharpSyntaxTokenKind.Yield + | YIELD_BANG _ -> FSharpSyntaxTokenKind.YieldBang + | BIGNUM _ -> FSharpSyntaxTokenKind.BigNumber + | DECIMAL _ -> FSharpSyntaxTokenKind.Decimal + | CHAR _ -> FSharpSyntaxTokenKind.Char + | IEEE64 _ -> FSharpSyntaxTokenKind.Ieee64 + | IEEE32 _ -> FSharpSyntaxTokenKind.Ieee32 + | NATIVEINT _ -> FSharpSyntaxTokenKind.NativeInt + | UNATIVEINT _ -> FSharpSyntaxTokenKind.UNativeInt + | UINT64 _ -> FSharpSyntaxTokenKind.UInt64 + | UINT32 _ -> FSharpSyntaxTokenKind.UInt32 + | UINT16 _ -> FSharpSyntaxTokenKind.UInt16 + | UINT8 _ -> FSharpSyntaxTokenKind.UInt8 + | INT64 _ -> FSharpSyntaxTokenKind.UInt64 + | INT32 _ -> FSharpSyntaxTokenKind.Int32 + | INT32_DOT_DOT _ -> FSharpSyntaxTokenKind.Int32DotDot + | INT16 _ -> FSharpSyntaxTokenKind.Int16 + | INT8 _ -> FSharpSyntaxTokenKind.Int8 + | FUNKY_OPERATOR_NAME _ -> FSharpSyntaxTokenKind.FunkyOperatorName + | ADJACENT_PREFIX_OP _ -> FSharpSyntaxTokenKind.AdjacentPrefixOperator + | PLUS_MINUS_OP _ -> FSharpSyntaxTokenKind.PlusMinusOperator + | INFIX_AMP_OP _ -> FSharpSyntaxTokenKind.InfixAmpersandOperator + | INFIX_STAR_DIV_MOD_OP _ -> FSharpSyntaxTokenKind.InfixStarDivideModuloOperator + | PREFIX_OP _ -> FSharpSyntaxTokenKind.PrefixOperator + | INFIX_BAR_OP _ -> FSharpSyntaxTokenKind.InfixBarOperator + | INFIX_AT_HAT_OP _ -> FSharpSyntaxTokenKind.InfixAtHatOperator + | INFIX_COMPARE_OP _ -> FSharpSyntaxTokenKind.InfixCompareOperator + | INFIX_STAR_STAR_OP _ -> FSharpSyntaxTokenKind.InfixStarStarOperator + | IDENT _ -> FSharpSyntaxTokenKind.Identifier + | KEYWORD_STRING _ -> FSharpSyntaxTokenKind.KeywordString + | STRING _ -> FSharpSyntaxTokenKind.String + | BYTEARRAY _ -> FSharpSyntaxTokenKind.ByteArray + | _ -> FSharpSyntaxTokenKind.None + + member this.IsKeyword = + match this.Kind with + | FSharpSyntaxTokenKind.Abstract + | FSharpSyntaxTokenKind.And + | FSharpSyntaxTokenKind.As + | FSharpSyntaxTokenKind.Assert + | FSharpSyntaxTokenKind.OffsideAssert + | FSharpSyntaxTokenKind.Base + | FSharpSyntaxTokenKind.Begin + | FSharpSyntaxTokenKind.Class + | FSharpSyntaxTokenKind.Default + | FSharpSyntaxTokenKind.Delegate + | FSharpSyntaxTokenKind.Do + | FSharpSyntaxTokenKind.OffsideDo + | FSharpSyntaxTokenKind.Done + | FSharpSyntaxTokenKind.Downcast + | FSharpSyntaxTokenKind.DownTo + | FSharpSyntaxTokenKind.Elif + | FSharpSyntaxTokenKind.Else + | FSharpSyntaxTokenKind.OffsideElse + | FSharpSyntaxTokenKind.End + | FSharpSyntaxTokenKind.OffsideEnd + | FSharpSyntaxTokenKind.Exception + | FSharpSyntaxTokenKind.Extern + | FSharpSyntaxTokenKind.False + | FSharpSyntaxTokenKind.Finally + | FSharpSyntaxTokenKind.Fixed + | FSharpSyntaxTokenKind.For + | FSharpSyntaxTokenKind.Fun + | FSharpSyntaxTokenKind.OffsideFun + | FSharpSyntaxTokenKind.Function + | FSharpSyntaxTokenKind.OffsideFunction + | FSharpSyntaxTokenKind.Global + | FSharpSyntaxTokenKind.If + | FSharpSyntaxTokenKind.In + | FSharpSyntaxTokenKind.Inherit + | FSharpSyntaxTokenKind.Inline + | FSharpSyntaxTokenKind.Interface + | FSharpSyntaxTokenKind.OffsideInterfaceMember + | FSharpSyntaxTokenKind.Internal + | FSharpSyntaxTokenKind.Lazy + | FSharpSyntaxTokenKind.OffsideLazy + | FSharpSyntaxTokenKind.Let // "let" and "use" + | FSharpSyntaxTokenKind.OffsideLet + | FSharpSyntaxTokenKind.DoBang // "let!", "use!" and "do!" + | FSharpSyntaxTokenKind.OffsideDoBang + | FSharpSyntaxTokenKind.Match + | FSharpSyntaxTokenKind.MatchBang + | FSharpSyntaxTokenKind.Member + | FSharpSyntaxTokenKind.Module + | FSharpSyntaxTokenKind.Mutable + | FSharpSyntaxTokenKind.Namespace + | FSharpSyntaxTokenKind.New + // | FSharpSyntaxTokenKind.Not // Not actually a keyword. However, not struct in combination is used as a generic parameter constraint. + | FSharpSyntaxTokenKind.Null + | FSharpSyntaxTokenKind.Of + | FSharpSyntaxTokenKind.Open + | FSharpSyntaxTokenKind.Or + | FSharpSyntaxTokenKind.Override + | FSharpSyntaxTokenKind.Private + | FSharpSyntaxTokenKind.Public + | FSharpSyntaxTokenKind.Rec + | FSharpSyntaxTokenKind.Yield // "yield" and "return" + | FSharpSyntaxTokenKind.YieldBang // "yield!" and "return!" + | FSharpSyntaxTokenKind.Static + | FSharpSyntaxTokenKind.Struct + | FSharpSyntaxTokenKind.Then + | FSharpSyntaxTokenKind.To + | FSharpSyntaxTokenKind.True + | FSharpSyntaxTokenKind.Try + | FSharpSyntaxTokenKind.Type + | FSharpSyntaxTokenKind.Upcast + | FSharpSyntaxTokenKind.Val + | FSharpSyntaxTokenKind.Void + | FSharpSyntaxTokenKind.When + | FSharpSyntaxTokenKind.While + | FSharpSyntaxTokenKind.With + | FSharpSyntaxTokenKind.OffsideWith + + // * Reserved - from OCAML * + | FSharpSyntaxTokenKind.Asr + | FSharpSyntaxTokenKind.InfixAsr + | FSharpSyntaxTokenKind.InfixLand + | FSharpSyntaxTokenKind.InfixLor + | FSharpSyntaxTokenKind.InfixLsl + | FSharpSyntaxTokenKind.InfixLsr + | FSharpSyntaxTokenKind.InfixLxor + | FSharpSyntaxTokenKind.InfixMod + | FSharpSyntaxTokenKind.Sig + + // * Reserved - for future * + // atomic + // break + // checked + // component + // const + // constraint + // constructor + // continue + // eager + // event + // external + // functor + // include + // method + // mixin + // object + // parallel + // process + // protected + // pure + // sealed + // tailcall + // trait + // virtual + // volatile + | FSharpSyntaxTokenKind.Reserved + | FSharpSyntaxTokenKind.KeywordString + | FSharpSyntaxTokenKind.Binder + | FSharpSyntaxTokenKind.OffsideBinder -> true + | _ -> false + + member this.IsIdentifier = + match this.Kind with + | FSharpSyntaxTokenKind.Identifier -> true + | _ -> false + + member this.IsStringLiteral = + match this.Kind with + | FSharpSyntaxTokenKind.String -> true + | _ -> false + + member this.IsNumericLiteral = + match this.Kind with + | FSharpSyntaxTokenKind.UInt8 + | FSharpSyntaxTokenKind.UInt16 + | FSharpSyntaxTokenKind.UInt64 + | FSharpSyntaxTokenKind.Int8 + | FSharpSyntaxTokenKind.Int16 + | FSharpSyntaxTokenKind.Int32 + | FSharpSyntaxTokenKind.Int64 + | FSharpSyntaxTokenKind.Ieee32 + | FSharpSyntaxTokenKind.Ieee64 + | FSharpSyntaxTokenKind.BigNumber -> true + | _ -> false + + member this.IsCommentTrivia = + match this.Kind with + | FSharpSyntaxTokenKind.CommentTrivia + | FSharpSyntaxTokenKind.LineCommentTrivia -> true + | _ -> false + + let lexWithErrorLogger (text: ISourceText) (filePath: string) conditionalCompilationDefines (flags: FSharpLexerFlags) supportsFeature errorLogger onToken pathMap (ct: CancellationToken) = + let canSkipTrivia = (flags &&& FSharpLexerFlags.SkipTrivia) = FSharpLexerFlags.SkipTrivia + let isLightSyntaxOn = (flags &&& FSharpLexerFlags.LightSyntaxOn) = FSharpLexerFlags.LightSyntaxOn + let isCompiling = (flags &&& FSharpLexerFlags.Compiling) = FSharpLexerFlags.Compiling + let isCompilingFSharpCore = (flags &&& FSharpLexerFlags.CompilingFSharpCore) = FSharpLexerFlags.CompilingFSharpCore + let canUseLexFilter = (flags &&& FSharpLexerFlags.UseLexFilter) = FSharpLexerFlags.UseLexFilter + + let lexbuf = UnicodeLexing.SourceTextAsLexbuf(supportsFeature, text) + let lightSyntaxStatus = LightSyntaxStatus(isLightSyntaxOn, true) + let lexargs = mkLexargs (filePath, conditionalCompilationDefines, lightSyntaxStatus, Lexhelp.LexResourceManager(0), [], errorLogger, pathMap) + let lexargs = { lexargs with applyLineDirectives = isCompiling } + + let getNextToken = + let lexer = Lexer.token lexargs canSkipTrivia + + if canUseLexFilter then + LexFilter.LexFilter(lexargs.lightSyntaxStatus, isCompilingFSharpCore, lexer, lexbuf).Lexer + else + lexer + + use _unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse + use _unwindEL = PushErrorLoggerPhaseUntilUnwind (fun _ -> DiscardErrorsLogger) + +#if FABLE_COMPILER + ignore ct +#endif + usingLexbufForParsing (lexbuf, filePath) (fun lexbuf -> + while not lexbuf.IsPastEndOfStream do +#if !FABLE_COMPILER + ct.ThrowIfCancellationRequested () +#endif + onToken (getNextToken lexbuf) lexbuf.LexemeRange) + + let lex text filePath conditionalCompilationDefines flags supportsFeature lexCallback pathMap ct = + let errorLogger = CompilationErrorLogger("Lexer", ErrorLogger.FSharpErrorSeverityOptions.Default) + lexWithErrorLogger text filePath conditionalCompilationDefines flags supportsFeature errorLogger lexCallback pathMap ct + + [] + type FSharpLexer = + + static member Lex(text: ISourceText, tokenCallback, ?langVersion, ?filePath, ?conditionalCompilationDefines, ?flags, ?pathMap, ?ct) = + let langVersion = defaultArg langVersion "latestmajor" + let flags = defaultArg flags FSharpLexerFlags.Default + let filePath = defaultArg filePath String.Empty + let conditionalCompilationDefines = defaultArg conditionalCompilationDefines [] + let pathMap = defaultArg pathMap Map.Empty +#if FABLE_COMPILER + let ct = defaultArg ct (CancellationToken()) +#else + let ct = defaultArg ct CancellationToken.None +#endif + + let supportsFeature = (LanguageVersion langVersion).SupportsFeature + + let pathMap = + (PathMap.empty, pathMap) + ||> Seq.fold (fun state pair -> state |> PathMap.addMapping pair.Key pair.Value) + + let onToken = + fun tok m -> + let fsTok = FSharpSyntaxToken(tok, m) + match fsTok.Kind with + | FSharpSyntaxTokenKind.None -> () + | _ -> tokenCallback fsTok + + lex text filePath conditionalCompilationDefines flags supportsFeature onToken pathMap ct \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/service/ServiceLexing.fsi b/src/fcs-fable/src/fsharp/service/ServiceLexing.fsi index 9dc9586759..db8cf2e827 100755 --- a/src/fcs-fable/src/fsharp/service/ServiceLexing.fsi +++ b/src/fcs-fable/src/fsharp/service/ServiceLexing.fsi @@ -5,7 +5,11 @@ namespace FSharp.Compiler.SourceCodeServices open FSharp.Compiler open Internal.Utilities.Text.Lexing +// Prevents warnings of experimental APIs within the signature file itself. +#nowarn "57" + type Position = int * int + type Range = Position * Position /// Represents encoded information for the end-of-line continuation of lexing @@ -13,10 +17,12 @@ type Range = Position * Position type FSharpTokenizerLexState = { PosBits: int64 OtherBits: int64 } + static member Initial : FSharpTokenizerLexState + member Equals : FSharpTokenizerLexState -> bool -/// Represents stable information for the state of the laxing engine at the end of a line +/// Represents stable information for the state of the lexing engine at the end of a line type FSharpTokenizerColorState = | Token = 1 | IfDefSkip = 3 @@ -33,7 +39,7 @@ type FSharpTokenizerColorState = | TripleQuoteStringInComment = 14 | InitialState = 0 -/// Gives an indicattion of the color class to assign to the token an IDE +/// Gives an indication of the color class to assign to the token an IDE type FSharpTokenColorKind = | Default = 0 | Text = 0 @@ -134,6 +140,8 @@ module FSharpTokenTag = /// Indicates the token is a `..` val DOT_DOT : int /// Indicates the token is a `..` + val DOT_DOT_HAT : int + /// Indicates the token is a `..^` val INT32_DOT_DOT : int /// Indicates the token is a `..` val UNDERSCORE : int @@ -244,6 +252,9 @@ module internal TestExpose = val TokenInfo : Parser.token -> (FSharpTokenColorKind * FSharpTokenCharKind * FSharpTokenTriggerClass) module Keywords = + /// Checks if adding backticks to identifier is needed. + val DoesIdentifierNeedQuotation : string -> bool + /// Add backticks if the identifier is a keyword. val QuoteIdentifierIfNeeded : string -> string @@ -252,3 +263,239 @@ module Keywords = /// Keywords paired with their descriptions. Used in completion and quick info. val KeywordsWithDescription : (string * string) list + +[] +module public Lexer = + + open System + open System.Threading + open FSharp.Compiler.Text + open FSharp.Compiler.Range + + [] + type public FSharpLexerFlags = + | Default = 0x11011 + | LightSyntaxOn = 0x00001 + | Compiling = 0x00010 + | CompilingFSharpCore = 0x00110 + | SkipTrivia = 0x01000 + | UseLexFilter = 0x10000 + + [] + type public FSharpSyntaxTokenKind = + | None + | HashIf + | HashElse + | HashEndIf + | CommentTrivia + | WhitespaceTrivia + | HashLine + | HashLight + | InactiveCode + | LineCommentTrivia + | StringText + | Fixed + | OffsideInterfaceMember + | OffsideBlockEnd + | OffsideRightBlockEnd + | OffsideDeclEnd + | OffsideEnd + | OffsideBlockSep + | OffsideBlockBegin + | OffsideReset + | OffsideFun + | OffsideFunction + | OffsideWith + | OffsideElse + | OffsideThen + | OffsideDoBang + | OffsideDo + | OffsideBinder + | OffsideLet + | HighPrecedenceTypeApp + | HighPrecedenceParenthesisApp + | HighPrecedenceBracketApp + | Extern + | Void + | Public + | Private + | Internal + | Global + | Static + | Member + | Class + | Abstract + | Override + | Default + | Constructor + | Inherit + | GreaterRightBracket + | Struct + | Sig + | Bar + | RightBracket + | RightBrace + | Minus + | Dollar + | BarRightBracket + | BarRightBrace + | Underscore + | Semicolon + | SemicolonSemicolon + | LeftArrow + | Equals + | LeftBracket + | LeftBracketBar + | LeftBraceBar + | LeftBracketLess + | LeftBrace + | QuestionMark + | QuestionMarkQuestionMark + | Dot + | Colon + | ColonColon + | ColonGreater + | ColonQuestionMark + | ColonQuestionMarkGreater + | ColonEquals + | When + | While + | With + | Hash + | Ampersand + | AmpersandAmpersand + | Quote + | LeftParenthesis + | RightParenthesis + | Star + | Comma + | RightArrow + | GreaterBarRightBracket + | LeftParenthesisStarRightParenthesis + | Open + | Or + | Rec + | Then + | To + | True + | Try + | Type + | Val + | Inline + | Interface + | Instance + | Const + | Lazy + | OffsideLazy + | Match + | MatchBang + | Mutable + | New + | Of + | Exception + | False + | For + | Fun + | Function + | If + | In + | JoinIn + | Finally + | DoBang + | And + | As + | Assert + | OffsideAssert + | Begin + | Do + | Done + | DownTo + | Else + | Elif + | End + | DotDot + | DotDotHat + | BarBar + | Upcast + | Downcast + | Null + | Reserved + | Module + | Namespace + | Delegate + | Constraint + | Base + | LeftQuote + | RightQuote + | RightQuoteDot + | PercentOperator + | Binder + | Less + | Greater + | Let + | Yield + | YieldBang + | BigNumber + | Decimal + | Char + | Ieee64 + | Ieee32 + | NativeInt + | UNativeInt + | UInt64 + | UInt32 + | UInt16 + | UInt8 + | Int64 + | Int32 + | Int32DotDot + | Int16 + | Int8 + | FunkyOperatorName + | AdjacentPrefixOperator + | PlusMinusOperator + | InfixAmpersandOperator + | InfixStarDivideModuloOperator + | PrefixOperator + | InfixBarOperator + | InfixAtHatOperator + | InfixCompareOperator + | InfixStarStarOperator + | Identifier + | KeywordString + | String + | ByteArray + | Asr + | InfixAsr + | InfixLand + | InfixLor + | InfixLsl + | InfixLsr + | InfixLxor + | InfixMod + + [] + type public FSharpSyntaxToken = + + val private tok: Parser.token + val private tokRange: range + + member Range: range + + member Kind: FSharpSyntaxTokenKind + + member IsIdentifier: bool + + member IsKeyword: bool + + member IsStringLiteral: bool + + member IsNumericLiteral: bool + + member IsCommentTrivia: bool + + [] + type public FSharpLexer = + + [] + static member Lex: text: ISourceText * tokenCallback: (FSharpSyntaxToken -> unit) * ?langVersion: string * ?filePath: string * ?conditionalCompilationDefines: string list * ?flags: FSharpLexerFlags * ?pathMap: Map * ?ct: CancellationToken -> unit \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/service/ServiceNavigation.fs b/src/fcs-fable/src/fsharp/service/ServiceNavigation.fs index a853805182..7e5591e594 100755 --- a/src/fcs-fable/src/fsharp/service/ServiceNavigation.fs +++ b/src/fcs-fable/src/fsharp/service/ServiceNavigation.fs @@ -8,7 +8,8 @@ namespace FSharp.Compiler.SourceCodeServices open FSharp.Compiler.Range -open FSharp.Compiler.Ast +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps /// Represents the different kinds of items that can appear in the navigation bar type FSharpNavigationDeclarationItemKind = @@ -71,11 +72,14 @@ type FSharpNavigationItems(declarations:FSharpNavigationTopLevelDeclaration[]) = member x.Declarations = declarations module NavigationImpl = - let unionRangesChecked r1 r2 = if r1 = range.Zero then r2 elif r2 = range.Zero then r1 else unionRanges r1 r2 + let unionRangesChecked r1 r2 = + if FSharp.Compiler.Range.equals r1 range.Zero then r2 + elif FSharp.Compiler.Range.equals r2 range.Zero then r1 + else unionRanges r1 r2 let rangeOfDecls2 f decls = match (decls |> List.map (f >> (fun (d:FSharpNavigationDeclarationItem) -> d.bodyRange))) with - | hd::tl -> tl |> List.fold unionRangesChecked hd + | hd :: tl -> tl |> List.fold unionRangesChecked hd | [] -> range.Zero let rangeOfDecls = rangeOfDecls2 fst @@ -94,15 +98,15 @@ module NavigationImpl = /// Get information for implementation file let getNavigationFromImplFile (modules: SynModuleOrNamespace list) = // Map for dealing with name conflicts - let nameMap = ref Map.empty + let mutable nameMap = Map.empty let addItemName name = - let count = defaultArg (!nameMap |> Map.tryFind name) 0 - nameMap := (Map.add name (count + 1) (!nameMap)) + let count = defaultArg (nameMap |> Map.tryFind name) 0 + nameMap <- (Map.add name (count + 1) (nameMap)) (count + 1) let uniqueName name idx = - let total = Map.find name (!nameMap) + let total = Map.find name nameMap sprintf "%s_%d_of_%d" name idx total // Create declaration (for the left dropdown) @@ -124,13 +128,13 @@ module NavigationImpl = FSharpNavigationDeclarationItem.Create(id.idText, kind, baseGlyph, m, m, false, enclosingEntityKind, isAbstract, access), (addItemName(id.idText)) // Process let-binding - let processBinding isMember enclosingEntityKind isAbstract (Binding(_, _, _, _, _, _, SynValData(memebrOpt, _, _), synPat, _, synExpr, _, _)) = + let processBinding isMember enclosingEntityKind isAbstract (Binding(_, _, _, _, _, _, SynValData(memberOpt, _, _), synPat, _, synExpr, _, _)) = let m = match synExpr with - | SynExpr.Typed(e, _, _) -> e.Range // fix range for properties with type annotations + | SynExpr.Typed (e, _, _) -> e.Range // fix range for properties with type annotations | _ -> synExpr.Range - match synPat, memebrOpt with + match synPat, memberOpt with | SynPat.LongIdent(longDotId=LongIdentWithDots(lid,_); accessibility=access), Some(flags) when isMember -> let icon, kind = match flags.MemberKind with @@ -143,8 +147,8 @@ module NavigationImpl = | MemberKind.PropertyGet -> FSharpGlyph.Property, PropertyDecl let lidShow, rangeMerge = match lid with - | _thisVar::nm::_ -> (List.tail lid, nm.idRange) - | hd::_ -> (lid, hd.idRange) + | _thisVar :: nm :: _ -> (List.tail lid, nm.idRange) + | hd :: _ -> (lid, hd.idRange) | _ -> (lid, m) [ createMemberLid(lidShow, kind, icon, unionRanges rangeMerge m, enclosingEntityKind, isAbstract, access) ] | SynPat.LongIdent(LongIdentWithDots(lid,_), _, _, _, access, _), _ -> @@ -287,7 +291,7 @@ module NavigationImpl = FSharpGlyph.Module, m, unionRangesChecked (rangeOfDecls nested) (moduleRange (rangeOfLid id) other), singleTopLevel, FSharpEnclosingEntityKind.Module, false, access), (addItemName(textOfLid id)), nested - decl::other) + decl :: other) let items = items @@ -302,13 +306,13 @@ module NavigationImpl = /// Get information for signature file let getNavigationFromSigFile (modules: SynModuleOrNamespaceSig list) = // Map for dealing with name conflicts - let nameMap = ref Map.empty + let mutable nameMap = Map.empty let addItemName name = - let count = defaultArg (!nameMap |> Map.tryFind name) 0 - nameMap := (Map.add name (count + 1) (!nameMap)) + let count = defaultArg (nameMap |> Map.tryFind name) 0 + nameMap <- (Map.add name (count + 1) (nameMap)) (count + 1) let uniqueName name idx = - let total = Map.find name (!nameMap) + let total = Map.find name nameMap sprintf "%s_%d_of_%d" name idx total // Create declaration (for the left dropdown) @@ -400,7 +404,7 @@ module NavigationImpl = // Get nested modules and types (for the left dropdown) let other = processFSharpNavigationTopLevelSigDeclarations(newBaseName, decls) - createDeclLid(baseName, lid, ModuleDecl, FSharpGlyph.Module, m, unionRangesChecked (rangeOfDecls nested) (moduleRange (rangeOfLid lid) other), nested, FSharpEnclosingEntityKind.Module, false, access)::other + createDeclLid(baseName, lid, ModuleDecl, FSharpGlyph.Module, m, unionRangesChecked (rangeOfDecls nested) (moduleRange (rangeOfLid lid) other), nested, FSharpEnclosingEntityKind.Module, false, access) :: other | SynModuleSigDecl.Types(tydefs, _) -> tydefs |> List.collect (processTycon baseName) | SynModuleSigDecl.Exception (defn,_) -> processExnSig baseName defn @@ -424,7 +428,7 @@ module NavigationImpl = FSharpGlyph.Module, m, unionRangesChecked (rangeOfDecls nested) (moduleRange (rangeOfLid id) other), singleTopLevel, FSharpEnclosingEntityKind.Module, false, access), (addItemName(textOfLid id)), nested - decl::other) + decl :: other) let items = items @@ -438,10 +442,12 @@ module NavigationImpl = items |> Array.sortInPlaceWith (fun a b -> compare a.Declaration.Name b.Declaration.Name) new FSharpNavigationItems(items) +[] +module FSharpNavigation = let getNavigation (parsedInput: ParsedInput) = match parsedInput with - | ParsedInput.SigFile(ParsedSigFileInput(modules = modules)) -> getNavigationFromSigFile modules - | ParsedInput.ImplFile(ParsedImplFileInput(modules = modules)) -> getNavigationFromImplFile modules + | ParsedInput.SigFile (ParsedSigFileInput (modules = modules)) -> NavigationImpl.getNavigationFromSigFile modules + | ParsedInput.ImplFile (ParsedImplFileInput (modules = modules)) -> NavigationImpl.getNavigationFromImplFile modules let empty = FSharpNavigationItems([||]) @@ -570,7 +576,7 @@ module NavigateTo = let ctor = mapMemberKind memberFlags.MemberKind addValSig ctor valSig isSig container - let rec walkSigFileInput (ParsedSigFileInput(fileName, _, _, _, moduleOrNamespaceList)) = + let rec walkSigFileInput (ParsedSigFileInput (fileName, _, _, _, moduleOrNamespaceList)) = for item in moduleOrNamespaceList do walkSynModuleOrNamespaceSig item { Type = ContainerType.File; Name = fileName } @@ -627,7 +633,7 @@ module NavigateTo = | SynMemberSig.Inherit _ | SynMemberSig.Interface _ -> () - and walkImplFileInpit (ParsedImplFileInput(fileName = fileName; modules = moduleOrNamespaceList)) = + and walkImplFileInput (ParsedImplFileInput (fileName = fileName; modules = moduleOrNamespaceList)) = let container = { Type = ContainerType.File; Name = fileName } for item in moduleOrNamespaceList do walkSynModuleOrNamespace item container @@ -727,7 +733,7 @@ module NavigateTo = match parsedInput with | ParsedInput.SigFile input -> walkSigFileInput input - | ParsedInput.ImplFile input -> walkImplFileInpit input + | ParsedInput.ImplFile input -> walkImplFileInput input result.ToArray() diff --git a/src/fcs-fable/src/fsharp/service/ServiceNavigation.fsi b/src/fcs-fable/src/fsharp/service/ServiceNavigation.fsi index be15736601..297880e77e 100755 --- a/src/fcs-fable/src/fsharp/service/ServiceNavigation.fsi +++ b/src/fcs-fable/src/fsharp/service/ServiceNavigation.fsi @@ -7,7 +7,8 @@ namespace FSharp.Compiler.SourceCodeServices -open FSharp.Compiler +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree /// Indicates a kind of item to show in an F# navigation bar type public FSharpNavigationDeclarationItemKind = @@ -39,12 +40,12 @@ type public FSharpNavigationDeclarationItem = member UniqueName : string member Glyph : FSharpGlyph member Kind : FSharpNavigationDeclarationItemKind - member Range : Range.range - member BodyRange : Range.range + member Range : range + member BodyRange : range member IsSingleTopLevel : bool member EnclosingEntityKind: FSharpEnclosingEntityKind member IsAbstract: bool - member Access : Ast.SynAccess option + member Access : SynAccess option /// Represents top-level declarations (that should be in the type drop-down) /// with nested declarations (that can be shown in the member drop-down) @@ -60,12 +61,10 @@ type public FSharpNavigationTopLevelDeclaration = type public FSharpNavigationItems = member Declarations : FSharpNavigationTopLevelDeclaration[] -// implementation details used by other code in the compiler -module internal NavigationImpl = - val internal getNavigationFromImplFile : Ast.SynModuleOrNamespace list -> FSharpNavigationItems - val internal getNavigationFromSigFile : Ast.SynModuleOrNamespaceSig list -> FSharpNavigationItems - val internal getNavigation : Ast.ParsedInput -> FSharpNavigationItems +// Functionality to access navigable F# items. +module public FSharpNavigation = val internal empty : FSharpNavigationItems + val getNavigation : ParsedInput -> FSharpNavigationItems module public NavigateTo = [] @@ -96,9 +95,9 @@ module public NavigateTo = type NavigableItem = { Name: string - Range: Range.range + Range: range IsSignature: bool Kind: NavigableItemKind Container: Container } - val getNavigableItems : Ast.ParsedInput -> NavigableItem [] + val getNavigableItems : ParsedInput -> NavigableItem [] diff --git a/src/fcs-fable/src/fsharp/service/ServiceParamInfoLocations.fs b/src/fcs-fable/src/fsharp/service/ServiceParamInfoLocations.fs index f527e493ba..b265d1b535 100755 --- a/src/fcs-fable/src/fsharp/service/ServiceParamInfoLocations.fs +++ b/src/fcs-fable/src/fsharp/service/ServiceParamInfoLocations.fs @@ -2,8 +2,9 @@ namespace FSharp.Compiler.SourceCodeServices +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps open FSharp.Compiler.Range -open FSharp.Compiler.Ast [] type FSharpNoteworthyParamInfoLocations(longId: string list, longIdRange: range, openParenLocation: pos, tupleEndLocations: pos list, isThereACloseParen: bool, namedParamNames: string option list) = @@ -41,10 +42,10 @@ module internal NoteworthyParamInfoLocationsImpl = let rec digOutIdentFromFuncExpr synExpr = // we found it, dig out ident match synExpr with - | SynExpr.Ident(id) -> Some ([id.idText], id.idRange) - | SynExpr.LongIdent(_, LongIdentWithDots(lid, _), _, lidRange) - | SynExpr.DotGet(_, _, LongIdentWithDots(lid, _), lidRange) -> Some (pathOfLid lid, lidRange) - | SynExpr.TypeApp(synExpr, _, _synTypeList, _commas, _, _, _range) -> digOutIdentFromFuncExpr synExpr + | SynExpr.Ident (id) -> Some ([id.idText], id.idRange) + | SynExpr.LongIdent (_, LongIdentWithDots(lid, _), _, lidRange) + | SynExpr.DotGet (_, _, LongIdentWithDots(lid, _), lidRange) -> Some (pathOfLid lid, lidRange) + | SynExpr.TypeApp (synExpr, _, _synTypeList, _commas, _, _, _range) -> digOutIdentFromFuncExpr synExpr | _ -> None type FindResult = @@ -60,17 +61,17 @@ module internal NoteworthyParamInfoLocationsImpl = let getNamedParamName e = match e with // f(x=4) - | SynExpr.App(ExprAtomicFlag.NonAtomic, _, - SynExpr.App(ExprAtomicFlag.NonAtomic, true, + | SynExpr.App (ExprAtomicFlag.NonAtomic, _, + SynExpr.App (ExprAtomicFlag.NonAtomic, true, SynExpr.Ident op, SynExpr.Ident n, _range), _, _) when op.idText="op_Equality" -> Some n.idText // f(?x=4) - | SynExpr.App(ExprAtomicFlag.NonAtomic, _, - SynExpr.App(ExprAtomicFlag.NonAtomic, true, + | SynExpr.App (ExprAtomicFlag.NonAtomic, _, + SynExpr.App (ExprAtomicFlag.NonAtomic, true, SynExpr.Ident op, - SynExpr.LongIdent(true(*isOptional*), LongIdentWithDots([n], _), _ref, _lidrange), _range), + SynExpr.LongIdent (true(*isOptional*), LongIdentWithDots([n], _), _ref, _lidrange), _range), _, _) when op.idText="op_Equality" -> Some n.idText | _ -> None @@ -83,7 +84,7 @@ module internal NoteworthyParamInfoLocationsImpl = let inner = traverseSynExpr synExpr match inner with | None -> - if AstTraversal.rangeContainsPosEdgesExclusive parenRange pos then + if AstTraversal.rangeContainsPosLeftEdgeExclusiveAndRightEdgeInclusive parenRange pos then Found (parenRange.Start, [(parenRange.End, getNamedParamName synExpr)], rpRangeOpt.IsSome), None else NotFound, None @@ -96,11 +97,11 @@ module internal NoteworthyParamInfoLocationsImpl = // see bug 345385. let rec searchSynArgExpr traverseSynExpr pos expr = match expr with - | SynExprParen((SynExpr.Tuple(false, synExprList, commaRanges, _tupleRange) as synExpr), _lpRange, rpRangeOpt, parenRange) -> // tuple argument + | SynExprParen((SynExpr.Tuple (false, synExprList, commaRanges, _tupleRange) as synExpr), _lpRange, rpRangeOpt, parenRange) -> // tuple argument let inner = traverseSynExpr synExpr match inner with | None -> - if AstTraversal.rangeContainsPosEdgesExclusive parenRange pos then + if AstTraversal.rangeContainsPosLeftEdgeExclusiveAndRightEdgeInclusive parenRange pos then let commasAndCloseParen = ((synExprList, commaRanges@[parenRange]) ||> List.map2 (fun e c -> c.End, getNamedParamName e)) let r = Found (parenRange.Start, commasAndCloseParen, rpRangeOpt.IsSome) r, None @@ -108,7 +109,7 @@ module internal NoteworthyParamInfoLocationsImpl = NotFound, None | _ -> NotFound, None - | SynExprParen(SynExprParen(SynExpr.Tuple(false, _, _, _), _, _, _) as synExpr, _, rpRangeOpt, parenRange) -> // f((x, y)) is special, single tuple arg + | SynExprParen(SynExprParen(SynExpr.Tuple (false, _, _, _), _, _, _) as synExpr, _, rpRangeOpt, parenRange) -> // f((x, y)) is special, single tuple arg handleSingleArg traverseSynExpr (pos, synExpr, parenRange, rpRangeOpt) // dig into multiple parens @@ -119,14 +120,14 @@ module internal NoteworthyParamInfoLocationsImpl = | SynExprParen(synExpr, _lpRange, rpRangeOpt, parenRange) -> // single argument handleSingleArg traverseSynExpr (pos, synExpr, parenRange, rpRangeOpt) - | SynExpr.ArbitraryAfterError(_debugStr, range) -> // single argument when e.g. after open paren you hit EOF + | SynExpr.ArbitraryAfterError (_debugStr, range) -> // single argument when e.g. after open paren you hit EOF if AstTraversal.rangeContainsPosEdgesExclusive range pos then let r = Found (range.Start, [(range.End, None)], false) r, None else NotFound, None - | SynExpr.Const(SynConst.Unit, unitRange) -> + | SynExpr.Const (SynConst.Unit, unitRange) -> if AstTraversal.rangeContainsPosEdgesExclusive unitRange pos then let r = Found (unitRange.Start, [(unitRange.End, None)], true) r, None @@ -164,7 +165,7 @@ module internal NoteworthyParamInfoLocationsImpl = match expr with // new LID(...) and error recovery of these - | SynExpr.New(_, synType, synExpr, _) -> + | SynExpr.New (_, synType, synExpr, _) -> let constrArgsResult, cacheOpt = searchSynArgExpr traverseSynExpr pos synExpr match constrArgsResult, cacheOpt with | Found(parenLoc, args, isThereACloseParen), _ -> @@ -178,7 +179,7 @@ module internal NoteworthyParamInfoLocationsImpl = | _ -> traverseSynExpr synExpr // EXPR< = error recovery of a form of half-written TypeApp - | SynExpr.App(_, _, SynExpr.App(_, true, SynExpr.Ident op, synExpr, openm), SynExpr.ArbitraryAfterError _, wholem) when op.idText = "op_LessThan" -> + | SynExpr.App (_, _, SynExpr.App (_, true, SynExpr.Ident op, synExpr, openm), SynExpr.ArbitraryAfterError _, wholem) when op.idText = "op_LessThan" -> // Look in the function expression let fResult = traverseSynExpr synExpr match fResult with @@ -194,7 +195,7 @@ module internal NoteworthyParamInfoLocationsImpl = None // EXPR EXPR2 - | SynExpr.App(_exprAtomicFlag, isInfix, synExpr, synExpr2, _range) -> + | SynExpr.App (_exprAtomicFlag, isInfix, synExpr, synExpr2, _range) -> // Look in the function expression let fResult = traverseSynExpr synExpr match fResult with @@ -219,7 +220,7 @@ module internal NoteworthyParamInfoLocationsImpl = | _ -> traverseSynExpr synExpr2 // ID and error recovery of these - | SynExpr.TypeApp(synExpr, openm, tyArgs, commas, closemOpt, _, wholem) -> + | SynExpr.TypeApp (synExpr, openm, tyArgs, commas, closemOpt, _, wholem) -> match traverseSynExpr synExpr with | Some _ as r -> r | None -> diff --git a/src/fcs-fable/src/fsharp/service/ServiceParamInfoLocations.fsi b/src/fcs-fable/src/fsharp/service/ServiceParamInfoLocations.fsi index 6961c892b0..618ced81d1 100755 --- a/src/fcs-fable/src/fsharp/service/ServiceParamInfoLocations.fsi +++ b/src/fcs-fable/src/fsharp/service/ServiceParamInfoLocations.fsi @@ -7,8 +7,8 @@ namespace FSharp.Compiler.SourceCodeServices -open FSharp.Compiler open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree /// Represents the locations relevant to activating parameter info in an IDE [] @@ -36,5 +36,5 @@ type public FSharpNoteworthyParamInfoLocations = member NamedParamNames : string option [] /// Find the information about parameter info locations at a particular source location - static member Find : pos * Ast.ParsedInput -> FSharpNoteworthyParamInfoLocations option + static member Find : pos * ParsedInput -> FSharpNoteworthyParamInfoLocations option diff --git a/src/fcs-fable/src/fsharp/service/ServiceParseTreeWalk.fs b/src/fcs-fable/src/fsharp/service/ServiceParseTreeWalk.fs index 40e6580cc8..7bf6028508 100755 --- a/src/fcs-fable/src/fsharp/service/ServiceParseTreeWalk.fs +++ b/src/fcs-fable/src/fsharp/service/ServiceParseTreeWalk.fs @@ -8,8 +8,7 @@ namespace FSharp.Compiler.SourceCodeServices open FSharp.Compiler.Range -open FSharp.Compiler.Ast - +open FSharp.Compiler.SyntaxTree /// A range of utility functions to assist with traversing an AST module public AstTraversal = @@ -27,6 +26,8 @@ module public AstTraversal = // treat ranges as though they are fully open: (,) let rangeContainsPosEdgesExclusive (m1:range) p = posGt p m1.Start && posGt m1.End p + let rangeContainsPosLeftEdgeExclusiveAndRightEdgeInclusive (m1:range) p = posGt p m1.Start && posGeq m1.End p + /// used to track route during traversal AST [] type TraverseStep = @@ -199,17 +200,17 @@ module public AstTraversal = let path = TraverseStep.Expr e :: path let traverseSynExpr = traverseSynExpr path match e with - | SynExpr.Paren(synExpr, _, _, _parenRange) -> traverseSynExpr synExpr - | SynExpr.Quote(_synExpr, _, synExpr2, _, _range) -> + | SynExpr.Paren (synExpr, _, _, _parenRange) -> traverseSynExpr synExpr + | SynExpr.Quote (_synExpr, _, synExpr2, _, _range) -> [//dive synExpr synExpr.Range traverseSynExpr // TODO, what is this? dive synExpr2 synExpr2.Range traverseSynExpr] |> pick expr - | SynExpr.Const(_synConst, _range) -> None - | SynExpr.Typed(synExpr, synType, _range) -> [ traverseSynExpr synExpr; traverseSynType synType ] |> List.tryPick id - | SynExpr.Tuple(_, synExprList, _, _range) - | SynExpr.ArrayOrList(_, synExprList, _range) -> synExprList |> List.map (fun x -> dive x x.Range traverseSynExpr) |> pick expr + | SynExpr.Const (_synConst, _range) -> None + | SynExpr.Typed (synExpr, synType, _range) -> [ traverseSynExpr synExpr; traverseSynType synType ] |> List.tryPick id + | SynExpr.Tuple (_, synExprList, _, _range) + | SynExpr.ArrayOrList (_, synExprList, _range) -> synExprList |> List.map (fun x -> dive x x.Range traverseSynExpr) |> pick expr - | SynExpr.AnonRecd(_isStruct, copyOpt, synExprList, _range) -> + | SynExpr.AnonRecd (_isStruct, copyOpt, synExprList, _range) -> [ match copyOpt with | Some(expr, (withRange, _)) -> yield dive expr expr.Range traverseSynExpr @@ -225,7 +226,7 @@ module public AstTraversal = for (_,x) in synExprList do yield dive x x.Range traverseSynExpr ] |> pick expr - | SynExpr.Record(inheritOpt,copyOpt,fields, _range) -> + | SynExpr.Record (inheritOpt,copyOpt,fields, _range) -> [ let diveIntoSeparator offsideColumn scPosOpt copyOpt = match scPosOpt with @@ -311,8 +312,8 @@ module public AstTraversal = | _ -> () ] |> pick expr - | SynExpr.New(_, _synType, synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.ObjExpr(ty,baseCallOpt,binds,ifaces,_range1,_range2) -> + | SynExpr.New (_, _synType, synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.ObjExpr (ty,baseCallOpt,binds,ifaces,_range1,_range2) -> let result = ifaces |> Seq.map (fun (InterfaceImpl(ty, _, _)) -> ty) @@ -325,7 +326,7 @@ module public AstTraversal = match baseCallOpt with | Some(expr,_) -> // this is like a call to 'new', so mock up a 'new' so we can recurse and use that existing logic - let newCall = SynExpr.New(false, ty, expr, unionRanges ty.Range expr.Range) + let newCall = SynExpr.New (false, ty, expr, unionRanges ty.Range expr.Range) yield dive newCall newCall.Range traverseSynExpr | _ -> () for b in binds do @@ -334,57 +335,57 @@ module public AstTraversal = for b in binds do yield dive b b.RangeOfBindingAndRhs (traverseSynBinding path) ] |> pick expr - | SynExpr.While(_sequencePointInfoForWhileLoop, synExpr, synExpr2, _range) -> + | SynExpr.While (_sequencePointInfoForWhileLoop, synExpr, synExpr2, _range) -> [dive synExpr synExpr.Range traverseSynExpr dive synExpr2 synExpr2.Range traverseSynExpr] |> pick expr - | SynExpr.For(_sequencePointInfoForForLoop, _ident, synExpr, _, synExpr2, synExpr3, _range) -> + | SynExpr.For (_sequencePointInfoForForLoop, _ident, synExpr, _, synExpr2, synExpr3, _range) -> [dive synExpr synExpr.Range traverseSynExpr dive synExpr2 synExpr2.Range traverseSynExpr dive synExpr3 synExpr3.Range traverseSynExpr] |> pick expr - | SynExpr.ForEach(_sequencePointInfoForForLoop, _seqExprOnly, _isFromSource, synPat, synExpr, synExpr2, _range) -> + | SynExpr.ForEach (_sequencePointInfoForForLoop, _seqExprOnly, _isFromSource, synPat, synExpr, synExpr2, _range) -> [dive synPat synPat.Range traversePat dive synExpr synExpr.Range traverseSynExpr dive synExpr2 synExpr2.Range traverseSynExpr] |> pick expr - | SynExpr.ArrayOrListOfSeqExpr(_, synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.CompExpr(_, _, synExpr, _range) -> + | SynExpr.ArrayOrListOfSeqExpr (_, synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.CompExpr (_, _, synExpr, _range) -> // now parser treats this syntactic expression as computation expression // { identifier } // here we detect this situation and treat CompExpr { Identifier } as attempt to create record // note: sequence expressions use SynExpr.CompExpr too - they need to be filtered out let isPartOfArrayOrList = match origPath with - | TraverseStep.Expr(SynExpr.ArrayOrListOfSeqExpr(_, _, _)) :: _ -> true + | TraverseStep.Expr(SynExpr.ArrayOrListOfSeqExpr (_, _, _)) :: _ -> true | _ -> false let ok = match isPartOfArrayOrList, synExpr with | false, SynExpr.Ident ident -> visitor.VisitRecordField(path, None, Some (LongIdentWithDots([ident], []))) - | false, SynExpr.LongIdent(false, lidwd, _, _) -> visitor.VisitRecordField(path, None, Some lidwd) + | false, SynExpr.LongIdent (false, lidwd, _, _) -> visitor.VisitRecordField(path, None, Some lidwd) | _ -> None if ok.IsSome then ok else traverseSynExpr synExpr - | SynExpr.Lambda(_, _, synSimplePats, synExpr, _range) -> + | SynExpr.Lambda (_, _, synSimplePats, synExpr, _range) -> match synSimplePats with | SynSimplePats.SimplePats(pats,_) -> match visitor.VisitSimplePats(pats) with | Some x -> Some x | None -> traverseSynExpr synExpr | _ -> traverseSynExpr synExpr - | SynExpr.MatchLambda(_isExnMatch,_argm,synMatchClauseList,_spBind,_wholem) -> + | SynExpr.MatchLambda (_isExnMatch,_argm,synMatchClauseList,_spBind,_wholem) -> synMatchClauseList |> List.map (fun x -> dive x x.Range (traverseSynMatchClause path)) |> pick expr - | SynExpr.Match(_sequencePointInfoForBinding, synExpr, synMatchClauseList, _range) -> + | SynExpr.Match (_sequencePointInfoForBinding, synExpr, synMatchClauseList, _range) -> [yield dive synExpr synExpr.Range traverseSynExpr yield! synMatchClauseList |> List.map (fun x -> dive x x.RangeOfGuardAndRhs (traverseSynMatchClause path))] |> pick expr - | SynExpr.Do(synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.Assert(synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.Fixed(synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.App(_exprAtomicFlag, isInfix, synExpr, synExpr2, _range) -> + | SynExpr.Do (synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.Assert (synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.Fixed (synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.App (_exprAtomicFlag, isInfix, synExpr, synExpr2, _range) -> if isInfix then [dive synExpr2 synExpr2.Range traverseSynExpr dive synExpr synExpr.Range traverseSynExpr] // reverse the args @@ -393,100 +394,107 @@ module public AstTraversal = [dive synExpr synExpr.Range traverseSynExpr dive synExpr2 synExpr2.Range traverseSynExpr] |> pick expr - | SynExpr.TypeApp(synExpr, _, _synTypeList, _commas, _, _, _range) -> traverseSynExpr synExpr - | SynExpr.LetOrUse(_, _, synBindingList, synExpr, range) -> + | SynExpr.TypeApp (synExpr, _, _synTypeList, _commas, _, _, _range) -> traverseSynExpr synExpr + | SynExpr.LetOrUse (_, _, synBindingList, synExpr, range) -> match visitor.VisitLetOrUse(path, traverseSynBinding path, synBindingList, range) with | Some x -> Some x | None -> [yield! synBindingList |> List.map (fun x -> dive x x.RangeOfBindingAndRhs (traverseSynBinding path)) yield dive synExpr synExpr.Range traverseSynExpr] |> pick expr - | SynExpr.TryWith(synExpr, _range, synMatchClauseList, _range2, _range3, _sequencePointInfoForTry, _sequencePointInfoForWith) -> + | SynExpr.TryWith (synExpr, _range, synMatchClauseList, _range2, _range3, _sequencePointInfoForTry, _sequencePointInfoForWith) -> [yield dive synExpr synExpr.Range traverseSynExpr yield! synMatchClauseList |> List.map (fun x -> dive x x.Range (traverseSynMatchClause path))] |> pick expr - | SynExpr.TryFinally(synExpr, synExpr2, _range, _sequencePointInfoForTry, _sequencePointInfoForFinally) -> + | SynExpr.TryFinally (synExpr, synExpr2, _range, _sequencePointInfoForTry, _sequencePointInfoForFinally) -> [dive synExpr synExpr.Range traverseSynExpr dive synExpr2 synExpr2.Range traverseSynExpr] |> pick expr - | SynExpr.Lazy(synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.Sequential(_sequencePointInfoForSeq, _, synExpr, synExpr2, _range) -> + | SynExpr.Lazy (synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.SequentialOrImplicitYield (_sequencePointInfoForSequential, synExpr, synExpr2, _, _range) + | SynExpr.Sequential (_sequencePointInfoForSequential, _, synExpr, synExpr2, _range) -> [dive synExpr synExpr.Range traverseSynExpr dive synExpr2 synExpr2.Range traverseSynExpr] |> pick expr - | SynExpr.IfThenElse(synExpr, synExpr2, synExprOpt, _sequencePointInfoForBinding, _isRecovery, _range, _range2) -> + | SynExpr.IfThenElse (synExpr, synExpr2, synExprOpt, _sequencePointInfoForBinding, _isRecovery, _range, _range2) -> [yield dive synExpr synExpr.Range traverseSynExpr yield dive synExpr2 synExpr2.Range traverseSynExpr match synExprOpt with | None -> () | Some(x) -> yield dive x x.Range traverseSynExpr] |> pick expr - | SynExpr.Ident(_ident) -> None - | SynExpr.LongIdent(_, _longIdent, _altNameRefCell, _range) -> None - | SynExpr.LongIdentSet(_longIdent, synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.DotGet(synExpr, _dotm, _longIdent, _range) -> traverseSynExpr synExpr - | SynExpr.Set(synExpr, synExpr2, _) - | SynExpr.DotSet(synExpr, _, synExpr2, _) -> + | SynExpr.Ident (_ident) -> None + | SynExpr.LongIdent (_, _longIdent, _altNameRefCell, _range) -> None + | SynExpr.LongIdentSet (_longIdent, synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.DotGet (synExpr, _dotm, _longIdent, _range) -> traverseSynExpr synExpr + | SynExpr.Set (synExpr, synExpr2, _) + | SynExpr.DotSet (synExpr, _, synExpr2, _) -> [dive synExpr synExpr.Range traverseSynExpr dive synExpr2 synExpr2.Range traverseSynExpr] |> pick expr - | SynExpr.DotIndexedGet(synExpr, synExprList, _range, _range2) -> + | SynExpr.DotIndexedGet (synExpr, synExprList, _range, _range2) -> [yield dive synExpr synExpr.Range traverseSynExpr for synExpr in synExprList do for x in synExpr.Exprs do yield dive x x.Range traverseSynExpr] |> pick expr - | SynExpr.DotIndexedSet(synExpr, synExprList, synExpr2, _, _range, _range2) -> + | SynExpr.DotIndexedSet (synExpr, synExprList, synExpr2, _, _range, _range2) -> [yield dive synExpr synExpr.Range traverseSynExpr for synExpr in synExprList do for x in synExpr.Exprs do yield dive x x.Range traverseSynExpr yield dive synExpr2 synExpr2.Range traverseSynExpr] |> pick expr - | SynExpr.JoinIn(synExpr1, _range, synExpr2, _range2) -> + | SynExpr.JoinIn (synExpr1, _range, synExpr2, _range2) -> [dive synExpr1 synExpr1.Range traverseSynExpr dive synExpr2 synExpr2.Range traverseSynExpr] |> pick expr - | SynExpr.NamedIndexedPropertySet(_longIdent, synExpr, synExpr2, _range) -> + | SynExpr.NamedIndexedPropertySet (_longIdent, synExpr, synExpr2, _range) -> [dive synExpr synExpr.Range traverseSynExpr dive synExpr2 synExpr2.Range traverseSynExpr] |> pick expr - | SynExpr.DotNamedIndexedPropertySet(synExpr, _longIdent, synExpr2, synExpr3, _range) -> + | SynExpr.DotNamedIndexedPropertySet (synExpr, _longIdent, synExpr2, synExpr3, _range) -> [dive synExpr synExpr.Range traverseSynExpr dive synExpr2 synExpr2.Range traverseSynExpr dive synExpr3 synExpr3.Range traverseSynExpr] |> pick expr - | SynExpr.TypeTest(synExpr, synType, _range) - | SynExpr.Upcast(synExpr, synType, _range) - | SynExpr.Downcast(synExpr, synType, _range) -> + | SynExpr.TypeTest (synExpr, synType, _range) + | SynExpr.Upcast (synExpr, synType, _range) + | SynExpr.Downcast (synExpr, synType, _range) -> [dive synExpr synExpr.Range traverseSynExpr dive synType synType.Range traverseSynType] |> pick expr - | SynExpr.InferredUpcast(synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.InferredDowncast(synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.Null(_range) -> None - | SynExpr.AddressOf(_, synExpr, _range, _range2) -> traverseSynExpr synExpr - | SynExpr.TraitCall(_synTyparList, _synMemberSig, synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.ImplicitZero(_range) -> None - | SynExpr.YieldOrReturn(_, synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.YieldOrReturnFrom(_, synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.LetOrUseBang(_sequencePointInfoForBinding, _, _, synPat, synExpr, synExpr2, _range) -> - [dive synPat synPat.Range traversePat - dive synExpr synExpr.Range traverseSynExpr - dive synExpr2 synExpr2.Range traverseSynExpr] + | SynExpr.InferredUpcast (synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.InferredDowncast (synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.Null (_range) -> None + | SynExpr.AddressOf (_, synExpr, _range, _range2) -> traverseSynExpr synExpr + | SynExpr.TraitCall (_synTyparList, _synMemberSig, synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.ImplicitZero (_range) -> None + | SynExpr.YieldOrReturn (_, synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.YieldOrReturnFrom (_, synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.LetOrUseBang(_sequencePointInfoForBinding, _, _, synPat, synExpr, andBangSynExprs, synExpr2, _range) -> + [ + yield dive synPat synPat.Range traversePat + yield dive synExpr synExpr.Range traverseSynExpr + yield! + [ for (_,_,_,andBangSynPat,andBangSynExpr,_) in andBangSynExprs do + yield (dive andBangSynPat andBangSynPat.Range traversePat) + yield (dive andBangSynExpr andBangSynExpr.Range traverseSynExpr)] + yield dive synExpr2 synExpr2.Range traverseSynExpr + ] |> pick expr - | SynExpr.MatchBang(_sequencePointInfoForBinding, synExpr, synMatchClauseList, _range) -> + | SynExpr.MatchBang (_sequencePointInfoForBinding, synExpr, synMatchClauseList, _range) -> [yield dive synExpr synExpr.Range traverseSynExpr yield! synMatchClauseList |> List.map (fun x -> dive x x.RangeOfGuardAndRhs (traverseSynMatchClause path))] |> pick expr - | SynExpr.DoBang(synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.DoBang (synExpr, _range) -> traverseSynExpr synExpr | SynExpr.LibraryOnlyILAssembly _ -> None | SynExpr.LibraryOnlyStaticOptimization _ -> None | SynExpr.LibraryOnlyUnionCaseFieldGet _ -> None | SynExpr.LibraryOnlyUnionCaseFieldSet _ -> None - | SynExpr.ArbitraryAfterError(_debugStr, _range) -> None - | SynExpr.FromParseError(synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.DiscardAfterMissingQualificationAfterDot(synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.ArbitraryAfterError (_debugStr, _range) -> None + | SynExpr.FromParseError (synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.DiscardAfterMissingQualificationAfterDot (synExpr, _range) -> traverseSynExpr synExpr visitor.VisitExpr(path, traverseSynExpr path, defaultTraverse, expr) @@ -501,8 +509,8 @@ module public AstTraversal = | SynPat.Attrib (p, _, _) -> traversePat p | SynPat.LongIdent(_, _, _, args, _, _) -> match args with - | SynConstructorArgs.Pats ps -> ps |> List.tryPick traversePat - | SynConstructorArgs.NamePatPairs (ps, _) -> + | SynArgPats.Pats ps -> ps |> List.tryPick traversePat + | SynArgPats.NamePatPairs (ps, _) -> ps |> List.map snd |> List.tryPick traversePat | SynPat.Typed (p, ty, _) -> [ traversePat p; traverseSynType ty ] |> List.tryPick id @@ -604,8 +612,10 @@ module public AstTraversal = match m with | SynMemberDefn.Open(_longIdent, _range) -> None | SynMemberDefn.Member(synBinding, _range) -> traverseSynBinding path synBinding - | SynMemberDefn.ImplicitCtor(_synAccessOption, _synAttributes, synSimplePatList, _identOption, _range) -> - visitor.VisitSimplePats(synSimplePatList) + | SynMemberDefn.ImplicitCtor(_synAccessOption, _synAttributes, simplePats, _identOption, _range) -> + match simplePats with + | SynSimplePats.SimplePats(simplePats, _) -> visitor.VisitSimplePats(simplePats) + | _ -> None | SynMemberDefn.ImplicitInherit(synType, synExpr, _identOption, range) -> [ dive () synType.Range (fun () -> @@ -661,7 +671,7 @@ module public AstTraversal = visitor.VisitBinding(defaultTraverse,b) match parseTree with - | ParsedInput.ImplFile(ParsedImplFileInput(_,_,_,_,_,l,_))-> + | ParsedInput.ImplFile (ParsedImplFileInput (_,_,_,_,_,l,_))-> let fileRange = #if DEBUG match l with [] -> range0 | _ -> l |> List.map (fun x -> x.Range) |> List.reduce unionRanges diff --git a/src/fcs-fable/src/fsharp/service/ServiceStructure.fs b/src/fcs-fable/src/fsharp/service/ServiceStructure.fs index e235b90a69..9fede9a955 100644 --- a/src/fcs-fable/src/fsharp/service/ServiceStructure.fs +++ b/src/fcs-fable/src/fsharp/service/ServiceStructure.fs @@ -2,16 +2,19 @@ namespace FSharp.Compiler.SourceCodeServices -open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.Ast open FSharp.Compiler +open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps module Structure = + /// Set of visitor utilities, designed for the express purpose of fetching ranges /// from an untyped AST for the purposes of block structure. [] module Range = + /// Create a range starting at the end of r1 and finishing at the end of r2 let endToEnd (r1: range) (r2: range) = mkFileIndexRange r1.FileIndex r1.End r2.End @@ -34,7 +37,6 @@ module Structure = let modend = mkPos r.EndLine (r.EndColumn+m) mkFileIndexRange r.FileIndex r.Start modend - /// Produce a new range by adding modStart to the StartColumn of `r` /// and subtracting modEnd from the EndColumn of `r` let modBoth modStart modEnd (r:range) = @@ -45,9 +47,9 @@ module Structure = let longIdentRange (longId:LongIdent) = match longId with | [] -> range0 - | head::_ -> Range.startToEnd head.idRange (List.last longId).idRange + | head :: _ -> Range.startToEnd head.idRange (List.last longId).idRange - /// Caclulate the range of the provided type arguments (<'a, ..., 'z>) + /// Calculate the range of the provided type arguments (<'a, ..., 'z>) /// or return the range `other` when `typeArgs` = [] let rangeOfTypeArgsElse other (typeArgs:SynTyparDecl list) = match typeArgs with @@ -77,7 +79,7 @@ module Structure = | Below | Same - /// Tag to identify the constuct that can be stored alongside its associated ranges + /// Tag to identify the construct that can be stored alongside its associated ranges [] type Scope = | Open @@ -127,6 +129,7 @@ module Structure = | UnionDefn | Comment | XmlDocComment + override self.ToString() = match self with | Open -> "Open" @@ -177,7 +180,7 @@ module Structure = | Comment -> "Comment" | XmlDocComment -> "XmlDocComment" - /// Stores the range for a construct, the sub-range that should be collapsed for outlinging, + /// Stores the range for a construct, the sub-range that should be collapsed for outlining, /// a tag for the construct type, and a tag for the collapse style [] type ScopeRange = @@ -204,7 +207,7 @@ module Structure = let getOutliningRanges (sourceLines: string[]) (parsedInput: ParsedInput) = let acc = ResizeArray() - /// Validation function to ensure that ranges yielded for outlinging span 2 or more lines + /// Validation function to ensure that ranges yielded for outlining span 2 or more lines let inline rcheck scope collapse (fullRange: range) (collapseRange: range) = if fullRange.StartLine <> fullRange.EndLine then acc.Add { Scope = scope @@ -220,7 +223,7 @@ module Structure = match expression with | SynExpr.Upcast (e, _, _) | SynExpr.Downcast (e, _, _) - | SynExpr.AddressOf(_, e, _, _) + | SynExpr.AddressOf (_, e, _, _) | SynExpr.InferredDowncast (e, _) | SynExpr.InferredUpcast (e, _) | SynExpr.DotGet (e, _, _, _) @@ -245,14 +248,21 @@ module Structure = | SynExpr.DoBang (e, r) -> rcheck Scope.Do Collapse.Below r <| Range.modStart 3 r parseExpr e - | SynExpr.LetOrUseBang (_, _, _, pat, e1, e2, _) -> - // for `let!` or `use!` the pattern begins at the end of the keyword so that - // this scope can be used without adjustment if there is no `=` on the same line - // if there is an `=` the range will be adjusted during the tooltip creation - let r = Range.endToEnd pat.Range e1.Range - rcheck Scope.LetOrUseBang Collapse.Below r r - parseExpr e1 - parseExpr e2 + | SynExpr.LetOrUseBang (_, _, _, pat, eLet, es, eBody, _) -> + [ + yield eLet + yield! [ for (_,_,_,_,eAndBang,_) in es do yield eAndBang ] + ] + |> List.iter (fun e -> + // for `let!`, `use!` or `and!` the pattern begins at the end of the + // keyword so that this scope can be used without adjustment if there is no `=` + // on the same line. If there is an `=` the range will be adjusted during the + // tooltip creation + let r = Range.endToEnd pat.Range e.Range + rcheck Scope.LetOrUseBang Collapse.Below r r + parseExpr e + ) + parseExpr eBody | SynExpr.For (_, _, _, _, _, e, r) | SynExpr.ForEach (_, _, _, _, _, e, r) -> rcheck Scope.For Collapse.Below r r @@ -263,7 +273,7 @@ module Structure = | SynExpr.Match (seqPointAtBinding, _expr, clauses, r) | SynExpr.MatchBang (seqPointAtBinding, _expr, clauses, r) -> match seqPointAtBinding with - | SequencePointAtBinding sr -> + | DebugPointAtBinding sr -> let collapse = Range.endToEnd sr r rcheck Scope.Match Collapse.Same r collapse | _ -> () @@ -271,7 +281,7 @@ module Structure = | SynExpr.MatchLambda (_, caseRange, clauses, matchSeqPoint, r) -> let caseRange = match matchSeqPoint with - | SequencePointAtBinding r -> r + | DebugPointAtBinding r -> r | _ -> caseRange let collapse = Range.endToEnd caseRange r rcheck Scope.MatchLambda Collapse.Same r collapse @@ -281,7 +291,7 @@ module Structure = if ExprAtomicFlag.NonAtomic=atomicFlag && (not isInfix) && (function SynExpr.Ident _ -> true | _ -> false) funcExpr && (function SynExpr.CompExpr _ -> false | _ -> true ) argExpr then - // if the argExrp is a computation expression another match will handle the outlining + // if the argExpr is a computation expression another match will handle the outlining // these cases must be removed to prevent creating unnecessary tags for the same scope let collapse = Range.endToEnd funcExpr.Range r rcheck Scope.SpecialFunc Collapse.Below r collapse @@ -311,7 +321,7 @@ module Structure = parseExprInterfaces extraImpls | SynExpr.TryWith (e, _, matchClauses, _, wholeRange, tryPoint, withPoint) -> match tryPoint, withPoint with - | SequencePointAtTry tryRange, SequencePointAtWith withRange -> + | DebugPointAtTry.Yes tryRange, DebugPointAtWith.Yes withRange -> let fullrange = Range.startToEnd tryRange wholeRange let collapse = Range.endToEnd tryRange wholeRange let collapseTry = Range.endToStart tryRange withRange @@ -326,7 +336,7 @@ module Structure = List.iter parseMatchClause matchClauses | SynExpr.TryFinally (tryExpr, finallyExpr, r, tryPoint, finallyPoint) -> match tryPoint, finallyPoint with - | SequencePointAtTry tryRange, SequencePointAtFinally finallyRange -> + | DebugPointAtTry.Yes tryRange, DebugPointAtFinally.Yes finallyRange -> let collapse = Range.endToEnd tryRange finallyExpr.Range let fullrange = Range.startToEnd tryRange finallyExpr.Range let collapseFinally = Range.endToEnd finallyRange r @@ -338,7 +348,7 @@ module Structure = parseExpr finallyExpr | SynExpr.IfThenElse (ifExpr, thenExpr, elseExprOpt, spIfToThen, _, ifToThenRange, r) -> match spIfToThen with - | SequencePointAtBinding rt -> + | DebugPointAtBinding rt -> // Outline the entire IfThenElse let fullrange = Range.startToEnd rt r let collapse = Range.endToEnd ifExpr.Range r @@ -405,7 +415,7 @@ module Structure = rcheck Scope.MatchClause Collapse.Same e.Range collapse parseExpr e - and parseAttributes (attrs: SynAttributes) = + and parseAttributes (Attributes attrs) = let attrListRange() = if not (List.isEmpty attrs) then let range = Range.startToEnd (attrs.[0].Range) (attrs.[attrs.Length-1].ArgExpr.Range) @@ -456,7 +466,7 @@ module Structure = and parseSynMemberDefn (objectModelRange: range) d = match d with - | SynMemberDefn.Member(SynBinding.Binding (attrs=attrs; valData=valData; headPat=synPat; range=bindingRange) as binding, _) -> + | SynMemberDefn.Member(SynBinding.Binding (attributes=attrs; valData=valData; headPat=synPat; range=bindingRange) as binding, _) -> match valData with | SynValData (Some { MemberKind=MemberKind.Constructor }, _, _) -> let collapse = Range.endToEnd synPat.Range d.Range @@ -543,18 +553,18 @@ module Structure = List.iter (parseSynMemberDefn r) members | SynTypeDefnRepr.Exception _ -> () - let getConsecutiveModuleDecls (predicate: SynModuleDecl -> range option) (scope: Scope) (decls: SynModuleDecls) = + let getConsecutiveModuleDecls (predicate: SynModuleDecl -> range option) (scope: Scope) (decls: SynModuleDecl list) = let groupConsecutiveDecls input = let rec loop (input: range list) (res: range list list) currentBulk = match input, currentBulk with | [], [] -> List.rev res - | [], _ -> List.rev (currentBulk::res) + | [], _ -> List.rev (currentBulk :: res) | r :: rest, [] -> loop rest res [r] | r :: rest, last :: _ when r.StartLine = last.EndLine + 1 || sourceLines.[last.EndLine..r.StartLine - 2] |> Array.forall System.String.IsNullOrWhiteSpace -> - loop rest res (r::currentBulk) - | r :: rest, _ -> loop rest (currentBulk::res) [r] + loop rest res (r :: currentBulk) + | r :: rest, _ -> loop rest (currentBulk :: res) [r] loop input [] [] let selectRanges (ranges: range list) = @@ -624,7 +634,7 @@ module Structure = collectOpens decls List.iter parseDeclaration decls - /// Determine if a line is a single line or xml docummentation comment + /// Determine if a line is a single line or xml documentation comment let (|Comment|_|) (line: string) = if line.StartsWithOrdinal("///") then Some XmlDoc elif line.StartsWithOrdinal("//") then Some SingleLine @@ -711,7 +721,7 @@ module Structure = let (TypeDefnSig(_, _, memberSigs, r)) = List.last ls lastMemberSigRangeElse r memberSigs - let lastModuleSigDeclRangeElse range (sigDecls:SynModuleSigDecls) = + let lastModuleSigDeclRangeElse range (sigDecls:SynModuleSigDecl list) = match sigDecls with | [] -> range | ls -> @@ -771,16 +781,16 @@ module Structure = parseSimpleRepr simpleRepr | SynTypeDefnSigRepr.Exception _ -> () - let getConsecutiveSigModuleDecls (predicate: SynModuleSigDecl -> range option) (scope:Scope) (decls: SynModuleSigDecls) = + let getConsecutiveSigModuleDecls (predicate: SynModuleSigDecl -> range option) (scope:Scope) (decls: SynModuleSigDecl list) = let groupConsecutiveSigDecls input = let rec loop (input: range list) (res: range list list) currentBulk = match input, currentBulk with | [], [] -> List.rev res - | [], _ -> List.rev (currentBulk::res) + | [], _ -> List.rev (currentBulk :: res) | r :: rest, [] -> loop rest res [r] | r :: rest, last :: _ when r.StartLine = last.EndLine + 1 -> - loop rest res (r::currentBulk) - | r :: rest, _ -> loop rest (currentBulk::res) [r] + loop rest res (r :: currentBulk) + | r :: rest, _ -> loop rest (currentBulk :: res) [r] loop input [] [] let selectSigRanges (ranges: range list) = @@ -801,7 +811,7 @@ module Structure = |> List.choose selectSigRanges |> acc.AddRange - let collectSigHashDirectives (decls: SynModuleSigDecls) = + let collectSigHashDirectives (decls: SynModuleSigDecl list) = decls |> getConsecutiveSigModuleDecls( function diff --git a/src/fcs-fable/src/fsharp/service/ServiceStructure.fsi b/src/fcs-fable/src/fsharp/service/ServiceStructure.fsi index ef90f4627e..6d26607e7a 100644 --- a/src/fcs-fable/src/fsharp/service/ServiceStructure.fsi +++ b/src/fcs-fable/src/fsharp/service/ServiceStructure.fsi @@ -2,8 +2,8 @@ namespace FSharp.Compiler.SourceCodeServices -open FSharp.Compiler.Ast open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree module public Structure = @@ -15,7 +15,7 @@ module public Structure = | Below | Same - /// Tag to identify the constuct that can be stored alongside its associated ranges + /// Tag to identify the construct that can be stored alongside its associated ranges [] type Scope = | Open diff --git a/src/fcs-fable/src/fsharp/service/ServiceUntypedParse.fs b/src/fcs-fable/src/fsharp/service/ServiceUntypedParse.fs index 0bbdf9503d..41a17c50c6 100755 --- a/src/fcs-fable/src/fsharp/service/ServiceUntypedParse.fs +++ b/src/fcs-fable/src/fsharp/service/ServiceUntypedParse.fs @@ -11,33 +11,38 @@ open System open System.IO open System.Collections.Generic open System.Diagnostics +open System.Text.RegularExpressions open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler -open FSharp.Compiler.Range -open FSharp.Compiler.Ast -open FSharp.Compiler.ErrorLogger open FSharp.Compiler.CompileOps open FSharp.Compiler.Lib +open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps /// Methods for dealing with F# sources files. module SourceFile = + /// Source file extensions - let private compilableExtensions = CompileOps.FSharpSigFileSuffixes @ CompileOps.FSharpImplFileSuffixes @ CompileOps.FSharpScriptFileSuffixes + let private compilableExtensions = FSharpSigFileSuffixes @ FSharpImplFileSuffixes @ FSharpScriptFileSuffixes + /// Single file projects extensions - let private singleFileProjectExtensions = CompileOps.FSharpScriptFileSuffixes + let private singleFileProjectExtensions = FSharpScriptFileSuffixes + /// Whether or not this file is compilable let IsCompilable file = - let ext = Path.GetExtension(file) + let ext = Path.GetExtension file compilableExtensions |> List.exists(fun e->0 = String.Compare(e, ext, StringComparison.OrdinalIgnoreCase)) + /// Whether or not this file should be a single-file project let MustBeSingleFileProject file = - let ext = Path.GetExtension(file) + let ext = Path.GetExtension file singleFileProjectExtensions |> List.exists(fun e-> 0 = String.Compare(e, ext, StringComparison.OrdinalIgnoreCase)) module SourceFileImpl = let IsInterfaceFile file = - let ext = Path.GetExtension(file) + let ext = Path.GetExtension file 0 = String.Compare(".fsi", ext, StringComparison.OrdinalIgnoreCase) /// Additional #defines that should be in place when editing a file in a file editor such as VS. @@ -87,7 +92,7 @@ type CompletionContext = //---------------------------------------------------------------------------- [] -type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput option, parseHadErrors: bool, dependencyFiles: string[]) = +type FSharpParseFileResults(errors: FSharpErrorInfo[], input: ParsedInput option, parseHadErrors: bool, dependencyFiles: string[]) = member scope.Errors = errors @@ -95,50 +100,50 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput op member scope.ParseTree = input - member scope.FindNoteworthyParamInfoLocations(pos) = + member scope.FindNoteworthyParamInfoLocations pos = match input with - | Some(input) -> FSharpNoteworthyParamInfoLocations.Find(pos, input) + | Some input -> FSharpNoteworthyParamInfoLocations.Find(pos, input) | _ -> None /// Get declared items and the selected item at the specified location member private scope.GetNavigationItemsImpl() = - ErrorScope.Protect Range.range0 + ErrorScope.Protect range0 (fun () -> match input with - | Some(ParsedInput.ImplFile(ParsedImplFileInput(modules = modules))) -> - NavigationImpl.getNavigationFromImplFile modules - | Some(ParsedInput.SigFile(ParsedSigFileInput _)) -> - NavigationImpl.empty + | Some (ParsedInput.ImplFile _ as p) -> + FSharpNavigation.getNavigation p + | Some (ParsedInput.SigFile _) -> + FSharpNavigation.empty | _ -> - NavigationImpl.empty ) + FSharpNavigation.empty) (fun err -> Trace.TraceInformation(sprintf "FCS: recovering from error in GetNavigationItemsImpl: '%s'" err) - NavigationImpl.empty) + FSharpNavigation.empty) - member private scope.ValidateBreakpointLocationImpl(pos) = + member private scope.ValidateBreakpointLocationImpl pos = let isMatchRange m = rangeContainsPos m pos || m.StartLine = pos.Line // Process let-binding let findBreakPoints () = let checkRange m = [ if isMatchRange m then yield m ] - let walkBindSeqPt sp = [ match sp with SequencePointAtBinding m -> yield! checkRange m | _ -> () ] - let walkForSeqPt sp = [ match sp with SequencePointAtForLoop m -> yield! checkRange m | _ -> () ] - let walkWhileSeqPt sp = [ match sp with SequencePointAtWhileLoop m -> yield! checkRange m | _ -> () ] - let walkTrySeqPt sp = [ match sp with SequencePointAtTry m -> yield! checkRange m | _ -> () ] - let walkWithSeqPt sp = [ match sp with SequencePointAtWith m -> yield! checkRange m | _ -> () ] - let walkFinallySeqPt sp = [ match sp with SequencePointAtFinally m -> yield! checkRange m | _ -> () ] + let walkBindSeqPt sp = [ match sp with DebugPointAtBinding m -> yield! checkRange m | _ -> () ] + let walkForSeqPt sp = [ match sp with DebugPointAtFor.Yes m -> yield! checkRange m | _ -> () ] + let walkWhileSeqPt sp = [ match sp with DebugPointAtWhile.Yes m -> yield! checkRange m | _ -> () ] + let walkTrySeqPt sp = [ match sp with DebugPointAtTry.Yes m -> yield! checkRange m | _ -> () ] + let walkWithSeqPt sp = [ match sp with DebugPointAtWith.Yes m -> yield! checkRange m | _ -> () ] + let walkFinallySeqPt sp = [ match sp with DebugPointAtFinally.Yes m -> yield! checkRange m | _ -> () ] let rec walkBind (Binding(_, _, _, _, _, _, SynValData(memFlagsOpt, _, _), synPat, _, synExpr, _, spInfo)) = [ // Don't yield the binding sequence point if there are any arguments, i.e. we're defining a function or a method let isFunction = Option.isSome memFlagsOpt || match synPat with - | SynPat.LongIdent (_, _, _, SynConstructorArgs.Pats args, _, _) when not (List.isEmpty args) -> true + | SynPat.LongIdent (_, _, _, SynArgPats.Pats args, _, _) when not (List.isEmpty args) -> true | _ -> false if not isFunction then yield! walkBindSeqPt spInfo - yield! walkExpr (isFunction || (match spInfo with SequencePointAtBinding _ -> false | _-> true)) synExpr ] + yield! walkExpr (isFunction || (match spInfo with DebugPointAtBinding _ -> false | _-> true)) synExpr ] and walkExprs es = List.collect (walkExpr false) es and walkBinds es = List.collect walkBind es @@ -179,7 +184,7 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput op | SynExpr.Const _ -> () - | SynExpr.Quote(_, _, e, _, _) + | SynExpr.Quote (_, _, e, _, _) | SynExpr.TypeTest (e, _, _) | SynExpr.Upcast (e, _, _) | SynExpr.AddressOf (_, e, _, _) @@ -200,8 +205,8 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput op | SynExpr.InferredUpcast (e, _) | SynExpr.InferredDowncast (e, _) | SynExpr.Lazy (e, _) - | SynExpr.TraitCall(_, _, e, _) - | SynExpr.Paren(e, _, _, _) -> + | SynExpr.TraitCall (_, _, e, _) + | SynExpr.Paren (e, _, _, _) -> yield! walkExpr false e | SynExpr.YieldOrReturn (_, e, _) @@ -246,7 +251,7 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput op yield! walkExpr false e1 yield! walkExpr true e2 - | SynExpr.JoinIn(e1, _range, e2, _range2) -> + | SynExpr.JoinIn (e1, _range, e2, _range2) -> yield! walkExpr false e1 yield! walkExpr false e2 @@ -261,7 +266,7 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput op yield! walkExpr false e1 yield! walkExpr true e2 - | SynExpr.MatchLambda(_isExnMatch, _argm, cl, spBind, _wholem) -> + | SynExpr.MatchLambda (_isExnMatch, _argm, cl, spBind, _wholem) -> yield! walkBindSeqPt spBind for (Clause(_, whenExpr, e, _, _)) in cl do yield! walkExprOpt false whenExpr @@ -293,9 +298,10 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput op yield! walkTrySeqPt spTry yield! walkFinallySeqPt spFinally + | SynExpr.SequentialOrImplicitYield (spSeq, e1, e2, _, _) | SynExpr.Sequential (spSeq, _, e1, e2, _) -> - yield! walkExpr (match spSeq with SuppressSequencePointOnStmtOfSequential -> false | _ -> true) e1 - yield! walkExpr (match spSeq with SuppressSequencePointOnExprOfSequential -> false | _ -> true) e2 + yield! walkExpr (match spSeq with DebugPointAtSequential.ExprOnly -> false | _ -> true) e1 + yield! walkExpr (match spSeq with DebugPointAtSequential.StmtOnly -> false | _ -> true) e2 | SynExpr.IfThenElse (e1, e2, e3opt, spBind, _, _, _) -> yield! walkBindSeqPt spBind @@ -317,9 +323,12 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput op yield! walkExpr false e2 yield! walkExpr false e3 - | SynExpr.LetOrUseBang (spBind, _, _, _, e1, e2, _) -> + | SynExpr.LetOrUseBang (spBind, _, _, _, e1, es, e2, _) -> yield! walkBindSeqPt spBind yield! walkExpr true e1 + for (andBangSpBind,_,_,_,eAndBang,_) in es do + yield! walkBindSeqPt andBangSpBind + yield! walkExpr true eAndBang yield! walkExpr true e2 | SynExpr.MatchBang (spBind, e, cl, _) -> @@ -346,7 +355,7 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput op | SynMemberDefn.AutoProperty(_attribs, _isStatic, _id, _tyOpt, _propKind, _, _xmlDoc, _access, synExpr, _, _) -> yield! walkExpr true synExpr | SynMemberDefn.ImplicitCtor(_, _, _, _, m) -> yield! checkRange m | SynMemberDefn.Member(bind, _) -> yield! walkBind bind - | SynMemberDefn.Interface(_synty, Some(membs), _) -> for m in membs do yield! walkMember m + | SynMemberDefn.Interface(_synty, Some membs, _) -> for m in membs do yield! walkMember m | SynMemberDefn.Inherit(_, _, m) -> // can break on the "inherit" clause yield! checkRange m @@ -386,10 +395,10 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput op let walkImplFile (modules: SynModuleOrNamespace list) = List.collect walkModule modules match input with - | Some(ParsedInput.ImplFile(ParsedImplFileInput(modules = modules))) -> walkImplFile modules + | Some (ParsedInput.ImplFile (ParsedImplFileInput (modules = modules))) -> walkImplFile modules | _ -> [] - ErrorScope.Protect Range.range0 + ErrorScope.Protect range0 (fun () -> let locations = findBreakPoints() @@ -420,8 +429,8 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput op member scope.FileName = match input with - | Some(ParsedInput.ImplFile(ParsedImplFileInput(fileName = modname))) - | Some(ParsedInput.SigFile(ParsedSigFileInput(fileName = modname))) -> modname + | Some (ParsedInput.ImplFile (ParsedImplFileInput (fileName = modname))) + | Some (ParsedInput.SigFile (ParsedSigFileInput (fileName = modname))) -> modname | _ -> "" // Get items for the navigation drop down bar @@ -429,9 +438,9 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput op // This does not need to be run on the background thread scope.GetNavigationItemsImpl() - member scope.ValidateBreakpointLocation(pos) = + member scope.ValidateBreakpointLocation pos = // This does not need to be run on the background thread - scope.ValidateBreakpointLocationImpl(pos) + scope.ValidateBreakpointLocationImpl pos type ModuleKind = { IsAutoOpen: bool; HasModuleSuffix: bool } @@ -444,15 +453,13 @@ type EntityKind = override x.ToString() = sprintf "%A" x module UntypedParseImpl = - open System.Text.RegularExpressions - open FSharp.Compiler.PrettyNaming let emptyStringSet = HashSet() let GetRangeOfExprLeftOfDot(pos: pos, parseTreeOpt) = match parseTreeOpt with | None -> None - | Some(parseTree) -> + | Some parseTree -> let CheckLongIdent(longIdent: LongIdent) = // find the longest prefix before the "pos" dot let mutable r = (List.head longIdent).idRange @@ -467,49 +474,49 @@ module UntypedParseImpl = member this.VisitExpr(_path, traverseSynExpr, defaultTraverse, expr) = let expr = expr // fix debugger locals match expr with - | SynExpr.LongIdent(_, LongIdentWithDots(longIdent, _), _altNameRefCell, _range) -> - let _, r = CheckLongIdent(longIdent) - Some(r) - | SynExpr.LongIdentSet(LongIdentWithDots(longIdent, _), synExpr, _range) -> + | SynExpr.LongIdent (_, LongIdentWithDots(longIdent, _), _altNameRefCell, _range) -> + let _, r = CheckLongIdent longIdent + Some r + | SynExpr.LongIdentSet (LongIdentWithDots(longIdent, _), synExpr, _range) -> if AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then traverseSynExpr synExpr else - let _, r = CheckLongIdent(longIdent) - Some(r) - | SynExpr.DotGet(synExpr, _dotm, LongIdentWithDots(longIdent, _), _range) -> + let _, r = CheckLongIdent longIdent + Some r + | SynExpr.DotGet (synExpr, _dotm, LongIdentWithDots(longIdent, _), _range) -> if AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then traverseSynExpr synExpr else - let inFront, r = CheckLongIdent(longIdent) + let inFront, r = CheckLongIdent longIdent if inFront then - Some(synExpr.Range) + Some (synExpr.Range) else // see comment below for SynExpr.DotSet - Some((unionRanges synExpr.Range r)) - | SynExpr.Set(synExpr, synExpr2, range) -> + Some ((unionRanges synExpr.Range r)) + | SynExpr.Set (synExpr, synExpr2, range) -> if AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then traverseSynExpr synExpr elif AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr2.Range pos then traverseSynExpr synExpr2 else - Some(range) - | SynExpr.DotSet(synExpr, LongIdentWithDots(longIdent, _), synExpr2, _range) -> + Some range + | SynExpr.DotSet (synExpr, LongIdentWithDots(longIdent, _), synExpr2, _range) -> if AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then traverseSynExpr synExpr elif AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr2.Range pos then traverseSynExpr synExpr2 else - let inFront, r = CheckLongIdent(longIdent) + let inFront, r = CheckLongIdent longIdent if inFront then - Some(synExpr.Range) + Some (synExpr.Range) else // f(0).X.Y.Z // ^ // - r has this value // ---- synExpr.Range has this value // ------ we want this value - Some((unionRanges synExpr.Range r)) - | SynExpr.DotNamedIndexedPropertySet(synExpr, LongIdentWithDots(longIdent, _), synExpr2, synExpr3, _range) -> + Some ((unionRanges synExpr.Range r)) + | SynExpr.DotNamedIndexedPropertySet (synExpr, LongIdentWithDots(longIdent, _), synExpr2, synExpr3, _range) -> if AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then traverseSynExpr synExpr elif AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr2.Range pos then @@ -517,31 +524,31 @@ module UntypedParseImpl = elif AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr3.Range pos then traverseSynExpr synExpr3 else - let inFront, r = CheckLongIdent(longIdent) + let inFront, r = CheckLongIdent longIdent if inFront then - Some(synExpr.Range) + Some (synExpr.Range) else - Some((unionRanges synExpr.Range r)) - | SynExpr.DiscardAfterMissingQualificationAfterDot(synExpr, _range) -> // get this for e.g. "bar()." + Some ((unionRanges synExpr.Range r)) + | SynExpr.DiscardAfterMissingQualificationAfterDot (synExpr, _range) -> // get this for e.g. "bar()." if AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then traverseSynExpr synExpr else - Some(synExpr.Range) - | SynExpr.FromParseError(synExpr, range) -> + Some (synExpr.Range) + | SynExpr.FromParseError (synExpr, range) -> if AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then traverseSynExpr synExpr else - Some(range) - | SynExpr.App(ExprAtomicFlag.NonAtomic, true, (SynExpr.Ident(ident)), rhs, _) + Some range + | SynExpr.App (ExprAtomicFlag.NonAtomic, true, (SynExpr.Ident ident), rhs, _) when ident.idText = "op_ArrayLookup" && not(AstTraversal.rangeContainsPosLeftEdgeInclusive rhs.Range pos) -> match defaultTraverse expr with | None -> // (expr).(expr) is an ML-deprecated array lookup, but we want intellisense on the dot // also want it for e.g. [|arr|].(0) - Some(expr.Range) + Some (expr.Range) | x -> x // we found the answer deeper somewhere in the lhs - | SynExpr.Const(SynConst.Double(_), range) -> Some(range) + | SynExpr.Const (SynConst.Double(_), range) -> Some range | _ -> defaultTraverse expr }) @@ -549,7 +556,7 @@ module UntypedParseImpl = let TryFindExpressionIslandInPosition(pos: pos, parseTreeOpt) = match parseTreeOpt with | None -> None - | Some(parseTree) -> + | Some parseTree -> let getLidParts (lid : LongIdent) = lid |> Seq.takeWhile (fun i -> posGeq pos i.idRange.Start) @@ -561,11 +568,11 @@ module UntypedParseImpl = // foundCandidate = true - we found candidate (DotGet) and now drill down to the left part let rec TryGetExpression foundCandidate expr = match expr with - | SynExpr.Paren(e, _, _, _) when foundCandidate -> + | SynExpr.Paren (e, _, _, _) when foundCandidate -> TryGetExpression foundCandidate e - | SynExpr.LongIdent(_isOptional, LongIdentWithDots(lid, _), _altNameRefCell, _m) -> + | SynExpr.LongIdent (_isOptional, LongIdentWithDots(lid, _), _altNameRefCell, _m) -> getLidParts lid |> Some - | SynExpr.DotGet(leftPart, _, LongIdentWithDots(lid, _), _) when (rangeContainsPos (rangeOfLid lid) pos) || foundCandidate -> + | SynExpr.DotGet (leftPart, _, LongIdentWithDots(lid, _), _) when (rangeContainsPos (rangeOfLid lid) pos) || foundCandidate -> // requested position is at the lid part of the DotGet // process left part and append result to the result of processing lid let leftPartResult = TryGetExpression true leftPart @@ -576,7 +583,7 @@ module UntypedParseImpl = yield! getLidParts lid ] |> Some | None -> None - | SynExpr.FromParseError(synExpr, _range) -> TryGetExpression foundCandidate synExpr + | SynExpr.FromParseError (synExpr, _range) -> TryGetExpression foundCandidate synExpr | _ -> None let rec walker = @@ -585,18 +592,18 @@ module UntypedParseImpl = if rangeContainsPos expr.Range pos then match TryGetExpression false expr with | (Some parts) -> parts |> String.concat "." |> Some - | _ -> defaultTraverse(expr) + | _ -> defaultTraverse expr else None } AstTraversal.Traverse(pos, parseTree, walker) // Given a cursor position here: - // f(x) . iden + // f(x) . ident // ^ // walk the AST to find the position here: - // f(x) . iden + // f(x) . ident // ^ - // On success, return Some(thatPos, boolTrueIfCursorIsAfterTheDotButBeforeTheIdentifier) + // On success, return Some (thatPos, boolTrueIfCursorIsAfterTheDotButBeforeTheIdentifier) // If there's no dot, return None, so for example // foo // ^ @@ -605,7 +612,7 @@ module UntypedParseImpl = let TryFindExpressionASTLeftOfDotLeftOfCursor(pos, parseTreeOpt) = match parseTreeOpt with | None -> None - | Some(parseTree) -> + | Some parseTree -> let dive x = AstTraversal.dive x let pick x = AstTraversal.pick pos x let walker = @@ -615,12 +622,12 @@ module UntypedParseImpl = let traverseSynExpr, defaultTraverse, expr = traverseSynExpr, defaultTraverse, expr // for debugging: debugger does not get object expression params as local vars if not(rangeContainsPos expr.Range pos) then match expr with - | SynExpr.DiscardAfterMissingQualificationAfterDot(e, _m) -> + | SynExpr.DiscardAfterMissingQualificationAfterDot (e, _m) -> // This happens with e.g. "f(x) . $" when you bring up a completion list a few spaces after a dot. The cursor is not 'in the parse tree', // but the dive algorithm will dive down into this node, and this is the one case where we do want to give a result despite the cursor // not properly being in a node. - match traverseSynExpr(e) with - | None -> Some(e.Range.End, false) + match traverseSynExpr e with + | None -> Some (e.Range.End, false) | r -> r | _ -> // This happens for e.g. "System.Console.[]$", where the ".[]" token is thrown away by the parser and we dive into the System.Console longId @@ -632,39 +639,39 @@ module UntypedParseImpl = let resultIfLeftOfLongId = match optExprIfLeftOfLongId with | None -> None - | Some e -> Some(e.Range.End, posGeq lidwd.Range.Start pos) + | Some e -> Some (e.Range.End, posGeq lidwd.Range.Start pos) match dots |> List.mapi (fun i x -> i, x) |> List.rev |> List.tryFind (fun (_, m) -> posGt pos m.Start) with | None -> resultIfLeftOfLongId - | Some(n, _) -> Some((List.item n lid).idRange.End, (List.length lid = n+1) // foo.$ + | Some (n, _) -> Some ((List.item n lid).idRange.End, (List.length lid = n+1) // foo.$ || (posGeq (List.item (n+1) lid).idRange.Start pos)) // foo.$bar match expr with - | SynExpr.LongIdent(_isOptional, lidwd, _altNameRefCell, _m) -> + | SynExpr.LongIdent (_isOptional, lidwd, _altNameRefCell, _m) -> traverseLidOrElse None lidwd - | SynExpr.LongIdentSet(lidwd, exprRhs, _m) -> + | SynExpr.LongIdentSet (lidwd, exprRhs, _m) -> [ dive lidwd lidwd.Range (traverseLidOrElse None) dive exprRhs exprRhs.Range traverseSynExpr ] |> pick expr - | SynExpr.DotGet(exprLeft, dotm, lidwd, _m) -> + | SynExpr.DotGet (exprLeft, dotm, lidwd, _m) -> let afterDotBeforeLid = mkRange dotm.FileName dotm.End lidwd.Range.Start [ dive exprLeft exprLeft.Range traverseSynExpr - dive exprLeft afterDotBeforeLid (fun e -> Some(e.Range.End, true)) + dive exprLeft afterDotBeforeLid (fun e -> Some (e.Range.End, true)) dive lidwd lidwd.Range (traverseLidOrElse (Some exprLeft)) ] |> pick expr - | SynExpr.DotSet(exprLeft, lidwd, exprRhs, _m) -> + | SynExpr.DotSet (exprLeft, lidwd, exprRhs, _m) -> [ dive exprLeft exprLeft.Range traverseSynExpr dive lidwd lidwd.Range (traverseLidOrElse(Some exprLeft)) dive exprRhs exprRhs.Range traverseSynExpr ] |> pick expr - | SynExpr.Set(exprLeft, exprRhs, _m) -> + | SynExpr.Set (exprLeft, exprRhs, _m) -> [ dive exprLeft exprLeft.Range traverseSynExpr dive exprRhs exprRhs.Range traverseSynExpr ] |> pick expr - | SynExpr.NamedIndexedPropertySet(lidwd, exprIndexer, exprRhs, _m) -> + | SynExpr.NamedIndexedPropertySet (lidwd, exprIndexer, exprRhs, _m) -> [ dive lidwd lidwd.Range (traverseLidOrElse None) dive exprIndexer exprIndexer.Range traverseSynExpr dive exprRhs exprRhs.Range traverseSynExpr ] |> pick expr - | SynExpr.DotNamedIndexedPropertySet(exprLeft, lidwd, exprIndexer, exprRhs, _m) -> + | SynExpr.DotNamedIndexedPropertySet (exprLeft, lidwd, exprIndexer, exprRhs, _m) -> [ dive exprLeft exprLeft.Range traverseSynExpr dive lidwd lidwd.Range (traverseLidOrElse(Some exprLeft)) dive exprIndexer exprIndexer.Range traverseSynExpr @@ -673,30 +680,30 @@ module UntypedParseImpl = | SynExpr.Const (SynConst.Double(_), m) -> if posEq m.End pos then // the cursor is at the dot - Some(m.End, false) + Some (m.End, false) else // the cursor is left of the dot None - | SynExpr.DiscardAfterMissingQualificationAfterDot(e, m) -> - match traverseSynExpr(e) with + | SynExpr.DiscardAfterMissingQualificationAfterDot (e, m) -> + match traverseSynExpr e with | None -> if posEq m.End pos then // the cursor is at the dot - Some(e.Range.End, false) + Some (e.Range.End, false) else // the cursor is left of the dot None | r -> r - | SynExpr.App(ExprAtomicFlag.NonAtomic, true, (SynExpr.Ident(ident)), lhs, _m) + | SynExpr.App (ExprAtomicFlag.NonAtomic, true, (SynExpr.Ident ident), lhs, _m) when ident.idText = "op_ArrayLookup" && not(AstTraversal.rangeContainsPosLeftEdgeInclusive lhs.Range pos) -> match defaultTraverse expr with | None -> // (expr).(expr) is an ML-deprecated array lookup, but we want intellisense on the dot // also want it for e.g. [|arr|].(0) - Some(lhs.Range.End, false) + Some (lhs.Range.End, false) | x -> x // we found the answer deeper somewhere in the lhs - | _ -> defaultTraverse(expr) } + | _ -> defaultTraverse expr } AstTraversal.Traverse(pos, parseTree, walker) let GetEntityKind (pos: pos, input: ParsedInput) : EntityKind option = @@ -706,20 +713,20 @@ module UntypedParseImpl = /// An recursive pattern that collect all sequential expressions to avoid StackOverflowException let rec (|Sequentials|_|) = function - | SynExpr.Sequential(_, _, e, Sequentials es, _) -> Some(e::es) - | SynExpr.Sequential(_, _, e1, e2, _) -> Some [e1; e2] + | SynExpr.Sequential (_, _, e, Sequentials es, _) -> Some (e :: es) + | SynExpr.Sequential (_, _, e1, e2, _) -> Some [e1; e2] | _ -> None - let inline isPosInRange range = Range.rangeContainsPos range pos + let inline isPosInRange range = rangeContainsPos range pos let inline ifPosInRange range f = if isPosInRange range then f() else None - let rec walkImplFileInput (ParsedImplFileInput(modules = moduleOrNamespaceList)) = + let rec walkImplFileInput (ParsedImplFileInput (modules = moduleOrNamespaceList)) = List.tryPick (walkSynModuleOrNamespace true) moduleOrNamespaceList - and walkSynModuleOrNamespace isTopLevel (SynModuleOrNamespace(_, _, _, decls, _, attrs, _, r)) = + and walkSynModuleOrNamespace isTopLevel (SynModuleOrNamespace(_, _, _, decls, _, Attributes attrs, _, r)) = List.tryPick walkAttribute attrs |> Option.orElse (ifPosInRange r (fun _ -> List.tryPick (walkSynModuleDecl isTopLevel) decls)) @@ -729,7 +736,7 @@ module UntypedParseImpl = and walkTypar (Typar (ident, _, _)) = ifPosInRange ident.idRange (fun _ -> Some EntityKind.Type) - and walkTyparDecl (SynTyparDecl.TyparDecl (attrs, typar)) = + and walkTyparDecl (SynTyparDecl.TyparDecl (Attributes attrs, typar)) = List.tryPick walkAttribute attrs |> Option.orElse (walkTypar typar) @@ -753,7 +760,7 @@ module UntypedParseImpl = if isPosInRange nameRange then None else walkPat pat | SynPat.Typed(pat, t, _) -> walkPat pat |> Option.orElse (walkType t) - | SynPat.Attrib(pat, attrs, _) -> walkPat pat |> Option.orElse (List.tryPick walkAttribute attrs) + | SynPat.Attrib(pat, Attributes attrs, _) -> walkPat pat |> Option.orElse (List.tryPick walkAttribute attrs) | SynPat.Or(pat1, pat2, _) -> List.tryPick walkPat [pat1; pat2] | SynPat.LongIdent(_, _, typars, ConstructorPats pats, _, r) -> ifPosInRange r (fun _ -> kind) @@ -772,7 +779,7 @@ module UntypedParseImpl = and walkPat = walkPatWithKind None - and walkBinding (SynBinding.Binding(_, _, _, _, attrs, _, _, pat, returnInfo, e, _, _)) = + and walkBinding (SynBinding.Binding(_, _, _, _, Attributes attrs, _, _, pat, returnInfo, e, _, _)) = List.tryPick walkAttribute attrs |> Option.orElse (walkPat pat) |> Option.orElse (walkExpr e) @@ -785,13 +792,13 @@ module UntypedParseImpl = List.tryPick walkBinding bindings and walkIndexerArg = function - | SynIndexerArg.One e -> walkExpr e - | SynIndexerArg.Two(e1, e2) -> List.tryPick walkExpr [e1; e2] + | SynIndexerArg.One (e, _, _) -> walkExpr e + | SynIndexerArg.Two(e1, _, e2, _, _, _) -> List.tryPick walkExpr [e1; e2] and walkType = function | SynType.LongIdent ident -> // we protect it with try..with because System.Exception : rangeOfLidwd may raise - // at FSharp.Compiler.Ast.LongIdentWithDots.get_Range() in D:\j\workspace\release_ci_pa---3f142ccc\src\fsharp\ast.fs: line 156 + // at FSharp.Compiler.SyntaxTree.LongIdentWithDots.get_Range() in D:\j\workspace\release_ci_pa---3f142ccc\src\fsharp\ast.fs: line 156 try ifPosInRange ident.Range (fun _ -> Some EntityKind.Type) with _ -> None | SynType.App(ty, _, types, _, _, _, _) -> walkType ty |> Option.orElse (List.tryPick walkType types) @@ -816,69 +823,76 @@ module UntypedParseImpl = | [] when isPosInRange r -> parentKind |> Option.orElse (Some (EntityKind.FunctionOrValue false)) | firstDotRange :: _ -> let firstPartRange = - Range.mkRange "" r.Start (Range.mkPos firstDotRange.StartLine (firstDotRange.StartColumn - 1)) + mkRange "" r.Start (mkPos firstDotRange.StartLine (firstDotRange.StartColumn - 1)) if isPosInRange firstPartRange then parentKind |> Option.orElse (Some (EntityKind.FunctionOrValue false)) else None | _ -> None | SynExpr.Paren (e, _, _, _) -> walkExprWithKind parentKind e - | SynExpr.Quote(_, _, e, _, _) -> walkExprWithKind parentKind e - | SynExpr.Typed(e, _, _) -> walkExprWithKind parentKind e - | SynExpr.Tuple(_, es, _, _) -> List.tryPick (walkExprWithKind parentKind) es - | SynExpr.ArrayOrList(_, es, _) -> List.tryPick (walkExprWithKind parentKind) es - | SynExpr.Record(_, _, fields, r) -> + | SynExpr.Quote (_, _, e, _, _) -> walkExprWithKind parentKind e + | SynExpr.Typed (e, _, _) -> walkExprWithKind parentKind e + | SynExpr.Tuple (_, es, _, _) -> List.tryPick (walkExprWithKind parentKind) es + | SynExpr.ArrayOrList (_, es, _) -> List.tryPick (walkExprWithKind parentKind) es + | SynExpr.Record (_, _, fields, r) -> ifPosInRange r (fun _ -> fields |> List.tryPick (fun (_, e, _) -> e |> Option.bind (walkExprWithKind parentKind))) - | SynExpr.New(_, t, e, _) -> walkExprWithKind parentKind e |> Option.orElse (walkType t) - | SynExpr.ObjExpr(ty, _, bindings, ifaces, _, _) -> + | SynExpr.New (_, t, e, _) -> walkExprWithKind parentKind e |> Option.orElse (walkType t) + | SynExpr.ObjExpr (ty, _, bindings, ifaces, _, _) -> walkType ty |> Option.orElse (List.tryPick walkBinding bindings) |> Option.orElse (List.tryPick walkInterfaceImpl ifaces) - | SynExpr.While(_, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.For(_, _, e1, _, e2, e3, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2; e3] - | SynExpr.ForEach(_, _, _, _, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.ArrayOrListOfSeqExpr(_, e, _) -> walkExprWithKind parentKind e - | SynExpr.CompExpr(_, _, e, _) -> walkExprWithKind parentKind e - | SynExpr.Lambda(_, _, _, e, _) -> walkExprWithKind parentKind e - | SynExpr.MatchLambda(_, _, synMatchClauseList, _, _) -> + | SynExpr.While (_, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] + | SynExpr.For (_, _, e1, _, e2, e3, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2; e3] + | SynExpr.ForEach (_, _, _, _, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] + | SynExpr.ArrayOrListOfSeqExpr (_, e, _) -> walkExprWithKind parentKind e + | SynExpr.CompExpr (_, _, e, _) -> walkExprWithKind parentKind e + | SynExpr.Lambda (_, _, _, e, _) -> walkExprWithKind parentKind e + | SynExpr.MatchLambda (_, _, synMatchClauseList, _, _) -> List.tryPick walkClause synMatchClauseList - | SynExpr.Match(_, e, synMatchClauseList, _) -> + | SynExpr.Match (_, e, synMatchClauseList, _) -> walkExprWithKind parentKind e |> Option.orElse (List.tryPick walkClause synMatchClauseList) - | SynExpr.Do(e, _) -> walkExprWithKind parentKind e - | SynExpr.Assert(e, _) -> walkExprWithKind parentKind e - | SynExpr.App(_, _, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.TypeApp(e, _, tys, _, _, _, _) -> + | SynExpr.Do (e, _) -> walkExprWithKind parentKind e + | SynExpr.Assert (e, _) -> walkExprWithKind parentKind e + | SynExpr.App (_, _, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] + | SynExpr.TypeApp (e, _, tys, _, _, _, _) -> walkExprWithKind (Some EntityKind.Type) e |> Option.orElse (List.tryPick walkType tys) - | SynExpr.LetOrUse(_, _, bindings, e, _) -> List.tryPick walkBinding bindings |> Option.orElse (walkExprWithKind parentKind e) - | SynExpr.TryWith(e, _, clauses, _, _, _, _) -> walkExprWithKind parentKind e |> Option.orElse (List.tryPick walkClause clauses) - | SynExpr.TryFinally(e1, e2, _, _, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.Lazy(e, _) -> walkExprWithKind parentKind e + | SynExpr.LetOrUse (_, _, bindings, e, _) -> List.tryPick walkBinding bindings |> Option.orElse (walkExprWithKind parentKind e) + | SynExpr.TryWith (e, _, clauses, _, _, _, _) -> walkExprWithKind parentKind e |> Option.orElse (List.tryPick walkClause clauses) + | SynExpr.TryFinally (e1, e2, _, _, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] + | SynExpr.Lazy (e, _) -> walkExprWithKind parentKind e | Sequentials es -> List.tryPick (walkExprWithKind parentKind) es - | SynExpr.IfThenElse(e1, e2, e3, _, _, _, _) -> + | SynExpr.IfThenElse (e1, e2, e3, _, _, _, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] |> Option.orElse (match e3 with None -> None | Some e -> walkExprWithKind parentKind e) | SynExpr.Ident ident -> ifPosInRange ident.idRange (fun _ -> Some (EntityKind.FunctionOrValue false)) - | SynExpr.LongIdentSet(_, e, _) -> walkExprWithKind parentKind e - | SynExpr.DotGet(e, _, _, _) -> walkExprWithKind parentKind e - | SynExpr.DotSet(e, _, _, _) -> walkExprWithKind parentKind e - | SynExpr.Set(e, _, _) -> walkExprWithKind parentKind e - | SynExpr.DotIndexedGet(e, args, _, _) -> walkExprWithKind parentKind e |> Option.orElse (List.tryPick walkIndexerArg args) - | SynExpr.DotIndexedSet(e, args, _, _, _, _) -> walkExprWithKind parentKind e |> Option.orElse (List.tryPick walkIndexerArg args) - | SynExpr.NamedIndexedPropertySet(_, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.DotNamedIndexedPropertySet(e1, _, e2, e3, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2; e3] - | SynExpr.TypeTest(e, t, _) -> walkExprWithKind parentKind e |> Option.orElse (walkType t) - | SynExpr.Upcast(e, t, _) -> walkExprWithKind parentKind e |> Option.orElse (walkType t) - | SynExpr.Downcast(e, t, _) -> walkExprWithKind parentKind e |> Option.orElse (walkType t) - | SynExpr.InferredUpcast(e, _) -> walkExprWithKind parentKind e - | SynExpr.InferredDowncast(e, _) -> walkExprWithKind parentKind e - | SynExpr.AddressOf(_, e, _, _) -> walkExprWithKind parentKind e - | SynExpr.JoinIn(e1, _, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.YieldOrReturn(_, e, _) -> walkExprWithKind parentKind e - | SynExpr.YieldOrReturnFrom(_, e, _) -> walkExprWithKind parentKind e - | SynExpr.Match(_, e, synMatchClauseList, _) - | SynExpr.MatchBang(_, e, synMatchClauseList, _) -> + | SynExpr.LongIdentSet (_, e, _) -> walkExprWithKind parentKind e + | SynExpr.DotGet (e, _, _, _) -> walkExprWithKind parentKind e + | SynExpr.DotSet (e, _, _, _) -> walkExprWithKind parentKind e + | SynExpr.Set (e, _, _) -> walkExprWithKind parentKind e + | SynExpr.DotIndexedGet (e, args, _, _) -> walkExprWithKind parentKind e |> Option.orElse (List.tryPick walkIndexerArg args) + | SynExpr.DotIndexedSet (e, args, _, _, _, _) -> walkExprWithKind parentKind e |> Option.orElse (List.tryPick walkIndexerArg args) + | SynExpr.NamedIndexedPropertySet (_, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] + | SynExpr.DotNamedIndexedPropertySet (e1, _, e2, e3, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2; e3] + | SynExpr.TypeTest (e, t, _) -> walkExprWithKind parentKind e |> Option.orElse (walkType t) + | SynExpr.Upcast (e, t, _) -> walkExprWithKind parentKind e |> Option.orElse (walkType t) + | SynExpr.Downcast (e, t, _) -> walkExprWithKind parentKind e |> Option.orElse (walkType t) + | SynExpr.InferredUpcast (e, _) -> walkExprWithKind parentKind e + | SynExpr.InferredDowncast (e, _) -> walkExprWithKind parentKind e + | SynExpr.AddressOf (_, e, _, _) -> walkExprWithKind parentKind e + | SynExpr.JoinIn (e1, _, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] + | SynExpr.YieldOrReturn (_, e, _) -> walkExprWithKind parentKind e + | SynExpr.YieldOrReturnFrom (_, e, _) -> walkExprWithKind parentKind e + | SynExpr.Match (_, e, synMatchClauseList, _) + | SynExpr.MatchBang (_, e, synMatchClauseList, _) -> walkExprWithKind parentKind e |> Option.orElse (List.tryPick walkClause synMatchClauseList) - | SynExpr.LetOrUseBang(_, _, _, _, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.DoBang(e, _) -> walkExprWithKind parentKind e + | SynExpr.LetOrUseBang(_, _, _, _, e1, es, e2, _) -> + [ + yield e1 + for (_,_,_,_,eAndBang,_) in es do + yield eAndBang + yield e2 + ] + |> List.tryPick (walkExprWithKind parentKind) + | SynExpr.DoBang (e, _) -> walkExprWithKind parentKind e | SynExpr.TraitCall (ts, sign, e, _) -> List.tryPick walkTypar ts |> Option.orElse (walkMemberSig sign) @@ -888,15 +902,15 @@ module UntypedParseImpl = and walkExpr = walkExprWithKind None and walkSimplePat = function - | SynSimplePat.Attrib (pat, attrs, _) -> + | SynSimplePat.Attrib (pat, Attributes attrs, _) -> walkSimplePat pat |> Option.orElse (List.tryPick walkAttribute attrs) | SynSimplePat.Typed(pat, t, _) -> walkSimplePat pat |> Option.orElse (walkType t) | _ -> None - and walkField (SynField.Field(attrs, _, _, t, _, _, _, _)) = + and walkField (SynField.Field(Attributes attrs, _, _, t, _, _, _, _)) = List.tryPick walkAttribute attrs |> Option.orElse (walkType t) - and walkValSig (SynValSig.ValSpfn(attrs, _, _, t, _, _, _, _, _, _, _)) = + and walkValSig (SynValSig.ValSpfn(Attributes attrs, _, _, t, _, _, _, _, _, _, _)) = List.tryPick walkAttribute attrs |> Option.orElse (walkType t) and walkMemberSig = function @@ -912,8 +926,8 @@ module UntypedParseImpl = and walkMember = function | SynMemberDefn.AbstractSlot (valSig, _, _) -> walkValSig valSig | SynMemberDefn.Member(binding, _) -> walkBinding binding - | SynMemberDefn.ImplicitCtor(_, attrs, pats, _, _) -> - List.tryPick walkAttribute attrs |> Option.orElse (List.tryPick walkSimplePat pats) + | SynMemberDefn.ImplicitCtor(_, Attributes attrs, SynSimplePats.SimplePats(simplePats, _), _, _) -> + List.tryPick walkAttribute attrs |> Option.orElse (List.tryPick walkSimplePat simplePats) | SynMemberDefn.ImplicitInherit(t, e, _, _) -> walkType t |> Option.orElse (walkExpr e) | SynMemberDefn.LetBindings(bindings, _, _, _) -> List.tryPick walkBinding bindings | SynMemberDefn.Interface(t, members, _) -> @@ -921,19 +935,19 @@ module UntypedParseImpl = | SynMemberDefn.Inherit(t, _, _) -> walkType t | SynMemberDefn.ValField(field, _) -> walkField field | SynMemberDefn.NestedType(tdef, _, _) -> walkTypeDefn tdef - | SynMemberDefn.AutoProperty(attrs, _, _, t, _, _, _, _, e, _, _) -> + | SynMemberDefn.AutoProperty(Attributes attrs, _, _, t, _, _, _, _, e, _, _) -> List.tryPick walkAttribute attrs |> Option.orElse (Option.bind walkType t) |> Option.orElse (walkExpr e) | _ -> None - and walkEnumCase (EnumCase(attrs, _, _, _, _)) = List.tryPick walkAttribute attrs + and walkEnumCase (EnumCase(Attributes attrs, _, _, _, _)) = List.tryPick walkAttribute attrs and walkUnionCaseType = function | SynUnionCaseType.UnionCaseFields fields -> List.tryPick walkField fields | SynUnionCaseType.UnionCaseFullType(t, _) -> walkType t - and walkUnionCase (UnionCase(attrs, _, t, _, _, _)) = + and walkUnionCase (UnionCase(Attributes attrs, _, t, _, _, _)) = List.tryPick walkAttribute attrs |> Option.orElse (walkUnionCaseType t) and walkTypeDefnSimple = function @@ -943,7 +957,7 @@ module UntypedParseImpl = | SynTypeDefnSimpleRepr.TypeAbbrev(_, t, _) -> walkType t | _ -> None - and walkComponentInfo isModule (ComponentInfo(attrs, typars, constraints, _, _, _, _, r)) = + and walkComponentInfo isModule (ComponentInfo(Attributes attrs, typars, constraints, _, _, _, _, r)) = if isModule then None else ifPosInRange r (fun _ -> Some EntityKind.Type) |> Option.orElse ( List.tryPick walkAttribute attrs @@ -1011,12 +1025,12 @@ module UntypedParseImpl = let rec collect plid (parts : Ident list) (dots : range list) = match parts, dots with | [], _ -> Some (plid, None) - | x::xs, ds -> + | x :: xs, ds -> if rangeContainsPos x.idRange pos then // pos lies with the range of current identifier let s = x.idText.Substring(0, pos.Column - x.idRange.Start.Column) let residue = if s.Length <> 0 then Some s else None - Some(plid, residue) + Some (plid, residue) elif posGt x.idRange.Start pos then // can happen if caret is placed after dot but before the existing identifier A. $ B // return accumulated plid with no residue @@ -1025,11 +1039,11 @@ module UntypedParseImpl = match ds with | [] -> // pos lies after the id and no dots found - return accumulated plid and current id as residue - Some(plid, Some(x.idText)) - | d::ds -> + Some (plid, Some (x.idText)) + | d :: ds -> if posGeq pos d.End then // pos lies after the dot - proceed to the next identifier - collect ((x.idText)::plid) xs ds + collect ((x.idText) :: plid) xs ds else // pos after the id but before the dot // A $.B - return nothing @@ -1037,7 +1051,7 @@ module UntypedParseImpl = match collect [] lid dots with | Some (parts, residue) -> - Some((List.rev parts), residue) + Some ((List.rev parts), residue) | None -> None let (|Class|Interface|Struct|Unknown|Invalid|) synAttributes = @@ -1049,11 +1063,11 @@ module UntypedParseImpl = let rec getKind isClass isInterface isStruct = function | [] -> isClass, isInterface, isStruct - | (SynAttr "Class")::xs -> getKind true isInterface isStruct xs - | (SynAttr "AbstractClass")::xs -> getKind true isInterface isStruct xs - | (SynAttr "Interface")::xs -> getKind isClass true isStruct xs - | (SynAttr "Struct")::xs -> getKind isClass isInterface true xs - | _::xs -> getKind isClass isInterface isStruct xs + | (SynAttr "Class") :: xs -> getKind true isInterface isStruct xs + | (SynAttr "AbstractClass") :: xs -> getKind true isInterface isStruct xs + | (SynAttr "Interface") :: xs -> getKind isClass true isStruct xs + | (SynAttr "Struct") :: xs -> getKind isClass isInterface true xs + | _ :: xs -> getKind isClass isInterface isStruct xs match getKind false false false synAttributes with | false, false, false -> Unknown @@ -1062,7 +1076,7 @@ module UntypedParseImpl = | false, false, true -> Struct | _ -> Invalid - let GetCompletionContextForInheritSynMember ((ComponentInfo(synAttributes, _, _, _, _, _, _, _)), typeDefnKind : SynTypeDefnKind, completionPath) = + let GetCompletionContextForInheritSynMember ((ComponentInfo(Attributes synAttributes, _, _, _, _, _, _, _)), typeDefnKind : SynTypeDefnKind, completionPath) = let success k = Some (CompletionContext.Inherit (k, completionPath)) @@ -1096,14 +1110,14 @@ module UntypedParseImpl = let (|Operator|_|) name e = match e with - | SynExpr.App(ExprAtomicFlag.NonAtomic, false, SynExpr.App(ExprAtomicFlag.NonAtomic, true, SynExpr.Ident(ident), lhs, _), rhs, _) - when ident.idText = name -> Some(lhs, rhs) + | SynExpr.App (ExprAtomicFlag.NonAtomic, false, SynExpr.App (ExprAtomicFlag.NonAtomic, true, SynExpr.Ident ident, lhs, _), rhs, _) + when ident.idText = name -> Some (lhs, rhs) | _ -> None // checks if we are in rhs of the range operator let isInRhsOfRangeOp (p : AstTraversal.TraversePath) = match p with - | TS.Expr(Operator "op_Range" _)::_ -> true + | TS.Expr(Operator "op_Range" _) :: _ -> true | _ -> false let (|Setter|_|) e = @@ -1113,7 +1127,7 @@ module UntypedParseImpl = let findSetters argList = match argList with - | SynExpr.Paren(SynExpr.Tuple(false, parameters, _, _), _, _, _) -> + | SynExpr.Paren (SynExpr.Tuple (false, parameters, _, _), _, _, _) -> let setters = HashSet() for p in parameters do match p with @@ -1147,13 +1161,13 @@ module UntypedParseImpl = | (SynExpr.App (_, false, SynExpr.Ident id, arg, _)) -> // A() Some (id.idRange.End, findSetters arg) - | (SynExpr.App (_, false, SynExpr.TypeApp(SynExpr.Ident id, _, _, _, mGreaterThan, _, _), arg, _)) -> + | (SynExpr.App (_, false, SynExpr.TypeApp (SynExpr.Ident id, _, _, _, mGreaterThan, _, _), arg, _)) -> // A<_>() Some (endOfClosingTokenOrIdent mGreaterThan id, findSetters arg) - | (SynExpr.App (_, false, SynExpr.LongIdent(_, lid, _, _), arg, _)) -> + | (SynExpr.App (_, false, SynExpr.LongIdent (_, lid, _, _), arg, _)) -> // A.B() Some (endOfLastIdent lid, findSetters arg) - | (SynExpr.App (_, false, SynExpr.TypeApp(SynExpr.LongIdent(_, lid, _, _), _, _, _, mGreaterThan, _, _), arg, _)) -> + | (SynExpr.App (_, false, SynExpr.TypeApp (SynExpr.LongIdent (_, lid, _, _), _, _, _, mGreaterThan, _, _), arg, _)) -> // A.B<_>() Some (endOfClosingTokenOrLastIdent mGreaterThan lid, findSetters arg) | _ -> None @@ -1161,9 +1175,9 @@ module UntypedParseImpl = let isOnTheRightOfComma (elements: SynExpr list) (commas: range list) current = let rec loop elements (commas: range list) = match elements with - | x::xs -> + | x :: xs -> match commas with - | c::cs -> + | c :: cs -> if x === current then posLt c.End pos || posEq c.End pos else loop xs cs | _ -> false @@ -1172,9 +1186,9 @@ module UntypedParseImpl = let (|PartOfParameterList|_|) precedingArgument path = match path with - | TS.Expr(SynExpr.Paren _)::TS.Expr(NewObjectOrMethodCall(args))::_ -> + | TS.Expr(SynExpr.Paren _) :: TS.Expr(NewObjectOrMethodCall args) :: _ -> if Option.isSome precedingArgument then None else Some args - | TS.Expr(SynExpr.Tuple (false, elements, commas, _))::TS.Expr(SynExpr.Paren _)::TS.Expr(NewObjectOrMethodCall(args))::_ -> + | TS.Expr(SynExpr.Tuple (false, elements, commas, _)) :: TS.Expr(SynExpr.Paren _) :: TS.Expr(NewObjectOrMethodCall args) :: _ -> match precedingArgument with | None -> Some args | Some e -> @@ -1199,9 +1213,9 @@ module UntypedParseImpl = else match expr with // new A($) - | SynExpr.Const(SynConst.Unit, m) when rangeContainsPos m pos -> + | SynExpr.Const (SynConst.Unit, m) when rangeContainsPos m pos -> match path with - | TS.Expr(NewObjectOrMethodCall args)::_ -> + | TS.Expr(NewObjectOrMethodCall args) :: _ -> Some (CompletionContext.ParameterList args) | _ -> defaultTraverse expr @@ -1228,13 +1242,13 @@ module UntypedParseImpl = let contextFromTreePath completionPath = // detect records usage in constructor match path with - | TS.Expr(_)::TS.Binding(_):: TS.MemberDefn(_)::TS.TypeDefn(SynTypeDefn.TypeDefn(ComponentInfo(_, _, _, [id], _, _, _, _), _, _, _))::_ -> + | TS.Expr(_) :: TS.Binding(_) :: TS.MemberDefn(_) :: TS.TypeDefn(SynTypeDefn.TypeDefn(ComponentInfo(_, _, _, [id], _, _, _, _), _, _, _)) :: _ -> RecordContext.Constructor(id.idText) - | _ -> RecordContext.New (completionPath) + | _ -> RecordContext.New completionPath match field with | Some field -> match parseLid field with - | Some (completionPath) -> + | Some completionPath -> let recordContext = match copyOpt with | Some (s : SynExpr) -> RecordContext.CopyOnUpdate(s.Range, completionPath) @@ -1252,7 +1266,7 @@ module UntypedParseImpl = match synType with | SynType.LongIdent lidwd -> match parseLid lidwd with - | Some (completionPath) -> GetCompletionContextForInheritSynMember (componentInfo, typeDefnKind, completionPath) + | Some completionPath -> GetCompletionContextForInheritSynMember (componentInfo, typeDefnKind, completionPath) | None -> Some (CompletionContext.Invalid) // A $ .B -> no completion list | _ -> None @@ -1263,7 +1277,7 @@ module UntypedParseImpl = | SynPat.Named (range = range) when rangeContainsPos range pos -> // parameter without type hint, no completion Some CompletionContext.Invalid - | SynPat.Typed(SynPat.Named(SynPat.Wild(range), _, _, _, _), _, _) when rangeContainsPos range pos -> + | SynPat.Typed(SynPat.Named(SynPat.Wild range, _, _, _, _), _, _) when rangeContainsPos range pos -> // parameter with type hint, but we are on its name, no completion Some CompletionContext.Invalid | _ -> defaultTraverse synBinding @@ -1274,7 +1288,7 @@ module UntypedParseImpl = Some CompletionContext.Invalid | SynPat.LongIdent(_, _, _, ctorArgs, _, _) -> match ctorArgs with - | SynConstructorArgs.Pats(pats) -> + | SynArgPats.Pats pats -> pats |> List.tryPick (fun pat -> match pat with | SynPat.Paren(pat, _) -> @@ -1282,7 +1296,7 @@ module UntypedParseImpl = | SynPat.Tuple(_, pats, _) -> pats |> List.tryPick visitParam | _ -> visitParam pat - | SynPat.Wild(range) when rangeContainsPos range pos -> + | SynPat.Wild range when rangeContainsPos range pos -> // let foo (x| Some CompletionContext.Invalid | _ -> visitParam pat @@ -1293,7 +1307,7 @@ module UntypedParseImpl = Some CompletionContext.Invalid | _ -> defaultTraverse synBinding - member __.VisitHashDirective(range) = + member __.VisitHashDirective range = if rangeContainsPos range pos then Some CompletionContext.Invalid else None @@ -1315,7 +1329,7 @@ module UntypedParseImpl = | [] when range.StartLine = pos.Line -> Some CompletionContext.Invalid | _ -> None - member __.VisitSimplePats(pats) = + member __.VisitSimplePats pats = pats |> List.tryPick (fun pat -> match pat with | SynSimplePat.Id(range = range) @@ -1380,7 +1394,7 @@ module UntypedParseImpl = #else // match the most nested paired [< and >] first let matches = - insideAttributeApplicationRegex.Matches(lineStr) + insideAttributeApplicationRegex.Matches lineStr |> Seq.cast |> Seq.filter (fun m -> m.Index <= pos.Column && m.Index + m.Length >= pos.Column) |> Seq.toArray diff --git a/src/fcs-fable/src/fsharp/service/ServiceUntypedParse.fsi b/src/fcs-fable/src/fsharp/service/ServiceUntypedParse.fsi index 8a88f766c8..8213ec7629 100755 --- a/src/fcs-fable/src/fsharp/service/ServiceUntypedParse.fsi +++ b/src/fcs-fable/src/fsharp/service/ServiceUntypedParse.fsi @@ -8,17 +8,16 @@ namespace FSharp.Compiler.SourceCodeServices open System.Collections.Generic -open FSharp.Compiler -open FSharp.Compiler.Ast + open FSharp.Compiler.Range -open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.SyntaxTree [] /// Represents the results of parsing an F# file type public FSharpParseFileResults = /// The syntax tree resulting from the parse - member ParseTree : Ast.ParsedInput option + member ParseTree : ParsedInput option /// Notable parse info for ParameterInfo at a given location member FindNoteworthyParamInfoLocations : pos:pos -> FSharpNoteworthyParamInfoLocations option @@ -41,7 +40,7 @@ type public FSharpParseFileResults = /// Indicates if any errors occurred during the parse member ParseHadErrors : bool - internal new: errors: FSharpErrorInfo[] * input: Ast.ParsedInput option * parseHadErrors: bool * dependencyFiles: string[] -> FSharpParseFileResults + internal new: errors: FSharpErrorInfo[] * input: ParsedInput option * parseHadErrors: bool * dependencyFiles: string[] -> FSharpParseFileResults /// Information about F# source file names module public SourceFile = @@ -103,14 +102,21 @@ type public EntityKind = // implementation details used by other code in the compiler module public UntypedParseImpl = val TryFindExpressionASTLeftOfDotLeftOfCursor : pos * ParsedInput option -> (pos * bool) option + val GetRangeOfExprLeftOfDot : pos * ParsedInput option -> range option + val TryFindExpressionIslandInPosition : pos * ParsedInput option -> string option + val TryGetCompletionContext : pos * ParsedInput * lineStr: string -> CompletionContext option + val GetEntityKind: pos * ParsedInput -> EntityKind option + val GetFullNameOfSmallestModuleOrNamespaceAtPoint : ParsedInput * pos -> string[] // implementation details used by other code in the compiler module internal SourceFileImpl = + val IsInterfaceFile : string -> bool + val AdditionalDefinesForUseInEditor: isInteractive: bool -> string list diff --git a/src/fcs-fable/src/fsharp/service/ServiceXmlDocParser.fs b/src/fcs-fable/src/fsharp/service/ServiceXmlDocParser.fs index 7cf4f3fb31..01073ec599 100644 --- a/src/fcs-fable/src/fsharp/service/ServiceXmlDocParser.fs +++ b/src/fcs-fable/src/fsharp/service/ServiceXmlDocParser.fs @@ -2,15 +2,17 @@ namespace FSharp.Compiler.SourceCodeServices -open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.Text +open FSharp.Compiler.XmlDoc /// Represent an Xml documentation block in source code type XmlDocable = | XmlDocable of line:int * indent:int * paramNames:string list module XmlDocParsing = - open FSharp.Compiler.Range - open FSharp.Compiler.Ast let (|ConstructorPats|) = function | Pats ps -> ps @@ -38,10 +40,10 @@ module XmlDocParsing = | SynPat.InstanceMember _ | SynPat.FromParseError _ -> [] - let getXmlDocablesImpl(sourceCodeLinesOfTheFile: string [], input: ParsedInput option) = + let getXmlDocablesImpl(sourceText: ISourceText, input: ParsedInput option) = let indentOf (lineNum: int) = let mutable i = 0 - let line = sourceCodeLinesOfTheFile.[lineNum-1] // -1 because lineNum reported by xmldocs are 1-based, but array is 0-based + let line = sourceText.GetLineString(lineNum-1) // -1 because lineNum reported by xmldocs are 1-based, but array is 0-based while i < line.Length && line.Chars(i) = ' ' do i <- i + 1 i @@ -146,7 +148,7 @@ module XmlDocParsing = and getXmlDocablesInput input = match input with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = symModules))-> + | ParsedInput.ImplFile (ParsedImplFileInput (modules = symModules))-> symModules |> List.collect getXmlDocablesSynModuleOrNamespace | ParsedInput.SigFile _ -> [] @@ -184,7 +186,7 @@ module XmlDocComment = res module XmlDocParser = + /// Get the list of Xml documentation from current source code - let getXmlDocables (sourceCodeOfTheFile, input) = - let sourceCodeLinesOfTheFile = String.getLines sourceCodeOfTheFile - XmlDocParsing.getXmlDocablesImpl (sourceCodeLinesOfTheFile, input) \ No newline at end of file + let getXmlDocables (sourceText: ISourceText, input) = + XmlDocParsing.getXmlDocablesImpl (sourceText, input) \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/service/ServiceXmlDocParser.fsi b/src/fcs-fable/src/fsharp/service/ServiceXmlDocParser.fsi index 128f351e29..75c212fca5 100644 --- a/src/fcs-fable/src/fsharp/service/ServiceXmlDocParser.fsi +++ b/src/fcs-fable/src/fsharp/service/ServiceXmlDocParser.fsi @@ -2,9 +2,8 @@ namespace FSharp.Compiler.SourceCodeServices -open FSharp.Compiler -open FSharp.Compiler.Range -open FSharp.Compiler.Ast +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.Text /// Represent an Xml documentation block in source code type public XmlDocable = @@ -16,6 +15,7 @@ module public XmlDocComment = val isBlank : string -> int option module public XmlDocParser = + /// Get the list of Xml documentation from current source code - val getXmlDocables : sourceCodeOfTheFile : string * input : Ast.ParsedInput option -> XmlDocable list + val getXmlDocables : ISourceText * input: ParsedInput option -> XmlDocable list \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/service/service.fs b/src/fcs-fable/src/fsharp/service/service.fs old mode 100755 new mode 100644 index 2c0a4057fb..dec4c8663e --- a/src/fcs-fable/src/fsharp/service/service.fs +++ b/src/fcs-fable/src/fsharp/service/service.fs @@ -1,29 +1,19 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -// Open up the compiler as an incremental service for parsing, -// type checking and intellisense-like environment-reporting. - namespace FSharp.Compiler.SourceCodeServices open System -open System.Collections.Generic open System.Collections.Concurrent open System.Diagnostics open System.IO open System.Reflection -open System.Text -open Microsoft.FSharp.Core.Printf open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.ILBinaryReader -open FSharp.Compiler.AbstractIL.Diagnostics -open FSharp.Compiler.AbstractIL.Internal -open FSharp.Compiler.AbstractIL.Internal.Library - -open FSharp.Compiler.AccessibilityLogic -open FSharp.Compiler.Ast +open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.AbstractIL.Internal.Utils open FSharp.Compiler.CompileOps open FSharp.Compiler.CompileOptions #if !FABLE_COMPILER @@ -31,30 +21,18 @@ open FSharp.Compiler.Driver #endif open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Lib -open FSharp.Compiler.PrettyNaming -open FSharp.Compiler.Parser open FSharp.Compiler.Range -open FSharp.Compiler.Lexhelp -open FSharp.Compiler.Layout -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.SyntaxTree open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Infos -open FSharp.Compiler.InfoReader -open FSharp.Compiler.NameResolution -open FSharp.Compiler.TypeChecker -open FSharp.Compiler.SourceCodeServices.SymbolHelpers +open FSharp.Compiler.Text open Internal.Utilities open Internal.Utilities.Collections -open FSharp.Compiler.Layout.TaggedTextOps type internal Layout = StructuredFormat.Layout [] module EnvMisc = - let getToolTipTextSize = GetEnvInteger "FCS_GetToolTipTextCacheSize" 5 - let maxTypeCheckErrorsOutOfProjectContext = GetEnvInteger "FCS_MaxErrorsOutOfProjectContext" 3 let braceMatchCacheSize = GetEnvInteger "FCS_BraceMatchCacheSize" 5 let parseFileCacheSize = GetEnvInteger "FCS_ParseFileCacheSize" 2 let checkFileInProjectCacheSize = GetEnvInteger "FCS_CheckFileInProjectCacheSize" 10 @@ -64,1764 +42,6 @@ module EnvMisc = let maxMBDefault = GetEnvInteger "FCS_MaxMB" 1000000 // a million MB = 1TB = disabled //let maxMBDefault = GetEnvInteger "FCS_maxMB" (if sizeof = 4 then 1700 else 3400) - /// Maximum time share for a piece of background work before it should (cooperatively) yield - /// to enable other requests to be serviced. Yielding means returning a continuation function - /// (via an Eventually<_> value of case NotYetDone) that can be called as the next piece of work. - let maxTimeShareMilliseconds = int64 (GetEnvInteger "FCS_MaxTimeShare" 100) - - -//---------------------------------------------------------------------------- -// Scopes. -//-------------------------------------------------------------------------- - -[] -type FSharpFindDeclFailureReason = - // generic reason: no particular information about error - | Unknown of message: string - // source code file is not available - | NoSourceCode - // trying to find declaration of ProvidedType without TypeProviderDefinitionLocationAttribute - | ProvidedType of string - // trying to find declaration of ProvidedMember without TypeProviderDefinitionLocationAttribute - | ProvidedMember of string - -[] -type FSharpFindDeclResult = - /// declaration not found + reason - | DeclNotFound of FSharpFindDeclFailureReason - /// found declaration - | DeclFound of range - /// Indicates an external declaration was found - | ExternalDecl of assembly : string * externalSym : ExternalSymbol - -/// This type is used to describe what was found during the name resolution. -/// (Depending on the kind of the items, we may stop processing or continue to find better items) -[] -[] -type internal NameResResult = - | Members of (ItemWithInst list * DisplayEnv * range) - | Cancel of DisplayEnv * range - | Empty - | TypecheckStaleAndTextChanged - - -[] -type ResolveOverloads = -| Yes -| No - -[] -type GetPreciseCompletionListFromExprTypingsResult = - | NoneBecauseTypecheckIsStaleAndTextChanged - | NoneBecauseThereWereTypeErrors - | None - | Some of (ItemWithInst list * DisplayEnv * range) * TType - -type Names = string list - -[] -type SemanticClassificationType = - | ReferenceType - | ValueType - | UnionCase - | Function - | Property - | MutableVar - | Module - | Printf - | ComputationExpression - | IntrinsicFunction - | Enumeration - | Interface - | TypeArgument - | Operator - | Disposable - -/// A TypeCheckInfo represents everything we get back from the typecheck of a file. -/// It acts like an in-memory database about the file. -/// It is effectively immutable and not updated: when we re-typecheck we just drop the previous -/// scope object on the floor and make a new one. -[] -type TypeCheckInfo - (// Information corresponding to miscellaneous command-line options (--define, etc). - _sTcConfig: TcConfig, - g: TcGlobals, - // The signature of the assembly being checked, up to and including the current file - ccuSigForFile: ModuleOrNamespaceType, - thisCcu: CcuThunk, - tcImports: TcImports, - tcAccessRights: AccessorDomain, - projectFileName: string, - mainInputFileName: string, - sResolutions: TcResolutions, - sSymbolUses: TcSymbolUses, - // This is a name resolution environment to use if no better match can be found. - sFallback: NameResolutionEnv, - loadClosure : LoadClosure option, - reactorOps : IReactorOperations, - checkAlive : (unit -> bool), - textSnapshotInfo:obj option, - implFileOpt: TypedImplFile option, - openDeclarations: OpenDeclaration[]) = - - let textSnapshotInfo = defaultArg textSnapshotInfo null - let (|CNR|) (cnr:CapturedNameResolution) = - (cnr.Pos, cnr.Item, cnr.ItemOccurence, cnr.DisplayEnv, cnr.NameResolutionEnv, cnr.AccessorDomain, cnr.Range) - - // These strings are potentially large and the editor may choose to hold them for a while. - // Use this cache to fold together data tip text results that are the same. - // Is not keyed on 'Names' collection because this is invariant for the current position in - // this unchanged file. Keyed on lineStr though to prevent a change to the currently line - // being available against a stale scope. - let getToolTipTextCache = AgedLookup>(getToolTipTextSize,areSimilar=(fun (x,y) -> x = y)) - - let amap = tcImports.GetImportMap() - let infoReader = new InfoReader(g,amap) - let ncenv = new NameResolver(g,amap,infoReader,NameResolution.FakeInstantiationGenerator) - let cenv = SymbolEnv(g, thisCcu, Some ccuSigForFile, tcImports, amap, infoReader) - - /// Find the most precise naming environment for the given line and column - let GetBestEnvForPos cursorPos = - - let mutable bestSoFar = None - - // Find the most deeply nested enclosing scope that contains given position - sResolutions.CapturedEnvs |> ResizeArray.iter (fun (possm,env,ad) -> - if rangeContainsPos possm cursorPos then - match bestSoFar with - | Some (bestm,_,_) -> - if rangeContainsRange bestm possm then - bestSoFar <- Some (possm,env,ad) - | None -> - bestSoFar <- Some (possm,env,ad)) - - let mostDeeplyNestedEnclosingScope = bestSoFar - - // Look for better subtrees on the r.h.s. of the subtree to the left of where we are - // Should really go all the way down the r.h.s. of the subtree to the left of where we are - // This is all needed when the index is floating free in the area just after the environment we really want to capture - // We guarantee to only refine to a more nested environment. It may not be strictly - // the right environment, but will always be at least as rich - - let bestAlmostIncludedSoFar = ref None - - sResolutions.CapturedEnvs |> ResizeArray.iter (fun (possm,env,ad) -> - // take only ranges that strictly do not include cursorPos (all ranges that touch cursorPos were processed during 'Strict Inclusion' part) - if rangeBeforePos possm cursorPos && not (posEq possm.End cursorPos) then - let contained = - match mostDeeplyNestedEnclosingScope with - | Some (bestm,_,_) -> rangeContainsRange bestm possm - | None -> true - - if contained then - match !bestAlmostIncludedSoFar with - | Some (rightm:range,_,_) -> - if posGt possm.End rightm.End || - (posEq possm.End rightm.End && posGt possm.Start rightm.Start) then - bestAlmostIncludedSoFar := Some (possm,env,ad) - | _ -> bestAlmostIncludedSoFar := Some (possm,env,ad)) - - let resEnv = - match !bestAlmostIncludedSoFar, mostDeeplyNestedEnclosingScope with - | Some (_,env,ad), None -> env, ad - | Some (_,almostIncludedEnv,ad), Some (_,mostDeeplyNestedEnv,_) - when almostIncludedEnv.eFieldLabels.Count >= mostDeeplyNestedEnv.eFieldLabels.Count -> - almostIncludedEnv,ad - | _ -> - match mostDeeplyNestedEnclosingScope with - | Some (_,env,ad) -> - env,ad - | None -> - sFallback,AccessibleFromSomeFSharpCode - let pm = mkRange mainInputFileName cursorPos cursorPos - - resEnv,pm - - /// The items that come back from ResolveCompletionsInType are a bit - /// noisy. Filter a few things out. - /// - /// e.g. prefer types to constructors for FSharpToolTipText - let FilterItemsForCtors filterCtors (items: ItemWithInst list) = - let items = items |> List.filter (fun item -> match item.Item with (Item.CtorGroup _) when filterCtors = ResolveTypeNamesToTypeRefs -> false | _ -> true) - items - - // Filter items to show only valid & return Some if there are any - let ReturnItemsOfType (items: ItemWithInst list) g denv (m:range) filterCtors hasTextChangedSinceLastTypecheck = - let items = - items - |> RemoveDuplicateItems g - |> RemoveExplicitlySuppressed g - |> FilterItemsForCtors filterCtors - - if not (isNil items) then - if hasTextChangedSinceLastTypecheck(textSnapshotInfo, m) then - NameResResult.TypecheckStaleAndTextChanged // typecheck is stale, wait for second-chance IntelliSense to bring up right result - else - NameResResult.Members (items, denv, m) - else NameResResult.Empty - - let GetCapturedNameResolutions endOfNamesPos resolveOverloads = - - let quals = - match resolveOverloads with - | ResolveOverloads.Yes -> sResolutions.CapturedNameResolutions - | ResolveOverloads.No -> sResolutions.CapturedMethodGroupResolutions - - let quals = quals |> ResizeArray.filter (fun cnr -> posEq cnr.Pos endOfNamesPos) - - quals - - /// Looks at the exact name resolutions that occurred during type checking - /// If 'membersByResidue' is specified, we look for members of the item obtained - /// from the name resolution and filter them by the specified residue (?) - let GetPreciseItemsFromNameResolution(line, colAtEndOfNames, membersByResidue, filterCtors, resolveOverloads, hasTextChangedSinceLastTypecheck) = - let endOfNamesPos = mkPos line colAtEndOfNames - - // Logic below expects the list to be in reverse order of resolution - let cnrs = GetCapturedNameResolutions endOfNamesPos resolveOverloads |> ResizeArray.toList |> List.rev - - match cnrs, membersByResidue with - - // If we're looking for members using a residue, we'd expect only - // a single item (pick the first one) and we need the residue (which may be "") - | CNR(_,Item.Types(_,(ty::_)), _, denv, nenv, ad, m)::_, Some _ -> - let items = ResolveCompletionsInType ncenv nenv (ResolveCompletionTargets.All(ConstraintSolver.IsApplicableMethApprox g amap m)) m ad true ty - let items = List.map ItemWithNoInst items - ReturnItemsOfType items g denv m filterCtors hasTextChangedSinceLastTypecheck - - // Value reference from the name resolution. Primarily to disallow "let x.$ = 1" - // In most of the cases, value references can be obtained from expression typings or from environment, - // so we wouldn't have to handle values here. However, if we have something like: - // let varA = "string" - // let varA = if b then 0 else varA. - // then the expression typings get confused (thinking 'varA:int'), so we use name resolution even for usual values. - - | CNR(_, Item.Value(vref), occurence, denv, nenv, ad, m)::_, Some _ -> - if (occurence = ItemOccurence.Binding || occurence = ItemOccurence.Pattern) then - // Return empty list to stop further lookup - for value declarations - NameResResult.Cancel(denv, m) - else - // If we have any valid items for the value, then return completions for its type now. - // Adjust the type in case this is the 'this' pointer stored in a reference cell. - let ty = StripSelfRefCell(g, vref.BaseOrThisInfo, vref.TauType) - // patch accessibility domain to remove protected members if accessing NormalVal - let ad = - match vref.BaseOrThisInfo, ad with - | ValBaseOrThisInfo.NormalVal, AccessibleFrom(paths, Some tcref) -> - let tcref = generalizedTyconRef tcref - // check that type of value is the same or subtype of tcref - // yes - allow access to protected members - // no - strip ability to access protected members - if FSharp.Compiler.TypeRelations.TypeFeasiblySubsumesType 0 g amap m tcref FSharp.Compiler.TypeRelations.CanCoerce ty then - ad - else - AccessibleFrom(paths, None) - | _ -> ad - - let items = ResolveCompletionsInType ncenv nenv (ResolveCompletionTargets.All(ConstraintSolver.IsApplicableMethApprox g amap m)) m ad false ty - let items = List.map ItemWithNoInst items - ReturnItemsOfType items g denv m filterCtors hasTextChangedSinceLastTypecheck - - // No residue, so the items are the full resolution of the name - | CNR(_, _, _, denv, _, _, m) :: _, None -> - let items = - cnrs - |> List.map (fun cnr -> cnr.ItemWithInst) - // "into" is special magic syntax, not an identifier or a library call. It is part of capturedNameResolutions as an - // implementation detail of syntax coloring, but we should not report name resolution results for it, to prevent spurious QuickInfo. - |> List.filter (fun item -> match item.Item with Item.CustomOperation(CustomOperations.Into,_,_) -> false | _ -> true) - ReturnItemsOfType items g denv m filterCtors hasTextChangedSinceLastTypecheck - | _, _ -> NameResResult.Empty - - let TryGetTypeFromNameResolution(line, colAtEndOfNames, membersByResidue, resolveOverloads) = - let endOfNamesPos = mkPos line colAtEndOfNames - let items = GetCapturedNameResolutions endOfNamesPos resolveOverloads |> ResizeArray.toList |> List.rev - - match items, membersByResidue with - | CNR(_,Item.Types(_,(ty::_)),_,_,_,_,_)::_, Some _ -> Some ty - | CNR(_, Item.Value(vref), occurence,_,_,_,_)::_, Some _ -> - if (occurence = ItemOccurence.Binding || occurence = ItemOccurence.Pattern) then None - else Some (StripSelfRefCell(g, vref.BaseOrThisInfo, vref.TauType)) - | _, _ -> None - - let CollectParameters (methods: MethInfo list) amap m: Item list = - methods - |> List.collect (fun meth -> - match meth.GetParamDatas(amap, m, meth.FormalMethodInst) with - | x::_ -> x |> List.choose(fun (ParamData(_isParamArray, _isInArg, _isOutArg, _optArgInfo, _callerInfo, name, _, ty)) -> - match name with - | Some n -> Some (Item.ArgName(n, ty, Some (ArgumentContainer.Method meth))) - | None -> None - ) - | _ -> [] - ) - - let GetNamedParametersAndSettableFields endOfExprPos hasTextChangedSinceLastTypecheck = - let cnrs = GetCapturedNameResolutions endOfExprPos ResolveOverloads.No |> ResizeArray.toList |> List.rev - let result = - match cnrs with - | CNR(_, Item.CtorGroup(_, ((ctor::_) as ctors)), _, denv, nenv, ad, m) ::_ -> - let props = ResolveCompletionsInType ncenv nenv ResolveCompletionTargets.SettablePropertiesAndFields m ad false ctor.ApparentEnclosingType - let parameters = CollectParameters ctors amap m - let items = props @ parameters - Some (denv, m, items) - | CNR(_, Item.MethodGroup(_, methods, _), _, denv, nenv, ad, m) ::_ -> - let props = - methods - |> List.collect (fun meth -> - let retTy = meth.GetFSharpReturnTy(amap, m, meth.FormalMethodInst) - ResolveCompletionsInType ncenv nenv ResolveCompletionTargets.SettablePropertiesAndFields m ad false retTy - ) - let parameters = CollectParameters methods amap m - let items = props @ parameters - Some (denv, m, items) - | _ -> - None - match result with - | None -> - NameResResult.Empty - | Some (denv, m, items) -> - let items = List.map ItemWithNoInst items - ReturnItemsOfType items g denv m TypeNameResolutionFlag.ResolveTypeNamesToTypeRefs hasTextChangedSinceLastTypecheck - - /// finds captured typing for the given position - let GetExprTypingForPosition(endOfExprPos) = - let quals = - sResolutions.CapturedExpressionTypings - |> Seq.filter (fun (pos,ty,denv,_,_,_) -> - // We only want expression types that end at the particular position in the file we are looking at. - let isLocationWeCareAbout = posEq pos endOfExprPos - // Get rid of function types. True, given a 2-arg curried function "f x y", it is legal to do "(f x).GetType()", - // but you almost never want to do this in practice, and we choose not to offer up any intellisense for - // F# function types. - let isFunction = isFunTy denv.g ty - isLocationWeCareAbout && not isFunction) - |> Seq.toArray - - let thereWereSomeQuals = not (Array.isEmpty quals) - // filter out errors - - let quals = quals - |> Array.filter (fun (_,ty,denv,_,_,_) -> not (isTyparTy denv.g ty && (destTyparTy denv.g ty).IsFromError)) - thereWereSomeQuals, quals - - /// obtains captured typing for the given position - /// if type of captured typing is record - returns list of record fields - let GetRecdFieldsForExpr(r : range) = - let _, quals = GetExprTypingForPosition(r.End) - let bestQual = - match quals with - | [||] -> None - | quals -> - quals |> Array.tryFind (fun (_,_,_,_,_,rq) -> - ignore(r) // for breakpoint - posEq r.Start rq.Start) - match bestQual with - | Some (_,ty,denv,_nenv,ad,m) when isRecdTy denv.g ty -> - let items = NameResolution.ResolveRecordOrClassFieldsOfType ncenv m ad ty false - Some (items, denv, m) - | _ -> None - - /// Looks at the exact expression types at the position to the left of the - /// residue then the source when it was typechecked. - let GetPreciseCompletionListFromExprTypings(parseResults:FSharpParseFileResults, endOfExprPos, filterCtors, hasTextChangedSinceLastTypecheck: (obj * range -> bool)) = - - let thereWereSomeQuals, quals = GetExprTypingForPosition(endOfExprPos) - - match quals with - | [| |] -> - if thereWereSomeQuals then - GetPreciseCompletionListFromExprTypingsResult.NoneBecauseThereWereTypeErrors - else - GetPreciseCompletionListFromExprTypingsResult.None - | _ -> - let bestQual, textChanged = - match parseResults.ParseTree with - | Some(input) -> - match UntypedParseImpl.GetRangeOfExprLeftOfDot(endOfExprPos,Some(input)) with // TODO we say "colAtEndOfNames" everywhere, but that's not really a good name ("foo . $" hit Ctrl-Space at $) - | Some( exprRange) -> - if hasTextChangedSinceLastTypecheck(textSnapshotInfo, exprRange) then - None, true // typecheck is stale, wait for second-chance IntelliSense to bring up right result - else - // See bug 130733. We have an up-to-date sync parse, and know the exact range of the prior expression. - // The quals all already have the same ending position, so find one with a matching starting position, if it exists. - // If not, then the stale typecheck info does not have a capturedExpressionTyping for this exact expression, and the - // user can wait for typechecking to catch up and second-chance intellisense to give the right result. - let qual = - quals |> Array.tryFind (fun (_,_,_,_,_,r) -> - ignore(r) // for breakpoint - posEq exprRange.Start r.Start) - qual, false - | None -> - // TODO In theory I think we should never get to this code path; it would be nice to add an assert. - // In practice, we do get here in some weird cases like "2.0 .. 3.0" and hitting Ctrl-Space in between the two dots of the range operator. - // I wasn't able to track down what was happening in those weird cases, not worth worrying about, it doesn't manifest as a product bug or anything. - None, false - | _ -> None, false - - match bestQual with - | Some bestQual -> - let (_,ty,denv,nenv,ad,m) = bestQual - let items = ResolveCompletionsInType ncenv nenv (ResolveCompletionTargets.All(ConstraintSolver.IsApplicableMethApprox g amap m)) m ad false ty - let items = items |> List.map ItemWithNoInst - let items = items |> RemoveDuplicateItems g - let items = items |> RemoveExplicitlySuppressed g - let items = items |> FilterItemsForCtors filterCtors - GetPreciseCompletionListFromExprTypingsResult.Some((items,denv,m), ty) - | None -> - if textChanged then GetPreciseCompletionListFromExprTypingsResult.NoneBecauseTypecheckIsStaleAndTextChanged - else GetPreciseCompletionListFromExprTypingsResult.None - - /// Find items in the best naming environment. - let GetEnvironmentLookupResolutions(nenv, ad, m, plid, filterCtors, showObsolete) = - let items = NameResolution.ResolvePartialLongIdent ncenv nenv (ConstraintSolver.IsApplicableMethApprox g amap m) m ad plid showObsolete - let items = items |> List.map ItemWithNoInst - let items = items |> RemoveDuplicateItems g - let items = items |> RemoveExplicitlySuppressed g - let items = items |> FilterItemsForCtors filterCtors - (items, nenv.DisplayEnv, m) - - /// Find items in the best naming environment. - let GetEnvironmentLookupResolutionsAtPosition(cursorPos, plid, filterCtors, showObsolete) = - let (nenv,ad),m = GetBestEnvForPos cursorPos - GetEnvironmentLookupResolutions(nenv, ad, m, plid, filterCtors, showObsolete) - - /// Find record fields in the best naming environment. - let GetClassOrRecordFieldsEnvironmentLookupResolutions(cursorPos, plid) = - let (nenv, ad),m = GetBestEnvForPos cursorPos - let items = NameResolution.ResolvePartialLongIdentToClassOrRecdFields ncenv nenv m ad plid false - let items = items |> List.map ItemWithNoInst - let items = items |> RemoveDuplicateItems g - let items = items |> RemoveExplicitlySuppressed g - items, nenv.DisplayEnv, m - - /// Resolve a location and/or text to items. - // Three techniques are used - // - look for an exact known name resolution from type checking - // - use the known type of an expression, e.g. (expr).Name, to generate an item list - // - lookup an entire name in the name resolution environment, e.g. A.B.Name, to generate an item list - // - // The overall aim is to resolve as accurately as possible based on what we know from type inference - - let GetBaseClassCandidates = function - | Item.ModuleOrNamespaces _ -> true - | Item.Types(_, ty::_) when (isClassTy g ty) && not (isSealedTy g ty) -> true - | _ -> false - - let GetInterfaceCandidates = function - | Item.ModuleOrNamespaces _ -> true - | Item.Types(_, ty::_) when (isInterfaceTy g ty) -> true - | _ -> false - - - // Return only items with the specified name - let FilterDeclItemsByResidue (getItem: 'a -> Item) residue (items: 'a list) = - let attributedResidue = residue + "Attribute" - let nameMatchesResidue name = (residue = name) || (attributedResidue = name) - - items |> List.filter (fun x -> - let item = getItem x - let n1 = item.DisplayName - match item with - | Item.Types _ -> nameMatchesResidue n1 - | Item.CtorGroup (_, meths) -> - nameMatchesResidue n1 || - meths |> List.exists (fun meth -> - let tcref = meth.ApparentEnclosingTyconRef -#if !NO_EXTENSIONTYPING - tcref.IsProvided || -#endif - nameMatchesResidue tcref.DisplayName) - | _ -> residue = n1) - - /// Post-filter items to make sure they have precisely the right name - /// This also checks that there are some remaining results - /// exactMatchResidueOpt = Some _ -- means that we are looking for exact matches - let FilterRelevantItemsBy (getItem: 'a -> Item) (exactMatchResidueOpt : _ option) check (items: 'a list, denv, m) = - - // can throw if type is in located in non-resolved CCU: i.e. bigint if reference to System.Numerics is absent - let safeCheck item = try check item with _ -> false - - // Are we looking for items with precisely the given name? - if not (isNil items) && exactMatchResidueOpt.IsSome then - let items = items |> FilterDeclItemsByResidue getItem exactMatchResidueOpt.Value |> List.filter safeCheck - if not (isNil items) then Some(items, denv, m) else None - else - // When (items = []) we must returns Some([],..) and not None - // because this value is used if we want to stop further processing (e.g. let x.$ = ...) - let items = items |> List.filter safeCheck - Some(items, denv, m) - - /// Post-filter items to make sure they have precisely the right name - /// This also checks that there are some remaining results - let (|FilterRelevantItems|_|) getItem exactMatchResidueOpt orig = - FilterRelevantItemsBy getItem exactMatchResidueOpt (fun _ -> true) orig - - /// Find the first non-whitespace position in a line prior to the given character - let FindFirstNonWhitespacePosition (lineStr: string) i = - if i >= lineStr.Length then None - else - let mutable p = i - while p >= 0 && System.Char.IsWhiteSpace(lineStr.[p]) do - p <- p - 1 - if p >= 0 then Some p else None - - let CompletionItem (ty: ValueOption) (assemblySymbol: ValueOption) (item: ItemWithInst) = - let kind = - match item.Item with - | Item.MethodGroup (_, minfo :: _, _) -> CompletionItemKind.Method minfo.IsExtensionMember - | Item.RecdField _ - | Item.Property _ -> CompletionItemKind.Property - | Item.Event _ -> CompletionItemKind.Event - | Item.ILField _ - | Item.Value _ -> CompletionItemKind.Field - | Item.CustomOperation _ -> CompletionItemKind.CustomOperation - | _ -> CompletionItemKind.Other - - { ItemWithInst = item - MinorPriority = 0 - Kind = kind - IsOwnMember = false - Type = match ty with ValueSome x -> Some x | _ -> None - Unresolved = match assemblySymbol with ValueSome x -> Some x.UnresolvedSymbol | _ -> None } - - let DefaultCompletionItem item = CompletionItem ValueNone ValueNone item - - let getItem (x: ItemWithInst) = x.Item - let GetDeclaredItems (parseResultsOpt: FSharpParseFileResults option, lineStr: string, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, - filterCtors, resolveOverloads, hasTextChangedSinceLastTypecheck, isInRangeOperator, allSymbols: unit -> AssemblySymbol list) = - - // Are the last two chars (except whitespaces) = ".." - let isLikeRangeOp = - match FindFirstNonWhitespacePosition lineStr (colAtEndOfNamesAndResidue - 1) with - | Some x when x >= 1 && lineStr.[x] = '.' && lineStr.[x - 1] = '.' -> true - | _ -> false - - // if last two chars are .. and we are not in range operator context - no completion - if isLikeRangeOp && not isInRangeOperator then None else - - // Try to use the exact results of name resolution during type checking to generate the results - // This is based on position (i.e. colAtEndOfNamesAndResidue). This is not used if a residueOpt is given. - let nameResItems = - match residueOpt with - | None -> GetPreciseItemsFromNameResolution(line, colAtEndOfNamesAndResidue, None, filterCtors,resolveOverloads, hasTextChangedSinceLastTypecheck) - | Some residue -> - // deals with cases when we have spaces between dot and\or identifier, like A . $ - // if this is our case - then we need to locate end position of the name skipping whitespaces - // this allows us to handle cases like: let x . $ = 1 - match lastDotPos |> Option.orElseWith (fun _ -> FindFirstNonWhitespacePosition lineStr (colAtEndOfNamesAndResidue - 1)) with - | Some p when lineStr.[p] = '.' -> - match FindFirstNonWhitespacePosition lineStr (p - 1) with - | Some colAtEndOfNames -> - let colAtEndOfNames = colAtEndOfNames + 1 // convert 0-based to 1-based - GetPreciseItemsFromNameResolution(line, colAtEndOfNames, Some(residue), filterCtors,resolveOverloads, hasTextChangedSinceLastTypecheck) - | None -> NameResResult.Empty - | _ -> NameResResult.Empty - - // Normalize to form A.B.C.D where D is the residue. It may be empty for "A.B.C." - // residueOpt = Some when we are looking for the exact match - let plid, exactMatchResidueOpt = - match origLongIdentOpt, residueOpt with - | None, _ -> [], None - | Some(origLongIdent), Some _ -> origLongIdent, None - | Some(origLongIdent), None -> - System.Diagnostics.Debug.Assert(not (isNil origLongIdent), "origLongIdent is empty") - // note: as above, this happens when we are called for "precise" resolution - (F1 keyword, data tip etc..) - let plid, residue = List.frontAndBack origLongIdent - plid, Some residue - - let pos = mkPos line loc - let (nenv, ad), m = GetBestEnvForPos pos - - let getType() = - match NameResolution.TryToResolveLongIdentAsType ncenv nenv m plid with - | Some x -> tryDestAppTy g x - | None -> - match lastDotPos |> Option.orElseWith (fun _ -> FindFirstNonWhitespacePosition lineStr (colAtEndOfNamesAndResidue - 1)) with - | Some p when lineStr.[p] = '.' -> - match FindFirstNonWhitespacePosition lineStr (p - 1) with - | Some colAtEndOfNames -> - let colAtEndOfNames = colAtEndOfNames + 1 // convert 0-based to 1-based - match TryGetTypeFromNameResolution(line, colAtEndOfNames, residueOpt, resolveOverloads) with - | Some x -> tryDestAppTy g x - | _ -> ValueNone - | None -> ValueNone - | _ -> ValueNone - - match nameResItems with - | NameResResult.TypecheckStaleAndTextChanged -> None // second-chance intellisense will try again - | NameResResult.Cancel(denv,m) -> Some([], denv, m) - | NameResResult.Members(FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m)) -> - // lookup based on name resolution results successful - Some (items |> List.map (CompletionItem (getType()) ValueNone), denv, m) - | _ -> - match origLongIdentOpt with - | None -> None - | Some _ -> - - // Try to use the type of the expression on the left to help generate a completion list - let qualItems, thereIsADotInvolved = - match parseResultsOpt with - | None -> - // Note, you will get here if the 'reason' is not CompleteWord/MemberSelect/DisplayMemberList, as those are currently the - // only reasons we do a sync parse to have the most precise and likely-to-be-correct-and-up-to-date info. So for example, - // if you do QuickInfo hovering over A in "f(x).A()", you will only get a tip if typechecking has a name-resolution recorded - // for A, not if merely we know the capturedExpressionTyping of f(x) and you very recently typed ".A()" - in that case, - // you won't won't get a tip until the typechecking catches back up. - GetPreciseCompletionListFromExprTypingsResult.None, false - | Some parseResults -> - - match UntypedParseImpl.TryFindExpressionASTLeftOfDotLeftOfCursor(mkPos line colAtEndOfNamesAndResidue,parseResults.ParseTree) with - | Some(pos,_) -> - GetPreciseCompletionListFromExprTypings(parseResults, pos, filterCtors, hasTextChangedSinceLastTypecheck), true - | None -> - // Can get here in a case like: if "f xxx yyy" is legal, and we do "f xxx y" - // We have no interest in expression typings, those are only useful for dot-completion. We want to fallback - // to "Use an environment lookup as the last resort" below - GetPreciseCompletionListFromExprTypingsResult.None, false - - match qualItems,thereIsADotInvolved with - | GetPreciseCompletionListFromExprTypingsResult.Some(FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m), ty), _ - // Initially we only use the expression typings when looking up, e.g. (expr).Nam or (expr).Name1.Nam - // These come through as an empty plid and residue "". Otherwise we try an environment lookup - // and then return to the qualItems. This is because the expression typings are a little inaccurate, primarily because - // it appears we're getting some typings recorded for non-atomic expressions like "f x" - when isNil plid -> - // lookup based on expression typings successful - Some (items |> List.map (CompletionItem (tryDestAppTy g ty) ValueNone), denv, m) - | GetPreciseCompletionListFromExprTypingsResult.NoneBecauseThereWereTypeErrors, _ -> - // There was an error, e.g. we have "." and there is an error determining the type of - // In this case, we don't want any of the fallback logic, rather, we want to produce zero results. - None - | GetPreciseCompletionListFromExprTypingsResult.NoneBecauseTypecheckIsStaleAndTextChanged, _ -> - // we want to report no result and let second-chance intellisense kick in - None - | _, true when isNil plid -> - // If the user just pressed '.' after an _expression_ (not a plid), it is never right to show environment-lookup top-level completions. - // The user might by typing quickly, and the LS didn't have an expression type right before the dot yet. - // Second-chance intellisense will bring up the correct list in a moment. - None - | _ -> - // Use an environment lookup as the last resort - let envItems, denv, m = GetEnvironmentLookupResolutions(nenv, ad, m, plid, filterCtors, residueOpt.IsSome) - - let envResult = - match nameResItems, (envItems, denv, m), qualItems with - - // First, use unfiltered name resolution items, if they're not empty - | NameResResult.Members(items, denv, m), _, _ when not (isNil items) -> - // lookup based on name resolution results successful - ValueSome(items |> List.map (CompletionItem (getType()) ValueNone), denv, m) - - // If we have nonempty items from environment that were resolved from a type, then use them... - // (that's better than the next case - here we'd return 'int' as a type) - | _, FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m), _ when not (isNil items) -> - // lookup based on name and environment successful - ValueSome(items |> List.map (CompletionItem (getType()) ValueNone), denv, m) - - // Try again with the qualItems - | _, _, GetPreciseCompletionListFromExprTypingsResult.Some(FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m), ty) -> - ValueSome(items |> List.map (CompletionItem (tryDestAppTy g ty) ValueNone), denv, m) - - | _ -> ValueNone - - let globalResult = - match origLongIdentOpt with - | None | Some [] -> - let globalItems = - allSymbols() - |> List.filter (fun x -> not x.Symbol.IsExplicitlySuppressed) - |> List.filter (fun x -> - match x.Symbol with - | :? FSharpMemberOrFunctionOrValue as m when m.IsConstructor && filterCtors = ResolveTypeNamesToTypeRefs -> false - | _ -> true) - - let getItem (x: AssemblySymbol) = x.Symbol.Item - - match globalItems, denv, m with - | FilterRelevantItems getItem exactMatchResidueOpt (globalItemsFiltered, denv, m) when not (isNil globalItemsFiltered) -> - globalItemsFiltered - |> List.map(fun globalItem -> CompletionItem (getType()) (ValueSome globalItem) (ItemWithNoInst globalItem.Symbol.Item)) - |> fun r -> ValueSome(r, denv, m) - | _ -> ValueNone - | _ -> ValueNone // do not return unresolved items after dot - - match envResult, globalResult with - | ValueSome (items, denv, m), ValueSome (gItems,_,_) -> Some (items @ gItems, denv, m) - | ValueSome x, ValueNone -> Some x - | ValueNone, ValueSome y -> Some y - | ValueNone, ValueNone -> None - - - let toCompletionItems (items: ItemWithInst list, denv: DisplayEnv, m: range ) = - items |> List.map DefaultCompletionItem, denv, m - - /// Get the auto-complete items at a particular location. - let GetDeclItemsForNamesAtPosition(ctok: CompilationThreadToken, parseResultsOpt: FSharpParseFileResults option, origLongIdentOpt: string list option, - residueOpt:string option, lastDotPos: int option, line:int, lineStr:string, colAtEndOfNamesAndResidue, filterCtors, resolveOverloads, - getAllSymbols: unit -> AssemblySymbol list, hasTextChangedSinceLastTypecheck: (obj * range -> bool)) - : (CompletionItem list * DisplayEnv * CompletionContext option * range) option = - RequireCompilationThread ctok // the operations in this method need the reactor thread - - let loc = - match colAtEndOfNamesAndResidue with - | pastEndOfLine when pastEndOfLine >= lineStr.Length -> lineStr.Length - | atDot when lineStr.[atDot] = '.' -> atDot + 1 - | atStart when atStart = 0 -> 0 - | otherwise -> otherwise - 1 - - // Look for a "special" completion context - let completionContext = - parseResultsOpt - |> Option.bind (fun x -> x.ParseTree) - |> Option.bind (fun parseTree -> UntypedParseImpl.TryGetCompletionContext(mkPos line colAtEndOfNamesAndResidue, parseTree, lineStr)) - - let res = - match completionContext with - // Invalid completion locations - | Some CompletionContext.Invalid -> None - - // Completion at 'inherit C(...)" - | Some (CompletionContext.Inherit(InheritanceContext.Class, (plid, _))) -> - GetEnvironmentLookupResolutionsAtPosition(mkPos line loc, plid, filterCtors, false) - |> FilterRelevantItemsBy getItem None (getItem >> GetBaseClassCandidates) - |> Option.map toCompletionItems - - // Completion at 'interface ..." - | Some (CompletionContext.Inherit(InheritanceContext.Interface, (plid, _))) -> - GetEnvironmentLookupResolutionsAtPosition(mkPos line loc, plid, filterCtors, false) - |> FilterRelevantItemsBy getItem None (getItem >> GetInterfaceCandidates) - |> Option.map toCompletionItems - - // Completion at 'implement ..." - | Some (CompletionContext.Inherit(InheritanceContext.Unknown, (plid, _))) -> - GetEnvironmentLookupResolutionsAtPosition(mkPos line loc, plid, filterCtors, false) - |> FilterRelevantItemsBy getItem None (getItem >> (fun t -> GetBaseClassCandidates t || GetInterfaceCandidates t)) - |> Option.map toCompletionItems - - // Completion at ' { XXX = ... } " - | Some(CompletionContext.RecordField(RecordContext.New(plid, _))) -> - // { x. } can be either record construction or computation expression. Try to get all visible record fields first - match GetClassOrRecordFieldsEnvironmentLookupResolutions(mkPos line loc, plid) |> toCompletionItems with - | [],_,_ -> - // no record fields found, return completion list as if we were outside any computation expression - GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors,resolveOverloads, hasTextChangedSinceLastTypecheck, false, fun() -> []) - | result -> Some(result) - - // Completion at ' { XXX = ... with ... } " - | Some(CompletionContext.RecordField(RecordContext.CopyOnUpdate(r, (plid, _)))) -> - match GetRecdFieldsForExpr(r) with - | None -> - Some (GetClassOrRecordFieldsEnvironmentLookupResolutions(mkPos line loc, plid)) - |> Option.map toCompletionItems - | Some (items, denv, m) -> - Some (List.map ItemWithNoInst items, denv, m) - |> Option.map toCompletionItems - - // Completion at ' { XXX = ... with ... } " - | Some(CompletionContext.RecordField(RecordContext.Constructor(typeName))) -> - Some(GetClassOrRecordFieldsEnvironmentLookupResolutions(mkPos line loc, [typeName])) - |> Option.map toCompletionItems - - // Completion at ' SomeMethod( ... ) ' with named arguments - | Some(CompletionContext.ParameterList (endPos, fields)) -> - let results = GetNamedParametersAndSettableFields endPos hasTextChangedSinceLastTypecheck - - let declaredItems = - GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors, resolveOverloads, - hasTextChangedSinceLastTypecheck, false, getAllSymbols) - - match results with - | NameResResult.Members(items, denv, m) -> - let filtered = - items - |> RemoveDuplicateItems g - |> RemoveExplicitlySuppressed g - |> List.filter (fun item -> not (fields.Contains item.Item.DisplayName)) - |> List.map (fun item -> - { ItemWithInst = item - Kind = CompletionItemKind.Argument - MinorPriority = 0 - IsOwnMember = false - Type = None - Unresolved = None }) - match declaredItems with - | None -> Some (toCompletionItems (items, denv, m)) - | Some (declItems, declaredDisplayEnv, declaredRange) -> Some (filtered @ declItems, declaredDisplayEnv, declaredRange) - | _ -> declaredItems - - | Some(CompletionContext.AttributeApplication) -> - GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors, resolveOverloads, hasTextChangedSinceLastTypecheck, false, getAllSymbols) - |> Option.map (fun (items, denv, m) -> - items - |> List.filter (fun cItem -> - match cItem.Item with - | Item.ModuleOrNamespaces _ -> true - | _ when IsAttribute infoReader cItem.Item -> true - | _ -> false), denv, m) - - | Some(CompletionContext.OpenDeclaration) -> - GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors, resolveOverloads, hasTextChangedSinceLastTypecheck, false, getAllSymbols) - |> Option.map (fun (items, denv, m) -> - items |> List.filter (fun x -> match x.Item with Item.ModuleOrNamespaces _ -> true | _ -> false), denv, m) - - // Completion at '(x: ...)" - | Some (CompletionContext.PatternType) -> - GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors, resolveOverloads, hasTextChangedSinceLastTypecheck, false, getAllSymbols) - |> Option.map (fun (items, denv, m) -> - items - |> List.filter (fun cItem -> - match cItem.Item with - | Item.ModuleOrNamespaces _ - | Item.Types _ - | Item.UnqualifiedType _ - | Item.ExnCase _ -> true - | _ -> false), denv, m) - - // Other completions - | cc -> - match residueOpt |> Option.bind Seq.tryHead with - | Some ''' -> - // The last token in - // let x = 'E - // is Ident with text "'E", however it's either unfinished char literal or generic parameter. - // We should not provide any completion in the former case, and we don't provide it for the latter one for now - // because providing generic parameters list is context aware, which we don't have here (yet). - None - | _ -> - let isInRangeOperator = (match cc with Some (CompletionContext.RangeOperator) -> true | _ -> false) - GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors,resolveOverloads, hasTextChangedSinceLastTypecheck, isInRangeOperator, getAllSymbols) - - res |> Option.map (fun (items, denv, m) -> items, denv, completionContext, m) - - /// Return 'false' if this is not a completion item valid in an interface file. - let IsValidSignatureFileItem item = - match item with - | Item.Types _ | Item.ModuleOrNamespaces _ -> true - | _ -> false - - /// Find the most precise display context for the given line and column. - member __.GetBestDisplayEnvForPos cursorPos = GetBestEnvForPos cursorPos - - member __.GetVisibleNamespacesAndModulesAtPosition(cursorPos: pos) : ModuleOrNamespaceRef list = - let (nenv, ad), m = GetBestEnvForPos cursorPos - NameResolution.GetVisibleNamespacesAndModulesAtPoint ncenv nenv m ad - - /// Determines if a long ident is resolvable at a specific point. - member __.IsRelativeNameResolvable(cursorPos: pos, plid: string list, item: Item) : bool = - ErrorScope.Protect - Range.range0 - (fun () -> - /// Find items in the best naming environment. - let (nenv, ad), m = GetBestEnvForPos cursorPos - NameResolution.IsItemResolvable ncenv nenv m ad plid item) - (fun msg -> - Trace.TraceInformation(sprintf "FCS: recovering from error in IsRelativeNameResolvable: '%s'" msg) - false) - - /// Determines if a long ident is resolvable at a specific point. - member scope.IsRelativeNameResolvableFromSymbol(cursorPos: pos, plid: string list, symbol: FSharpSymbol) : bool = - scope.IsRelativeNameResolvable(cursorPos, plid, symbol.Item) - - /// Get the auto-complete items at a location - member __.GetDeclarations (ctok, parseResultsOpt, line, lineStr, partialName, getAllEntities, hasTextChangedSinceLastTypecheck) = - let isInterfaceFile = SourceFileImpl.IsInterfaceFile mainInputFileName - ErrorScope.Protect Range.range0 - (fun () -> - match GetDeclItemsForNamesAtPosition(ctok, parseResultsOpt, Some partialName.QualifyingIdents, Some partialName.PartialIdent, partialName.LastDotPos, line, lineStr, partialName.EndColumn + 1, ResolveTypeNamesToCtors, ResolveOverloads.Yes, getAllEntities, hasTextChangedSinceLastTypecheck) with - | None -> FSharpDeclarationListInfo.Empty - | Some (items, denv, ctx, m) -> - let items = if isInterfaceFile then items |> List.filter (fun x -> IsValidSignatureFileItem x.Item) else items - let getAccessibility item = FSharpSymbol.GetAccessibility (FSharpSymbol.Create(cenv, item)) - let currentNamespaceOrModule = - parseResultsOpt - |> Option.bind (fun x -> x.ParseTree) - |> Option.map (fun parsedInput -> UntypedParseImpl.GetFullNameOfSmallestModuleOrNamespaceAtPoint(parsedInput, mkPos line 0)) - let isAttributeApplication = ctx = Some CompletionContext.AttributeApplication - FSharpDeclarationListInfo.Create(infoReader,m,denv,getAccessibility,items,reactorOps,currentNamespaceOrModule,isAttributeApplication,checkAlive)) - (fun msg -> - Trace.TraceInformation(sprintf "FCS: recovering from error in GetDeclarations: '%s'" msg) - FSharpDeclarationListInfo.Error msg) - - /// Get the symbols for auto-complete items at a location - member __.GetDeclarationListSymbols (ctok, parseResultsOpt, line, lineStr, partialName, getAllEntities, hasTextChangedSinceLastTypecheck) = - let isInterfaceFile = SourceFileImpl.IsInterfaceFile mainInputFileName - ErrorScope.Protect Range.range0 - (fun () -> - match GetDeclItemsForNamesAtPosition(ctok, parseResultsOpt, Some partialName.QualifyingIdents, Some partialName.PartialIdent, partialName.LastDotPos, line, lineStr, partialName.EndColumn + 1, ResolveTypeNamesToCtors, ResolveOverloads.Yes, getAllEntities, hasTextChangedSinceLastTypecheck) with - | None -> List.Empty - | Some (items, denv, _, m) -> - let items = if isInterfaceFile then items |> List.filter (fun x -> IsValidSignatureFileItem x.Item) else items - - //do filtering like Declarationset - let items = items |> RemoveExplicitlySuppressedCompletionItems g - - // Sort by name. For things with the same name, - // - show types with fewer generic parameters first - // - show types before over other related items - they usually have very useful XmlDocs - let items = - items |> List.sortBy (fun d -> - let n = - match d.Item with - | Item.Types (_,(TType_app(tcref,_) :: _)) -> 1 + tcref.TyparsNoRange.Length - // Put delegate ctors after types, sorted by #typars. RemoveDuplicateItems will remove FakeInterfaceCtor and DelegateCtor if an earlier type is also reported with this name - | Item.FakeInterfaceCtor (TType_app(tcref,_)) - | Item.DelegateCtor (TType_app(tcref,_)) -> 1000 + tcref.TyparsNoRange.Length - // Put type ctors after types, sorted by #typars. RemoveDuplicateItems will remove DefaultStructCtors if a type is also reported with this name - | Item.CtorGroup (_, (cinfo :: _)) -> 1000 + 10 * cinfo.DeclaringTyconRef.TyparsNoRange.Length - | _ -> 0 - (d.Item.DisplayName,n)) - - // Remove all duplicates. We've put the types first, so this removes the DelegateCtor and DefaultStructCtor's. - let items = items |> RemoveDuplicateCompletionItems g - - // Group by compiled name for types, display name for functions - // (We don't want types with the same display name to be grouped as overloads) - let items = - items |> List.groupBy (fun d -> - match d.Item with - | Item.Types (_,(TType_app(tcref,_) :: _)) - | Item.ExnCase tcref -> tcref.LogicalName - | Item.UnqualifiedType(tcref :: _) - | Item.FakeInterfaceCtor (TType_app(tcref,_)) - | Item.DelegateCtor (TType_app(tcref,_)) -> tcref.CompiledName - | Item.CtorGroup (_, (cinfo :: _)) -> - cinfo.ApparentEnclosingTyconRef.CompiledName - | _ -> d.Item.DisplayName) - - // Filter out operators (and list) - let items = - // Check whether this item looks like an operator. - let isOpItem(nm, item: CompletionItem list) = - match item |> List.map (fun x -> x.Item) with - | [Item.Value _] - | [Item.MethodGroup(_,[_],_)] -> IsOperatorName nm - | [Item.UnionCase _] -> IsOperatorName nm - | _ -> false - - let isFSharpList nm = (nm = "[]") // list shows up as a Type and a UnionCase, only such entity with a symbolic name, but want to filter out of intellisense - - items |> List.filter (fun (nm,items) -> not (isOpItem(nm,items)) && not(isFSharpList nm)) - - let items = - // Filter out duplicate names - items |> List.map (fun (_nm,itemsWithSameName) -> - match itemsWithSameName with - | [] -> failwith "Unexpected empty bag" - | items -> - items - |> List.map (fun item -> let symbol = FSharpSymbol.Create(cenv, item.Item) - FSharpSymbolUse(g, denv, symbol, ItemOccurence.Use, m))) - - //end filtering - items) - (fun msg -> - Trace.TraceInformation(sprintf "FCS: recovering from error in GetDeclarationListSymbols: '%s'" msg) - []) - - /// Get the "reference resolution" tooltip for at a location - member __.GetReferenceResolutionStructuredToolTipText(ctok, line,col) = - - RequireCompilationThread ctok // the operations in this method need the reactor thread but the reasons why are not yet grounded - - let pos = mkPos line col - let isPosMatch(pos, ar:AssemblyReference) : bool = - let isRangeMatch = (Range.rangeContainsPos ar.Range pos) - let isNotSpecialRange = (ar.Range <> rangeStartup) && (ar.Range <> range0) && (ar.Range <> rangeCmdArgs) - let isMatch = isRangeMatch && isNotSpecialRange - isMatch - - let dataTipOfReferences() = - let matches = - match loadClosure with - | None -> [] - | Some(loadClosure) -> - loadClosure.References - |> List.map snd - |> List.concat - |> List.filter(fun ar->isPosMatch(pos, ar.originalReference)) - - match matches with - | resolved::_ // Take the first seen - | [resolved] -> - let tip = wordL (TaggedTextOps.tagStringLiteral((resolved.prepareToolTip ()).TrimEnd([|'\n'|]))) - FSharpStructuredToolTipText.FSharpToolTipText [FSharpStructuredToolTipElement.Single(tip, FSharpXmlDoc.None)] - - | [] -> FSharpStructuredToolTipText.FSharpToolTipText [] - - ErrorScope.Protect Range.range0 - dataTipOfReferences - (fun err -> - Trace.TraceInformation(sprintf "FCS: recovering from error in GetReferenceResolutionStructuredToolTipText: '%s'" err) - FSharpToolTipText [FSharpStructuredToolTipElement.CompositionError err]) - - // GetToolTipText: return the "pop up" (or "Quick Info") text given a certain context. - member __.GetStructuredToolTipText(ctok, line, lineStr, colAtEndOfNames, names) = - let Compute() = - ErrorScope.Protect Range.range0 - (fun () -> - match GetDeclItemsForNamesAtPosition(ctok, None,Some(names),None,None,line,lineStr,colAtEndOfNames,ResolveTypeNamesToCtors,ResolveOverloads.Yes,(fun() -> []),fun _ -> false) with - | None -> FSharpToolTipText [] - | Some(items, denv, _, m) -> - FSharpToolTipText(items |> List.map (fun x -> FormatStructuredDescriptionOfItem false infoReader m denv x.ItemWithInst))) - (fun err -> - Trace.TraceInformation(sprintf "FCS: recovering from error in GetStructuredToolTipText: '%s'" err) - FSharpToolTipText [FSharpStructuredToolTipElement.CompositionError err]) - - // See devdiv bug 646520 for rationale behind truncating and caching these quick infos (they can be big!) - let key = line,colAtEndOfNames,lineStr - match getToolTipTextCache.TryGet (ctok, key) with - | Some res -> res - | None -> - let res = Compute() - getToolTipTextCache.Put(ctok, key,res) - res - - member __.GetF1Keyword (ctok, line, lineStr, colAtEndOfNames, names) : string option = - ErrorScope.Protect Range.range0 - (fun () -> - match GetDeclItemsForNamesAtPosition(ctok, None, Some names, None, None, line, lineStr, colAtEndOfNames, ResolveTypeNamesToCtors, ResolveOverloads.No,(fun() -> []), fun _ -> false) with // F1 Keywords do not distinguish between overloads - | None -> None - | Some (items: CompletionItem list, _,_, _) -> - match items with - | [] -> None - | [item] -> - GetF1Keyword g item.Item - | _ -> - // handle new Type() - let allTypes, constr, ty = - List.fold - (fun (allTypes,constr,ty) (item: CompletionItem) -> - match item.Item, constr, ty with - | (Item.Types _) as t, _, None -> allTypes, constr, Some t - | (Item.Types _), _, _ -> allTypes, constr, ty - | (Item.CtorGroup _), None, _ -> allTypes, Some item.Item, ty - | _ -> false, None, None) - (true,None,None) items - match allTypes, constr, ty with - | true, Some (Item.CtorGroup(_, _) as item), _ - -> GetF1Keyword g item - | true, _, Some ty - -> GetF1Keyword g ty - | _ -> None - ) - (fun msg -> - Trace.TraceInformation(sprintf "FCS: recovering from error in GetF1Keyword: '%s'" msg) - None) - - member __.GetMethods (ctok, line, lineStr, colAtEndOfNames, namesOpt) = - ErrorScope.Protect Range.range0 - (fun () -> - match GetDeclItemsForNamesAtPosition(ctok, None,namesOpt,None,None,line,lineStr,colAtEndOfNames,ResolveTypeNamesToCtors,ResolveOverloads.No,(fun() -> []),fun _ -> false) with - | None -> FSharpMethodGroup("",[| |]) - | Some (items, denv, _, m) -> - // GetDeclItemsForNamesAtPosition returns Items.Types and Item.CtorGroup for `new T(|)`, - // the Item.Types is not needed here as it duplicates (at best) parameterless ctor. - let ctors = items |> List.filter (fun x -> match x.Item with Item.CtorGroup _ -> true | _ -> false) - let items = - match ctors with - | [] -> items - | ctors -> ctors - FSharpMethodGroup.Create(infoReader, m, denv, items |> List.map (fun x -> x.ItemWithInst))) - (fun msg -> - Trace.TraceInformation(sprintf "FCS: recovering from error in GetMethods: '%s'" msg) - FSharpMethodGroup(msg,[| |])) - - member __.GetMethodsAsSymbols (ctok, line, lineStr, colAtEndOfNames, names) = - ErrorScope.Protect Range.range0 - (fun () -> - match GetDeclItemsForNamesAtPosition (ctok, None,Some(names), None, None,line, lineStr, colAtEndOfNames, ResolveTypeNamesToCtors, ResolveOverloads.No,(fun() -> []),fun _ -> false) with - | None | Some ([],_,_,_) -> None - | Some (items, denv, _, m) -> - let allItems = items |> List.collect (fun item -> SymbolHelpers.FlattenItems g m item.Item) - let symbols = allItems |> List.map (fun item -> FSharpSymbol.Create(cenv, item)) - Some (symbols, denv, m) - ) - (fun msg -> - Trace.TraceInformation(sprintf "FCS: recovering from error in GetMethodsAsSymbols: '%s'" msg) - None) - - member __.GetDeclarationLocation (ctok, line, lineStr, colAtEndOfNames, names, preferFlag) = - ErrorScope.Protect Range.range0 - (fun () -> - match GetDeclItemsForNamesAtPosition (ctok, None,Some(names), None, None, line, lineStr, colAtEndOfNames, ResolveTypeNamesToCtors,ResolveOverloads.Yes,(fun() -> []), fun _ -> false) with - | None - | Some ([], _, _, _) -> FSharpFindDeclResult.DeclNotFound (FSharpFindDeclFailureReason.Unknown "") - | Some (item :: _, _, _, _) -> - let getTypeVarNames (ilinfo: ILMethInfo) = - let classTypeParams = ilinfo.DeclaringTyconRef.ILTyconRawMetadata.GenericParams |> List.map (fun paramDef -> paramDef.Name) - let methodTypeParams = ilinfo.FormalMethodTypars |> List.map (fun ty -> ty.Name) - classTypeParams @ methodTypeParams |> Array.ofList - - let result = - match item.Item with - | Item.CtorGroup (_, (ILMeth (_,ilinfo,_)) :: _) -> - match ilinfo.MetadataScope with - | ILScopeRef.Assembly assemblyRef -> - let typeVarNames = getTypeVarNames ilinfo - ParamTypeSymbol.tryOfILTypes typeVarNames ilinfo.ILMethodRef.ArgTypes - |> Option.map (fun args -> - let externalSym = ExternalSymbol.Constructor (ilinfo.ILMethodRef.DeclaringTypeRef.FullName, args) - FSharpFindDeclResult.ExternalDecl (assemblyRef.Name, externalSym)) - | _ -> None - - | Item.MethodGroup (name, (ILMeth (_,ilinfo,_)) :: _, _) -> - match ilinfo.MetadataScope with - | ILScopeRef.Assembly assemblyRef -> - let typeVarNames = getTypeVarNames ilinfo - ParamTypeSymbol.tryOfILTypes typeVarNames ilinfo.ILMethodRef.ArgTypes - |> Option.map (fun args -> - let externalSym = ExternalSymbol.Method (ilinfo.ILMethodRef.DeclaringTypeRef.FullName, name, args, ilinfo.ILMethodRef.GenericArity) - FSharpFindDeclResult.ExternalDecl (assemblyRef.Name, externalSym)) - | _ -> None - - | Item.Property (name, ILProp propInfo :: _) -> - let methInfo = - if propInfo.HasGetter then Some propInfo.GetterMethod - elif propInfo.HasSetter then Some propInfo.SetterMethod - else None - - match methInfo with - | Some methInfo -> - match methInfo.MetadataScope with - | ILScopeRef.Assembly assemblyRef -> - let externalSym = ExternalSymbol.Property (methInfo.ILMethodRef.DeclaringTypeRef.FullName, name) - Some (FSharpFindDeclResult.ExternalDecl (assemblyRef.Name, externalSym)) - | _ -> None - | None -> None - - | Item.ILField (ILFieldInfo (typeInfo, fieldDef)) when not typeInfo.TyconRefOfRawMetadata.IsLocalRef -> - match typeInfo.ILScopeRef with - | ILScopeRef.Assembly assemblyRef -> - let externalSym = ExternalSymbol.Field (typeInfo.ILTypeRef.FullName, fieldDef.Name) - Some (FSharpFindDeclResult.ExternalDecl (assemblyRef.Name, externalSym)) - | _ -> None - - | Item.Event (ILEvent (ILEventInfo (typeInfo, eventDef))) when not typeInfo.TyconRefOfRawMetadata.IsLocalRef -> - match typeInfo.ILScopeRef with - | ILScopeRef.Assembly assemblyRef -> - let externalSym = ExternalSymbol.Event (typeInfo.ILTypeRef.FullName, eventDef.Name) - Some (FSharpFindDeclResult.ExternalDecl (assemblyRef.Name, externalSym)) - | _ -> None - - | Item.ImplicitOp(_, {contents = Some(TraitConstraintSln.FSMethSln(_, _vref, _))}) -> - //Item.Value(vref) - None - - | Item.Types (_, TType_app (tr, _) :: _) when tr.IsLocalRef && tr.IsTypeAbbrev -> None - - | Item.Types (_, [ AppTy g (tr, _) ]) when not tr.IsLocalRef -> - match tr.TypeReprInfo, tr.PublicPath with - | TILObjectRepr(TILObjectReprData (ILScopeRef.Assembly assemblyRef, _, _)), Some (PubPath parts) -> - let fullName = parts |> String.concat "." - Some (FSharpFindDeclResult.ExternalDecl (assemblyRef.Name, ExternalSymbol.Type fullName)) - | _ -> None - | _ -> None - match result with - | Some x -> x - | None -> - match rangeOfItem g preferFlag item.Item with - | Some itemRange -> - let projectDir = Filename.directoryName (if projectFileName = "" then mainInputFileName else projectFileName) - let range = fileNameOfItem g (Some projectDir) itemRange item.Item - mkRange range itemRange.Start itemRange.End - |> FSharpFindDeclResult.DeclFound - | None -> - match item.Item with -#if !NO_EXTENSIONTYPING -// provided items may have TypeProviderDefinitionLocationAttribute that binds them to some location - | Item.CtorGroup (name, ProvidedMeth (_)::_ ) - | Item.MethodGroup(name, ProvidedMeth (_)::_, _) - | Item.Property (name, ProvidedProp (_)::_ ) -> FSharpFindDeclFailureReason.ProvidedMember name - | Item.Event ( ProvidedEvent(_) as e ) -> FSharpFindDeclFailureReason.ProvidedMember e.EventName - | Item.ILField ( ProvidedField(_) as f ) -> FSharpFindDeclFailureReason.ProvidedMember f.FieldName - | SymbolHelpers.ItemIsProvidedType g (tcref) -> FSharpFindDeclFailureReason.ProvidedType tcref.DisplayName -#endif - | _ -> FSharpFindDeclFailureReason.Unknown "" - |> FSharpFindDeclResult.DeclNotFound - ) - (fun msg -> - Trace.TraceInformation(sprintf "FCS: recovering from error in GetDeclarationLocation: '%s'" msg) - FSharpFindDeclResult.DeclNotFound (FSharpFindDeclFailureReason.Unknown msg)) - - member __.GetSymbolUseAtLocation (ctok, line, lineStr, colAtEndOfNames, names) = - ErrorScope.Protect Range.range0 - (fun () -> - match GetDeclItemsForNamesAtPosition (ctok, None,Some(names), None, None, line, lineStr, colAtEndOfNames, ResolveTypeNamesToCtors, ResolveOverloads.Yes,(fun() -> []), fun _ -> false) with - | None | Some ([], _, _, _) -> None - | Some (item :: _, denv, _, m) -> - let symbol = FSharpSymbol.Create(cenv, item.Item) - Some (symbol, denv, m) - ) - (fun msg -> - Trace.TraceInformation(sprintf "FCS: recovering from error in GetSymbolUseAtLocation: '%s'" msg) - None) - - member __.PartialAssemblySignatureForFile = - FSharpAssemblySignature(g, thisCcu, ccuSigForFile, tcImports, None, ccuSigForFile) - - member __.AccessRights = tcAccessRights - - member __.GetReferencedAssemblies() = - [ for x in tcImports.GetImportedAssemblies() do - yield FSharpAssembly(g, tcImports, x.FSharpViewOfMetadata) ] - - member __.GetFormatSpecifierLocationsAndArity() = - sSymbolUses.GetFormatSpecifierLocationsAndArity() - - member __.GetSemanticClassification(range: range option) : (range * SemanticClassificationType) [] = - ErrorScope.Protect Range.range0 - (fun () -> - let (|LegitTypeOccurence|_|) = function - | ItemOccurence.UseInType - | ItemOccurence.UseInAttribute - | ItemOccurence.Use _ - | ItemOccurence.Binding _ - | ItemOccurence.Pattern _ -> Some() - | _ -> None - - let (|OptionalArgumentAttribute|_|) ttype = - match ttype with - | TType.TType_app(tref, _) when tref.Stamp = g.attrib_OptionalArgumentAttribute.TyconRef.Stamp -> Some() - | _ -> None - - let (|KeywordIntrinsicValue|_|) (vref: ValRef) = - if valRefEq g g.raise_vref vref || - valRefEq g g.reraise_vref vref || - valRefEq g g.typeof_vref vref || - valRefEq g g.typedefof_vref vref || - valRefEq g g.sizeof_vref vref - // TODO uncomment this after `nameof` operator is implemented - // || valRefEq g g.nameof_vref vref - then Some() - else None - - let (|EnumCaseFieldInfo|_|) (rfinfo : RecdFieldInfo) = - match rfinfo.TyconRef.TypeReprInfo with - | TFSharpObjectRepr x -> - match x.fsobjmodel_kind with - | TTyconEnum -> Some () - | _ -> None - | _ -> None - - let resolutions = - match range with - | Some range -> - sResolutions.CapturedNameResolutions - |> Seq.filter (fun cnr -> rangeContainsPos range cnr.Range.Start || rangeContainsPos range cnr.Range.End) - | None -> - sResolutions.CapturedNameResolutions :> seq<_> - - let isDisposableTy (ty: TType) = - protectAssemblyExplorationNoReraise false false (fun () -> Infos.ExistsHeadTypeInEntireHierarchy g amap range0 ty g.tcref_System_IDisposable) - - let isStructTyconRef (tyconRef: TyconRef) = - let ty = generalizedTyconRef tyconRef - let underlyingTy = stripTyEqnsAndMeasureEqns g ty - isStructTy g underlyingTy - - let isValRefMutable (vref: ValRef) = - // Mutable values, ref cells, and non-inref byrefs are mutable. - vref.IsMutable - || Tastops.isRefCellTy g vref.Type - || (Tastops.isByrefTy g vref.Type && not (Tastops.isInByrefTy g vref.Type)) - - let isRecdFieldMutable (rfinfo: RecdFieldInfo) = - (rfinfo.RecdField.IsMutable && rfinfo.LiteralValue.IsNone) - || Tastops.isRefCellTy g rfinfo.RecdField.FormalType - - resolutions - |> Seq.choose (fun cnr -> - match cnr with - // 'seq' in 'seq { ... }' gets colored as keywords - | CNR(_, (Item.Value vref), ItemOccurence.Use, _, _, _, m) when valRefEq g g.seq_vref vref -> - Some (m, SemanticClassificationType.ComputationExpression) - | CNR(_, (Item.Value vref), _, _, _, _, m) when isValRefMutable vref -> - Some (m, SemanticClassificationType.MutableVar) - | CNR(_, Item.Value KeywordIntrinsicValue, ItemOccurence.Use, _, _, _, m) -> - Some (m, SemanticClassificationType.IntrinsicFunction) - | CNR(_, (Item.Value vref), _, _, _, _, m) when isFunction g vref.Type -> - if valRefEq g g.range_op_vref vref || valRefEq g g.range_step_op_vref vref then - None - elif vref.IsPropertyGetterMethod || vref.IsPropertySetterMethod then - Some (m, SemanticClassificationType.Property) - elif IsOperatorName vref.DisplayName then - Some (m, SemanticClassificationType.Operator) - else - Some (m, SemanticClassificationType.Function) - | CNR(_, Item.RecdField rfinfo, _, _, _, _, m) when isRecdFieldMutable rfinfo -> - Some (m, SemanticClassificationType.MutableVar) - | CNR(_, Item.RecdField rfinfo, _, _, _, _, m) when isFunction g rfinfo.FieldType -> - Some (m, SemanticClassificationType.Function) - | CNR(_, Item.RecdField EnumCaseFieldInfo, _, _, _, _, m) -> - Some (m, SemanticClassificationType.Enumeration) - | CNR(_, Item.MethodGroup _, _, _, _, _, m) -> - Some (m, SemanticClassificationType.Function) - // custom builders, custom operations get colored as keywords - | CNR(_, (Item.CustomBuilder _ | Item.CustomOperation _), ItemOccurence.Use, _, _, _, m) -> - Some (m, SemanticClassificationType.ComputationExpression) - // types get colored as types when they occur in syntactic types or custom attributes - // typevariables get colored as types when they occur in syntactic types custom builders, custom operations get colored as keywords - | CNR(_, Item.Types (_, [OptionalArgumentAttribute]), LegitTypeOccurence, _, _, _, _) -> None - | CNR(_, Item.CtorGroup(_, [MethInfo.FSMeth(_, OptionalArgumentAttribute, _, _)]), LegitTypeOccurence, _, _, _, _) -> None - | CNR(_, Item.Types(_, types), LegitTypeOccurence, _, _, _, m) when types |> List.exists (isInterfaceTy g) -> - Some (m, SemanticClassificationType.Interface) - | CNR(_, Item.Types(_, types), LegitTypeOccurence, _, _, _, m) when types |> List.exists (isStructTy g) -> - Some (m, SemanticClassificationType.ValueType) - | CNR(_, Item.Types(_, TType_app(tyconRef, TType_measure _ :: _) :: _), LegitTypeOccurence, _, _, _, m) when isStructTyconRef tyconRef -> - Some (m, SemanticClassificationType.ValueType) - | CNR(_, Item.Types(_, types), LegitTypeOccurence, _, _, _, m) when types |> List.exists isDisposableTy -> - Some (m, SemanticClassificationType.Disposable) - | CNR(_, Item.Types _, LegitTypeOccurence, _, _, _, m) -> - Some (m, SemanticClassificationType.ReferenceType) - | CNR(_, (Item.TypeVar _ ), LegitTypeOccurence, _, _, _, m) -> - Some (m, SemanticClassificationType.TypeArgument) - | CNR(_, Item.UnqualifiedType tyconRefs, LegitTypeOccurence, _, _, _, m) -> - if tyconRefs |> List.exists (fun tyconRef -> tyconRef.Deref.IsStructOrEnumTycon) then - Some (m, SemanticClassificationType.ValueType) - else Some (m, SemanticClassificationType.ReferenceType) - | CNR(_, Item.CtorGroup(_, minfos), LegitTypeOccurence, _, _, _, m) -> - if minfos |> List.exists (fun minfo -> isStructTy g minfo.ApparentEnclosingType) then - Some (m, SemanticClassificationType.ValueType) - else Some (m, SemanticClassificationType.ReferenceType) - | CNR(_, Item.ExnCase _, LegitTypeOccurence, _, _, _, m) -> - Some (m, SemanticClassificationType.ReferenceType) - | CNR(_, Item.ModuleOrNamespaces refs, LegitTypeOccurence, _, _, _, m) when refs |> List.exists (fun x -> x.IsModule) -> - Some (m, SemanticClassificationType.Module) - | CNR(_, (Item.ActivePatternCase _ | Item.UnionCase _ | Item.ActivePatternResult _), _, _, _, _, m) -> - Some (m, SemanticClassificationType.UnionCase) - | _ -> None) - |> Seq.toArray - |> Array.append (sSymbolUses.GetFormatSpecifierLocationsAndArity() |> Array.map (fun m -> fst m, SemanticClassificationType.Printf)) - ) - (fun msg -> - Trace.TraceInformation(sprintf "FCS: recovering from error in GetSemanticClassification: '%s'" msg) - Array.empty) - - /// The resolutions in the file - member __.ScopeResolutions = sResolutions - - /// The uses of symbols in the analyzed file - member __.ScopeSymbolUses = sSymbolUses - - member __.TcGlobals = g - - member __.TcImports = tcImports - - /// The inferred signature of the file - member __.CcuSigForFile = ccuSigForFile - - /// The assembly being analyzed - member __.ThisCcu = thisCcu - - member __.ImplementationFile = implFileOpt - - /// All open declarations in the file, including auto open modules - member __.OpenDeclarations = openDeclarations - - member __.SymbolEnv = cenv - - override __.ToString() = "TypeCheckInfo(" + mainInputFileName + ")" - -type FSharpParsingOptions = - { SourceFiles: string [] - ConditionalCompilationDefines: string list - ErrorSeverityOptions: FSharpErrorSeverityOptions - IsInteractive: bool - LightSyntax: bool option - CompilingFsLib: bool - IsExe: bool } - - member x.LastFileName = - Debug.Assert(not (Array.isEmpty x.SourceFiles), "Parsing options don't contain any file") - Array.last x.SourceFiles - - static member Default = - { SourceFiles = Array.empty - ConditionalCompilationDefines = [] - ErrorSeverityOptions = FSharpErrorSeverityOptions.Default - IsInteractive = false - LightSyntax = None - CompilingFsLib = false - IsExe = false } - - static member FromTcConfig(tcConfig: TcConfig, sourceFiles, isInteractive: bool) = - { SourceFiles = sourceFiles - ConditionalCompilationDefines = tcConfig.conditionalCompilationDefines - ErrorSeverityOptions = tcConfig.errorSeverityOptions - IsInteractive = isInteractive - LightSyntax = tcConfig.light - CompilingFsLib = tcConfig.compilingFslib - IsExe = tcConfig.target.IsExe } - -#if !FABLE_COMPILER - static member FromTcConfigBuidler(tcConfigB: TcConfigBuilder, sourceFiles, isInteractive: bool) = - { - SourceFiles = sourceFiles - ConditionalCompilationDefines = tcConfigB.conditionalCompilationDefines - ErrorSeverityOptions = tcConfigB.errorSeverityOptions - IsInteractive = isInteractive - LightSyntax = tcConfigB.light - CompilingFsLib = tcConfigB.compilingFslib - IsExe = tcConfigB.target.IsExe - } -#endif //!FABLE_COMPILER - -module internal Parser = - - // We'll need number of lines for adjusting error messages at EOF - let GetFileInfoForLastLineErrors (source: string) = - // number of lines in the source file - let lastLine = (source |> Seq.sumBy (fun c -> if c = '\n' then 1 else 0)) + 1 - // length of the last line -#if FABLE_COMPILER - let lastLineLength = source.Length - source.LastIndexOf("\n") - 1 -#else - let lastLineLength = source.Length - source.LastIndexOf("\n",StringComparison.Ordinal) - 1 -#endif - lastLine, lastLineLength - - - /// Error handler for parsing & type checking while processing a single file - type ErrorHandler(reportErrors, mainInputFileName, errorSeverityOptions: FSharpErrorSeverityOptions, source) = - let mutable options = errorSeverityOptions - let errorsAndWarningsCollector = new ResizeArray<_>() - let mutable errorCount = 0 - - // We'll need number of lines for adjusting error messages at EOF - let fileInfo = GetFileInfoForLastLineErrors source - - // This function gets called whenever an error happens during parsing or checking - let diagnosticSink sev (exn: PhasedDiagnostic) = - // Sanity check here. The phase of an error should be in a phase known to the language service. - let exn = - if not(exn.IsPhaseInCompile()) then - // Reaching this point means that the error would be sticky if we let it prop up to the language service. - // Assert and recover by replacing phase with one known to the language service. - Trace.TraceInformation(sprintf "The subcategory '%s' seen in an error should not be seen by the language service" (exn.Subcategory())) - { exn with Phase = BuildPhase.TypeCheck } - else exn - if reportErrors then - let report exn = - for ei in ErrorHelpers.ReportError (options, false, mainInputFileName, fileInfo, (exn, sev)) do - errorsAndWarningsCollector.Add ei - if sev = FSharpErrorSeverity.Error then - errorCount <- errorCount + 1 - - match exn with -#if !NO_EXTENSIONTYPING - | { Exception = (:? TypeProviderError as tpe) } -> tpe.Iter(fun e -> report { exn with Exception = e }) -#endif - | e -> report e - - let errorLogger = - { new ErrorLogger("ErrorHandler") with - member x.DiagnosticSink (exn, isError) = diagnosticSink (if isError then FSharpErrorSeverity.Error else FSharpErrorSeverity.Warning) exn - member x.ErrorCount = errorCount } - - // Public members - member x.ErrorLogger = errorLogger - member x.CollectedDiagnostics = errorsAndWarningsCollector.ToArray() - member x.ErrorCount = errorCount - member x.ErrorSeverityOptions with set opts = options <- opts - member x.AnyErrors = errorCount > 0 - - let getLightSyntaxStatus fileName options = - let lower = String.lowercase fileName - let lightOnByDefault = List.exists (Filename.checkSuffix lower) FSharpLightSyntaxFileSuffixes - let lightSyntaxStatus = if lightOnByDefault then (options.LightSyntax <> Some false) else (options.LightSyntax = Some true) - LightSyntaxStatus(lightSyntaxStatus, true) - - let createLexerFunction fileName options lexbuf (errHandler: ErrorHandler) = - let lightSyntaxStatus = getLightSyntaxStatus fileName options - - // If we're editing a script then we define INTERACTIVE otherwise COMPILED. - // Since this parsing for intellisense we always define EDITING. - let defines = (SourceFileImpl.AdditionalDefinesForUseInEditor options.IsInteractive) @ options.ConditionalCompilationDefines - - // Note: we don't really attempt to intern strings across a large scope. - let lexResourceManager = new Lexhelp.LexResourceManager() - - // When analyzing files using ParseOneFile, i.e. for the use of editing clients, we do not apply line directives. - let lexargs = mkLexargs(fileName, defines, lightSyntaxStatus, lexResourceManager, ref [], errHandler.ErrorLogger) - let lexargs = { lexargs with applyLineDirectives = false } - - let tokenizer = LexFilter.LexFilter(lightSyntaxStatus, options.CompilingFsLib, Lexer.token lexargs true, lexbuf) - tokenizer.Lexer - - // Adding this new-line character at the end of the source seems odd but is required for some unit tests - // Todo: fix tests - let addNewLine (source: string) = - if source.Length = 0 || not (source.[source.Length - 1] = '\n') then source + "\n" else source - - let matchBraces(source, fileName, options: FSharpParsingOptions, userOpName: string) = - let delayedLogger = CapturingErrorLogger("matchBraces") - use _unwindEL = PushErrorLoggerPhaseUntilUnwind (fun _ -> delayedLogger) - use _unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse - - Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "matchBraces", fileName) - - // Make sure there is an ErrorLogger installed whenever we do stuff that might record errors, even if we ultimately ignore the errors - let delayedLogger = CapturingErrorLogger("matchBraces") - use _unwindEL = PushErrorLoggerPhaseUntilUnwind (fun _ -> delayedLogger) - use _unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse - - let matchingBraces = new ResizeArray<_>() - Lexhelp.usingLexbufForParsing(UnicodeLexing.StringAsLexbuf(addNewLine source), fileName) (fun lexbuf -> - let errHandler = ErrorHandler(false, fileName, options.ErrorSeverityOptions, source) - let lexfun = createLexerFunction fileName options lexbuf errHandler - let parenTokensBalance t1 t2 = - match t1, t2 with - | (LPAREN, RPAREN) - | (LPAREN, RPAREN_IS_HERE) - | (LBRACE, RBRACE) - | (LBRACE, RBRACE_IS_HERE) - | (SIG, END) - | (STRUCT, END) - | (LBRACK_BAR, BAR_RBRACK) - | (LBRACK, RBRACK) - | (LBRACK_LESS, GREATER_RBRACK) - | (BEGIN, END) -> true - | (LQUOTE q1, RQUOTE q2) -> q1 = q2 - | _ -> false - let rec matchBraces stack = - match lexfun lexbuf, stack with - | tok2, ((tok1, m1) :: stack') when parenTokensBalance tok1 tok2 -> - matchingBraces.Add(m1, lexbuf.LexemeRange) - matchBraces stack' - | ((LPAREN | LBRACE | LBRACK | LBRACK_BAR | LQUOTE _ | LBRACK_LESS) as tok), _ -> - matchBraces ((tok, lexbuf.LexemeRange) :: stack) - | (EOF _ | LEX_FAILURE _), _ -> () - | _ -> matchBraces stack - matchBraces []) - matchingBraces.ToArray() - - let parseFile(source, fileName, options: FSharpParsingOptions, userOpName: string) = - Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "parseFile", fileName) - let errHandler = new ErrorHandler(true, fileName, options.ErrorSeverityOptions, source) - use unwindEL = PushErrorLoggerPhaseUntilUnwind (fun _oldLogger -> errHandler.ErrorLogger) - use unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse - - let parseResult = - Lexhelp.usingLexbufForParsing(UnicodeLexing.StringAsLexbuf(addNewLine source), fileName) (fun lexbuf -> - let lexfun = createLexerFunction fileName options lexbuf errHandler - let isLastCompiland = -#if FABLE_COMPILER - fileName.Equals(options.LastFileName, StringComparison.OrdinalIgnoreCase) || -#else - fileName.Equals(options.LastFileName, StringComparison.CurrentCultureIgnoreCase) || -#endif - CompileOps.IsScript(fileName) - let isExe = options.IsExe - try Some (ParseInput(lexfun, errHandler.ErrorLogger, lexbuf, None, fileName, (isLastCompiland, isExe))) - with e -> - errHandler.ErrorLogger.StopProcessingRecovery e Range.range0 // don't re-raise any exceptions, we must return None. - None) - errHandler.CollectedDiagnostics, parseResult, errHandler.AnyErrors - - /// Indicates if the type check got aborted because it is no longer relevant. - type TypeCheckAborted = Yes | No of TypeCheckInfo - - // Type check a single file against an initial context, gleaning both errors and intellisense information. - let CheckOneFile - (parseResults: FSharpParseFileResults, - source: string, - mainInputFileName: string, - projectFileName: string, - tcConfig: TcConfig, - tcGlobals: TcGlobals, - tcImports: TcImports, - tcState: TcState, - moduleNamesDict: ModuleNamesDict, - loadClosure: LoadClosure option, - // These are the errors and warnings seen by the background compiler for the entire antecedent - backgroundDiagnostics: (PhasedDiagnostic * FSharpErrorSeverity)[], - reactorOps: IReactorOperations, - // Used by 'FSharpDeclarationListInfo' to check the IncrementalBuilder is still alive. - checkAlive : (unit -> bool), - textSnapshotInfo : obj option, - userOpName: string) = - -#if !FABLE_COMPILER - async { -#endif - use _logBlock = Logger.LogBlock LogCompilerFunctionId.Service_CheckOneFile - - match parseResults.ParseTree with - // When processing the following cases, we don't need to type-check -#if FABLE_COMPILER - | None -> [||], TypeCheckAborted.Yes -#else - | None -> return [||], TypeCheckAborted.Yes -#endif - - // Run the type checker... - | Some parsedMainInput -> - // Initialize the error handler - let errHandler = new ErrorHandler(true, mainInputFileName, tcConfig.errorSeverityOptions, source) - - use _unwindEL = PushErrorLoggerPhaseUntilUnwind (fun _oldLogger -> errHandler.ErrorLogger) - use _unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.TypeCheck - -#if !FABLE_COMPILER - // Apply nowarns to tcConfig (may generate errors, so ensure errorLogger is installed) - let tcConfig = ApplyNoWarnsToTcConfig (tcConfig, parsedMainInput,Path.GetDirectoryName mainInputFileName) -#endif - - // update the error handler with the modified tcConfig - errHandler.ErrorSeverityOptions <- tcConfig.errorSeverityOptions - - // Play background errors and warnings for this file. - for (err,sev) in backgroundDiagnostics do - diagnosticSink (err, (sev = FSharpErrorSeverity.Error)) - -#if !FABLE_COMPILER - // If additional references were brought in by the preprocessor then we need to process them - match loadClosure with - | Some loadClosure -> - // Play unresolved references for this file. - tcImports.ReportUnresolvedAssemblyReferences(loadClosure.UnresolvedReferences) - - // If there was a loadClosure, replay the errors and warnings from resolution, excluding parsing - loadClosure.LoadClosureRootFileDiagnostics |> List.iter diagnosticSink - - let fileOfBackgroundError err = (match GetRangeOfDiagnostic (fst err) with Some m-> m.FileName | None -> null) - let sameFile file hashLoadInFile = - (0 = String.Compare(hashLoadInFile, file, StringComparison.OrdinalIgnoreCase)) - - // walk the list of #loads and keep the ones for this file. - let hashLoadsInFile = - loadClosure.SourceFiles - |> List.filter(fun (_,ms) -> ms<>[]) // #loaded file, ranges of #load - - let hashLoadBackgroundDiagnostics, otherBackgroundDiagnostics = - backgroundDiagnostics - |> Array.partition (fun backgroundError -> - hashLoadsInFile - |> List.exists (fst >> sameFile (fileOfBackgroundError backgroundError))) - - // Create single errors for the #load-ed files. - // Group errors and warnings by file name. - let hashLoadBackgroundDiagnosticsGroupedByFileName = - hashLoadBackgroundDiagnostics - |> Array.map(fun err -> fileOfBackgroundError err,err) - |> Array.groupBy fst // fileWithErrors, error list - - // Join the sets and report errors. - // It is by-design that these messages are only present in the language service. A true build would report the errors at their - // spots in the individual source files. - for (fileOfHashLoad, rangesOfHashLoad) in hashLoadsInFile do - for (file, errorGroupedByFileName) in hashLoadBackgroundDiagnosticsGroupedByFileName do - if sameFile file fileOfHashLoad then - for rangeOfHashLoad in rangesOfHashLoad do // Handle the case of two #loads of the same file - let diagnostics = errorGroupedByFileName |> Array.map(fun (_,(pe,f)) -> pe.Exception,f) // Strip the build phase here. It will be replaced, in total, with TypeCheck - let errors = [ for (err,sev) in diagnostics do if sev = FSharpErrorSeverity.Error then yield err ] - let warnings = [ for (err,sev) in diagnostics do if sev = FSharpErrorSeverity.Warning then yield err ] - - let message = HashLoadedSourceHasIssues(warnings,errors,rangeOfHashLoad) - if errors=[] then warning(message) - else errorR(message) - - // Replay other background errors. - for (phasedError,sev) in otherBackgroundDiagnostics do - if sev = FSharpErrorSeverity.Warning then - warning phasedError.Exception - else errorR phasedError.Exception - - | None -> - // For non-scripts, check for disallow #r and #load. - ApplyMetaCommandsFromInputToTcConfig (tcConfig, parsedMainInput,Path.GetDirectoryName mainInputFileName) |> ignore -#endif - - // A problem arises with nice name generation, which really should only - // be done in the backend, but is also done in the typechecker for better or worse. - // If we don't do this the NNG accumulates data and we get a memory leak. - tcState.NiceNameGenerator.Reset() - - // Typecheck the real input. - let sink = TcResultsSinkImpl(tcGlobals, source = source) -#if FABLE_COMPILER - ignore userOpName - let resOpt = - try - let ctok = AssumeCompilationThreadWithoutEvidence() - let checkForErrors() = (parseResults.ParseHadErrors || errHandler.ErrorCount > 0) - let parsedMainInput, _moduleNamesDict = DeduplicateParsedInputModuleName moduleNamesDict parsedMainInput - let (tcEnvAtEnd, _, implFiles, ccuSigsForFiles), tcState = - TypeCheckOneInputAndFinishEventually(checkForErrors, tcConfig, tcImports, tcGlobals, None, TcResultsSink.WithSink sink, tcState, parsedMainInput) - |> Eventually.force ctok - Some (tcEnvAtEnd, implFiles, ccuSigsForFiles, tcState) - with - | e -> - errorR e - Some(tcState.TcEnvFromSignatures, [], [NewEmptyModuleOrNamespaceType Namespace], tcState) -#else //!FABLE_COMPILER - let! ct = Async.CancellationToken - - let! resOpt = - async { - try - let checkForErrors() = (parseResults.ParseHadErrors || errHandler.ErrorCount > 0) - - let parsedMainInput, _moduleNamesDict = DeduplicateParsedInputModuleName moduleNamesDict parsedMainInput - - // Typecheck is potentially a long running operation. We chop it up here with an Eventually continuation and, at each slice, give a chance - // for the client to claim the result as obsolete and have the typecheck abort. - - let! result = - TypeCheckOneInputAndFinishEventually(checkForErrors, tcConfig, tcImports, tcGlobals, None, TcResultsSink.WithSink sink, tcState, parsedMainInput) - |> Eventually.repeatedlyProgressUntilDoneOrTimeShareOverOrCanceled maxTimeShareMilliseconds ct (fun ctok f -> f ctok) - |> Eventually.forceAsync - (fun work -> - reactorOps.EnqueueAndAwaitOpAsync(userOpName, "CheckOneFile.Fragment", mainInputFileName, - fun ctok -> - // This work is not cancellable - let res = - // Reinstall the compilation globals each time we start or restart - use unwind = new CompilationGlobalsScope (errHandler.ErrorLogger, BuildPhase.TypeCheck) - work ctok - cancellable.Return(res) - )) - - return result |> Option.map (fun ((tcEnvAtEnd, _, implFiles, ccuSigsForFiles), tcState) -> tcEnvAtEnd, implFiles, ccuSigsForFiles, tcState) - with e -> - errorR e - return Some(tcState.TcEnvFromSignatures, [], [NewEmptyModuleOrNamespaceType Namespace], tcState) - } -#endif //!FABLE_COMPILER - - let errors = errHandler.CollectedDiagnostics - - match resOpt with - | Some (tcEnvAtEnd, implFiles, ccuSigsForFiles, tcState) -> - let scope = - TypeCheckInfo(tcConfig, tcGlobals, - List.head ccuSigsForFiles, - tcState.Ccu, - tcImports, - tcEnvAtEnd.AccessRights, - projectFileName, - mainInputFileName, - sink.GetResolutions(), - sink.GetSymbolUses(), - tcEnvAtEnd.NameEnv, - loadClosure, - reactorOps, - checkAlive, - textSnapshotInfo, - List.tryHead implFiles, - sink.GetOpenDeclarations()) -#if FABLE_COMPILER - errors, TypeCheckAborted.No scope - | None -> - errors, TypeCheckAborted.Yes -#else - return errors, TypeCheckAborted.No scope - | None -> - return errors, TypeCheckAborted.Yes - } -#endif - type UnresolvedReferencesSet = UnresolvedReferencesSet of UnresolvedAssemblyReference list // NOTE: may be better just to move to optional arguments here @@ -1836,7 +56,7 @@ type FSharpProjectOptions = UseScriptResolutionRules : bool LoadTime : System.DateTime UnresolvedReferences : UnresolvedReferencesSet option - OriginalLoadReferences: (range * string) list + OriginalLoadReferences: (range * string * string) list ExtraProjectInfo : obj option Stamp : int64 option } @@ -1870,359 +90,12 @@ type FSharpProjectOptions = member po.ProjectDirectory = System.IO.Path.GetDirectoryName(po.ProjectFileName) override this.ToString() = "FSharpProjectOptions(" + this.ProjectFileName + ")" - -[] -type FSharpProjectContext(thisCcu: CcuThunk, assemblies: FSharpAssembly list, ad: AccessorDomain) = - - /// Get the assemblies referenced - member __.GetReferencedAssemblies() = assemblies - - member __.AccessibilityRights = FSharpAccessibilityRights(thisCcu, ad) - - -[] -// 'details' is an option because the creation of the tcGlobals etc. for the project may have failed. -type FSharpCheckProjectResults(projectFileName:string, tcConfigOption, keepAssemblyContents:bool, errors: FSharpErrorInfo[], - details:(TcGlobals * TcImports * CcuThunk * ModuleOrNamespaceType * TcSymbolUses list * TopAttribs option * CompileOps.IRawFSharpAssemblyData option * ILAssemblyRef * AccessorDomain * TypedImplFile list option * string[]) option) = - - let getDetails() = - match details with - | None -> invalidOp ("The project has no results due to critical errors in the project options. Check the HasCriticalErrors before accessing the detailed results. Errors: " + String.concat "\n" [ for e in errors -> e.Message ]) - | Some d -> d - - let getTcConfig() = - match tcConfigOption with - | None -> invalidOp ("The project has no results due to critical errors in the project options. Check the HasCriticalErrors before accessing the detailed results. Errors: " + String.concat "\n" [ for e in errors -> e.Message ]) - | Some d -> d - - member info.Errors = errors - - member info.HasCriticalErrors = details.IsNone - - member info.AssemblySignature = - let (tcGlobals, tcImports, thisCcu, ccuSig, _tcSymbolUses, topAttribs, _tcAssemblyData, _ilAssemRef, _ad, _tcAssemblyExpr, _dependencyFiles) = getDetails() - FSharpAssemblySignature(tcGlobals, thisCcu, ccuSig, tcImports, topAttribs, ccuSig) - - member info.TypedImplementionFiles = - if not keepAssemblyContents then invalidOp "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" - let (tcGlobals, tcImports, thisCcu, _ccuSig, _tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, tcAssemblyExpr, _dependencyFiles) = getDetails() - let mimpls = - match tcAssemblyExpr with - | None -> [] - | Some mimpls -> mimpls - tcGlobals, thisCcu, tcImports, mimpls - - member info.AssemblyContents = - if not keepAssemblyContents then invalidOp "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" - let (tcGlobals, tcImports, thisCcu, ccuSig, _tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, tcAssemblyExpr, _dependencyFiles) = getDetails() - let mimpls = - match tcAssemblyExpr with - | None -> [] - | Some mimpls -> mimpls - FSharpAssemblyContents(tcGlobals, thisCcu, Some ccuSig, tcImports, mimpls) - - member info.GetOptimizedAssemblyContents() = - if not keepAssemblyContents then invalidOp "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" - let (tcGlobals, tcImports, thisCcu, ccuSig, _tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, tcAssemblyExpr, _dependencyFiles) = getDetails() - let mimpls = - match tcAssemblyExpr with - | None -> [] - | Some mimpls -> mimpls - let outfile = "" // only used if tcConfig.writeTermsToFiles is true - let importMap = tcImports.GetImportMap() - let optEnv0 = GetInitialOptimizationEnv (tcImports, tcGlobals) - let tcConfig = getTcConfig() - let optimizedImpls, _optimizationData, _ = ApplyAllOptimizations (tcConfig, tcGlobals, (LightweightTcValForUsingInBuildMethodCall tcGlobals), outfile, importMap, false, optEnv0, thisCcu, mimpls) - let mimpls = - match optimizedImpls with - | TypedAssemblyAfterOptimization files -> - files |> List.map fst - - FSharpAssemblyContents(tcGlobals, thisCcu, Some ccuSig, tcImports, mimpls) - - // Not, this does not have to be a SyncOp, it can be called from any thread - member info.GetUsesOfSymbol(symbol:FSharpSymbol) = - let (tcGlobals, _tcImports, _thisCcu, _ccuSig, tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, _tcAssemblyExpr, _dependencyFiles) = getDetails() - - tcSymbolUses - |> Seq.collect (fun r -> r.GetUsesOfSymbol symbol.Item) - |> Seq.distinctBy (fun symbolUse -> symbolUse.ItemOccurence, symbolUse.Range) - |> Seq.filter (fun symbolUse -> symbolUse.ItemOccurence <> ItemOccurence.RelatedText) - |> Seq.map (fun symbolUse -> FSharpSymbolUse(tcGlobals, symbolUse.DisplayEnv, symbol, symbolUse.ItemOccurence, symbolUse.Range)) - |> Seq.toArray - |> async.Return - - // Not, this does not have to be a SyncOp, it can be called from any thread - member __.GetAllUsesOfAllSymbols() = - let (tcGlobals, tcImports, thisCcu, ccuSig, tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, _tcAssemblyExpr, _dependencyFiles) = getDetails() - let cenv = SymbolEnv(tcGlobals, thisCcu, Some ccuSig, tcImports) - - [| for r in tcSymbolUses do - for symbolUseChunk in r.AllUsesOfSymbols do - for symbolUse in symbolUseChunk do - if symbolUse.ItemOccurence <> ItemOccurence.RelatedText then - let symbol = FSharpSymbol.Create(cenv, symbolUse.Item) - yield FSharpSymbolUse(tcGlobals, symbolUse.DisplayEnv, symbol, symbolUse.ItemOccurence, symbolUse.Range) |] - |> async.Return - - member __.ProjectContext = - let (tcGlobals, tcImports, thisCcu, _ccuSig, _tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, ad, _tcAssemblyExpr, _dependencyFiles) = getDetails() - let assemblies = - [ for x in tcImports.GetImportedAssemblies() do - yield FSharpAssembly(tcGlobals, tcImports, x.FSharpViewOfMetadata) ] - FSharpProjectContext(thisCcu, assemblies, ad) - - member __.RawFSharpAssemblyData = - let (_tcGlobals, _tcImports, _thisCcu, _ccuSig, _tcSymbolUses, _topAttribs, tcAssemblyData, _ilAssemRef, _ad, _tcAssemblyExpr, _dependencyFiles) = getDetails() - tcAssemblyData - - member __.DependencyFiles = - let (_tcGlobals, _tcImports, _thisCcu, _ccuSig, _tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, _tcAssemblyExpr, dependencyFiles) = getDetails() - dependencyFiles - - member __.AssemblyFullName = - let (_tcGlobals, _tcImports, _thisCcu, _ccuSig, _tcSymbolUses, _topAttribs, _tcAssemblyData, ilAssemRef, _ad, _tcAssemblyExpr, _dependencyFiles) = getDetails() - ilAssemRef.QualifiedName - - override info.ToString() = "FSharpCheckProjectResults(" + projectFileName + ")" - -[] -/// A live object of this type keeps the background corresponding background builder (and type providers) alive (through reference-counting). -// -// There is an important property of all the objects returned by the methods of this type: they do not require -// the corresponding background builder to be alive. That is, they are simply plain-old-data through pre-formatting of all result text. -type FSharpCheckFileResults(filename: string, errors: FSharpErrorInfo[], scopeOptX: TypeCheckInfo option, dependencyFiles: string[], builderX: IncrementalBuilder option, reactorOpsX:IReactorOperations, keepAssemblyContents: bool) = - - // This may be None initially, or may be set to None when the object is disposed or finalized - let mutable details = match scopeOptX with None -> None | Some scopeX -> Some (scopeX, builderX, reactorOpsX) - - // Increment the usage count on the IncrementalBuilder. We want to keep the IncrementalBuilder and all associated - // resources and type providers alive for the duration of the lifetime of this object. - let decrementer = - match details with - | Some (_,builderOpt,_) -> IncrementalBuilder.KeepBuilderAlive builderOpt - | _ -> { new System.IDisposable with member x.Dispose() = () } - - let mutable disposed = false - - let dispose() = - if not disposed then - disposed <- true - match details with - | Some (_,_,reactor) -> - // Make sure we run disposal in the reactor thread, since it may trigger type provider disposals etc. - details <- None - reactor.EnqueueOp ("GCFinalizer","FSharpCheckFileResults.DecrementUsageCountOnIncrementalBuilder", filename, fun ctok -> - RequireCompilationThread ctok - decrementer.Dispose()) - | _ -> () - - // Run an operation that needs to access a builder and be run in the reactor thread - let reactorOp userOpName opName dflt f = - async { - match details with - | None -> - return dflt - | Some (_, Some builder, _) when not builder.IsAlive -> - System.Diagnostics.Debug.Assert(false,"unexpected dead builder") - return dflt - | Some (scope, builderOpt, reactor) -> - // Increment the usage count to ensure the builder doesn't get released while running operations asynchronously. - use _unwind = IncrementalBuilder.KeepBuilderAlive builderOpt - let! res = reactor.EnqueueAndAwaitOpAsync(userOpName, opName, filename, fun ctok -> f ctok scope |> cancellable.Return) - return res - } - - // Run an operation that can be called from any thread - let threadSafeOp dflt f = - match details with - | None -> dflt() - | Some (scope, _builderOpt, _ops) -> f scope - - // At the moment we only dispose on finalize - we never explicitly dispose these objects. Explicitly disposing is not - // really worth much since the underlying project builds are likely to still be in the incrementalBuilder cache. - override info.Finalize() = dispose() - - member info.Errors = errors - - member info.HasFullTypeCheckInfo = details.IsSome - - /// Intellisense autocompletions - member info.GetDeclarationListInfo(parseResultsOpt, line, lineStr, partialName, ?getAllEntities, ?hasTextChangedSinceLastTypecheck, ?userOpName: string) = - let userOpName = defaultArg userOpName "Unknown" - let getAllEntities = defaultArg getAllEntities (fun() -> []) - let hasTextChangedSinceLastTypecheck = defaultArg hasTextChangedSinceLastTypecheck (fun _ -> false) - reactorOp userOpName "GetDeclarations" FSharpDeclarationListInfo.Empty (fun ctok scope -> - scope.GetDeclarations(ctok, parseResultsOpt, line, lineStr, partialName, getAllEntities, hasTextChangedSinceLastTypecheck)) - - member info.GetDeclarationListSymbols(parseResultsOpt, line, lineStr, partialName, ?getAllEntities, ?hasTextChangedSinceLastTypecheck, ?userOpName: string) = - let userOpName = defaultArg userOpName "Unknown" - let hasTextChangedSinceLastTypecheck = defaultArg hasTextChangedSinceLastTypecheck (fun _ -> false) - let getAllEntities = defaultArg getAllEntities (fun() -> []) - reactorOp userOpName "GetDeclarationListSymbols" List.empty (fun ctok scope -> scope.GetDeclarationListSymbols(ctok, parseResultsOpt, line, lineStr, partialName, getAllEntities, hasTextChangedSinceLastTypecheck)) - - /// Resolve the names at the given location to give a data tip - member info.GetStructuredToolTipText(line, colAtEndOfNames, lineStr, names, tokenTag, ?userOpName: string) = - let userOpName = defaultArg userOpName "Unknown" - let dflt = FSharpToolTipText [] - match tokenTagToTokenId tokenTag with - | TOKEN_IDENT -> - reactorOp userOpName "GetStructuredToolTipText" dflt (fun ctok scope -> scope.GetStructuredToolTipText(ctok, line, lineStr, colAtEndOfNames, names)) - | TOKEN_STRING | TOKEN_STRING_TEXT -> - reactorOp userOpName "GetReferenceResolutionToolTipText" dflt (fun ctok scope -> scope.GetReferenceResolutionStructuredToolTipText(ctok, line, colAtEndOfNames) ) - | _ -> - async.Return dflt - - - member info.GetToolTipText(line, colAtEndOfNames, lineStr, names, tokenTag, userOpName) = - info.GetStructuredToolTipText(line, colAtEndOfNames, lineStr, names, tokenTag, ?userOpName=userOpName) - |> Tooltips.Map Tooltips.ToFSharpToolTipText - - member info.GetF1Keyword (line, colAtEndOfNames, lineStr, names, ?userOpName: string) = - let userOpName = defaultArg userOpName "Unknown" - reactorOp userOpName "GetF1Keyword" None (fun ctok scope -> - scope.GetF1Keyword (ctok, line, lineStr, colAtEndOfNames, names)) - - // Resolve the names at the given location to a set of methods - member info.GetMethods(line, colAtEndOfNames, lineStr, names, ?userOpName: string) = - let userOpName = defaultArg userOpName "Unknown" - let dflt = FSharpMethodGroup("",[| |]) - reactorOp userOpName "GetMethods" dflt (fun ctok scope -> - scope.GetMethods (ctok, line, lineStr, colAtEndOfNames, names)) - - member info.GetDeclarationLocation (line, colAtEndOfNames, lineStr, names, ?preferFlag, ?userOpName: string) = - let userOpName = defaultArg userOpName "Unknown" - let dflt = FSharpFindDeclResult.DeclNotFound (FSharpFindDeclFailureReason.Unknown "") - reactorOp userOpName "GetDeclarationLocation" dflt (fun ctok scope -> - scope.GetDeclarationLocation (ctok, line, lineStr, colAtEndOfNames, names, preferFlag)) - - member info.GetSymbolUseAtLocation (line, colAtEndOfNames, lineStr, names, ?userOpName: string) = - let userOpName = defaultArg userOpName "Unknown" - reactorOp userOpName "GetSymbolUseAtLocation" None (fun ctok scope -> - scope.GetSymbolUseAtLocation (ctok, line, lineStr, colAtEndOfNames, names) - |> Option.map (fun (sym,denv,m) -> FSharpSymbolUse(scope.TcGlobals,denv,sym,ItemOccurence.Use,m))) - - member info.GetMethodsAsSymbols (line, colAtEndOfNames, lineStr, names, ?userOpName: string) = - let userOpName = defaultArg userOpName "Unknown" - reactorOp userOpName "GetMethodsAsSymbols" None (fun ctok scope -> - scope.GetMethodsAsSymbols (ctok, line, lineStr, colAtEndOfNames, names) - |> Option.map (fun (symbols,denv,m) -> - symbols |> List.map (fun sym -> FSharpSymbolUse(scope.TcGlobals,denv,sym,ItemOccurence.Use,m)))) - - member info.GetSymbolAtLocation (line, colAtEndOfNames, lineStr, names, ?userOpName: string) = - let userOpName = defaultArg userOpName "Unknown" - reactorOp userOpName "GetSymbolAtLocation" None (fun ctok scope -> - scope.GetSymbolUseAtLocation (ctok, line, lineStr, colAtEndOfNames, names) - |> Option.map (fun (sym,_,_) -> sym)) - - member info.GetFormatSpecifierLocations() = - info.GetFormatSpecifierLocationsAndArity() |> Array.map fst - - member info.GetFormatSpecifierLocationsAndArity() = - threadSafeOp - (fun () -> [| |]) - (fun scope -> - // This operation is not asynchronous - GetFormatSpecifierLocationsAndArity can be run on the calling thread - scope.GetFormatSpecifierLocationsAndArity()) - - member __.GetSemanticClassification(range: range option) = - threadSafeOp - (fun () -> [| |]) - (fun scope -> - // This operation is not asynchronous - GetSemanticClassification can be run on the calling thread - scope.GetSemanticClassification(range)) - - member __.PartialAssemblySignature = - threadSafeOp - (fun () -> failwith "not available") - (fun scope -> - // This operation is not asynchronous - PartialAssemblySignature can be run on the calling thread - scope.PartialAssemblySignatureForFile) - - member __.ProjectContext = - threadSafeOp - (fun () -> failwith "not available") - (fun scope -> - // This operation is not asynchronous - GetReferencedAssemblies can be run on the calling thread - FSharpProjectContext(scope.ThisCcu, scope.GetReferencedAssemblies(), scope.AccessRights)) - - member __.DependencyFiles = dependencyFiles - - member info.GetAllUsesOfAllSymbolsInFile() = - threadSafeOp - (fun () -> [| |]) - (fun scope -> - let cenv = scope.SymbolEnv - [| for symbolUseChunk in scope.ScopeSymbolUses.AllUsesOfSymbols do - for symbolUse in symbolUseChunk do - if symbolUse.ItemOccurence <> ItemOccurence.RelatedText then - let symbol = FSharpSymbol.Create(cenv, symbolUse.Item) - yield FSharpSymbolUse(scope.TcGlobals, symbolUse.DisplayEnv, symbol, symbolUse.ItemOccurence, symbolUse.Range) |]) - |> async.Return - - member info.GetUsesOfSymbolInFile(symbol:FSharpSymbol) = - threadSafeOp - (fun () -> [| |]) - (fun scope -> - [| for symbolUse in scope.ScopeSymbolUses.GetUsesOfSymbol(symbol.Item) |> Seq.distinctBy (fun symbolUse -> symbolUse.ItemOccurence, symbolUse.Range) do - if symbolUse.ItemOccurence <> ItemOccurence.RelatedText then - yield FSharpSymbolUse(scope.TcGlobals, symbolUse.DisplayEnv, symbol, symbolUse.ItemOccurence, symbolUse.Range) |]) - |> async.Return - - member info.GetVisibleNamespacesAndModulesAtPoint(pos: pos) = - threadSafeOp - (fun () -> [| |]) - (fun scope -> scope.GetVisibleNamespacesAndModulesAtPosition(pos) |> List.toArray) - |> async.Return - - member info.IsRelativeNameResolvable(pos: pos, plid: string list, item: Item, ?userOpName: string) = - let userOpName = defaultArg userOpName "Unknown" - reactorOp userOpName "IsRelativeNameResolvable" true (fun ctok scope -> - RequireCompilationThread ctok - scope.IsRelativeNameResolvable(pos, plid, item)) - - member info.IsRelativeNameResolvableFromSymbol(pos: pos, plid: string list, symbol: FSharpSymbol, ?userOpName: string) = - let userOpName = defaultArg userOpName "Unknown" - reactorOp userOpName "IsRelativeNameResolvableFromSymbol" true (fun ctok scope -> - RequireCompilationThread ctok - scope.IsRelativeNameResolvableFromSymbol(pos, plid, symbol)) - - member info.GetDisplayEnvForPos(pos: pos) : Async = - let userOpName = "CodeLens" - reactorOp userOpName "GetDisplayContextAtPos" None (fun ctok scope -> - DoesNotRequireCompilerThreadTokenAndCouldPossiblyBeMadeConcurrent ctok - let (nenv, _), _ = scope.GetBestDisplayEnvForPos pos - Some nenv.DisplayEnv) - - member info.ImplementationFile = - if not keepAssemblyContents then invalidOp "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" - scopeOptX - |> Option.map (fun scope -> - let cenv = SymbolEnv(scope.TcGlobals, scope.ThisCcu, Some scope.CcuSigForFile, scope.TcImports) - scope.ImplementationFile |> Option.map (fun implFile -> FSharpImplementationFileContents(cenv, implFile))) - |> Option.defaultValue None - - member info.OpenDeclarations = - scopeOptX - |> Option.map (fun scope -> - let cenv = scope.SymbolEnv - scope.OpenDeclarations |> Array.map (fun x -> FSharpOpenDeclaration(x.LongId, x.Range, (x.Modules |> List.map (fun x -> FSharpEntity(cenv, x))), x.AppliedScope, x.IsOwnNamespace))) - |> Option.defaultValue [| |] - - override info.ToString() = "FSharpCheckFileResults(" + filename + ")" - #if !FABLE_COMPILER //---------------------------------------------------------------------------- // BackgroundCompiler // -[] -type FSharpCheckFileAnswer = - | Aborted - | Succeeded of FSharpCheckFileResults - - /// Callback that indicates whether a requested result has become obsolete. [] type IsResultObsolete = @@ -2232,9 +105,6 @@ type IsResultObsolete = [] module Helpers = - // Look for DLLs in the location of the service DLL first. - let defaultFSharpBinariesDir = FSharpEnvironment.BinFolderOfDefaultFSharpCompiler(Some(typeof.Assembly.Location)).Value - /// Determine whether two (fileName,options) keys are identical w.r.t. affect on checking let AreSameForChecking2((fileName1: string, options1: FSharpProjectOptions), (fileName2, options2)) = (fileName1 = fileName2) @@ -2246,17 +116,17 @@ module Helpers = && FSharpProjectOptions.UseSameProject(o1,o2) /// Determine whether two (fileName,sourceText,options) keys should be identical w.r.t. parsing - let AreSameForParsing((fileName1: string, source1: string, options1), (fileName2, source2, options2)) = - fileName1 = fileName2 && options1 = options2 && source1 = source2 + let AreSameForParsing((fileName1: string, source1Hash: int, 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, source1: string, options1: FSharpProjectOptions), (fileName2, source2, options2)) = + let AreSameForChecking3((fileName1: string, source1Hash: int, options1: FSharpProjectOptions), (fileName2, source2Hash, options2)) = (fileName1 = fileName2) && FSharpProjectOptions.AreSameForChecking(options1,options2) - && (source1 = source2) + && 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)) = @@ -2264,12 +134,12 @@ module Helpers = && FSharpProjectOptions.UseSameProject(o1,o2) module CompileHelpers = - let mkCompilationErorHandlers() = + let mkCompilationErrorHandlers() = let errors = ResizeArray<_>() let errorSink isError exn = let mainError, relatedErrors = SplitRelatedDiagnostics exn - let oneError e = errors.Add(FSharpErrorInfo.CreateFromException (e, isError, Range.range0)) + let oneError e = errors.Add(FSharpErrorInfo.CreateFromException (e, isError, Range.range0, true)) // Suggest names for errors oneError mainError List.iter oneError relatedErrors @@ -2297,7 +167,7 @@ module CompileHelpers = /// Compile using the given flags. Source files names are resolved via the FileSystem API. The output file must be given by a -o flag. let compileFromArgs (ctok, argv: string[], legacyReferenceResolver, tcImportsCapture, dynamicAssemblyCreator) = - let errors, errorLogger, loggerProvider = mkCompilationErorHandlers() + let errors, errorLogger, loggerProvider = mkCompilationErrorHandlers() let result = tryCompile errorLogger (fun exiter -> mainCompile (ctok, argv, legacyReferenceResolver, (*bannerAlreadyPrinted*)true, ReduceMemoryFlag.Yes, CopyFSharpCoreFlag.No, exiter, loggerProvider, tcImportsCapture, dynamicAssemblyCreator) ) @@ -2306,7 +176,7 @@ module CompileHelpers = let compileFromAsts (ctok, legacyReferenceResolver, asts, assemblyName, outFile, dependencies, noframework, pdbFile, executable, tcImportsCapture, dynamicAssemblyCreator) = - let errors, errorLogger, loggerProvider = mkCompilationErorHandlers() + let errors, errorLogger, loggerProvider = mkCompilationErrorHandlers() let executable = defaultArg executable true let target = if executable then CompilerTarget.ConsoleExe else CompilerTarget.Dll @@ -2338,7 +208,7 @@ module CompileHelpers = TypeDefs = ilxMainModule.TypeDefs.AsList |> List.filter (fun td -> not (isTypeNameForGlobalFunctions td.Name)) |> mkILTypeDefs Resources=mkILResources [] } - // The function used to resolve typees while emitting the code + // The function used to resolve types while emitting the code let assemblyResolver s = match tcImportsRef.Value.Value.TryFindExistingFullyQualifiedPathByExactAssemblyRef (ctok, s) with | Some res -> Some (Choice1Of2 res) @@ -2359,7 +229,7 @@ module CompileHelpers = // Register the reflected definitions for the dynamically generated assembly for resource in ilxMainModule.Resources.AsList do if IsReflectedDefinitionsResource resource then - Quotations.Expr.RegisterReflectedDefinitions(assemblyBuilder, moduleBuilder.Name, resource.GetBytes()) + Quotations.Expr.RegisterReflectedDefinitions (assemblyBuilder, moduleBuilder.Name, resource.GetBytes().ToArray()) // Save the result assemblyBuilderRef := Some assemblyBuilder @@ -2372,9 +242,8 @@ module CompileHelpers = System.Console.SetError error | None -> () - -type FileName = string -type Source = string +type SourceTextHash = int +type FileName = string type FilePath = string type ProjectPath = string type FileVersion = int @@ -2384,7 +253,7 @@ type ScriptClosureCacheToken() = interface LockToken // There is only one instance of this type, held in FSharpChecker -type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyContents, keepAllBackgroundResolutions, tryGetMetadataSnapshot) as self = +type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyContents, keepAllBackgroundResolutions, tryGetMetadataSnapshot, suggestNamesForErrors, keepAllBackgroundSymbolUses, enableBackgroundItemKeyStoreAndSemanticClassification) as self = // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.backgroundCompiler.reactor: The one and only Reactor let reactor = Reactor.Singleton let beforeFileChecked = Event() @@ -2438,22 +307,21 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC let loadClosure = scriptClosureCacheLock.AcquireLock (fun ltok -> scriptClosureCache.TryGet (ltok, options)) let! builderOpt, diagnostics = IncrementalBuilder.TryCreateBackgroundBuilderForProjectOptions - (ctok, legacyReferenceResolver, defaultFSharpBinariesDir, frameworkTcImportsCache, loadClosure, Array.toList options.SourceFiles, + (ctok, legacyReferenceResolver, FSharpCheckerResultsSettings.defaultFSharpBinariesDir, frameworkTcImportsCache, loadClosure, Array.toList options.SourceFiles, Array.toList options.OtherOptions, projectReferences, options.ProjectDirectory, - options.UseScriptResolutionRules, keepAssemblyContents, keepAllBackgroundResolutions, maxTimeShareMilliseconds, - tryGetMetadataSnapshot) - - // We're putting the builder in the cache, so increment its count. - let decrement = IncrementalBuilder.KeepBuilderAlive builderOpt + options.UseScriptResolutionRules, keepAssemblyContents, keepAllBackgroundResolutions, FSharpCheckerResultsSettings.maxTimeShareMilliseconds, + tryGetMetadataSnapshot, suggestNamesForErrors, keepAllBackgroundSymbolUses, enableBackgroundItemKeyStoreAndSemanticClassification) match builderOpt with | None -> () | Some builder -> +#if !NO_EXTENSIONTYPING // Register the behaviour that responds to CCUs being invalidated because of type // provider Invalidate events. This invalidates the configuration in the build. - builder.ImportedCcusInvalidated.Add (fun _ -> + builder.ImportsInvalidatedByTypeProvider.Add (fun _ -> self.InvalidateConfiguration(options, None, userOpName)) +#endif // Register the callback called just before a file is typechecked by the background builder (without recording // errors or intellisense information). @@ -2465,7 +333,7 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC builder.FileChecked.Add (fun file -> fileChecked.Trigger(file, options.ExtraProjectInfo)) builder.ProjectChecked.Add (fun () -> projectChecked.Trigger (options.ProjectFileName, options.ExtraProjectInfo)) - return (builderOpt, diagnostics, decrement) + return (builderOpt, diagnostics) } // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.backgroundCompiler.incrementalBuildersCache. This root typically holds more @@ -2474,27 +342,23 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC // /// Cache of builds keyed by options. let incrementalBuildersCache = - MruCache + MruCache (keepStrongly=projectCacheSize, keepMax=projectCacheSize, areSame = FSharpProjectOptions.AreSameForChecking, - areSimilar = FSharpProjectOptions.UseSameProject, - requiredToKeep=(fun (builderOpt,_,_) -> match builderOpt with None -> false | Some (b:IncrementalBuilder) -> b.IsBeingKeptAliveApartFromCacheEntry), - onDiscard = (fun (_, _, decrement:IDisposable) -> decrement.Dispose())) + areSimilar = FSharpProjectOptions.UseSameProject) - let getOrCreateBuilderAndKeepAlive (ctok, options, userOpName) = + let getOrCreateBuilder (ctok, options, userOpName) = cancellable { RequireCompilationThread ctok match incrementalBuildersCache.TryGet (ctok, options) with - | Some (builderOpt,creationErrors,_) -> - Logger.Log LogCompilerFunctionId.Service_IncrementalBuildersCache_BuildingNewCache - let decrement = IncrementalBuilder.KeepBuilderAlive builderOpt - return builderOpt,creationErrors, decrement - | None -> + | Some (builderOpt,creationErrors) -> Logger.Log LogCompilerFunctionId.Service_IncrementalBuildersCache_GettingCache - let! (builderOpt,creationErrors,_) as info = CreateOneIncrementalBuilder (ctok, options, userOpName) + return builderOpt,creationErrors + | None -> + Logger.Log LogCompilerFunctionId.Service_IncrementalBuildersCache_BuildingNewCache + let! (builderOpt,creationErrors) as info = CreateOneIncrementalBuilder (ctok, options, userOpName) incrementalBuildersCache.Set (ctok, options, info) - let decrement = IncrementalBuilder.KeepBuilderAlive builderOpt - return builderOpt, creationErrors, decrement + return builderOpt, creationErrors } let parseCacheLock = Lock() @@ -2519,12 +383,12 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC // Also keyed on source. This can only be out of date if the antecedent is out of date let checkFileInProjectCache = - MruCache + MruCache (keepStrongly=checkFileInProjectCacheSize, areSame=AreSameForChecking3, areSimilar=AreSubsumable3) - /// Holds keys for files being currently checked. It's used to prevent checking same file in parallel (interleaving chunck queued to Reactor). + /// Holds keys for files being currently checked. It's used to prevent checking same file in parallel (interleaving chunk queued to Reactor). let beingCheckedFileTable = ConcurrentDictionary (HashIdentity.FromFunctions @@ -2532,28 +396,10 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC (fun (f1, o1, v1) (f2, o2, v2) -> f1 = f2 && v1 = v2 && FSharpProjectOptions.AreSameForChecking(o1, o2))) static let mutable foregroundParseCount = 0 + static let mutable foregroundTypeCheckCount = 0 - let MakeCheckFileResultsEmpty(filename, creationErrors) = - FSharpCheckFileResults (filename, creationErrors, None, [| |], None, reactorOps, keepAssemblyContents) - - let MakeCheckFileResults(filename, options:FSharpProjectOptions, builder, scope, dependencyFiles, creationErrors, parseErrors, tcErrors) = - let errors = - [| yield! creationErrors - yield! parseErrors - if options.IsIncompleteTypeCheckEnvironment then - yield! Seq.truncate maxTypeCheckErrorsOutOfProjectContext tcErrors - else - yield! tcErrors |] - - FSharpCheckFileResults (filename, errors, Some scope, dependencyFiles, Some builder, reactorOps, keepAssemblyContents) - - let MakeCheckFileAnswer(filename, tcFileResult, options:FSharpProjectOptions, builder, dependencyFiles, creationErrors, parseErrors, tcErrors) = - match tcFileResult with - | Parser.TypeCheckAborted.Yes -> FSharpCheckFileAnswer.Aborted - | Parser.TypeCheckAborted.No scope -> FSharpCheckFileAnswer.Succeeded(MakeCheckFileResults(filename, options, builder, scope, dependencyFiles, creationErrors, parseErrors, tcErrors)) - - member bc.RecordTypeCheckFileInProjectResults(filename,options,parsingOptions,parseResults,fileVersion,priorTimeStamp,checkAnswer,source) = + member __.RecordTypeCheckFileInProjectResults(filename,options,parsingOptions,parseResults,fileVersion,priorTimeStamp,checkAnswer,sourceText) = match checkAnswer with | None | Some FSharpCheckFileAnswer.Aborted -> () @@ -2561,55 +407,61 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC foregroundTypeCheckCount <- foregroundTypeCheckCount + 1 parseCacheLock.AcquireLock (fun ltok -> checkFileInProjectCachePossiblyStale.Set(ltok, (filename,options),(parseResults,typedResults,fileVersion)) - checkFileInProjectCache.Set(ltok, (filename,source,options),(parseResults,typedResults,fileVersion,priorTimeStamp)) - parseFileCache.Set(ltok, (filename, source, parsingOptions), parseResults)) + checkFileInProjectCache.Set(ltok, (filename, sourceText, options),(parseResults,typedResults,fileVersion,priorTimeStamp)) + parseFileCache.Set(ltok, (filename, sourceText, parsingOptions), parseResults)) member bc.ImplicitlyStartCheckProjectInBackground(options, userOpName) = if implicitlyStartBackgroundWork then - bc.CheckProjectInBackground(options, userOpName + ".ImplicitlyStartCheckProjectInBackground") + bc.CheckProjectInBackground(options, userOpName + ".ImplicitlyStartCheckProjectInBackground") - member bc.ParseFile(filename: string, source: string, options: FSharpParsingOptions, userOpName: string) = + member __.ParseFile(filename: string, sourceText: ISourceText, options: FSharpParsingOptions, userOpName: string) = async { - match parseCacheLock.AcquireLock(fun ltok -> parseFileCache.TryGet(ltok, (filename, source, options))) with + let hash = sourceText.GetHashCode() + match parseCacheLock.AcquireLock(fun ltok -> parseFileCache.TryGet(ltok, (filename, hash, options))) with | Some res -> return res | None -> foregroundParseCount <- foregroundParseCount + 1 - let parseErrors, parseTreeOpt, anyErrors = Parser.parseFile(source, filename, options, userOpName) + let parseErrors, parseTreeOpt, anyErrors = ParseAndCheckFile.parseFile(sourceText, filename, options, userOpName, suggestNamesForErrors) let res = FSharpParseFileResults(parseErrors, parseTreeOpt, anyErrors, options.SourceFiles) - parseCacheLock.AcquireLock(fun ltok -> parseFileCache.Set(ltok, (filename, source, options), res)) + parseCacheLock.AcquireLock(fun ltok -> parseFileCache.Set(ltok, (filename, hash, options), res)) return res } + member bc.ParseFileNoCache(filename, sourceText, options, userOpName) = + async { + let parseErrors, parseTreeOpt, anyErrors = ParseAndCheckFile.parseFile(sourceText, filename, options, userOpName, false) + return FSharpParseFileResults(parseErrors, parseTreeOpt, anyErrors, options.SourceFiles) + } + /// Fetch the parse information from the background compiler (which checks w.r.t. the FileSystem API) - member bc.GetBackgroundParseResultsForFileInProject(filename, options, userOpName) = + member __.GetBackgroundParseResultsForFileInProject(filename, options, userOpName) = reactor.EnqueueAndAwaitOpAsync(userOpName, "GetBackgroundParseResultsForFileInProject ", filename, fun ctok -> - cancellable { - let! builderOpt, creationErrors, decrement = getOrCreateBuilderAndKeepAlive (ctok, options, userOpName) - use _unwind = decrement - match builderOpt with - | None -> return FSharpParseFileResults(creationErrors, None, true, [| |]) - | Some builder -> - let! parseTreeOpt,_,_,parseErrors = builder.GetParseResultsForFile (ctok, filename) - let errors = [| yield! creationErrors; yield! ErrorHelpers.CreateErrorInfos (builder.TcConfig.errorSeverityOptions, false, filename, parseErrors) |] - return FSharpParseFileResults(errors = errors, input = parseTreeOpt, parseHadErrors = false, dependencyFiles = builder.AllDependenciesDeprecated) - } + cancellable { + let! builderOpt, creationErrors = getOrCreateBuilder (ctok, options, userOpName) + match builderOpt with + | None -> return FSharpParseFileResults(creationErrors, None, true, [| |]) + | Some builder -> + let! parseTreeOpt,_,_,parseErrors = builder.GetParseResultsForFile (ctok, filename) + let errors = [| yield! creationErrors; yield! ErrorHelpers.CreateErrorInfos (builder.TcConfig.errorSeverityOptions, false, filename, parseErrors, suggestNamesForErrors) |] + return FSharpParseFileResults(errors = errors, input = parseTreeOpt, parseHadErrors = false, dependencyFiles = builder.AllDependenciesDeprecated) + } ) - member bc.GetCachedCheckFileResult(builder: IncrementalBuilder,filename,source,options) = - // 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 = parseCacheLock.AcquireLock (fun ltok -> checkFileInProjectCache.TryGet(ltok, (filename,source,options))) + member __.GetCachedCheckFileResult(builder: IncrementalBuilder, filename, sourceText: ISourceText, options) = + // 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 = parseCacheLock.AcquireLock (fun ltok -> checkFileInProjectCache.TryGet(ltok, (filename, sourceText.GetHashCode(), options))) - match cachedResults with + match cachedResults with // | Some (parseResults, checkResults, _, _) when builder.AreCheckResultsBeforeFileInProjectReady(filename) -> - | Some (parseResults, checkResults,_,priorTimeStamp) - when - (match builder.GetCheckResultsBeforeFileInProjectEvenIfStale filename with - | None -> false - | Some(tcPrior) -> - tcPrior.TimeStamp = priorTimeStamp && - builder.AreCheckResultsBeforeFileInProjectReady(filename)) -> - Some (parseResults,checkResults) - | _ -> None + | Some (parseResults, checkResults,_,priorTimeStamp) + when + (match builder.GetCheckResultsBeforeFileInProjectEvenIfStale filename with + | None -> false + | Some(tcPrior) -> + tcPrior.TimeStamp = priorTimeStamp && + builder.AreCheckResultsBeforeFileInProjectReady(filename)) -> + Some (parseResults,checkResults) + | _ -> None /// 1. Repeatedly try to get cached file check results or get file "lock". /// @@ -2626,7 +478,7 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC /// 7. Releases the file "lock". member private bc.CheckOneFileImpl (parseResults: FSharpParseFileResults, - source: string, + sourceText: ISourceText, fileName: string, options: FSharpProjectOptions, textSnapshotInfo: obj option, @@ -2642,7 +494,7 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC let rec loop() = async { // results may appear while we were waiting for the lock, let's recheck if it's the case - let cachedResults = bc.GetCachedCheckFileResult(builder, fileName, source, options) + let cachedResults = bc.GetCachedCheckFileResult(builder, fileName, sourceText, options) match cachedResults with | Some (_, checkResults) -> return FSharpCheckFileAnswer.Succeeded checkResults @@ -2652,12 +504,32 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC // Get additional script #load closure information if applicable. // For scripts, this will have been recorded by GetProjectOptionsFromScript. let loadClosure = scriptClosureCacheLock.AcquireLock (fun ltok -> scriptClosureCache.TryGet (ltok, options)) - let! tcErrors, tcFileResult = - Parser.CheckOneFile(parseResults, source, fileName, options.ProjectFileName, tcPrior.TcConfig, tcPrior.TcGlobals, tcPrior.TcImports, - tcPrior.TcState, tcPrior.ModuleNamesDict, loadClosure, tcPrior.TcErrors, reactorOps, (fun () -> builder.IsAlive), textSnapshotInfo, userOpName) + let! checkAnswer = + FSharpCheckFileResults.CheckOneFile + (parseResults, + sourceText, + fileName, + options.ProjectFileName, + tcPrior.TcConfig, + tcPrior.TcGlobals, + tcPrior.TcImports, + tcPrior.TcState, + tcPrior.ModuleNamesDict, + loadClosure, + tcPrior.TcErrors, + reactorOps, + textSnapshotInfo, + userOpName, + options.IsIncompleteTypeCheckEnvironment, + builder, + Array.ofList tcPrior.TcDependencyFiles, + creationErrors, + parseResults.Errors, + keepAssemblyContents, + suggestNamesForErrors) let parsingOptions = FSharpParsingOptions.FromTcConfig(tcPrior.TcConfig, Array.ofList builder.SourceFiles, options.UseScriptResolutionRules) - let checkAnswer = MakeCheckFileAnswer(fileName, tcFileResult, options, builder, Array.ofList tcPrior.TcDependencyFiles, creationErrors, parseResults.Errors, tcErrors) - bc.RecordTypeCheckFileInProjectResults(fileName, options, parsingOptions, parseResults, fileVersion, tcPrior.TimeStamp, Some checkAnswer, source) + reactor.SetPreferredUILang tcPrior.TcConfig.preferredUiLang + bc.RecordTypeCheckFileInProjectResults(fileName, options, parsingOptions, parseResults, fileVersion, tcPrior.TimeStamp, Some checkAnswer, sourceText.GetHashCode()) return checkAnswer finally let dummy = ref () @@ -2673,7 +545,7 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC } /// Type-check the result obtained by parsing, but only if the antecedent type checking context is available. - member bc.CheckFileInProjectAllowingStaleCachedResults(parseResults: FSharpParseFileResults, filename, fileVersion, source, options, textSnapshotInfo: obj option, userOpName) = + member bc.CheckFileInProjectAllowingStaleCachedResults(parseResults: FSharpParseFileResults, filename, fileVersion, sourceText: ISourceText, options, textSnapshotInfo: obj option, userOpName) = let execWithReactorAsync action = reactor.EnqueueAndAwaitOpAsync(userOpName, "CheckFileInProjectAllowingStaleCachedResults ", filename, action) async { try @@ -2683,12 +555,11 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC let! cachedResults = execWithReactorAsync <| fun ctok -> cancellable { - let! _builderOpt,_creationErrors,decrement = getOrCreateBuilderAndKeepAlive (ctok, options, userOpName) - use _unwind = decrement + let! _builderOpt,_creationErrors = getOrCreateBuilder (ctok, options, userOpName) match incrementalBuildersCache.TryGetAny (ctok, options) with - | Some (Some builder, creationErrors, _) -> - match bc.GetCachedCheckFileResult(builder, filename, source, options) with + | Some (Some builder, creationErrors) -> + match bc.GetCachedCheckFileResult(builder, filename, sourceText, options) with | Some (_, checkResults) -> return Some (builder, creationErrors, Some (FSharpCheckFileAnswer.Succeeded checkResults)) | _ -> return Some (builder, creationErrors, None) | _ -> return None // the builder wasn't ready @@ -2708,7 +579,7 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC match tcPrior with | Some tcPrior -> - let! checkResults = bc.CheckOneFileImpl(parseResults, source, filename, options, textSnapshotInfo, fileVersion, builder, tcPrior, creationErrors, userOpName) + let! checkResults = bc.CheckOneFileImpl(parseResults, sourceText, filename, options, textSnapshotInfo, fileVersion, builder, tcPrior, creationErrors, userOpName) return Some checkResults | None -> return None // the incremental builder was not up to date finally @@ -2716,33 +587,32 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC } /// 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, source, options, textSnapshotInfo, userOpName) = + member bc.CheckFileInProject(parseResults: FSharpParseFileResults, filename, fileVersion, sourceText: ISourceText, options, textSnapshotInfo, userOpName) = let execWithReactorAsync action = reactor.EnqueueAndAwaitOpAsync(userOpName, "CheckFileInProject", filename, action) async { try if implicitlyStartBackgroundWork then reactor.CancelBackgroundOp() // cancel the background work, since we will start new work after we're done - let! builderOpt,creationErrors, decrement = execWithReactorAsync (fun ctok -> getOrCreateBuilderAndKeepAlive (ctok, options, userOpName)) - use _unwind = decrement + let! builderOpt,creationErrors = execWithReactorAsync (fun ctok -> getOrCreateBuilder (ctok, options, userOpName)) match builderOpt with - | None -> return FSharpCheckFileAnswer.Succeeded (MakeCheckFileResultsEmpty(filename, creationErrors)) + | None -> return FSharpCheckFileAnswer.Succeeded (FSharpCheckFileResults.MakeEmpty(filename, creationErrors, reactorOps, 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, source, options) + let cachedResults = bc.GetCachedCheckFileResult(builder, filename, sourceText, options) match cachedResults with | Some (_, checkResults) -> return FSharpCheckFileAnswer.Succeeded checkResults | _ -> Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "CheckFileInProject.CacheMiss", filename) let! tcPrior = execWithReactorAsync <| fun ctok -> builder.GetCheckResultsBeforeFileInProject (ctok, filename) - let! checkAnswer = bc.CheckOneFileImpl(parseResults, source, filename, options, textSnapshotInfo, fileVersion, builder, tcPrior, creationErrors, userOpName) + let! checkAnswer = bc.CheckOneFileImpl(parseResults, sourceText, filename, options, textSnapshotInfo, fileVersion, builder, tcPrior, creationErrors, userOpName) return checkAnswer finally bc.ImplicitlyStartCheckProjectInBackground(options, userOpName) } /// Parses and checks the source file and returns untyped AST and check results. - member bc.ParseAndCheckFileInProject (filename:string, fileVersion, source, options:FSharpProjectOptions, textSnapshotInfo, userOpName) = + member bc.ParseAndCheckFileInProject (filename:string, fileVersion, sourceText: ISourceText, options:FSharpProjectOptions, textSnapshotInfo, userOpName) = let execWithReactorAsync action = reactor.EnqueueAndAwaitOpAsync(userOpName, "ParseAndCheckFileInProject", filename, action) async { try @@ -2753,8 +623,7 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC Logger.LogMessage (filename + strGuid + "-Cancelling background work") LogCompilerFunctionId.Service_ParseAndCheckFileInProject reactor.CancelBackgroundOp() // cancel the background work, since we will start new work after we're done - let! builderOpt,creationErrors,decrement = execWithReactorAsync (fun ctok -> getOrCreateBuilderAndKeepAlive (ctok, options, userOpName)) - use _unwind = decrement + let! builderOpt,creationErrors = execWithReactorAsync (fun ctok -> getOrCreateBuilder (ctok, options, userOpName)) match builderOpt with | None -> Logger.LogBlockMessageStop (filename + strGuid + "-Failed_Aborted") LogCompilerFunctionId.Service_ParseAndCheckFileInProject @@ -2763,7 +632,7 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC return (parseResults, FSharpCheckFileAnswer.Aborted) | Some builder -> - let cachedResults = bc.GetCachedCheckFileResult(builder, filename, source, options) + let cachedResults = bc.GetCachedCheckFileResult(builder, filename, sourceText, options) match cachedResults with | Some (parseResults, checkResults) -> @@ -2777,9 +646,10 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC // Do the parsing. let parsingOptions = FSharpParsingOptions.FromTcConfig(builder.TcConfig, Array.ofList (builder.SourceFiles), options.UseScriptResolutionRules) - let parseErrors, parseTreeOpt, anyErrors = Parser.parseFile (source, filename, parsingOptions, userOpName) + reactor.SetPreferredUILang tcPrior.TcConfig.preferredUiLang + let parseErrors, parseTreeOpt, anyErrors = ParseAndCheckFile.parseFile (sourceText, filename, parsingOptions, userOpName, suggestNamesForErrors) let parseResults = FSharpParseFileResults(parseErrors, parseTreeOpt, anyErrors, builder.AllDependenciesDeprecated) - let! checkResults = bc.CheckOneFileImpl(parseResults, source, filename, options, textSnapshotInfo, fileVersion, builder, tcPrior, creationErrors, userOpName) + let! checkResults = bc.CheckOneFileImpl(parseResults, sourceText, filename, options, textSnapshotInfo, fileVersion, builder, tcPrior, creationErrors, userOpName) Logger.LogBlockMessageStop (filename + strGuid + "-Successful") LogCompilerFunctionId.Service_ParseAndCheckFileInProject @@ -2789,55 +659,88 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC } /// Fetch the check information from the background compiler (which checks w.r.t. the FileSystem API) - member bc.GetBackgroundCheckResultsForFileInProject(filename, options, userOpName) = + member __.GetBackgroundCheckResultsForFileInProject(filename, options, userOpName) = reactor.EnqueueAndAwaitOpAsync(userOpName, "GetBackgroundCheckResultsForFileInProject", filename, fun ctok -> cancellable { - let! builderOpt, creationErrors, decrement = getOrCreateBuilderAndKeepAlive (ctok, options, userOpName) - use _unwind = decrement + let! builderOpt, creationErrors = getOrCreateBuilder (ctok, options, userOpName) match builderOpt with | None -> let parseResults = FSharpParseFileResults(creationErrors, None, true, [| |]) - let typedResults = MakeCheckFileResultsEmpty(filename, creationErrors) + let typedResults = FSharpCheckFileResults.MakeEmpty(filename, creationErrors, reactorOps, keepAssemblyContents) return (parseResults, typedResults) | Some builder -> let! (parseTreeOpt, _, _, untypedErrors) = builder.GetParseResultsForFile (ctok, filename) let! tcProj = builder.GetCheckResultsAfterFileInProject (ctok, filename) let errorOptions = builder.TcConfig.errorSeverityOptions - let untypedErrors = [| yield! creationErrors; yield! ErrorHelpers.CreateErrorInfos (errorOptions, false, filename, untypedErrors) |] - let tcErrors = [| yield! creationErrors; yield! ErrorHelpers.CreateErrorInfos (errorOptions, false, filename, tcProj.TcErrors) |] + let untypedErrors = [| yield! creationErrors; yield! ErrorHelpers.CreateErrorInfos (errorOptions, false, filename, untypedErrors, suggestNamesForErrors) |] + let tcErrors = [| yield! creationErrors; yield! ErrorHelpers.CreateErrorInfos (errorOptions, false, filename, tcProj.TcErrors, suggestNamesForErrors) |] let parseResults = FSharpParseFileResults(errors = untypedErrors, input = parseTreeOpt, parseHadErrors = false, dependencyFiles = builder.AllDependenciesDeprecated) let loadClosure = scriptClosureCacheLock.AcquireLock (fun ltok -> scriptClosureCache.TryGet (ltok, options) ) - let scope = - TypeCheckInfo(tcProj.TcConfig, tcProj.TcGlobals, - Option.get tcProj.LastestCcuSigForFile, - tcProj.TcState.Ccu, tcProj.TcImports, tcProj.TcEnvAtEnd.AccessRights, - options.ProjectFileName, filename, - List.head tcProj.TcResolutionsRev, - List.head tcProj.TcSymbolUsesRev, - tcProj.TcEnvAtEnd.NameEnv, - loadClosure, reactorOps, (fun () -> builder.IsAlive), None, - tcProj.LatestImplementationFile, - List.head tcProj.TcOpenDeclarationsRev) - let typedResults = MakeCheckFileResults(filename, options, builder, scope, Array.ofList tcProj.TcDependencyFiles, creationErrors, parseResults.Errors, tcErrors) + let typedResults = + FSharpCheckFileResults.Make + (filename, + options.ProjectFileName, + tcProj.TcConfig, + tcProj.TcGlobals, + options.IsIncompleteTypeCheckEnvironment, + builder, + Array.ofList tcProj.TcDependencyFiles, + creationErrors, + parseResults.Errors, + tcErrors, + reactorOps, + keepAssemblyContents, + Option.get tcProj.LatestCcuSigForFile, + tcProj.TcState.Ccu, + tcProj.TcImports, + tcProj.TcEnvAtEnd.AccessRights, + List.head tcProj.TcResolutionsRev, + List.head tcProj.TcSymbolUsesRev, + tcProj.TcEnvAtEnd.NameEnv, + loadClosure, + tcProj.LatestImplementationFile, + List.head tcProj.TcOpenDeclarationsRev) return (parseResults, typedResults) }) + member __.FindReferencesInFile(filename: string, options: FSharpProjectOptions, symbol: FSharpSymbol, userOpName: string) = + reactor.EnqueueAndAwaitOpAsync(userOpName, "FindReferencesInFile", filename, fun ctok -> + cancellable { + let! builderOpt, _ = getOrCreateBuilder (ctok, options, userOpName) + match builderOpt with + | None -> return Seq.empty + | Some builder -> + let! checkResults = builder.GetCheckResultsAfterFileInProject (ctok, filename) + return + match checkResults.ItemKeyStore with + | None -> Seq.empty + | Some reader -> reader.FindAll symbol.Item }) + + member __.GetSemanticClassificationForFile(filename: string, options: FSharpProjectOptions, userOpName: string) = + reactor.EnqueueAndAwaitOpAsync(userOpName, "GetSemanticClassificationForFile", filename, fun ctok -> + cancellable { + let! builderOpt, _ = getOrCreateBuilder (ctok, options, userOpName) + match builderOpt with + | None -> return [||] + | Some builder -> + let! checkResults = builder.GetCheckResultsAfterFileInProject (ctok, filename) + return checkResults.SemanticClassification }) + /// Try to get recent approximate type check results for a file. - member bc.TryGetRecentCheckResultsForFile(filename: string, options:FSharpProjectOptions, source, _userOpName: string) = - match source with + member __.TryGetRecentCheckResultsForFile(filename: string, options:FSharpProjectOptions, sourceText: ISourceText option, _userOpName: string) = + match sourceText with | Some sourceText -> parseCacheLock.AcquireLock (fun ltok -> - match checkFileInProjectCache.TryGet(ltok,(filename,sourceText,options)) with + match checkFileInProjectCache.TryGet(ltok,(filename,sourceText.GetHashCode(),options)) with | Some (a,b,c,_) -> Some (a,b,c) | None -> parseCacheLock.AcquireLock (fun ltok -> checkFileInProjectCachePossiblyStale.TryGet(ltok,(filename,options)))) | None -> parseCacheLock.AcquireLock (fun ltok -> checkFileInProjectCachePossiblyStale.TryGet(ltok,(filename,options))) /// Parse and typecheck the whole project (the implementation, called recursively as project graph is evaluated) - member private bc.ParseAndCheckProjectImpl(options, ctok, userOpName) : Cancellable = + member private __.ParseAndCheckProjectImpl(options, ctok, userOpName) : Cancellable = cancellable { - let! builderOpt,creationErrors,decrement = getOrCreateBuilderAndKeepAlive (ctok, options, userOpName) - use _unwind = decrement + let! builderOpt,creationErrors = getOrCreateBuilder (ctok, options, userOpName) match builderOpt with | None -> return FSharpCheckProjectResults (options.ProjectFileName, None, keepAssemblyContents, creationErrors, None) @@ -2845,7 +748,7 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC let! (tcProj, ilAssemRef, tcAssemblyDataOpt, tcAssemblyExprOpt) = builder.GetCheckResultsAndImplementationsForProject(ctok) let errorOptions = tcProj.TcConfig.errorSeverityOptions let fileName = TcGlobals.DummyFileNameForRangesWithoutASpecificLocation - let errors = [| yield! creationErrors; yield! ErrorHelpers.CreateErrorInfos (errorOptions, true, fileName, tcProj.TcErrors) |] + let errors = [| yield! creationErrors; yield! ErrorHelpers.CreateErrorInfos (errorOptions, true, fileName, tcProj.TcErrors, suggestNamesForErrors) |] return FSharpCheckProjectResults (options.ProjectFileName, Some tcProj.TcConfig, keepAssemblyContents, errors, Some(tcProj.TcGlobals, tcProj.TcImports, tcProj.TcState.Ccu, tcProj.TcState.CcuSig, tcProj.TcSymbolUses, tcProj.TopAttribs, tcAssemblyDataOpt, ilAssemRef, @@ -2853,41 +756,38 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC } /// Get the timestamp that would be on the output if fully built immediately - member private bc.TryGetLogicalTimeStampForProject(cache, ctok, options, userOpName: string) = + member private __.TryGetLogicalTimeStampForProject(cache, ctok, options, userOpName: string) = // NOTE: This creation of the background builder is currently run as uncancellable. Creating background builders is generally // cheap though the timestamp computations look suspicious for transitive project references. - let builderOpt,_creationErrors,decrement = getOrCreateBuilderAndKeepAlive (ctok, options, userOpName + ".TryGetLogicalTimeStampForProject") |> Cancellable.runWithoutCancellation - use _unwind = decrement + let builderOpt,_creationErrors = getOrCreateBuilder (ctok, options, userOpName + ".TryGetLogicalTimeStampForProject") |> Cancellable.runWithoutCancellation match builderOpt with | None -> None | Some builder -> Some (builder.GetLogicalTimeStampForProject(cache, ctok)) - /// Keep the projet builder alive over a scope - member bc.KeepProjectAlive(options, userOpName) = - reactor.EnqueueAndAwaitOpAsync(userOpName, "KeepProjectAlive", options.ProjectFileName, fun ctok -> - cancellable { - let! _builderOpt,_creationErrors,decrement = getOrCreateBuilderAndKeepAlive (ctok, options, userOpName) - return decrement - }) - /// Parse and typecheck the whole project. member bc.ParseAndCheckProject(options, userOpName) = reactor.EnqueueAndAwaitOpAsync(userOpName, "ParseAndCheckProject", options.ProjectFileName, fun ctok -> bc.ParseAndCheckProjectImpl(options, ctok, userOpName)) - member bc.GetProjectOptionsFromScript(filename, source, loadedTimeStamp, otherFlags, useFsiAuxLib: bool option, assumeDotNetFramework: bool option, extraProjectInfo: obj option, optionsStamp: int64 option, userOpName) = + member __.GetProjectOptionsFromScript(filename, sourceText, previewEnabled, loadedTimeStamp, otherFlags, useFsiAuxLib: bool option, useSdkRefs: bool option, assumeDotNetFramework: bool option, extraProjectInfo: obj option, optionsStamp: int64 option, userOpName) = reactor.EnqueueAndAwaitOpAsync (userOpName, "GetProjectOptionsFromScript", filename, fun ctok -> cancellable { use errors = new ErrorScope() // 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 otherFlags = defaultArg otherFlags [| |] + let extraFlags = + if previewEnabled then + [| "--langversion:preview" |] + else + [||] + let otherFlags = defaultArg otherFlags extraFlags let useSimpleResolution = #if ENABLE_MONO_SUPPORT runningOnMono || otherFlags |> Array.exists (fun x -> x = "--simpleresolution") @@ -2901,8 +801,8 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC let loadClosure = LoadClosure.ComputeClosureOfScriptText(ctok, legacyReferenceResolver, - defaultFSharpBinariesDir, filename, source, - CodeContext.Editing, useSimpleResolution, useFsiAuxLib, new Lexhelp.LexResourceManager(), + FSharpCheckerResultsSettings.defaultFSharpBinariesDir, filename, sourceText, + CodeContext.Editing, useSimpleResolution, useFsiAuxLib, useSdkRefs, new Lexhelp.LexResourceManager(), applyCompilerOptions, assumeDotNetFramework, tryGetMetadataSnapshot=tryGetMetadataSnapshot, reduceMemoryUsage=reduceMemoryUsage) @@ -2950,7 +850,7 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC if startBackgroundCompileIfAlreadySeen then bc.CheckProjectInBackground(options, userOpName + ".StartBackgroundCompile")) - member bc.NotifyProjectCleaned (options : FSharpProjectOptions, userOpName) = + member __.NotifyProjectCleaned (options : FSharpProjectOptions, userOpName) = reactor.EnqueueAndAwaitOpAsync(userOpName, "NotifyProjectCleaned", options.ProjectFileName, fun ctok -> cancellable { // If there was a similar entry (as there normally will have been) then re-establish an empty builder . This @@ -2963,13 +863,12 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC incrementalBuildersCache.Set(ctok, options, newBuilderInfo) }) - member bc.CheckProjectInBackground (options, userOpName) = + member __.CheckProjectInBackground (options, userOpName) = reactor.SetBackgroundOp (Some (userOpName, "CheckProjectInBackground", options.ProjectFileName, (fun ctok ct -> // The creation of the background builder can't currently be cancelled - match getOrCreateBuilderAndKeepAlive (ctok, options, userOpName) |> Cancellable.run ct with + match getOrCreateBuilder (ctok, options, userOpName) |> Cancellable.run ct with | ValueOrCancelled.Cancelled _ -> false - | ValueOrCancelled.Value (builderOpt,_,decrement) -> - use _unwind = decrement + | ValueOrCancelled.Value (builderOpt,_) -> match builderOpt with | None -> false | Some builder -> @@ -2978,25 +877,30 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC | ValueOrCancelled.Value v -> v | ValueOrCancelled.Cancelled _ -> false))) - member bc.StopBackgroundCompile () = + member __.StopBackgroundCompile () = reactor.SetBackgroundOp(None) - member bc.WaitForBackgroundCompile() = + member __.WaitForBackgroundCompile() = reactor.WaitForBackgroundOpCompletion() - member bc.CompleteAllQueuedOps() = + member __.CompleteAllQueuedOps() = reactor.CompleteAllQueuedOps() - member bc.Reactor = reactor - member bc.ReactorOps = reactorOps - member bc.BeforeBackgroundFileCheck = beforeFileChecked.Publish - member bc.FileParsed = fileParsed.Publish - member bc.FileChecked = fileChecked.Publish - member bc.ProjectChecked = projectChecked.Publish + member __.Reactor = reactor + + member __.ReactorOps = reactorOps + + member __.BeforeBackgroundFileCheck = beforeFileChecked.Publish - member bc.CurrentQueueLength = reactor.CurrentQueueLength + member __.FileParsed = fileParsed.Publish - member bc.ClearCachesAsync (userOpName) = + member __.FileChecked = fileChecked.Publish + + member __.ProjectChecked = projectChecked.Publish + + member __.CurrentQueueLength = reactor.CurrentQueueLength + + member __.ClearCachesAsync (userOpName) = reactor.EnqueueAndAwaitOpAsync (userOpName, "ClearCachesAsync", "", fun ctok -> parseCacheLock.AcquireLock (fun ltok -> checkFileInProjectCachePossiblyStale.Clear ltok @@ -3007,7 +911,7 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC scriptClosureCacheLock.AcquireLock (fun ltok -> scriptClosureCache.Clear ltok) cancellable.Return ()) - member bc.DownsizeCaches(userOpName) = + member __.DownsizeCaches(userOpName) = reactor.EnqueueAndAwaitOpAsync (userOpName, "DownsizeCaches", "", fun ctok -> parseCacheLock.AcquireLock (fun ltok -> checkFileInProjectCachePossiblyStale.Resize(ltok, keepStrongly=1) @@ -3019,25 +923,29 @@ type BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyC cancellable.Return ()) member __.FrameworkImportsCache = frameworkTcImportsCache + member __.ImplicitlyStartBackgroundWork with get() = implicitlyStartBackgroundWork and set v = implicitlyStartBackgroundWork <- v + static member GlobalForegroundParseCountStatistic = foregroundParseCount - static member GlobalForegroundTypeCheckCountStatistic = foregroundTypeCheckCount + static member GlobalForegroundTypeCheckCountStatistic = foregroundTypeCheckCount -//---------------------------------------------------------------------------- -// FSharpChecker -// -[] -[] -// There is typically only one instance of this type in a Visual Studio process. -type FSharpChecker(legacyReferenceResolver, projectCacheSize, keepAssemblyContents, keepAllBackgroundResolutions, tryGetMetadataSnapshot) = +[] +// There is typically only one instance of this type in an IDE process. +type FSharpChecker(legacyReferenceResolver, + projectCacheSize, + keepAssemblyContents, + keepAllBackgroundResolutions, + tryGetMetadataSnapshot, + suggestNamesForErrors, + keepAllBackgroundSymbolUses, + enableBackgroundItemKeyStoreAndSemanticClassification) = - let backgroundCompiler = BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyContents, keepAllBackgroundResolutions, tryGetMetadataSnapshot) + let backgroundCompiler = BackgroundCompiler(legacyReferenceResolver, projectCacheSize, keepAssemblyContents, keepAllBackgroundResolutions, tryGetMetadataSnapshot, suggestNamesForErrors, keepAllBackgroundSymbolUses, enableBackgroundItemKeyStoreAndSemanticClassification) static let globalInstance = lazy FSharpChecker.Create() - - + // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.braceMatchCache. Most recently used cache for brace matching. Accessed on the // background UI thread, not on the compiler thread. // @@ -3045,78 +953,88 @@ type FSharpChecker(legacyReferenceResolver, projectCacheSize, keepAssemblyConten let braceMatchCache = MruCache(braceMatchCacheSize, areSimilar = AreSimilarForParsing, areSame = AreSameForParsing) let mutable maxMemoryReached = false + let mutable maxMB = maxMBDefault + let maxMemEvent = new Event() /// Instantiate an interactive checker. - static member Create(?projectCacheSize, ?keepAssemblyContents, ?keepAllBackgroundResolutions, ?legacyReferenceResolver, ?tryGetMetadataSnapshot) = + static member Create(?projectCacheSize, ?keepAssemblyContents, ?keepAllBackgroundResolutions, ?legacyReferenceResolver, ?tryGetMetadataSnapshot, ?suggestNamesForErrors, ?keepAllBackgroundSymbolUses, ?enableBackgroundItemKeyStoreAndSemanticClassification) = let legacyReferenceResolver = - match legacyReferenceResolver with - | None -> SimulatedMSBuildReferenceResolver.GetBestAvailableResolver() + match legacyReferenceResolver with | Some rr -> rr + | None -> SimulatedMSBuildReferenceResolver.getResolver() let keepAssemblyContents = defaultArg keepAssemblyContents false let keepAllBackgroundResolutions = defaultArg keepAllBackgroundResolutions true let projectCacheSizeReal = defaultArg projectCacheSize projectCacheSizeDefault let tryGetMetadataSnapshot = defaultArg tryGetMetadataSnapshot (fun _ -> None) - new FSharpChecker(legacyReferenceResolver, projectCacheSizeReal,keepAssemblyContents, keepAllBackgroundResolutions, tryGetMetadataSnapshot) + let suggestNamesForErrors = defaultArg suggestNamesForErrors false + let keepAllBackgroundSymbolUses = defaultArg keepAllBackgroundSymbolUses true + let enableBackgroundItemKeyStoreAndSemanticClassification = defaultArg enableBackgroundItemKeyStoreAndSemanticClassification false + new FSharpChecker(legacyReferenceResolver, projectCacheSizeReal,keepAssemblyContents, keepAllBackgroundResolutions, tryGetMetadataSnapshot, suggestNamesForErrors, keepAllBackgroundSymbolUses, enableBackgroundItemKeyStoreAndSemanticClassification) - member ic.ReferenceResolver = legacyReferenceResolver + member __.ReferenceResolver = legacyReferenceResolver - member ic.MatchBraces(filename, source, options: FSharpParsingOptions, ?userOpName: string) = + member __.MatchBraces(filename, sourceText: ISourceText, options: FSharpParsingOptions, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" + let hash = sourceText.GetHashCode() async { - match braceMatchCache.TryGet(AssumeAnyCallerThreadWithoutEvidence(), (filename, source, options)) with + match braceMatchCache.TryGet(AssumeAnyCallerThreadWithoutEvidence(), (filename, hash, options)) with | Some res -> return res | None -> - let res = Parser.matchBraces(source, filename, options, userOpName) - braceMatchCache.Set(AssumeAnyCallerThreadWithoutEvidence(), (filename, source, options), res) + let res = ParseAndCheckFile.matchBraces(sourceText, filename, options, userOpName, suggestNamesForErrors) + braceMatchCache.Set(AssumeAnyCallerThreadWithoutEvidence(), (filename, hash, options), res) return res } + member ic.MatchBraces(filename, source: string, options: FSharpProjectOptions, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + let parsingOptions, _ = ic.GetParsingOptionsFromProjectOptions(options) + ic.MatchBraces(filename, SourceText.ofString source, parsingOptions, userOpName) + member ic.GetParsingOptionsFromProjectOptions(options): FSharpParsingOptions * _ = let sourceFiles = List.ofArray options.SourceFiles let argv = List.ofArray options.OtherOptions ic.GetParsingOptionsFromCommandLineArgs(sourceFiles, argv, options.UseScriptResolutionRules) - member ic.MatchBraces(filename, source, options: FSharpProjectOptions, ?userOpName: string) = + member ic.ParseFile(filename, sourceText, options, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" - let parsingOptions, _ = ic.GetParsingOptionsFromProjectOptions(options) - ic.MatchBraces(filename, source, parsingOptions, userOpName) + ic.CheckMaxMemoryReached() + backgroundCompiler.ParseFile(filename, sourceText, options, userOpName) - member ic.ParseFile(filename, source, options, ?userOpName: string) = + member ic.ParseFileNoCache(filename, sourceText, options, ?userOpName) = let userOpName = defaultArg userOpName "Unknown" ic.CheckMaxMemoryReached() - backgroundCompiler.ParseFile(filename, source, options, userOpName) - + backgroundCompiler.ParseFileNoCache(filename, sourceText, options, userOpName) - member ic.ParseFileInProject(filename, source, options, ?userOpName: string) = + member ic.ParseFileInProject(filename, source: string, options, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" let parsingOptions, _ = ic.GetParsingOptionsFromProjectOptions(options) - ic.ParseFile(filename, source, parsingOptions, userOpName) + ic.ParseFile(filename, SourceText.ofString source, parsingOptions, userOpName) - member ic.GetBackgroundParseResultsForFileInProject (filename,options, ?userOpName: string) = + member __.GetBackgroundParseResultsForFileInProject (filename,options, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" backgroundCompiler.GetBackgroundParseResultsForFileInProject(filename, options, userOpName) - member ic.GetBackgroundCheckResultsForFileInProject (filename,options, ?userOpName: string) = + member __.GetBackgroundCheckResultsForFileInProject (filename,options, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" backgroundCompiler.GetBackgroundCheckResultsForFileInProject(filename,options, userOpName) /// Try to get recent approximate type check results for a file. - member ic.TryGetRecentCheckResultsForFile(filename: string, options:FSharpProjectOptions, ?source, ?userOpName: string) = + member __.TryGetRecentCheckResultsForFile(filename: string, options:FSharpProjectOptions, ?sourceText, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" - backgroundCompiler.TryGetRecentCheckResultsForFile(filename,options,source, userOpName) + backgroundCompiler.TryGetRecentCheckResultsForFile(filename,options,sourceText, userOpName) - member ic.Compile(argv: string[], ?userOpName: string) = + member __.Compile(argv: string[], ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" backgroundCompiler.Reactor.EnqueueAndAwaitOpAsync (userOpName, "Compile", "", fun ctok -> cancellable { return CompileHelpers.compileFromArgs (ctok, argv, legacyReferenceResolver, None, None) }) - member ic.Compile (ast:ParsedInput list, assemblyName:string, outFile:string, dependencies:string list, ?pdbFile:string, ?executable:bool, ?noframework:bool, ?userOpName: string) = + member __.Compile (ast:ParsedInput list, assemblyName:string, outFile:string, dependencies:string list, ?pdbFile:string, ?executable:bool, ?noframework:bool, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" backgroundCompiler.Reactor.EnqueueAndAwaitOpAsync (userOpName, "Compile", assemblyName, fun ctok -> cancellable { @@ -3125,14 +1043,14 @@ type FSharpChecker(legacyReferenceResolver, projectCacheSize, keepAssemblyConten } ) - member ic.CompileToDynamicAssembly (otherFlags: string[], execute: (TextWriter * TextWriter) option, ?userOpName: string) = + member __.CompileToDynamicAssembly (otherFlags: string[], execute: (TextWriter * TextWriter) option, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" backgroundCompiler.Reactor.EnqueueAndAwaitOpAsync (userOpName, "CompileToDynamicAssembly", "", fun ctok -> cancellable { CompileHelpers.setOutputStreams execute // References used to capture the results of compilation - let tcImportsRef = ref (None: TcImports option) + let tcImportsRef = ref None let assemblyBuilderRef = ref None let tcImportsCapture = Some (fun tcImports -> tcImportsRef := Some tcImports) @@ -3153,7 +1071,7 @@ type FSharpChecker(legacyReferenceResolver, projectCacheSize, keepAssemblyConten } ) - member ic.CompileToDynamicAssembly (asts:ParsedInput list, assemblyName:string, dependencies:string list, execute: (TextWriter * TextWriter) option, ?debug:bool, ?noframework:bool, ?userOpName: string) = + member __.CompileToDynamicAssembly (asts:ParsedInput list, assemblyName:string, dependencies:string list, execute: (TextWriter * TextWriter) option, ?debug:bool, ?noframework:bool, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" backgroundCompiler.Reactor.EnqueueAndAwaitOpAsync (userOpName, "CompileToDynamicAssembly", assemblyName, fun ctok -> cancellable { @@ -3193,7 +1111,7 @@ type FSharpChecker(legacyReferenceResolver, projectCacheSize, keepAssemblyConten member ic.InvalidateAll() = ic.ClearCaches() - member ic.ClearCachesAsync(?userOpName: string) = + member __.ClearCachesAsync(?userOpName: string) = let utok = AssumeAnyCallerThreadWithoutEvidence() let userOpName = defaultArg userOpName "Unknown" braceMatchCache.Clear(utok) @@ -3202,7 +1120,7 @@ type FSharpChecker(legacyReferenceResolver, projectCacheSize, keepAssemblyConten member ic.ClearCaches(?userOpName) = ic.ClearCachesAsync(?userOpName=userOpName) |> Async.Start // this cache clearance is not synchronous, it will happen when the background op gets run - member ic.CheckMaxMemoryReached() = + member __.CheckMaxMemoryReached() = if not maxMemoryReached && System.GC.GetTotalMemory(false) > int64 maxMB * 1024L * 1024L then Trace.TraceWarning("!!!!!!!! MAX MEMORY REACHED, DOWNSIZING F# COMPILER CACHES !!!!!!!!!!!!!!!") // If the maxMB limit is reached, drastic action is taken @@ -3224,50 +1142,56 @@ type FSharpChecker(legacyReferenceResolver, projectCacheSize, keepAssemblyConten /// This function is called when the configuration is known to have changed for reasons not encoded in the ProjectOptions. /// For example, dependent references may have been deleted or created. - member ic.InvalidateConfiguration(options: FSharpProjectOptions, ?startBackgroundCompile, ?userOpName: string) = + member __.InvalidateConfiguration(options: FSharpProjectOptions, ?startBackgroundCompile, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" backgroundCompiler.InvalidateConfiguration(options, startBackgroundCompile, userOpName) /// This function is called when a project has been cleaned, and thus type providers should be refreshed. - member ic.NotifyProjectCleaned(options: FSharpProjectOptions, ?userOpName: string) = + member __.NotifyProjectCleaned(options: FSharpProjectOptions, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" backgroundCompiler.NotifyProjectCleaned (options, userOpName) /// Typecheck a source code file, returning a handle to the results of the /// parse including the reconstructed types in the file. - member ic.CheckFileInProjectAllowingStaleCachedResults(parseResults:FSharpParseFileResults, filename:string, fileVersion:int, source:string, options:FSharpProjectOptions, ?textSnapshotInfo:obj, ?userOpName: string) = + member __.CheckFileInProjectAllowingStaleCachedResults(parseResults:FSharpParseFileResults, filename:string, fileVersion:int, source:string, options:FSharpProjectOptions, ?textSnapshotInfo:obj, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" - backgroundCompiler.CheckFileInProjectAllowingStaleCachedResults(parseResults,filename,fileVersion,source,options,textSnapshotInfo, userOpName) - + backgroundCompiler.CheckFileInProjectAllowingStaleCachedResults(parseResults,filename,fileVersion,SourceText.ofString source,options,textSnapshotInfo, userOpName) + /// Typecheck a source code file, returning a handle to the results of the /// parse including the reconstructed types in the file. - member ic.CheckFileInProject(parseResults:FSharpParseFileResults, filename:string, fileVersion:int, source:string, options:FSharpProjectOptions, ?textSnapshotInfo:obj, ?userOpName: string) = + member ic.CheckFileInProject(parseResults:FSharpParseFileResults, filename:string, fileVersion:int, sourceText:ISourceText, options:FSharpProjectOptions, ?textSnapshotInfo:obj, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" ic.CheckMaxMemoryReached() - backgroundCompiler.CheckFileInProject(parseResults,filename,fileVersion,source,options,textSnapshotInfo, userOpName) - + backgroundCompiler.CheckFileInProject(parseResults,filename,fileVersion,sourceText,options,textSnapshotInfo, userOpName) + /// Typecheck a source code file, returning a handle to the results of the /// parse including the reconstructed types in the file. - member ic.ParseAndCheckFileInProject(filename:string, fileVersion:int, source:string, options:FSharpProjectOptions, ?textSnapshotInfo:obj, ?userOpName: string) = + member ic.ParseAndCheckFileInProject(filename:string, fileVersion:int, sourceText:ISourceText, options:FSharpProjectOptions, ?textSnapshotInfo:obj, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" ic.CheckMaxMemoryReached() - backgroundCompiler.ParseAndCheckFileInProject(filename, fileVersion, source, options, textSnapshotInfo, userOpName) + backgroundCompiler.ParseAndCheckFileInProject(filename, fileVersion, sourceText, options, textSnapshotInfo, userOpName) member ic.ParseAndCheckProject(options, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" ic.CheckMaxMemoryReached() backgroundCompiler.ParseAndCheckProject(options, userOpName) - member ic.KeepProjectAlive(options, ?userOpName: string) = + member ic.FindBackgroundReferencesInFile(filename:string, options: FSharpProjectOptions, symbol: FSharpSymbol, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + ic.CheckMaxMemoryReached() + backgroundCompiler.FindReferencesInFile(filename, options, symbol, userOpName) + + member ic.GetBackgroundSemanticClassificationForFile(filename:string, options: FSharpProjectOptions, ?userOpName) = let userOpName = defaultArg userOpName "Unknown" - backgroundCompiler.KeepProjectAlive(options, userOpName) + ic.CheckMaxMemoryReached() + backgroundCompiler.GetSemanticClassificationForFile(filename, options, userOpName) /// For a given script file, get the ProjectOptions implied by the #load closure - member ic.GetProjectOptionsFromScript(filename, source, ?loadedTimeStamp, ?otherFlags, ?useFsiAuxLib, ?assumeDotNetFramework, ?extraProjectInfo: obj, ?optionsStamp: int64, ?userOpName: string) = + member __.GetProjectOptionsFromScript(filename, source, ?previewEnabled, ?loadedTimeStamp, ?otherFlags, ?useFsiAuxLib, ?useSdkRefs, ?assumeDotNetFramework, ?extraProjectInfo: obj, ?optionsStamp: int64, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" - backgroundCompiler.GetProjectOptionsFromScript(filename, source, loadedTimeStamp, otherFlags, useFsiAuxLib, assumeDotNetFramework, extraProjectInfo, optionsStamp, userOpName) - - member ic.GetProjectOptionsFromCommandLineArgs(projectFileName, argv, ?loadedTimeStamp, ?extraProjectInfo: obj) = + backgroundCompiler.GetProjectOptionsFromScript(filename, source, previewEnabled, loadedTimeStamp, otherFlags, useFsiAuxLib, useSdkRefs, assumeDotNetFramework, extraProjectInfo, optionsStamp, userOpName) + + member __.GetProjectOptionsFromCommandLineArgs(projectFileName, argv, ?loadedTimeStamp, ?extraProjectInfo: obj) = let loadedTimeStamp = defaultArg loadedTimeStamp DateTime.MaxValue // Not 'now', we don't want to force reloading { ProjectFileName = projectFileName ProjectId = None @@ -3282,20 +1206,20 @@ type FSharpChecker(legacyReferenceResolver, projectCacheSize, keepAssemblyConten ExtraProjectInfo=extraProjectInfo Stamp = None } - member ic.GetParsingOptionsFromCommandLineArgs(initialSourceFiles, argv, ?isInteractive) = + member __.GetParsingOptionsFromCommandLineArgs(initialSourceFiles, argv, ?isInteractive) = let isInteractive = defaultArg isInteractive false use errorScope = new ErrorScope() let tcConfigBuilder = TcConfigBuilder.Initial // Apply command-line arguments and collect more source files if they are in the arguments let sourceFilesNew = ApplyCommandLineArgs(tcConfigBuilder, initialSourceFiles, argv) - FSharpParsingOptions.FromTcConfigBuidler(tcConfigBuilder, Array.ofList sourceFilesNew, isInteractive), errorScope.Diagnostics + FSharpParsingOptions.FromTcConfigBuilder(tcConfigBuilder, Array.ofList sourceFilesNew, isInteractive), errorScope.Diagnostics member ic.GetParsingOptionsFromCommandLineArgs(argv, ?isInteractive: bool) = ic.GetParsingOptionsFromCommandLineArgs([], argv, ?isInteractive=isInteractive) /// Begin background parsing the given project. - member ic.StartBackgroundCompile(options, ?userOpName) = + member __.StartBackgroundCompile(options, ?userOpName) = let userOpName = defaultArg userOpName "Unknown" backgroundCompiler.CheckProjectInBackground(options, userOpName) @@ -3304,37 +1228,45 @@ type FSharpChecker(legacyReferenceResolver, projectCacheSize, keepAssemblyConten ic.StartBackgroundCompile(options, ?userOpName=userOpName) /// Stop the background compile. - member ic.StopBackgroundCompile() = + member __.StopBackgroundCompile() = backgroundCompiler.StopBackgroundCompile() /// Block until the background compile finishes. // // This is for unit testing only - member ic.WaitForBackgroundCompile() = backgroundCompiler.WaitForBackgroundCompile() + member __.WaitForBackgroundCompile() = backgroundCompiler.WaitForBackgroundCompile() // Publish the ReactorOps from the background compiler for internal use member ic.ReactorOps = backgroundCompiler.ReactorOps - member ic.CurrentQueueLength = backgroundCompiler.CurrentQueueLength + member __.CurrentQueueLength = backgroundCompiler.CurrentQueueLength + + member __.BeforeBackgroundFileCheck = backgroundCompiler.BeforeBackgroundFileCheck + + member __.FileParsed = backgroundCompiler.FileParsed + + member __.FileChecked = backgroundCompiler.FileChecked + + member __.ProjectChecked = backgroundCompiler.ProjectChecked + + member __.ImplicitlyStartBackgroundWork with get() = backgroundCompiler.ImplicitlyStartBackgroundWork and set v = backgroundCompiler.ImplicitlyStartBackgroundWork <- v - member ic.BeforeBackgroundFileCheck = backgroundCompiler.BeforeBackgroundFileCheck - member ic.FileParsed = backgroundCompiler.FileParsed - member ic.FileChecked = backgroundCompiler.FileChecked - member ic.ProjectChecked = backgroundCompiler.ProjectChecked - member ic.ImplicitlyStartBackgroundWork with get() = backgroundCompiler.ImplicitlyStartBackgroundWork and set v = backgroundCompiler.ImplicitlyStartBackgroundWork <- v - member ic.PauseBeforeBackgroundWork with get() = Reactor.Singleton.PauseBeforeBackgroundWork and set v = Reactor.Singleton.PauseBeforeBackgroundWork <- v + member __.PauseBeforeBackgroundWork with get() = Reactor.Singleton.PauseBeforeBackgroundWork and set v = Reactor.Singleton.PauseBeforeBackgroundWork <- v static member GlobalForegroundParseCountStatistic = BackgroundCompiler.GlobalForegroundParseCountStatistic + static member GlobalForegroundTypeCheckCountStatistic = BackgroundCompiler.GlobalForegroundTypeCheckCountStatistic - member ic.MaxMemoryReached = maxMemEvent.Publish - member ic.MaxMemory with get() = maxMB and set v = maxMB <- v + member __.MaxMemoryReached = maxMemEvent.Publish + + member __.MaxMemory with get() = maxMB and set v = maxMB <- v static member Instance with get() = globalInstance.Force() + member internal __.FrameworkImportsCache = backgroundCompiler.FrameworkImportsCache /// Tokenize a single line, returning token information and a tokenization state represented by an integer - member x.TokenizeLine (line: string, state: FSharpTokenizerLexState) = + member __.TokenizeLine (line: string, state: FSharpTokenizerLexState) = let tokenizer = FSharpSourceTokenizer([], None) let lineTokenizer = tokenizer.CreateLineTokenizer line let mutable state = (None, state) @@ -3354,50 +1286,6 @@ type FSharpChecker(legacyReferenceResolver, projectCacheSize, keepAssemblyConten yield tokens |] tokens - -type FsiInteractiveChecker(legacyReferenceResolver, reactorOps: IReactorOperations, tcConfig: TcConfig, tcGlobals, tcImports, tcState) = - let keepAssemblyContents = false - - member __.ParseAndCheckInteraction (ctok, source, ?userOpName: string) = - async { - let userOpName = defaultArg userOpName "Unknown" - let filename = Path.Combine(tcConfig.implicitIncludeDir, "stdin.fsx") - // Note: projectSourceFiles is only used to compute isLastCompiland, and is ignored if Build.IsScript(mainInputFileName) is true (which it is in this case). - let parsingOptions = FSharpParsingOptions.FromTcConfig(tcConfig, [| filename |], true) - let parseErrors, parseTreeOpt, anyErrors = Parser.parseFile (source, filename, parsingOptions, userOpName) - let dependencyFiles = [| |] // interactions have no dependencies - let parseResults = FSharpParseFileResults(parseErrors, parseTreeOpt, parseHadErrors = anyErrors, dependencyFiles = dependencyFiles) - - let backgroundDiagnostics = [| |] - let reduceMemoryUsage = ReduceMemoryFlag.Yes - let assumeDotNetFramework = true - - let applyCompilerOptions tcConfigB = - let fsiCompilerOptions = CompileOptions.GetCoreFsiCompilerOptions tcConfigB - CompileOptions.ParseCompilerOptions (ignore, fsiCompilerOptions, [ ]) - - let loadClosure = LoadClosure.ComputeClosureOfScriptText(ctok, legacyReferenceResolver, defaultFSharpBinariesDir, filename, source, CodeContext.Editing, tcConfig.useSimpleResolution, tcConfig.useFsiAuxLib, new Lexhelp.LexResourceManager(), applyCompilerOptions, assumeDotNetFramework, tryGetMetadataSnapshot=(fun _ -> None), reduceMemoryUsage=reduceMemoryUsage) - let! tcErrors, tcFileResult = Parser.CheckOneFile(parseResults, source, filename, "project", tcConfig, tcGlobals, tcImports, tcState, Map.empty, Some loadClosure, backgroundDiagnostics, reactorOps, (fun () -> true), None, userOpName) - - return - match tcFileResult with - | Parser.TypeCheckAborted.No tcFileInfo -> - let errors = [| yield! parseErrors; yield! tcErrors |] - let typeCheckResults = FSharpCheckFileResults (filename, errors, Some tcFileInfo, dependencyFiles, None, reactorOps, false) - let projectResults = - FSharpCheckProjectResults (filename, Some tcConfig, keepAssemblyContents, errors, - Some(tcGlobals, tcImports, tcFileInfo.ThisCcu, tcFileInfo.CcuSigForFile, - [tcFileInfo.ScopeSymbolUses], None, None, mkSimpleAssemblyRef "stdin", - tcState.TcEnvFromImpls.AccessRights, None, dependencyFiles)) - parseResults, typeCheckResults, projectResults - | _ -> - failwith "unexpected aborted" - } - -//---------------------------------------------------------------------------- -// CompilerEnvironment, DebuggerEnvironment -// - type CompilerEnvironment = static member BinFolderOfDefaultFSharpCompiler(?probePoint) = FSharpEnvironment.BinFolderOfDefaultFSharpCompiler(probePoint) @@ -3407,7 +1295,7 @@ type CompilerEnvironment = module CompilerEnvironment = /// These are the names of assemblies that should be referenced for .fs, .ml, .fsi, .mli files that /// are not associated with a project - let DefaultReferencesForOrphanSources(assumeDotNetFramework) = DefaultReferencesForScriptsAndOutOfProjectSources(assumeDotNetFramework) + let DefaultReferencesForOrphanSources assumeDotNetFramework = DefaultReferencesForScriptsAndOutOfProjectSources assumeDotNetFramework /// Publish compiler-flags parsing logic. Must be fast because its used by the colorizer. let GetCompilationDefinesForEditing (parsingOptions: FSharpParsingOptions) = @@ -3435,60 +1323,7 @@ module PrettyNaming = let QuoteIdentifierIfNeeded id = Lexhelp.Keywords.QuoteIdentifierIfNeeded id let KeywordNames = Lexhelp.Keywords.keywordNames -namespace Microsoft.FSharp.Compiler.SourceCodeServices - - open System - - [] - type FSharpFindDeclFailureReason = A | B - [] - type FSharpFindDeclResult = A | B - [] - type FSharpProjectContext = A | B - [] - type SemanticClassificationType = A | B - [] - type FSharpCheckFileResults = A | B - [] - type FSharpCheckProjectResults = A | B - [] - type UnresolvedReferencesSet = A | B - [] - type FSharpParsingOptions = A | B - [] - type FSharpProjectOptions = A | B - [] - type FSharpCheckFileAnswer = A | B - [] - type FSharpChecker = A | B - [] - type CompilerEnvironment = A | B - [] - module CompilerEnvironment = begin end - [] - module DebuggerEnvironment = begin end - [] - module PrettyNaming = begin end - -namespace Microsoft.FSharp.Compiler.Interactive.Shell - - open System - - [] - type FsiValue = A | B - [] - type EvaluationEventArgs = A | B - [] - type public FsiEvaluationSessionHostConfig = A | B - [] - type FsiEvaluationSession = A | B - [] - module Settings = begin end - - /// Defines a read-only input stream used to feed content to the hosted F# Interactive dynamic compiler. - [] - type CompilerInputStream = A | B - [] - type CompilerOutputStream = A | B +module FSharpFileUtilities = + let isScriptFile (fileName: string) = CompileOps.IsScript fileName #endif //!FABLE_COMPILER diff --git a/src/fcs-fable/src/fsharp/service/service.fsi b/src/fcs-fable/src/fsharp/service/service.fsi index cc6e87d6c7..afd01541ff 100755 --- a/src/fcs-fable/src/fsharp/service/service.fsi +++ b/src/fcs-fable/src/fsharp/service/service.fsi @@ -1,358 +1,24 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -//---------------------------------------------------------------------------- -// SourceCodeServices API to the compiler as an incremental service for parsing, -// type checking and intellisense-like environment-reporting. -//---------------------------------------------------------------------------- - +/// SourceCodeServices API to the compiler as an incremental service for parsing, +/// type checking and intellisense-like environment-reporting. namespace FSharp.Compiler.SourceCodeServices + open System open System.IO -open System.Collections.Generic -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.IL -open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler open FSharp.Compiler.AbstractIL.ILBinaryReader -open FSharp.Compiler -open FSharp.Compiler.AccessibilityLogic -open FSharp.Compiler.Ast -#if !FABLE_COMPILER -open FSharp.Compiler.Driver -#endif -open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.SyntaxTree open FSharp.Compiler.Range -open FSharp.Compiler.TcGlobals -open FSharp.Compiler.NameResolution -open FSharp.Compiler.CompileOps -open FSharp.Compiler.Infos -open FSharp.Compiler.InfoReader -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops - -/// Represents the reason why the GetDeclarationLocation operation failed. -[] -type public FSharpFindDeclFailureReason = - - /// Generic reason: no particular information about error apart from a message - | Unknown of message: string - - /// Source code file is not available - | NoSourceCode - - /// Trying to find declaration of ProvidedType without TypeProviderDefinitionLocationAttribute - | ProvidedType of string - - /// Trying to find declaration of ProvidedMember without TypeProviderDefinitionLocationAttribute - | ProvidedMember of string - -/// Represents the result of the GetDeclarationLocation operation. -[] -type public FSharpFindDeclResult = - /// Indicates a declaration location was not found, with an additional reason - | DeclNotFound of FSharpFindDeclFailureReason - /// Indicates a declaration location was found - | DeclFound of range - /// Indicates an external declaration was found - | ExternalDecl of assembly : string * externalSym : ExternalSymbol - -/// Represents the checking context implied by the ProjectOptions -[] -type public FSharpProjectContext = - /// Get the resolution and full contents of the assemblies referenced by the project options - member GetReferencedAssemblies : unit -> FSharpAssembly list - - /// Get the accessibility rights for this project context w.r.t. InternalsVisibleTo attributes granting access to other assemblies - member AccessibilityRights : FSharpAccessibilityRights - - -[] -type public SemanticClassificationType = - | ReferenceType - | ValueType - | UnionCase - | Function - | Property - | MutableVar - | Module - | Printf - | ComputationExpression - | IntrinsicFunction - | Enumeration - | Interface - | TypeArgument - | Operator - | Disposable - -#if FABLE_COMPILER -[] -type internal TypeCheckInfo = - internal new : - tcConfig: TcConfig * - tcGlobals: TcGlobals * - ccuSigForFile: ModuleOrNamespaceType * - thisCcu: CcuThunk * - tcImports: TcImports * - tcAccessRights: AccessorDomain * - projectFileName: string * - mainInputFileName: string * - sResolutions: TcResolutions * - sSymbolUses: TcSymbolUses * - sFallback: NameResolutionEnv * - loadClosure : LoadClosure option * - reactorOps : IReactorOperations * - checkAlive : (unit -> bool) * - textSnapshotInfo: obj option * - implFileOpt: TypedImplFile option * - openDeclarations: OpenDeclaration[] - -> TypeCheckInfo - member ScopeResolutions: TcResolutions - member ScopeSymbolUses: TcSymbolUses - member TcGlobals: TcGlobals - member TcImports: TcImports - member CcuSigForFile: Tast.ModuleOrNamespaceType - member ThisCcu: Tast.CcuThunk - member ImplementationFile: TypedImplFile option -#endif - -/// A handle to the results of CheckFileInProject. -[] -type public FSharpCheckFileResults = - -#if FABLE_COMPILER - internal new : filename: string * errors: FSharpErrorInfo[] * scopeOptX: TypeCheckInfo option * dependencyFiles: string[] * builderX: IncrementalBuilder option * reactorOpsX:IReactorOperations * keepAssemblyContents: bool -> FSharpCheckFileResults -#endif - /// The errors returned by parsing a source file. - member Errors : FSharpErrorInfo[] - - /// Get a view of the contents of the assembly up to and including the file just checked - member PartialAssemblySignature : FSharpAssemblySignature - - /// Get the resolution of the ProjectOptions - member ProjectContext : FSharpProjectContext - - /// Indicates whether type checking successfully occurred with some results returned. If false, indicates that - /// an unrecoverable error in earlier checking/parsing/resolution steps. - member HasFullTypeCheckInfo: bool - - /// Indicates the set of files which must be watched to accurately track changes that affect these results, - /// Clients interested in reacting to updates to these files should watch these files and take actions as described - /// in the documentation for compiler service. - member DependencyFiles : string[] - - /// Get the items for a declaration list - /// - /// - /// If this is present, it is used to filter declarations based on location in the - /// parse tree, specifically at 'open' declarations, 'inherit' of class or interface - /// 'record field' locations and r.h.s. of 'range' operator a..b - /// - /// The line number where the completion is happening - /// - /// Partial long name. QuickParse.GetPartialLongNameEx can be used to get it. - /// - /// - /// The text of the line where the completion is happening. This is only used to make a couple - /// of adhoc corrections to completion accuracy (e.g. checking for "..") - /// - /// - /// Function that returns all entities from current and referenced assemblies. - /// - /// - /// If text has been used from a captured name resolution from the typecheck, then - /// callback to the client to check if the text has changed. If it has, then give up - /// and assume that we're going to repeat the operation later on. - /// - /// An optional string used for tracing compiler operations associated with this request. - member GetDeclarationListInfo : ParsedFileResultsOpt:FSharpParseFileResults option * line: int * lineText:string * partialName: PartialLongName * ?getAllEntities: (unit -> AssemblySymbol list) * ?hasTextChangedSinceLastTypecheck: (obj * range -> bool) * ?userOpName: string -> Async - - /// Get the items for a declaration list in FSharpSymbol format - /// - /// - /// If this is present, it is used to filter declarations based on location in the - /// parse tree, specifically at 'open' declarations, 'inherit' of class or interface - /// 'record field' locations and r.h.s. of 'range' operator a..b - /// - /// The line number where the completion is happening - /// - /// Partial long name. QuickParse.GetPartialLongNameEx can be used to get it. - /// - /// - /// The text of the line where the completion is happening. This is only used to make a couple - /// of adhoc corrections to completion accuracy (e.g. checking for "..") - /// - /// - /// Function that returns all entities from current and referenced assemblies. - /// - /// - /// If text has been used from a captured name resolution from the typecheck, then - /// callback to the client to check if the text has changed. If it has, then give up - /// and assume that we're going to repeat the operation later on. - /// - /// An optional string used for tracing compiler operations associated with this request. - member GetDeclarationListSymbols : ParsedFileResultsOpt:FSharpParseFileResults option * line: int * lineText:string * partialName: PartialLongName * ?getAllEntities: (unit -> AssemblySymbol list) * ?hasTextChangedSinceLastTypecheck: (obj * range -> bool) * ?userOpName: string -> Async - - - /// Compute a formatted tooltip for the given location - /// - /// The line number where the information is being requested. - /// The column number at the end of the identifiers where the information is being requested. - /// The text of the line where the information is being requested. - /// The identifiers at the location where the information is being requested. - /// Used to discriminate between 'identifiers', 'strings' and others. For strings, an attempt is made to give a tooltip for a #r "..." location. Use a value from FSharpTokenInfo.Tag, or FSharpTokenTag.Identifier, unless you have other information available. - /// An optional string used for tracing compiler operations associated with this request. - member GetStructuredToolTipText : line:int * colAtEndOfNames:int * lineText:string * names:string list * tokenTag:int * ?userOpName: string -> Async - - /// Compute a formatted tooltip for the given location - /// - /// The line number where the information is being requested. - /// The column number at the end of the identifiers where the information is being requested. - /// The text of the line where the information is being requested. - /// The identifiers at the location where the information is being requested. - /// Used to discriminate between 'identifiers', 'strings' and others. For strings, an attempt is made to give a tooltip for a #r "..." location. Use a value from FSharpTokenInfo.Tag, or FSharpTokenTag.Identifier, unless you have other information available. - /// An optional string used for tracing compiler operations associated with this request. - member GetToolTipText : line:int * colAtEndOfNames:int * lineText:string * names:string list * tokenTag:int * ?userOpName: string -> Async - - /// Compute the Visual Studio F1-help key identifier for the given location, based on name resolution results - /// - /// The line number where the information is being requested. - /// The column number at the end of the identifiers where the information is being requested. - /// The text of the line where the information is being requested. - /// The identifiers at the location where the information is being requested. - /// An optional string used for tracing compiler operations associated with this request. - member GetF1Keyword : line:int * colAtEndOfNames:int * lineText:string * names:string list * ?userOpName: string -> Async - - - /// Compute a set of method overloads to show in a dialog relevant to the given code location. - /// - /// The line number where the information is being requested. - /// The column number at the end of the identifiers where the information is being requested. - /// The text of the line where the information is being requested. - /// The identifiers at the location where the information is being requested. - /// An optional string used for tracing compiler operations associated with this request. - member GetMethods : line:int * colAtEndOfNames:int * lineText:string * names:string list option * ?userOpName: string -> Async - - /// Compute a set of method overloads to show in a dialog relevant to the given code location. The resulting method overloads are returned as symbols. - /// The line number where the information is being requested. - /// The column number at the end of the identifiers where the information is being requested. - /// The text of the line where the information is being requested. - /// The identifiers at the location where the information is being requested. - /// An optional string used for tracing compiler operations associated with this request. - member GetMethodsAsSymbols : line:int * colAtEndOfNames:int * lineText:string * names:string list * ?userOpName: string -> Async - - /// Resolve the names at the given location to the declaration location of the corresponding construct. - /// - /// The line number where the information is being requested. - /// The column number at the end of the identifiers where the information is being requested. - /// The text of the line where the information is being requested. - /// The identifiers at the location where the information is being requested. - /// If not given, then get the location of the symbol. If false, then prefer the location of the corresponding symbol in the implementation of the file (rather than the signature if present). If true, prefer the location of the corresponding symbol in the signature of the file (rather than the implementation). - /// An optional string used for tracing compiler operations associated with this request. - member GetDeclarationLocation : line:int * colAtEndOfNames:int * lineText:string * names:string list * ?preferFlag:bool * ?userOpName: string -> Async - - - /// Resolve the names at the given location to a use of symbol. - /// - /// The line number where the information is being requested. - /// The column number at the end of the identifiers where the information is being requested. - /// The text of the line where the information is being requested. - /// The identifiers at the location where the information is being requested. - /// An optional string used for tracing compiler operations associated with this request. - member GetSymbolUseAtLocation : line:int * colAtEndOfNames:int * lineText:string * names:string list * ?userOpName: string -> Async - - /// Get any extra colorization info that is available after the typecheck - member GetSemanticClassification : range option -> (range * SemanticClassificationType)[] - - /// Get the locations of format specifiers - [] - member GetFormatSpecifierLocations : unit -> range[] - - /// Get the locations of and number of arguments associated with format specifiers - member GetFormatSpecifierLocationsAndArity : unit -> (range*int)[] - - /// Get all textual usages of all symbols throughout the file - member GetAllUsesOfAllSymbolsInFile : unit -> Async - - /// Get the textual usages that resolved to the given symbol throughout the file - member GetUsesOfSymbolInFile : symbol:FSharpSymbol -> Async - - member internal GetVisibleNamespacesAndModulesAtPoint : pos -> Async - - /// Find the most precise display environment for the given line and column. - member internal GetDisplayEnvForPos : pos : pos -> Async - - /// Determines if a long ident is resolvable at a specific point. - /// An optional string used for tracing compiler operations associated with this request. - member internal IsRelativeNameResolvable: cursorPos : pos * plid : string list * item: Item * ?userOpName: string -> Async - - /// Determines if a long ident is resolvable at a specific point. - /// An optional string used for tracing compiler operations associated with this request. - member IsRelativeNameResolvableFromSymbol: cursorPos : pos * plid : string list * symbol: FSharpSymbol * ?userOpName: string -> Async - - /// Represents complete typechecked implementation file, including its typechecked signatures if any. - member ImplementationFile: FSharpImplementationFileContents option - - /// Open declarations in the file, including auto open modules. - member OpenDeclarations: FSharpOpenDeclaration[] - -/// A handle to the results of CheckFileInProject. -[] -type public FSharpCheckProjectResults = - -#if FABLE_COMPILER - internal new : projectFileName:string * tcConfigOption: TcConfig option * keepAssemblyContents: bool * errors: FSharpErrorInfo[] * details:(TcGlobals*TcImports*Tast.CcuThunk*Tast.ModuleOrNamespaceType*TcSymbolUses list*TypeChecker.TopAttribs option*CompileOps.IRawFSharpAssemblyData option * ILAssemblyRef * AccessibilityLogic.AccessorDomain * Tast.TypedImplFile list option * string[]) option -> FSharpCheckProjectResults -#endif - /// The errors returned by processing the project - member Errors: FSharpErrorInfo[] - - /// Get a view of the overall signature of the assembly. Only valid to use if HasCriticalErrors is false. - member AssemblySignature: FSharpAssemblySignature - - /// Get a view of the overall contents of the assembly. Only valid to use if HasCriticalErrors is false. - member AssemblyContents: FSharpAssemblyContents - - /// Get an optimized view of the overall contents of the assembly. Only valid to use if HasCriticalErrors is false. - member GetOptimizedAssemblyContents: unit -> FSharpAssemblyContents - - /// Get the resolution of the ProjectOptions - member ProjectContext: FSharpProjectContext - - /// Get the textual usages that resolved to the given symbol throughout the project - member GetUsesOfSymbol: symbol:FSharpSymbol -> Async - - /// Get all textual usages of all symbols throughout the project - member GetAllUsesOfAllSymbols: unit -> Async - - /// Indicates if critical errors existed in the project options - member HasCriticalErrors: bool - - /// Indicates the set of files which must be watched to accurately track changes that affect these results, - /// Clients interested in reacting to updates to these files should watch these files and take actions as described - /// in the documentation for compiler service. - member DependencyFiles: string[] +open FSharp.Compiler.Text /// Unused in this API -type public UnresolvedReferencesSet - -/// Options used to determine active --define conditionals and other options relevant to parsing files in a project -type public FSharpParsingOptions = - { - SourceFiles: string[] - ConditionalCompilationDefines: string list - ErrorSeverityOptions: FSharpErrorSeverityOptions - IsInteractive: bool - LightSyntax: bool option - CompilingFsLib: bool - IsExe: bool - } - static member Default: FSharpParsingOptions -#if FABLE_COMPILER - static member internal FromTcConfig: tcConfig: TcConfig * sourceFiles: string[] * isInteractive: bool -> FSharpParsingOptions -#endif +type public UnresolvedReferencesSet /// A set of information describing a project or script build configuration. -type public FSharpProjectOptions = - { +type public FSharpProjectOptions = + { // Note that this may not reduce to just the project directory, because there may be two projects in the same directory. ProjectFileName: string @@ -370,7 +36,7 @@ type public FSharpProjectOptions = ReferencedProjects: (string * FSharpProjectOptions)[] /// When true, the typechecking environment is known a priori to be incomplete, for - /// example when a .fs file is opened outside of a project. In this case, the number of error + /// example when a .fs file is opened outside of a project. In this case, the number of error /// messages reported is reduced. IsIncompleteTypeCheckEnvironment : bool @@ -386,7 +52,7 @@ type public FSharpProjectOptions = UnresolvedReferences : UnresolvedReferencesSet option /// Unused in this API and should be '[]' when used as user-specified input - OriginalLoadReferences: (range * string) list + OriginalLoadReferences: (range * string * string) list /// Extra information passed back on event trigger ExtraProjectInfo : obj option @@ -396,26 +62,14 @@ type public FSharpProjectOptions = /// if and only if the stamps are equal Stamp: int64 option } - -#if FABLE_COMPILER -module internal Parser = - type TypeCheckAborted = Yes | No of TypeCheckInfo - val internal parseFile: source: string * filename: string * options: FSharpParsingOptions * userOpName: string -> FSharpErrorInfo [] * ParsedInput option * bool - val internal CheckOneFile : parseResults:FSharpParseFileResults * source:string * mainInputFileName:string * projectFileName:string * tcConfig:TcConfig * tcGlobals:TcGlobals * tcImports:TcImports * tcState:TcState * moduleNamesDict: ModuleNamesDict * loadClosure:LoadClosure option * backgroundDiagnostics:(PhasedDiagnostic * FSharpErrorSeverity)[] * reactorOps:IReactorOperations * checkAlive:(unit -> bool) * textSnapshotInfo:obj option * userOpName: string -> FSharpErrorInfo [] * TypeCheckAborted - -#else //!FABLE_COMPILER - -/// The result of calling TypeCheckResult including the possibility of abort and background compiler not caught up. -[] -type public FSharpCheckFileAnswer = - | Aborted // because cancellation caused an abandonment of the operation - | Succeeded of FSharpCheckFileResults - -[] + +#if !FABLE_COMPILER + +[] /// Used to parse and check F# source code. type public FSharpChecker = /// - /// Create an instance of an FSharpChecker. + /// Create an instance of an FSharpChecker. /// /// /// The optional size of the project checking cache. @@ -423,7 +77,7 @@ type public FSharpChecker = /// If false, do not keep full intermediate checking results from background checking suitable for returning from GetBackgroundCheckResultsForFileInProject. This reduces memory usage. /// An optional resolver for non-file references, for legacy purposes /// An optional resolver to access the contents of .NET binaries in a memory-efficient way - static member Create : ?projectCacheSize: int * ?keepAssemblyContents: bool * ?keepAllBackgroundResolutions: bool * ?legacyReferenceResolver: ReferenceResolver.Resolver * ?tryGetMetadataSnapshot: ILReaderTryGetMetadataSnapshot -> FSharpChecker + static member Create : ?projectCacheSize: int * ?keepAssemblyContents: bool * ?keepAllBackgroundResolutions: bool * ?legacyReferenceResolver: ReferenceResolver.Resolver * ?tryGetMetadataSnapshot: ILReaderTryGetMetadataSnapshot * ?suggestNamesForErrors: bool * ?keepAllBackgroundSymbolUses: bool * ?enableBackgroundItemKeyStoreAndSemanticClassification: bool -> FSharpChecker /// /// Parse a source code file, returning information about brace matching in the file. @@ -431,10 +85,10 @@ type public FSharpChecker = /// /// /// The filename for the file, used to help caching of results. - /// The full source for the file. + /// The full source for the file. /// Parsing options for the project or script. /// An optional string used for tracing compiler operations associated with this request. - member MatchBraces: filename: string * source: string * options: FSharpParsingOptions * ?userOpName: string -> Async<(range * range)[]> + member MatchBraces: filename: string * sourceText: ISourceText * options: FSharpParsingOptions * ?userOpName: string -> Async<(range * range)[]> /// /// Parse a source code file, returning information about brace matching in the file. @@ -449,25 +103,32 @@ type public FSharpChecker = member MatchBraces: filename: string * source: string * options: FSharpProjectOptions * ?userOpName: string -> Async<(range * range)[]> /// - /// Parse a source code file, returning a handle that can be used for obtaining navigation bar information - /// To get the full information, call 'CheckFileInProject' method on the result + /// Parses a source code for a file and caches the results. Returns an AST that can be traversed for various features. /// /// - /// The filename for the file. - /// The full source for the file. + /// The path for the file. The file name is used as a module name for implicit top level modules (e.g. in scripts). + /// The source to be parsed. /// Parsing options for the project or script. /// An optional string used for tracing compiler operations associated with this request. - member ParseFile: filename: string * source: string * options: FSharpParsingOptions * ?userOpName: string -> Async + member ParseFile: filename: string * sourceText: ISourceText * options: FSharpParsingOptions * ?userOpName: string -> Async /// - /// Parse a source code file, returning a handle that can be used for obtaining navigation bar information - /// To get the full information, call 'CheckFileInProject' method on the result - /// All files except the one being checked are read from the FileSystem API + /// Parses a source code for a file. Returns an AST that can be traversed for various features. /// /// - /// The filename for the file. - /// The full source for the file. - /// The options for the project or script, used to determine active --define conditionals and other options relevant to parsing. + /// The path for the file. The file name is also as a module name for implicit top level modules (e.g. in scripts). + /// The source to be parsed. + /// Parsing options for the project or script. + /// An optional string used for tracing compiler operations associated with this request. + member ParseFileNoCache: filename: string * sourceText: ISourceText * options: FSharpParsingOptions * ?userOpName: string -> Async + + /// + /// Parses a source code for a file. Returns an AST that can be traversed for various features. + /// + /// + /// The path for the file. The file name is also as a module name for implicit top level modules (e.g. in scripts). + /// The source to be parsed. + /// Parsing options for the project or script. /// An optional string used for tracing compiler operations associated with this request. [] member ParseFileInProject: filename: string * source: string * options: FSharpProjectOptions * ?userOpName: string -> Async @@ -477,8 +138,8 @@ type public FSharpChecker = /// the reconstructed types in the file. /// /// All files except the one being checked are read from the FileSystem API - /// Note: returns NoAntecedent if the background builder is not yet done preparing the type check context for the - /// file (e.g. loading references and parsing/checking files in the project that this file depends upon). + /// Note: returns NoAntecedent if the background builder is not yet done preparing the type check context for the + /// file (e.g. loading references and parsing/checking files in the project that this file depends upon). /// In this case, the caller can either retry, or wait for FileTypeCheckStateIsDirty to be raised for this file. /// /// @@ -489,8 +150,8 @@ type public FSharpChecker = /// The full source for the file. /// The options for the project or script. /// - /// An item passed back to 'hasTextChangedSinceLastTypecheck' (from some calls made on 'FSharpCheckFileResults') to help determine if - /// an approximate intellisense resolution is inaccurate because a range of text has changed. This + /// An item passed back to 'hasTextChangedSinceLastTypecheck' (from some calls made on 'FSharpCheckFileResults') to help determine if + /// an approximate intellisense resolution is inaccurate because a range of text has changed. This /// can be used to marginally increase accuracy of intellisense results in some situations. /// /// An optional string used for tracing compiler operations associated with this request. @@ -512,19 +173,19 @@ type public FSharpChecker = /// The results of ParseFile for this file. /// The name of the file in the project whose source is being checked. /// An integer that can be used to indicate the version of the file. This will be returned by TryGetRecentCheckResultsForFile when looking up the file. - /// The full source for the file. + /// The full source for the file. /// The options for the project or script. /// - /// An item passed back to 'hasTextChangedSinceLastTypecheck' (from some calls made on 'FSharpCheckFileResults') to help determine if - /// an approximate intellisense resolution is inaccurate because a range of text has changed. This + /// An item passed back to 'hasTextChangedSinceLastTypecheck' (from some calls made on 'FSharpCheckFileResults') to help determine if + /// an approximate intellisense resolution is inaccurate because a range of text has changed. This /// can be used to marginally increase accuracy of intellisense results in some situations. /// /// An optional string used for tracing compiler operations associated with this request. - member CheckFileInProject : parsed: FSharpParseFileResults * filename: string * fileversion: int * source: string * options: FSharpProjectOptions * ?textSnapshotInfo: obj * ?userOpName: string -> Async + member CheckFileInProject : parsed: FSharpParseFileResults * filename: string * fileversion: int * sourceText: ISourceText * options: FSharpProjectOptions * ?textSnapshotInfo: obj * ?userOpName: string -> Async /// /// - /// Parse and check a source code file, returning a handle to the results + /// Parse and check a source code file, returning a handle to the results /// /// /// Note: all files except the one being checked are read from the FileSystem API @@ -539,12 +200,12 @@ type public FSharpChecker = /// The full source for the file. /// The options for the project or script. /// - /// An item passed back to 'hasTextChangedSinceLastTypecheck' (from some calls made on 'FSharpCheckFileResults') to help determine if - /// an approximate intellisense resolution is inaccurate because a range of text has changed. This + /// An item passed back to 'hasTextChangedSinceLastTypecheck' (from some calls made on 'FSharpCheckFileResults') to help determine if + /// an approximate intellisense resolution is inaccurate because a range of text has changed. This /// can be used to marginally increase accuracy of intellisense results in some situations. /// /// An optional string used for tracing compiler operations associated with this request. - member ParseAndCheckFileInProject : filename: string * fileversion: int * source: string * options: FSharpProjectOptions * ?textSnapshotInfo: obj * ?userOpName: string -> Async + member ParseAndCheckFileInProject : filename: string * fileversion: int * sourceText: ISourceText * options: FSharpProjectOptions * ?textSnapshotInfo: obj * ?userOpName: string -> Async /// /// Parse and typecheck all files in a project. @@ -555,14 +216,6 @@ type public FSharpChecker = /// An optional string used for tracing compiler operations associated with this request. member ParseAndCheckProject : options: FSharpProjectOptions * ?userOpName: string -> Async - /// - /// Create resources for the project and keep the project alive until the returned object is disposed. - /// - /// - /// The options for the project or script. - /// An optional string used for tracing compiler operations associated with this request. - member KeepProjectAlive : options: FSharpProjectOptions * ?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. @@ -575,7 +228,7 @@ type public FSharpChecker = /// so that an 'unload' and 'reload' action will cause the script to be considered as a new project, /// so that references are re-resolved. /// An optional string used for tracing compiler operations associated with this request. - member GetProjectOptionsFromScript : filename: string * source: string * ?loadedTimeStamp: DateTime * ?otherFlags: string[] * ?useFsiAuxLib: bool * ?assumeDotNetFramework: bool * ?extraProjectInfo: obj * ?optionsStamp: int64 * ?userOpName: string -> Async + member GetProjectOptionsFromScript : filename: string * sourceText: ISourceText * ?previewEnabled:bool * ?loadedTimeStamp: DateTime * ?otherFlags: string[] * ?useFsiAuxLib: bool * ?useSdkRefs: bool * ?assumeDotNetFramework: bool * ?extraProjectInfo: obj * ?optionsStamp: int64 * ?userOpName: string -> Async /// /// Get the FSharpProjectOptions implied by a set of command line arguments. @@ -631,13 +284,34 @@ type public FSharpChecker = member GetBackgroundCheckResultsForFileInProject : filename : string * options : FSharpProjectOptions * ?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. + /// Optimized find references for a given symbol in a file of project. + /// All files are read from the FileSystem API, including the file being checked. + /// + /// + /// The filename for the file. + /// The options for the project or script, used to determine active --define conditionals and other options relevant to parsing. + /// The symbol to find all uses in the file. + /// An optional string used for tracing compiler operations associated with this request. + member FindBackgroundReferencesInFile : filename : string * options : FSharpProjectOptions * symbol: FSharpSymbol * ?userOpName: string -> Async + + /// + /// Get semantic classification for a file. + /// All files are read from the FileSystem API, including the file being checked. + /// + /// + /// The filename for the file. + /// The options for the project or script, used to determine active --define conditionals and other options relevant to parsing. + /// An optional string used for tracing compiler operations associated with this request. + member GetBackgroundSemanticClassificationForFile : filename : string * options : FSharpProjectOptions * ?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. /// The first argument is ignored and can just be "fsc.exe". /// /// An optional string used for tracing compiler operations associated with this request. member Compile: argv:string[] * ?userOpName: string -> Async - + /// /// TypeCheck and compile provided AST /// @@ -645,15 +319,15 @@ type public FSharpChecker = member Compile: ast:ParsedInput list * assemblyName:string * outFile:string * dependencies:string list * ?pdbFile:string * ?executable:bool * ?noframework:bool * ?userOpName: string -> Async /// - /// Compiles to a dynamic assembly using the given flags. + /// Compiles to a dynamic assembly using the given flags. /// /// The first argument is ignored and can just be "fsc.exe". /// /// Any source files names are resolved via the FileSystem API. An output file name must be given by a -o flag, but this will not /// be written - instead a dynamic assembly will be created and loaded. /// - /// If the 'execute' parameter is given the entry points for the code are executed and - /// the given TextWriters are used for the stdout and stderr streams respectively. In this + /// If the 'execute' parameter is given the entry points for the code are executed and + /// the given TextWriters are used for the stdout and stderr streams respectively. In this /// case, a global setting is modified during the execution. /// /// An optional string used for tracing compiler operations associated with this request. @@ -664,7 +338,7 @@ type public FSharpChecker = /// /// An optional string used for tracing compiler operations associated with this request. member CompileToDynamicAssembly: ast:ParsedInput list * assemblyName:string * dependencies:string list * execute:(TextWriter * TextWriter) option * ?debug:bool * ?noframework:bool * ?userOpName: string -> Async - + /// /// Try to get type check results for a file. This looks up the results of recent type checks of the /// same file, regardless of contents. The version tag specified in the original check of the file is returned. @@ -673,30 +347,30 @@ type public FSharpChecker = /// /// The filename for the file. /// The options for the project or script, used to determine active --define conditionals and other options relevant to parsing. - /// Optionally, specify source that must match the previous parse precisely. + /// Optionally, specify source that must match the previous parse precisely. /// An optional string used for tracing compiler operations associated with this request. - member TryGetRecentCheckResultsForFile : filename: string * options:FSharpProjectOptions * ?source: string * ?userOpName: string -> (FSharpParseFileResults * FSharpCheckFileResults * (*version*)int) option + member TryGetRecentCheckResultsForFile : filename: string * options:FSharpProjectOptions * ?sourceText: ISourceText * ?userOpName: string -> (FSharpParseFileResults * FSharpCheckFileResults * (*version*)int) option /// This function is called when the entire environment is known to have changed for reasons not encoded in the ProjectOptions of any project/compilation. - member InvalidateAll : unit -> unit - + member InvalidateAll : unit -> unit + /// This function is called when the configuration is known to have changed for reasons not encoded in the ProjectOptions. /// For example, dependent references may have been deleted or created. /// Start a background compile of the project if a project with the same name has already been seen before. /// An optional string used for tracing compiler operations associated with this request. - member InvalidateConfiguration: options: FSharpProjectOptions * ?startBackgroundCompileIfAlreadySeen: bool * ?userOpName: string -> unit + member InvalidateConfiguration: options: FSharpProjectOptions * ?startBackgroundCompileIfAlreadySeen: bool * ?userOpName: string -> unit /// Set the project to be checked in the background. Overrides any previous call to CheckProjectInBackground member CheckProjectInBackground: options: FSharpProjectOptions * ?userOpName: string -> unit /// Stop the background compile. - //[] + //[] member StopBackgroundCompile : unit -> unit /// Block until the background compile finishes. - //[] + //[] member WaitForBackgroundCompile : unit -> unit - + /// Report a statistic for testability static member GlobalForegroundParseCountStatistic : int @@ -706,8 +380,8 @@ type public FSharpChecker = /// Flush all caches and garbage collect member ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients : unit -> unit - /// Current queue length of the service, for debug purposes. - /// In addition, a single async operation or a step of a background build + /// Current queue length of the service, for debug purposes. + /// In addition, a single async operation or a step of a background build /// may be in progress - such an operation is not counted in the queue length. member CurrentQueueLength : int @@ -716,7 +390,7 @@ type public FSharpChecker = /// /// An optional string used for tracing compiler operations associated with this request. member NotifyProjectCleaned: options: FSharpProjectOptions * ?userOpName: string -> Async - + /// Notify the host that the logical type checking context for a file has now been updated internally /// and that the file has become eligible to be re-typechecked for errors. /// @@ -732,29 +406,29 @@ type public FSharpChecker = /// /// The event will be raised on a background thread. member FileChecked : IEvent - + /// Raised after the maxMB memory threshold limit is reached member MaxMemoryReached : IEvent /// A maximum number of megabytes of allocated memory. If the figure reported by System.GC.GetTotalMemory(false) goes over this limit, the FSharpChecker object will attempt to free memory and reduce cache sizes to a minimum. member MaxMemory : int with get, set - - /// Get or set a flag which controls if background work is started implicitly. + + /// Get or set a flag which controls if background work is started implicitly. /// /// If true, calls to CheckFileInProject implicitly start a background check of that project, replacing - /// any other background checks in progress. This is useful in IDE applications with spare CPU cycles as + /// any other background checks in progress. This is useful in IDE applications with spare CPU cycles as /// it prepares the project analysis results for use. The default is 'true'. member ImplicitlyStartBackgroundWork: bool with get, set - + /// Get or set the pause time in milliseconds before background work is started. member PauseBeforeBackgroundWork: int with get, set - + /// Notify the host that a project has been fully checked in the background (using file contents provided by the file system API) /// /// The event may be raised on a background thread. member ProjectChecked : IEvent - // For internal use only + // For internal use only member internal ReactorOps : IReactorOperations [] @@ -767,15 +441,6 @@ type public FSharpChecker = /// Tokenize an entire file, line by line member TokenizeFile: source:string -> FSharpTokenInfo [] [] - - -// An object to typecheck source in a given typechecking environment. -// Used internally to provide intellisense over F# Interactive. -type internal FsiInteractiveChecker = - internal new : ReferenceResolver.Resolver * ops: IReactorOperations * tcConfig: TcConfig * tcGlobals: TcGlobals * tcImports: TcImports * tcState: TcState -> FsiInteractiveChecker - - /// An optional string used for tracing compiler operations associated with this request. - member internal ParseAndCheckInteraction : CompilationThreadToken * source:string * ?userOpName: string -> Async /// Information about the compilation environment [] @@ -783,8 +448,8 @@ type public CompilerEnvironment = /// The default location of FSharp.Core.dll and fsc.exe based on the version of fsc.exe that is running static member BinFolderOfDefaultFSharpCompiler : ?probePoint: string -> string option -/// Information about the compilation environment -[] +/// Information about the compilation environment +[] module public CompilerEnvironment = /// These are the names of assemblies that should be referenced for .fs or .fsi files that /// are not associated with a project. @@ -799,7 +464,7 @@ module public DebuggerEnvironment = /// Return the language ID, which is the expression evaluator id that the /// debugger will use. val GetLanguageID : unit -> Guid - + /// A set of helpers related to naming of identifiers module public PrettyNaming = @@ -811,66 +476,14 @@ module public PrettyNaming = val FormatAndOtherOverloadsString : int -> string - /// A utility to help determine if an identifier needs to be quoted + /// A utility to help determine if an identifier needs to be quoted val QuoteIdentifierIfNeeded : string -> string - /// All the keywords in the F# language + /// All the keywords in the F# language val KeywordNames : string list -namespace Microsoft.FSharp.Compiler.SourceCodeServices - - open System - - [] - type FSharpFindDeclFailureReason - [] - type FSharpFindDeclResult - [] - type FSharpProjectContext - [] - type SemanticClassificationType - [] - type FSharpCheckFileResults - [] - type FSharpCheckProjectResults - [] - type UnresolvedReferencesSet - [] - type FSharpParsingOptions - [] - type FSharpProjectOptions - [] - type FSharpCheckFileAnswer - [] - type FSharpChecker - [] - type CompilerEnvironment - [] - module CompilerEnvironment = begin end - [] - module DebuggerEnvironment = begin end - [] - module PrettyNaming = begin end - -namespace Microsoft.FSharp.Compiler.Interactive.Shell - - open System - - [] - type FsiValue - [] - type EvaluationEventArgs - [] - type public FsiEvaluationSessionHostConfig - [] - type FsiEvaluationSession - [] - module Settings = begin end - - /// Defines a read-only input stream used to feed content to the hosted F# Interactive dynamic compiler. - [] - type CompilerInputStream - [] - type CompilerOutputStream +/// A set of helpers for dealing with F# files. +module FSharpFileUtilities = + val isScriptFile : string -> bool #endif //!FABLE_COMPILER diff --git a/src/fcs-fable/src/fsharp/sr.fs b/src/fcs-fable/src/fsharp/sr.fs old mode 100755 new mode 100644 index a59c2419ea..ae81bb6abc --- a/src/fcs-fable/src/fsharp/sr.fs +++ b/src/fcs-fable/src/fsharp/sr.fs @@ -2,13 +2,8 @@ namespace FSharp.Compiler open Microsoft.FSharp.Core - open Microsoft.FSharp.Core.Operators open Microsoft.FSharp.Collections open Microsoft.FSharp.Reflection - open System.Globalization - open System.IO - open System.Text - open System.Reflection module internal SR = let private resources = lazy (new System.Resources.ResourceManager("fsstrings", System.Reflection.Assembly.GetExecutingAssembly())) @@ -24,9 +19,6 @@ namespace FSharp.Compiler module internal DiagnosticMessage = open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators - open Microsoft.FSharp.Reflection - open System.Reflection - open Internal.Utilities.StructuredFormat let mkFunctionValue (tys: System.Type[]) (impl:obj->obj) = FSharpValue.MakeFunction(FSharpType.MakeFunctionType(tys.[0],tys.[1]), impl) @@ -57,7 +49,7 @@ namespace FSharp.Compiler | '%' -> go args ty (i+1) | 'd' | 'f' - | 's' -> buildFunctionForOneArgPat ty (fun rty n -> go (n::args) rty (i+1)) + | 's' -> buildFunctionForOneArgPat ty (fun rty n -> go (n :: args) rty (i+1)) | _ -> failwith "bad format specifier" // newlines and tabs get converted to strings when read from a resource file diff --git a/src/fcs-fable/src/fsharp/sr.fsi b/src/fcs-fable/src/fsharp/sr.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/fsharp/symbols/Exprs.fs b/src/fcs-fable/src/fsharp/symbols/Exprs.fs index d7480cb07a..fcafddbf22 100644 --- a/src/fcs-fable/src/fsharp/symbols/Exprs.fs +++ b/src/fcs-fable/src/fsharp/symbols/Exprs.fs @@ -7,10 +7,12 @@ open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.Lib open FSharp.Compiler.Infos -open FSharp.Compiler.Range -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops open FSharp.Compiler.QuotationTranslator +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TypeRelations [] @@ -19,16 +21,21 @@ module ExprTranslationImpl = let nonNil x = not (List.isEmpty x) type ExprTranslationEnv = - { //Map from Val to binding index + { + /// Map from Val to binding index vs: ValMap - //Map from typar stamps to binding index + + /// Map from typar stamps to binding index tyvs: StampMap + // Map for values bound by the // 'let v = isinst e in .... if nonnull v then ...v .... ' // construct arising out the compilation of pattern matching. We decode these back to the form // 'if istype v then ...unbox v .... ' isinstVals: ValMap - substVals: ValMap } + + substVals: ValMap + } static member Empty = { vs=ValMap<_>.Empty @@ -61,7 +68,6 @@ module ExprTranslationImpl = let wfail (msg, m: range) = failwith (msg + sprintf " at %s" (m.ToString())) - /// The core tree of data produced by converting F# compiler TAST expressions into the form which we make available through the compiler API /// through active patterns. type E = @@ -90,7 +96,7 @@ type E = | UnionCaseSet of FSharpExpr * FSharpType * FSharpUnionCase * FSharpField * FSharpExpr | UnionCaseTag of FSharpExpr * FSharpType | UnionCaseTest of FSharpExpr * FSharpType * FSharpUnionCase - | TraitCall of FSharpType list * string * Ast.MemberFlags * FSharpType list * FSharpType list * FSharpExpr list + | TraitCall of FSharpType list * string * MemberFlags * FSharpType list * FSharpType list * FSharpExpr list | NewTuple of FSharpType * FSharpExpr list | TupleGet of FSharpType * int * FSharpExpr | Coerce of FSharpType * FSharpExpr @@ -144,7 +150,7 @@ and [] FSharpExpr (cenv, f: (unit -> FSharpExpr) option, e: E, m: range, | E.NewUnionCase (_unionType, _unionCase, es) -> es | E.NewTuple (_tupleType, es) -> es | E.TupleGet (_tupleType, _itemIndex, tupleExpr) -> [tupleExpr] - | E.Call (objOpt, _b, _c, _d, es) -> (match objOpt with None -> es | Some x -> x::es) + | E.Call (objOpt, _b, _c, _d, es) -> (match objOpt with None -> es | Some x -> x :: es) | E.NewObject (_a, _b, c) -> c | E.FSharpFieldGet (objOpt, _b, _c) -> (match objOpt with None -> [] | Some x -> [x]) | E.FSharpFieldSet (objOpt, _b, _c, d) -> (match objOpt with None -> [d] | Some x -> [x;d]) @@ -153,7 +159,7 @@ and [] FSharpExpr (cenv, f: (unit -> FSharpExpr) option, e: E, m: range, | E.UnionCaseTest (obj, _b, _c) -> [obj] | E.NewArray (_ty, elems) -> elems | E.Coerce (_ty, b) -> [b] - | E.Quote (a) -> [a] + | E.Quote a -> [a] | E.TypeTest (_ty, b) -> [b] | E.Sequential (a, b) -> [a;b] | E.FastIntegerForLoop (a, b, c, _dir) -> [a;b;c] @@ -161,12 +167,12 @@ and [] FSharpExpr (cenv, f: (unit -> FSharpExpr) option, e: E, m: range, | E.TryFinally (body, b) -> [body; b] | E.TryWith (body, _b, _c, _d, handler) -> [body; handler] | E.NewDelegate (_ty, body) -> [body] - | E.DefaultValue (_ty) -> [] + | E.DefaultValue _ty -> [] | E.AddressSet (lvalueExpr, rvalueExpr) -> [lvalueExpr; rvalueExpr] | E.ValueSet (_v, rvalueExpr) -> [rvalueExpr] - | E.AddressOf (lvalueExpr) -> [lvalueExpr] - | E.ThisValue (_ty) -> [] - | E.BaseValue (_ty) -> [] + | E.AddressOf lvalueExpr -> [lvalueExpr] + | E.ThisValue _ty -> [] + | E.BaseValue _ty -> [] | E.ILAsm (_code, _tyargs, argExprs) -> argExprs | E.ILFieldGet (objOpt, _ty, _fieldName) -> (match objOpt with None -> [] | Some x -> [x]) | E.ILFieldSet (objOpt, _ty, _fieldName, d) -> (match objOpt with None -> [d] | Some x -> [x;d]) @@ -195,13 +201,13 @@ module FSharpExprConvert = // Match "if [AI_clt](init@41, 6) then IntrinsicFunctions.FailStaticInit () else ()" let (|StaticInitializationCheck|_|) e = match e with - | Expr.Match (_, _, TDSwitch(Expr.Op(TOp.ILAsm ([ AI_clt ], _), _, [Expr.Op(TOp.ValFieldGet rfref, _, _, _) ;_], _), _, _, _), _, _, _) when IsStaticInitializationField rfref -> Some () + | Expr.Match (_, _, TDSwitch(Expr.Op (TOp.ILAsm ([ AI_clt ], _), _, [Expr.Op (TOp.ValFieldGet rfref, _, _, _) ;_], _), _, _, _), _, _, _) when IsStaticInitializationField rfref -> Some () | _ -> None // Match "init@41 <- 6" let (|StaticInitializationCount|_|) e = match e with - | Expr.Op(TOp.ValFieldSet rfref, _, _, _) when IsStaticInitializationField rfref -> Some () + | Expr.Op (TOp.ValFieldSet rfref, _, _, _) when IsStaticInitializationField rfref -> Some () | _ -> None let (|ILUnaryOp|_|) e = @@ -307,15 +313,15 @@ module FSharpExprConvert = let rec exprOfExprAddr (cenv: SymbolEnv) expr = match expr with - | Expr.Op(op, tyargs, args, m) -> + | Expr.Op (op, tyargs, args, m) -> match op, args, tyargs with - | TOp.LValueOp(LAddrOf _, vref), _, _ -> exprForValRef m vref - | TOp.ValFieldGetAddr(rfref, _), [], _ -> mkStaticRecdFieldGet(rfref, tyargs, m) - | TOp.ValFieldGetAddr(rfref, _), [arg], _ -> mkRecdFieldGetViaExprAddr(exprOfExprAddr cenv arg, rfref, tyargs, m) - | TOp.UnionCaseFieldGetAddr(uref, n, _), [arg], _ -> mkUnionCaseFieldGetProvenViaExprAddr(exprOfExprAddr cenv arg, uref, tyargs, n, m) - | TOp.ILAsm([ I_ldflda(fspec) ], rtys), [arg], _ -> mkAsmExpr([ mkNormalLdfld(fspec) ], tyargs, [exprOfExprAddr cenv arg], rtys, m) - | TOp.ILAsm([ I_ldsflda(fspec) ], rtys), _, _ -> mkAsmExpr([ mkNormalLdsfld(fspec) ], tyargs, args, rtys, m) - | TOp.ILAsm(([ I_ldelema(_ro, _isNativePtr, shape, _tyarg) ] ), _), (arr::idxs), [elemty] -> + | TOp.LValueOp (LAddrOf _, vref), _, _ -> exprForValRef m vref + | TOp.ValFieldGetAddr (rfref, _), [], _ -> mkStaticRecdFieldGet (rfref, tyargs, m) + | TOp.ValFieldGetAddr (rfref, _), [arg], _ -> mkRecdFieldGetViaExprAddr (exprOfExprAddr cenv arg, rfref, tyargs, m) + | TOp.UnionCaseFieldGetAddr (uref, n, _), [arg], _ -> mkUnionCaseFieldGetProvenViaExprAddr (exprOfExprAddr cenv arg, uref, tyargs, n, m) + | TOp.ILAsm ([ I_ldflda fspec ], rtys), [arg], _ -> mkAsmExpr ([ mkNormalLdfld fspec ], tyargs, [exprOfExprAddr cenv arg], rtys, m) + | TOp.ILAsm ([ I_ldsflda fspec ], rtys), _, _ -> mkAsmExpr ([ mkNormalLdsfld fspec ], tyargs, args, rtys, m) + | TOp.ILAsm (([ I_ldelema(_ro, _isNativePtr, shape, _tyarg) ] ), _), (arr :: idxs), [elemty] -> match shape.Rank, idxs with | 1, [idx1] -> mkCallArrayGet cenv.g m elemty arr idx1 | 2, [idx1; idx2] -> mkCallArray2DGet cenv.g m elemty arr idx1 idx2 @@ -335,28 +341,28 @@ module FSharpExprConvert = and ConvExpr cenv env expr = Mk2 cenv expr (ConvExprPrim cenv env expr) - and ConvExprLinear cenv env expr contf = - ConvExprPrimLinear cenv env expr (fun exprR -> contf (Mk2 cenv expr exprR)) + and ConvExprLinear cenv env expr contF = + ConvExprPrimLinear cenv env expr (fun exprR -> contF (Mk2 cenv expr exprR)) // Tail recursive function to process the subset of expressions considered "linear" - and ConvExprPrimLinear cenv env expr contf = + and ConvExprPrimLinear cenv env expr contF = match expr with // Large lists - | Expr.Op(TOp.UnionCase ucref, tyargs, [e1;e2], _) -> + | Expr.Op (TOp.UnionCase ucref, tyargs, [e1;e2], _) -> let mkR = ConvUnionCaseRef cenv ucref let typR = ConvType cenv (mkAppTy ucref.TyconRef tyargs) let e1R = ConvExpr cenv env e1 // tail recursive - ConvExprLinear cenv env e2 (contf << (fun e2R -> E.NewUnionCase(typR, mkR, [e1R; e2R]) )) + ConvExprLinear cenv env e2 (contF << (fun e2R -> E.NewUnionCase(typR, mkR, [e1R; e2R]) )) // Large sequences of let bindings | Expr.Let (bind, body, _, _) -> match ConvLetBind cenv env bind with - | None, env -> ConvExprPrimLinear cenv env body contf - | Some(bindR), env -> + | None, env -> ConvExprPrimLinear cenv env body contF + | Some bindR, env -> // tail recursive - ConvExprLinear cenv env body (contf << (fun bodyR -> E.Let(bindR, bodyR))) + ConvExprLinear cenv env body (contF << (fun bodyR -> E.Let(bindR, bodyR))) // Remove initialization checks // Remove static initialization counter updates @@ -365,26 +371,26 @@ module FSharpExprConvert = // Put in ConvExprPrimLinear because of the overlap with Expr.Sequential below // // TODO: allow clients to see static initialization checks if they want to - | Expr.Sequential(ObjectInitializationCheck cenv.g, x1, NormalSeq, _, _) - | Expr.Sequential (StaticInitializationCount, x1, NormalSeq, _, _) - | Expr.Sequential (StaticInitializationCheck, x1, NormalSeq, _, _) -> - ConvExprPrim cenv env x1 |> contf + | Expr.Sequential (ObjectInitializationCheck cenv.g, x1, NormalSeq, _, _) + | Expr.Sequential (StaticInitializationCount, x1, NormalSeq, _, _) + | Expr.Sequential (StaticInitializationCheck, x1, NormalSeq, _, _) -> + ConvExprPrim cenv env x1 |> contF // Large sequences of sequential code | Expr.Sequential (e1, e2, NormalSeq, _, _) -> let e1R = ConvExpr cenv env e1 // tail recursive - ConvExprLinear cenv env e2 (contf << (fun e2R -> E.Sequential(e1R, e2R))) + ConvExprLinear cenv env e2 (contF << (fun e2R -> E.Sequential(e1R, e2R))) - | Expr.Sequential (x0, x1, ThenDoSeq, _, _) -> E.Sequential(ConvExpr cenv env x0, ConvExpr cenv env x1) + | Expr.Sequential (x0, x1, ThenDoSeq, _, _) -> E.Sequential(ConvExpr cenv env x0, ConvExpr cenv env x1) | ModuleValueOrMemberUse cenv.g (vref, vFlags, _f, _fty, tyargs, curriedArgs) when (nonNil tyargs || nonNil curriedArgs) && vref.IsMemberOrModuleBinding -> - ConvModuleValueOrMemberUseLinear cenv env (expr, vref, vFlags, tyargs, curriedArgs) contf + ConvModuleValueOrMemberUseLinear cenv env (expr, vref, vFlags, tyargs, curriedArgs) contF | Expr.Match (_spBind, m, dtree, tgs, _, retTy) -> let dtreeR = ConvDecisionTree cenv env retTy dtree m // tailcall - ConvTargetsLinear cenv env (List.ofArray tgs) (contf << fun (targetsR: _ list) -> + ConvTargetsLinear cenv env (List.ofArray tgs) (contF << fun (targetsR: _ list) -> let (|E|) (x: FSharpExpr) = x.E // If the match is really an "if-then-else" then return it as such. @@ -393,12 +399,11 @@ module FSharpExprConvert = | _ -> E.DecisionTree(dtreeR, targetsR)) | _ -> - ConvExprPrim cenv env expr |> contf - + ConvExprPrim cenv env expr |> contF /// A nasty function copied from creflect.fs. Made nastier by taking a continuation to process the /// arguments to the call in a tail-recursive fashion. - and ConvModuleValueOrMemberUseLinear (cenv: SymbolEnv) env (expr: Expr, vref, vFlags, tyargs, curriedArgs) contf = + and ConvModuleValueOrMemberUseLinear (cenv: SymbolEnv) env (expr: Expr, vref, vFlags, tyargs, curriedArgs) contF = let m = expr.Range let (numEnclTypeArgs, _, isNewObj, _valUseFlags, _isSelfInit, takesInstanceArg, _isPropGet, _isPropSet) = @@ -423,7 +428,7 @@ module FSharpExprConvert = let objArgs, curriedArgs = match takesInstanceArg, curriedArgs with | false, curriedArgs -> [], curriedArgs - | true, (objArg::curriedArgs) -> [objArg], curriedArgs + | true, (objArg :: curriedArgs) -> [objArg], curriedArgs | true, [] -> failwith ("warning: unexpected missing object argument when generating quotation for call to F# object member "+vref.LogicalName) // Check to see if there aren't enough arguments or if there is a tuple-arity mismatch @@ -441,7 +446,7 @@ module FSharpExprConvert = let expr, exprty = AdjustValForExpectedArity cenv.g m vref vFlags topValInfo let splitCallExpr = MakeApplicationAndBetaReduce cenv.g (expr, exprty, [tyargs], curriedArgs, m) // tailcall - ConvExprPrimLinear cenv env splitCallExpr contf + ConvExprPrimLinear cenv env splitCallExpr contF else let curriedArgs, laterArgs = List.splitAt curriedArgInfos.Length curriedArgs @@ -456,11 +461,11 @@ module FSharpExprConvert = let contf2 = match laterArgs with - | [] -> contf - | _ -> (fun subCallR -> (subCallR, laterArgs) ||> List.fold (fun fR arg -> E.Application (Mk2 cenv arg fR, [], [ConvExpr cenv env arg])) |> contf) + | [] -> contF + | _ -> (fun subCallR -> (subCallR, laterArgs) ||> List.fold (fun fR arg -> E.Application (Mk2 cenv arg fR, [], [ConvExpr cenv env arg])) |> contF) if isMember then - let callArgs = (objArgs::untupledCurriedArgs) |> List.concat + let callArgs = (objArgs :: untupledCurriedArgs) |> List.concat let enclTyArgs, methTyArgs = List.splitAfter numEnclTypeArgs tyargs // tailcall ConvObjectModelCallLinear cenv env (isNewObj, FSharpMemberOrFunctionOrValue(cenv, vref), enclTyArgs, methTyArgs, callArgs) contf2 @@ -483,12 +488,12 @@ module FSharpExprConvert = match expr with // Uses of possibly-polymorphic values which were not polymorphic in the end - | Expr.App(InnerExprPat(Expr.Val _ as ve), _fty, [], [], _) -> + | Expr.App (InnerExprPat(Expr.Val _ as ve), _fty, [], [], _) -> ConvExprPrim cenv env ve // These cases are the start of a "linear" sequence where we use tail recursion to allow use to // deal with large expressions. - | Expr.Op(TOp.UnionCase _, _, [_;_], _) // big lists + | Expr.Op (TOp.UnionCase _, _, [_;_], _) // big lists | Expr.Let _ // big linear sequences of 'let' | Expr.Match _ // big linear sequences of 'match ... -> ....' | Expr.Sequential _ -> @@ -498,17 +503,17 @@ module FSharpExprConvert = // Process applications of top-level values in a tail-recursive way ConvModuleValueOrMemberUseLinear cenv env (expr, vref, vFlags, tyargs, curriedArgs) (fun e -> e) - | Expr.Val(vref, _vFlags, m) -> + | Expr.Val (vref, _vFlags, m) -> ConvValRef cenv env m vref // Simple applications - | Expr.App(f, _fty, tyargs, args, _m) -> + | Expr.App (f, _fty, tyargs, args, _m) -> E.Application (ConvExpr cenv env f, ConvTypes cenv tyargs, ConvExprs cenv env args) - | Expr.Const(c, m, ty) -> + | Expr.Const (c, m, ty) -> ConvConst cenv env m c ty - | Expr.LetRec(binds, body, _, _) -> + | Expr.LetRec (binds, body, _, _) -> let vs = valsOfBinds binds let vsR = vs |> List.map (ConvVal cenv) let env = env.BindVals vs @@ -516,13 +521,13 @@ module FSharpExprConvert = let bindsR = List.zip vsR (binds |> List.map (fun b -> b.Expr |> ConvExpr cenv env)) E.LetRec(bindsR, bodyR) - | Expr.Lambda(_, _, _, vs, b, _, _) -> + | Expr.Lambda (_, _, _, vs, b, _, _) -> let v, b = MultiLambdaToTupledLambda cenv.g vs b let vR = ConvVal cenv v let bR = ConvExpr cenv (env.BindVal v) b E.Lambda(vR, bR) - | Expr.Quote(ast, _, _, _, _) -> + | Expr.Quote (ast, _, _, _, _) -> E.Quote(ConvExpr cenv env ast) | Expr.TyLambda (_, tps, b, _, _) -> @@ -558,7 +563,7 @@ module FSharpExprConvert = E.ObjectExpr(ConvType cenv ty, basecallR, overridesR, iimplsR) - | Expr.Op(op, tyargs, args, m) -> + | Expr.Op (op, tyargs, args, m) -> match op, tyargs, args with | TOp.UnionCase ucref, _, _ -> let mkR = ConvUnionCaseRef cenv ucref @@ -603,42 +608,42 @@ module FSharpExprConvert = | TOp.ValFieldGetAddr _, _tyargs, _ -> E.AddressOf(ConvLValueExpr cenv env expr) - | TOp.ValFieldGet(rfref), tyargs, [] -> + | TOp.ValFieldGet rfref, tyargs, [] -> let projR = ConvRecdFieldRef cenv rfref let typR = ConvType cenv (mkAppTy rfref.TyconRef tyargs) E.FSharpFieldGet(None, typR, projR) - | TOp.ValFieldGet(rfref), tyargs, [obj] -> + | TOp.ValFieldGet rfref, tyargs, [obj] -> let objR = ConvLValueExpr cenv env obj let projR = ConvRecdFieldRef cenv rfref let typR = ConvType cenv (mkAppTy rfref.TyconRef tyargs) E.FSharpFieldGet(Some objR, typR, projR) - | TOp.TupleFieldGet(tupInfo, n), tyargs, [e] -> + | TOp.TupleFieldGet (tupInfo, n), tyargs, [e] -> let tyR = ConvType cenv (mkAnyTupledTy cenv.g tupInfo tyargs) E.TupleGet(tyR, n, ConvExpr cenv env e) - | TOp.ILAsm([ I_ldfld(_, _, fspec) ], _), enclTypeArgs, [obj] -> + | TOp.ILAsm ([ I_ldfld (_, _, fspec) ], _), enclTypeArgs, [obj] -> let typR = ConvILTypeRefApp cenv m fspec.DeclaringTypeRef enclTypeArgs let objR = ConvLValueExpr cenv env obj E.ILFieldGet(Some objR, typR, fspec.Name) - | TOp.ILAsm(( [ I_ldsfld (_, fspec) ] | [ I_ldsfld (_, fspec); AI_nop ]), _), enclTypeArgs, [] -> + | TOp.ILAsm (( [ I_ldsfld (_, fspec) ] | [ I_ldsfld (_, fspec); AI_nop ]), _), enclTypeArgs, [] -> let typR = ConvILTypeRefApp cenv m fspec.DeclaringTypeRef enclTypeArgs E.ILFieldGet(None, typR, fspec.Name) - | TOp.ILAsm([ I_stfld(_, _, fspec) ], _), enclTypeArgs, [obj;arg] -> + | TOp.ILAsm ([ I_stfld (_, _, fspec) ], _), enclTypeArgs, [obj;arg] -> let typR = ConvILTypeRefApp cenv m fspec.DeclaringTypeRef enclTypeArgs let objR = ConvLValueExpr cenv env obj let argR = ConvExpr cenv env arg E.ILFieldSet(Some objR, typR, fspec.Name, argR) - | TOp.ILAsm([ I_stsfld(_, fspec) ], _), enclTypeArgs, [arg] -> + | TOp.ILAsm ([ I_stsfld (_, fspec) ], _), enclTypeArgs, [arg] -> let typR = ConvILTypeRefApp cenv m fspec.DeclaringTypeRef enclTypeArgs let argR = ConvExpr cenv env arg E.ILFieldSet(None, typR, fspec.Name, argR) - | TOp.ILAsm([ ], [tty]), _, [arg] -> + | TOp.ILAsm ([ ], [tty]), _, [arg] -> match tty with | TTypeConvOp cenv convOp -> let ty = tyOfExpr cenv.g arg @@ -647,15 +652,15 @@ module FSharpExprConvert = | _ -> ConvExprPrim cenv env arg - | TOp.ILAsm([ I_box _ ], _), [ty], [arg] -> + | TOp.ILAsm ([ I_box _ ], _), [ty], [arg] -> let op = mkCallBox cenv.g m ty arg ConvExprPrim cenv env op - | TOp.ILAsm([ I_unbox_any _ ], _), [ty], [arg] -> + | TOp.ILAsm ([ I_unbox_any _ ], _), [ty], [arg] -> let op = mkCallUnbox cenv.g m ty arg ConvExprPrim cenv env op - | TOp.ILAsm([ I_isinst _ ], _), [ty], [arg] -> + | TOp.ILAsm ([ I_isinst _ ], _), [ty], [arg] -> let op = mkCallTypeTest cenv.g m ty arg ConvExprPrim cenv env op @@ -665,56 +670,56 @@ module FSharpExprConvert = let op = mkCallHash cenv.g m ty arg ConvExprPrim cenv env op - | TOp.ILCall(_, _, _, _, _, _, _, mref, _, _, _), [], - [Expr.Op(TOp.ILAsm([ I_ldtoken (ILToken.ILType _) ], _), [ty], _, _)] + | TOp.ILCall (_, _, _, _, _, _, _, mref, _, _, _), [], + [Expr.Op (TOp.ILAsm ([ I_ldtoken (ILToken.ILType _) ], _), [ty], _, _)] when mref.DeclaringTypeRef.Name = "System.Type" && mref.Name = "GetTypeFromHandle" -> let op = mkCallTypeOf cenv.g m ty ConvExprPrim cenv env op - | TOp.ILAsm([ EI_ilzero _ ], _), [ty], _ -> + | TOp.ILAsm ([ EI_ilzero _ ], _), [ty], _ -> E.DefaultValue (ConvType cenv ty) - | TOp.ILAsm([ AI_ldnull; AI_cgt_un ], _), _, [arg] -> + | TOp.ILAsm ([ AI_ldnull; AI_cgt_un ], _), _, [arg] -> let elemTy = tyOfExpr cenv.g arg let nullVal = mkNull m elemTy let op = mkCallNotEqualsOperator cenv.g m elemTy arg nullVal ConvExprPrim cenv env op - | TOp.ILAsm([ I_ldlen; AI_conv DT_I4 ], _), _, [arr] -> + | TOp.ILAsm ([ I_ldlen; AI_conv DT_I4 ], _), _, [arr] -> let arrayTy = tyOfExpr cenv.g arr let elemTy = destArrayTy cenv.g arrayTy let op = mkCallArrayLength cenv.g m elemTy arr ConvExprPrim cenv env op - | TOp.ILAsm([ I_newarr (ILArrayShape [(Some 0, None)], _)], _), [elemTy], xa -> + | TOp.ILAsm ([ I_newarr (ILArrayShape [(Some 0, None)], _)], _), [elemTy], xa -> E.NewArray(ConvType cenv elemTy, ConvExprs cenv env xa) - | TOp.ILAsm([ I_ldelem_any (ILArrayShape [(Some 0, None)], _)], _), [elemTy], [arr; idx1] -> + | TOp.ILAsm ([ I_ldelem_any (ILArrayShape [(Some 0, None)], _)], _), [elemTy], [arr; idx1] -> let op = mkCallArrayGet cenv.g m elemTy arr idx1 ConvExprPrim cenv env op - | TOp.ILAsm([ I_stelem_any (ILArrayShape [(Some 0, None)], _)], _), [elemTy], [arr; idx1; v] -> + | TOp.ILAsm ([ I_stelem_any (ILArrayShape [(Some 0, None)], _)], _), [elemTy], [arr; idx1; v] -> let op = mkCallArraySet cenv.g m elemTy arr idx1 v ConvExprPrim cenv env op - | TOp.ILAsm([ ILUnaryOp unaryOp ], _), _, [arg] -> + | TOp.ILAsm ([ ILUnaryOp unaryOp ], _), _, [arg] -> let ty = tyOfExpr cenv.g arg let op = unaryOp cenv.g m ty arg ConvExprPrim cenv env op - | TOp.ILAsm([ ILBinaryOp binaryOp ], _), _, [arg1;arg2] -> + | TOp.ILAsm ([ ILBinaryOp binaryOp ], _), _, [arg1;arg2] -> let ty = tyOfExpr cenv.g arg1 let op = binaryOp cenv.g m ty arg1 arg2 ConvExprPrim cenv env op - | TOp.ILAsm([ ILConvertOp convertOp1; ILConvertOp convertOp2 ], _), _, [arg] -> + | TOp.ILAsm ([ ILConvertOp convertOp1; ILConvertOp convertOp2 ], _), _, [arg] -> let ty1 = tyOfExpr cenv.g arg let op1 = convertOp1 cenv.g m ty1 arg let ty2 = tyOfExpr cenv.g op1 let op2 = convertOp2 cenv.g m ty2 op1 ConvExprPrim cenv env op2 - | TOp.ILAsm([ ILConvertOp convertOp ], [TType_app (tcref,_)]), _, [arg] -> + | TOp.ILAsm ([ ILConvertOp convertOp ], [TType_app (tcref,_)]), _, [arg] -> let ty = tyOfExpr cenv.g arg let op = if tyconRefEq cenv.g tcref cenv.g.char_tcr @@ -722,11 +727,11 @@ module FSharpExprConvert = else convertOp cenv.g m ty arg ConvExprPrim cenv env op - | TOp.ILAsm([ I_throw ], _), _, [arg1] -> + | TOp.ILAsm ([ I_throw ], _), _, [arg1] -> let raiseExpr = mkCallRaise cenv.g m (tyOfExpr cenv.g expr) arg1 ConvExprPrim cenv env raiseExpr - | TOp.ILAsm(il, _), tyargs, args -> + | TOp.ILAsm (il, _), tyargs, args -> E.ILAsm(sprintf "%+A" il, ConvTypes cenv tyargs, ConvExprs cenv env args) | TOp.ExnConstr tcref, tyargs, args -> @@ -745,7 +750,7 @@ module FSharpExprConvert = let projR = ConvRecdFieldRef cenv rfref E.FSharpFieldSet(None, typR, projR, argR) - | TOp.ExnFieldGet(tcref, i), [], [obj] -> + | TOp.ExnFieldGet (tcref, i), [], [obj] -> let exnc = stripExnEqns tcref let fspec = exnc.TrueInstanceFieldsAsList.[i] let fref = mkRecdFieldRef tcref fspec.Name @@ -753,7 +758,7 @@ module FSharpExprConvert = let objR = ConvExpr cenv env (mkCoerceExpr (obj, mkAppTy tcref [], m, cenv.g.exn_ty)) E.FSharpFieldGet(Some objR, typR, ConvRecdFieldRef cenv fref) - | TOp.ExnFieldSet(tcref, i), [], [obj;e2] -> + | TOp.ExnFieldSet (tcref, i), [], [obj;e2] -> let exnc = stripExnEqns tcref let fspec = exnc.TrueInstanceFieldsAsList.[i] let fref = mkRecdFieldRef tcref fspec.Name @@ -771,44 +776,44 @@ module FSharpExprConvert = // rebuild reraise() and Convert mkReraiseLibCall cenv.g toTy m |> ConvExprPrim cenv env - | TOp.LValueOp(LAddrOf _, vref), [], [] -> + | TOp.LValueOp (LAddrOf _, vref), [], [] -> E.AddressOf(ConvExpr cenv env (exprForValRef m vref)) - | TOp.LValueOp(LByrefSet, vref), [], [e] -> + | TOp.LValueOp (LByrefSet, vref), [], [e] -> E.AddressSet(ConvExpr cenv env (exprForValRef m vref), ConvExpr cenv env e) - | TOp.LValueOp(LSet, vref), [], [e] -> + | TOp.LValueOp (LSet, vref), [], [e] -> E.ValueSet(FSharpMemberOrFunctionOrValue(cenv, vref), ConvExpr cenv env e) - | TOp.LValueOp(LByrefGet, vref), [], [] -> + | TOp.LValueOp (LByrefGet, vref), [], [] -> ConvValRef cenv env m vref | TOp.Array, [ty], xa -> E.NewArray(ConvType cenv ty, ConvExprs cenv env xa) - | TOp.While _, [], [Expr.Lambda(_, _, _, [_], test, _, _);Expr.Lambda(_, _, _, [_], body, _, _)] -> + | TOp.While _, [], [Expr.Lambda (_, _, _, [_], test, _, _);Expr.Lambda (_, _, _, [_], body, _, _)] -> E.WhileLoop(ConvExpr cenv env test, ConvExpr cenv env body) - | TOp.For(_, dir), [], [Expr.Lambda(_, _, _, [_], lim0, _, _); Expr.Lambda(_, _, _, [_], SimpleArrayLoopUpperBound, lm, _); SimpleArrayLoopBody cenv.g (arr, elemTy, body)] -> + | TOp.For (_, dir), [], [Expr.Lambda (_, _, _, [_], lim0, _, _); Expr.Lambda (_, _, _, [_], SimpleArrayLoopUpperBound, lm, _); SimpleArrayLoopBody cenv.g (arr, elemTy, body)] -> let lim1 = let len = mkCallArrayLength cenv.g lm elemTy arr // Array.length arr mkCallSubtractionOperator cenv.g lm cenv.g.int32_ty len (mkOne cenv.g lm) // len - 1 E.FastIntegerForLoop(ConvExpr cenv env lim0, ConvExpr cenv env lim1, ConvExpr cenv env body, dir <> FSharpForLoopDown) - | TOp.For(_, dir), [], [Expr.Lambda(_, _, _, [_], lim0, _, _); Expr.Lambda(_, _, _, [_], lim1, lm, _); body] -> + | TOp.For (_, dir), [], [Expr.Lambda (_, _, _, [_], lim0, _, _); Expr.Lambda (_, _, _, [_], lim1, lm, _); body] -> let lim1 = if dir = CSharpForLoopUp then mkCallSubtractionOperator cenv.g lm cenv.g.int32_ty lim1 (mkOne cenv.g lm) // len - 1 else lim1 E.FastIntegerForLoop(ConvExpr cenv env lim0, ConvExpr cenv env lim1, ConvExpr cenv env body, dir <> FSharpForLoopDown) - | TOp.ILCall(_, _, _, isNewObj, valUseFlags, _isProp, _, ilMethRef, enclTypeArgs, methTypeArgs, _tys), [], callArgs -> + | TOp.ILCall (_, _, _, isNewObj, valUseFlags, _isProp, _, ilMethRef, enclTypeArgs, methTypeArgs, _tys), [], callArgs -> ConvILCall cenv env (isNewObj, valUseFlags, ilMethRef, enclTypeArgs, methTypeArgs, callArgs, m) - | TOp.TryFinally _, [_resty], [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [_], e2, _, _)] -> + | TOp.TryFinally _, [_resty], [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [_], e2, _, _)] -> E.TryFinally(ConvExpr cenv env e1, ConvExpr cenv env e2) - | TOp.TryCatch _, [_resty], [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [vf], ef, _, _); Expr.Lambda(_, _, _, [vh], eh, _, _)] -> + | TOp.TryCatch _, [_resty], [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [vf], ef, _, _); Expr.Lambda (_, _, _, [vh], eh, _, _)] -> let vfR = ConvVal cenv vf let envf = env.BindVal vf let vhR = ConvVal cenv vh @@ -824,7 +829,7 @@ module FSharpExprConvert = let typR = ConvType cenv (mkAppTy tycr tyargs) E.UnionCaseTag(ConvExpr cenv env arg1, typR) - | TOp.TraitCall (TTrait(tys, nm, memFlags, argtys, _rty, _colution)), _, _ -> + | TOp.TraitCall (TTrait(tys, nm, memFlags, argtys, _rty, _solution)), _, _ -> let tysR = ConvTypes cenv tys let tyargsR = ConvTypes cenv tyargs let argtysR = ConvTypes cenv argtys @@ -846,9 +851,9 @@ module FSharpExprConvert = // 'let v = isinst e in .... if nonnull v then ...v .... ' // construct arising out the compilation of pattern matching. We decode these back to the form // 'if istype e then ...unbox e .... ' - // It's bit annoying that pattern matching does this tranformation. Like all premature optimization we pay a + // It's bit annoying that pattern matching does this transformation. Like all premature optimization we pay a // cost here to undo it. - | Expr.Op(TOp.ILAsm([ I_isinst _ ], _), [ty], [e], _) -> + | Expr.Op (TOp.ILAsm ([ I_isinst _ ], _), [ty], [e], _) -> None, env.BindIsInstVal bind.Var (ty, e) // Remove let = from quotation tree @@ -856,11 +861,11 @@ module FSharpExprConvert = None, env.BindSubstVal bind.Var bind.Expr // Remove let = () from quotation tree - | Expr.Const(Const.Unit, _, _) when bind.Var.IsCompilerGenerated && (not bind.Var.IsMutable) -> + | Expr.Const (Const.Unit, _, _) when bind.Var.IsCompilerGenerated && (not bind.Var.IsMutable) -> None, env.BindSubstVal bind.Var bind.Expr // Remove let unionCase = ... from quotation tree - | Expr.Op(TOp.UnionCaseProof _, _, [e], _) when (not bind.Var.IsMutable) -> + | Expr.Op (TOp.UnionCaseProof _, _, [e], _) when (not bind.Var.IsMutable) -> None, env.BindSubstVal bind.Var e | _ -> @@ -912,7 +917,7 @@ module FSharpExprConvert = let ccu = nlr.EnclosingEntity.nlr.Ccu let vName = nlr.ItemKey.PartialKey.LogicalName // this is actually compiled name let findByName = - enclosingEntity.MembersOfFSharpTyconSorted |> List.filter (fun v -> v.CompiledName = vName) + enclosingEntity.MembersOfFSharpTyconSorted |> List.filter (fun v -> (v.CompiledName cenv.g.CompilerGlobalState) = vName) match findByName with | [v] -> makeFSCall isMember v @@ -922,7 +927,7 @@ module FSharpExprConvert = let findModuleMemberByName = enclosingEntity.ModuleOrNamespaceType.AllValsAndMembers |> Seq.filter (fun v -> - v.CompiledName = vName && + (v.CompiledName cenv.g.CompilerGlobalState) = vName && match v.DeclaringEntity with | Parent p -> p.PublicPath = enclosingEntity.PublicPath | _ -> false @@ -938,7 +943,7 @@ module FSharpExprConvert = let name = PrettyNaming.ChopPropertyName vName let findByName = enclosingEntity.ModuleOrNamespaceType.AllValsAndMembers - |> Seq.filter (fun v -> v.CompiledName = name) + |> Seq.filter (fun v -> (v.CompiledName cenv.g.CompilerGlobalState) = name) |> List.ofSeq match findByName with | [ v ] -> @@ -948,7 +953,7 @@ module FSharpExprConvert = else let valR = ConvExpr cenv env callArgs.Head E.ValueSet (m, valR) - | _ -> failwith "Failed to resolve module value unambigously" + | _ -> failwith "Failed to resolve module value unambiguously" else failwith "Failed to resolve module member" | _ -> @@ -956,7 +961,7 @@ module FSharpExprConvert = elif enclosingEntity.IsRecordTycon then if isProp then let name = PrettyNaming.ChopPropertyName vName - let projR = ConvRecdFieldRef cenv (RFRef(tcref, name)) + let projR = ConvRecdFieldRef cenv (RecdFieldRef(tcref, name)) let objR = ConvLValueExpr cenv env callArgs.Head if isPropGet then E.FSharpFieldGet(Some objR, typR, projR) @@ -973,27 +978,27 @@ module FSharpExprConvert = let objR = ConvExpr cenv env callArgs.Head E.UnionCaseTag(objR, typR) elif vName.StartsWithOrdinal("New") then - let name = vName.Substring(3) - let mkR = ConvUnionCaseRef cenv (UCRef(tcref, name)) + let name = vName.Substring 3 + let mkR = ConvUnionCaseRef cenv (UnionCaseRef(tcref, name)) let argsR = ConvExprs cenv env callArgs E.NewUnionCase(typR, mkR, argsR) elif vName.StartsWithOrdinal("Is") then - let name = vName.Substring(2) - let mkR = ConvUnionCaseRef cenv (UCRef(tcref, name)) + let name = vName.Substring 2 + let mkR = ConvUnionCaseRef cenv (UnionCaseRef(tcref, name)) let objR = ConvExpr cenv env callArgs.Head E.UnionCaseTest(objR, typR, mkR) else match subClass with | Some name -> - let ucref = UCRef(tcref, name) - let mkR = ConvUnionCaseRef cenv ucref + let ucref = UnionCaseRef(tcref, name) + let mkR = ConvUnionCaseRef cenv ucref let objR = ConvLValueExpr cenv env callArgs.Head let projR = FSharpField(cenv, ucref, ucref.Index) E.UnionCaseGet(objR, typR, mkR, projR) | _ -> failwith "Failed to recognize union type member" else - let names = enclosingEntity.MembersOfFSharpTyconSorted |> List.map (fun v -> v.CompiledName) |> String.concat ", " + let names = enclosingEntity.MembersOfFSharpTyconSorted |> List.map (fun v -> v.CompiledName cenv.g.CompilerGlobalState) |> String.concat ", " failwithf "Member '%s' not found in type %s, found: %s" vName enclosingEntity.DisplayName names | _ -> // member is overloaded match nlr.ItemKey.TypeForLinkage with @@ -1040,8 +1045,8 @@ module FSharpExprConvert = let isCtor = (ilMethRef.Name = ".ctor") let isStatic = isCtor || ilMethRef.CallingConv.IsStatic let scoref = ilMethRef.DeclaringTypeRef.Scope - let typars1 = tcref.Typars(m) - let typars2 = [ 1 .. ilMethRef.GenericArity ] |> List.map (fun _ -> NewRigidTypar "T" m) + let typars1 = tcref.Typars m + let typars2 = [ 1 .. ilMethRef.GenericArity ] |> List.map (fun _ -> Construct.NewRigidTypar "T" m) let tinst1 = typars1 |> generalizeTypars let tinst2 = typars2 |> generalizeTypars // TODO: this will not work for curried methods in F# classes. @@ -1074,7 +1079,7 @@ module FSharpExprConvert = with e -> failwithf "An IL call to '%s' could not be resolved: %s" (ilMethRef.ToString()) e.Message - and ConvObjectModelCallLinear cenv env (isNewObj, v: FSharpMemberOrFunctionOrValue, enclTyArgs, methTyArgs, callArgs) contf = + and ConvObjectModelCallLinear cenv env (isNewObj, v: FSharpMemberOrFunctionOrValue, enclTyArgs, methTyArgs, callArgs) contF = let enclTyArgsR = ConvTypes cenv enclTyArgs let methTyArgsR = ConvTypes cenv methTyArgs let obj, callArgs = @@ -1086,7 +1091,7 @@ module FSharpExprConvert = None, callArgs let objR = Option.map (ConvLValueExpr cenv env) obj // tailcall - ConvExprsLinear cenv env callArgs (contf << fun callArgsR -> + ConvExprsLinear cenv env callArgs (contF << fun callArgsR -> if isNewObj then E.NewObject(v, enclTyArgsR, callArgsR) else @@ -1095,21 +1100,21 @@ module FSharpExprConvert = and ConvExprs cenv env args = List.map (ConvExpr cenv env) args - // Process a list of expressions in a tail-recursive way. Identical to "ConvExprs" but the result is eventually passed to contf. - and ConvExprsLinear cenv env args contf = + // Process a list of expressions in a tail-recursive way. Identical to "ConvExprs" but the result is eventually passed to contF. + and ConvExprsLinear cenv env args contF = match args with - | [] -> contf [] - | [arg] -> ConvExprLinear cenv env arg (fun argR -> contf [argR]) - | arg::rest -> ConvExprLinear cenv env arg (fun argR -> ConvExprsLinear cenv env rest (fun restR -> contf (argR :: restR))) + | [] -> contF [] + | [arg] -> ConvExprLinear cenv env arg (fun argR -> contF [argR]) + | arg :: rest -> ConvExprLinear cenv env arg (fun argR -> ConvExprsLinear cenv env rest (fun restR -> contF (argR :: restR))) - and ConvTargetsLinear cenv env tgs contf = + and ConvTargetsLinear cenv env tgs contF = match tgs with - | [] -> contf [] - | TTarget(vars, rhs, _)::rest -> + | [] -> contF [] + | TTarget(vars, rhs, _) :: rest -> let varsR = (List.rev vars) |> List.map (ConvVal cenv) ConvExprLinear cenv env rhs (fun targetR -> ConvTargetsLinear cenv env rest (fun restR -> - contf ((varsR, targetR) :: restR))) + contF ((varsR, targetR) :: restR))) and ConvValRef cenv env m (vref: ValRef) = let v = vref.Deref @@ -1193,7 +1198,7 @@ module FSharpExprConvert = | DecisionTreeTest.IsNull -> // Decompile cached isinst tests match e1 with - | Expr.Val(vref, _, _) when env.isinstVals.ContainsVal vref.Deref -> + | Expr.Val (vref, _, _) when env.isinstVals.ContainsVal vref.Deref -> let (ty, e) = env.isinstVals.[vref.Deref] let tyR = ConvType cenv ty let eR = ConvExpr cenv env e @@ -1208,7 +1213,8 @@ module FSharpExprConvert = let e1R = ConvExpr cenv env e1 E.IfThenElse (E.TypeTest (ConvType cenv tgty, e1R) |> Mk cenv m cenv.g.bool_ty, ConvDecisionTree cenv env dtreeRetTy dtree m, acc) | DecisionTreeTest.ActivePatternCase _ -> wfail("unexpected Test.ActivePatternCase test in quoted expression", m) - | DecisionTreeTest.ArrayLength _ -> wfail("FSharp.Compiler.Service cannot yet return array pattern matching", m)) + | DecisionTreeTest.ArrayLength _ -> wfail("FSharp.Compiler.Service cannot yet return array pattern matching", m) + | DecisionTreeTest.Error m -> wfail("error recovery", m)) | TDSuccess (args, n) -> // TAST stores pattern bindings in reverse order for some reason @@ -1221,7 +1227,7 @@ module FSharpExprConvert = // The binding may be a compiler-generated binding that gets removed in the quotation presentation match ConvLetBind cenv env bind with | None, env -> ConvDecisionTreePrim cenv env dtreeRetTy rest - | Some(bindR), env -> E.Let(bindR, ConvDecisionTree cenv env dtreeRetTy rest bind.Var.Range) + | Some bindR, env -> E.Let(bindR, ConvDecisionTree cenv env dtreeRetTy rest bind.Var.Range) /// Wrap the conversion in a function to make it on-demand. Any pattern matching on the FSharpExpr will /// force the evaluation of the entire conversion process eagerly. @@ -1244,7 +1250,7 @@ and FSharpImplementationFileDeclaration = | InitAction of FSharpExpr and FSharpImplementationFileContents(cenv, mimpl) = - let (TImplFile(qname, _pragmas, ModuleOrNamespaceExprWithSig(_, mdef, _), hasExplicitEntryPoint, isScript, _anonRecdTypes)) = mimpl + let (TImplFile (qname, _pragmas, ModuleOrNamespaceExprWithSig(_, mdef, _), hasExplicitEntryPoint, isScript, _anonRecdTypes)) = mimpl let rec getDecls2 (ModuleOrNamespaceExprWithSig(_mty, def, _m)) = getDecls def and getBind (bind: Binding) = let v = bind.Var @@ -1270,15 +1276,15 @@ and FSharpImplementationFileContents(cenv, mimpl) = | ModuleOrNamespaceBinding.Module(mspec, def) -> let entity = FSharpEntity(cenv, mkLocalEntityRef mspec) yield FSharpImplementationFileDeclaration.Entity (entity, getDecls def) - | ModuleOrNamespaceBinding.Binding(bind) -> + | ModuleOrNamespaceBinding.Binding bind -> yield getBind bind ] - | TMAbstract(mexpr) -> getDecls2 mexpr + | TMAbstract mexpr -> getDecls2 mexpr | TMDefLet(bind, _m) -> [ yield getBind bind ] | TMDefDo(expr, _m) -> [ let expr = FSharpExprConvert.ConvExprOnDemand cenv ExprTranslationEnv.Empty expr - yield FSharpImplementationFileDeclaration.InitAction(expr) ] - | TMDefs(mdefs) -> + yield FSharpImplementationFileDeclaration.InitAction expr ] + | TMDefs mdefs -> [ for mdef in mdefs do yield! getDecls mdef ] member __.QualifiedName = qname.Text @@ -1289,7 +1295,7 @@ and FSharpImplementationFileContents(cenv, mimpl) = module BasicPatterns = - let (|Value|_|) (e: FSharpExpr) = match e.E with E.Value (v) -> Some (v) | _ -> None + let (|Value|_|) (e: FSharpExpr) = match e.E with E.Value v -> Some v | _ -> None let (|Const|_|) (e: FSharpExpr) = match e.E with E.Const (v, ty) -> Some (v, ty) | _ -> None let (|TypeLambda|_|) (e: FSharpExpr) = match e.E with E.TypeLambda (v, e) -> Some (v, e) | _ -> None let (|Lambda|_|) (e: FSharpExpr) = match e.E with E.Lambda (v, e) -> Some (v, e) | _ -> None @@ -1312,7 +1318,7 @@ module BasicPatterns = let (|UnionCaseTest|_|) (e: FSharpExpr) = match e.E with E.UnionCaseTest (a, b, c) -> Some (a, b, c) | _ -> None let (|NewArray|_|) (e: FSharpExpr) = match e.E with E.NewArray (a, b) -> Some (a, b) | _ -> None let (|Coerce|_|) (e: FSharpExpr) = match e.E with E.Coerce (a, b) -> Some (a, b) | _ -> None - let (|Quote|_|) (e: FSharpExpr) = match e.E with E.Quote (a) -> Some (a) | _ -> None + let (|Quote|_|) (e: FSharpExpr) = match e.E with E.Quote a -> Some a | _ -> None let (|TypeTest|_|) (e: FSharpExpr) = match e.E with E.TypeTest (a, b) -> Some (a, b) | _ -> None let (|Sequential|_|) (e: FSharpExpr) = match e.E with E.Sequential (a, b) -> Some (a, b) | _ -> None let (|FastIntegerForLoop|_|) (e: FSharpExpr) = match e.E with E.FastIntegerForLoop (a, b, c, d) -> Some (a, b, c, d) | _ -> None @@ -1320,12 +1326,12 @@ module BasicPatterns = let (|TryFinally|_|) (e: FSharpExpr) = match e.E with E.TryFinally (a, b) -> Some (a, b) | _ -> None let (|TryWith|_|) (e: FSharpExpr) = match e.E with E.TryWith (a, b, c, d, e) -> Some (a, b, c, d, e) | _ -> None let (|NewDelegate|_|) (e: FSharpExpr) = match e.E with E.NewDelegate (ty, e) -> Some (ty, e) | _ -> None - let (|DefaultValue|_|) (e: FSharpExpr) = match e.E with E.DefaultValue (ty) -> Some (ty) | _ -> None + let (|DefaultValue|_|) (e: FSharpExpr) = match e.E with E.DefaultValue ty -> Some ty | _ -> None let (|AddressSet|_|) (e: FSharpExpr) = match e.E with E.AddressSet (a, b) -> Some (a, b) | _ -> None let (|ValueSet|_|) (e: FSharpExpr) = match e.E with E.ValueSet (a, b) -> Some (a, b) | _ -> None - let (|AddressOf|_|) (e: FSharpExpr) = match e.E with E.AddressOf (a) -> Some (a) | _ -> None - let (|ThisValue|_|) (e: FSharpExpr) = match e.E with E.ThisValue (a) -> Some (a) | _ -> None - let (|BaseValue|_|) (e: FSharpExpr) = match e.E with E.BaseValue (a) -> Some (a) | _ -> None + let (|AddressOf|_|) (e: FSharpExpr) = match e.E with E.AddressOf a -> Some a | _ -> None + let (|ThisValue|_|) (e: FSharpExpr) = match e.E with E.ThisValue a -> Some a | _ -> None + let (|BaseValue|_|) (e: FSharpExpr) = match e.E with E.BaseValue a -> Some a | _ -> None let (|ILAsm|_|) (e: FSharpExpr) = match e.E with E.ILAsm (a, b, c) -> Some (a, b, c) | _ -> None let (|ILFieldGet|_|) (e: FSharpExpr) = match e.E with E.ILFieldGet (a, b, c) -> Some (a, b, c) | _ -> None let (|ILFieldSet|_|) (e: FSharpExpr) = match e.E with E.ILFieldSet (a, b, c, d) -> Some (a, b, c, d) | _ -> None diff --git a/src/fcs-fable/src/fsharp/symbols/Exprs.fsi b/src/fcs-fable/src/fsharp/symbols/Exprs.fsi index 72f8746481..f1b2ea1a9f 100644 --- a/src/fcs-fable/src/fsharp/symbols/Exprs.fsi +++ b/src/fcs-fable/src/fsharp/symbols/Exprs.fsi @@ -2,12 +2,11 @@ namespace FSharp.Compiler.SourceCodeServices -open FSharp.Compiler -open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Tast -open FSharp.Compiler.Range open FSharp.Compiler.CompileOps - +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypedTree /// Represents the definitional contents of an assembly, as seen by the F# language type public FSharpAssemblyContents = @@ -92,7 +91,7 @@ module public BasicPatterns = /// Matches expressions which are type abstractions val (|TypeLambda|_|) : FSharpExpr -> (FSharpGenericParameter list * FSharpExpr) option - /// Matches expressions with a decision expression, each branch of which ends in DecisionTreeSuccess pasing control and values to one of the targets. + /// Matches expressions with a decision expression, each branch of which ends in DecisionTreeSuccess passing control and values to one of the targets. val (|DecisionTree|_|) : FSharpExpr -> (FSharpExpr * (FSharpMemberOrFunctionOrValue list * FSharpExpr) list) option /// Special expressions at the end of a conditional decision structure in the decision expression node of a DecisionTree . @@ -220,5 +219,5 @@ module public BasicPatterns = val (|ObjectExpr|_|) : FSharpExpr -> (FSharpType * FSharpExpr * FSharpObjectExprOverride list * (FSharpType * FSharpObjectExprOverride list) list) option /// Matches expressions for an unresolved call to a trait - val (|TraitCall|_|) : FSharpExpr -> (FSharpType list * string * Ast.MemberFlags * FSharpType list * FSharpType list * FSharpExpr list) option + val (|TraitCall|_|) : FSharpExpr -> (FSharpType list * string * MemberFlags * FSharpType list * FSharpType list * FSharpExpr list) option diff --git a/src/fcs-fable/src/fsharp/symbols/SymbolHelpers.fs b/src/fcs-fable/src/fsharp/symbols/SymbolHelpers.fs index bac181cf3f..1be28fe65b 100644 --- a/src/fcs-fable/src/fsharp/symbols/SymbolHelpers.fs +++ b/src/fcs-fable/src/fsharp/symbols/SymbolHelpers.fs @@ -8,29 +8,30 @@ namespace FSharp.Compiler.SourceCodeServices open System -open System.Collections.Generic open System.IO -open Microsoft.FSharp.Core.Printf +open FSharp.Core.Printf open FSharp.Compiler open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Diagnostics open FSharp.Compiler.AccessibilityLogic -open FSharp.Compiler.Ast +open FSharp.Compiler.CompileOps open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.InfoReader +open FSharp.Compiler.Infos open FSharp.Compiler.Layout open FSharp.Compiler.Layout.TaggedTextOps open FSharp.Compiler.Lib +open FSharp.Compiler.NameResolution open FSharp.Compiler.PrettyNaming open FSharp.Compiler.Range -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Infos -open FSharp.Compiler.NameResolution -open FSharp.Compiler.InfoReader -open FSharp.Compiler.CompileOps +open FSharp.Compiler.XmlDoc module EnvMisc2 = let maxMembers = GetEnvInteger "FCS_MaxMembersInQuickInfo" 10 @@ -43,36 +44,57 @@ type FSharpErrorSeverity = | Warning | Error -type FSharpErrorInfo(fileName, s: pos, e: pos, severity: FSharpErrorSeverity, message: string, subcategory: string, errorNum: int) = - member __.StartLine = Line.toZ s.Line - member __.StartLineAlternate = s.Line - member __.EndLine = Line.toZ e.Line - member __.EndLineAlternate = e.Line - member __.StartColumn = s.Column - member __.EndColumn = e.Column - member __.Severity = severity - member __.Message = message - member __.Subcategory = subcategory - member __.FileName = fileName - member __.ErrorNumber = errorNum - member __.WithStart(newStart) = FSharpErrorInfo(fileName, newStart, e, severity, message, subcategory, errorNum) - member __.WithEnd(newEnd) = FSharpErrorInfo(fileName, s, newEnd, severity, message, subcategory, errorNum) - override __.ToString()= sprintf "%s (%d,%d)-(%d,%d) %s %s %s" fileName (int s.Line) (s.Column + 1) (int e.Line) (e.Column + 1) subcategory (if severity=FSharpErrorSeverity.Warning then "warning" else "error") message - +module FSharpErrorInfo = + let [] ObsoleteMessage = "Use FSharpErrorInfo.Range. This API will be removed in a future update." + +type FSharpErrorInfo(m: range, severity: FSharpErrorSeverity, message: string, subcategory: string, errorNum: int) = + member _.Range = m + member _.Severity = severity + member _.Message = message + member _.Subcategory = subcategory + member _.ErrorNumber = errorNum + + [] member _.Start = m.Start + [] member _.End = m.End + + [] member _.StartLine = Line.toZ m.Start.Line + [] member _.StartLineAlternate = m.Start.Line + [] member _.EndLine = Line.toZ m.End.Line + [] member _.EndLineAlternate = m.End.Line + [] member _.StartColumn = m.Start.Column + [] member _.EndColumn = m.End.Column + [] member _.FileName = m.FileName + + member _.WithStart newStart = + let m = mkFileIndexRange m.FileIndex newStart m.End + FSharpErrorInfo(m, severity, message, subcategory, errorNum) + + member _.WithEnd newEnd = + let m = mkFileIndexRange m.FileIndex m.Start newEnd + FSharpErrorInfo(m, severity, message, subcategory, errorNum) + + override _.ToString() = + let fileName = m.FileName + let s = m.Start + let e = m.End + let severity = if severity=FSharpErrorSeverity.Warning then "warning" else "error" + sprintf "%s (%d,%d)-(%d,%d) %s %s %s" fileName s.Line (s.Column + 1) e.Line (e.Column + 1) subcategory severity message + /// Decompose a warning or error into parts: position, severity, message, error number - static member CreateFromException(exn, isError, fallbackRange: range) = + static member CreateFromException(exn, isError, fallbackRange: range, suggestNames: bool) = let m = match GetRangeOfDiagnostic exn with Some m -> m | None -> fallbackRange - let msg = bufs (fun buf -> OutputPhasedDiagnostic buf exn false) + let severity = if isError then FSharpErrorSeverity.Error else FSharpErrorSeverity.Warning + let msg = bufs (fun buf -> OutputPhasedDiagnostic buf exn false suggestNames) let errorNum = GetDiagnosticNumber exn - FSharpErrorInfo(m.FileName, m.Start, m.End, (if isError then FSharpErrorSeverity.Error else FSharpErrorSeverity.Warning), msg, exn.Subcategory(), errorNum) - + FSharpErrorInfo(m, severity, msg, exn.Subcategory(), errorNum) + /// Decompose a warning or error into parts: position, severity, message, error number - static member CreateFromExceptionAndAdjustEof(exn, isError, fallbackRange: range, (linesCount: int, lastLength: int)) = - let r = FSharpErrorInfo.CreateFromException(exn, isError, fallbackRange) - - // Adjust to make sure that errors reported at Eof are shown at the linesCount - let startline, schange = min (r.StartLineAlternate, false) (linesCount, true) - let endline, echange = min (r.EndLineAlternate, false) (linesCount, true) + static member CreateFromExceptionAndAdjustEof(exn, isError, fallbackRange: range, (linesCount: int, lastLength: int), suggestNames: bool) = + let r = FSharpErrorInfo.CreateFromException(exn, isError, fallbackRange, suggestNames) + + // Adjust to make sure that errors reported at Eof are shown at the linesCount + let startline, schange = min (r.Range.StartLine, false) (linesCount, true) + let endline, echange = min (r.Range.EndLine, false) (linesCount, true) if not (schange || echange) then r else @@ -90,7 +112,7 @@ type ErrorScope() = PushErrorLoggerPhaseUntilUnwind (fun _oldLogger -> { new ErrorLogger("ErrorScope") with member x.DiagnosticSink(exn, isError) = - let err = FSharpErrorInfo.CreateFromException(exn, isError, range.Zero) + let err = FSharpErrorInfo.CreateFromException(exn, isError, range.Zero, false) errors <- err :: errors if isError && firstError.IsNone then firstError <- Some err.Message @@ -117,7 +139,7 @@ type ErrorScope() = /// may hit internal compiler failures. /// /// In some calling cases, we get a chance to report the error as part of user text. For example - /// if there is a "msising assembly" error while formatting the text of the description of an + /// if there is a "missing assembly" error while formatting the text of the description of an /// autocomplete, then the error message is shown in replacement of the text (rather than crashing Visual /// Studio, or swallowing the exception completely) static member Protect<'a> (m: range) (f: unit->'a) (err: string->'a): 'a = @@ -173,15 +195,16 @@ type CompilationGlobalsScope(errorLogger: ErrorLogger, phase: BuildPhase) = unwindEL.Dispose() module ErrorHelpers = - let ReportError (options, allErrors, mainInputFileName, fileInfo, (exn, sev)) = + let ReportError (options, allErrors, mainInputFileName, fileInfo, (exn, sev), suggestNames) = [ let isError = (sev = FSharpErrorSeverity.Error) || ReportWarningAsError options exn if (isError || ReportWarning options exn) then let oneError exn = [ // We use the first line of the file as a fallbackRange for reporting unexpected errors. // Not ideal, but it's hard to see what else to do. let fallbackRange = rangeN mainInputFileName 1 - let ei = FSharpErrorInfo.CreateFromExceptionAndAdjustEof (exn, isError, fallbackRange, fileInfo) - if allErrors || (ei.FileName = mainInputFileName) || (ei.FileName = TcGlobals.DummyFileNameForRangesWithoutASpecificLocation) then + let ei = FSharpErrorInfo.CreateFromExceptionAndAdjustEof (exn, isError, fallbackRange, fileInfo, suggestNames) + let fileName = ei.Range.FileName + if allErrors || fileName = mainInputFileName || fileName = TcGlobals.DummyFileNameForRangesWithoutASpecificLocation then yield ei ] let mainError, relatedErrors = SplitRelatedDiagnostics exn @@ -189,10 +212,10 @@ module ErrorHelpers = for e in relatedErrors do yield! oneError e ] - let CreateErrorInfos (options, allErrors, mainInputFileName, errors) = + let CreateErrorInfos (options, allErrors, mainInputFileName, errors, suggestNames) = let fileInfo = (Int32.MaxValue, Int32.MaxValue) [| for (exn, isError) in errors do - yield! ReportError (options, allErrors, mainInputFileName, fileInfo, (exn, isError)) |] + yield! ReportError (options, allErrors, mainInputFileName, fileInfo, (exn, isError), suggestNames) |] //---------------------------------------------------------------------------- @@ -212,7 +235,7 @@ type FSharpXmlDoc = type FSharpToolTipElementData<'T> = { MainDescription: 'T XmlDoc: FSharpXmlDoc - /// typar insantiation text, to go after xml + /// typar instantiation text, to go after xml TypeMapping: 'T list Remarks: 'T option ParamName : string option } @@ -253,17 +276,17 @@ module Tooltips = match tooltip with | FSharpStructuredToolTipElement.None -> FSharpToolTipElement.None - | FSharpStructuredToolTipElement.Group(l) -> + | FSharpStructuredToolTipElement.Group l -> FSharpToolTipElement.Group(l |> List.map(fun x -> { MainDescription=showL x.MainDescription XmlDoc=x.XmlDoc TypeMapping=List.map showL x.TypeMapping ParamName=x.ParamName Remarks= Option.map showL x.Remarks })) - | FSharpStructuredToolTipElement.CompositionError(text) -> - FSharpToolTipElement.CompositionError(text) + | FSharpStructuredToolTipElement.CompositionError text -> + FSharpToolTipElement.CompositionError text - let ToFSharpToolTipText (FSharpStructuredToolTipText.FSharpToolTipText(text)) = + let ToFSharpToolTipText (FSharpStructuredToolTipText.FSharpToolTipText text) = FSharpToolTipText(List.map ToFSharpToolTipElement text) let Map f a = async.Bind(a, f >> async.Return) @@ -324,14 +347,14 @@ module internal SymbolHelpers = let rangeOfPropInfo preferFlag (pinfo: PropInfo) = match pinfo with #if !NO_EXTENSIONTYPING - | ProvidedProp(_, pi, _) -> ComputeDefinitionLocationOfProvidedItem pi + | ProvidedProp(_, pi, _) -> Construct.ComputeDefinitionLocationOfProvidedItem pi #endif | _ -> pinfo.ArbitraryValRef |> Option.map (rangeOfValRef preferFlag) let rangeOfMethInfo (g: TcGlobals) preferFlag (minfo: MethInfo) = match minfo with #if !NO_EXTENSIONTYPING - | ProvidedMeth(_, mi, _, _) -> ComputeDefinitionLocationOfProvidedItem mi + | ProvidedMeth(_, mi, _, _) -> Construct.ComputeDefinitionLocationOfProvidedItem mi #endif | DefaultStructCtor(_, AppTy g (tcref, _)) -> Some(rangeOfEntityRef preferFlag tcref) | _ -> minfo.ArbitraryValRef |> Option.map (rangeOfValRef preferFlag) @@ -339,7 +362,7 @@ module internal SymbolHelpers = let rangeOfEventInfo preferFlag (einfo: EventInfo) = match einfo with #if !NO_EXTENSIONTYPING - | ProvidedEvent (_, ei, _) -> ComputeDefinitionLocationOfProvidedItem ei + | ProvidedEvent (_, ei, _) -> Construct.ComputeDefinitionLocationOfProvidedItem ei #endif | _ -> einfo.ArbitraryValRef |> Option.map (rangeOfValRef preferFlag) @@ -349,11 +372,14 @@ module internal SymbolHelpers = | Some false -> ucinfo.UnionCase.DefinitionRange | Some true -> ucinfo.UnionCase.SigRange - let rangeOfRecdFieldInfo preferFlag (rfinfo: RecdFieldInfo) = - match preferFlag with - | None -> rfinfo.RecdField.Range - | Some false -> rfinfo.RecdField.DefinitionRange - | Some true -> rfinfo.RecdField.SigRange + let rangeOfRecdField preferFlag (rField: RecdField) = + match preferFlag with + | None -> rField.Range + | Some false -> rField.DefinitionRange + | Some true -> rField.SigRange + + let rangeOfRecdFieldInfo preferFlag (rfinfo: RecdFieldInfo) = + rangeOfRecdField preferFlag rfinfo.RecdField let rec rangeOfItem (g: TcGlobals) preferFlag d = match d with @@ -363,13 +389,14 @@ module internal SymbolHelpers = | Item.ExnCase tcref -> Some tcref.Range | Item.AnonRecdField (_,_,_,m) -> Some m | Item.RecdField rfinfo -> Some (rangeOfRecdFieldInfo preferFlag rfinfo) + | Item.UnionCaseField (UnionCaseInfo (_, ucref), fieldIndex) -> Some (rangeOfRecdField preferFlag (ucref.FieldByIndex(fieldIndex))) | Item.Event einfo -> rangeOfEventInfo preferFlag einfo | Item.ILField _ -> None | Item.Property(_, pinfos) -> rangeOfPropInfo preferFlag pinfos.Head | Item.Types(_, tys) -> tys |> List.tryPick (tryNiceEntityRefOfTyOption >> Option.map (rangeOfEntityRef preferFlag)) | Item.CustomOperation (_, _, Some minfo) -> rangeOfMethInfo g preferFlag minfo | Item.TypeVar (_, tp) -> Some tp.Range - | Item.ModuleOrNamespaces(modrefs) -> modrefs |> List.tryPick (rangeOfEntityRef preferFlag >> Some) + | Item.ModuleOrNamespaces modrefs -> modrefs |> List.tryPick (rangeOfEntityRef preferFlag >> Some) | Item.MethodGroup(_, minfos, _) | Item.CtorGroup(_, minfos) -> minfos |> List.tryPick (rangeOfMethInfo g preferFlag) | Item.ActivePatternResult(APInfo _, _, _, m) -> Some m @@ -406,6 +433,7 @@ module internal SymbolHelpers = | Item.ActivePatternCase apref -> ccuOfValRef apref.ActivePatternVal | Item.ExnCase tcref -> computeCcuOfTyconRef tcref | Item.RecdField rfinfo -> computeCcuOfTyconRef rfinfo.RecdFieldRef.TyconRef + | Item.UnionCaseField (ucinfo, _) -> computeCcuOfTyconRef ucinfo.TyconRef | Item.Event einfo -> einfo.DeclaringTyconRef |> computeCcuOfTyconRef | Item.ILField finfo -> finfo.DeclaringTyconRef |> computeCcuOfTyconRef | Item.Property(_, pinfos) -> @@ -424,8 +452,8 @@ module internal SymbolHelpers = | Item.ArgName (_, _, Some (ArgumentContainer.Type eref)) -> computeCcuOfTyconRef eref - | Item.ModuleOrNamespaces(erefs) - | Item.UnqualifiedType(erefs) -> erefs |> List.tryPick computeCcuOfTyconRef + | Item.ModuleOrNamespaces erefs + | Item.UnqualifiedType erefs -> erefs |> List.tryPick computeCcuOfTyconRef | Item.SetterArg (_, item) -> ccuOfItem g item | Item.AnonRecdField (info, _, _, _) -> Some info.Assembly @@ -479,7 +507,7 @@ module internal SymbolHelpers = | ERefLocal _ -> None | ERefNonLocal nlref -> // Generalize to get a formal signature - let formalTypars = tcref.Typars(m) + let formalTypars = tcref.Typars m let formalTypeInst = generalizeTypars formalTypars let ty = TType_app(tcref, formalTypeInst) if isILAppTy g ty then @@ -489,7 +517,7 @@ module internal SymbolHelpers = let mkXmlComment thing = match thing with - | Some (Some(fileName), xmlDocSig) -> FSharpXmlDoc.XmlDocFileSignature(fileName, xmlDocSig) + | Some (Some fileName, xmlDocSig) -> FSharpXmlDoc.XmlDocFileSignature(fileName, xmlDocSig) | _ -> FSharpXmlDoc.None let GetXmlDocSigOfEntityRef infoReader m (eref: EntityRef) = @@ -624,7 +652,7 @@ module internal SymbolHelpers = | Item.ModuleOrNamespaces(modref :: _) -> mkXmlComment (GetXmlDocSigOfEntityRef infoReader m modref) | Item.Property(_, (pinfo :: _)) -> mkXmlComment (GetXmlDocSigOfProp infoReader m pinfo) - | Item.Event(einfo) -> mkXmlComment (GetXmlDocSigOfEvent infoReader m einfo) + | Item.Event einfo -> mkXmlComment (GetXmlDocSigOfEvent infoReader m einfo) | Item.MethodGroup(_, minfo :: _, _) -> mkXmlComment (GetXmlDocSigOfMethInfo infoReader m minfo) | Item.CtorGroup(_, minfo :: _) -> mkXmlComment (GetXmlDocSigOfMethInfo infoReader m minfo) @@ -632,7 +660,7 @@ module internal SymbolHelpers = match argContainer with | ArgumentContainer.Method minfo -> mkXmlComment (GetXmlDocSigOfMethInfo infoReader m minfo) | ArgumentContainer.Type tcref -> mkXmlComment (GetXmlDocSigOfEntityRef infoReader m tcref) - | ArgumentContainer.UnionCase ucinfo -> mkXmlComment (GetXmlDocSigOfUnionCaseInfo ucinfo) + | Item.UnionCaseField (ucinfo, _) -> mkXmlComment (GetXmlDocSigOfUnionCaseInfo ucinfo) | _ -> FSharpXmlDoc.None /// Produce an XmlComment with a signature or raw text, given the F# comment and the item @@ -678,7 +706,7 @@ module internal SymbolHelpers = let tpsL = FormatTyparMapping denv prettyTyparInst FSharpToolTipElementData<_>.Create(layout, xml, tpsL) ] - FSharpStructuredToolTipElement.Group(layouts) + FSharpStructuredToolTipElement.Group layouts let pubpathOfValRef (v: ValRef) = v.PublicPath @@ -725,9 +753,9 @@ module internal SymbolHelpers = // In this case just bail out and assume items are not equal protectAssemblyExploration false (fun () -> let equalHeadTypes(ty1, ty2) = - match tryDestAppTy g ty1 with + match tryTcrefOfAppTy g ty1 with | ValueSome tcref1 -> - match tryDestAppTy g ty2 with + match tryTcrefOfAppTy g ty2 with | ValueSome tcref2 -> tyconRefEq g tcref1 tcref2 | _ -> typeEquiv g ty1 ty2 | _ -> typeEquiv g ty1 ty2 @@ -736,15 +764,15 @@ module internal SymbolHelpers = // Much of this logic is already covered by 'ItemsAreEffectivelyEqual' match item1, item2 with - | Item.DelegateCtor(ty1), Item.DelegateCtor(ty2) -> equalHeadTypes(ty1, ty2) + | Item.DelegateCtor ty1, Item.DelegateCtor ty2 -> equalHeadTypes(ty1, ty2) | Item.Types(dn1, [ty1]), Item.Types(dn2, [ty2]) -> // Bug 4403: We need to compare names as well, because 'int' and 'Int32' are physically the same type, but we want to show both dn1 = dn2 && equalHeadTypes(ty1, ty2) // Prefer a type to a DefaultStructCtor, a DelegateCtor and a FakeInterfaceCtor - | ItemWhereTypIsPreferred(ty1), ItemWhereTypIsPreferred(ty2) -> equalHeadTypes(ty1, ty2) + | ItemWhereTypIsPreferred ty1, ItemWhereTypIsPreferred ty2 -> equalHeadTypes(ty1, ty2) - | Item.ExnCase(tcref1), Item.ExnCase(tcref2) -> tyconRefEq g tcref1 tcref2 + | Item.ExnCase tcref1, Item.ExnCase tcref2 -> tyconRefEq g tcref1 tcref2 | Item.ILField(ILFieldInfo(_, fld1)), Item.ILField(ILFieldInfo(_, fld2)) -> fld1 === fld2 // reference equality on the object identity of the AbstractIL metadata blobs for the fields | Item.CustomOperation (_, _, Some minfo1), Item.CustomOperation (_, _, Some minfo2) -> @@ -752,7 +780,7 @@ module internal SymbolHelpers = | Item.TypeVar (nm1, tp1), Item.TypeVar (nm2, tp2) -> (nm1 = nm2) && typarRefEq tp1 tp2 | Item.ModuleOrNamespaces(modref1 :: _), Item.ModuleOrNamespaces(modref2 :: _) -> fullDisplayTextOfModRef modref1 = fullDisplayTextOfModRef modref2 - | Item.SetterArg(id1, _), Item.SetterArg(id2, _) -> (id1.idRange, id1.idText) = (id2.idRange, id2.idText) + | Item.SetterArg(id1, _), Item.SetterArg(id2, _) -> Range.equals id1.idRange id2.idRange && id1.idText = id2.idText | Item.MethodGroup(_, meths1, _), Item.MethodGroup(_, meths2, _) -> Seq.zip meths1 meths2 |> Seq.forall (fun (minfo1, minfo2) -> MethInfo.MethInfosUseIdenticalDefinitions minfo1 minfo2) @@ -762,18 +790,18 @@ module internal SymbolHelpers = idx1 = idx2 && valRefEq g vref1 vref2 | Item.UnionCase(UnionCaseInfo(_, ur1), _), Item.UnionCase(UnionCaseInfo(_, ur2), _) -> g.unionCaseRefEq ur1 ur2 - | Item.RecdField(RecdFieldInfo(_, RFRef(tcref1, n1))), Item.RecdField(RecdFieldInfo(_, RFRef(tcref2, n2))) -> + | Item.RecdField(RecdFieldInfo(_, RecdFieldRef(tcref1, n1))), Item.RecdField(RecdFieldInfo(_, RecdFieldRef(tcref2, n2))) -> (tyconRefEq g tcref1 tcref2) && (n1 = n2) // there is no direct function as in the previous case | Item.Property(_, pi1s), Item.Property(_, pi2s) -> List.zip pi1s pi2s |> List.forall(fun (pi1, pi2) -> PropInfo.PropInfosUseIdenticalDefinitions pi1 pi2) - | Item.Event(evt1), Item.Event(evt2) -> - EventInfo.EventInfosUseIdenticalDefintions evt1 evt2 + | Item.Event evt1, Item.Event evt2 -> + EventInfo.EventInfosUseIdenticalDefinitions evt1 evt2 | Item.AnonRecdField(anon1, _, i1, _), Item.AnonRecdField(anon2, _, i2, _) -> - Tastops.anonInfoEquiv anon1 anon2 && i1 = i2 + anonInfoEquiv anon1 anon2 && i1 = i2 | Item.CtorGroup(_, meths1), Item.CtorGroup(_, meths2) -> List.zip meths1 meths2 |> List.forall (fun (minfo1, minfo2) -> MethInfo.MethInfosUseIdenticalDefinitions minfo1 minfo2) - | Item.UnqualifiedType(tcRefs1), Item.UnqualifiedType(tcRefs2) -> + | Item.UnqualifiedType tcRefs1, Item.UnqualifiedType tcRefs2 -> List.zip tcRefs1 tcRefs2 |> List.forall (fun (tcRef1, tcRef2) -> tyconRefEq g tcRef1 tcRef2) | Item.Types(_, [TType.TType_app(tcRef1, _)]), Item.UnqualifiedType([tcRef2]) -> tyconRefEq g tcRef1 tcRef2 @@ -786,8 +814,8 @@ module internal SymbolHelpers = protectAssemblyExploration 1027 (fun () -> match item with | ItemWhereTypIsPreferred ty -> - match tryDestAppTy g ty with - | ValueSome tcref -> hash (tcref).LogicalName + match tryTcrefOfAppTy g ty with + | ValueSome tcref -> hash tcref.LogicalName | _ -> 1010 | Item.ILField(ILFieldInfo(_, fld)) -> #if FABLE_COMPILER @@ -804,9 +832,9 @@ module internal SymbolHelpers = | Item.CtorGroup(name, meths) -> name.GetHashCode() + (meths |> List.fold (fun st a -> st + a.ComputeHashCode()) 0) | (Item.Value vref | Item.CustomBuilder (_, vref)) -> hash vref.LogicalName | Item.ActivePatternCase(APElemRef(_apinfo, vref, idx)) -> hash (vref.LogicalName, idx) - | Item.ExnCase(tcref) -> hash tcref.LogicalName - | Item.UnionCase(UnionCaseInfo(_, UCRef(tcref, n)), _) -> hash(tcref.Stamp, n) - | Item.RecdField(RecdFieldInfo(_, RFRef(tcref, n))) -> hash(tcref.Stamp, n) + | Item.ExnCase tcref -> hash tcref.LogicalName + | Item.UnionCase(UnionCaseInfo(_, UnionCaseRef(tcref, n)), _) -> hash(tcref.Stamp, n) + | Item.RecdField(RecdFieldInfo(_, RecdFieldRef(tcref, n))) -> hash(tcref.Stamp, n) | Item.AnonRecdField(anon, _, i, _) -> hash anon.SortedNames.[i] | Item.Event evt -> evt.ComputeHashCode() | Item.Property(_name, pis) -> hash (pis |> List.map (fun pi -> pi.ComputeHashCode())) @@ -819,7 +847,7 @@ module internal SymbolHelpers = { new IPartialEqualityComparer with member x.InEqualityRelation item = itemComparer.InEqualityRelation item.Item member x.Equals(item1, item2) = itemComparer.Equals(item1.Item, item2.Item) - member x.GetHashCode (item) = itemComparer.GetHashCode(item.Item) } + member x.GetHashCode item = itemComparer.GetHashCode(item.Item) } let ItemWithTypeDisplayPartialEquality g = let itemComparer = ItemDisplayPartialEquality g @@ -827,7 +855,7 @@ module internal SymbolHelpers = { new IPartialEqualityComparer with member x.InEqualityRelation ((item, _)) = itemComparer.InEqualityRelation item member x.Equals((item1, _), (item2, _)) = itemComparer.Equals(item1, item2) - member x.GetHashCode ((item, _)) = itemComparer.GetHashCode(item) } + member x.GetHashCode ((item, _)) = itemComparer.GetHashCode item } // Remove items containing the same module references let RemoveDuplicateModuleRefs modrefs = @@ -835,7 +863,7 @@ module internal SymbolHelpers = { new IPartialEqualityComparer with member x.InEqualityRelation _ = true member x.Equals(item1, item2) = (fullDisplayTextOfModRef item1 = fullDisplayTextOfModRef item2) - member x.GetHashCode(item) = hash item.Stamp } + member x.GetHashCode item = hash item.Stamp } /// Remove all duplicate items let RemoveDuplicateItems g (items: ItemWithInst list) = @@ -849,19 +877,22 @@ module internal SymbolHelpers = // This may explore assemblies that are not in the reference set. // In this case just assume the item is not suppressed. protectAssemblyExploration true (fun () -> - match item with - | Item.Types(it, [ty]) -> - isAppTy g ty && - g.suppressed_types - |> List.exists (fun supp -> - let generalizedSupp = generalizedTyconRef supp - // check the display name is precisely the one we're suppressing - isAppTy g generalizedSupp && it = supp.DisplayName && - // check if they are the same logical type (after removing all abbreviations) - let tcr1 = tcrefOfAppTy g ty - let tcr2 = tcrefOfAppTy g generalizedSupp - tyconRefEq g tcr1 tcr2) - | _ -> false) + match item with + | Item.Types(it, [ty]) -> + match tryTcrefOfAppTy g ty with + | ValueSome tcr1 -> + g.suppressed_types + |> List.exists (fun supp -> + let generalizedSupp = generalizedTyconRef supp + // check the display name is precisely the one we're suppressing + match tryTcrefOfAppTy g generalizedSupp with + | ValueSome tcr2 -> + it = supp.DisplayName && + // check if they are the same logical type (after removing all abbreviations) + tyconRefEq g tcr1 tcr2 + | _ -> false) + | _ -> false + | _ -> false) /// Filter types that are explicitly suppressed from the IntelliSense (such as uppercase "FSharpList", "Option", etc.) let RemoveExplicitlySuppressed (g: TcGlobals) (items: ItemWithInst list) = @@ -880,7 +911,7 @@ module internal SymbolHelpers = maxMembers=Some EnvMisc2.maxMembers } let rec FullNameOfItem g item = - let denv = DisplayEnv.Empty(g) + let denv = DisplayEnv.Empty g match item with | Item.ImplicitOp(_, { contents = Some(TraitConstraintSln.FSMethSln(_, vref, _)) }) | Item.Value vref | Item.CustomBuilder (_, vref) -> fullDisplayTextOfValRef vref @@ -893,7 +924,7 @@ module internal SymbolHelpers = | Item.NewDef id -> id.idText | Item.ILField finfo -> bufs (fun os -> NicePrint.outputILTypeRef denv os finfo.ILTypeRef; bprintf os ".%s" finfo.FieldName) | Item.Event einfo -> bufs (fun os -> NicePrint.outputTyconRef denv os einfo.DeclaringTyconRef; bprintf os ".%s" einfo.EventName) - | Item.Property(_, (pinfo::_)) -> bufs (fun os -> NicePrint.outputTyconRef denv os pinfo.DeclaringTyconRef; bprintf os ".%s" pinfo.PropertyName) + | Item.Property(_, (pinfo :: _)) -> bufs (fun os -> NicePrint.outputTyconRef denv os pinfo.DeclaringTyconRef; bprintf os ".%s" pinfo.PropertyName) | Item.CustomOperation (customOpName, _, _) -> customOpName | Item.CtorGroup(_, minfo :: _) -> bufs (fun os -> NicePrint.outputTyconRef denv os minfo.DeclaringTyconRef) | Item.MethodGroup(_, _, Some minfo) -> bufs (fun os -> NicePrint.outputTyconRef denv os minfo.DeclaringTyconRef; bprintf os ".%s" minfo.DisplayName) @@ -901,8 +932,8 @@ module internal SymbolHelpers = | Item.UnqualifiedType (tcref :: _) -> bufs (fun os -> NicePrint.outputTyconRef denv os tcref) | Item.FakeInterfaceCtor ty | Item.DelegateCtor ty - | Item.Types(_, ty:: _) -> - match tryDestAppTy g ty with + | Item.Types(_, ty :: _) -> + match tryTcrefOfAppTy g ty with | ValueSome tcref -> bufs (fun os -> NicePrint.outputTyconRef denv os tcref) | _ -> "" | Item.ModuleOrNamespaces((modref :: _) as modrefs) -> @@ -912,6 +943,7 @@ module internal SymbolHelpers = | Item.ArgName (id, _, _) -> id.idText | Item.SetterArg (_, item) -> FullNameOfItem g item | Item.ImplicitOp(id, _) -> id.idText + | Item.UnionCaseField (UnionCaseInfo (_, ucref), fieldIndex) -> ucref.FieldByIndex(fieldIndex).Name // unreachable | Item.UnqualifiedType([]) | Item.Types(_, []) @@ -940,7 +972,16 @@ module internal SymbolHelpers = GetXmlCommentForItemAux (if tyconRefUsesLocalXmlDoc g.compilingFslib ecref || ecref.XmlDoc.NonEmpty then Some ecref.XmlDoc else None) infoReader m item | Item.RecdField rfinfo -> - GetXmlCommentForItemAux (if tyconRefUsesLocalXmlDoc g.compilingFslib rfinfo.TyconRef || rfinfo.TyconRef.XmlDoc.NonEmpty then Some rfinfo.RecdField.XmlDoc else None) infoReader m item + let tcref = rfinfo.TyconRef + let xmldoc = + if tyconRefUsesLocalXmlDoc g.compilingFslib tcref || tcref.XmlDoc.NonEmpty then + if tcref.IsExceptionDecl then + Some tcref.XmlDoc + else + Some rfinfo.RecdField.XmlDoc + else + None + GetXmlCommentForItemAux xmldoc infoReader m item | Item.Event einfo -> GetXmlCommentForItemAux (if einfo.HasDirectXmlComment || einfo.XmlDoc.NonEmpty then Some einfo.XmlDoc else None) infoReader m item @@ -954,7 +995,7 @@ module internal SymbolHelpers = | Item.MethodGroup(_, minfo :: _, _) -> GetXmlCommentForMethInfoItem infoReader m item minfo - | Item.Types(_, ((TType_app(tcref, _)):: _)) -> + | Item.Types(_, ((TType_app(tcref, _)) :: _)) -> GetXmlCommentForItemAux (if tyconRefUsesLocalXmlDoc g.compilingFslib tcref || tcref.XmlDoc.NonEmpty then Some tcref.XmlDoc else None) infoReader m item | Item.ModuleOrNamespaces((modref :: _) as modrefs) -> @@ -967,15 +1008,18 @@ module internal SymbolHelpers = | Item.ArgName (_, _, argContainer) -> let xmldoc = match argContainer with - | Some(ArgumentContainer.Method (minfo)) -> + | Some(ArgumentContainer.Method minfo) -> if minfo.HasDirectXmlComment || minfo.XmlDoc.NonEmpty then Some minfo.XmlDoc else None - | Some(ArgumentContainer.Type(tcref)) -> + | Some(ArgumentContainer.Type tcref) -> if tyconRefUsesLocalXmlDoc g.compilingFslib tcref || tcref.XmlDoc.NonEmpty then Some tcref.XmlDoc else None - | Some(ArgumentContainer.UnionCase(ucinfo)) -> - if tyconRefUsesLocalXmlDoc g.compilingFslib ucinfo.TyconRef || ucinfo.UnionCase.XmlDoc.NonEmpty then Some ucinfo.UnionCase.XmlDoc else None | _ -> None GetXmlCommentForItemAux xmldoc infoReader m item + | Item.UnionCaseField (ucinfo, _) -> + let xmldoc = + if tyconRefUsesLocalXmlDoc g.compilingFslib ucinfo.TyconRef || ucinfo.UnionCase.XmlDoc.NonEmpty then Some ucinfo.UnionCase.XmlDoc else None + GetXmlCommentForItemAux xmldoc infoReader m item + | Item.SetterArg (_, item) -> GetXmlCommentForItem infoReader m item @@ -993,7 +1037,7 @@ module internal SymbolHelpers = let g = infoReader.g let amap = infoReader.amap match item with - | Item.Types(_, ((TType_app(tcref, _)):: _)) + | Item.Types(_, ((TType_app(tcref, _)) :: _)) | Item.UnqualifiedType(tcref :: _) -> let ty = generalizedTyconRef tcref Infos.ExistsHeadTypeInEntireHierarchy g amap range0 ty g.tcref_System_Attribute @@ -1066,6 +1110,16 @@ module internal SymbolHelpers = let remarks= OutputFullName isListItem pubpathOfTyconRef fullDisplayTextOfExnRefAsLayout ecref FSharpStructuredToolTipElement.Single (layout, xml, remarks=remarks) + | Item.RecdField rfinfo when rfinfo.TyconRef.IsExceptionDecl -> + let ty, _ = PrettyTypes.PrettifyType g rfinfo.FieldType + let id = rfinfo.RecdField.Id + let layout = + wordL (tagText (FSComp.SR.typeInfoArgument())) ^^ + wordL (tagParameter id.idText) ^^ + RightL.colon ^^ + NicePrint.layoutType denv ty + FSharpStructuredToolTipElement.Single (layout, xml, paramName = id.idText) + // F# record field names | Item.RecdField rfinfo -> let rfield = rfinfo.RecdField @@ -1083,6 +1137,17 @@ module internal SymbolHelpers = ) FSharpStructuredToolTipElement.Single (layout, xml) + | Item.UnionCaseField (ucinfo, fieldIndex) -> + let rfield = ucinfo.UnionCase.GetFieldByIndex(fieldIndex) + let fieldTy, _ = PrettyTypes.PrettifyType g rfield.rfield_type + let id = rfield.Id + let layout = + wordL (tagText (FSComp.SR.typeInfoArgument())) ^^ + wordL (tagParameter id.idText) ^^ + RightL.colon ^^ + NicePrint.layoutType denv fieldTy + FSharpStructuredToolTipElement.Single (layout, xml, paramName = id.idText) + // Not used | Item.NewDef id -> let layout = @@ -1178,7 +1243,7 @@ module internal SymbolHelpers = FSharpStructuredToolTipElement.Single(layout, xml) // Types. - | Item.Types(_, ((TType_app(tcref, _)):: _)) + | Item.Types(_, ((TType_app(tcref, _)) :: _)) | Item.UnqualifiedType (tcref :: _) -> let denv = { denv with shortTypeNames = true } let layout = NicePrint.layoutTycon denv infoReader AccessibleFromSomewhere m (* width *) tcref.Deref @@ -1205,7 +1270,7 @@ module internal SymbolHelpers = ([], modrefs) ||> Seq.fold (fun st modref -> match fullDisplayTextOfParentOfModRef modref with - | ValueSome txt -> txt::st + | ValueSome txt -> txt :: st | _ -> st) |> Seq.mapi (fun i x -> i, x) |> Seq.toList @@ -1279,7 +1344,7 @@ module internal SymbolHelpers = match tyconRef.TypeReprInfo with | TProvidedTypeExtensionPoint info -> info.ProvidedType | _ -> failwith "unreachable" - let staticParameters = typeBeforeArguments.PApplyWithProvider((fun (typeBeforeArguments, provider) -> typeBeforeArguments.GetStaticParameters(provider)), range=m) + let staticParameters = typeBeforeArguments.PApplyWithProvider((fun (typeBeforeArguments, provider) -> typeBeforeArguments.GetStaticParameters provider), range=m) let staticParameters = staticParameters.PApplyArray(id, "GetStaticParameters", m) Some staticParameters else @@ -1310,15 +1375,15 @@ module internal SymbolHelpers = #endif - /// Get the "F1 Keyword" associated with an item, for looking up documentatio help indexes on the web - let rec GetF1Keyword g item = + /// Get the "F1 Keyword" associated with an item, for looking up documentation help indexes on the web + let rec GetF1Keyword (g: TcGlobals) item = let getKeywordForMethInfo (minfo : MethInfo) = match minfo with | FSMeth(_, _, vref, _) -> match vref.DeclaringEntity with | Parent tcref -> - (tcref |> ticksAndArgCountTextOfTyconRef)+"."+vref.CompiledName|> Some + (tcref |> ticksAndArgCountTextOfTyconRef) + "." + vref.CompiledName g.CompilerGlobalState |> Some | ParentNone -> None | ILMeth (_, minfo, _) -> @@ -1343,32 +1408,32 @@ module internal SymbolHelpers = | [] -> "" | l -> "``"+(List.length l).ToString() - sprintf "%s.%s%s" (tyconRef |> ticksAndArgCountTextOfTyconRef) v.CompiledName paramsString |> Some + sprintf "%s.%s%s" (tyconRef |> ticksAndArgCountTextOfTyconRef) (v.CompiledName g.CompilerGlobalState) paramsString |> Some else None - | Item.ActivePatternCase apref -> + | Item.ActivePatternCase apref -> GetF1Keyword g (Item.Value apref.ActivePatternVal) - | Item.UnionCase(ucinfo, _) -> - (ucinfo.TyconRef |> ticksAndArgCountTextOfTyconRef)+"."+ucinfo.Name |> Some + | Item.UnionCase(ucinfo, _) -> + (ucinfo.TyconRef |> ticksAndArgCountTextOfTyconRef) + "."+ucinfo.Name |> Some - | Item.RecdField rfi -> - (rfi.TyconRef |> ticksAndArgCountTextOfTyconRef)+"."+rfi.Name |> Some + | Item.RecdField rfi -> + (rfi.TyconRef |> ticksAndArgCountTextOfTyconRef) + "." + rfi.Name |> Some - | Item.AnonRecdField _ -> None + | Item.AnonRecdField _ -> None - | Item.ILField finfo -> + | Item.ILField finfo -> match finfo with | ILFieldInfo(tinfo, fdef) -> - (tinfo.TyconRefOfRawMetadata |> ticksAndArgCountTextOfTyconRef)+"."+fdef.Name |> Some + (tinfo.TyconRefOfRawMetadata |> ticksAndArgCountTextOfTyconRef) + "." + fdef.Name |> Some #if !NO_EXTENSIONTYPING | ProvidedField _ -> None #endif | Item.Types(_, ((AppTy g (tcref, _)) :: _)) | Item.DelegateCtor(AppTy g (tcref, _)) | Item.FakeInterfaceCtor(AppTy g (tcref, _)) - | Item.UnqualifiedType (tcref::_) + | Item.UnqualifiedType (tcref :: _) | Item.ExnCase tcref -> // strip off any abbreviation match generalizedTyconRef tcref with @@ -1445,7 +1510,7 @@ module internal SymbolHelpers = | Parent tcref -> (tcref |> ticksAndArgCountTextOfTyconRef) + ".#ctor"|> Some | ParentNone -> None #if !NO_EXTENSIONTYPING - | ProvidedMeth _::_ -> None + | ProvidedMeth _ :: _ -> None #endif | minfo :: _ -> let tcref = minfo.DeclaringTyconRef @@ -1458,6 +1523,7 @@ module internal SymbolHelpers = | Item.CustomOperation (_, _, None) // "into" | Item.NewDef _ // "let x$yz = ..." - no keyword | Item.ArgName _ // no keyword on named parameters + | Item.UnionCaseField _ | Item.TypeVar _ | Item.ImplicitOp _ | Item.ActivePatternResult _ // "let (|Foo|Bar|) = .. Fo$o ..." - no keyword @@ -1468,7 +1534,7 @@ module internal SymbolHelpers = let FormatStructuredDescriptionOfItem isListItem infoReader m denv item = ErrorScope.Protect m (fun () -> FormatItemDescriptionToToolTipElement isListItem infoReader m denv item) - (fun err -> FSharpStructuredToolTipElement.CompositionError(err)) + (fun err -> FSharpStructuredToolTipElement.CompositionError err) /// Get rid of groups of overloads an replace them with single items. let FlattenItems g (_m: range) item = @@ -1480,10 +1546,10 @@ module internal SymbolHelpers = | Item.NewDef _ | Item.ILField _ -> [] | Item.Event _ -> [] - | Item.RecdField(rfinfo) -> if isFunction g rfinfo.FieldType then [item] else [] + | Item.RecdField rfinfo -> if isFunction g rfinfo.FieldType then [item] else [] | Item.Value v -> if isFunction g v.Type then [item] else [] | Item.UnionCase(ucr, _) -> if not ucr.UnionCase.IsNullary then [item] else [] - | Item.ExnCase(ecr) -> if isNil (recdFieldsOfExnDefRef ecr) then [] else [item] + | Item.ExnCase ecr -> if isNil (recdFieldsOfExnDefRef ecr) then [] else [item] | Item.Property(_, pinfos) -> let pinfo = List.head pinfos if pinfo.IsIndexer then [item] else [] diff --git a/src/fcs-fable/src/fsharp/symbols/SymbolHelpers.fsi b/src/fcs-fable/src/fsharp/symbols/SymbolHelpers.fsi index 205d573961..664471ab44 100755 --- a/src/fcs-fable/src/fsharp/symbols/SymbolHelpers.fsi +++ b/src/fcs-fable/src/fsharp/symbols/SymbolHelpers.fsi @@ -13,35 +13,34 @@ open FSharp.Compiler.TcGlobals open FSharp.Compiler.Infos open FSharp.Compiler.NameResolution open FSharp.Compiler.InfoReader -open FSharp.Compiler.Tast -open FSharp.Compiler.Tastops +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.ErrorLogger -//---------------------------------------------------------------------------- -// Object model for diagnostics - - [] type public FSharpErrorSeverity = -| Warning + | Warning | Error +/// Object model for diagnostics [] type public FSharpErrorInfo = member FileName: string - member StartLineAlternate:int - member EndLineAlternate:int - member StartColumn:int - member EndColumn:int - member Severity:FSharpErrorSeverity - member Message:string - member Subcategory:string - member ErrorNumber:int - static member internal CreateFromExceptionAndAdjustEof : PhasedDiagnostic * isError: bool * range * lastPosInFile:(int*int) -> FSharpErrorInfo - static member internal CreateFromException : PhasedDiagnostic * isError: bool * range -> FSharpErrorInfo - -//---------------------------------------------------------------------------- -// Object model for quick info + member Start: pos + member End: pos + member StartLineAlternate: int + member EndLineAlternate: int + member StartColumn: int + member EndColumn: int + + member Range: range + member Severity: FSharpErrorSeverity + member Message: string + member Subcategory: string + member ErrorNumber: int + + static member internal CreateFromExceptionAndAdjustEof: PhasedDiagnostic * isError: bool * range * lastPosInFile: (int*int) * suggestNames: bool -> FSharpErrorInfo + static member internal CreateFromException: PhasedDiagnostic * isError: bool * range * suggestNames: bool -> FSharpErrorInfo /// Describe a comment as either a block of text or a file+signature reference into an intellidoc file. // @@ -62,14 +61,20 @@ type public Layout = Internal.Utilities.StructuredFormat.Layout /// A single data tip display element [] type public FSharpToolTipElementData<'T> = - { MainDescription: 'T + { + MainDescription: 'T + XmlDoc: FSharpXmlDoc - /// typar insantiation text, to go after xml + + /// typar instantiation text, to go after xml TypeMapping: 'T list + /// Extra text, goes at the end Remarks: 'T option + /// Parameter name - ParamName : string option } + ParamName : string option + } /// A single tool tip display element // @@ -88,7 +93,6 @@ type public FSharpToolTipElement<'T> = /// A single data tip display element with where text is expressed as string type public FSharpToolTipElement = FSharpToolTipElement - /// A single data tip display element with where text is expressed as type public FSharpStructuredToolTipElement = FSharpToolTipElement @@ -96,15 +100,13 @@ type public FSharpStructuredToolTipElement = FSharpToolTipElement // // Note: instances of this type do not hold any references to any compiler resources. type public FSharpToolTipText<'T> = + /// A list of data tip elements to display. | FSharpToolTipText of FSharpToolTipElement<'T> list type public FSharpToolTipText = FSharpToolTipText -type public FSharpStructuredToolTipText = FSharpToolTipText - -//---------------------------------------------------------------------------- -// Object model for completion list entries (one of several in the API...) +type public FSharpStructuredToolTipText = FSharpToolTipText [] type public CompletionItemKind = @@ -117,58 +119,101 @@ type public CompletionItemKind = | Other type UnresolvedSymbol = - { FullName: string + { + FullName: string + DisplayName: string - Namespace: string[] } + + Namespace: string[] + } type internal CompletionItem = - { ItemWithInst: ItemWithInst + { + ItemWithInst: ItemWithInst + Kind: CompletionItemKind + IsOwnMember: bool + MinorPriority: int + Type: TyconRef option - Unresolved: UnresolvedSymbol option } + + Unresolved: UnresolvedSymbol option + } member Item : Item module public Tooltips = + val ToFSharpToolTipElement: FSharpStructuredToolTipElement -> FSharpToolTipElement + val ToFSharpToolTipText: FSharpStructuredToolTipText -> FSharpToolTipText + val Map: f: ('T1 -> 'T2) -> a: Async<'T1> -> Async<'T2> // Implementation details used by other code in the compiler module internal SymbolHelpers = + val isFunction : TcGlobals -> TType -> bool + val ParamNameAndTypesOfUnaryCustomOperation : TcGlobals -> MethInfo -> ParamNameAndType list val GetXmlDocSigOfEntityRef : InfoReader -> range -> EntityRef -> (string option * string) option + val GetXmlDocSigOfScopedValRef : TcGlobals -> TyconRef -> ValRef -> (string option * string) option + val GetXmlDocSigOfILFieldInfo : InfoReader -> range -> ILFieldInfo -> (string option * string) option + val GetXmlDocSigOfRecdFieldInfo : RecdFieldInfo -> (string option * string) option + val GetXmlDocSigOfUnionCaseInfo : UnionCaseInfo -> (string option * string) option + val GetXmlDocSigOfMethInfo : InfoReader -> range -> MethInfo -> (string option * string) option + val GetXmlDocSigOfValRef : TcGlobals -> ValRef -> (string option * string) option + val GetXmlDocSigOfProp : InfoReader -> range -> PropInfo -> (string option * string) option + val GetXmlDocSigOfEvent : InfoReader -> range -> EventInfo -> (string option * string) option + val GetXmlCommentForItem : InfoReader -> range -> Item -> FSharpXmlDoc + val FormatStructuredDescriptionOfItem : isDecl:bool -> InfoReader -> range -> DisplayEnv -> ItemWithInst -> FSharpStructuredToolTipElement + val RemoveDuplicateItems : TcGlobals -> ItemWithInst list -> ItemWithInst list + val RemoveExplicitlySuppressed : TcGlobals -> ItemWithInst list -> ItemWithInst list + val RemoveDuplicateCompletionItems : TcGlobals -> CompletionItem list -> CompletionItem list + val RemoveExplicitlySuppressedCompletionItems : TcGlobals -> CompletionItem list -> CompletionItem list + val GetF1Keyword : TcGlobals -> Item -> string option + val rangeOfItem : TcGlobals -> bool option -> Item -> range option + val fileNameOfItem : TcGlobals -> string option -> range -> Item -> string + val FullNameOfItem : TcGlobals -> Item -> string + val ccuOfItem : TcGlobals -> Item -> CcuThunk option + val mutable ToolTipFault : string option + val IsAttribute : InfoReader -> Item -> bool + val IsExplicitlySuppressed : TcGlobals -> Item -> bool + val FlattenItems : TcGlobals -> range -> Item -> Item list + #if !NO_EXTENSIONTYPING val (|ItemIsProvidedType|_|) : TcGlobals -> Item -> TyconRef option + val (|ItemIsWithStaticArguments|_|): range -> TcGlobals -> Item -> Tainted[] option + val (|ItemIsProvidedTypeWithStaticArguments|_|): range -> TcGlobals -> Item -> Tainted[] option #endif + val SimplerDisplayEnv : DisplayEnv -> DisplayEnv //---------------------------------------------------------------------------- @@ -200,5 +245,5 @@ type internal CompilationGlobalsScope = interface IDisposable module internal ErrorHelpers = - val ReportError: FSharpErrorSeverityOptions * allErrors: bool * mainInputFileName: string * fileInfo: (int * int) * (PhasedDiagnostic * FSharpErrorSeverity) -> FSharpErrorInfo list - val CreateErrorInfos: FSharpErrorSeverityOptions * allErrors: bool * mainInputFileName: string * seq<(PhasedDiagnostic * FSharpErrorSeverity)> -> FSharpErrorInfo[] + val ReportError: FSharpErrorSeverityOptions * allErrors: bool * mainInputFileName: string * fileInfo: (int * int) * (PhasedDiagnostic * FSharpErrorSeverity) * suggestNames: bool -> FSharpErrorInfo list + val CreateErrorInfos: FSharpErrorSeverityOptions * allErrors: bool * mainInputFileName: string * seq<(PhasedDiagnostic * FSharpErrorSeverity)> * suggestNames: bool -> FSharpErrorInfo[] diff --git a/src/fcs-fable/src/fsharp/symbols/SymbolPatterns.fs b/src/fcs-fable/src/fsharp/symbols/SymbolPatterns.fs index ee4134d90e..79ca3f9e2b 100644 --- a/src/fcs-fable/src/fsharp/symbols/SymbolPatterns.fs +++ b/src/fcs-fable/src/fsharp/symbols/SymbolPatterns.fs @@ -2,12 +2,13 @@ namespace FSharp.Compiler.SourceCodeServices +open System +open System.Text.RegularExpressions +open FSharp.Compiler.AbstractIL.Internal.Library + /// Patterns over FSharpSymbol and derivatives. [] module Symbol = - open System - open System.Text.RegularExpressions - open FSharp.Compiler.AbstractIL.Internal.Library let isAttribute<'T> (attribute: FSharpAttribute) = // CompiledName throws exception on DataContractAttribute generated by SQLProvider @@ -142,8 +143,8 @@ module Symbol = #endif let (|Enum|_|) (entity: FSharpEntity) = if entity.IsEnum then Some() else None - let (|Tuple|_|) (ty: FSharpType option) = - ty |> Option.bind (fun ty -> if ty.IsTupleType then Some() else None) + let (|Tuple|_|) (ty: FSharpType) = + if ty.IsTupleType then Some() else None let (|RefCell|_|) (ty: FSharpType) = match getAbbreviatedType ty with diff --git a/src/fcs-fable/src/fsharp/symbols/SymbolPatterns.fsi b/src/fcs-fable/src/fsharp/symbols/SymbolPatterns.fsi index c4c242270c..a0209cae21 100644 --- a/src/fcs-fable/src/fsharp/symbols/SymbolPatterns.fsi +++ b/src/fcs-fable/src/fsharp/symbols/SymbolPatterns.fsi @@ -2,54 +2,96 @@ namespace FSharp.Compiler.SourceCodeServices -[] /// Patterns over FSharpSymbol and derivatives. +[] module public Symbol = val isAttribute<'T> : FSharpAttribute -> bool + val tryGetAttribute<'T> : seq -> FSharpAttribute option + val hasModuleSuffixAttribute : FSharpEntity -> bool + val isOperator : name: string -> bool + val isUnnamedUnionCaseField : FSharpField -> bool + val (|AbbreviatedType|_|) : FSharpEntity -> FSharpType option + val (|TypeWithDefinition|_|) : FSharpType -> FSharpEntity option + val getEntityAbbreviatedType : FSharpEntity -> (FSharpEntity * FSharpType option) + val getAbbreviatedType : FSharpType -> FSharpType + val (|Attribute|_|) : FSharpEntity -> unit option + val hasAttribute<'T> : seq -> bool + val (|ValueType|_|) : FSharpEntity -> unit option + val (|Class|_|) : original: FSharpEntity * abbreviated: FSharpEntity * 'a -> unit option + val (|Record|_|) : FSharpEntity -> unit option + val (|UnionType|_|) : FSharpEntity -> unit option + val (|Delegate|_|) : FSharpEntity -> unit option + val (|FSharpException|_|) : FSharpEntity -> unit option + val (|Interface|_|) : FSharpEntity -> unit option + val (|AbstractClass|_|) : FSharpEntity -> unit option + val (|FSharpType|_|) : FSharpEntity -> unit option + #if !NO_EXTENSIONTYPING val (|ProvidedType|_|) : FSharpEntity -> unit option #endif + val (|ByRef|_|) : FSharpEntity -> unit option + val (|Array|_|) : FSharpEntity -> unit option + val (|FSharpModule|_|) : FSharpEntity -> unit option + val (|Namespace|_|) : FSharpEntity -> unit option + #if !NO_EXTENSIONTYPING val (|ProvidedAndErasedType|_|) : FSharpEntity -> unit option #endif + val (|Enum|_|) : FSharpEntity -> unit option - val (|Tuple|_|) : FSharpType option -> unit option + + val (|Tuple|_|) : FSharpType -> unit option + val (|RefCell|_|) : FSharpType -> unit option + val (|FunctionType|_|) : FSharpType -> unit option + val (|Pattern|_|) : FSharpSymbol -> unit option + val (|Field|_|) : FSharpSymbol -> (FSharpField * FSharpType) option + val (|MutableVar|_|) : FSharpSymbol -> unit option + val (|FSharpEntity|_|) : FSharpSymbol -> (FSharpEntity * FSharpEntity * FSharpType option) option + val (|Parameter|_|) : FSharpSymbol -> unit option + val (|UnionCase|_|) : FSharpSymbol -> FSharpUnionCase option + val (|RecordField|_|) : FSharpSymbol -> FSharpField option + val (|ActivePatternCase|_|) : FSharpSymbol -> FSharpActivePatternCase option + val (|MemberFunctionOrValue|_|) : FSharpSymbol -> FSharpMemberOrFunctionOrValue option + val (|Constructor|_|) : FSharpMemberOrFunctionOrValue -> FSharpEntity option + val (|Function|_|) : excluded: bool -> FSharpMemberOrFunctionOrValue -> unit option + val (|ExtensionMember|_|) : FSharpMemberOrFunctionOrValue -> unit option + val (|Event|_|) : FSharpMemberOrFunctionOrValue -> unit option \ No newline at end of file diff --git a/src/fcs-fable/src/fsharp/symbols/Symbols.fs b/src/fcs-fable/src/fsharp/symbols/Symbols.fs old mode 100755 new mode 100644 index 5c1b19378a..c3a91e38fa --- a/src/fcs-fable/src/fsharp/symbols/Symbols.fs +++ b/src/fcs-fable/src/fsharp/symbols/Symbols.fs @@ -1,23 +1,28 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. namespace FSharp.Compiler.SourceCodeServices open System.Collections.Generic + open FSharp.Compiler open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.IL -open FSharp.Compiler.Infos open FSharp.Compiler.AttributeChecking open FSharp.Compiler.AccessibilityLogic -open FSharp.Compiler.InfoReader -open FSharp.Compiler.Range -open FSharp.Compiler.Ast open FSharp.Compiler.CompileOps -open FSharp.Compiler.Tast +open FSharp.Compiler.Infos +open FSharp.Compiler.InfoReader +open FSharp.Compiler.Lib open FSharp.Compiler.NameResolution +open FSharp.Compiler.Range +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics open FSharp.Compiler.TcGlobals -open FSharp.Compiler.Lib -open FSharp.Compiler.Tastops +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.XmlDoc + open Internal.Utilities type FSharpAccessibility(a:Accessibility, ?isProtected) = @@ -34,7 +39,7 @@ type FSharpAccessibility(a:Accessibility, ?isProtected) = | _ when List.forall isInternalCompPath p -> Internal | _ -> Private - member __.IsPublic = not isProtected && match a with Public -> true | _ -> false + member __.IsPublic = not isProtected && match a with TAccess [] -> true | _ -> false member __.IsPrivate = not isProtected && match a with Private -> true | _ -> false @@ -77,7 +82,7 @@ module Impl = System.Collections.ObjectModel.ReadOnlyCollection<_>(Seq.toArray arr) :> IList<_> #endif - let makeXmlDoc (XmlDoc x) = makeReadOnlyCollection (x) + let makeXmlDoc (XmlDoc x) = makeReadOnlyCollection x let rescopeEntity optViewedCcu (entity: Entity) = match optViewedCcu with @@ -94,7 +99,7 @@ module Impl = | _ -> false let checkEntityIsResolved(entity:EntityRef) = - if entityIsUnresolved(entity) then + if entityIsUnresolved entity then let poorQualifiedName = if entity.nlr.AssemblyName = "mscorlib" then entity.nlr.DisplayName + ", mscorlib" @@ -103,7 +108,7 @@ module Impl = invalidOp (sprintf "The entity '%s' does not exist or is in an unresolved assembly." poorQualifiedName) /// Checking accessibility that arise from different compilations needs more care - this is a duplicate of the F# compiler code for this case - let checkForCrossProjectAccessibility (thisCcu2:CcuThunk, ad2) (thisCcu1, taccess1) = + let checkForCrossProjectAccessibility (ilg: ILGlobals) (thisCcu2:CcuThunk, ad2) (thisCcu1, taccess1) = match ad2 with | AccessibleFrom(cpaths2, _) -> let nameOfScoRef (thisCcu:CcuThunk) scoref = @@ -111,10 +116,11 @@ module Impl = | ILScopeRef.Local -> thisCcu.AssemblyName | ILScopeRef.Assembly aref -> aref.Name | ILScopeRef.Module mref -> mref.Name + | ILScopeRef.PrimaryAssembly -> ilg.primaryAssemblyName let canAccessCompPathFromCrossProject (CompPath(scoref1, cpath1)) (CompPath(scoref2, cpath2)) = let rec loop p1 p2 = match p1, p2 with - | (a1, k1)::rest1, (a2, k2)::rest2 -> (a1=a2) && (k1=k2) && loop rest1 rest2 + | (a1, k1) :: rest1, (a2, k2) :: rest2 -> (a1=a2) && (k1=k2) && loop rest1 rest2 | [], _ -> true | _ -> false // cpath1 is longer loop cpath1 cpath2 && @@ -191,8 +197,12 @@ module Impl = | _ -> "" type FSharpDisplayContext(denv: TcGlobals -> DisplayEnv) = - member x.Contents(g) = denv(g) - static member Empty = FSharpDisplayContext(fun g -> DisplayEnv.Empty(g)) + member x.Contents g = denv g + + static member Empty = FSharpDisplayContext(fun g -> DisplayEnv.Empty g) + + member x.WithShortTypeNames shortNames = + FSharpDisplayContext(fun g -> { denv g with shortTypeNames = shortNames }) // delay the realization of 'item' in case it is unresolved @@ -210,12 +220,12 @@ type FSharpSymbol(cenv: SymbolEnv, item: (unit -> Item), access: (FSharpSymbol - member x.DeclarationLocation = SymbolHelpers.rangeOfItem cenv.g None x.Item - member x.ImplementationLocation = SymbolHelpers.rangeOfItem cenv.g (Some(false)) x.Item + member x.ImplementationLocation = SymbolHelpers.rangeOfItem cenv.g (Some false) x.Item - member x.SignatureLocation = SymbolHelpers.rangeOfItem cenv.g (Some(true)) x.Item + member x.SignatureLocation = SymbolHelpers.rangeOfItem cenv.g (Some true) x.Item member x.IsEffectivelySameAs(y:FSharpSymbol) = - x.Equals(y) || ItemsAreEffectivelyEqual cenv.g x.Item y.Item + x.Equals y || ItemsAreEffectivelyEqual cenv.g x.Item y.Item member x.GetEffectivelySameAsHash() = ItemsAreEffectivelyEqualHash cenv.g x.Item @@ -247,6 +257,7 @@ type FSharpSymbol(cenv: SymbolEnv, item: (unit -> Item), access: (FSharpSymbol - | Item.UnionCase (uinfo, _) -> FSharpUnionCase(cenv, uinfo.UnionCaseRef) :> _ | Item.ExnCase tcref -> FSharpEntity(cenv, tcref) :>_ | Item.RecdField rfinfo -> FSharpField(cenv, RecdOrClass rfinfo.RecdFieldRef) :> _ + | Item.UnionCaseField (UnionCaseInfo (_, ucref), index) -> FSharpField (cenv, Union (ucref, index)) :> _ | Item.ILField finfo -> FSharpField(cenv, ILField finfo) :> _ @@ -291,8 +302,8 @@ type FSharpSymbol(cenv: SymbolEnv, item: (unit -> Item), access: (FSharpSymbol - | Item.ActivePatternResult (apinfo, ty, n, _) -> FSharpActivePatternCase(cenv, apinfo, ty, n, None, item) :> _ - | Item.ArgName(id, ty, _) -> - FSharpParameter(cenv, ty, {Attribs=[]; Name=Some id}, Some id.idRange, isParamArrayArg=false, isInArg=false, isOutArg=false, isOptionalArg=false) :> _ + | Item.ArgName(id, ty, argOwner) -> + FSharpParameter(cenv, id, ty, argOwner) :> _ | Item.ImplicitOp(_, { contents = Some(TraitConstraintSln.FSMethSln(_, vref, _)) }) -> FSharpMemberOrFunctionOrValue(cenv, V vref, item) :> _ @@ -324,11 +335,11 @@ type FSharpSymbol(cenv: SymbolEnv, item: (unit -> Item), access: (FSharpSymbol - and FSharpEntity(cenv: SymbolEnv, entity:EntityRef) = inherit FSharpSymbol(cenv, (fun () -> - checkEntityIsResolved(entity) + checkEntityIsResolved entity if entity.IsModuleOrNamespace then Item.ModuleOrNamespaces [entity] else Item.UnqualifiedType [entity]), (fun _this thisCcu2 ad -> - checkForCrossProjectAccessibility (thisCcu2, ad) (cenv.thisCcu, getApproxFSharpAccessibilityOfEntity entity)) + checkForCrossProjectAccessibility cenv.g.ilg (thisCcu2, ad) (cenv.thisCcu, getApproxFSharpAccessibilityOfEntity entity)) // && AccessibilityLogic.IsEntityAccessible cenv.amap range0 ad entity) ) @@ -541,11 +552,11 @@ and FSharpEntity(cenv: SymbolEnv, entity:EntityRef) = member __.Accessibility = - if isUnresolved() then FSharpAccessibility(taccessPublic) else + if isUnresolved() then FSharpAccessibility taccessPublic else FSharpAccessibility(getApproxFSharpAccessibilityOfEntity entity) member __.RepresentationAccessibility = - if isUnresolved() then FSharpAccessibility(taccessPublic) else + if isUnresolved() then FSharpAccessibility taccessPublic else FSharpAccessibility(entity.TypeReprAccessibility) member x.DeclaredInterfaces = @@ -647,7 +658,7 @@ and FSharpEntity(cenv: SymbolEnv, entity:EntityRef) = | TProvidedTypeExtensionPoint info -> let m = x.DeclarationLocation let typeBeforeArguments = info.ProvidedType - let staticParameters = typeBeforeArguments.PApplyWithProvider((fun (typeBeforeArguments, provider) -> typeBeforeArguments.GetStaticParameters(provider)), range=m) + let staticParameters = typeBeforeArguments.PApplyWithProvider((fun (typeBeforeArguments, provider) -> typeBeforeArguments.GetStaticParameters provider), range=m) let staticParameters = staticParameters.PApplyArray(id, "GetStaticParameters", m) [| for p in staticParameters -> FSharpStaticParameter(cenv, p, m) |] #endif @@ -680,7 +691,7 @@ and FSharpEntity(cenv: SymbolEnv, entity:EntityRef) = let formalTypeInfo = ILTypeInfo.FromType cenv.g ty tdef.Fields.AsList |> List.map (fun tdef -> let ilFieldInfo = ILFieldInfo(formalTypeInfo, tdef) - FSharpField(cenv, FSharpFieldData.ILField(ilFieldInfo) )) + FSharpField(cenv, FSharpFieldData.ILField ilFieldInfo )) |> makeReadOnlyCollection else @@ -759,7 +770,7 @@ and FSharpUnionCase(cenv, v: UnionCaseRef) = checkEntityIsResolved v.TyconRef Item.UnionCase(UnionCaseInfo(generalizeTypars v.TyconRef.TyparsNoRange, v), false)), (fun _this thisCcu2 ad -> - checkForCrossProjectAccessibility (thisCcu2, ad) (cenv.thisCcu, v.UnionCase.Accessibility)) + checkForCrossProjectAccessibility cenv.g.ilg (thisCcu2, ad) (cenv.thisCcu, v.UnionCase.Accessibility)) //&& AccessibilityLogic.IsUnionCaseAccessible cenv.amap range0 ad v) ) @@ -783,9 +794,13 @@ and FSharpUnionCase(cenv, v: UnionCaseRef) = checkIsResolved() v.Range + member __.HasFields = + if isUnresolved() then false else + v.UnionCase.RecdFieldsArray.Length <> 0 + member __.UnionCaseFields = if isUnresolved() then makeReadOnlyCollection [] else - v.UnionCase.RecdFields |> List.mapi (fun i _ -> FSharpField(cenv, FSharpFieldData.Union (v, i))) |> makeReadOnlyCollection + v.UnionCase.RecdFieldsArray |> Array.mapi (fun i _ -> FSharpField(cenv, FSharpFieldData.Union (v, i))) |> makeReadOnlyCollection member __.ReturnType = checkIsResolved() @@ -811,7 +826,7 @@ and FSharpUnionCase(cenv, v: UnionCaseRef) = v.Attribs |> List.map (fun a -> FSharpAttribute(cenv, AttribInfo.FSAttribInfo(cenv.g, a))) |> makeReadOnlyCollection member __.Accessibility = - if isUnresolved() then FSharpAccessibility(taccessPublic) else + if isUnresolved() then FSharpAccessibility taccessPublic else FSharpAccessibility(v.UnionCase.Accessibility) member private x.V = v @@ -820,12 +835,11 @@ and FSharpUnionCase(cenv, v: UnionCaseRef) = match other with | :? FSharpUnionCase as uc -> v === uc.V | _ -> false - + override x.GetHashCode() = hash v.CaseName override x.ToString() = x.CompiledName - and FSharpFieldData = | AnonField of AnonRecdTypeInfo * TTypes * int * range | ILField of ILFieldInfo @@ -836,15 +850,14 @@ and FSharpFieldData = match x with | AnonField (anonInfo, tinst, n, m) -> (anonInfo, tinst, n, m) |> Choice3Of3 | RecdOrClass v -> v.RecdField |> Choice1Of3 - | Union (v, n) -> v.FieldByIndex(n) |> Choice1Of3 + | Union (v, n) -> v.FieldByIndex n |> Choice1Of3 | ILField f -> f |> Choice2Of3 member x.TryDeclaringTyconRef = match x with - | AnonField _ -> None | RecdOrClass v -> Some v.TyconRef - | Union (v, _) -> Some v.TyconRef | ILField f -> Some f.DeclaringTyconRef + | _ -> None and FSharpAnonRecordTypeDetails(cenv: SymbolEnv, anonInfo: AnonRecdTypeInfo) = member __.Assembly = FSharpAssembly (cenv, anonInfo.Assembly) @@ -867,13 +880,13 @@ and FSharpField(cenv: SymbolEnv, d: FSharpFieldData) = | RecdOrClass v -> checkEntityIsResolved v.TyconRef Item.RecdField(RecdFieldInfo(generalizeTypars v.TyconRef.TyparsNoRange, v)) - | Union (v, _) -> - // This is not correct: there is no "Item" for a named union case field - Item.UnionCase(UnionCaseInfo(generalizeTypars v.TyconRef.TyparsNoRange, v), false) + | Union (v, fieldIndex) -> + checkEntityIsResolved v.TyconRef + Item.UnionCaseField (UnionCaseInfo (generalizeTypars v.TyconRef.TyparsNoRange, v), fieldIndex) | ILField f -> Item.ILField f), (fun this thisCcu2 ad -> - checkForCrossProjectAccessibility (thisCcu2, ad) (cenv.thisCcu, (this :?> FSharpField).Accessibility.Contents)) + checkForCrossProjectAccessibility cenv.g.ilg (thisCcu2, ad) (cenv.thisCcu, (this :?> FSharpField).Accessibility.Contents)) //&& //match d with //| Recd v -> AccessibilityLogic.IsRecdFieldAccessible cenv.amap range0 ad v @@ -900,9 +913,9 @@ and FSharpField(cenv: SymbolEnv, d: FSharpFieldData) = invalidOp (sprintf "The union case '%s' could not be found in the target type" v.CaseName) | ILField _ -> () - new (cenv, ucref, n) = FSharpField(cenv, FSharpFieldData.Union(ucref, n)) + new (cenv, ucref: UnionCaseRef, n) = FSharpField(cenv, FSharpFieldData.Union(ucref, n)) - new (cenv, rfref) = FSharpField(cenv, FSharpFieldData.RecdOrClass(rfref)) + new (cenv, rfref: RecdFieldRef) = FSharpField(cenv, FSharpFieldData.RecdOrClass rfref) member __.DeclaringEntity = d.TryDeclaringTyconRef |> Option.map (fun tcref -> FSharpEntity(cenv, tcref)) @@ -959,6 +972,16 @@ and FSharpField(cenv: SymbolEnv, d: FSharpFieldData) = | AnonField (anonInfo, types, n, _) -> FSharpAnonRecordTypeDetails(cenv, anonInfo), [| for ty in types -> FSharpType(cenv, ty) |], n | _ -> invalidOp "not an anonymous record field" + member __.IsUnionCaseField = + match d with + | Union _ -> true + | _ -> false + + member __.DeclaringUnionCase = + match d with + | Union (v, _) -> Some (FSharpUnionCase (cenv, v)) + | _ -> None + member __.XmlDocSig = checkIsResolved() let xmlsig = @@ -1044,13 +1067,13 @@ and FSharpField(cenv: SymbolEnv, d: FSharpFieldData) = |> makeReadOnlyCollection member __.Accessibility: FSharpAccessibility = - if isUnresolved() then FSharpAccessibility(taccessPublic) else + if isUnresolved() then FSharpAccessibility taccessPublic else let access = match d.TryRecdField with | Choice1Of3 r -> r.Accessibility | Choice2Of3 _ -> taccessPublic | Choice3Of3 _ -> taccessPublic - FSharpAccessibility(access) + FSharpAccessibility access member private x.V = d @@ -1369,7 +1392,7 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item2) = (fun () -> item2), (fun this thisCcu2 ad -> let this = this :?> FSharpMemberOrFunctionOrValue - checkForCrossProjectAccessibility (thisCcu2, ad) (cenv.thisCcu, this.Accessibility.Contents)) + checkForCrossProjectAccessibility cenv.g.ilg (thisCcu2, ad) (cenv.thisCcu, this.Accessibility.Contents)) //&& //match d with //| E e -> @@ -1404,7 +1427,12 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item2) = let mkEventSym einfo = FSharpMemberOrFunctionOrValue(cenv, E einfo, Item.Event einfo) new (cenv, vref) = FSharpMemberFunctionOrValue(cenv, V vref, Item.Value vref) - new (cenv, minfo) = FSharpMemberFunctionOrValue(cenv, M minfo, Item.MethodGroup(minfo.LogicalName, [minfo], None)) + + new (cenv, minfo: MethInfo) = + if minfo.IsConstructor || minfo.IsClassConstructor then + FSharpMemberFunctionOrValue(cenv, C minfo, Item.CtorGroup(minfo.LogicalName, [minfo])) + else + FSharpMemberFunctionOrValue(cenv, M minfo, Item.MethodGroup(minfo.LogicalName, [minfo], None)) member __.IsUnresolved = isUnresolved() @@ -1418,16 +1446,22 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item2) = member x.Overloads matchParameterNumber = checkIsResolved() match d with - | M m -> + | M m | C m -> match item2 with - | Item.MethodGroup (_name, methodInfos, _) -> + | Item.MethodGroup (_, methodInfos, _) + | Item.CtorGroup (_, methodInfos) -> + let isConstructor = x.IsConstructor let methods = if matchParameterNumber then methodInfos |> List.filter (fun methodInfo -> not (methodInfo.NumArgs = m.NumArgs) ) else methodInfos methods - |> List.map (fun mi -> FSharpMemberOrFunctionOrValue(cenv, M mi, item2)) + |> List.map (fun mi -> + if isConstructor then + FSharpMemberOrFunctionOrValue(cenv, C mi, item2) + else + FSharpMemberOrFunctionOrValue(cenv, M mi, item2)) |> makeReadOnlyCollection |> Some | _ -> None @@ -1750,7 +1784,7 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item2) = member x.CompiledName = checkIsResolved() match fsharpInfo() with - | Some v -> v.CompiledName + | Some v -> v.CompiledName cenv.g.CompilerGlobalState | None -> x.LogicalName member __.LogicalName = @@ -1808,12 +1842,11 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item2) = checkIsResolved() match d with | P p -> - [ [ for (ParamData(isParamArrayArg, isInArg, isOutArg, optArgInfo, _callerInfo, nmOpt, _reflArgInfo, pty)) in p.GetParamDatas(cenv.amap, range0) do // INCOMPLETENESS: Attribs is empty here, so we can't look at attributes for // either .NET or F# parameters let argInfo: ArgReprInfo = { Name=nmOpt; Attribs= [] } - yield FSharpParameter(cenv, pty, argInfo, x.DeclarationLocationOpt, isParamArrayArg, isInArg, isOutArg, optArgInfo.IsOptional) ] + yield FSharpParameter(cenv, pty, argInfo, None, x.DeclarationLocationOpt, isParamArrayArg, isInArg, isOutArg, optArgInfo.IsOptional) ] |> makeReadOnlyCollection ] |> makeReadOnlyCollection @@ -1825,7 +1858,7 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item2) = // INCOMPLETENESS: Attribs is empty here, so we can't look at attributes for // either .NET or F# parameters let argInfo: ArgReprInfo = { Name=nmOpt; Attribs= [] } - yield FSharpParameter(cenv, pty, argInfo, x.DeclarationLocationOpt, isParamArrayArg, isInArg, isOutArg, optArgInfo.IsOptional) ] + yield FSharpParameter(cenv, pty, argInfo, None, x.DeclarationLocationOpt, isParamArrayArg, isInArg, isOutArg, optArgInfo.IsOptional) ] |> makeReadOnlyCollection ] |> makeReadOnlyCollection @@ -1842,7 +1875,7 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item2) = else [ty] yield allArguments - |> List.map (fun arg -> FSharpParameter(cenv, arg, { Name=None; Attribs= [] }, x.DeclarationLocationOpt, false, false, false, false)) + |> List.map (fun arg -> FSharpParameter(cenv, arg, ValReprInfo.unnamedTopArg1, x.DeclarationLocationOpt)) |> makeReadOnlyCollection ] |> makeReadOnlyCollection else makeReadOnlyCollection [] @@ -1857,7 +1890,7 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item2) = let isInArg = HasFSharpAttribute cenv.g cenv.g.attrib_InAttribute argInfo.Attribs && isByrefTy cenv.g argty let isOutArg = HasFSharpAttribute cenv.g cenv.g.attrib_OutAttribute argInfo.Attribs && isByrefTy cenv.g argty let isOptionalArg = HasFSharpAttribute cenv.g cenv.g.attrib_OptionalArgumentAttribute argInfo.Attribs - yield FSharpParameter(cenv, argty, argInfo, x.DeclarationLocationOpt, isParamArrayArg, isInArg, isOutArg, isOptionalArg) ] + yield FSharpParameter(cenv, argty, argInfo, None, x.DeclarationLocationOpt, isParamArrayArg, isInArg, isOutArg, isOptionalArg) ] |> makeReadOnlyCollection ] |> makeReadOnlyCollection @@ -1865,37 +1898,32 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item2) = checkIsResolved() match d with | E e -> - // INCOMPLETENESS: Attribs is empty here, so we can't look at return attributes for .NET or F# methods - let retInfo: ArgReprInfo = { Name=None; Attribs= [] } + // INCOMPLETENESS: Attribs is empty here, so we can't look at return attributes for .NET or F# methods let rty = try PropTypOfEventInfo cenv.infoReader range0 AccessibleFromSomewhere e with _ -> // For non-standard events, just use the delegate type as the ReturnParameter type e.GetDelegateType(cenv.amap, range0) - - FSharpParameter(cenv, rty, retInfo, x.DeclarationLocationOpt, isParamArrayArg=false, isInArg=false, isOutArg=false, isOptionalArg=false) + FSharpParameter(cenv, rty, ValReprInfo.unnamedRetVal, x.DeclarationLocationOpt) | P p -> - // INCOMPLETENESS: Attribs is empty here, so we can't look at return attributes for .NET or F# methods - let retInfo: ArgReprInfo = { Name=None; Attribs= [] } + // INCOMPLETENESS: Attribs is empty here, so we can't look at return attributes for .NET or F# methods let rty = p.GetPropertyType(cenv.amap, range0) - FSharpParameter(cenv, rty, retInfo, x.DeclarationLocationOpt, isParamArrayArg=false, isInArg=false, isOutArg=false, isOptionalArg=false) + FSharpParameter(cenv, rty, ValReprInfo.unnamedRetVal, x.DeclarationLocationOpt) | M m | C m -> - // INCOMPLETENESS: Attribs is empty here, so we can't look at return attributes for .NET or F# methods - let retInfo: ArgReprInfo = { Name=None; Attribs= [] } + // INCOMPLETENESS: Attribs is empty here, so we can't look at return attributes for .NET or F# methods let rty = m.GetFSharpReturnTy(cenv.amap, range0, m.FormalMethodInst) - FSharpParameter(cenv, rty, retInfo, x.DeclarationLocationOpt, isParamArrayArg=false, isInArg=false, isOutArg=false, isOptionalArg=false) + FSharpParameter(cenv, rty, ValReprInfo.unnamedRetVal, x.DeclarationLocationOpt) | V v -> match v.ValReprInfo with | None -> let _, tau = v.TypeScheme let _argtysl, rty = stripFunTy cenv.g tau - let empty: ArgReprInfo = { Name=None; Attribs= [] } - FSharpParameter(cenv, rty, empty, x.DeclarationLocationOpt, isParamArrayArg=false, isInArg=false, isOutArg=false, isOptionalArg=false) + FSharpParameter(cenv, rty, ValReprInfo.unnamedRetVal, x.DeclarationLocationOpt) | Some (ValReprInfo(_typars, argInfos, retInfo)) -> let tau = v.TauType let _c, rty = GetTopTauTypeInFSharpForm cenv.g argInfos tau range0 - FSharpParameter(cenv, rty, retInfo, x.DeclarationLocationOpt, isParamArrayArg=false, isInArg=false, isOutArg=false, isOptionalArg=false) + FSharpParameter(cenv, rty, retInfo, x.DeclarationLocationOpt) member __.Attributes = @@ -1942,7 +1970,7 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item2) = /// How visible is this? member this.Accessibility: FSharpAccessibility = - if isUnresolved() then FSharpAccessibility(taccessPublic) else + if isUnresolved() then FSharpAccessibility taccessPublic else match fsharpInfo() with | Some v -> FSharpAccessibility(v.Accessibility) | None -> @@ -1950,7 +1978,7 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item2) = // Note, returning "public" is wrong for IL members that are private match d with | E e -> - // For IL events, we get an approximate accessiblity that at least reports "internal" as "internal" and "private" as "private" + // For IL events, we get an approximate accessibility that at least reports "internal" as "internal" and "private" as "private" let access = match e with | ILEvent ileinfo -> @@ -1958,10 +1986,10 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item2) = getApproxFSharpAccessibilityOfMember this.DeclaringEntity.Value.Entity ilAccess | _ -> taccessPublic - FSharpAccessibility(access) + FSharpAccessibility access | P p -> - // For IL properties, we get an approximate accessiblity that at least reports "internal" as "internal" and "private" as "private" + // For IL properties, we get an approximate accessibility that at least reports "internal" as "internal" and "private" as "private" let access = match p with | ILProp ilpinfo -> @@ -1969,17 +1997,17 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item2) = getApproxFSharpAccessibilityOfMember this.DeclaringEntity.Value.Entity ilAccess | _ -> taccessPublic - FSharpAccessibility(access) + FSharpAccessibility access | M m | C m -> - // For IL methods, we get an approximate accessiblity that at least reports "internal" as "internal" and "private" as "private" + // For IL methods, we get an approximate accessibility that at least reports "internal" as "internal" and "private" as "private" let access = match m with | ILMeth (_, x, _) -> getApproxFSharpAccessibilityOfMember x.DeclaringTyconRef x.RawMetadata.Access | _ -> taccessPublic - FSharpAccessibility(access, isProtected=m.IsProtectedAccessiblity) + FSharpAccessibility(access, isProtected=m.IsProtectedAccessibility) | V v -> FSharpAccessibility(v.Accessibility) @@ -2008,9 +2036,10 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item2) = match other with | :? FSharpMemberOrFunctionOrValue as other -> match d, other.Data with - | E evt1, E evt2 -> EventInfo.EventInfosUseIdenticalDefintions evt1 evt2 + | E evt1, E evt2 -> EventInfo.EventInfosUseIdenticalDefinitions evt1 evt2 | P p1, P p2 -> PropInfo.PropInfosUseIdenticalDefinitions p1 p2 - | M m1, M m2 -> MethInfo.MethInfosUseIdenticalDefinitions m1 m2 + | M m1, M m2 + | C m1, C m2 -> MethInfo.MethInfosUseIdenticalDefinitions m1 m2 | V v1, V v2 -> valRefEq cenv.g v1 v2 | _ -> false | _ -> false @@ -2019,13 +2048,13 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item2) = override x.ToString() = try let prefix = (if x.IsEvent then "event " elif x.IsProperty then "property " elif x.IsMember then "member " else "val ") - prefix + x.LogicalName + prefix + x.LogicalName with _ -> "??" member x.FormatLayout (denv:FSharpDisplayContext) = match x.IsMember, d with | true, V v -> - NicePrint.prettyLayoutOfValOrMemberNoInst { (denv.Contents cenv.g) with showMemberContainers=true } v.Deref + NicePrint.prettyLayoutOfMemberNoInstShort { (denv.Contents cenv.g) with showMemberContainers=true } v.Deref | _,_ -> checkIsResolved() let ty = @@ -2172,7 +2201,7 @@ and FSharpType(cenv, ty:TType) = member private x.V = ty member private x.cenv = cenv - member private ty.AdjustType(t) = + member private ty.AdjustType t = FSharpType(ty.cenv, t) // Note: This equivalence relation is modulo type abbreviations @@ -2220,12 +2249,12 @@ and FSharpType(cenv, ty:TType) = | h :: _ -> let cenv = h.cenv let prettyTys = PrettyTypes.PrettifyTypes cenv.g [ for t in xs -> t.V ] |> fst - (xs, prettyTys) ||> List.map2 (fun p pty -> p.AdjustType(pty)) + (xs, prettyTys) ||> List.map2 (fun p pty -> p.AdjustType pty) |> makeReadOnlyCollection static member Prettify(parameter: FSharpParameter) = let prettyTy = parameter.V |> PrettyTypes.PrettifyType parameter.cenv2.g |> fst - parameter.AdjustType(prettyTy) + parameter.AdjustType prettyTy static member Prettify(parameters: IList) = let parameters = parameters |> List.ofSeq @@ -2234,7 +2263,7 @@ and FSharpType(cenv, ty:TType) = | h :: _ -> let cenv = h.cenv2 let prettyTys = parameters |> List.map (fun p -> p.V) |> PrettyTypes.PrettifyTypes cenv.g |> fst - (parameters, prettyTys) ||> List.map2 (fun p pty -> p.AdjustType(pty)) + (parameters, prettyTys) ||> List.map2 (fun p pty -> p.AdjustType pty) |> makeReadOnlyCollection static member Prettify(parameters: IList>) = @@ -2245,15 +2274,15 @@ and FSharpType(cenv, ty:TType) = | Some h -> let cenv = h.cenv2 let prettyTys = xs |> List.mapSquared (fun p -> p.V) |> PrettyTypes.PrettifyCurriedTypes cenv.g |> fst - (xs, prettyTys) ||> List.map2 (List.map2 (fun p pty -> p.AdjustType(pty))) + (xs, prettyTys) ||> List.map2 (List.map2 (fun p pty -> p.AdjustType pty)) |> List.map makeReadOnlyCollection |> makeReadOnlyCollection static member Prettify(parameters: IList>, returnParameter: FSharpParameter) = let xs = parameters |> List.ofSeq |> List.map List.ofSeq let cenv = returnParameter.cenv2 let prettyTys, prettyRetTy = xs |> List.mapSquared (fun p -> p.V) |> (fun tys -> PrettyTypes.PrettifyCurriedSigTypes cenv.g (tys, returnParameter.V) )|> fst - let ps = (xs, prettyTys) ||> List.map2 (List.map2 (fun p pty -> p.AdjustType(pty))) |> List.map makeReadOnlyCollection |> makeReadOnlyCollection - ps, returnParameter.AdjustType(prettyRetTy) + let ps = (xs, prettyTys) ||> List.map2 (List.map2 (fun p pty -> p.AdjustType pty)) |> List.map makeReadOnlyCollection |> makeReadOnlyCollection + ps, returnParameter.AdjustType prettyRetTy and FSharpAttribute(cenv: SymbolEnv, attrib: AttribInfo) = @@ -2322,37 +2351,55 @@ and FSharpStaticParameter(cenv, sp: Tainted< ExtensionTyping.ProvidedParameterIn override x.Equals(other: obj) = box x === other || match other with - | :? FSharpStaticParameter as p -> x.Name = p.Name && x.DeclarationLocation = p.DeclarationLocation + | :? FSharpStaticParameter as p -> x.Name = p.Name && Range.equals x.DeclarationLocation p.DeclarationLocation | _ -> false override x.GetHashCode() = hash x.Name override x.ToString() = "static parameter " + x.Name #endif -and FSharpParameter(cenv, paramTy:TType, topArgInfo:ArgReprInfo, mOpt, isParamArrayArg, isInArg, isOutArg, isOptionalArg) = + +and FSharpParameter(cenv, paramTy: TType, topArgInfo: ArgReprInfo, ownerOpt, ownerRangeOpt, isParamArrayArg, isInArg, isOutArg, isOptionalArg) = inherit FSharpSymbol(cenv, (fun () -> - let m = match mOpt with Some m -> m | None -> range0 - Item.ArgName((match topArgInfo.Name with None -> mkSynId m "" | Some v -> v), paramTy, None)), + let m = defaultArg ownerRangeOpt range0 + let id = match topArgInfo.Name with | Some id -> id | None -> mkSynId m "" + Item.ArgName(id, paramTy, ownerOpt)), (fun _ _ _ -> true)) - let attribs = topArgInfo.Attribs - let idOpt = topArgInfo.Name - let m = match mOpt with Some m -> m | None -> range0 - member __.Name = match idOpt with None -> None | Some v -> Some v.idText + new (cenv, id, ty, container) = + let argInfo: ArgReprInfo = { Name = Some id; Attribs = [] } + FSharpParameter(cenv, ty, argInfo, container, None, false, false, false, false) + + new (cenv, ty, argInfo: ArgReprInfo, ownerRangeOpt) = + FSharpParameter(cenv, ty, argInfo, None, ownerRangeOpt, false, false, false, false) + + member __.Name = match topArgInfo.Name with None -> None | Some v -> Some v.idText member __.cenv2: SymbolEnv = cenv - member __.AdjustType(t) = FSharpParameter(cenv, t, topArgInfo, mOpt, isParamArrayArg, isInArg, isOutArg, isOptionalArg) + member __.AdjustType ty = FSharpParameter(cenv, ty, topArgInfo, ownerOpt, ownerRangeOpt, isParamArrayArg, isInArg, isOutArg, isOptionalArg) member __.Type: FSharpType = FSharpType(cenv, paramTy) member __.V = paramTy - member __.DeclarationLocation = match idOpt with None -> m | Some v -> v.idRange + member __.DeclarationLocation = + match topArgInfo.Name with + | Some v -> v.idRange + | None -> + + match ownerRangeOpt with + | Some m -> m + | None -> range0 + + member __.Owner = + match ownerOpt with + | Some (ArgumentContainer.Method minfo) -> Some (FSharpMemberOrFunctionOrValue (cenv, minfo) :> FSharpSymbol) + | _ -> None member __.Attributes = - attribs |> List.map (fun a -> FSharpAttribute(cenv, AttribInfo.FSAttribInfo(cenv.g, a))) |> makeReadOnlyCollection + topArgInfo.Attribs |> List.map (fun a -> FSharpAttribute(cenv, AttribInfo.FSAttribInfo(cenv.g, a))) |> makeReadOnlyCollection member __.IsParamArrayArg = isParamArrayArg @@ -2367,7 +2414,7 @@ and FSharpParameter(cenv, paramTy:TType, topArgInfo:ArgReprInfo, mOpt, isParamAr override x.Equals(other: obj) = box x === other || match other with - | :? FSharpParameter as p -> x.Name = p.Name && x.DeclarationLocation = p.DeclarationLocation + | :? FSharpParameter as p -> x.Name = p.Name && Range.equals x.DeclarationLocation p.DeclarationLocation | _ -> false override x.GetHashCode() = hash (box topArgInfo) @@ -2455,7 +2502,12 @@ and FSharpAssembly internal (cenv, ccu: CcuThunk) = member __.Contents : FSharpAssemblySignature = FSharpAssemblySignature(cenv, ccu) - override x.ToString() = ccu.ILScopeRef.QualifiedName + override x.ToString() = + match ccu.ILScopeRef with + | ILScopeRef.PrimaryAssembly -> + cenv.g.ilg.primaryAssemblyRef.QualifiedName + | scoref -> + scoref.QualifiedName /// Represents open declaration in F# code. [] @@ -2505,5 +2557,30 @@ type FSharpSymbolUse(g:TcGlobals, denv: DisplayEnv, symbol:FSharpSymbol, itemOcc member __.Range = Range.toZ range member __.RangeAlternate = range + + member this.IsPrivateToFile = + let isPrivate = + match this.Symbol with + | :? FSharpMemberOrFunctionOrValue as m -> not m.IsModuleValueOrMember || m.Accessibility.IsPrivate + | :? FSharpEntity as m -> m.Accessibility.IsPrivate + | :? FSharpGenericParameter -> true + | :? FSharpUnionCase as m -> m.Accessibility.IsPrivate + | :? FSharpField as m -> m.Accessibility.IsPrivate + | _ -> false + + let declarationLocation = + match this.Symbol.SignatureLocation with + | Some x -> Some x + | _ -> + match this.Symbol.DeclarationLocation with + | Some x -> Some x + | _ -> this.Symbol.ImplementationLocation + + let declaredInTheFile = + match declarationLocation with + | Some declRange -> declRange.FileName = this.RangeAlternate.FileName + | _ -> false + + isPrivate && declaredInTheFile override __.ToString() = sprintf "%O, %O, %O" symbol itemOcc range diff --git a/src/fcs-fable/src/fsharp/symbols/Symbols.fsi b/src/fcs-fable/src/fsharp/symbols/Symbols.fsi index bd5e0b188d..4f8313c791 100644 --- a/src/fcs-fable/src/fsharp/symbols/Symbols.fsi +++ b/src/fcs-fable/src/fsharp/symbols/Symbols.fsi @@ -3,21 +3,23 @@ namespace FSharp.Compiler.SourceCodeServices open System.Collections.Generic + open FSharp.Compiler open FSharp.Compiler.AccessibilityLogic open FSharp.Compiler.CompileOps open FSharp.Compiler.Import open FSharp.Compiler.InfoReader +open FSharp.Compiler.NameResolution open FSharp.Compiler.Range -open FSharp.Compiler.Ast -open FSharp.Compiler.Tast +open FSharp.Compiler.SyntaxTree +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals -open FSharp.Compiler.NameResolution // Implementation details used by other code in the compiler type internal SymbolEnv = - new: TcGlobals * thisCcu:CcuThunk * thisCcuTyp: ModuleOrNamespaceType option * tcImports: TcImports -> SymbolEnv - new: TcGlobals * thisCcu:CcuThunk * thisCcuTyp: ModuleOrNamespaceType option * tcImports: TcImports * amap: ImportMap * infoReader: InfoReader -> SymbolEnv + new: TcGlobals * thisCcu: CcuThunk * thisCcuTyp: ModuleOrNamespaceType option * tcImports: TcImports -> SymbolEnv + new: TcGlobals * thisCcu: CcuThunk * thisCcuTyp: ModuleOrNamespaceType option * tcImports: TcImports * amap: ImportMap * infoReader: InfoReader -> SymbolEnv member amap: ImportMap member g: TcGlobals @@ -25,17 +27,20 @@ type internal SymbolEnv = type public FSharpAccessibility = internal new: Accessibility * ?isProtected: bool -> FSharpAccessibility - /// Indicates the symbol has public accessibility - member IsPublic : bool + /// Indicates the symbol has public accessibility. + member IsPublic: bool + + /// Indicates the symbol has private accessibility. + member IsPrivate: bool - /// Indicates the symbol has private accessibility - member IsPrivate : bool + /// Indicates the symbol has internal accessibility. + member IsInternal: bool - /// Indicates the symbol has internal accessibility - member IsInternal : bool + /// Indicates the symbol has protected accessibility. + member IsProtected: bool /// The underlying Accessibility - member internal Contents : Accessibility + member internal Contents: Accessibility /// Represents the information needed to format types and other information in a style @@ -44,9 +49,11 @@ type public FSharpAccessibility = /// Acquired via GetDisplayEnvAtLocationAlternate and similar methods. May be passed /// to the Format method on FSharpType and other methods. type [] public FSharpDisplayContext = - internal new : denv: (TcGlobals -> Tastops.DisplayEnv) -> FSharpDisplayContext + internal new : denv: (TcGlobals -> DisplayEnv) -> FSharpDisplayContext static member Empty: FSharpDisplayContext + member WithShortTypeNames: bool -> FSharpDisplayContext + /// Represents a symbol in checked F# source code or a compiled .NET component. /// /// The subtype of the symbol may reveal further information and can be one of FSharpEntity, FSharpUnionCase @@ -82,7 +89,7 @@ type [] public FSharpSymbol = /// Return true if two symbols are effectively the same when referred to in F# source code text. /// This sees through signatures (a symbol in a signature will be considered effectively the same as - /// the matching symbol in an implementation). In addition, other equivalances are applied + /// the matching symbol in an implementation). In addition, other equivalences are applied /// when the same F# source text implies the same declaration name - for example, constructors /// are considered to be effectively the same symbol as the corresponding type definition. /// @@ -377,6 +384,9 @@ and [] public FSharpUnionCase = /// Get the range of the name of the case member DeclarationLocation : range + /// Indicates if the union case has field definitions + member HasFields: bool + /// Get the data carried by the case. member UnionCaseFields: IList @@ -432,6 +442,12 @@ and [] public FSharpField = /// If the field is from an anonymous record type then get the details of the field including the index in the sorted array of fields member AnonRecordFieldDetails: FSharpAnonRecordTypeDetails * FSharpType[] * int + /// Indicates if the field is declared in a union case + member IsUnionCaseField: bool + + /// Returns the declaring union case symbol + member DeclaringUnionCase: FSharpUnionCase option + /// Indicates if the field is declared 'static' member IsMutable: bool @@ -1057,7 +1073,7 @@ type public FSharpOpenDeclaration = type public FSharpSymbolUse = // For internal use only - internal new : g:TcGlobals * denv: Tastops.DisplayEnv * symbol:FSharpSymbol * itemOcc:ItemOccurence * range: range -> FSharpSymbolUse + internal new : g:TcGlobals * denv: DisplayEnv * symbol:FSharpSymbol * itemOcc:ItemOccurence * range: range -> FSharpSymbolUse /// The symbol referenced member Symbol : FSharpSymbol @@ -1093,3 +1109,5 @@ type public FSharpSymbolUse = /// The range of text representing the reference to the symbol member RangeAlternate: range + /// Indicates if the FSharpSymbolUse is declared as private + member IsPrivateToFile: bool diff --git a/src/fcs-fable/src/fsharp/tainted.fs b/src/fcs-fable/src/fsharp/tainted.fs old mode 100755 new mode 100644 index ebdc96c746..15d2378b3f --- a/src/fcs-fable/src/fsharp/tainted.fs +++ b/src/fcs-fable/src/fsharp/tainted.fs @@ -9,9 +9,6 @@ open FSharp.Compiler.Range open Microsoft.FSharp.Core.CompilerServices open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Library -open System.Reflection -open System.Collections.Generic -open ErrorLogger type internal TypeProviderError ( diff --git a/src/fcs-fable/src/fsharp/tainted.fsi b/src/fcs-fable/src/fsharp/tainted.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/ilx/EraseClosures.fs b/src/fcs-fable/src/ilx/EraseClosures.fs old mode 100755 new mode 100644 index ec419f425f..a7fe3b002b --- a/src/fcs-fable/src/ilx/EraseClosures.fs +++ b/src/fcs-fable/src/ilx/EraseClosures.fs @@ -2,18 +2,13 @@ module internal FSharp.Compiler.AbstractIL.Extensions.ILX.EraseClosures -open Internal.Utilities -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Extensions.ILX open FSharp.Compiler.AbstractIL.Extensions.ILX.Types -open FSharp.Compiler.AbstractIL.Extensions.ILX.IlxSettings open FSharp.Compiler.AbstractIL.Morphs open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.PrettyNaming -open System.Reflection // -------------------------------------------------------------------- // Erase closures and function types @@ -27,7 +22,7 @@ let rec stripUpTo n test dest x = if test x then let l, r = dest x let ls, res = stripUpTo (n-1) test dest r - (l::ls), res + (l :: ls), res else ([], x) // -------------------------------------------------------------------- @@ -116,12 +111,22 @@ let mkFuncTypeRef n = [IlxSettings.ilxNamespace () + ".OptimizedClosures"], "FSharpFunc`"+ string (n + 1)) type cenv = - { ilg:ILGlobals + { + ilg:ILGlobals + tref_Func: ILTypeRef[] + mkILTyFuncTy: ILType + addFieldGeneratedAttrs: ILFieldDef -> ILFieldDef + addFieldNeverAttrs: ILFieldDef -> ILFieldDef - addMethodGeneratedAttrs: ILMethodDef -> ILMethodDef } + + addMethodGeneratedAttrs: ILMethodDef -> ILMethodDef + } + + override __.ToString() = "" + let addMethodGeneratedAttrsToTypeDef cenv (tdef: ILTypeDef) = tdef.With(methods = (tdef.Methods.AsList |> List.map (fun md -> md |> cenv.addMethodGeneratedAttrs) |> mkILMethods)) @@ -231,7 +236,7 @@ let mkCallFunc cenv allocLocal numThisGenParams tl apps = let storers, (loaders2 : ILInstr list list) = unwind rest (List.rev (List.concat storers) : ILInstr list) , List.concat loaders2 else - stripUpTo n (function (_x::_y) -> true | _ -> false) (function (x::y) -> (x, y) | _ -> failwith "no!") loaders + stripUpTo n (function (_x :: _y) -> true | _ -> false) (function (x :: y) -> (x, y) | _ -> failwith "no!") loaders let rec buildApp fst loaders apps = // Strip off one valid indirect call. [fst] indicates if this is the @@ -369,7 +374,7 @@ let rec convIlxClosureDef cenv encl (td: ILTypeDef) clo = let fixupArg mkEnv mkArg n = let rec findMatchingArg l c = match l with - | ((m, _)::t) -> + | ((m, _) :: t) -> if n = m then mkEnv c else findMatchingArg t (c+1) | [] -> mkArg (n - argToFreeVarMap.Length + 1) diff --git a/src/fcs-fable/src/ilx/EraseClosures.fsi b/src/fcs-fable/src/ilx/EraseClosures.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/ilx/EraseUnions.fs b/src/fcs-fable/src/ilx/EraseUnions.fs old mode 100755 new mode 100644 index 5f4998f1c4..99af1becfd --- a/src/fcs-fable/src/ilx/EraseUnions.fs +++ b/src/fcs-fable/src/ilx/EraseUnions.fs @@ -9,10 +9,8 @@ module internal FSharp.Compiler.AbstractIL.Extensions.ILX.EraseUnions open System.Collections.Generic -open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.AbstractIL.Extensions.ILX open FSharp.Compiler.AbstractIL.Extensions.ILX.Types open System.Reflection @@ -587,13 +585,9 @@ let emitDataSwitch ilg (cg: ICodeGen<'Mark>) (avoidHelpers, cuspec, cases) = for (i,case) in cases do dict.[i] <- case let failLab = cg.GenerateDelayMark () let emitCase i _ = -#if FABLE_COMPILER - let ok, res = dict.TryGetValue(i) -#else - let mutable res = Unchecked.defaultof<_> - let ok = dict.TryGetValue(i, &res) -#endif - if ok then res else cg.CodeLabel failLab + match dict.TryGetValue i with + | true, res -> res + | _ -> cg.CodeLabel failLab let dests = Array.mapi emitCase cuspec.AlternativesArray cg.EmitInstrs (mkGetTag ilg cuspec) diff --git a/src/fcs-fable/src/ilx/EraseUnions.fsi b/src/fcs-fable/src/ilx/EraseUnions.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/ilx/ilxsettings.fs b/src/fcs-fable/src/ilx/ilxsettings.fs old mode 100755 new mode 100644 index 868a29d94e..2355a6b1b6 --- a/src/fcs-fable/src/ilx/ilxsettings.fs +++ b/src/fcs-fable/src/ilx/ilxsettings.fs @@ -2,28 +2,26 @@ module internal FSharp.Compiler.AbstractIL.Extensions.ILX.IlxSettings -open Internal.Utilities open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.Internal -open FSharp.Compiler.AbstractIL.Extensions.ILX type IlxCallImplementation = | VirtEntriesVirtCode //++GLOBAL MUTABLE STATE (concurrency-safe because assigned only during F# library compilation) -let ilxCompilingFSharpCoreLib = ref false +let mutable ilxCompilingFSharpCoreLib = false //++GLOBAL MUTABLE STATE (concurrency-safe because assigned only during F# library compilation) -let ilxFsharpCoreLibAssemRef = ref (None : ILAssemblyRef option) +let mutable ilxFsharpCoreLibAssemRef = None : ILAssemblyRef option /// Scope references for FSharp.Core.dll let ilxFsharpCoreLibScopeRef () = - if !ilxCompilingFSharpCoreLib then + if ilxCompilingFSharpCoreLib then ILScopeRef.Local else let assemblyRef = - match !ilxFsharpCoreLibAssemRef with + match ilxFsharpCoreLibAssemRef with | Some o -> o | None -> // The exact public key token and version used here don't actually matter, or shouldn't. diff --git a/src/fcs-fable/src/scripts/VerifyAllTranslations.fsx b/src/fcs-fable/src/scripts/VerifyAllTranslations.fsx deleted file mode 100644 index 24e2d4eebb..0000000000 --- a/src/fcs-fable/src/scripts/VerifyAllTranslations.fsx +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. - -// verifies that all translations in all .xlf files have `state="translated"`. - -#r "System.Xml.Linq" - -open System -open System.IO -open System.Xml.Linq - -// usage: fsi VerifyAllTranslations.fsx -- baseDirectory -let baseDirectory = - Environment.GetCommandLineArgs() - |> Seq.skipWhile ((<>) "--") - |> Seq.skip 1 - |> Seq.head - -let hasUntranslatedStrings (xlfFile:string) = - let doc = XDocument.Load(xlfFile) - let untranslatedStates = - doc.Root.Descendants() - |> Seq.filter (fun (elem:XElement) -> elem.Name.LocalName = "target") - |> Seq.map (fun (elem:XElement) -> elem.Attribute(XName.op_Implicit("state"))) - |> Seq.filter (isNull >> not) - |> Seq.map (fun (attr:XAttribute) -> attr.Value) - |> Seq.filter ((<>) "translated") - Seq.length untranslatedStates > 0 - -let filesWithMissingTranslations = - Directory.EnumerateFiles(baseDirectory, "*.xlf", SearchOption.AllDirectories) - |> Seq.filter (fun (file:string) -> file.EndsWith(".en.xlf") |> not) // the english baseline files are never translated - |> Seq.filter hasUntranslatedStrings - |> Seq.toList - -match filesWithMissingTranslations with -| [] -> printfn "All .xlf files have translations assigned." -| _ -> - printfn "The following .xlf files have untranslated strings (state != 'translated'):\n\t%s" (String.Join("\n\t", filesWithMissingTranslations)) - Environment.Exit(1) diff --git a/src/fcs-fable/src/scripts/scriptlib.fsx b/src/fcs-fable/src/scripts/scriptlib.fsx deleted file mode 100644 index f5f9276c49..0000000000 --- a/src/fcs-fable/src/scripts/scriptlib.fsx +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -// -// Scripting utilities -//========================================================================================= - -namespace global - -open System -open System.IO -open System.Text -open System.Diagnostics - -[] -module Scripting = - - let isNullOrEmpty s = String.IsNullOrEmpty s - - let executeProcess filename arguments = - let processWriteMessage (chan:TextWriter) (message:string) = - if message <> null then - chan.WriteLine(message) - printfn "%s %s" filename arguments - let info = ProcessStartInfo(Arguments=arguments, UseShellExecute=false, - RedirectStandardOutput=true, RedirectStandardError=true, - CreateNoWindow=true, FileName=filename) - let p = new Process(StartInfo=info) - p.OutputDataReceived.Add(fun x -> processWriteMessage stdout x.Data) - p.ErrorDataReceived.Add(fun x -> processWriteMessage stderr x.Data) - if p.Start() then - p.BeginOutputReadLine() - p.BeginErrorReadLine() - p.WaitForExit() - p.ExitCode - else - 0 - -#if INTERACTIVE - let argv = FSharp.Compiler.Interactive.Settings.fsi.CommandLineArgs |> Seq.skip 1 |> Seq.toArray - - let getCmdLineArgOptional (switchName: string) = - argv |> Array.filter(fun t -> t.StartsWith(switchName)) |> Array.map(fun t -> t.Remove(0, switchName.Length).Trim()) |> Array.tryHead - - let getCmdLineArg switchName defaultValue = - match getCmdLineArgOptional switchName with - | Some file -> file - | _ -> defaultValue - - let getCmdLineArgReqd switchName = - match getCmdLineArg switchName null with - | null -> failwith (sprintf "The argument %s is required" switchName) - | x -> x - - let getCmdLineExtraArgs isSwitch = argv |> Array.skipWhile isSwitch - -#endif - - let makeDirectory output = - if not (Directory.Exists(output)) then - Directory.CreateDirectory(output) |> ignore - - let (++) a b = Path.Combine(a,b) - - let getBasename (a:string) = Path.GetFileNameWithoutExtension a - let getFullPath (a:string) = Path.GetFullPath a - let getFilename (a:string) = Path.GetFileName a - let getDirectoryName (a:string) = Path.GetDirectoryName a - - let copyFile (source:string) dir = - let dest = - if not (Directory.Exists dir) then Directory.CreateDirectory dir |>ignore - let result = Path.Combine(dir, getFilename source) - result - //printfn "Copy %s --> %s" source dest - File.Copy(source, dest, true) - - let deleteDirectory output = - if Directory.Exists output then - Directory.Delete(output, true) - - - let log format = printfn format - - type FilePath = string - - type CmdResult = - | Success - | ErrorLevel of string * int - - type CmdArguments = - { RedirectOutput : (string -> unit) option - RedirectError : (string -> unit) option - RedirectInput : (StreamWriter -> unit) option } - - module Process = - - let processExePath baseDir (exe:string) = - if Path.IsPathRooted(exe) then exe - else - match getDirectoryName exe with - | "" -> exe - | _ -> Path.Combine(baseDir,exe) |> Path.GetFullPath - - let exec cmdArgs (workDir: FilePath) envs (path: FilePath) arguments = - - let exePath = path |> processExePath workDir - let processInfo = new ProcessStartInfo(exePath, arguments) - processInfo.CreateNoWindow <- true - processInfo.UseShellExecute <- false - processInfo.WorkingDirectory <- workDir - -#if !NET46 - ignore envs // work out what to do about this -#else - envs - |> Map.iter (fun k v -> processInfo.EnvironmentVariables.[k] <- v) -#endif - - let p = new Process() - p.EnableRaisingEvents <- true - p.StartInfo <- processInfo - let out = StringBuilder() - let err = StringBuilder() - - cmdArgs.RedirectOutput|> Option.iter (fun f -> - processInfo.RedirectStandardOutput <- true - p.OutputDataReceived.Add (fun ea -> - if ea.Data <> null then - out.Append(ea.Data + Environment.NewLine) |> ignore - f ea.Data) - ) - - cmdArgs.RedirectError |> Option.iter (fun f -> - processInfo.RedirectStandardError <- true - p.ErrorDataReceived.Add (fun ea -> - if ea.Data <> null then - err.Append(ea.Data + Environment.NewLine) |> ignore - f ea.Data) - ) - - cmdArgs.RedirectInput - |> Option.iter (fun _ -> p.StartInfo.RedirectStandardInput <- true) - - p.Start() |> ignore - - cmdArgs.RedirectOutput |> Option.iter (fun _ -> p.BeginOutputReadLine()) - cmdArgs.RedirectError |> Option.iter (fun _ -> p.BeginErrorReadLine()) - - cmdArgs.RedirectInput |> Option.iter (fun input -> - async { - let inputWriter = p.StandardInput - do! inputWriter.FlushAsync () |> Async.AwaitIAsyncResult |> Async.Ignore - input inputWriter - do! inputWriter.FlushAsync () |> Async.AwaitIAsyncResult |> Async.Ignore - inputWriter.Dispose () - } - |> Async.Start) - - p.WaitForExit() - - match p.ExitCode with - | 0 -> Success - | errCode -> - let msg = sprintf "Error running command '%s' with args '%s' in directory '%s'.\n---- stdout below --- \n%s\n---- stderr below --- \n%s " exePath arguments workDir (out.ToString()) (err.ToString()) - ErrorLevel (msg, errCode) - - type OutPipe (writer: TextWriter) = - member x.Post (msg:string) = lock writer (fun () -> writer.WriteLine(msg)) - interface System.IDisposable with - member __.Dispose() = writer.Flush() - - let redirectTo (writer: TextWriter) = new OutPipe (writer) - - let redirectToLog () = redirectTo System.Console.Out - -#if !FSHARP_SUITE_DRIVES_CORECLR_TESTS - let defaultPlatform = - match Environment.OSVersion.Platform, Environment.Is64BitOperatingSystem with - | PlatformID.MacOSX, true -> "osx.10.11-x64" - | PlatformID.Unix,true -> "ubuntu.14.04-x64" - | _, true -> "win7-x64" - | _, false -> "win7-x86" -#endif - - let executeProcessNoRedirect filename arguments = - let info = ProcessStartInfo(Arguments=arguments, UseShellExecute=false, - RedirectStandardOutput=true, RedirectStandardError=true,RedirectStandardInput=true, - CreateNoWindow=true, FileName=filename) - let p = new Process(StartInfo=info) - if p.Start() then - - async { try - let buffer = Array.zeroCreate 4096 - while not p.StandardOutput.EndOfStream do - let n = p.StandardOutput.Read(buffer, 0, buffer.Length) - if n > 0 then System.Console.Out.Write(buffer, 0, n) - with _ -> () } |> Async.Start - async { try - let buffer = Array.zeroCreate 4096 - while not p.StandardError.EndOfStream do - let n = p.StandardError.Read(buffer, 0, buffer.Length) - if n > 0 then System.Console.Error.Write(buffer, 0, n) - with _ -> () } |> Async.Start - async { try - while true do - let c = System.Console.In.ReadLine() - p.StandardInput.WriteLine(c) - with _ -> () } |> Async.Start - p.WaitForExit() - p.ExitCode - else - 0 diff --git a/src/fcs-fable/src/utils/CompilerLocationUtils.fs b/src/fcs-fable/src/utils/CompilerLocationUtils.fs old mode 100755 new mode 100644 index 55dcac8ccc..694fb3793c --- a/src/fcs-fable/src/utils/CompilerLocationUtils.fs +++ b/src/fcs-fable/src/utils/CompilerLocationUtils.fs @@ -1,36 +1,34 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. namespace Internal.Utilities + open System +open System.Diagnostics open System.IO open System.Reflection -open Microsoft.Win32 open System.Runtime.InteropServices +open Microsoft.Win32 +open Microsoft.FSharp.Core #nowarn "44" // ConfigurationSettings is obsolete but the new stuff is horribly complicated. module internal FSharpEnvironment = /// The F# version reported in the banner - let FSharpBannerVersion = "10.2.3 for F# 4.5" +#if LOCALIZATION_FSBUILD + let FSharpBannerVersion = FSBuild.SR.fSharpBannerVersion(FSharp.BuildProperties.fsProductVersion, FSharp.BuildProperties.fsLanguageVersion) +#else +#if LOCALIZATION_FSCOMP + let FSharpBannerVersion = FSComp.SR.fSharpBannerVersion(FSharp.BuildProperties.fsProductVersion, FSharp.BuildProperties.fsLanguageVersion) +#else + let FSharpBannerVersion = sprintf "%s for F# %s" (FSharp.BuildProperties.fsProductVersion) (FSharp.BuildProperties.fsLanguageVersion) +#endif +#endif let versionOf<'t> = -#if FX_RESHAPED_REFLECTION - let aq = (typeof<'t>).AssemblyQualifiedName - let version = - if aq <> null then - let x = aq.Split(',', ' ') |> Seq.filter(fun x -> x.StartsWith("Version=", StringComparison.OrdinalIgnoreCase)) |> Seq.tryHead - match x with - | Some(x) -> x.Substring(8) - | _ -> null - else - null - version -#else typeof<'t>.Assembly.GetName().Version.ToString() -#endif - let FSharpCoreLibRunningVersion = + let FSharpCoreLibRunningVersion = try match versionOf with | null -> None | "" -> None @@ -43,6 +41,9 @@ module internal FSharpEnvironment = // WARNING: Do not change this revision number unless you absolutely know what you're doing. let FSharpBinaryMetadataFormatRevision = "2.0.0.0" + let isRunningOnCoreClr = (typeof.Assembly).FullName.StartsWith("System.Private.CoreLib", StringComparison.InvariantCultureIgnoreCase) + + #if FX_NO_WIN_REGISTRY #else [] @@ -64,6 +65,7 @@ module internal FSharpEnvironment = // See: ndp\clr\src\BCL\System\IO\Path.cs let maxPath = 260; let maxDataLength = (new System.Text.UTF32Encoding()).GetMaxByteCount(maxPath) + #if FX_NO_WIN_REGISTRY #else let KEY_WOW64_DEFAULT = 0x0000 @@ -77,10 +79,11 @@ module internal FSharpEnvironment = (try downcast Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\\"+subKey,null,null) with e-> - System.Diagnostics.Debug.Assert(false, sprintf "Failed in GetDefaultRegistryStringValueViaDotNet: %s" (e.ToString())) +#if DEBUG + Debug.Assert(false, sprintf "Failed in GetDefaultRegistryStringValueViaDotNet: %s" (e.ToString())) +#endif null) - let Get32BitRegistryStringValueViaPInvoke(subKey:string) = Option.ofString (try @@ -120,16 +123,18 @@ module internal FSharpEnvironment = if pathResult <> IntPtr.Zero then Marshal.FreeCoTaskMem(pathResult) with e-> - System.Diagnostics.Debug.Assert(false, sprintf "Failed in Get32BitRegistryStringValueViaPInvoke: %s" (e.ToString())) +#if DEBUG + Debug.Assert(false, sprintf "Failed in Get32BitRegistryStringValueViaPInvoke: %s" (e.ToString())) +#endif null) let is32Bit = IntPtr.Size = 4 - + let runningOnMono = try System.Type.GetType("Mono.Runtime") <> null with e-> false let tryRegKey(subKey:string) = - //if we are runing on mono simply return None + //if we are running on mono simply return None // GetDefaultRegistryStringValueViaDotNet will result in an access denied by default, // and Get32BitRegistryStringValueViaPInvoke will fail due to Advapi32.dll not existing if runningOnMono then None else @@ -139,7 +144,7 @@ module internal FSharpEnvironment = // by comparing against the result from GetDefaultRegistryStringValueViaDotNet(...) #if DEBUG let viaPinvoke = Get32BitRegistryStringValueViaPInvoke(subKey) - System.Diagnostics.Debug.Assert((s = viaPinvoke), sprintf "32bit path: pi=%A def=%A" viaPinvoke s) + Debug.Assert((s = viaPinvoke), sprintf "32bit path: pi=%A def=%A" viaPinvoke s) #endif s else @@ -147,13 +152,9 @@ module internal FSharpEnvironment = #endif let internal tryCurrentDomain() = - let pathFromCurrentDomain = -#if FX_NO_APP_DOMAINS - System.AppContext.BaseDirectory -#else - System.AppDomain.CurrentDomain.BaseDirectory -#endif - if not(String.IsNullOrEmpty(pathFromCurrentDomain)) then + let pathFromCurrentDomain = + AppDomain.CurrentDomain.BaseDirectory + if not(String.IsNullOrEmpty(pathFromCurrentDomain)) then Some pathFromCurrentDomain else None @@ -163,14 +164,17 @@ module internal FSharpEnvironment = #else let internal tryAppConfig (_appConfigKey:string) = let locationFromAppConfig = System.Configuration.ConfigurationSettings.AppSettings.[_appConfigKey] - System.Diagnostics.Debug.Print(sprintf "Considering _appConfigKey %s which has value '%s'" _appConfigKey locationFromAppConfig) - +#if DEBUG + Debug.Print(sprintf "Considering _appConfigKey %s which has value '%s'" _appConfigKey locationFromAppConfig) +#endif if String.IsNullOrEmpty(locationFromAppConfig) then None else - let exeAssemblyFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + let exeAssemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) let locationFromAppConfig = locationFromAppConfig.Replace("{exepath}", exeAssemblyFolder) - System.Diagnostics.Debug.Print(sprintf "Using path %s" locationFromAppConfig) +#if DEBUG + Debug.Print(sprintf "Using path %s" locationFromAppConfig) +#endif Some locationFromAppConfig #endif @@ -181,45 +185,36 @@ module internal FSharpEnvironment = // - default F# binaries directory in service.fs (REVIEW: check this) // - default location of fsi.exe in FSharp.VS.FSI.dll (REVIEW: check this) // - default F# binaries directory in (project system) Project.fs - let BinFolderOfDefaultFSharpCompiler(probePoint:string option) = -#if FX_NO_WIN_REGISTRY - ignore probePoint -#if FX_NO_APP_DOMAINS - Some System.AppContext.BaseDirectory -#else - Some System.AppDomain.CurrentDomain.BaseDirectory -#endif -#else + let BinFolderOfDefaultFSharpCompiler(probePoint:string option) = // Check for an app.config setting to redirect the default compiler location // Like fsharp-compiler-location - try - // FSharp.Compiler support setting an appkey for compiler location. I've never seen this used. + try + // FSharp.Compiler support setting an appKey for compiler location. I've never seen this used. let result = tryAppConfig "fsharp-compiler-location" - match result with - | Some _ -> result + match result with + | Some _ -> result | None -> let safeExists f = (try File.Exists(f) with _ -> false) + // Look in the probePoint if given, e.g. look for a compiler alongside of FSharp.Build.dll match probePoint with | Some p when safeExists (Path.Combine(p,"FSharp.Core.dll")) -> Some p - | _ -> - // We let you set FSHARP_COMPILER_BIN. I've rarely seen this used and its not documented in the install instructions. - let result = System.Environment.GetEnvironmentVariable("FSHARP_COMPILER_BIN") - if not (String.IsNullOrEmpty(result)) then - Some result - else - // For the prototype compiler, we can just use the current domain - tryCurrentDomain() - with e -> - System.Diagnostics.Debug.Assert(false, "Error while determining default location of F# compiler") - None - + | _ -> + // We let you set FSHARP_COMPILER_BIN. I've rarely seen this used and its not documented in the install instructions. + let result = Environment.GetEnvironmentVariable("FSHARP_COMPILER_BIN") + if not (String.IsNullOrEmpty(result)) then + Some result + else + // For the prototype compiler, we can just use the current domain + tryCurrentDomain() + with e -> None - // Apply the given function to the registry entry corresponding to the subkey. +#if !FX_NO_WIN_REGISTRY + // Apply the given function to the registry entry corresponding to the subKey. // The reg key is disposed at the end of the scope. - let useKey subkey f = - let key = Registry.LocalMachine.OpenSubKey subkey + let useKey subKey f = + let key = Registry.LocalMachine.OpenSubKey subKey try f key finally match key with @@ -227,12 +222,12 @@ module internal FSharpEnvironment = | _ -> key.Dispose() // Check if the framework version 4.5 or above is installed at the given key entry - let IsNetFx45OrAboveInstalledAt subkey = + let IsNetFx45OrAboveInstalledAt subKey = try - useKey subkey (fun regkey -> - match regkey with + useKey subKey (fun regKey -> + match regKey with | null -> false - | _ -> regkey.GetValue("Release", 0) :?> int |> (fun s -> s >= 0x50000)) // 0x50000 implies 4.5.0 + | _ -> regKey.GetValue("Release", 0) :?> int |> (fun s -> s >= 0x50000)) // 0x50000 implies 4.5.0 with _ -> false // Check if the framework version 4.5 or above is installed @@ -240,7 +235,7 @@ module internal FSharpEnvironment = IsNetFx45OrAboveInstalledAt @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Client" || IsNetFx45OrAboveInstalledAt @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" || runningOnMono - + // Check if the running framework version is 4.5 or above. // Use the presence of v4.5.x in the registry to distinguish between 4.0 and 4.5 let IsRunningOnNetFx45OrAbove = @@ -249,3 +244,108 @@ module internal FSharpEnvironment = major > 4 || (major = 4 && IsNetFx45OrAboveInstalled) #endif + + // Specify the tooling-compatible fragments of a path such as: + // typeproviders/fsharp41/net461/MyProvider.DesignTime.dll + // tools/fsharp41/net461/MyProvider.DesignTime.dll + // See https://github.com/Microsoft/visualfsharp/issues/3736 + + // Represents the F#-compiler <-> type provider protocol. + // When the API or protocol updates, add a new version moniker to the front of the list here. + let toolingCompatibleTypeProviderProtocolMonikers() = + [ "fsharp41" ] + + // Detect the host tooling context + let toolingCompatibleVersions = + if typeof.Assembly.GetName().Name = "mscorlib" then + [| "net48"; "net472"; "net471";"net47";"net462";"net461"; "net452"; "net451"; "net45"; "netstandard2.0" |] + elif typeof.Assembly.GetName().Name = "System.Private.CoreLib" then + [| "netcoreapp3.1"; "netcoreapp3.0"; "netstandard2.1"; "netcoreapp2.2"; "netcoreapp2.1"; "netcoreapp2.0"; "netstandard2.0" |] + else + System.Diagnostics.Debug.Assert(false, "Couldn't determine runtime tooling context, assuming it supports at least .NET Standard 2.0") + [| "netstandard2.0" |] + + let toolPaths = [| "tools"; "typeproviders" |] + + let toolingCompatiblePaths() = [ + for toolPath in toolPaths do + for protocol in toolingCompatibleTypeProviderProtocolMonikers() do + for netRuntime in toolingCompatibleVersions do + yield Path.Combine(toolPath, protocol, netRuntime) + ] + + let rec searchToolPaths path compilerToolPaths = + seq { + let searchToolPath path = + seq { + yield path + for toolPath in toolingCompatiblePaths() do + yield Path.Combine (path, toolPath) + } + + for toolPath in compilerToolPaths do + yield! searchToolPath toolPath + + match path with + | None -> () + | Some path -> yield! searchToolPath path + } + + let getTypeProviderAssembly (runTimeAssemblyFileName: string, designTimeAssemblyName: string, compilerToolPaths: string list, raiseError) = + // Find and load the designer assembly for the type provider component. + // We look in the directories stepping up from the location of the runtime assembly. + let loadFromLocation designTimeAssemblyPath = + try + Some (Assembly.UnsafeLoadFrom designTimeAssemblyPath) + with e -> + raiseError e + + let rec searchParentDirChain path assemblyName = + seq { + match path with + | None -> () + | Some (p:string) -> + match Path.GetDirectoryName(p) with + | s when s = "" || s = null || Path.GetFileName(p) = "packages" || s = p -> () + | parentDir -> yield! searchParentDirChain (Some parentDir) assemblyName + + for p in searchToolPaths path compilerToolPaths do + let fileName = Path.Combine (p, assemblyName) + if File.Exists fileName then yield fileName + } + + let loadFromParentDirRelativeToRuntimeAssemblyLocation designTimeAssemblyName = + let runTimeAssemblyPath = Path.GetDirectoryName runTimeAssemblyFileName + let paths = searchParentDirChain (Some runTimeAssemblyPath) designTimeAssemblyName + paths + |> Seq.tryHead + |> function + | Some res -> loadFromLocation res + | None -> + // The search failed, just load from the first location and report an error + let runTimeAssemblyPath = Path.GetDirectoryName runTimeAssemblyFileName + loadFromLocation (Path.Combine (runTimeAssemblyPath, designTimeAssemblyName)) + + if designTimeAssemblyName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) then + loadFromParentDirRelativeToRuntimeAssemblyLocation designTimeAssemblyName + else + // Cover the case where the ".dll" extension has been left off and no version etc. has been used in the assembly + // string specification. The Name=FullName comparison is particularly strange, and was there to support + // design-time DLLs specified using "x.DesignTIme, Version= ..." long assembly names and GAC loads. + // These kind of design-time assembly specifications are no longer used to our knowledge so that comparison is basically legacy + // and will always succeed. + let name = AssemblyName (Path.GetFileNameWithoutExtension designTimeAssemblyName) + if name.Name.Equals(name.FullName, StringComparison.OrdinalIgnoreCase) then + let designTimeFileName = designTimeAssemblyName + ".dll" + loadFromParentDirRelativeToRuntimeAssemblyLocation designTimeFileName + else + // Load from the GAC using Assembly.Load. This is legacy since type provider design-time components are + // never in the GAC these days and "x.DesignTIme, Version= ..." specifications are never used. + try + let name = AssemblyName designTimeAssemblyName + Some (Assembly.Load (name)) + with e -> + raiseError e + + let getCompilerToolsDesignTimeAssemblyPaths compilerToolPaths = + searchToolPaths None compilerToolPaths diff --git a/src/fcs-fable/src/utils/EditDistance.fs b/src/fcs-fable/src/utils/EditDistance.fs index 503662400f..bd66352d44 100644 --- a/src/fcs-fable/src/utils/EditDistance.fs +++ b/src/fcs-fable/src/utils/EditDistance.fs @@ -4,7 +4,6 @@ module internal Internal.Utilities.EditDistance open System -open System.Collections.Generic /// Given an offset and a radius from that offset, does mChar exist in that part of str? let inline existsInWin (mChar: char) (str: string) (offset: int) (rad: int) = diff --git a/src/fcs-fable/src/utils/HashMultiMap.fs b/src/fcs-fable/src/utils/HashMultiMap.fs old mode 100755 new mode 100644 index f04948e2ba..924e31cffa --- a/src/fcs-fable/src/utils/HashMultiMap.fs +++ b/src/fcs-fable/src/utils/HashMultiMap.fs @@ -2,45 +2,36 @@ namespace Internal.Utilities.Collections -open System open System.Collections.Generic open Microsoft.FSharp.Collections // Each entry in the HashMultiMap dictionary has at least one entry. Under normal usage each entry has _only_ // one entry. So use two hash tables: one for the main entries and one for the overflow. [] -type internal HashMultiMap<'Key,'Value>(n: int, hasheq: IEqualityComparer<'Key>) = +type internal HashMultiMap<'Key,'Value>(n: int, hashEq: IEqualityComparer<'Key>) = - let firstEntries = Dictionary<_,_>(n,hasheq) + let firstEntries = Dictionary<_,_>(n,hashEq) - let rest = Dictionary<_,_>(3,hasheq) + let rest = Dictionary<_,_>(3,hashEq) #if !FABLE_COMPILER - new (hasheq : IEqualityComparer<'Key>) = HashMultiMap<'Key,'Value>(11, hasheq) + new (hashEq : IEqualityComparer<'Key>) = HashMultiMap<'Key,'Value>(11, hashEq) - new (seq : seq<'Key * 'Value>, hasheq : IEqualityComparer<'Key>) as x = - new HashMultiMap<'Key,'Value>(11, hasheq) + new (seq : seq<'Key * 'Value>, hashEq : IEqualityComparer<'Key>) as x = + new HashMultiMap<'Key,'Value>(11, hashEq) then seq |> Seq.iter (fun (k,v) -> x.Add(k,v)) #endif member x.GetRest(k) = -#if FABLE_COMPILER - let ok, res = rest.TryGetValue(k) -#else - let mutable res = [] - let ok = rest.TryGetValue(k,&res) -#endif - if ok then res else [] + match rest.TryGetValue k with + | true, res -> res + | _ -> [] member x.Add(y,z) = -#if FABLE_COMPILER - let ok, res = firstEntries.TryGetValue(y) -#else - let mutable res = Unchecked.defaultof<'Value> - let ok = firstEntries.TryGetValue(y,&res) -#endif - if ok then + match firstEntries.TryGetValue y with + | true, res -> rest.[y] <- res :: x.GetRest(y) + | _ -> () firstEntries.[y] <- z member x.Clear() = @@ -53,7 +44,7 @@ type internal HashMultiMap<'Key,'Value>(n: int, hasheq: IEqualityComparer<'Key>) member x.Copy() = #if FABLE_COMPILER - let res = HashMultiMap<'Key,'Value>(firstEntries.Count, hasheq) + let res = HashMultiMap<'Key,'Value>(firstEntries.Count, hashEq) #else let res = HashMultiMap<'Key,'Value>(firstEntries.Count,firstEntries.Comparer) #endif @@ -66,24 +57,16 @@ type internal HashMultiMap<'Key,'Value>(n: int, hasheq: IEqualityComparer<'Key>) member x.Item with get(y : 'Key) = -#if FABLE_COMPILER - let ok, res = firstEntries.TryGetValue(y) -#else - let mutable res = Unchecked.defaultof<'Value> - let ok = firstEntries.TryGetValue(y,&res) -#endif - if ok then res else raise (KeyNotFoundException("The item was not found in collection")) + match firstEntries.TryGetValue y with + | true, res -> res + | _ -> raise (KeyNotFoundException("The item was not found in collection")) and set (y:'Key) (z:'Value) = x.Replace(y,z) member x.FindAll(y) = -#if FABLE_COMPILER - let ok, res = firstEntries.TryGetValue(y) -#else - let mutable res = Unchecked.defaultof<'Value> - let ok = firstEntries.TryGetValue(y,&res) -#endif - if ok then res :: x.GetRest(y) else [] + match firstEntries.TryGetValue y with + | true, res -> res :: x.GetRest(y) + | _ -> [] member x.Fold f acc = let mutable res = acc @@ -110,45 +93,32 @@ type internal HashMultiMap<'Key,'Value>(n: int, hasheq: IEqualityComparer<'Key>) member x.ContainsKey(y) = firstEntries.ContainsKey(y) member x.Remove(y) = -#if FABLE_COMPILER - let ok, _ = firstEntries.TryGetValue(y) -#else - let mutable res = Unchecked.defaultof<'Value> - let ok = firstEntries.TryGetValue(y,&res) -#endif + match firstEntries.TryGetValue y with // NOTE: If not ok then nothing to remove - nop - if ok then + | true, _res -> // We drop the FirstEntry. Here we compute the new FirstEntry and residue MoreEntries -#if FABLE_COMPILER - let ok, res = rest.TryGetValue(y) -#else - let mutable res = [] - let ok = rest.TryGetValue(y,&res) -#endif - if ok then + match rest.TryGetValue y with + | true, res -> match res with | [h] -> firstEntries.[y] <- h; rest.Remove(y) |> ignore - | (h::t) -> + | (h :: t) -> firstEntries.[y] <- h rest.[y] <- t | _ -> () - else + | _ -> firstEntries.Remove(y) |> ignore + | _ -> () member x.Replace(y,z) = firstEntries.[y] <- z member x.TryFind(y) = -#if FABLE_COMPILER - let ok, res = firstEntries.TryGetValue(y) -#else - let mutable res = Unchecked.defaultof<'Value> - let ok = firstEntries.TryGetValue(y,&res) -#endif - if ok then Some(res) else None + match firstEntries.TryGetValue y with + | true, res -> Some res + | _ -> None member x.Count = firstEntries.Count @@ -166,6 +136,7 @@ type internal HashMultiMap<'Key,'Value>(n: int, hasheq: IEqualityComparer<'Key>) } elems.GetEnumerator() #else //!FABLE_COMPILER + interface IEnumerable> with member s.GetEnumerator() = diff --git a/src/fcs-fable/src/utils/HashMultiMap.fsi b/src/fcs-fable/src/utils/HashMultiMap.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/utils/PathMap.fs b/src/fcs-fable/src/utils/PathMap.fs new file mode 100644 index 0000000000..cda4520ff5 --- /dev/null +++ b/src/fcs-fable/src/utils/PathMap.fs @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +/// Functions to map real paths to paths to be written to PDB/IL +namespace Internal.Utilities + +open System +open System.IO + +type PathMap = PathMap of Map + +[] +module internal PathMap = + + let dirSepStr = Path.DirectorySeparatorChar.ToString() + + let empty = PathMap Map.empty + + let addMapping (src : string) (dst : string) (PathMap map) : PathMap = + // Normalise the path +#if FABLE_COMPILER + let normalSrc = src // no file system +#else + let normalSrc = Path.GetFullPath src +#endif + + let oldPrefix = + if normalSrc.EndsWith dirSepStr then normalSrc + else normalSrc + dirSepStr + + // Always add a path separator + map |> Map.add oldPrefix dst |> PathMap + + // Map a file path with its replacement. + // This logic replicates C#'s PathUtilities.NormalizePathPrefix + let apply (PathMap map) (filePath : string) : string = + // Find the first key in the path map that matches a prefix of the + // normalized path. We expect the client to use consistent capitalization; + // we use ordinal (case-sensitive) comparisons. + map + |> Map.tryPick (fun oldPrefix replacementPrefix -> + // 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 filename /goooo + if filePath.StartsWith(oldPrefix, StringComparison.Ordinal) then + let replacement = replacementPrefix + filePath.Substring (oldPrefix.Length - 1) + + // Normalize the path separators if used uniformly in the replacement + let hasSlash = replacementPrefix.IndexOf '/' >= 0 + let hasBackslash = replacementPrefix.IndexOf '\\' >= 0 + + if hasSlash && not hasBackslash then replacement.Replace('\\', '/') + elif hasBackslash && not hasSlash then replacement.Replace('/', '\\') + else replacement + |> Some + else + None + ) + |> Option.defaultValue filePath + + let applyDir pathMap (dirName : string) : string = + if dirName.EndsWith dirSepStr then apply pathMap dirName + else + let mapped = apply pathMap (dirName + dirSepStr) + mapped.TrimEnd (Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) diff --git a/src/fcs-fable/src/utils/PathMap.fsi b/src/fcs-fable/src/utils/PathMap.fsi new file mode 100644 index 0000000000..8cf4e2f248 --- /dev/null +++ b/src/fcs-fable/src/utils/PathMap.fsi @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +/// Functions to map real paths to paths to be written to PDB/IL +namespace Internal.Utilities + +type PathMap + +[] +module internal PathMap = + + val empty : PathMap + + /// Add a path mapping to the map. + val addMapping : string -> string -> PathMap -> PathMap + + /// Map a file path with its replacement. + /// Prefixes are compared case sensitively. + val apply : PathMap -> string -> string + + /// Map a directory name with its replacement. + /// Prefixes are compared case sensitively. + val applyDir : PathMap -> string -> string diff --git a/src/fcs-fable/src/utils/ResizeArray.fs b/src/fcs-fable/src/utils/ResizeArray.fs old mode 100755 new mode 100644 index 6661304434..597f37d16b --- a/src/fcs-fable/src/utils/ResizeArray.fs +++ b/src/fcs-fable/src/utils/ResizeArray.fs @@ -58,7 +58,7 @@ module internal ResizeArray = let res = new ResizeArray<_>(len) let rec add = function | [] -> () - | e::l -> res.Add(e); add l + | e :: l -> res.Add(e); add l add l res diff --git a/src/fcs-fable/src/utils/ResizeArray.fsi b/src/fcs-fable/src/utils/ResizeArray.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/utils/TaggedCollections.fs b/src/fcs-fable/src/utils/TaggedCollections.fs old mode 100755 new mode 100644 index efe059acda..f7bb0fbbf8 --- a/src/fcs-fable/src/utils/TaggedCollections.fs +++ b/src/fcs-fable/src/utils/TaggedCollections.fs @@ -7,12 +7,8 @@ namespace Internal.Utilities.Collections.Tagged #nowarn "60" // override implementations in augmentations open Microsoft.FSharp.Core - open Microsoft.FSharp.Core.Operators open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators - open System open System.Collections.Generic - open Internal.Utilities - open Internal.Utilities.Collections [] @@ -482,15 +478,15 @@ namespace Internal.Utilities.Collections.Tagged not stack.IsEmpty let toSeq s = - let i = ref (SetIterator s) + let mutable i = SetIterator s { new IEnumerator<_> with - member __.Current = (!i).Current + member _.Current = i.Current interface System.Collections.IEnumerator with - member __.Current = box (!i).Current - member __.MoveNext() = (!i).MoveNext() - member __.Reset() = i := SetIterator s + member _.Current = box i.Current + member _.MoveNext() = i.MoveNext() + member _.Reset() = i <- SetIterator s interface System.IDisposable with - member __.Dispose() = () } + member _.Dispose() = () } //-------------------------------------------------------------------------- // Set comparison. This can be expensive. @@ -549,8 +545,8 @@ namespace Internal.Utilities.Collections.Tagged loop s [] let copyToArray s (arr: _[]) i = - let j = ref i - iter (fun x -> arr.[!j] <- x; j := !j + 1) s + let mutable j = i + iter (fun x -> arr.[j] <- x; j <- j + 1) s let toArray s = let n = (count s) @@ -1027,8 +1023,8 @@ namespace Internal.Utilities.Collections.Tagged mkFromEnumerator comparer empty ie let copyToArray s (arr: _[]) i = - let j = ref i - s |> iter (fun x y -> arr.[!j] <- KeyValuePair(x,y); j := !j + 1) + let mutable j = i + s |> iter (fun x y -> arr.[j] <- KeyValuePair(x,y); j <- j + 1) /// Imperative left-to-right iterators. @@ -1086,13 +1082,13 @@ namespace Internal.Utilities.Collections.Tagged not stack.IsEmpty let toSeq s = - let i = ref (MapIterator(s)) + let mutable i = MapIterator(s) { new IEnumerator<_> with - member self.Current = (!i).Current + member self.Current = i.Current interface System.Collections.IEnumerator with - member self.Current = box (!i).Current - member self.MoveNext() = (!i).MoveNext() - member self.Reset() = i := MapIterator(s) + member self.Current = box i.Current + member self.MoveNext() = i.MoveNext() + member self.Reset() = i <- MapIterator(s) interface System.IDisposable with member self.Dispose() = ()} diff --git a/src/fcs-fable/src/utils/TaggedCollections.fsi b/src/fcs-fable/src/utils/TaggedCollections.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/utils/filename.fs b/src/fcs-fable/src/utils/filename.fs old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/utils/filename.fsi b/src/fcs-fable/src/utils/filename.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/utils/prim-lexing.fs b/src/fcs-fable/src/utils/prim-lexing.fs old mode 100755 new mode 100644 index 25e1b0a7dd..040ad5840b --- a/src/fcs-fable/src/utils/prim-lexing.fs +++ b/src/fcs-fable/src/utils/prim-lexing.fs @@ -2,12 +2,123 @@ #nowarn "47" // recursive initialization of LexBuffer +namespace FSharp.Compiler.Text + +open System +open System.IO + +type ISourceText = + + abstract Item : int -> char with get + + abstract GetLineString : lineIndex: int -> string + + abstract GetLineCount : unit -> int + + abstract GetLastCharacterPosition : unit -> int * int + + abstract GetSubTextString : start: int * length: int -> string + + abstract SubTextEquals : target: string * startIndex: int -> bool + + abstract Length : int + + abstract ContentEquals : sourceText: ISourceText -> bool + + abstract CopyTo : sourceIndex: int * destination: char [] * destinationIndex: int * count: int -> unit + +[] +type StringText(str: string) = + + let getLines (str: string) = +#if FABLE_COMPILER + System.Text.RegularExpressions.Regex.Split(str, "\r\n|\r|\n"); +#else + use reader = new StringReader(str) + [| + let mutable line = reader.ReadLine() + while not (isNull line) do + yield line + line <- reader.ReadLine() + if str.EndsWith("\n", StringComparison.Ordinal) then + // last trailing space not returned + // http://stackoverflow.com/questions/19365404/stringreader-omits-trailing-linebreak + yield String.Empty + |] +#endif + + let getLines = + // This requires allocating and getting all the lines. + // However, likely whoever is calling it is using a different implementation of ISourceText + // So, it's ok that we do this for now. + lazy getLines str + + member __.String = str + + override __.GetHashCode() = str.GetHashCode() + override __.Equals(obj: obj) = str.Equals(obj) + + interface ISourceText with + + member __.Item with get index = str.[index] + + member __.GetLastCharacterPosition() = + let lines = getLines.Value + if lines.Length > 0 then + (lines.Length, lines.[lines.Length - 1].Length) + else + (0, 0) + + member __.GetLineString(lineIndex) = + getLines.Value.[lineIndex] + + member __.GetLineCount() = getLines.Value.Length + + member __.GetSubTextString(start, length) = + str.Substring(start, length) + + member __.SubTextEquals(target, startIndex) = + if startIndex < 0 || startIndex >= str.Length then + invalidArg "startIndex" "Out of range." + + if String.IsNullOrEmpty(target) then + invalidArg "target" "Is null or empty." + + let lastIndex = startIndex + target.Length + if lastIndex <= startIndex || lastIndex >= str.Length then + invalidArg "target" "Too big." + +#if FABLE_COMPILER + str.IndexOf(target, startIndex) <> -1 +#else + str.IndexOf(target, startIndex, target.Length) <> -1 +#endif + + member __.Length = str.Length + + member this.ContentEquals(sourceText) = + match sourceText with + | :? StringText as sourceText when sourceText = this || sourceText.String = str -> true + | _ -> false + + member __.CopyTo(sourceIndex, destination, destinationIndex, count) = +#if FABLE_COMPILER + Array.blit (str.ToCharArray()) sourceIndex destination destinationIndex count +#else + str.CopyTo(sourceIndex, destination, destinationIndex, count) +#endif + +module SourceText = + + let ofString str = StringText(str) :> ISourceText // NOTE: the code in this file is a drop-in replacement runtime for Lexing.fs from the FsLexYacc repository namespace Internal.Utilities.Text.Lexing + open FSharp.Compiler.Text open Microsoft.FSharp.Core open Microsoft.FSharp.Collections + open FSharp.Compiler.Features open System.Collections.Generic [] @@ -70,11 +181,17 @@ namespace Internal.Utilities.Text.Lexing 0, 0) - type internal LexBufferFiller<'Char> = (LexBuffer<'Char> -> unit) - +#if FABLE_COMPILER + type internal LexBufferChar = uint16 +#else + type internal LexBufferChar = char +#endif + + type internal LexBufferFiller<'Char> = (LexBuffer<'Char> -> unit) + and [] - internal LexBuffer<'Char>(filler: LexBufferFiller<'Char>) = - let context = new Dictionary(1) + internal LexBuffer<'Char>(filler: LexBufferFiller<'Char>, supportsFeature:LanguageFeature -> bool) = + let context = new Dictionary(1) let mutable buffer = [||] /// number of valid characters beyond bufferScanStart. let mutable bufferMaxScanLength = 0 @@ -97,8 +214,7 @@ namespace Internal.Utilities.Text.Lexing Array.blit keep 0 buffer 0 nkeep bufferScanStart <- 0 bufferMaxScanLength <- nkeep - - + member lexbuf.EndOfScan () : int = //Printf.eprintf "endOfScan, lexBuffer.lexemeLength = %d\n" lexBuffer.lexemeLength; if bufferAcceptAction < 0 then @@ -113,14 +229,14 @@ namespace Internal.Utilities.Text.Lexing member lexbuf.StartPos with get() = startPos and set b = startPos <- b - + member lexbuf.EndPos with get() = endPos and set b = endPos <- b member lexbuf.Lexeme = Array.sub buffer bufferScanStart lexemeLength member lexbuf.LexemeChar(n) = buffer.[n+bufferScanStart] - + member lexbuf.BufferLocalStore = (context :> IDictionary<_,_>) member lexbuf.LexemeLength with get() : int = lexemeLength and set v = lexemeLength <- v member lexbuf.Buffer with get() : 'Char[] = buffer and set v = buffer <- v @@ -147,48 +263,66 @@ namespace Internal.Utilities.Text.Lexing member x.BufferScanPos = bufferScanStart + bufferScanLength member lexbuf.EnsureBufferSize n = - if lexbuf.BufferScanPos + n >= buffer.Length then - let repl = Array.zeroCreate (lexbuf.BufferScanPos + n) + if lexbuf.BufferScanPos + n >= buffer.Length then + let repl = Array.zeroCreate (lexbuf.BufferScanPos + n) Array.blit buffer bufferScanStart repl bufferScanStart bufferScanLength buffer <- repl + member __.SupportsFeature featureId = supportsFeature featureId - static member FromFunction (f : 'Char[] * int * int -> int) : LexBuffer<'Char> = + static member FromFunction (supportsFeature:LanguageFeature -> bool, f : 'Char[] * int * int -> int) : LexBuffer<'Char> = let extension= Array.zeroCreate 4096 let filler (lexBuffer: LexBuffer<'Char>) = let n = f (extension,0,extension.Length) lexBuffer.EnsureBufferSize n Array.blit extension 0 lexBuffer.Buffer lexBuffer.BufferScanPos n lexBuffer.BufferMaxScanLength <- lexBuffer.BufferScanLength + n - new LexBuffer<'Char>(filler) - + new LexBuffer<'Char>(filler, supportsFeature) + // Important: This method takes ownership of the array - static member FromArrayNoCopy (buffer: 'Char[]) : LexBuffer<'Char> = - let lexBuffer = new LexBuffer<'Char>(fun _ -> ()) + static member FromArrayNoCopy (supportsFeature:LanguageFeature -> bool, buffer: 'Char[]) : LexBuffer<'Char> = + let lexBuffer = new LexBuffer<'Char>((fun _ -> ()), supportsFeature) lexBuffer.Buffer <- buffer lexBuffer.BufferMaxScanLength <- buffer.Length lexBuffer // Important: this method does copy the array - static member FromArray (s: 'Char[]) : LexBuffer<'Char> = + static member FromArray (supportsFeature: LanguageFeature -> bool, s: 'Char[]) : LexBuffer<'Char> = let buffer = Array.copy s - LexBuffer<'Char>.FromArrayNoCopy buffer + LexBuffer<'Char>.FromArrayNoCopy(supportsFeature, buffer) - static member FromString (s: string) = + // Important: This method takes ownership of the array + static member FromChars (supportsFeature:LanguageFeature -> bool, arr:LexBufferChar[]) = LexBuffer.FromArrayNoCopy (supportsFeature, arr) + + static member FromSourceText (supportsFeature: LanguageFeature -> bool, sourceText: ISourceText) = #if FABLE_COMPILER - let arr = Array.init s.Length (fun i -> uint16 s.[i]) - LexBuffer.FromArrayNoCopy arr + let arr = Array.init sourceText.Length (fun i -> uint16 (sourceText.Item i)) + LexBuffer.FromArrayNoCopy (supportsFeature, arr) #else - LexBuffer.FromArrayNoCopy (s.ToCharArray()) + let mutable currentSourceIndex = 0 + LexBuffer.FromFunction(supportsFeature, fun (chars, start, length) -> + let lengthToCopy = + if currentSourceIndex + length <= sourceText.Length then + length + else + sourceText.Length - currentSourceIndex + + if lengthToCopy <= 0 then 0 + else + sourceText.CopyTo(currentSourceIndex, chars, start, lengthToCopy) + currentSourceIndex <- currentSourceIndex + lengthToCopy + lengthToCopy + ) #endif + static member FromString (supportsFeature: LanguageFeature -> bool, s: string) = #if FABLE_COMPILER - and internal LexBufferChar = uint16 + let arr = Array.init s.Length (fun i -> uint16 s.[i]) + LexBuffer.FromArrayNoCopy (supportsFeature, arr) #else - and internal LexBufferChar = char + LexBuffer.FromArrayNoCopy (supportsFeature, s.ToCharArray()) #endif - module GenericImplFragments = let startInterpret(lexBuffer:LexBuffer) = lexBuffer.BufferScanStart <- lexBuffer.BufferScanStart + lexBuffer.LexemeLength; @@ -217,7 +351,6 @@ namespace Internal.Utilities.Text.Lexing open GenericImplFragments - [] type internal UnicodeTables(trans: uint16[] array, accept: uint16[]) = let sentinel = 255 * 256 + 255 @@ -239,10 +372,10 @@ namespace Internal.Utilities.Text.Lexing // ways let baseForUnicodeCategories = numLowUnicodeChars+numSpecificUnicodeChars*2 let unicodeCategory = -#if FX_RESHAPED_GLOBALIZATION - System.Globalization.CharUnicodeInfo.GetUnicodeCategory(char inp) -#else +#if FABLE_COMPILER System.Char.GetUnicodeCategory(char inp) +#else + System.Char.GetUnicodeCategory(inp) #endif //System.Console.WriteLine("inp = {0}, unicodeCategory = {1}", [| box inp; box unicodeCategory |]); int trans.[state].[baseForUnicodeCategories + int32 unicodeCategory] @@ -254,10 +387,9 @@ namespace Internal.Utilities.Text.Lexing if c = inp then int trans.[state].[baseForSpecificUnicodeChars+i*2+1] else loop(i+1) - loop 0 let eofPos = numLowUnicodeChars + 2*numSpecificUnicodeChars + numUnicodeCategories - + let rec scanUntilSentinel lexBuffer state = // Return an endOfScan after consuming the input let a = int accept.[state] diff --git a/src/fcs-fable/src/utils/prim-lexing.fsi b/src/fcs-fable/src/utils/prim-lexing.fsi old mode 100755 new mode 100644 index bfb89b033d..48d6e2f59a --- a/src/fcs-fable/src/utils/prim-lexing.fsi +++ b/src/fcs-fable/src/utils/prim-lexing.fsi @@ -2,15 +2,44 @@ // LexBuffers are for use with automatically generated lexical analyzers, // in particular those produced by 'fslex'. + +namespace FSharp.Compiler.Text + +type ISourceText = + + abstract Item : int -> char with get + + abstract GetLineString : lineIndex: int -> string + + abstract GetLineCount : unit -> int + + abstract GetLastCharacterPosition : unit -> int * int + + abstract GetSubTextString : start: int * length: int -> string + + abstract SubTextEquals : target: string * startIndex: int -> bool + + abstract Length : int + + abstract ContentEquals : sourceText: ISourceText -> bool + + abstract CopyTo : sourceIndex: int * destination: char [] * destinationIndex: int * count: int -> unit + +module SourceText = + + val ofString : string -> ISourceText + // // 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. -// The underlying table format intepreted must precisely match the format generated by FsLex. +// The underlying table format interpreted must precisely match the format generated by FsLex. namespace Internal.Utilities.Text.Lexing open System.Collections.Generic +open FSharp.Compiler.Text open Microsoft.FSharp.Core open Microsoft.FSharp.Control +open FSharp.Compiler.Features /// Position information stored for lexing tokens [] @@ -50,12 +79,18 @@ type internal Position = /// Apply a #line directive. member ApplyLineDirective : fileIdx:int * line:int -> Position - + /// Get an arbitrary position, with the empty string as filename. static member Empty : Position - + static member FirstLine : fileIdx:int -> Position - + +#if FABLE_COMPILER +type internal LexBufferChar = uint16 +#else +type internal LexBufferChar = char +#endif + [] /// Input buffers consumed by lexers generated by fslex.exe. /// The type must be generic to match the code generated by FsLex and FsYacc (if you would like to @@ -69,27 +104,31 @@ type internal LexBuffer<'Char> = /// The matched string. member Lexeme: 'Char [] - + /// Fast helper to turn the matched characters into a string, avoiding an intermediate array. static member LexemeString : LexBuffer -> string - + /// Dynamically typed, non-lexically scoped parameter table. member BufferLocalStore : IDictionary - + /// True if the refill of the buffer ever failed , or if explicitly set to True. member IsPastEndOfStream: bool with get,set + /// True if the refill of the buffer ever failed , or if explicitly set to True. + member SupportsFeature:LanguageFeature -> bool + + /// Create a lex buffer suitable for Unicode lexing that reads characters from the given array. + /// Important: does take ownership of the array. + static member FromChars: (LanguageFeature -> bool) * LexBufferChar[] -> LexBuffer + /// Create a lex buffer suitable for Unicode lexing that reads characters from the given string. - static member FromString: string -> LexBuffer + static member FromString: (LanguageFeature -> bool) * string -> LexBuffer /// Create a lex buffer that reads character or byte inputs by using the given function. - static member FromFunction: ('Char[] * int * int -> int) -> LexBuffer<'Char> + static member FromFunction: (LanguageFeature -> bool) * ('Char[] * int * int -> int) -> LexBuffer<'Char> -#if FABLE_COMPILER -and internal LexBufferChar = uint16 -#else -and internal LexBufferChar = char -#endif + /// Create a lex buffer backed by source text. + static member FromSourceText : (LanguageFeature -> bool) * ISourceText -> LexBuffer /// The type of tables for an unicode lexer generated by fslex.exe. [] diff --git a/src/fcs-fable/src/utils/prim-parsing.fs b/src/fcs-fable/src/utils/prim-parsing.fs old mode 100755 new mode 100644 index 12b4e38567..1d685eed46 --- a/src/fcs-fable/src/utils/prim-parsing.fs +++ b/src/fcs-fable/src/utils/prim-parsing.fs @@ -4,11 +4,12 @@ namespace Internal.Utilities.Text.Parsing -open Internal.Utilities open Internal.Utilities.Text.Lexing open System -open System.Collections.Generic +#if !FABLE_COMPILER +open System.Buffers +#endif exception RecoverableParseError exception Accept of obj @@ -135,11 +136,7 @@ module internal Implementation = //------------------------------------------------------------------------- // Read the tables written by FSYACC. - type AssocTable(elemTab:uint16[], offsetTab:uint16[]) = - let cacheSize = 7919 // the 1000'th prime - // Use a simpler hash table with faster lookup, but only one - // hash bucket per key. - let cache = Array.zeroCreate (cacheSize * 2) + type AssocTable(elemTab: uint16[], offsetTab: uint16[], cache: int[], cacheSize: int) = member t.ReadAssoc (minElemNum,maxElemNum,defaultValueOfAssoc,keyToFind) = // do a binary chop on the table @@ -238,8 +235,26 @@ module internal Implementation = let ruleValues = (Array.zeroCreate 100 : obj[]) let lhsPos = (Array.zeroCreate 2 : Position[]) let reductions = tables.reductions - let actionTable = new AssocTable(tables.actionTableElements, tables.actionTableRowOffsets) - let gotoTable = new AssocTable(tables.gotos, tables.sparseGotoTableRowOffsets) + let cacheSize = 7919 // the 1000'th prime + // Use a simpler hash table with faster lookup, but only one + // hash bucket per key. +#if FABLE_COMPILER + let actionTableCache = Array.zeroCreate (cacheSize * 2) + let gotoTableCache = Array.zeroCreate (cacheSize * 2) +#else + let actionTableCache = ArrayPool.Shared.Rent(cacheSize * 2) + let gotoTableCache = ArrayPool.Shared.Rent(cacheSize * 2) + // Clear the arrays since ArrayPool does not + Array.Clear(actionTableCache, 0, actionTableCache.Length) + Array.Clear(gotoTableCache, 0, gotoTableCache.Length) + use _cacheDisposal = + { new IDisposable with + member _.Dispose() = + ArrayPool.Shared.Return actionTableCache + ArrayPool.Shared.Return gotoTableCache } +#endif + let actionTable = AssocTable(tables.actionTableElements, tables.actionTableRowOffsets, actionTableCache, cacheSize) + let gotoTable = AssocTable(tables.gotos, tables.sparseGotoTableRowOffsets, gotoTableCache, cacheSize) let stateToProdIdxsTable = new IdxToIdxListTable(tables.stateToProdIdxsTableElements, tables.stateToProdIdxsTableRowOffsets) let parseState = @@ -343,7 +358,7 @@ module internal Implementation = if errorSuppressionCountDown > 0 then errorSuppressionCountDown <- errorSuppressionCountDown - 1 #if DEBUG - if Flags.debug then Console.WriteLine("shifting, reduced errorRecoverylevel to {0}\n", errorSuppressionCountDown) + if Flags.debug then Console.WriteLine("shifting, reduced errorRecoveryLevel to {0}\n", errorSuppressionCountDown) #endif let nextState = actionValue action if not haveLookahead then failwith "shift on end of input!" @@ -363,38 +378,49 @@ module internal Implementation = #if DEBUG if Flags.debug then Console.Write("reduce popping {0} values/states, lookahead {1}", n, report haveLookahead lookaheadToken) #endif - for i = 0 to n - 1 do + // For every range to reduce merge it + for i = 0 to n - 1 do if valueStack.IsEmpty then failwith "empty symbol stack" - let topVal = valueStack.Peep() + let topVal = valueStack.Peep() // Grab topVal valueStack.Pop() |> ignore stateStack.Pop() |> ignore - ruleValues.[(n-i)-1] <- topVal.value - ruleStartPoss.[(n-i)-1] <- topVal.startPos - ruleEndPoss.[(n-i)-1] <- topVal.endPos - if i = 0 then lhsPos.[1] <- topVal.endPos - if i = n - 1 then lhsPos.[0] <- topVal.startPos - - // Use the lookahead token to populate the locations if the rhs is empty - if n = 0 then + + let ruleIndex = (n-i)-1 + ruleValues.[ruleIndex] <- topVal.value + ruleStartPoss.[ruleIndex] <- topVal.startPos + ruleEndPoss.[ruleIndex] <- topVal.endPos + + if i = 0 then + // Initial range + lhsPos.[0] <- topVal.startPos + lhsPos.[1] <- topVal.endPos + elif topVal.startPos.FileIndex = lhsPos.[1].FileIndex && topVal.startPos.Line <= lhsPos.[1].Line then + // Reduce range if same file as the initial end point + lhsPos.[0] <- topVal.startPos + + // Use the lookahead token to populate the locations if the rhs is empty + if n = 0 then if haveLookahead then - lhsPos.[0] <- lookaheadStartPos - lhsPos.[1] <- lookaheadEndPos + lhsPos.[0] <- lookaheadStartPos + lhsPos.[1] <- lookaheadEndPos else lhsPos.[0] <- lexbuf.StartPos lhsPos.[1] <- lexbuf.EndPos - try - // printf "reduce %d\n" prod - let redResult = reduction parseState - valueStack.Push(ValueInfo(redResult, lhsPos.[0], lhsPos.[1])) + try + // printf "reduce %d\n" prod + let redResult = reduction parseState + let valueInfo = ValueInfo(redResult, lhsPos.[0], lhsPos.[1]) + valueStack.Push(valueInfo) let currState = stateStack.Peep() let newGotoState = gotoTable.Read(int tables.productionToNonTerminalTable.[prod], currState) stateStack.Push(newGotoState) + #if DEBUG if Flags.debug then Console.WriteLine(" goto state {0}", newGotoState) #endif - with - | Accept res -> - finished <- true + with + | Accept res -> + finished <- true valueStack.Push(ValueInfo(res, lhsPos.[0], lhsPos.[1])) | RecoverableParseError -> #if DEBUG diff --git a/src/fcs-fable/src/utils/prim-parsing.fsi b/src/fcs-fable/src/utils/prim-parsing.fsi old mode 100755 new mode 100644 diff --git a/src/fcs-fable/src/utils/reshapedmsbuild.fs b/src/fcs-fable/src/utils/reshapedmsbuild.fs index 571edd3ae4..20b5cd6f96 100644 --- a/src/fcs-fable/src/utils/reshapedmsbuild.fs +++ b/src/fcs-fable/src/utils/reshapedmsbuild.fs @@ -21,41 +21,45 @@ type ITaskItem = abstract member CopyMetadataTo : ITaskItem -> unit abstract member CloneCustomMetadata : IDictionary -namespace Microsoft.Build.Utilities -open Microsoft.Build.Framework -open Microsoft.FSharp.Core.ReflectionAdapters -open System -open System.Collections -open System.Reflection - -type TaskItem (itemSpec:string) = - let assembly = Assembly.Load(new AssemblyName("Microsoft.Build.Utilities.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")) - let buildUtilitiesTaskType = assembly.GetType("Microsoft.Build.Utilities.Task") - let instance = Activator.CreateInstance(buildUtilitiesTaskType, [|itemSpec|]) - - interface ITaskItem with - member this.ItemSpec - with get () :string = (instance.GetPropertyValue("ItemSpec") :?> string) - and set (value:string) = (instance.SetPropertyValue("ItemSpec", value)); () - member this.MetadataNames - with get () :ICollection = (instance.GetPropertyValue("MetadataNames") :?> ICollection) - member this.MetadataCount - with get () :int = (instance.GetPropertyValue("MetadataCount") :?> int) - member this.CopyMetadataTo(iTaskItem) = - let m = buildUtilitiesTaskType.GetMethod("CopyMetadataTo", [| typeof |]) - m.Invoke(instance, [|iTaskItem :>obj|]) |> ignore - member this.CloneCustomMetadata = - let m = buildUtilitiesTaskType.GetMethod("CloneCustomMetadata", [||]) - (m.Invoke(instance,[||])) :?>IDictionary - member this.GetMetadata(metadataName) = - let m = buildUtilitiesTaskType.GetMethod("GetMetadata", [|typeof|]) - (m.Invoke(instance,[|metadataName|])) :?>string - member this.RemoveMetadata(metadataName) = - let m = buildUtilitiesTaskType.GetMethod("RemoveMetadata", [|typeof|]) - (m.Invoke(instance,[|metadataName|])) :?>string |>ignore - member this.SetMetadata(metadataName, metadataValue) = - let m = buildUtilitiesTaskType.GetMethod("SetMetadata", [|typeof;typeof|]) - (m.Invoke(instance,[|metadataName; metadataValue|])) |>ignore +module Utilities = + open Microsoft.Build.Framework + open System + open System.Collections + open System.Reflection + + type System.Object with + member this.GetPropertyValue(propName) = this.GetType().GetProperty(propName, BindingFlags.Public).GetValue(this, null) + member this.SetPropertyValue(propName, propValue) = this.GetType().GetProperty(propName, BindingFlags.Public).SetValue(this, propValue, null) + member this.GetMethod(methodName, argTypes) = this.GetType().GetMethod(methodName, argTypes, [||]) + + type TaskItem (itemSpec:string) = + let assembly = Assembly.Load(new AssemblyName("Microsoft.Build.Utilities.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")) + let buildUtilitiesTaskType = assembly.GetType("Microsoft.Build.Utilities.Task") + let instance = Activator.CreateInstance(buildUtilitiesTaskType, [|itemSpec|]) + + interface ITaskItem with + member this.ItemSpec + with get () :string = (instance.GetPropertyValue("ItemSpec") :?> string) + and set (value:string) = (instance.SetPropertyValue("ItemSpec", value)); () + member this.MetadataNames + with get () :ICollection = (instance.GetPropertyValue("MetadataNames") :?> ICollection) + member this.MetadataCount + with get () :int = (instance.GetPropertyValue("MetadataCount") :?> int) + member this.CopyMetadataTo(iTaskItem) = + let m = buildUtilitiesTaskType.GetMethod("CopyMetadataTo", [| typeof |]) + m.Invoke(instance, [|iTaskItem :>obj|]) |> ignore + member this.CloneCustomMetadata = + let m = buildUtilitiesTaskType.GetMethod("CloneCustomMetadata", [||]) + (m.Invoke(instance,[||])) :?>IDictionary + member this.GetMetadata(metadataName) = + let m = buildUtilitiesTaskType.GetMethod("GetMetadata", [|typeof|]) + (m.Invoke(instance,[|metadataName|])) :?>string + member this.RemoveMetadata(metadataName) = + let m = buildUtilitiesTaskType.GetMethod("RemoveMetadata", [|typeof|]) + (m.Invoke(instance,[|metadataName|])) :?>string |>ignore + member this.SetMetadata(metadataName, metadataValue) = + let m = buildUtilitiesTaskType.GetMethod("SetMetadata", [|typeof;typeof|]) + (m.Invoke(instance,[|metadataName; metadataValue|])) |>ignore namespace FSharp.Compiler open System @@ -66,13 +70,13 @@ open System.Linq open System.Runtime.Versioning open FSComp open Microsoft.Win32 +open Microsoft.Build.Framework.Utilities module internal MsBuildAdapters = - open Microsoft.FSharp.Core.ReflectionAdapters - /// - /// Used to specify the targeted version of the .NET Framework for some methods of ToolLocationHelper. + /// Used to specify the targeted version of the .NET Framework for some methods of ToolLocationHelper. This is meant to mimic + /// the official version here: https://source.dot.net/#q=TargetDotNetFrameworkVersion. /// type public TargetDotNetFrameworkVersion = | Version11 = 0 @@ -89,7 +93,7 @@ module internal MsBuildAdapters = | Version47 = 11 | Version471 = 12 | Version472 = 13 - | VersionLatest = 8 //TargetDotNetFrameworkVersion.Version461 + | VersionLatest = 13 //TargetDotNetFrameworkVersion.Version472 /// /// Used to specify the targeted bitness of the .NET Framework for some methods of ToolLocationHelper @@ -101,7 +105,6 @@ module internal MsBuildAdapters = module internal ToolLocationHelper = open Microsoft.Build.Framework - open Microsoft.FSharp.Core.ReflectionAdapters open System.Linq open System.Reflection open MsBuildAdapters @@ -118,7 +121,11 @@ module internal ToolLocationHelper = let dotNetFrameworkVersion451 = Version(4, 5, 1) let dotNetFrameworkVersion452 = Version(4, 5, 2) let dotNetFrameworkVersion46 = Version(4, 6) - let dotNetFrameworkVersion461 = Version(4, 6, 1) + let dotNetFrameworkVersion461 = Version(4, 6, 1) + let dotNetFrameworkVersion462 = Version(4, 6, 2) + let dotNetFrameworkVersion47 = Version(4, 7) + let dotNetFrameworkVersion471 = Version(4, 7, 1) + let dotNetFrameworkVersion472 = Version(4, 7, 2) // visual studio versions. let visualStudioVersion100 = new Version(10, 0); @@ -210,6 +217,10 @@ module internal ToolLocationHelper = | TargetDotNetFrameworkVersion.Version452 -> dotNetFrameworkVersion452 | TargetDotNetFrameworkVersion.Version46 -> dotNetFrameworkVersion46 | TargetDotNetFrameworkVersion.Version461 -> dotNetFrameworkVersion461 + | TargetDotNetFrameworkVersion.Version462 -> dotNetFrameworkVersion462 + | TargetDotNetFrameworkVersion.Version47 -> dotNetFrameworkVersion47 + | TargetDotNetFrameworkVersion.Version471 -> dotNetFrameworkVersion471 + | TargetDotNetFrameworkVersion.Version472 -> dotNetFrameworkVersion472 | _ -> raise (getArgumentException version) let complusInstallRoot = Environment.GetEnvironmentVariable("COMPLUS_INSTALLROOT") @@ -360,7 +371,7 @@ module internal ToolLocationHelper = // Doesn't need to be virtual @@@@@ abstract member GetPathToDotNetFramework: DotNetFrameworkArchitecture -> string default this.GetPathToDotNetFramework arch = - match this.pathsToDotNetFramework.TryGetValue(arch) with + match this.pathsToDotNetFramework.TryGetValue arch with | true, x -> x | _ -> if not (CheckForFrameworkInstallation this.dotNetFrameworkRegistryKey this.dotNetFrameworkSetupRegistryInstalledName) then null @@ -749,11 +760,15 @@ module internal ToolLocationHelper = CreateDotNetFrameworkSpecForV4 dotNetFrameworkVersion452 visualStudioVersion150 // v4.5.2 CreateDotNetFrameworkSpecForV4 dotNetFrameworkVersion46 visualStudioVersion140 // v4.6 CreateDotNetFrameworkSpecForV4 dotNetFrameworkVersion461 visualStudioVersion150 // v4.6.1 + CreateDotNetFrameworkSpecForV4 dotNetFrameworkVersion462 visualStudioVersion150 // v4.6.2 + CreateDotNetFrameworkSpecForV4 dotNetFrameworkVersion47 visualStudioVersion150 // v4.7 + CreateDotNetFrameworkSpecForV4 dotNetFrameworkVersion471 visualStudioVersion150 // v4.7.1 + CreateDotNetFrameworkSpecForV4 dotNetFrameworkVersion472 visualStudioVersion150 // v4.7.2 |] array.ToDictionary(fun spec -> spec.Version) let getDotNetFrameworkSpec version = - match dotNetFrameworkSpecDict.TryGetValue(version) with + match dotNetFrameworkSpecDict.TryGetValue version with | true, x -> x | _ -> raise (getArgumentException version) diff --git a/src/fcs-fable/src/utils/reshapedreflection.fs b/src/fcs-fable/src/utils/reshapedreflection.fs deleted file mode 100644 index b1f0aeca8d..0000000000 --- a/src/fcs-fable/src/utils/reshapedreflection.fs +++ /dev/null @@ -1,401 +0,0 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. - -namespace Microsoft.FSharp.Core -open System.Reflection - -//Replacement for: System.Security.SecurityElement.Escape(line) All platforms -module internal XmlAdapters = - open System.Text - open Microsoft.FSharp.Collections - - let s_escapeChars = [| '<'; '>'; '\"'; '\''; '&' |] - - let getEscapeSequence c = - match c with - | '<' -> "<" - | '>' -> ">" - | '\"' -> """ - | '\'' -> "'" - | '&' -> "&" - | _ as ch -> ch.ToString() - - let escape str = String.collect getEscapeSequence str - -#if FX_RESHAPED_REFLECTION -module internal ReflectionAdapters = - open System - open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators - open Microsoft.FSharp.Collections - open PrimReflectionAdapters - - let inline hasFlag (flag : BindingFlags) f = (f &&& flag) = flag - let isDeclaredFlag f = hasFlag BindingFlags.DeclaredOnly f - let isPublicFlag f = hasFlag BindingFlags.Public f - let isStaticFlag f = hasFlag BindingFlags.Static f - let isInstanceFlag f = hasFlag BindingFlags.Instance f - let isNonPublicFlag f = hasFlag BindingFlags.NonPublic f - - let isAcceptable bindingFlags isStatic isPublic = - // 1. check if member kind (static\instance) was specified in flags - ((isStaticFlag bindingFlags && isStatic) || (isInstanceFlag bindingFlags && not isStatic)) && - // 2. check if member accessibility was specified in flags - ((isPublicFlag bindingFlags && isPublic) || (isNonPublicFlag bindingFlags && not isPublic)) - - let publicFlags = BindingFlags.Public ||| BindingFlags.Instance ||| BindingFlags.Static - - let commit (results : _[]) = - match results with - | [||] -> null - | [| m |] -> m - | _ -> raise (AmbiguousMatchException()) - - let canUseAccessor (accessor : MethodInfo) nonPublic = - (not (isNull (box accessor))) && (accessor.IsPublic || nonPublic) - - type System.Type with - member this.GetTypeInfo() = IntrospectionExtensions.GetTypeInfo(this) - member this.GetRuntimeProperties() = RuntimeReflectionExtensions.GetRuntimeProperties(this) - member this.GetRuntimeEvents() = RuntimeReflectionExtensions.GetRuntimeEvents(this) - member this.Attributes = this.GetTypeInfo().Attributes - member this.GetCustomAttributes(attrTy, inherits) : obj[] = downcast box(CustomAttributeExtensions.GetCustomAttributes(this.GetTypeInfo(), attrTy, inherits) |> Seq.toArray) - member this.GetNestedType (name, bindingFlags) = - // MSDN: http://msdn.microsoft.com/en-us/library/0dcb3ad5.aspx - // The following BindingFlags filter flags can be used to define which nested types to include in the search: - // You must specify either BindingFlags.Public or BindingFlags.NonPublic to get a return. - // Specify BindingFlags.Public to include public nested types in the search. - // Specify BindingFlags.NonPublic to include non-public nested types (that is, private, internal, and protected nested types) in the search. - // This method returns only the nested types of the current type. It does not search the base classes of the current type. - // To find types that are nested in base classes, you must walk the inheritance hierarchy, calling GetNestedType at each level. - let nestedTyOpt = - this.GetTypeInfo().DeclaredNestedTypes - |> Seq.tryFind (fun nestedTy -> - nestedTy.Name = name && ( - (isPublicFlag bindingFlags && nestedTy.IsNestedPublic) || - (isNonPublicFlag bindingFlags && (nestedTy.IsNestedPrivate || nestedTy.IsNestedFamily || nestedTy.IsNestedAssembly || nestedTy.IsNestedFamORAssem || nestedTy.IsNestedFamANDAssem)) - ) - ) - |> Option.map (fun ti -> ti.AsType()) - defaultArg nestedTyOpt null - // use different sources based on Declared flag - member this.GetMethods(bindingFlags) = - (if isDeclaredFlag bindingFlags then this.GetTypeInfo().DeclaredMethods else this.GetRuntimeMethods()) - |> Seq.filter (fun m -> isAcceptable bindingFlags m.IsStatic m.IsPublic) - |> Seq.toArray - - // use different sources based on Declared flag - member this.GetFields(bindingFlags) = - (if isDeclaredFlag bindingFlags then this.GetTypeInfo().DeclaredFields else this.GetRuntimeFields()) - |> Seq.filter (fun f -> isAcceptable bindingFlags f.IsStatic f.IsPublic) - |> Seq.toArray - - // use different sources based on Declared flag - member this.GetProperties(?bindingFlags) = - let bindingFlags = defaultArg bindingFlags publicFlags - (if isDeclaredFlag bindingFlags then this.GetTypeInfo().DeclaredProperties else this.GetRuntimeProperties()) - |> Seq.filter (fun pi-> - let mi = match pi.GetMethod with | null -> pi.SetMethod | _ -> pi.GetMethod - if mi = null then false - else isAcceptable bindingFlags mi.IsStatic mi.IsPublic - ) - |> Seq.toArray - - member this.GetEvents(?bindingFlags) = - let bindingFlags = defaultArg bindingFlags publicFlags - (if isDeclaredFlag bindingFlags then this.GetTypeInfo().DeclaredEvents else this.GetRuntimeEvents()) - |> Seq.filter (fun ei-> - let m = ei.GetAddMethod(true) - if m = null then false - else isAcceptable bindingFlags m.IsStatic m.IsPublic - ) - |> Seq.toArray - - member this.GetEvent(name, ?bindingFlags) = - let bindingFlags = defaultArg bindingFlags publicFlags - this.GetEvents(bindingFlags) - |> Array.filter (fun ei -> ei.Name = name) - |> commit - - member this.GetConstructor(bindingFlags, _binder, argsT:Type[], _parameterModifiers) = - this.GetConstructor(bindingFlags,argsT) - - member this.GetMethod(name, ?bindingFlags) = - let bindingFlags = defaultArg bindingFlags publicFlags - this.GetMethods(bindingFlags) - |> Array.filter(fun m -> m.Name = name) - |> commit - - member this.GetMethod(name, _bindingFlags, _binder, argsT:Type[], _parameterModifiers) = - this.GetMethod(name, argsT) - - // use different sources based on Declared flag - member this.GetProperty(name, bindingFlags) = - this.GetProperties(bindingFlags) - |> Array.filter (fun pi -> pi.Name = name) - |> commit - - member this.GetMethod(methodName, args:Type[], ?bindingFlags) = - let bindingFlags = defaultArg bindingFlags publicFlags - let compareSequences parms args = - Seq.compareWith (fun parm arg -> if parm <> arg then 1 else 0) parms args - this.GetMethods(bindingFlags) - |> Array.filter(fun m -> m.Name = methodName && (compareSequences (m.GetParameters() |> Seq.map(fun x -> x.ParameterType)) args) = 0) - |> commit - - member this.GetNestedTypes(?bindingFlags) = - let bindingFlags = defaultArg bindingFlags publicFlags - this.GetTypeInfo().DeclaredNestedTypes - |> Seq.filter (fun nestedTy-> - (isPublicFlag bindingFlags && nestedTy.IsNestedPublic) || - (isNonPublicFlag bindingFlags && (nestedTy.IsNestedPrivate || nestedTy.IsNestedFamily || nestedTy.IsNestedAssembly || nestedTy.IsNestedFamORAssem || nestedTy.IsNestedFamANDAssem))) - |> Seq.map (fun ti -> ti.AsType()) - |> Seq.toArray - - member this.GetEnumUnderlyingType() = - Enum.GetUnderlyingType(this) - - member this.InvokeMember(memberName, bindingFlags, _binder, target:obj, arguments:obj[], _cultureInfo) = - let m = this.GetMethod(memberName, (arguments |> Seq.map(fun x -> x.GetType()) |> Seq.toArray), bindingFlags) - match m with - | null -> raise <| System.MissingMethodException(String.Format("Method '{0}.{1}' not found.", this.FullName, memberName)) - | _ -> m.Invoke(target, arguments) - - member this.IsGenericType = this.GetTypeInfo().IsGenericType - - member this.IsGenericTypeDefinition = this.GetTypeInfo().IsGenericTypeDefinition - - member this.GetGenericArguments() = - if this.IsGenericTypeDefinition then this.GetTypeInfo().GenericTypeParameters - elif this.IsGenericType then this.GenericTypeArguments - else [||] - - member this.IsInterface = this.GetTypeInfo().IsInterface - - member this.IsPublic = this.GetTypeInfo().IsPublic - - member this.IsNestedPublic = this.GetTypeInfo().IsNestedPublic - - member this.IsClass = this.GetTypeInfo().IsClass - - member this.IsValueType = this.GetTypeInfo().IsValueType - - member this.IsSealed = this.GetTypeInfo().IsSealed - - member this.BaseType = this.GetTypeInfo().BaseType - - member this.GetConstructor(bindingFlags, parameterTypes : Type[]) = - this.GetTypeInfo().DeclaredConstructors - |> Seq.filter (fun ci -> isAcceptable bindingFlags ci.IsStatic ci.IsPublic) - |> Seq.filter (fun ci -> - ( - let parameters = ci.GetParameters() - (parameters.Length = parameterTypes.Length) && - (parameterTypes, parameters) ||> Array.forall2 (fun ty pi -> pi.ParameterType.Equals ty) - ) - ) - |> Seq.toArray - |> commit - - member this.GetConstructor(parameterTypes : Type[]) = - this.GetConstructor(BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.Instance, parameterTypes) - - member this.GetConstructors(?bindingFlags) = - let bindingFlags = defaultArg bindingFlags (BindingFlags.Public ||| BindingFlags.Instance) - // type initializer will also be included in resultset - this.GetTypeInfo().DeclaredConstructors - |> Seq.filter (fun ci -> isAcceptable bindingFlags ci.IsStatic ci.IsPublic) - |> Seq.toArray - - // MSDN: returns an array of Type objects representing all the interfaces implemented or inherited by the current Type. - member this.GetInterfaces() = this.GetTypeInfo().ImplementedInterfaces |> Seq.toArray - - member this.GetMethods() = this.GetMethods(publicFlags) - - member this.Assembly = this.GetTypeInfo().Assembly - - member this.IsSubclassOf(otherTy : Type) = this.GetTypeInfo().IsSubclassOf(otherTy) - - member this.IsEnum = this.GetTypeInfo().IsEnum; - - member this.GetField(name, bindingFlags) = - this.GetFields(bindingFlags) - |> Array.filter (fun fi -> fi.Name = name) - |> commit - - member this.GetField(name) = RuntimeReflectionExtensions.GetRuntimeField(this, name) - - member this.GetProperty(name, propertyType, parameterTypes : Type[]) = - this.GetProperties() - |> Array.filter (fun pi -> - pi.Name = name && - pi.PropertyType = propertyType && - ( - let parameters = pi.GetIndexParameters() - (parameters.Length = parameterTypes.Length) && - (parameterTypes, parameters) ||> Array.forall2 (fun ty pi -> pi.ParameterType.Equals ty) - ) - ) - |> commit - - static member GetTypeCode(ty : Type) = - if typeof.Equals ty then TypeCode.Int32 - elif typeof.Equals ty then TypeCode.Int64 - elif typeof.Equals ty then TypeCode.Byte - elif ty = typeof then TypeCode.SByte - elif ty = typeof then TypeCode.Int16 - elif ty = typeof then TypeCode.UInt16 - elif ty = typeof then TypeCode.UInt32 - elif ty = typeof then TypeCode.UInt64 - elif ty = typeof then TypeCode.Single - elif ty = typeof then TypeCode.Double - elif ty = typeof then TypeCode.Decimal - else TypeCode.Object - - member this.Module = - this.GetTypeInfo().Module - - member this.MetadataToken = - // TODO: is this an adequate replacement for MetadataToken - let s = String.Format("{0}", this.ToString()) - s.GetHashCode() - - type System.Reflection.EventInfo with - - member this.GetAddMethod() = - this.AddMethod - - member this.GetRemoveMethod() = - this.RemoveMethod - - member this.MetadataToken = - // TODO: is this an adequate replacement for MetadataToken - let s = String.Format("{0},{0}", this.DeclaringType.ToString(), this.ToString()) - s.GetHashCode() - - type System.Reflection.FieldInfo with - member this.GetRawConstantValue() = - this.GetValue(null) - - member this.MetadataToken = - // TODO: is this an adequate replacement for MetadataToken - let s = String.Format("{0},{0}", this.DeclaringType.ToString(), this.ToString()) - s.GetHashCode() - - type System.Reflection.MemberInfo with - member this.GetCustomAttributes(attrTy, inherits) : obj[] = downcast box(CustomAttributeExtensions.GetCustomAttributes(this, attrTy, inherits) |> Seq.toArray) - - // TODO: is this an adequate replacement for MetadataToken - member this.MetadataToken = - // TODO: is this an adequate replacement for MetadataToken - let s = String.Format("{0},{0}", this.DeclaringType.ToString(), this.ToString()) - s.GetHashCode() - - type System.Reflection.MethodInfo with - - member this.GetCustomAttributes(inherits : bool) : obj[] = downcast box(CustomAttributeExtensions.GetCustomAttributes(this, inherits) |> Seq.toArray) - - member this.Invoke(obj, _bindingFlags, _binder, args, _ci) = - this.Invoke(obj, args) - - member this.MetadataToken = - // TODO: is this an adequate replacement for MetadataToken - let s = String.Format("{0},{0}", this.DeclaringType.ToString(), this.ToString()) - s.GetHashCode() - - type System.Reflection.ParameterInfo with - - member this.RawDefaultValue = this.DefaultValue - - member this.MetadataToken = - // TODO: is this an adequate replacement for MetadataToken - // I really do not understand why: sprintf "%s,%s" (this.ReflectedType.ToString()) (this.ToString()) did not work - let s = String.Format("{0},{0},{0}", this.Member.DeclaringType.ToString(),this.Member.ToString(), this.ToString()) - s.GetHashCode() - - type System.Reflection.PropertyInfo with - - member this.GetGetMethod(nonPublic) = - let mi = this.GetMethod - if canUseAccessor mi nonPublic then mi - else null - - member this.GetSetMethod(nonPublic) = - let mi = this.SetMethod - if canUseAccessor mi nonPublic then mi - else null - - member this.GetGetMethod() = this.GetMethod - - member this.GetSetMethod() = this.SetMethod - - type System.Reflection.Assembly with - - member this.GetTypes() = - this.DefinedTypes - |> Seq.map (fun ti -> ti.AsType()) - |> Seq.toArray - - member this.GetExportedTypes() = - this.DefinedTypes - |> Seq.filter(fun ti -> ti.IsPublic) - |> Seq.map (fun ti -> ti.AsType()) - |> Seq.toArray - - member this.Location = - this.ManifestModule.FullyQualifiedName - - type System.Delegate with - - static member CreateDelegate(delegateType, methodInfo : MethodInfo) = methodInfo.CreateDelegate(delegateType) - - static member CreateDelegate(delegateType, obj : obj, methodInfo : MethodInfo) = methodInfo.CreateDelegate(delegateType, obj) - - type System.Object with - member this.GetPropertyValue(propName) = - this.GetType().GetProperty(propName, BindingFlags.Public).GetValue(this, null) - - member this.SetPropertyValue(propName, propValue) = - this.GetType().GetProperty(propName, BindingFlags.Public).SetValue(this, propValue, null) - - member this.GetMethod(methodName, argTypes) = - this.GetType().GetMethod(methodName, argTypes, BindingFlags.Public) - - type System.Char with - static member GetUnicodeCategory(c) = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(c) - - type System.Reflection.Module with - member this.MetadataToken = - // TODO: is this an adequate replacement for MetadataToken - let s = this.FullyQualifiedName - s.GetHashCode() - -#if COMPILER // This part includes global state in globalLoadContext. Only include this support "once", i.e. when compiling FSharp.Compiler.Private.dll, FSharp.Compiler.Service.dll, fsc-proto.exe - - type CustomAssemblyResolver() = - inherit System.Runtime.Loader.AssemblyLoadContext() - override this.Load (assemblyName:AssemblyName):Assembly = - this.LoadFromAssemblyName(assemblyName) - - let globalLoadContext = - // This is an unfortunate temporary fix!!!! - // ======================================== - // We need to run fsi tests on a very old version of the corclr because of an unfortunate test framework - // This hack detects that, and uses the old code. - // On slightly newer code AssemblyLoadContext.Default is the way to go. - match Seq.tryHead (typeof.GetTypeInfo().Assembly.GetCustomAttributes()) with - | Some a when a.Version = "4.6.24410.01" -> new CustomAssemblyResolver() :> System.Runtime.Loader.AssemblyLoadContext - | _ -> System.Runtime.Loader.AssemblyLoadContext.Default - - type System.Reflection.Assembly with - static member LoadFrom(filename:string) = - globalLoadContext.LoadFromAssemblyPath(filename) - - static member UnsafeLoadFrom(filename:string) = - globalLoadContext.LoadFromAssemblyPath(filename) - - type System.Reflection.AssemblyName with - static member GetAssemblyName(path) = - System.Runtime.Loader.AssemblyLoadContext.GetAssemblyName(path) - -#endif - -#endif diff --git a/src/fcs-fable/src/utils/sformat.fs b/src/fcs-fable/src/utils/sformat.fs old mode 100755 new mode 100644 index fbcc6ecc7c..08b1e59ee8 --- a/src/fcs-fable/src/utils/sformat.fs +++ b/src/fcs-fable/src/utils/sformat.fs @@ -25,23 +25,14 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl // This is a fresh implementation of pre-existing ideas. open System - open System.Diagnostics - open System.Text open System.IO open System.Reflection open System.Globalization open System.Collections.Generic open Microsoft.FSharp.Core open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators - open Microsoft.FSharp.Core.Operators open Microsoft.FSharp.Reflection open Microsoft.FSharp.Collections - open Microsoft.FSharp.Primitives.Basics - -#if FX_RESHAPED_REFLECTION - open PrimReflectionAdapters - open ReflectionAdapters -#endif [] type LayoutTag = @@ -266,10 +257,10 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl let tagListL tagger = function | [] -> emptyL | [x] -> x - | x::xs -> + | x :: xs -> let rec process' prefixL = function | [] -> prefixL - | y::ys -> process' ((tagger prefixL) ++ y) ys + | y :: ys -> process' ((tagger prefixL) ++ y) ys process' x xs let commaListL layouts = tagListL (fun prefixL -> prefixL ^^ rightL (Literals.comma)) layouts @@ -282,7 +273,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl match layouts with | [] -> emptyL | [x] -> x - | x::ys -> List.fold (fun pre y -> pre @@ y) x ys + | x :: ys -> List.fold (fun pre y -> pre @@ y) x ys let optionL selector value = match value with @@ -323,11 +314,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl StringLimit : int; #endif FormatProvider: System.IFormatProvider; -#if FX_RESHAPED_REFLECTION - ShowNonPublic : bool -#else BindingFlags: System.Reflection.BindingFlags -#endif PrintWidth : int; PrintDepth : int; PrintLength : int; @@ -341,11 +328,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl StringLimit = System.Int32.MaxValue; #endif AttributeProcessor= (fun _ _ _ -> ()); -#if FX_RESHAPED_REFLECTION - ShowNonPublic = false -#else BindingFlags = System.Reflection.BindingFlags.Public; -#endif FloatingPointFormat = "g10"; PrintWidth = 80 ; PrintDepth = 100 ; @@ -357,13 +340,6 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl module ReflectUtils = - open System - open System.Reflection - -#if FX_RESHAPED_REFLECTION - open PrimReflectionAdapters - open Microsoft.FSharp.Core.ReflectionAdapters -#endif [] type TypeInfo = @@ -392,24 +368,31 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl (let cases = FSharpType.GetUnionCases ty cases.Length > 0 && equivHeadTypes (typedefof>) cases.[0].DeclaringType) + [] + type TupleType = + | Value + | Reference + [] type ValueInfo = - | TupleValue of (obj * Type) list + | TupleValue of TupleType * (obj * Type) list | FunctionClosureValue of System.Type | RecordValue of (string * obj * Type) list - | ConstructorValue of string * (string * (obj * Type)) list + | ConstructorValue of declaringType: Type option * string * (string * (obj * Type)) list | ExceptionValue of System.Type * (string * (obj * Type)) list | UnitValue | ObjectValue of obj - module Value = + module Value = + + // Returns true if a given type has the RequireQualifiedAccess attribute + let private requiresQualifiedAccess (declaringType:Type) = + let rqaAttr = declaringType.GetCustomAttribute(typeof, false) + isNull rqaAttr |> not // Analyze an object to see if it the representation // of an F# value. - let GetValueInfoOfObject (bindingFlags:BindingFlags) (obj : obj) = -#if FX_RESHAPED_REFLECTION - let showNonPublic = isNonPublicFlag bindingFlags -#endif + let GetValueInfoOfObject (bindingFlags:BindingFlags) (obj : obj) = match obj with | null -> ObjectValue(obj) | _ -> @@ -422,7 +405,11 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl if FSharpType.IsTuple reprty then let tyArgs = FSharpType.GetTupleElements(reprty) - TupleValue (FSharpValue.GetTupleFields obj |> Array.mapi (fun i v -> (v, tyArgs.[i])) |> Array.toList) + let fields = FSharpValue.GetTupleFields obj |> Array.mapi (fun i v -> (v, tyArgs.[i])) |> Array.toList + let tupleType = + if reprty.Name.StartsWith "ValueTuple" then TupleType.Value + else TupleType.Reference + TupleValue (tupleType, fields) elif FSharpType.IsFunction reprty then FunctionClosureValue reprty @@ -431,34 +418,21 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl // the type are the actual fields of the type. Again, // we should be reading attributes here that indicate the // true structure of the type, e.g. the order of the fields. -#if FX_RESHAPED_REFLECTION - elif FSharpType.IsUnion(reprty, showNonPublic) then - let tag,vals = FSharpValue.GetUnionFields (obj,reprty, showNonPublic) -#else elif FSharpType.IsUnion(reprty,bindingFlags) then let tag,vals = FSharpValue.GetUnionFields (obj,reprty,bindingFlags) -#endif let props = tag.GetFields() let pvals = (props,vals) ||> Array.map2 (fun prop v -> prop.Name,(v, prop.PropertyType)) - ConstructorValue(tag.Name, Array.toList pvals) -#if FX_RESHAPED_REFLECTION - elif FSharpType.IsExceptionRepresentation(reprty, showNonPublic) then - let props = FSharpType.GetExceptionFields(reprty, showNonPublic) - let vals = FSharpValue.GetExceptionFields(obj, showNonPublic) -#else + let declaringType = + if requiresQualifiedAccess tag.DeclaringType then Some tag.DeclaringType + else None + ConstructorValue(declaringType, tag.Name, Array.toList pvals) elif FSharpType.IsExceptionRepresentation(reprty,bindingFlags) then let props = FSharpType.GetExceptionFields(reprty,bindingFlags) let vals = FSharpValue.GetExceptionFields(obj,bindingFlags) -#endif let pvals = (props,vals) ||> Array.map2 (fun prop v -> prop.Name,(v, prop.PropertyType)) ExceptionValue(reprty, pvals |> Array.toList) -#if FX_RESHAPED_REFLECTION - elif FSharpType.IsRecord(reprty, showNonPublic) then - let props = FSharpType.GetRecordFields(reprty, showNonPublic) -#else elif FSharpType.IsRecord(reprty,bindingFlags) then let props = FSharpType.GetRecordFields(reprty,bindingFlags) -#endif RecordValue(props |> Array.map (fun prop -> prop.Name, prop.GetValue(obj,null), prop.PropertyType) |> Array.toList) else ObjectValue(obj) @@ -471,16 +445,19 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl let obj = (box x) match obj with | null -> - let isNullaryUnion = - match ty.GetCustomAttributes(typeof, false) with - | [|:? CompilationRepresentationAttribute as attr|] -> + let isNullaryUnion = + match ty.GetCustomAttributes(typeof, false) with + | [|:? CompilationRepresentationAttribute as attr|] -> (attr.Flags &&& CompilationRepresentationFlags.UseNullAsTrueValue) = CompilationRepresentationFlags.UseNullAsTrueValue - | _ -> false - if isNullaryUnion then - let nullaryCase = FSharpType.GetUnionCases ty |> Array.filter (fun uc -> uc.GetFields().Length = 0) |> Array.item 0 - ConstructorValue(nullaryCase.Name, []) - elif isUnitType ty then UnitValue - else ObjectValue(obj) + | _ -> false + if isNullaryUnion then + let nullaryCase = FSharpType.GetUnionCases ty |> Array.filter (fun uc -> uc.GetFields().Length = 0) |> Array.item 0 + let declaringType = + if requiresQualifiedAccess ty then Some ty + else None + ConstructorValue(declaringType, nullaryCase.Name, []) + elif isUnitType ty then UnitValue + else ObjectValue(obj) | _ -> GetValueInfoOfObject bindingFlags (obj) @@ -493,12 +470,8 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl let string_of_int (i:int) = i.ToString() let typeUsesSystemObjectToString (ty:System.Type) = - try -#if FX_RESHAPED_REFLECTION - let methInfo = ty.GetRuntimeMethod("ToString",[| |]) -#else + try let methInfo = ty.GetMethod("ToString",BindingFlags.Public ||| BindingFlags.Instance,null,[| |],null) -#endif methInfo.DeclaringType = typeof with e -> false /// If "str" ends with "ending" then remove it from "str", otherwise no change. @@ -649,7 +622,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl let combine (strs: string list) = System.String.Concat strs let showL opts leafFormatter layout = - let push x rstrs = x::rstrs + let push x rstrs = x :: rstrs let z0 = [],0 let addText (rstrs,i) (text:string) = push text rstrs,i + text.Length let index (_,i) = i @@ -749,11 +722,11 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl | null -> None | _ -> match getValueInfo bindingFlags (x, ty) with - | ConstructorValue ("Cons",recd) -> Some (unpackCons recd) - | ConstructorValue ("Empty",[]) -> None + | ConstructorValue (_,"Cons",recd) -> Some (unpackCons recd) + | ConstructorValue (_,"Empty",[]) -> None | _ -> failwith "List value had unexpected ValueInfo" - let compactCommaListL xs = sepListL (sepL Literals.comma) xs // compact, no spaces around "," + let structL = wordL (tagKeyword "struct") let nullL = wordL (tagKeyword "null") let measureL = wordL (tagPunctuation "()") @@ -761,18 +734,14 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl // pprinter: attributes // -------------------------------------------------------------------- - let makeRecordVerticalL nameXs = - let itemL (name,xL) = let labelL = wordL name in ((labelL ^^ wordL Literals.equals)) -- (xL ^^ (rightL Literals.semicolon)) - let braceL xs = (leftL Literals.leftBrace) ^^ xs ^^ (rightL Literals.rightBrace) - braceL (aboveListL (List.map itemL nameXs)) - - // This is a more compact rendering of records - and is more like tuples - let makeRecordHorizontalL nameXs = - let itemL (name,xL) = let labelL = wordL name in ((labelL ^^ wordL Literals.equals)) -- xL - let braceL xs = (leftL Literals.leftBrace) ^^ xs ^^ (rightL Literals.rightBrace) - braceL (sepListL (rightL Literals.semicolon) (List.map itemL nameXs)) - - let makeRecordL nameXs = makeRecordVerticalL nameXs + let makeRecordL nameXs = + let itemL (name,xL) = wordL name ^^ wordL Literals.equals -- xL + let braceL xs = (wordL Literals.leftBrace) ^^ xs ^^ (wordL Literals.rightBrace) + + nameXs + |> List.map itemL + |> aboveListL + |> braceL let makePropertiesL nameXs = let itemL (name,v) = @@ -802,16 +771,8 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl // -------------------------------------------------------------------- let getProperty (ty: Type) (obj: obj) name = -#if FX_RESHAPED_REFLECTION - let prop = ty.GetProperty(name, (BindingFlags.Instance ||| BindingFlags.Public ||| BindingFlags.NonPublic)) - if not (isNull prop) then prop.GetValue(obj,[||]) - // Others raise MissingMethodException - else - let msg = System.String.Concat([| "Method '"; ty.FullName; "."; name; "' not found." |]) - raise (System.MissingMethodException(msg)) -#else ty.InvokeMember(name, (BindingFlags.GetProperty ||| BindingFlags.Instance ||| BindingFlags.Public ||| BindingFlags.NonPublic), null, obj, [| |],CultureInfo.InvariantCulture) -#endif + let getField obj (fieldInfo: FieldInfo) = fieldInfo.GetValue(obj) @@ -883,9 +844,9 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl let path = Dictionary(10,HashIdentity.Reference) // Roughly count the "nodes" printed, e.g. leaf items and inner nodes, but not every bracket and comma. - let size = ref opts.PrintSize - let exceededPrintSize() = !size<=0 - let countNodes n = if !size > 0 then size := !size - n else () // no need to keep decrementing (and avoid wrap around) + let mutable size = opts.PrintSize + let exceededPrintSize() = size<=0 + let countNodes n = if size > 0 then size <- size - n else () // no need to keep decrementing (and avoid wrap around) let stopShort _ = exceededPrintSize() // for unfoldL // Recursive descent @@ -937,7 +898,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl let illFormedMatch = System.Text.RegularExpressions.Regex.IsMatch(txt, illFormedBracketPattern) match illFormedMatch with | true -> None // there are mismatched brackets, bail out - | false when layouts.Length > 1 -> Some (spaceListL (List.rev ((wordL (tagText(replaceEscapedBrackets(txt)))::layouts)))) + | false when layouts.Length > 1 -> Some (spaceListL (List.rev ((wordL (tagText(replaceEscapedBrackets(txt))) :: layouts)))) | false -> Some (wordL (tagText(replaceEscapedBrackets(txt)))) | true -> // we have a hit on a property reference @@ -974,7 +935,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl | false -> postText | true -> postTextMatch.Groups.["pre"].Value - let newLayouts = (sepL (tagText preText) ^^ alternativeObjL ^^ sepL (tagText currentPostText))::layouts + let newLayouts = (sepL (tagText preText) ^^ alternativeObjL ^^ sepL (tagText currentPostText)) :: layouts match postText with | "" -> //We are done, build a space-delimited layout from the collection of layouts we've accumulated @@ -997,7 +958,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl | false -> // We are done, there's more text but it doesn't contain any more properties, we need to remove escaped brackets now though // since that wasn't done when creating currentPostText - Some (spaceListL (List.rev ((sepL (tagText preText) ^^ alternativeObjL ^^ sepL (tagText(replaceEscapedBrackets(remaingPropertyText))))::layouts))) + Some (spaceListL (List.rev ((sepL (tagText preText) ^^ alternativeObjL ^^ sepL (tagText(replaceEscapedBrackets(remaingPropertyText)))) :: layouts))) with _ -> None // Seed with an empty layout with a space to the left for formatting purposes @@ -1028,17 +989,20 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl // tuples up args to UnionConstruction or ExceptionConstructor. no node count. match recd with | [(_,x)] -> objL depthLim Precedence.BracketIfTupleOrNotAtomic x - | txs -> leftL Literals.leftParen ^^ compactCommaListL (List.map (snd >> objL depthLim Precedence.BracketIfTuple) txs) ^^ rightL Literals.rightParen + | txs -> leftL Literals.leftParen ^^ commaListL (List.map (snd >> objL depthLim Precedence.BracketIfTuple) txs) ^^ rightL Literals.rightParen and bracketIfL b basicL = if b then (leftL Literals.leftParen) ^^ basicL ^^ (rightL Literals.rightParen) else basicL and reprL showMode depthLim prec repr x (* x could be null *) = let showModeFilter lay = match showMode with ShowAll -> lay | ShowTopLevelBinding -> emptyL - match repr with - | TupleValue vals -> + match repr with + | TupleValue (tupleType, vals) -> let basicL = sepListL (rightL Literals.comma) (List.map (objL depthLim Precedence.BracketIfTuple ) vals) - bracketIfL (prec <= Precedence.BracketIfTuple) basicL + let fields = bracketIfL (prec <= Precedence.BracketIfTuple) basicL + match tupleType with + | TupleType.Value -> structL ^^ fields + | TupleType.Reference -> fields | RecordValue items -> let itemL (name,x,ty) = @@ -1046,7 +1010,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl (tagRecordField name,objL depthLim Precedence.BracketIfTuple (x, ty)) makeRecordL (List.map itemL items) - | ConstructorValue (constr,recd) when // x is List. Note: "null" is never a valid list value. + | ConstructorValue (_,constr,recd) when // x is List. Note: "null" is never a valid list value. x<>null && isListType (x.GetType()) -> match constr with | "Cons" -> @@ -1058,13 +1022,17 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl countNodes 1 wordL (tagPunctuation "[]") - | ConstructorValue(nm,[]) -> + | ConstructorValue(declaringType,nm,recd) -> countNodes 1 - (wordL (tagMethod nm)) - - | ConstructorValue(nm,recd) -> - countNodes 1 // e.g. Some (Some (Some (Some 2))) should count for 5 - (wordL (tagMethod nm) --- recdAtomicTupleL depthLim recd) |> bracketIfL (prec <= Precedence.BracketIfTupleOrNotAtomic) + let caseName = + match declaringType with + | None -> + wordL (tagMethod nm) + | Some declaringType -> + wordL (tagClass declaringType.Name) ^^ sepL (tagPunctuation ".") ^^ wordL (tagMethod nm) + match recd with + | [] -> caseName + | recd -> (caseName --- recdAtomicTupleL depthLim recd) |> bracketIfL (prec <= Precedence.BracketIfTupleOrNotAtomic) | ExceptionValue(ty,recd) -> countNodes 1 @@ -1080,7 +1048,12 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl | ObjectValue(obj) -> match obj with - | null -> (countNodes 1; nullL) + | null -> + countNodes 1 + // If this is the root element, wrap the null with angle brackets + if depthLim = opts.PrintDepth - 1 then + wordL (tagText "") + else nullL | _ -> let ty = obj.GetType() match obj with @@ -1107,7 +1080,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl let b1 = arr.GetLowerBound(0) let project depthLim = if depthLim=(b1+n) then None else Some ((box (arr.GetValue(depthLim)), ty),depthLim+1) let itemLs = boundedUnfoldL (objL depthLim Precedence.BracketIfTuple) project stopShort b1 opts.PrintLength - makeArrayL (if b1 = 0 then itemLs else wordL (tagText("bound1="+string_of_int b1))::itemLs) + makeArrayL (if b1 = 0 then itemLs else wordL (tagText("bound1="+string_of_int b1)) :: itemLs) | 2 -> let n1 = arr.GetLength(0) let n2 = arr.GetLength(1) @@ -1119,7 +1092,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl let rowL x = boundedUnfoldL (objL depthLim Precedence.BracketIfTuple) (project2 x) stopShort b2 opts.PrintLength |> makeListL let project1 x = if x>=(b1+n1) then None else Some (x,x+1) let rowsL = boundedUnfoldL rowL project1 stopShort b1 opts.PrintLength - makeArray2L (if b1=0 && b2 = 0 then rowsL else wordL (tagText("bound1=" + string_of_int b1))::wordL(tagText("bound2=" + string_of_int b2))::rowsL) + makeArray2L (if b1=0 && b2 = 0 then rowsL else wordL (tagText("bound1=" + string_of_int b1)) :: wordL(tagText("bound2=" + string_of_int b2)) :: rowsL) | n -> makeArrayL [wordL (tagText("rank=" + string_of_int n))] @@ -1179,11 +1152,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl // If the leafFormatter was directly here, then layout leaves could store strings. match obj with | _ when opts.ShowProperties -> -#if FX_RESHAPED_REFLECTION - let props = ty.GetProperties(BindingFlags.Instance ||| BindingFlags.Public) -#else let props = ty.GetProperties(BindingFlags.GetField ||| BindingFlags.Instance ||| BindingFlags.Public) -#endif let fields = ty.GetFields(BindingFlags.Instance ||| BindingFlags.Public) |> Array.map (fun i -> i :> MemberInfo) let propsAndFields = props |> Array.map (fun i -> i :> MemberInfo) @@ -1199,10 +1168,10 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl // massively reign in deep printing of properties let nDepth = depthLim/10 #if NETSTANDARD - Array.Sort((propsAndFields),{ new IComparer with member this.Compare(p1,p2) = compare (p1.Name) (p2.Name) } ); -#else - Array.Sort((propsAndFields :> Array),{ new System.Collections.IComparer with member this.Compare(p1,p2) = compare ((p1 :?> MemberInfo).Name) ((p2 :?> MemberInfo).Name) } ); -#endif + Array.Sort((propsAndFields),{ new IComparer with member this.Compare(p1,p2) = compare (p1.Name) (p2.Name) } ) +#else + Array.Sort((propsAndFields :> Array),{ new System.Collections.IComparer with member this.Compare(p1,p2) = compare ((p1 :?> MemberInfo).Name) ((p2 :?> MemberInfo).Name) } ) +#endif if propsAndFields.Length = 0 || (nDepth <= 0) then basicL else basicL --- @@ -1313,12 +1282,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl let fsi_any_to_layout opts x = anyL ShowTopLevelBinding BindingFlags.Public opts x #else // FSharp.Core -#if FX_RESHAPED_REFLECTION - let internal anyToStringForPrintf options (showNonPublicMembers : bool) x = - let bindingFlags = ReflectionUtils.toBindingFlags showNonPublicMembers -#else let internal anyToStringForPrintf options (bindingFlags:BindingFlags) x = -#endif x |> anyL ShowAll bindingFlags options |> layout_to_string options #endif diff --git a/src/fcs-fable/src/utils/sformat.fsi b/src/fcs-fable/src/utils/sformat.fsi old mode 100755 new mode 100644 index 8afd5f56f9..b40e399c8d --- a/src/fcs-fable/src/utils/sformat.fsi +++ b/src/fcs-fable/src/utils/sformat.fsi @@ -304,11 +304,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl StringLimit: int; #endif FormatProvider: System.IFormatProvider -#if FX_RESHAPED_REFLECTION - ShowNonPublic : bool -#else BindingFlags: System.Reflection.BindingFlags -#endif PrintWidth : int PrintDepth : int PrintLength : int @@ -343,11 +339,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl #if FSHARP_CORE // FSharp.Core.dll: Most functions aren't needed in FSharp.Core.dll, but we add one entry for printf -#if FX_RESHAPED_REFLECTION - val anyToStringForPrintf: options:FormatOptions -> showNonPublicMembers : bool -> value:'T * Type -> string -#else val anyToStringForPrintf: options:FormatOptions -> bindingFlags:System.Reflection.BindingFlags -> value:'T * Type -> string -#endif #else val asTaggedTextWriter: writer: TextWriter -> TaggedTextWriter val any_to_layout : options:FormatOptions -> value:'T * Type -> Layout diff --git a/src/fcs-fable/test/Metadata.fs b/src/fcs-fable/test/Metadata.fs index 93bdc0cee4..64ea889fd8 100644 --- a/src/fcs-fable/test/Metadata.fs +++ b/src/fcs-fable/test/Metadata.fs @@ -13,10 +13,13 @@ let references_core = [| "System.Console" "System.Core" "System.Diagnostics.Debug" + "System.Diagnostics.Tools" "System.Diagnostics.Tracing" "System.Globalization" "System" "System.IO" + "System.Net.Requests" + "System.Net.WebClient" "System.Numerics" "System.Reflection" "System.Reflection.Extensions" @@ -32,167 +35,173 @@ let references_core = [| "System.Threading" "System.Threading.Tasks" "System.ValueTuple" -|] + |] -let references use_net45_meta = - if use_net45_meta then - [|"Fable.Core" - "Fable.Import.Browser" - "FSharp.Core" - "mscorlib" - "System" - "System.Core" - "System.Data" - "System.IO" - "System.Xml" - "System.Numerics" - |] - else - [|"Fable.Core" - "Fable.Import.Browser" - "FSharp.Core" - "Microsoft.CSharp" - "Microsoft.VisualBasic" - "Microsoft.Win32.Primitives" - "mscorlib" - "netstandard" - "System.AppContext" - "System.Buffers" - "System.Collections.Concurrent" - "System.Collections" - "System.Collections.Immutable" - "System.Collections.NonGeneric" - "System.Collections.Specialized" - "System.ComponentModel.Annotations" - //"System.ComponentModel.Composition" // removed in 2.1.300 - "System.ComponentModel.DataAnnotations" - "System.ComponentModel" - "System.ComponentModel.EventBasedAsync" - "System.ComponentModel.Primitives" - "System.ComponentModel.TypeConverter" - "System.Configuration" - "System.Console" - "System.Core" - "System.Data.Common" - "System.Data" - "System.Diagnostics.Contracts" - "System.Diagnostics.Debug" - "System.Diagnostics.DiagnosticSource" - "System.Diagnostics.FileVersionInfo" - "System.Diagnostics.Process" - "System.Diagnostics.StackTrace" - "System.Diagnostics.TextWriterTraceListener" - "System.Diagnostics.Tools" - "System.Diagnostics.TraceSource" - "System.Diagnostics.Tracing" - "System" - "System.Drawing" - "System.Drawing.Primitives" - "System.Dynamic.Runtime" - "System.Globalization.Calendars" - "System.Globalization" - "System.Globalization.Extensions" - //"System.IO.Compression.Brotli" // added in 2.1.300 - "System.IO.Compression" - "System.IO.Compression.FileSystem" - "System.IO.Compression.ZipFile" - "System.IO" - "System.IO.FileSystem" - "System.IO.FileSystem.DriveInfo" - "System.IO.FileSystem.Primitives" - "System.IO.FileSystem.Watcher" - "System.IO.IsolatedStorage" - "System.IO.MemoryMappedFiles" - "System.IO.Pipes" - "System.IO.UnmanagedMemoryStream" - "System.Linq" - "System.Linq.Expressions" - "System.Linq.Parallel" - "System.Linq.Queryable" - //"System.Memory" // added in 2.1.300 - "System.Net" - "System.Net.Http" - "System.Net.HttpListener" - "System.Net.Mail" - "System.Net.NameResolution" - "System.Net.NetworkInformation" - "System.Net.Ping" - "System.Net.Primitives" - "System.Net.Requests" - "System.Net.Security" - "System.Net.ServicePoint" - "System.Net.Sockets" - "System.Net.WebClient" - "System.Net.WebHeaderCollection" - "System.Net.WebProxy" - "System.Net.WebSockets.Client" - "System.Net.WebSockets" - "System.Numerics" - "System.Numerics.Vectors" - "System.ObjectModel" - "System.Reflection.DispatchProxy" - "System.Reflection" - "System.Reflection.Emit" - "System.Reflection.Emit.ILGeneration" - "System.Reflection.Emit.Lightweight" - "System.Reflection.Extensions" - "System.Reflection.Metadata" - "System.Reflection.Primitives" - "System.Reflection.TypeExtensions" - "System.Resources.Reader" - "System.Resources.ResourceManager" - "System.Resources.Writer" - "System.Runtime.CompilerServices.VisualC" - "System.Runtime" - "System.Runtime.Extensions" - "System.Runtime.Handles" - "System.Runtime.InteropServices" - "System.Runtime.InteropServices.RuntimeInformation" - "System.Runtime.InteropServices.WindowsRuntime" - "System.Runtime.Loader" - "System.Runtime.Numerics" - "System.Runtime.Serialization" - "System.Runtime.Serialization.Formatters" - "System.Runtime.Serialization.Json" - "System.Runtime.Serialization.Primitives" - "System.Runtime.Serialization.Xml" - "System.Security.Claims" - "System.Security.Cryptography.Algorithms" - "System.Security.Cryptography.Csp" - "System.Security.Cryptography.Encoding" - "System.Security.Cryptography.Primitives" - "System.Security.Cryptography.X509Certificates" - "System.Security" - "System.Security.Principal" - "System.Security.SecureString" - "System.ServiceModel.Web" - "System.ServiceProcess" - "System.Text.Encoding" - "System.Text.Encoding.Extensions" - "System.Text.RegularExpressions" - "System.Threading" - "System.Threading.Overlapped" - "System.Threading.Tasks.Dataflow" - "System.Threading.Tasks" - "System.Threading.Tasks.Extensions" - "System.Threading.Tasks.Parallel" - "System.Threading.Thread" - "System.Threading.ThreadPool" - "System.Threading.Timer" - "System.Transactions" - "System.Transactions.Local" - "System.ValueTuple" - "System.Web" - "System.Web.HttpUtility" - "System.Windows" - "System.Xml" - "System.Xml.Linq" - "System.Xml.ReaderWriter" - "System.Xml.Serialization" - "System.Xml.XDocument" - "System.Xml.XmlDocument" - "System.Xml.XmlSerializer" - "System.Xml.XPath" - "System.Xml.XPath.XDocument" - "WindowsBase" - |] +let references_net45 = [| + "Fable.Core" + "Fable.Import.Browser" + "FSharp.Core" + "mscorlib" + "System" + "System.Core" + "System.Data" + "System.IO" + "System.Xml" + "System.Numerics" + |] + +let references_full = [| + "Fable.Core" + "FSharp.Core" + "Microsoft.CSharp" + "Microsoft.VisualBasic.Core" + "Microsoft.VisualBasic" + "Microsoft.Win32.Primitives" + "mscorlib" + "netstandard" + "System.AppContext" + "System.Buffers" + "System.Collections.Concurrent" + "System.Collections" + "System.Collections.Immutable" + "System.Collections.NonGeneric" + "System.Collections.Specialized" + "System.ComponentModel.Annotations" + "System.ComponentModel.DataAnnotations" + "System.ComponentModel" + "System.ComponentModel.EventBasedAsync" + "System.ComponentModel.Primitives" + "System.ComponentModel.TypeConverter" + "System.Configuration" + "System.Console" + "System.Core" + "System.Data.Common" + "System.Data.DataSetExtensions" + "System.Data" + "System.Diagnostics.Contracts" + "System.Diagnostics.Debug" + "System.Diagnostics.DiagnosticSource" + "System.Diagnostics.FileVersionInfo" + "System.Diagnostics.Process" + "System.Diagnostics.StackTrace" + "System.Diagnostics.TextWriterTraceListener" + "System.Diagnostics.Tools" + "System.Diagnostics.TraceSource" + "System.Diagnostics.Tracing" + "System" + "System.Drawing" + "System.Drawing.Primitives" + "System.Dynamic.Runtime" + "System.Globalization.Calendars" + "System.Globalization" + "System.Globalization.Extensions" + "System.IO.Compression.Brotli" + "System.IO.Compression" + "System.IO.Compression.FileSystem" + "System.IO.Compression.ZipFile" + "System.IO" + "System.IO.FileSystem" + "System.IO.FileSystem.DriveInfo" + "System.IO.FileSystem.Primitives" + "System.IO.FileSystem.Watcher" + "System.IO.IsolatedStorage" + "System.IO.MemoryMappedFiles" + "System.IO.Pipes" + "System.IO.UnmanagedMemoryStream" + "System.Linq" + "System.Linq.Expressions" + "System.Linq.Parallel" + "System.Linq.Queryable" + "System.Memory" + "System.Net" + "System.Net.Http" + "System.Net.HttpListener" + "System.Net.Mail" + "System.Net.NameResolution" + "System.Net.NetworkInformation" + "System.Net.Ping" + "System.Net.Primitives" + "System.Net.Requests" + "System.Net.Security" + "System.Net.ServicePoint" + "System.Net.Sockets" + "System.Net.WebClient" + "System.Net.WebHeaderCollection" + "System.Net.WebProxy" + "System.Net.WebSockets.Client" + "System.Net.WebSockets" + "System.Numerics" + "System.Numerics.Vectors" + "System.ObjectModel" + "System.Reflection.DispatchProxy" + "System.Reflection" + "System.Reflection.Emit" + "System.Reflection.Emit.ILGeneration" + "System.Reflection.Emit.Lightweight" + "System.Reflection.Extensions" + "System.Reflection.Metadata" + "System.Reflection.Primitives" + "System.Reflection.TypeExtensions" + "System.Resources.Reader" + "System.Resources.ResourceManager" + "System.Resources.Writer" + "System.Runtime.CompilerServices.Unsafe" + "System.Runtime.CompilerServices.VisualC" + "System.Runtime" + "System.Runtime.Extensions" + "System.Runtime.Handles" + "System.Runtime.InteropServices" + "System.Runtime.InteropServices.RuntimeInformation" + "System.Runtime.InteropServices.WindowsRuntime" + "System.Runtime.Intrinsics" + "System.Runtime.Loader" + "System.Runtime.Numerics" + "System.Runtime.Serialization" + "System.Runtime.Serialization.Formatters" + "System.Runtime.Serialization.Json" + "System.Runtime.Serialization.Primitives" + "System.Runtime.Serialization.Xml" + "System.Security.Claims" + "System.Security.Cryptography.Algorithms" + "System.Security.Cryptography.Csp" + "System.Security.Cryptography.Encoding" + "System.Security.Cryptography.Primitives" + "System.Security.Cryptography.X509Certificates" + "System.Security" + "System.Security.Principal" + "System.Security.SecureString" + "System.ServiceModel.Web" + "System.ServiceProcess" + "System.Text.Encoding.CodePages" + "System.Text.Encoding" + "System.Text.Encoding.Extensions" + "System.Text.Encodings.Web" + "System.Text.Json" + "System.Text.RegularExpressions" + "System.Threading.Channels" + "System.Threading" + "System.Threading.Overlapped" + "System.Threading.Tasks.Dataflow" + "System.Threading.Tasks" + "System.Threading.Tasks.Extensions" + "System.Threading.Tasks.Parallel" + "System.Threading.Thread" + "System.Threading.ThreadPool" + "System.Threading.Timer" + "System.Transactions" + "System.Transactions.Local" + "System.ValueTuple" + "System.Web" + "System.Web.HttpUtility" + "System.Windows" + "System.Xml" + "System.Xml.Linq" + "System.Xml.ReaderWriter" + "System.Xml.Serialization" + "System.Xml.XDocument" + "System.Xml.XmlDocument" + "System.Xml.XmlSerializer" + "System.Xml.XPath" + "System.Xml.XPath.XDocument" + "WindowsBase" + |] diff --git a/src/fcs-fable/test/Platform.fs b/src/fcs-fable/test/Platform.fs index f6adec9f67..a3878b1a86 100644 --- a/src/fcs-fable/test/Platform.fs +++ b/src/fcs-fable/test/Platform.fs @@ -15,10 +15,12 @@ let measureTime (f: 'a -> 'b) x = sw.ElapsedMilliseconds, res let normalizeFullPath (path: string) = + let path = if System.String.IsNullOrWhiteSpace path then "." else path Path.GetFullPath(path).Replace('\\', '/') -let getRelativePath (pathFrom: string) (pathTo: string) = - Path.GetRelativePath(pathFrom, pathTo).Replace('\\', '/') +let getRelativePath (path: string) (pathTo: string) = + let path = if System.String.IsNullOrWhiteSpace path then "." else path + Path.GetRelativePath(path, pathTo).Replace('\\', '/') #else @@ -55,8 +57,8 @@ let measureTime (f: 'a -> 'b) x = let normalizeFullPath (path: string) = JS.Path.resolve(path).Replace('\\', '/') -let getRelativePath (pathFrom: string) (pathTo: string) = - JS.Path.relative(pathFrom, pathTo).Replace('\\', '/') +let getRelativePath (path: string) (pathTo: string) = + JS.Path.relative(path, pathTo).Replace('\\', '/') #endif diff --git a/src/fcs-fable/test/ProjectParser.fs b/src/fcs-fable/test/ProjectParser.fs index 20a4e05342..eac497e38b 100644 --- a/src/fcs-fable/test/ProjectParser.fs +++ b/src/fcs-fable/test/ProjectParser.fs @@ -78,14 +78,12 @@ let parseCompilerOptions projectText = |] otherOptions -let parseProjectScript projectPath = - let projectFileName = Path.GetFileName projectPath - let projectText = readAllText projectPath - let projectDir = Path.GetDirectoryName projectPath +let parseProjectScript projectFileName = + let projectText = readAllText projectFileName + let projectDir = Path.GetDirectoryName projectFileName let dllRefs, srcFiles = (([||], [||]), projectText.Split('\n')) ||> Array.fold (fun (dllRefs, srcFiles) line -> - let line = line.Trim() match line.Trim() with | Regex @"^#r\s+""(.*?)""$" [_;path] when not(path.EndsWith("Fable.Core.dll")) -> @@ -94,13 +92,12 @@ let parseProjectScript projectPath = dllRefs, Array.append [|Path.Combine(projectDir, path)|] srcFiles | _ -> dllRefs, srcFiles) let projectRefs = [||] - let sourceFiles = Array.append srcFiles [|Path.GetFileName projectPath|] + let sourceFiles = Array.append srcFiles [|Path.GetFileName projectFileName|] let otherOptions = [| "--define:FABLE_COMPILER" |] - (projectFileName, dllRefs, projectRefs, sourceFiles, otherOptions) + (dllRefs, projectRefs, sourceFiles, otherOptions) -let parseProjectFile projectPath = - let projectFileName = Path.GetFileName projectPath - let projectText = readAllText projectPath +let parseProjectFile projectFileName = + let projectText = readAllText projectFileName // remove all comments let projectText = Regex.Replace(projectText, @"", "") @@ -126,7 +123,7 @@ let parseProjectFile projectPath = let dllRefs = [||] let otherOptions = parseCompilerOptions projectText - (projectFileName, dllRefs, projectRefs, sourceFiles, otherOptions) + (dllRefs, projectRefs, sourceFiles, otherOptions) let makeHashSetIgnoreCase () = let equalityComparerIgnoreCase = @@ -154,13 +151,13 @@ let dedupFileNames (fileSet: HashSet) fileNames = fileName fileNames |> Array.map dedup -let rec parseProject (projSet: HashSet) (projectPath: string) = - let (projectFileName, dllRefs, projectRefs, sourceFiles, otherOptions) = - if projectPath.EndsWith(".fsx") - then parseProjectScript projectPath - else parseProjectFile projectPath +let rec parseProject (projSet: HashSet) (projectFileName: string) = + let (dllRefs, projectRefs, sourceFiles, otherOptions) = + if projectFileName.EndsWith(".fsx") + then parseProjectScript projectFileName + else parseProjectFile projectFileName - let projectFileDir = Path.GetDirectoryName projectPath + let projectFileDir = Path.GetDirectoryName projectFileName let isAbsolutePath (path: string) = path.StartsWith("/") || path.IndexOf(":") = 1 let makePath path = if isAbsolutePath path then path @@ -172,8 +169,8 @@ let rec parseProject (projSet: HashSet) (projectPath: string) = // parse and combine all referenced projects into one big project let parsedProjects = projectRefs |> Array.map makePath |> dedupProjectRefs projSet |> Array.map (parseProject projSet) - let sourcePaths = sourcePaths |> Array.append (parsedProjects |> Array.collect (fun (_,_,x,_,_) -> x)) - let sourceTexts = sourceTexts |> Array.append (parsedProjects |> Array.collect (fun (_,_,_,x,_) -> x)) - let otherOptions = otherOptions |> Array.append (parsedProjects |> Array.collect (fun (_,_,_,_,x) -> x)) + let sourcePaths = sourcePaths |> Array.append (parsedProjects |> Array.collect (fun (_,x,_,_) -> x)) + let sourceTexts = sourceTexts |> Array.append (parsedProjects |> Array.collect (fun (_,_,x,_) -> x)) + let otherOptions = otherOptions |> Array.append (parsedProjects |> Array.collect (fun (_,_,_,x) -> x)) - (projectFileName, dllRefs, sourcePaths, sourceTexts, otherOptions |> Array.distinct) + (dllRefs, sourcePaths, sourceTexts, otherOptions |> Array.distinct) diff --git a/src/fcs-fable/test/bench/bench.fs b/src/fcs-fable/test/bench/bench.fs index 1a0329bd3d..801677d27f 100644 --- a/src/fcs-fable/test/bench/bench.fs +++ b/src/fcs-fable/test/bench/bench.fs @@ -5,15 +5,14 @@ open Fable.Compiler.Platform open Fable.Compiler.ProjectParser let references = Metadata.references_core -let metadataPath = "/temp/repl/metadata2/" // .NET BCL binaries +let metadataPath = "/Projects/Fable/src/fable-metadata/lib/" // .NET BCL binaries let printErrors showWarnings (errors: FSharpErrorInfo[]) = let isWarning (e: FSharpErrorInfo) = e.Severity = FSharpErrorSeverity.Warning let printError (e: FSharpErrorInfo) = let errorType = (if isWarning e then "Warning" else "Error") - printfn "%s (%d,%d--%d,%d): %s: %s" e.FileName e.EndLineAlternate - e.StartColumn e.EndLineAlternate e.EndColumn errorType e.Message + printfn "%s (%d,%d): %s: %s" e.FileName e.StartLineAlternate e.StartColumn errorType e.Message let warnings, errors = errors |> Array.partition isWarning let hasErrors = not (Array.isEmpty errors) if showWarnings then @@ -22,10 +21,10 @@ let printErrors showWarnings (errors: FSharpErrorInfo[]) = errors |> Array.iter printError failwith "Too many errors." -let parseFiles projectPath outDir optimize = +let parseFiles projectFileName outDir optimize = // parse project let projSet = makeHashSetIgnoreCase () - let (projectFileName, dllRefs, fileNames, sources, otherOptions) = parseProject projSet projectPath + let (dllRefs, fileNames, sources, otherOptions) = parseProject projSet projectFileName // dedup file names let fileSet = makeHashSetIgnoreCase () @@ -95,10 +94,10 @@ let parseArguments (argv: string[]) = let usage = "Usage: bench [--options]" let opts, args = argv |> Array.partition (fun s -> s.StartsWith("--")) match args with - | [| projectPath |] -> + | [| projectFileName |] -> let outDir = "./out-test" let optimize = opts |> Array.contains "--optimize-fcs" - parseFiles projectPath outDir optimize + parseFiles projectFileName outDir optimize | _ -> printfn "%s" usage [] diff --git a/src/fcs-fable/test/bench/fcs-fable-bench.fsproj b/src/fcs-fable/test/bench/fcs-fable-bench.fsproj index f2e8c6d0bc..50636c4d92 100644 --- a/src/fcs-fable/test/bench/fcs-fable-bench.fsproj +++ b/src/fcs-fable/test/bench/fcs-fable-bench.fsproj @@ -2,7 +2,7 @@ Exe - netcoreapp2.2 + netcoreapp3.1 $(DefineConstants);DOTNET_FILE_SYSTEM true @@ -19,8 +19,8 @@ - - + + diff --git a/src/fcs-fable/test/fcs-fable-test.fsproj b/src/fcs-fable/test/fcs-fable-test.fsproj index 5214e3d6aa..2ef9c546dd 100644 --- a/src/fcs-fable/test/fcs-fable-test.fsproj +++ b/src/fcs-fable/test/fcs-fable-test.fsproj @@ -2,7 +2,7 @@ Exe - netcoreapp2.2 + netcoreapp3.1 $(DefineConstants);DOTNET_FILE_SYSTEM true @@ -18,8 +18,8 @@ - - + + diff --git a/src/fcs-fable/test/package.json b/src/fcs-fable/test/package.json index cb72ec2c1e..12b0c43302 100644 --- a/src/fcs-fable/test/package.json +++ b/src/fcs-fable/test/package.json @@ -1,15 +1,15 @@ { "private": true, + "type": "module", "scripts": { - "build-test": "dotnet run -c Release -p ../../../../Fable/src/dotnet/Fable.Compiler npm-splitter", - "splitter": "node ./node_modules/fable-splitter/dist/cli --commonjs", + "build-test": "dotnet build -c Release fcs-fable-test.fsproj", + "build-bench": "dotnet build -c Release bench/fcs-fable-bench.fsproj", + "build-node": "fable fcs-fable-test.fsproj out-test", "test-node": "node out-test/test", "test-dotnet": "dotnet run -c Release -p fcs-fable-test.fsproj", "bench-dotnet": "dotnet run -c Release -p bench/fcs-fable-bench.fsproj ../fcs-fable.fsproj" }, "devDependencies": { - "@babel/core": "^7.4.0", - "@babel/plugin-transform-modules-commonjs": "^7.4.0", - "fable-splitter": "^2.1.6" + "fable-compiler-js": "^1.3.1" } } diff --git a/src/fcs-fable/test/splitter.config.js b/src/fcs-fable/test/splitter.config.js index 7995bac7a8..428407dfe0 100644 --- a/src/fcs-fable/test/splitter.config.js +++ b/src/fcs-fable/test/splitter.config.js @@ -10,12 +10,9 @@ const babelOptions = useCommonjs const fableOptions = { define: [ "FX_NO_CORHOST_SIGNER", - "FX_NO_LINKEDRESOURCES", "FX_NO_PDB_READER", "FX_NO_PDB_WRITER", "FX_NO_WEAKTABLE", - "FX_REDUCED_EXCEPTIONS", - "NO_COMPILER_BACKEND", "NO_EXTENSIONTYPING", "NO_INLINE_IL_PARSER" ], diff --git a/src/fcs-fable/test/test.fs b/src/fcs-fable/test/test.fs index 4bcdc54b22..979c3fed6c 100644 --- a/src/fcs-fable/test/test.fs +++ b/src/fcs-fable/test/test.fs @@ -5,10 +5,10 @@ open FSharp.Compiler.SourceCodeServices open Fable.Compiler.Platform let references = Metadata.references_core -let metadataPath = "/temp/repl/metadata2/" // .NET BCL binaries +let metadataPath = "/Projects/Fable/src/fable-metadata/lib/" // .NET BCL binaries [] -let main argv = +let main _argv = printfn "Parsing begins..." let defines = [||] diff --git a/src/fcs-fable/test/test_script.fsx b/src/fcs-fable/test/test_script.fsx index 1bbe729ab7..344a81772e 100644 --- a/src/fcs-fable/test/test_script.fsx +++ b/src/fcs-fable/test/test_script.fsx @@ -4,5 +4,6 @@ open Fable.Import let foo() = let msg = String.Concat("Hello"," ","world") let len = msg.Length - let canvas = Browser.document.createElement_canvas () - canvas.width <- 1000. + // let canvas = Browser.document.createElement_canvas () + // canvas.width <- 1000. + () \ No newline at end of file diff --git a/src/quicktest/QuickTest.fs b/src/quicktest/QuickTest.fs index 51fff5ba93..4fc6bb9397 100644 --- a/src/quicktest/QuickTest.fs +++ b/src/quicktest/QuickTest.fs @@ -1,9 +1,10 @@ module QuickTest -// Run a full build (or at least build fable-library) before playing with this file -// Run `npm run quicktest` to start compiler in watch mode and write your tests below -// You can check the compiled JS in the "bin" folder within this directory -// Please don't add this file to your commits +// Run `npm run build quicktest` and then add tests to this file, +// when you save they will be run automatically with latest changes in compiler and fable-library. +// When everything works, move the tests to the appropiate file in tests/Main. +// You can check the compiled JS in the "bin" folder within this directory. +// Please don't add this file to your commits. open System open System.Collections.Generic diff --git a/src/quicktest/QuickTest.fsproj b/src/quicktest/QuickTest.fsproj new file mode 100644 index 0000000000..3c6e0ebfaa --- /dev/null +++ b/src/quicktest/QuickTest.fsproj @@ -0,0 +1,15 @@ + + + Exe + netcoreapp2.1 + Major + preview + + + + + + + + + \ No newline at end of file diff --git a/src/quicktest/Quicktest.fsproj b/src/quicktest/Quicktest.fsproj deleted file mode 100644 index 8f54543f04..0000000000 --- a/src/quicktest/Quicktest.fsproj +++ /dev/null @@ -1,13 +0,0 @@ - - - Exe - netcoreapp2.0 - - - - - - - - - \ No newline at end of file diff --git a/src/quicktest/splitter.config.js b/src/quicktest/splitter.config.js index 8256e7c00b..e5c620d90d 100644 --- a/src/quicktest/splitter.config.js +++ b/src/quicktest/splitter.config.js @@ -6,8 +6,11 @@ module.exports = { // outDir: resolve("temp"), // port: 61225, fable: { - define: ["DEBUG"] + define: [] //["DEBUG"] }, + babel: { + sourceMaps: true + } // allFiles: true }; diff --git a/src/tools/ASTViewer/ASTViewer.fsproj b/src/tools/ASTViewer/ASTViewer.fsproj index d084ee64aa..b3b7184a85 100644 --- a/src/tools/ASTViewer/ASTViewer.fsproj +++ b/src/tools/ASTViewer/ASTViewer.fsproj @@ -2,6 +2,7 @@ Exe netcoreapp2.1 + Major true @@ -9,8 +10,8 @@ - - + + diff --git a/src/tools/InjectProcessor/InjectProcessor.fs b/src/tools/InjectProcessor/InjectProcessor.fs index 33d046ce59..2d16b33218 100644 --- a/src/tools/InjectProcessor/InjectProcessor.fs +++ b/src/tools/InjectProcessor/InjectProcessor.fs @@ -84,7 +84,7 @@ let rec getInjects initialized decls = let main _argv = printfn "Checking methods in Fable.Library with last argument decorated with Inject..." let checker = FSharpChecker.Create(keepAssemblyContents=true) - let proj = parse checker (IO.Path.Combine(__SOURCE_DIRECTORY__,"../../js/fable-library/Fable.Library.fsproj")) + let proj = parse checker (IO.Path.Combine(__SOURCE_DIRECTORY__,"../../fable-library/Fable.Library.fsproj")) let lines = seq { yield """/// AUTOMATICALLY GENERATED - DO NOT TOUCH! @@ -124,6 +124,6 @@ let fableReplacementsModules = yield " ]" yield " ]\n" } - File.WriteAllLines(IO.Path.Combine(__SOURCE_DIRECTORY__,"../../dotnet/Fable.Compiler/Transforms/ReplacementsInject.fs"), lines) + File.WriteAllLines(IO.Path.Combine(__SOURCE_DIRECTORY__,"../../Fable.Transforms/ReplacementsInject.fs"), lines) printfn "Finished!" 0 diff --git a/src/tools/InjectProcessor/InjectProcessor.fsproj b/src/tools/InjectProcessor/InjectProcessor.fsproj index 05ada548cf..f8ce9d4e0f 100644 --- a/src/tools/InjectProcessor/InjectProcessor.fsproj +++ b/src/tools/InjectProcessor/InjectProcessor.fsproj @@ -1,16 +1,20 @@ Exe - netcoreapp2.0 + netcoreapp2.1 + Major + true - - - + + + + - - + + + diff --git a/src/tools/build-utils.js b/src/tools/build-utils.js deleted file mode 100644 index 0e5ad85fe6..0000000000 --- a/src/tools/build-utils.js +++ /dev/null @@ -1,33 +0,0 @@ -const path = require("path"); -const shell = require("shelljs"); -shell.config.verbose = true; - -module.exports = { - runNpmBin, - runTargets -}; - -const REPO_ROOT_DIR = path.join(__dirname, "../../.."); - -async function runNpmBin(name, args) { - const isWin = process.platform === "win32"; - const res = await shell.exec(`${path.join(REPO_ROOT_DIR, "node_modules/.bin", name + (isWin ? ".cmd" : ""))} ${args || ""}`); - if (res.code !== 0) { - throw new Error(`${name} failed with code ${res.code}`); - } -} - -function runTargets(targets) { - const args = process.argv.slice(2); - const [target, restArgs] = - typeof args[0] === "string" && !args[0].startsWith("--") - ? [args[0].toLowerCase(), args.splice(1)] - : ["build", args]; - const res = targets[target].apply(targets, restArgs); - if (res instanceof Promise) { - res.then(() => {}, er => { - console.error(er); - process.exit(1); - }) - } -} \ No newline at end of file diff --git a/tests/Main/ApplicativeTests.fs b/tests/Main/ApplicativeTests.fs index 93980a7170..56e1ccf4d6 100644 --- a/tests/Main/ApplicativeTests.fs +++ b/tests/Main/ApplicativeTests.fs @@ -389,6 +389,8 @@ let update (model: RecordA) action = | CheckboxChanged (id, value, lens) -> Optic.set (RecordA.RecordB_ >-> lens) value model +type Item2 = static member inline Invoke value = (^t : (member Item2 : _) value) + type Id = Id of string type Ideable = @@ -501,6 +503,9 @@ let tests5 = [ input2 |> equal "bar" checkbox2 |> equal true + testCase "Trait calls work with tuples" <| fun () -> + Item2.Invoke (1,2,3) |> equal 2 + testCase "Trait calls work with record fields" <| fun () -> let ar = [| {Id=Id"foo"; Name="Sarah"}; {Id=Id"bar"; Name="James"} |] replaceById {Id=Id"ja"; Name="Voll"} ar |> Seq.head |> fun x -> equal "Sarah" x.Name @@ -833,6 +838,11 @@ module private PseudoElmish = setState = (fun m d -> setStateAccumulated <- setStateAccumulated + m) } +let mul x y = x * y + +let addOne (add: int->int->int) x = add 1 x +let pointFree_addOne = addOne + let tests7 = [ testCase "SRTP with ActivePattern works" <| fun () -> (lengthWrapper []) |> equal 0 @@ -1086,8 +1096,38 @@ let tests7 = [ setState 2 doMapCalled |> equal 1 doMapResultCalled |> equal 2 + + testCase "OptimizedClosures.FSharpFunc<_,_,_>.Adapt works" <| fun () -> // See #1904 + let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt (fun x y -> x + y) + f.Invoke(3, 4) |> equal 7 + let f2 = OptimizedClosures.FSharpFunc<_,_,_>.Adapt mul + f2.Invoke(3, 4) |> equal 12 + + testCase "Arguments passed to point-free function are uncurried" <| fun () -> // See #1959 + let x = pointFree_addOne (+) 2 + let y = addOne (+) 2 + equal 3 x + equal 3 y ] +// Test ported directly from https://github.com/fable-compiler/Fable/pull/1336/files +let private SomeProcedure (s: string): unit = failwith "Never called" +let private SomeFunction (s: string): string = s + +[] +let private getName (f: obj) = failwith "JS only" + +let tests8 = + [ + #if FABLE_COMPILER + testCase "Functions passed as parameters don't generate intermediate anonymous functions" <| fun () -> + let functionName = getName SomeFunction + equal "SomeFunction" functionName + let procedureName = getName SomeProcedure + equal "SomeProcedure" procedureName + #endif + ] + let tests = testList "Applicative" ( tests1 @@ -1097,5 +1137,6 @@ let tests = @ tests5 @ tests6 @ tests7 + @ tests8 @ CurriedApplicative.tests ) diff --git a/tests/Main/ArithmeticTests.fs b/tests/Main/ArithmeticTests.fs index 1b362639eb..78476f1ad1 100644 --- a/tests/Main/ArithmeticTests.fs +++ b/tests/Main/ArithmeticTests.fs @@ -209,6 +209,14 @@ let tests = Math.Round 1.546M |> equal 2.M Math.Round -1.546M |> equal -2.M + testCase "Decimal round half to even works" <| fun () -> + round 1.5M |> equal 2.M + round 2.5M |> equal 2.M + round 3.5M |> equal 4.M + round -1.5M |> equal -2.M + round -2.5M |> equal -2.M + round -3.5M |> equal -4.M + testCase "Decimal round with digits works" <| fun () -> Math.Round(1.426M, 2) |> equal 1.43M Math.Round(1.426M, 1) |> equal 1.4M @@ -601,4 +609,37 @@ let tests = sign -72L |> equal -1 sign -1. |> equal -1 sign -89. |> equal -1 -] \ No newline at end of file + + testCase "Formatting of decimal works" <| fun () -> + + let formatNumber (d:decimal) = + (sprintf "%.2f" d).Replace(",","").Replace(".",",") + + formatNumber 0.0M |> equal "0,00" + formatNumber 0.020M |> equal "0,02" + formatNumber 0.20M |> equal "0,20" + formatNumber 2.0M |> equal "2,00" + + + testCase "Formatting of decimal works with inline" <| fun () -> + + let inline formatNumber (d:decimal) = + (sprintf "%.2f" d).Replace(",","").Replace(".",",") + + formatNumber 0.0M |> equal "0,00" + formatNumber 0.020M |> equal "0,02" + formatNumber 0.20M |> equal "0,20" + formatNumber 2.0M |> equal "2,00" + + testCase "Formatting of € works with inline" <| fun () -> + + let inline formatNumber (d:decimal) = + (sprintf "%.2f" d).Replace(",","").Replace(".",",") + + let inline formatEuro (d:decimal) = (formatNumber d) + " €" + + formatEuro 0.0M |> equal "0,00 €" + formatEuro 0.020M |> equal "0,02 €" + formatEuro 0.20M |> equal "0,20 €" + formatEuro 2.0M |> equal "2,00 €" +] diff --git a/tests/Main/ArrayTests.fs b/tests/Main/ArrayTests.fs index fa16631a74..049d5ba8e4 100644 --- a/tests/Main/ArrayTests.fs +++ b/tests/Main/ArrayTests.fs @@ -2,6 +2,7 @@ module Fable.Tests.Arrays open System open Util.Testing +open Fable.Tests.Util type ParamArrayTest = static member Add([] xs: int[]) = Array.sum xs @@ -116,7 +117,7 @@ let tests = ar.[0] <- ar.[0] + 255uy equal 4uy ar.[0] - // TODO: How to test at the same time that both clamped and non-clampled arrays work? + // TODO: How to test at the same time that both clamped and non-clamped arrays work? // #if FABLE_COMPILER // testCase "Clamped byte arrays work" <| fun () -> // let ar = DllRef.Lib.createClampedArray() @@ -182,6 +183,12 @@ let tests = equal 2 xs.Length equal 0 xs.[1] + // See https://github.com/fable-compiler/repl/issues/96 + testCase "Array.zeroCreate works with KeyValuePair" <| fun () -> + let a = Array.zeroCreate> 3 + equal 0. a.[1].Key + equal false a.[2].Value + testCase "Array.create works" <| fun () -> let xs = Array.create 2 5 equal 2 xs.Length @@ -328,6 +335,11 @@ let tests = let ys = xs |> Array.filter (fun x -> x > 2s) ys.Length |> equal 2 + testCase "Array.filter with chars works" <| fun () -> + let xs = [|'a'; '2'; 'b'; 'c'|] + let ys = xs |> Array.filter Char.IsLetter + ys.Length |> equal 3 + testCase "Array.find works" <| fun () -> let xs = [|1us; 2us; 3us; 4us|] xs |> Array.find ((=) 2us) @@ -464,6 +476,13 @@ let tests = let zs = Array.map2 (*) xs ys zs.[0] |> equal 2. + testCase "Array.map3 works" <| fun () -> + let value1 = [|1.|] + let value2 = [|2.|] + let value3 = [|3.|] + let zs = Array.map3 (fun a b c -> a * b * c) value1 value2 value3 + zs.[0] |> equal 6. + testCase "Array.mapi works" <| fun () -> let xs = [|1.; 2.|] let ys = xs |> Array.mapi (fun i x -> float i + x) @@ -896,4 +915,96 @@ let tests = Array.windowed 5 nums |> equal [|[| 1.0; 1.5; 2.0; 1.5; 1.0 |]; [| 1.5; 2.0; 1.5; 1.0; 1.5 |]|] Array.windowed 6 nums |> equal [|[| 1.0; 1.5; 2.0; 1.5; 1.0; 1.5 |]|] Array.windowed 7 nums |> Array.isEmpty |> equal true + + testCase "Array.allPairs works" <| fun () -> + let xs = [|1;2;3;4|] + let ys = [|'a';'b';'c';'d';'e';'f'|] + Array.allPairs xs ys + |> equal + [|(1, 'a'); (1, 'b'); (1, 'c'); (1, 'd'); (1, 'e'); (1, 'f'); (2, 'a'); + (2, 'b'); (2, 'c'); (2, 'd'); (2, 'e'); (2, 'f'); (3, 'a'); (3, 'b'); + (3, 'c'); (3, 'd'); (3, 'e'); (3, 'f'); (4, 'a'); (4, 'b'); (4, 'c'); + (4, 'd'); (4, 'e'); (4, 'f')|] + + testCase "Casting to System.Array works" <| fun () -> + let xs = [|1;2;3;4|] :> System.Array // Numeric array + let ys = [|'a';'b';'c';'d';'e';'f'|] :> System.Array + [ for i in xs do for j in ys do yield (unbox i, unbox j) ] + |> equal + [ (1, 'a'); (1, 'b'); (1, 'c'); (1, 'd'); (1, 'e'); (1, 'f'); (2, 'a'); + (2, 'b'); (2, 'c'); (2, 'd'); (2, 'e'); (2, 'f'); (3, 'a'); (3, 'b'); + (3, 'c'); (3, 'd'); (3, 'e'); (3, 'f'); (4, 'a'); (4, 'b'); (4, 'c'); + (4, 'd'); (4, 'e'); (4, 'f') ] + + testCase "Testing against System.Array works" <| fun () -> + let xs = box [|1;2;3;4|] + let ys = box [|'a';'b';'c';'d';'e';'f'|] + let zs = box [1;2;3;4] + xs :? System.Array |> equal true + ys :? System.Array |> equal true + zs :? System.Array |> equal false + + testCase "Array.Copy works with numeric arrays" <| fun () -> + let source = [| 99 |] + let destination = [| 1; 2; 3 |] + Array.Copy(source, 0, destination, 0, 1) + equal [| 99; 2; 3 |] destination + + testCase "Array.Copy works with non-numeric arrays" <| fun () -> + let source = [| "xy"; "xx"; "xyz" |] + let destination = [| "a"; "b"; "c" |] + Array.Copy(source, 1, destination, 1, 2) + equal [| "a"; "xx"; "xyz" |] destination + + testCase "Array.splitInto works" <| fun () -> + Array.splitInto 3 [|1..10|] |> equal [| [|1..4|]; [|5..7|]; [|8..10|] |] + Array.splitInto 3 [|1..11|] |> equal [| [|1..4|]; [|5..8|]; [|9..11|] |] + Array.splitInto 3 [|1..12|] |> equal [| [|1..4|]; [|5..8|]; [|9..12|] |] + Array.splitInto 4 [|1..5|] |> equal [| [|1..2|]; [|3|]; [|4|]; [|5|] |] + Array.splitInto 20 [|1..4|] |> equal [| [|1|]; [|2|]; [|3|]; [|4|] |] + + testCase "Array.exactlyOne works" <| fun () -> + [|1.|] |> Array.exactlyOne |> equal 1. + (try Array.exactlyOne [|1.;2.|] |> ignore; false with | _ -> true) |> equal true + (try Array.exactlyOne [||] |> ignore; false with | _ -> true) |> equal true + + testCase "Array.tryExactlyOne works" <| fun () -> + [|1.|] |> Array.tryExactlyOne |> equal (Some 1.) + [|1.;2.|] |> Array.tryExactlyOne |> equal None + [||] |> Array.tryExactlyOne |> equal None + + testCase "Array.pairwise works" <| fun () -> + Array.pairwise [||] |> equal [||] + Array.pairwise [|1|] |> equal [||] + Array.pairwise [|1; 2|] |> equal [|(1, 2)|] + let xs = [|1; 2; 3; 4|] + let xs2 = xs |> Array.pairwise + equal [|(1, 2); (2, 3); (3, 4)|] xs2 + xs2 |> Array.map (fun (x, y) -> sprintf "%i%i" x y) + |> String.concat "" + |> equal "122334" + + testCase "Array.transpose works" <| fun () -> + // integer array + Array.transpose (seq [[|1..3|]; [|4..6|]]) + |> equal [|[|1;4|]; [|2;5|]; [|3;6|]|] + Array.transpose [|[|1..3|]|] + |> equal [|[|1|]; [|2|]; [|3|]|] + Array.transpose [|[|1|]; [|2|]|] + |> equal [|[|1..2|]|] + // string array + Array.transpose (seq [[|"a";"b";"c"|]; [|"d";"e";"f"|]]) + |> equal [|[|"a";"d"|]; [|"b";"e"|]; [|"c";"f"|]|] + // empty array + Array.transpose [| |] + |> equal [| |] + // array of empty arrays - m x 0 array transposes to 0 x m (i.e. empty) + Array.transpose [| [||] |] + |> equal [| |] + Array.transpose [| [||]; [||] |] + |> equal [| |] + // jagged arrays + throwsAnyError (fun () -> Array.transpose [| [|1; 2|]; [|3|] |]) + throwsAnyError (fun () -> Array.transpose [| [|1|]; [|2; 3|] |]) + ] diff --git a/tests/Main/ComparisonTests.fs b/tests/Main/ComparisonTests.fs index ad7bfca303..d391cdedb8 100644 --- a/tests/Main/ComparisonTests.fs +++ b/tests/Main/ComparisonTests.fs @@ -5,6 +5,7 @@ open Util.Testing open Fable.Tests.Util open Fable.Core.JsInterop open System.Collections.Generic +open FSharp.Data.UnitSystems.SI.UnitSymbols type UTest = A of int | B of int type RTest = { a: int; b: int } @@ -372,6 +373,21 @@ let tests = false |> equal false + testCase "using function disposes the resource when action finishes" <| fun () -> + let mutable disposed = false + let resource = { new IDisposable with member __.Dispose() = disposed <- true } + using resource (fun _resource -> ()) + equal true disposed + + testCase "using function disposes the resource when action fails" <| fun () -> + let mutable disposed = false + let resource = { new IDisposable with member __.Dispose() = disposed <- true } + try + using resource (fun _resource -> failwith "action failed") + with + | _ -> () // ignore + equal true disposed + testCase "isNull with primitives works" <| fun () -> isNull null |> equal true isNull "" |> equal false @@ -535,4 +551,32 @@ let tests = LanguagePrimitives.PhysicalEquality "2" "3" |> equal false LanguagePrimitives.PhysicalEquality [1] [1] |> equal false LanguagePrimitives.PhysicalEquality [2] [3] |> equal false + + testCase "LanguagePrimitives.SByteWithMeasure works" <| fun () -> + let distance: sbyte = LanguagePrimitives.SByteWithMeasure 1y + distance |> equal 1y + + testCase "LanguagePrimitives.Int16WithMeasure works" <| fun () -> + let distance: int16 = LanguagePrimitives.Int16WithMeasure 1s + distance |> equal 1s + + testCase "LanguagePrimitives.Int32WithMeasure works" <| fun () -> + let distance: int = LanguagePrimitives.Int32WithMeasure 1 + distance |> equal 1 + + testCase "LanguagePrimitives.Int64WithMeasure works" <| fun () -> + let distance: int64 = LanguagePrimitives.Int64WithMeasure 1L + distance |> equal 1L + + testCase "LanguagePrimitives.Float32WithMeasure works" <| fun () -> + let distance: float32 = LanguagePrimitives.Float32WithMeasure 1.0f + distance |> equal 1.0f + + testCase "LanguagePrimitives.FloatWithMeasure works" <| fun () -> + let distance: float = LanguagePrimitives.FloatWithMeasure 1.0 + distance |> equal 1.0 + + testCase "LanguagePrimitives.DecimalWithMeasure works" <| fun () -> + let distance: decimal = LanguagePrimitives.DecimalWithMeasure 1.0m + distance |> equal 1.0m ] \ No newline at end of file diff --git a/tests/Main/ConvertTests.fs b/tests/Main/ConvertTests.fs index 698237154c..1714fb393a 100644 --- a/tests/Main/ConvertTests.fs +++ b/tests/Main/ConvertTests.fs @@ -353,6 +353,13 @@ let tests = xnu |> int32 |> equal -1 xnu |> uint32 |> equal 0xFFFFFFFFu + testCase "Special cases conversion to UInt64 work" <| fun () -> // See #1880 + uint64 "0x9fffffffffffffff" |> equal 11529215046068469759UL + uint64 "0xafffffffffffffff" |> equal 12682136550675316735UL + uint64 "0xAFFFFFFFFFFFFFFF" |> equal 12682136550675316735UL + uint64 "0x9fffffff_ffffffff" |> equal 11529215046068469759UL + uint64 "0x9fff_ffff_ffff_ffff" |> equal 11529215046068469759UL + testCase "System.Convert.ToInt64 works" <| fun () -> let x = 1L int64(1y) |> equal x @@ -1145,61 +1152,4 @@ let tests = System.Text.Encoding.UTF8.GetString(bytes, 6, 6) |> equal "\u03B2\uD8FF\uDCFF" - - // testCase "int64 can be JSON serialized forth and back" <| fun () -> - // let val1 = 5348937298839933899L - // #if FABLE_COMPILER - // let json = Fable.Core.JsInterop.toJson val1 - // let val2 = Fable.Core.JsInterop.ofJson json - // equal true (box val2 :? int64) // Type is kept - // equal val1 val2 - // equal val2 5348937298839933899L - // let val2 = Fable.Core.JsInterop.ofJsonAsType json (val1.GetType()) - // equal true (val2 :? int64) // Type is kept - // let val2 = val2 :?> int64 - // #else - // let json = Newtonsoft.Json.JsonConvert.SerializeObject val1 - // let val2 = Newtonsoft.Json.JsonConvert.DeserializeObject json - // #endif - // // printfn "JSON: %s" json - // equal val1 val2 - // equal val2 5348937298839933899L - - // testCase "uint64 can be JSON serialized forth and back" <| fun () -> - // let val1 = 9348937298839933899UL - // #if FABLE_COMPILER - // let json = Fable.Core.JsInterop.toJson val1 - // let val2 = Fable.Core.JsInterop.ofJson json - // equal true (box val2 :? uint64) // Type is kept - // equal val1 val2 - // equal val2 9348937298839933899UL - // let val2 = Fable.Core.JsInterop.ofJsonAsType json (val1.GetType()) - // equal true (val2 :? uint64) // Type is kept - // let val2 = val2 :?> uint64 - // #else - // let json = Newtonsoft.Json.JsonConvert.SerializeObject val1 - // let val2 = Newtonsoft.Json.JsonConvert.DeserializeObject json - // #endif - // // printfn "JSON: %s" json - // equal val1 val2 - // equal val2 9348937298839933899UL - - // testCase "BigInts can be JSON serialized forth and back" <| fun () -> - // let val1 = 59823749821707124891298739821798327321028091380980I - // #if FABLE_COMPILER - // let json = Fable.Core.JsInterop.toJson val1 - // let val2 = Fable.Core.JsInterop.ofJson json - // equal true (box val2 :? bigint) // Type is kept - // equal val1 val2 - // equal val2 59823749821707124891298739821798327321028091380980I - // let val2 = Fable.Core.JsInterop.ofJsonAsType json (val1.GetType()) - // equal true (val2 :? bigint) // Type is kept - // let val2 = val2 :?> bigint - // #else - // let json = Newtonsoft.Json.JsonConvert.SerializeObject val1 - // let val2 = Newtonsoft.Json.JsonConvert.DeserializeObject json - // #endif - // // printfn "JSON: %s" json - // equal val1 val2 - // equal val2 59823749821707124891298739821798327321028091380980I ] diff --git a/tests/Main/DateTimeOffsetTests.fs b/tests/Main/DateTimeOffsetTests.fs index f6c661bdc5..ad7f928413 100644 --- a/tests/Main/DateTimeOffsetTests.fs +++ b/tests/Main/DateTimeOffsetTests.fs @@ -36,18 +36,6 @@ let tests = System.Text.RegularExpressions.Regex.Replace(str, "0{3,}", "000") |> equal "2014-09-11T16:37:02.000+00:00" - // testCase "DateTimeOffset can be JSON serialized forth and back" <| fun () -> - // let dof = DateTimeOffset(2016, 8, 4, 17, 30, 0, TimeSpan.FromHours(3.)) - // #if FABLE_COMPILER - // let json = Fable.Core.JsInterop.toJson dof - // let dof = Fable.Core.JsInterop.ofJson json - // #else - // let json = Newtonsoft.Json.JsonConvert.SerializeObject dof - // let dof = Newtonsoft.Json.JsonConvert.DeserializeObject json - // #endif - // dof.Offset |> equal (TimeSpan.FromHours(3.)) - // dof.ToString("HH:mm") |> equal "17:30" - testCase "DateTimeOffset from Year 1 to 99 works" <| fun () -> let date = DateTimeOffset(1, 1, 1, 0, 0, 0, TimeSpan.Zero) date.Year |> equal 1 @@ -130,7 +118,7 @@ let tests = equal compound utcDate testCase "DateTimeOffset <-> Ticks isomorphism" <| fun () -> - let checkIsomorphism (d: DateTimeOffset) = + let checkIsomorphism (d: DateTimeOffset) = try let ticks = d.Ticks let utcTicks = d.UtcTicks @@ -142,7 +130,7 @@ let tests = equal d fromUtcTicks equal ticks fromTicks.Ticks equal utcTicks fromTicks.UtcTicks - if offset <> TimeSpan.Zero + if offset <> TimeSpan.Zero then notEqual ticks utcTicks else equal ticks utcTicks with e -> diff --git a/tests/Main/DateTimeTests.fs b/tests/Main/DateTimeTests.fs index e12c4f11fd..53a33d1a85 100644 --- a/tests/Main/DateTimeTests.fs +++ b/tests/Main/DateTimeTests.fs @@ -44,18 +44,6 @@ let tests = // DateTime(2014, 9, 11, 16, 37, 2, DateTimeKind.Local).ToString("O") // |> equal "2014-09-11T16:37:02.000+02:00" // Here the time zone is Europte/Paris (GMT+2) - // testCase "DateTime can be JSON serialized forth and back" <| fun () -> - // let utc = DateTime(2016, 8, 4, 17, 30, 0, DateTimeKind.Utc) - // #if FABLE_COMPILER - // let json = Fable.Core.JsInterop.toJson utc - // let utc = Fable.Core.JsInterop.ofJson json - // #else - // let json = Newtonsoft.Json.JsonConvert.SerializeObject utc - // let utc = Newtonsoft.Json.JsonConvert.DeserializeObject json - // #endif - // utc.Kind = DateTimeKind.Utc |> equal true - // utc.ToString("HH:mm") |> equal "17:30" - testCase "DateTime from Year 1 to 99 works" <| fun () -> let date = DateTime(1, 1, 1) date.Year |> equal 1 @@ -272,6 +260,14 @@ let tests = d.ToUniversalTime().Kind <> d.Kind |> equal true + testCase "DateTime.SpecifyKind works" <| fun () -> // See #1844 + let d = DateTime(2014, 10, 9, 13, 23, 30, DateTimeKind.Local) + let d2 = DateTime.SpecifyKind(d, DateTimeKind.Utc) + d2.Kind |> equal DateTimeKind.Utc + d.Ticks = d2.Ticks |> equal true + // let d3 = d.ToUniversalTime() + // d.Ticks = d3.Ticks |> equal false + testCase "DateTime.Date works" <| fun () -> let d = DateTime(2014, 10, 9, 13, 23, 30) d.Date.Hour |> equal 0 @@ -535,4 +531,40 @@ let tests = equal 10 !res t.Stop() } + + testCaseAsync "Assigning an event to a variable works" <| fun () -> // See #1863 + let createTimerAndObservable timerInterval = + // setup a timer + let timer = new System.Timers.Timer(float timerInterval) + timer.AutoReset <- true + // events are automatically IObservable + let observable = timer.Elapsed + // return an async task + let task = async { + timer.Start() + do! Async.Sleep 200 + timer.Stop() + } + // return a async task and the observable + (task,observable) + // create the timer and the corresponding observable + let basicTimer2 , timerEventStream = createTimerAndObservable 50 + + let mutable acc = 1 + // register that everytime something happens on the + // event stream, print the time. + timerEventStream |> Observable.subscribe (fun _ -> + acc <- acc + 1) |>ignore + + async { + do! basicTimer2 + // printfn "%i" acc + acc > 2 |> equal true + } + + // In regions with daylight saving time, 20/10/2019 will have different timezone + // offset than 29/10/2019 + testCase "Adding days to a local date works even if daylight saving time changes" <| fun () -> + let dt = DateTime(2019, 10, 20, 0, 0, 0, DateTimeKind.Local) + dt.AddDays(9.).Day |> equal 29 ] diff --git a/tests/Main/DictionaryTests.fs b/tests/Main/DictionaryTests.fs index 68275d6ece..57332b99ca 100644 --- a/tests/Main/DictionaryTests.fs +++ b/tests/Main/DictionaryTests.fs @@ -230,37 +230,16 @@ let tests = let dic = Dictionary<_,_>() dic.Add("A", 65) // throwsError "The given key 'B' was not present in the dictionary." (fun _ -> dic.["B"] |> ignore) - throwsAnyError (fun _ -> dic.["B"] |> ignore) - - // testCase "Dictionaries can be JSON serialized forth and back" <| fun () -> - // let x = Dictionary<_,_>() - // x.Add("a", { i=1; s="1" }) - // x.Add("b", { i=2; s="2" }) - // #if FABLE_COMPILER - // let json = Fable.Core.JsInterop.toJson x - // let x2 = Fable.Core.JsInterop.ofJson> json - // (0, x2) ||> Seq.fold (fun acc kv -> acc + kv.Value.i) - // |> equal 3 - // let json = Fable.Core.JsInterop.toJsonWithTypeInfo x - // let x2 = Fable.Core.JsInterop.ofJsonWithTypeInfo> json - // #else - // let json = Newtonsoft.Json.JsonConvert.SerializeObject x - // let x2 = Newtonsoft.Json.JsonConvert.DeserializeObject> json - // #endif - // (0, x2) ||> Seq.fold (fun acc kv -> acc + kv.Value.i) - // |> equal 3 - - // testCase "Dictionaries serialized with Json.NET can be deserialized" <| fun () -> - // // let x = Dictionary<_,_>() - // // x.Add("a", { i=1; s="1" }) - // // x.Add("b", { i=2; s="2" }) - // // let json = JsonConvert.SerializeObject(x, JsonSerializerSettings(TypeNameHandling=TypeNameHandling.All)) - // let json = """{"$type":"System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[Fable.Tests.Maps+R, Fable.Tests]], FSharp.Core","a":{"$type":"Fable.Tests.Maps+R, Fable.Tests","i":1,"s":"1"},"b":{"$type":"Fable.Tests.Maps+R, Fable.Tests","i":2,"s":"2"}}""" - // #if FABLE_COMPILER - // let x2 = Fable.Core.JsInterop.ofJsonWithTypeInfo> json - // #else - // let x2 = Newtonsoft.Json.JsonConvert.DeserializeObject> json - // #endif - // (0, x2) ||> Seq.fold (fun acc kv -> acc + kv.Value.i) - // |> equal 3 - ] \ No newline at end of file + throwsAnyError (fun () -> dic.["B"]) + + testCase "conversion from array works" <| fun () -> + let dic = [| "A",1; "B",2|] |> dict + dic.Values.Count + |> equal 2 + + testCase "conversion from array works with duplicates" <| fun () -> + let dic = [| "A",1; "A",3; "B",2|] |> dict + dic.Values.Count + |> equal 2 + + ] diff --git a/tests/Main/EnumTests.fs b/tests/Main/EnumTests.fs index 556bc326cc..792e6f9d21 100644 --- a/tests/Main/EnumTests.fs +++ b/tests/Main/EnumTests.fs @@ -1,5 +1,6 @@ module Fable.Tests.Enum +open System open FSharp.Core.LanguagePrimitives open Util.Testing @@ -23,8 +24,8 @@ let myRootValue = module EnumOperations = let inline enumOfValue1<'T,'U when 'U: enum<'T>> (value: 'T) : 'U = LanguagePrimitives.EnumOfValue<'T,'U>(value) let inline enumOfValue2 value = LanguagePrimitives.EnumOfValue value - let enumOfValue3 value = LanguagePrimitives.EnumOfValue value - let enumOfValue4 = LanguagePrimitives.EnumOfValue + // let enumOfValue3 value = LanguagePrimitives.EnumOfValue value + // let enumOfValue4 = LanguagePrimitives.EnumOfValue type BinaryBoolean = | A = 0uy @@ -33,6 +34,11 @@ type BinaryBoolean = | D = 3uy | E = 4uy +type MyEnum = + | Foo = 1y + | Bar = 5y + | Baz = 8y + let tests = testList "Enum" [ testCase "Enum.HasFlag works" <| fun () -> @@ -130,17 +136,17 @@ let tests = EnumOfValue 2 |> equal Fruits.Banana EnumOfValue 4 |> equal Fruits.Coconut - testCase "EnumOfValue works when type is unknown at compile time" <| fun () -> // #1536 + testCase "EnumOfValue works in inlined functions" <| fun () -> // #1536 let e0 : BinaryBoolean = LanguagePrimitives.EnumOfValue 0uy let e1 : BinaryBoolean = EnumOperations.enumOfValue1 1uy let e2 : BinaryBoolean = EnumOperations.enumOfValue2 2uy - let e3 : BinaryBoolean = EnumOperations.enumOfValue3 3uy - let e4 : BinaryBoolean = EnumOperations.enumOfValue4 4uy + // let e3 : BinaryBoolean = EnumOperations.enumOfValue3 3uy + // let e4 : BinaryBoolean = EnumOperations.enumOfValue4 4uy e0 |> equal BinaryBoolean.A e1 |> equal BinaryBoolean.B e2 |> equal BinaryBoolean.C - e3 |> equal BinaryBoolean.D - e4 |> equal BinaryBoolean.E + // e3 |> equal BinaryBoolean.D + // e4 |> equal BinaryBoolean.E match e2 with | BinaryBoolean.C -> () | _ -> failwith "unexpected" @@ -203,4 +209,45 @@ let tests = | _ -> 1 | _ -> 0 test 2 |> equal 1 + + testCase "Enum.GetValues works" <| fun () -> + let check (ar: Array) = + ar + |> Seq.cast + |> Seq.toList + |> equal [1y; 5y; 8y] + let t = typeof + Enum.GetValues(t) |> check + t.GetEnumValues() |> check + + testCase "Enum.GetNames works" <| fun () -> + let t = typeof + Enum.GetNames(t) |> equal [|"Foo"; "Bar"; "Baz"|] + t.GetEnumNames() |> equal [|"Foo"; "Bar"; "Baz"|] + + testCase "Enum.GetName works" <| fun () -> + let t = typeof + Enum.GetName(t, MyEnum.Foo) |> equal "Foo" + Enum.GetName(t, box 5y) |> equal "Bar" + Enum.GetName(t, MyEnum.Baz) |> equal "Baz" + + testCase "Enum.IsDefined works" <| fun () -> + let t = typeof + Enum.IsDefined(t, "Foo") |> equal true + Enum.IsDefined(t, "Baz") |> equal true + Enum.IsDefined(t, "Ozu") |> equal false + Enum.IsDefined(t, 5y) |> equal true + Enum.IsDefined(t, 10y) |> equal false + + testCase "Enum.Parse works" <| fun () -> + let t = typeof + Enum.Parse(t, "Foo") |> equal (box MyEnum.Foo) + Enum.Parse(t, "Bar") |> equal (box MyEnum.Bar) + Enum.Parse(t, "8") |> equal (box MyEnum.Baz) + + testCase "Enum.TryParse works" <| fun () -> + let t = typeof + Enum.TryParse(t, "Foo") |> equal (true, box MyEnum.Foo) + Enum.TryParse(t, "Bar") |> equal (true, box MyEnum.Bar) + Enum.TryParse(t, "Ozu") |> fst |> equal false ] \ No newline at end of file diff --git a/tests/Main/Fable.Tests.fsproj b/tests/Main/Fable.Tests.fsproj index 09b507712b..11957cf18c 100644 --- a/tests/Main/Fable.Tests.fsproj +++ b/tests/Main/Fable.Tests.fsproj @@ -1,12 +1,15 @@ - + - netcoreapp2.0 Exe + netcoreapp2.1 + Major $(OtherFlags) --crossoptimize- + true - + + @@ -15,6 +18,7 @@ + @@ -40,7 +44,6 @@ - @@ -66,4 +69,23 @@ + + + + + + + + + diff --git a/tests/Main/Globs/GlobTest.fs b/tests/Main/Globs/GlobTest.fs new file mode 100644 index 0000000000..4ae7595b91 --- /dev/null +++ b/tests/Main/Globs/GlobTest.fs @@ -0,0 +1,5 @@ +// Check that files can be imported via fsproj globbing patterns +// https://github.com/fable-compiler/Fable/issues/1942 +module Fable.Tests.Glob + +let hello name = sprintf "Hello %s from Glob" name \ No newline at end of file diff --git a/tests/Main/HashSetTests.fs b/tests/Main/HashSetTests.fs index 05d52265ad..eb689be75f 100644 --- a/tests/Main/HashSetTests.fs +++ b/tests/Main/HashSetTests.fs @@ -206,34 +206,4 @@ let tests = apa.Contains ({ i = 5; s = "foo"}) |> equal true apa.Contains ({ i = 5; s = "fo"}) |> equal false - // testCase "HashSet can be JSON serialized forth and back" <| fun () -> - // let x = HashSet<_>() - // x.Add(1) |> ignore - // x.Add(2) |> ignore - // #if FABLE_COMPILER - // let json = Fable.Core.JsInterop.toJson x - // let x2 = Fable.Core.JsInterop.ofJson> json - // x2.IsSubsetOf x |> equal true - // (0, x2) ||> Seq.fold (fun acc v -> acc + v) |> equal 3 - // let json = Fable.Core.JsInterop.toJsonWithTypeInfo x - // let x2 = Fable.Core.JsInterop.ofJsonWithTypeInfo> json - // #else - // let json = Newtonsoft.Json.JsonConvert.SerializeObject x - // let x2 = Newtonsoft.Json.JsonConvert.DeserializeObject> json - // #endif - // x2.IsSubsetOf x |> equal true - // (0, x2) ||> Seq.fold (fun acc v -> acc + v) |> equal 3 - - // testCase "HashSet serialized with Json.NET can be deserialized" <| fun () -> - // // let x = HashSet<_>() - // // x.Add({ i=1; s="1" }) |> ignore - // // x.Add({ i=2; s="2" }) |> ignore - // // let json = JsonConvert.SerializeObject(x, JsonSerializerSettings(TypeNameHandling=TypeNameHandling.All)) - // let json = """{"$type":"System.Collections.Generic.HashSet`1[[Fable.Tests.HashSets+R, Fable.Tests]], FSharp.Core","$values":[{"$type":"Fable.Tests.HashSets+R, Fable.Tests","i":1,"s":"1"},{"$type":"Fable.Tests.HashSets+R, Fable.Tests","i":2,"s":"2"}]}""" - // #if FABLE_COMPILER - // let x2 = Fable.Core.JsInterop.ofJsonWithTypeInfo> json - // #else - // let x2 = Newtonsoft.Json.JsonConvert.DeserializeObject> json - // #endif - // (0, x2) ||> Seq.fold (fun acc v -> acc + v.i) |> equal 3 ] \ No newline at end of file diff --git a/tests/Main/JsInteropTests.fs b/tests/Main/JsInteropTests.fs index 34cfaacb8c..7e8bdbb8b8 100644 --- a/tests/Main/JsInteropTests.fs +++ b/tests/Main/JsInteropTests.fs @@ -6,6 +6,7 @@ open Util.Testing #if FABLE_COMPILER open Fable.Core open Fable.Core.JsInterop +open Fable.Core.DynamicExtensions open Fable.Core.Experimental [] @@ -79,6 +80,19 @@ type MyStrings = | Vertical | [] Horizontal +[] +type UserInfo = + | UserLoginCount + +[] +type UserInfo2 = + | UserLoginCount + +[] +type MyCssOptions = + | ContentBox + | BorderBox + [] #endif type Field = OldPassword | NewPassword | ConfirmPassword @@ -201,12 +215,11 @@ let tests = // opts2?foo2?flag1 |> unbox |> equal true // opts2?bar2?(1) |> unbox |> equal 3 - // TODO - // testCase "Array inside keyValueList is preserved" <| fun () -> - // let props = [ Names [| { Name = "name" } |] ] - // let actual = [ Names [| { Name = "name" } |] ] |> keyValueList CaseRules.LowerFirst |> toJson - // let expected = props |> keyValueList CaseRules.LowerFirst |> toJson - // actual |> equal expected + testCase "Array inside keyValueList is preserved" <| fun () -> + let props = [ Names [| { Name = "name" } |] ] + let actual = [ Names [| { Name = "name" } |] ] |> keyValueList CaseRules.LowerFirst |> JS.JSON.stringify + let expected = props |> keyValueList CaseRules.LowerFirst |> JS.JSON.stringify + actual |> equal expected testCase "Erased union cases work with keyValueList" <| fun () -> let props: Props list = [ Custom("Foo", 5); Names [|{Name = "Mikhail"}|] ] @@ -259,6 +272,13 @@ let tests = style.Bar |> equal "foo" style.Add(3,5) |> equal 8 + testCase "Assigning null with emit works" <| fun () -> + let x = createEmpty + x.["prop"] <- "prop value" + x.["prop"] |> isNull |> equal false + x.["prop"] <- null + x.["prop"] |> equal null + testCase "Emit attribute conditional parameters works" <| fun () -> let style = createEmpty style.FontFamily <- Some "ha" @@ -280,9 +300,8 @@ let tests = nameof(record.Int) |> equal "Int" nameof(record.InnerRecord) + "." + nameof(record.InnerRecord.Float) |> equal "InnerRecord.Float" - // TODO!!! - // nameof(typeof) |> equal "Record" - // nameof(typeof) |> equal "InnerRecord" + nameof(typeof) |> equal "Record" + nameof(typeof) |> equal "InnerRecord" testCase "nameofLambda works" <| fun () -> nameofLambda(fun (x:Record) -> x.String) |> equal "String" @@ -291,6 +310,18 @@ let tests = testCase "StringEnum attribute works" <| fun () -> Vertical |> unbox |> equal "vertical" Horizontal |> unbox |> equal "Horizontal" + Vertical |> string |> equal "vertical" + Horizontal |> string |> equal "Horizontal" + + testCase "StringEnum works with CaseRules.SnakeCase" <| fun () -> + UserInfo.UserLoginCount |> unbox |> equal "user_login_count" + + testCase "StringEnum works with CaseRules.SnakeCaseAllCaps" <| fun () -> + UserInfo2.UserLoginCount |> unbox |> equal "USER_LOGIN_COUNT" + + testCase "StringEnum works with CaseRules.KebabCase" <| fun () -> + BorderBox |> unbox |> equal "border-box" + ContentBox |> unbox |> equal "content-box" // See https://github.com/fable-compiler/fable-import/issues/72 testCase "Can use values and functions from global modules" <| fun () -> @@ -300,6 +331,11 @@ let tests = testCase "Local import with curried signatures works" <| fun () -> let add (x:int) (y:int): int = importMember "./js/1foo.js" 3 |> add 2 |> equal 5 + + testCase "TypedArray element can be set and get using index" <| fun () -> + let arr = JS.Constructors.Uint8Array.Create(5) + arr.[0] <- 5uy + equal 5uy arr.[0] #endif testCase "Pattern matching with StringEnum works" <| fun () -> diff --git a/tests/Main/JsonTests.fs b/tests/Main/JsonTests.fs deleted file mode 100644 index 4ca7b40e03..0000000000 --- a/tests/Main/JsonTests.fs +++ /dev/null @@ -1,501 +0,0 @@ -[] -module Fable.Tests.Json -open Util.Testing -open Fable.Tests.Util - -#if FABLE_COMPILER -let toJson(x) = Fable.Core.JsInterop.toJson(x) -let [] ofJson<'T>(x) = Fable.Core.JsInterop.ofJson<'T>(x) -#else -open Newtonsoft.Json -let toJson x = JsonConvert.SerializeObject(x, Fable.JsonConverter()) -let ofJson<'T> x = JsonConvert.DeserializeObject<'T>(x, Fable.JsonConverter()) -#endif - -type Child = - { a: string - b: int } - -type Simple = { - Name : string - Child : Child -} - -type U = - | CaseA of int - | CaseB of Simple list - | CaseC of Child * int - -type R() = - member __.Foo() = "foo" - -type A<'U> = {a: 'U} -type B<'J> = {b: A<'J>} -type C<'T> = {c: B<'T>} - -[] -let ``Nested generics``() = - let x = { c={ b={ a=R() } } } - let json = toJson x - let x2 = ofJson> json - x2.c.b.a.Foo() |> equal "foo" - -type D<'Q> = {d: A<'Q> option } - -[] -let ``Nested options``() = - let x = { d = Some { a=R() } } - let json = toJson x - let x2 = ofJson> json - x2.d.Value.a.Foo() |> equal "foo" - -type E<'Q> = { e: A<'Q>[] } - -[] -let ``Nested arrays``() = - let x = { e = [|{ a=R() }|] } - let json = toJson x - let x2 = ofJson> json - x2.e.[0].a.Foo() |> equal "foo" - -type R2() = - member __.Foo() = "bar" - -type F<'Q,'V> = { f: A<'Q>*B<'V> } - -[] -let ``Nested tuples``() = - let x = { f = { a=R() }, { b={a=R2()} } } - let json = toJson x - let x2 = ofJson> json - let (i, j) = x2.f - i.a.Foo() |> equal "foo" - j.b.a.Foo() |> equal "bar" - -[] -let ``Records``() = - let json = - """ - { - "Name": "foo", - "Child": { - "a": "Hi", - "b": 10 - } - } - """ - let result: Simple = ofJson json - result.Name |> equal "foo" - // Use the built in compare to ensure the fields are being hooked up. - // Should compile to something like: result.Child.Equals(new Child("Hi", 10)) - result.Child = {a="Hi"; b=10} |> equal true - -#if FABLE_COMPILER -[] -let ``Validation works``() = - let mutable err = false - let json = - """ - { - "Name": "foo", - "Child": { - "a": 5, - "b": 10 - } - } - """ - try - ofJson json |> ignore - with _ -> err <- true - equal true err -#endif - -[] -let ``Date``() = - let d = System.DateTime(2016, 1, 30, 11, 25, 0, System.DateTimeKind.Utc) - let json = d |> toJson - let result : System.DateTime = ofJson json - result.Year |> equal 2016 - result.Month |> equal 1 - result.Day |> equal 30 - result.Hour |> equal 11 - result.Minute |> equal 25 - -[] -let ``Date Kind Unspecified roundtrip``() = - let d = System.DateTime(2016, 1, 30, 11, 25, 0, System.DateTimeKind.Unspecified) - let json = d |> toJson - let result : System.DateTime = ofJson json - result.Year |> equal 2016 - result.Month |> equal 1 - result.Day |> equal 30 - result.Hour |> equal 11 - result.Minute |> equal 25 - -type JsonDate = { - Date : System.DateTime -} - -[] -let ``Child Date``() = - let d = System.DateTime(2016, 1, 1, 0, 0, 0, System.DateTimeKind.Utc) - let json = { Date = d } |> toJson - let result : JsonDate = ofJson json - result.Date.Year |> equal 2016 - -type JsonArray = { - Name : string -} - -[] -let ``Arrays``() = - let json = """[{ "Name": "a" }, { "Name": "b" }]""" - let result : JsonArray[] = ofJson json - result |> Array.length |> equal 2 - result.[1] = { Name="b" } |> equal true - -[] -let ``Arrays 2``() = - let x = [|R2()|] - let json = toJson x - let x2 = ofJson json - x2.[0].Foo() |> equal "bar" - -[] -let ``Typed Arrays``() = - let xs1 = [|1;2;3|] - let json = toJson xs1 - let xs2 = ofJson json - Array.sum xs2 |> equal (Array.sum xs1) - -type ChildArray = { - Children : JsonArray[] -} - -[] -let ``Child Array``() = - let json = """{ "Children": [{ "Name": "a" }, { "Name": "b" }] }""" - let result : ChildArray = ofJson json - result.Children |> Array.length |> equal 2 - result.Children.[1] = { Name="b" } |> equal true - -[] -let ``String Generic List``() = - let json = """["a","b"]""" - let result : System.Collections.Generic.List = ofJson json - result.Count |> equal 2 - result.[1] |> equal "b" - -[] -let ``Child Generic List``() = - let json = """[{ "Name": "a" }, { "Name": "b" }]""" - let result : System.Collections.Generic.List = ofJson json - result.Count |> equal 2 - result.[1] = { Name="b" } |> equal true - -[] -let ``Lists``() = - let json = """["a","b"]""" - let result : string list = ofJson json - result |> List.length |> equal 2 - result.Tail |> List.length |> equal 1 - result.[1] |> equal "b" - result.Head |> equal "a" - - -type ChildList = { - Children : JsonArray list -} - -[] -let ``Child List``() = - let json = """{ "Children": [{ "Name": "a" }, { "Name": "b" }] }""" - let result : ChildList = ofJson json - result.Children |> List.length |> equal 2 - result.Children.[1] = { Name="b" } |> equal true - -type Wrapper<'T> = { thing : 'T } - -let inline parseAndUnwrap json: 'T = (ofJson> json).thing - -[] -let ``generic`` () = - let result1 : string = parseAndUnwrap """ { "thing" : "a" } """ - result1 |> equal "a" - let result2 : int = parseAndUnwrap """ { "thing" : 1 } """ - result2 |> equal 1 - let result3 : Child = parseAndUnwrap """ { "thing" : { "a": "a", "b": 1 } } """ - result3.a |> equal "a" - result3 = {a = "a"; b = 1} |> equal true - // let result4 : Child = parseAndUnwrap """ {"$type":"Fable.Tests.Json+Wrapper`1[[Fable.Tests.Json+Child, Fable.Tests]], Fable.Tests","thing":{"$type":"Fable.Tests.Json+Child, Fable.Tests","a":"a","b":1}} """ - // if result4 <> {a = "a"; b = 1} then - // invalidOp "things not equal" - -type OptionJson = - { a: int option } - -[] -let ``Option Some`` () = - let json1 = """ {"a":1 } """ - let result1 : OptionJson = ofJson json1 - let json2 = """ {"a":null } """ - let result2 : OptionJson = ofJson json2 - match result1.a, result2.a with - | Some v, None -> v - | _ -> -1 - |> equal 1 - -[] -let ``Option Wrapped Some`` () = - let createSome (a: 'T) = Some a - let a = createSome 1 - let json1 = toJson <| { a=a } - equal (json1.Replace(" ", "")) """{"a":1}""" - let result1 : OptionJson = ofJson json1 - match result1.a with - | Some v -> v - | _ -> -1 - |> equal 1 - -type ComplexOptionJson = - { a: Child option } - -[] -let ``Complex Option Some`` () = - let json = """ {"a":{"a":"John","b":14}} """ - let result : ComplexOptionJson = ofJson json - match result.a with - | Some v -> v = {a="John";b=14} - | None -> false - |> equal true - -type TupleJson = - { a: int * int } - -[] -let ``Tuple`` () = - let json = """ {"a":[1,2]} """ - let result : TupleJson = ofJson json - result.a = (1, 2) |> equal true - - -type OptionalTuple = - { tuple: (string * string) option } - -[] -let ``Optional Tuple in records`` () = - - let json1 = """ { "tuple": ["a", "b"] } """ - let result1 : OptionalTuple = ofJson json1 - let json2 = """ { "tuple": null } """ - let result2 : OptionalTuple = ofJson json2 - match result1.tuple, result2.tuple with - | Some v, None -> v - | _ -> ("", "") - |> equal ("a", "b") - - -type TupleComplexJson = - { a: int * Child } - -[] -let ``Complex Tuple`` () = - let json = """ {"a":[1,{"a":"A","b":1}]} """ - let result : TupleComplexJson = ofJson json - snd result.a = { a = "A"; b = 1 } |> equal true - -type SetJson = - { a: Set } - -[] -let ``Sets`` () = - let json = """ {"a":["a","b"]} """ - let result : SetJson = ofJson json - result.a |> Set.contains "b" |> equal true - -type MapJson = - { a: Map } - -[] -let ``Maps`` () = - let json = """ {"a":{"a":{"a":"aa","b":1},"b":{"a":"bb","b":2}}} """ - let result : MapJson = ofJson json - result.a.Count |> equal 2 - result.a.["b"] = { a="bb"; b=2 } |> equal true - -[] -let ``Map string keys are not quoted``() = // #659 - let v = [ "foo", 1 ] |> Map.ofList - let serialised = toJson v - (toJson v).Replace(" ", "") |> equal """{"foo":1}""" - -type DictionaryJson = - { a: System.Collections.Generic.Dictionary } - -[] -let ``Dictionaries`` () = - let json = """ {"a":{"a":{"a":"aa","b":1},"b":{"a":"bb","b":2}}} """ - let result : DictionaryJson = ofJson json - result.a.Count |> equal 2 - result.a.["b"] = { a="bb"; b=2 } |> equal true - -// Dunno why, but this tests is not working with Json.NET -#if FABLE_COMPILER -type PropertyJson() = - member val Prop1 = {a="";b=0} with get,set - -[] -let ``Properties`` () = - let json = """ {"Prop1": { "a":"aa", "b": 1 }} """ - let result : PropertyJson = ofJson json - result.Prop1.a |> equal "aa" - result.Prop1.b |> equal 1 -#endif - -[] -let ``Union of list``() = - let u = CaseB [{Name="Sarah";Child={a="John";b=14}}] - let u2: U = toJson u |> ofJson - u = u2 |> equal true - let u3: U = ofJson """{"CaseB":[{"Name":"Sarah","Child":{"a":"John","b":14}}]}""" - u = u3 |> equal true - - -[] -let ``Union with multiple fields``() = - let u = CaseC({a="John";b=14}, 2) - let u2: U = toJson u |> ofJson - u = u2 |> equal true - let u3: U = ofJson """{"CaseC":[{"a":"John","b":14},2]}""" - u = u3 |> equal true - -type UnionJson = - | Type1 of string - | Type2 of Child - -type UnionHolder = - { a : UnionJson } - -[] -let ``Union of record`` () = - let json = """ {"a":{"Type2": {"a":"a","b":1} }} """ - let result : UnionHolder = ofJson json - match result.a with - | Type2 t -> t = { a="a"; b=1 } - | Type1 _ -> false - |> equal true - -type MultiUnion = - | EmptyCase - | SingleCase of int - | MultiCase of string * Child - -[] -let ``Union case with no fields``() = - let u: MultiUnion = ofJson """ "EmptyCase" """ - u = EmptyCase |> equal true - -[] -let ``Union case with single field``() = - let u: MultiUnion = ofJson """ {"SingleCase": 100} """ - u = (SingleCase 100) |> equal true - -[] -let ``Union case with multiple fields``() = - let u: MultiUnion = ofJson """ {"MultiCase": ["foo",{"a":"John","b":14}]} """ - let u2 = MultiCase("foo", {a="John"; b=14}) - u = u2 |> equal true - - -type OptionalUnionHolder = - { a : UnionJson option } - -[] -let ``Optional union of record: with a value`` () = - let json = """ {"a":{"Type2": {"a":"a","b":1} }} """ - let result : OptionalUnionHolder = ofJson json - match result.a with - | Some (Type2 t) -> t = { a= "a"; b=1 } - | _ -> false - |> equal true - -[] -let ``Optional union of record: for undefined`` () = - let json = """ {} """ - let result : OptionalUnionHolder = ofJson json - match result.a with - | None -> true - | _ -> false - |> equal true - -[] -let ``Optional union of record: for null`` () = - let json = """ {"a":null} """ - let result : OptionalUnionHolder = ofJson json - match result.a with - | None -> true - | _ -> false - |> equal true - -#if FABLE_COMPILER -type UnionWithCaseOfObj = - | CaseOfObj of obj - | AnotherCase - -[] -let jsUndefined = obj() - -[] -let ``Union with case of obj with single undefined field value`` () = - let x = UnionWithCaseOfObj.CaseOfObj jsUndefined - let json = toJson x - let x2 = ofJson json - x2 |> equal x -#endif - -#if FABLE_COMPILER -type IData = interface end - -type Text = - { kind:string; text:string } - interface IData - -type Numbered = - { kind:string; number:int } - interface IData - -type Things = { name:string; data:IData } - -[] -let ``Generics with interface`` () = - // let x = [ { name = "one"; data = { kind = "number"; number = 4 } }; - // { name = "two"; data = { kind = "number"; number = 3 } }; - // { name = "three"; data = { kind = "text"; text = "yo!" } } ] - // let json = Newtonsoft.Json.JsonConvert.SerializeObject(x, Newtonsoft.Json.JsonSerializerSettings(TypeNameHandling=Newtonsoft.Json.TypeNameHandling.All)) - let json = """ {"$type":"Microsoft.FSharp.Collections.FSharpList`1[[Fable.Tests.Json+Things, Fable.Tests]], FSharp.Core","$values":[{"$type":"Fable.Tests.Json+Things, Fable.Tests","name":"one","data":{"$type":"Fable.Tests.Json+Numbered, Fable.Tests","kind":"number","number":4}},{"$type":"Fable.Tests.Json+Things, Fable.Tests","name":"two","data":{"$type":"Fable.Tests.Json+Numbered, Fable.Tests","kind":"number","number":3}},{"$type":"Fable.Tests.Json+Things, Fable.Tests","name":"three","data":{"$type":"Fable.Tests.Json+Text, Fable.Tests","kind":"text","text":"yo!"}}]} """ - let result : Things list = Fable.Core.JsInterop.ofJsonWithTypeInfo json - result.[1].data = ({ kind = "number"; number = 3 } :> IData) |> equal true - -type RrdWithLong = { long: int64 } - -[] -let ``Roundtripped int64 is convertible to float``() = - let r = {long = 0L} |> toJson |> ofJson - r.long |> float - |> equal 0. - -type WrappedInteger = { Data : int } - -[] -let ``Can roundtrip Result of non-primitive type`` () = - let x = { Data = 0 } - let wx : Result<_, unit> = Ok x - let wx' = wx |> toJson |> ofJson - match wx' with - | Ok x' -> - if x' = x then - () - else - failwithf "Unexpected data %A" x' - | res -> failwithf "Unexpected result %A" res -#endif diff --git a/tests/Main/ListTests.fs b/tests/Main/ListTests.fs index e7db5d3029..30d0534d95 100644 --- a/tests/Main/ListTests.fs +++ b/tests/Main/ListTests.fs @@ -1,6 +1,7 @@ module Fable.Tests.Lists open Util.Testing +open Fable.Tests.Util type List(x: int) = member val Value = x @@ -127,6 +128,11 @@ let tests = let xs3 = [] (try List.exactlyOne xs3 |> ignore; false with | _ -> true) |> equal true + testCase "List.tryExactlyOne works" <| fun () -> + [1.] |> List.tryExactlyOne |> equal (Some 1.) + [1.;2.] |> List.tryExactlyOne |> equal None + [] |> List.tryExactlyOne |> equal None + testCase "List.exists works" <| fun () -> let xs = [1; 2; 3; 4] xs |> List.exists (fun x -> x = 2) @@ -672,6 +678,12 @@ let tests = equal 4 ys.[2] equal 6 ys.[4] + testCase "List.chunkBySize works" <| fun () -> + List.chunkBySize 4 [1..8] + |> equal [ [1..4]; [5..8] ] + List.chunkBySize 4 [1..10] + |> equal [ [1..4]; [5..8]; [9..10] ] + testCase "List.range works" <| fun () -> [1..5] |> List.reduce (+) @@ -788,4 +800,62 @@ let tests = let res = revert [2;3;4] equal 3 res.Length equal 4 res.Head + + testCase "List.allPairs works" <| fun () -> + let xs = [1;2;3;4] + let ys = ['a';'b';'c';'d';'e';'f'] + List.allPairs xs ys + |> equal + [(1, 'a'); (1, 'b'); (1, 'c'); (1, 'd'); (1, 'e'); (1, 'f'); (2, 'a'); + (2, 'b'); (2, 'c'); (2, 'd'); (2, 'e'); (2, 'f'); (3, 'a'); (3, 'b'); + (3, 'c'); (3, 'd'); (3, 'e'); (3, 'f'); (4, 'a'); (4, 'b'); (4, 'c'); + (4, 'd'); (4, 'e'); (4, 'f')] + + // TODO: Remove conditional compilation after upgrading to dotnet SDK with F# 4.7 + // #if FABLE_COMPILER + testCase "Implicit yields work" <| fun () -> + let makeList condition = + [ + 1 + 2 + if condition then + 3 + ] + makeList true |> List.sum |> equal 6 + makeList false |> List.sum |> equal 3 + // #endif + + testCase "List.splitInto works" <| fun () -> + List.splitInto 3 [1..10] |> equal [ [1..4]; [5..7]; [8..10] ] + List.splitInto 3 [1..11] |> equal [ [1..4]; [5..8]; [9..11] ] + List.splitInto 3 [1..12] |> equal [ [1..4]; [5..8]; [9..12] ] + List.splitInto 4 [1..5] |> equal [ [1..2]; [3]; [4]; [5] ] + List.splitInto 20 [1..4] |> equal [ [1]; [2]; [3]; [4] ] + + testCase "List.transpose works" <| fun () -> + // integer list + List.transpose (seq [[1..3]; [4..6]]) + |> equal [[1; 4]; [2; 5]; [3; 6]] + List.transpose [[1..3]] + |> equal [[1]; [2]; [3]] + List.transpose [[1]; [2]] + |> equal [[1..2]] + // string list + List.transpose (seq [["a";"b";"c"]; ["d";"e";"f"]]) + |> equal [["a";"d"]; ["b";"e"]; ["c";"f"]] + // empty list + List.transpose [] + |> equal [] + // list of empty lists - m x 0 list transposes to 0 x m (i.e. empty) + List.transpose [[]] + |> equal [] + List.transpose [[]; []] + |> equal [] + // jagged lists + throwsAnyError (fun () -> List.transpose [[1; 2]; [3]]) + throwsAnyError (fun () -> List.transpose [[1]; [2; 3]]) + throwsAnyError (fun () -> List.transpose [[]; [1; 2]; [3; 4]]) + throwsAnyError (fun () -> List.transpose [[1; 2]; []; [3; 4]]) + throwsAnyError (fun () -> List.transpose [[1; 2]; [3; 4]; []]) + ] \ No newline at end of file diff --git a/tests/Main/Main.fs b/tests/Main/Main.fs index cf0f15243a..d978d6717d 100644 --- a/tests/Main/Main.fs +++ b/tests/Main/Main.fs @@ -3,48 +3,48 @@ open System let allTests = [| - Applicative.tests - Arithmetic.tests - Arrays.tests - Async.tests - Chars.tests - Comparison.tests - Convert.tests - CustomOperators.tests - DateTimeOffset.tests - DateTime.tests - Dictionaries.tests -#if FABLE_COMPILER - ElmishParser.tests -#endif - Enumerable.tests +// Applicative.tests +// Arithmetic.tests +// Arrays.tests +// Async.tests +// Chars.tests +// Comparison.tests +// Convert.tests +// CustomOperators.tests +// DateTimeOffset.tests +// DateTime.tests +// Dictionaries.tests +// #if FABLE_COMPILER +// ElmishParser.tests +// #endif +// Enumerable.tests Enum.tests - Event.tests - HashSets.tests - Import.tests - JsInterop.tests - Lists.tests - Maps.tests - Misc.tests - Observable.tests - Option.tests - RecordTypes.tests + // Event.tests + // HashSets.tests + // Import.tests + // JsInterop.tests + // Lists.tests + // Maps.tests + // Misc.tests + // Observable.tests + // Option.tests + // RecordTypes.tests Reflection.tests - Regex.tests - ResizeArrays.tests - Result.tests - SeqExpressions.tests - Seqs.tests - Sets.tests - Strings.tests - Sudoku.tests - TailCalls.tests - TimeSpan.tests - TupleTypes.tests - TypeTests.tests - UnionTypes.tests - Uri.tests - Expr.tests + // Regex.tests + // ResizeArrays.tests + // Result.tests + // SeqExpressions.tests + // Seqs.tests + // Sets.tests + // Strings.tests + // Sudoku.tests + // TailCalls.tests + // TimeSpan.tests + // TupleTypes.tests + // TypeTests.tests + // UnionTypes.tests + // Uri.tests + // Expr.tests |] #if FABLE_COMPILER @@ -56,14 +56,23 @@ open Fable.Core.JsInterop // but not available in node.js runtime importSideEffects "./js/polyfill" -let [] describe (name: string) (f: unit->unit) = jsNative -let [] it (msg: string) (f: unit->unit) = jsNative +let [] describe (name: string) (f: unit->unit) : unit = jsNative +let [] it (msg: string) (f: unit->unit) : unit = jsNative -let run () = - for (name, tests) in allTests do + +let rec flattenTest (test:Fable.Tests.Util.Testing.TestKind) : unit = + match test with + | Fable.Tests.Util.Testing.TestKind.TestList(name, tests) -> describe name (fun () -> - for (msg, test) in tests do - it msg (unbox test)) + for t in tests do + flattenTest t) + | Fable.Tests.Util.Testing.TestKind.TestCase (name, test) -> + it name (unbox test) + + +let run () = + for t in allTests do + flattenTest t run() #else @@ -72,8 +81,8 @@ open Expecto [] let main args = - Array.toList allTests - |> testList "All" - |> runTestsWithArgs defaultConfig args + Array.toList allTests + |> testList "All" + |> runTestsWithArgs defaultConfig args #endif diff --git a/tests/Main/MapTests.fs b/tests/Main/MapTests.fs index e2f1a6eb66..c4986794c1 100644 --- a/tests/Main/MapTests.fs +++ b/tests/Main/MapTests.fs @@ -1,7 +1,11 @@ module Fable.Tests.Maps +open System.Collections.Generic open Util.Testing +type R = { i: int; s: string } +type R2 = { kv: KeyValuePair } + let tests = testList "Maps" [ testCase "Map construction from lists works" <| fun () -> @@ -201,43 +205,16 @@ let tests = (Seq.item 2 xs |> snd) = (Seq.item 2 zs |> snd) |> equal true - // type R = { i: int; s: string } - - // testCase "Maps can be JSON serialized forth and back" <| fun () -> - // let x = ["a", { i=1; s="1" }; "b", { i=2; s="2" } ] |> Map - // #if FABLE_COMPILER - // let json = Fable.Core.JsInterop.toJson x - // let x2 = Fable.Core.JsInterop.ofJson> json - // (0, x2) ||> Map.fold (fun acc k v -> acc + v.i) |> equal 3 - // let x2 = Fable.Core.JsInterop.ofJsonAsType json (x.GetType()) :?> Map - // (0, x2) ||> Map.fold (fun acc k v -> acc + v.i) |> equal 3 - // let json = Fable.Core.JsInterop.toJsonWithTypeInfo x - // let x2 = Fable.Core.JsInterop.ofJsonWithTypeInfo> json - // #else - // let json = Newtonsoft.Json.JsonConvert.SerializeObject x - // let x2 = Newtonsoft.Json.JsonConvert.DeserializeObject> json - // #endif - // (0, x2) ||> Map.fold (fun acc k v -> acc + v.i) - // |> equal 3 - - // testCase "Maps serialized with Json.NET can be deserialized" <| fun () -> - // // let x = ["a", { i=1; s="1" }; "b", { i=2; s="2" } ] |> Map - // // let json = JsonConvert.SerializeObject(x, JsonSerializerSettings(TypeNameHandling=TypeNameHandling.All)) - // let json = """{"$type":"Microsoft.FSharp.Collections.FSharpMap`2[[System.String, mscorlib],[Fable.Tests.Maps+R, Fable.Tests]], FSharp.Core","a":{"$type":"Fable.Tests.Maps+R, Fable.Tests","i":1,"s":"1"},"b":{"$type":"Fable.Tests.Maps+R, Fable.Tests","i":2,"s":"2"}}""" - // #if FABLE_COMPILER - // let x2 = Fable.Core.JsInterop.ofJsonWithTypeInfo> json - // #else - // let x2 = Newtonsoft.Json.JsonConvert.DeserializeObject> json - // #endif - // (0, x2) ||> Map.fold (fun acc k v -> acc + v.i) - // |> equal 3 - - // open System.Collections.Generic - - // type R2 = { kv: KeyValuePair } - - // testCase "KeyValuePair can be referenced``() = // Se" <| fun () -> - // let r2 = { kv = new KeyValuePair<_,_>("bar",25) } - // r2.kv.Key |> equal "bar" - // r2.kv.Value |> equal 25 + testCase "Map can be casted to IDictionary" <| fun () -> // See #1729, #1857 + let map = Map [ "a", 1; "b", 2; "c", 3] + let dic = map :> System.Collections.Generic.IDictionary<_,_> + dic.TryGetValue("c") |> equal (true,3) + dic.TryGetValue("d") |> fst |> equal false + dic.Keys |> Seq.toList |> equal ["a"; "b"; "c"] + dic.Values |> Seq.toList |> equal [1; 2; 3] + + testCase "KeyValuePair can be referenced" <| fun () -> + let r2 = { kv = new KeyValuePair<_,_>("bar",25) } + r2.kv.Key |> equal "bar" + r2.kv.Value |> equal 25 ] diff --git a/tests/Main/MiscTests.fs b/tests/Main/MiscTests.fs index f0e69e4a4b..50e28fc6c5 100644 --- a/tests/Main/MiscTests.fs +++ b/tests/Main/MiscTests.fs @@ -364,6 +364,11 @@ type StaticClass = static member inline Add(x: int, ?y: int) = x + (defaultArg y 2) +type ValueType = + struct + val public X : int + end + let tests = testList "Miscellaneous" [ testCase "Values of autogenerated functions are not replaced by optimizations" <| fun () -> // See #1583 @@ -788,8 +793,17 @@ let tests = testCase "Unchecked.defaultof works" <| fun () -> Unchecked.defaultof |> equal 0 + Unchecked.defaultof |> equal 0L + Unchecked.defaultof |> equal 0I + Unchecked.defaultof |> equal 0M + Unchecked.defaultof |> equal DateTime.MinValue + Unchecked.defaultof |> equal (TimeSpan.FromMilliseconds 0.) Unchecked.defaultof |> equal false Unchecked.defaultof |> equal null + Unchecked.defaultof |> equal Guid.Empty + let x = ValueType() + Unchecked.defaultof |> equal x + x.X |> equal 0 testCase "Pattern matching optimization works (switch statement)" <| fun () -> let mutable x = "" @@ -901,4 +915,8 @@ let tests = testCase "Ignore shouldn't return value" <| fun () -> // See #1360 let producer () = 7 equal (box ()) (box(ignore(producer()))) - ] \ No newline at end of file + + testCase "Can import files specified via globbing patterns" <| fun () -> // See #1942 + Glob.hello "Albert" + |> equal "Hello Albert from Glob" + ] diff --git a/tests/Main/OptionTests.fs b/tests/Main/OptionTests.fs index ee97584715..c6afeca0e9 100644 --- a/tests/Main/OptionTests.fs +++ b/tests/Main/OptionTests.fs @@ -90,6 +90,18 @@ let tests = let mutable value = Some "Alfonso" fun () -> match value with Some x -> value <- None; Some x | None -> None getOnlyOnce() |> Option.map ((+) "Hello ") |> equal (Some "Hello Alfonso") + getOnlyOnce() |> Option.map ((+) "Hello ") |> equal None + + testCase "Option.map2 works" <| fun () -> + (Some 2, Some 3) ||> Option.map2 (+) |> equal (Some 5) + (None, Some 3) ||> Option.map2 (+) |> equal None + (Some 2, None) ||> Option.map2 (+) |> equal None + + testCase "Option.map3 works" <| fun () -> + (Some 2, Some 3, Some 4) |||> Option.map3 (fun x y z -> x + y + z) |> equal (Some 9) + (None, Some 3, Some 4) |||> Option.map3 (fun x y z -> x + y + z) |> equal None + (Some 2, None, Some 4) |||> Option.map3 (fun x y z -> x + y + z) |> equal None + (Some 2, Some 3, None) |||> Option.map3 (fun x y z -> x + y + z) |> equal None testCase "Option.bind works" <| fun () -> let getOnlyOnce = @@ -258,4 +270,13 @@ let tests = | Some(Some _) -> 1 | Some(None) -> 2 |> equal 2 + + testCase "Option.map ignore generates Some ()" <| fun () -> // See #1923 + let mySome = Some () + let myOtherSome = mySome |> Option.map (ignore) + equal mySome myOtherSome + + testCase "Some (box null) |> Option.isSome evals to true" <| fun () -> // See #1948 + Some (box null) |> Option.isSome |> equal true + Some (null) |> Option.isSome |> equal true ] diff --git a/tests/Main/RecordTypeTests.fs b/tests/Main/RecordTypeTests.fs index 25e0c6c487..6a10f84326 100644 --- a/tests/Main/RecordTypeTests.fs +++ b/tests/Main/RecordTypeTests.fs @@ -35,16 +35,16 @@ type Id = Id of string let inline replaceById< ^t when ^t : (member Id : Id)> (newItem : ^t) (ar: ^t[]) = Array.map (fun (x: ^t) -> if (^t : (member Id : Id) newItem) = (^t : (member Id : Id) x) then newItem else x) ar -// TODO: Remove this (and the one below) when dotnet tests support anonymous records -#if FABLE_COMPILER let makeAnonRec() = {| X = 5; Y = "Foo"; F = fun x y -> x + y |} -#endif + +type Time = + static member inline duration(value: {| from: int; until: int |}) = value.until - value.from + static member inline duration(value: {| from: int |}) = Time.duration {| value with until = 10 |} let tests = testList "RecordTypes" [ -#if FABLE_COMPILER testCase "Anonymous records work" <| fun () -> let r = makeAnonRec() sprintf "Tell me %s %i times" r.Y (r.F r.X 3) @@ -59,7 +59,22 @@ let tests = let ar = [| {|Id=Id"foo"; Name="Sarah"|}; {|Id=Id"bar"; Name="James"|} |] replaceById {|Id=Id"ja"; Name="Voll"|} ar |> Seq.head |> fun x -> equal "Sarah" x.Name replaceById {|Id=Id"foo"; Name="Anna"|} ar |> Seq.head |> fun x -> equal "Anna" x.Name -#endif + + testCase "Overloads with anonymous record arguments don't have same mangled name" <| fun () -> + Time.duration {| from = 1 |} |> equal 9 + Time.duration {| from = 1; until = 5 |} |> equal 4 + + testCase "Anonymous record execution order" <| fun () -> + let mutable x = 2 + let record = + {| + C = (x <- x * 3; x) + B = (x <- x + 5; x) + A = (x <- x / 2; x) + |} + record.A |> equal 5 + record.B |> equal 11 + record.C |> equal 6 testCase "Recursive record does not cause issues" <| fun () -> let r = { things = [ { things = [] } ] } @@ -93,62 +108,6 @@ let tests = equal 1. x.``s p a c e`` equal 2. x.``s*y*m*b*o*l`` - // testCase "Records can be JSON serialized forth and back" <| fun () -> - // let parent = { children=[|{a="3";b=5}; {b=7;a="1"} |] } - // let sum1 = parent.Sum() - // #if FABLE_COMPILER - // let json = Fable.Core.JsInterop.toJson parent - // let parent2 = Fable.Core.JsInterop.ofJson json - // let sum2 = parent.Sum() - // equal true (box parent2 :? Parent) // Type is kept - // equal true (sum1 = sum2) // Prototype methods can be accessed - // let parent2 = Fable.Core.JsInterop.ofJsonAsType json (parent.GetType()) :?> Parent - // let sum2 = parent.Sum() - // equal true (box parent2 :? Parent) // Type is kept - // equal true (sum1 = sum2) // Prototype methods can be accessed - // let json = Fable.Core.JsInterop.toJsonWithTypeInfo parent - // let parent2 = Fable.Core.JsInterop.ofJsonWithTypeInfo json - // #else - // let json = Newtonsoft.Json.JsonConvert.SerializeObject parent - // let parent2 = Newtonsoft.Json.JsonConvert.DeserializeObject json - // #endif - // let sum2 = parent.Sum() - // equal true (box parent2 :? Parent) // Type is kept - // equal true (sum1 = sum2) // Prototype methods can be accessed - - // testCase "Records serialized with Json.NET can be deserialized" <| fun () -> - // // let x = { a="Hi"; b=20 } - // // let json = JsonConvert.SerializeObject(x, JsonSerializerSettings(TypeNameHandling=TypeNameHandling.All)) - // let json = """{"$type":"Fable.Tests.RecordTypes+Child","a":"Hi","b":10}""" - // #if FABLE_COMPILER - // let x2 = Fable.Core.JsInterop.ofJsonWithTypeInfo json - // #else - // let x2 = Newtonsoft.Json.JsonConvert.DeserializeObject json - // #endif - // x2.a |> equal "Hi" - // x2.b |> equal 10 - - #if FABLE_COMPILER - // testCase "Trying to deserialize a JSON with unexpected $type info throws an exception" <| fun () -> - // let success (f:unit->'T) = - // try f() |> ignore; true - // with _ -> false - // let child = {a="3";b=5} - // let json = JsInterop.toJsonWithTypeInfo child - // success (fun () -> JsInterop.ofJsonWithTypeInfo json) - // |> equal false - // success (fun () -> JsInterop.ofJsonWithTypeInfo json) - // |> equal true - // success (fun () -> JsInterop.ofJsonWithTypeInfo json) - // |> equal true - - // testCase "POJOS can be inflated" <| fun () -> - // let x = Fable.Import.JS.JSON.parse """{"a":"Hi","b":10}""" - // let x2: Child = JsInterop.inflate x - // x2.a |> equal "Hi" - // x2.b |> equal 10 - #endif - testCase "Mutating records work" <| fun () -> let x = { uniqueA = 10; uniqueB = 20 } equal 10 x.uniqueA diff --git a/tests/Main/ReflectionTests.fs b/tests/Main/ReflectionTests.fs index dc1913b054..066c607f16 100644 --- a/tests/Main/ReflectionTests.fs +++ b/tests/Main/ReflectionTests.fs @@ -30,6 +30,11 @@ type TestType5 = class end type GenericRecord<'A,'B> = { a: 'A; b: 'B } +type MyEnum = + | Foo = 1y + | Bar = 5y + | Baz = 8y + let genericTests = [ testCase "typedefof works" <| fun () -> let tdef1 = typedefof @@ -168,8 +173,8 @@ type TestRecord = { } type TestUnion = - | StringCase of String: string * string - | IntCase of Int: int + | StringCase of SomeString: string * string + | IntCase of SomeInt: int type RecordF = { F : int -> string } @@ -187,6 +192,14 @@ type A() = member __.Value = 5 type B() = member __.Value = 10 +type AnonRec1 = {| name: string; child: {| name: string |} |} +type AnonRec2 = {| numbers: int list |} + +type RecordGetValueType = { + Firstname : string + Age : int +} + let reflectionTests = [ testCase "Reflection: Array" <| fun () -> let arType = typeof @@ -252,8 +265,37 @@ let reflectionTests = [ let all = isRecord && matchRecordFields && matchIndividualRecordFields && canMakeSameRecord all |> equal true -// TODO: Remove this when upgrading dotnet SDK to support anonymous records -#if FABLE_COMPILER + testCase "PropertyInfo.GetValue works" <| fun () -> + let value: obj = { Firstname = "Maxime"; Age = 12 } :> obj + + let theType: System.Type = typeof + + // now we want to print out the fields + let fieldNameToValue: Map = + match theType with + | t when FSharpType.IsRecord t -> + FSharpType.GetRecordFields(t) + |> Seq.fold + (fun acc field -> + let fieldValue = field.GetValue value + acc.Add (field.Name, fieldValue) + ) + Map.empty + | _ -> Map.empty + + let expected = "map [(Age, 12); (Firstname, Maxime)]" + + equal expected (sprintf "%O" fieldNameToValue) + + testCase "Comparing anonymous record types works" <| fun () -> + let x = {| numbers = [3; 4] |} + typeof = typeof |> equal false + typeof = typeof |> equal true + typeof = x.GetType() |> equal true + let generic = typeof> + generic = typeof> |> equal false + generic = typeof> |> equal true + testCase "FSharp.Reflection: Anonymous Record" <| fun () -> let typ = typeof<{| String: string; Int: int |}> let record = {| String = "a"; Int = 1 |} @@ -280,7 +322,6 @@ let reflectionTests = [ FSharpValue.MakeRecord(typ, recordValueFields) |> unbox<{| String: string; Int: int |}> |> equal record -#endif testCase "FSharp.Reflection Functions" <| fun () -> let recordType = typeof @@ -341,8 +382,8 @@ let reflectionTests = [ let unionCaseInfos = [| unionCase1Info; unionCase2Info |] let unionCaseValueFields = [| unionCase1ValueFields; unionCase2ValueFields |] - let expectedUnionCase1Fields = 0, "StringCase", [| typeof; typeof |], [| box "a"; box "b" |] - let expectedUnionCase2Fields = 1, "IntCase", [| typeof |], [| box 1 |] + let expectedUnionCase1Fields = 0, "StringCase", [| typeof; typeof |], [| "SomeString"; "Item2" |], [| box "a"; box "b" |] + let expectedUnionCase2Fields = 1, "IntCase", [| typeof |], [| "SomeInt" |], [| box 1 |] let expectedUnionFields = [| expectedUnionCase1Fields; expectedUnionCase2Fields |] let unionFields = @@ -351,7 +392,10 @@ let reflectionTests = [ let types = info.GetFields() |> Array.map (fun field -> field.PropertyType) - info.Tag, info.Name, types, values) + let names = + info.GetFields() + |> Array.map (fun field -> field.Name) + info.Tag, info.Name, types, names, values) let canMakeSameUnionCases = unbox (FSharpValue.MakeUnion(unionCase1Info, unionCase1ValueFields)) = unionCase1 @@ -403,6 +447,14 @@ let reflectionTests = [ testCase "Generic numbers type info doesn't get into runtime" <| fun () -> let value = 0.7833263478179128134089M value.GetType().FullName |> equal "System.Decimal" + +// testCase "Reflection works with enums" <| fun () -> +// typeof.IsEnum |> equal true +// typeof.IsEnum |> equal false +// let t = typeof +// t.IsEnum |> equal true +// t.GetEnumUnderlyingType() |> equal typeof +// System.Enum.GetUnderlyingType(t) |> equal typeof ] // TODO!!! Add reflection tests for interfaces, erased unions, diff --git a/tests/Main/RegexTests.fs b/tests/Main/RegexTests.fs index 1e697f53ef..1e62499e8d 100644 --- a/tests/Main/RegexTests.fs +++ b/tests/Main/RegexTests.fs @@ -26,12 +26,13 @@ let tests = test "^bc" false testCase "Regex.Escape works" <| fun _ -> - Regex.Escape("[(.*?)]") |> equal "\\[\\(\\.\\*\\?\\)]" - Regex.Escape(@"C:\Temp") |> equal "C:\\\\Temp" + // TODO: a few chars are not escaped (e.g. # and white space) + Regex.Escape(@"\*+?|{[()^$") |> equal @"\\\*\+\?\|\{\[\(\)\^\$" + Regex.Escape(@"C:\Temp") |> equal @"C:\\Temp" testCase "Regex.Unescape works" <| fun _ -> - Regex.Unescape("\[\(\.\*\?\)]") |> equal "[(.*?)]" - Regex.Unescape(@"C:\\Temp") |> equal "C:\\Temp" + Regex.Unescape(@"\\\*\+\?\|\{\[\(\)\^\$") |> equal @"\*+?|{[()^$" + Regex.Unescape(@"C:\\Temp") |> equal @"C:\Temp" testCase "Regex instance IsMatch works" <| fun _ -> let str = "For more information, see Chapter 3.4.5.1" @@ -80,6 +81,13 @@ let tests = Regex.IsMatch(str, "^cd", RegexOptions.Multiline) |> equal true Regex.IsMatch(str, "^AB", RegexOptions.Multiline) |> equal false + testCase "RegexOptions.Singleline works" <| fun _ -> + let str = "ab\ncd" + let m1 = Regex.Match(str, ".+") + let m2 = Regex.Match(str, ".+", RegexOptions.Singleline) + m1.Length |> equal 2 + m2.Length |> equal 5 + testCase "Regex.Match works" <| fun _ -> let str = "For more information, see Chapter 3.4.5.1" Regex.Match(str, "Chapter \d+(\.\d)*").Success |> equal true diff --git a/tests/Main/ResizeArrayTests.fs b/tests/Main/ResizeArrayTests.fs index 3f9be909b6..7b2ccc6bee 100644 --- a/tests/Main/ResizeArrayTests.fs +++ b/tests/Main/ResizeArrayTests.fs @@ -22,6 +22,11 @@ let tests = Seq.sum li |> equal 15 + testCase "ResizeArray creation with literal list works" <| fun () -> + let li = ResizeArray<_> [1;2;3;4;5] + Seq.sum li + |> equal 15 + testCase "ResizeArray casting to seq works" <| fun () -> let xs = ResizeArray<_>(seq{1..5}) :> seq<_> Seq.sum xs @@ -163,7 +168,7 @@ let tests = equal 1 xs.[0] equal 4 xs.[1] equal 5 xs.[2] - + testCase "ResizeArray.Exists works" <| fun () -> let xs = ResizeArray() for x in [1 .. 5] do xs.Add(x) diff --git a/tests/Main/SeqTests.fs b/tests/Main/SeqTests.fs index b842a475e9..b19636a8db 100644 --- a/tests/Main/SeqTests.fs +++ b/tests/Main/SeqTests.fs @@ -294,8 +294,8 @@ let tests = testCase "Seq.isEmpty works" <| fun () -> let xs = [1] - Seq.isEmpty xs - |> equal false + Seq.isEmpty xs |> equal false + Seq.isEmpty [] |> equal true testCase "Seq.iter works" <| fun () -> let xs = [1.; 2.; 3.; 4.] @@ -522,6 +522,26 @@ let tests = |> Seq.reduce (+) |> equal 20UL + testCase "Seq.range works with decimal" <| fun () -> + seq{1M .. 50M} + |> Seq.reduce (+) + |> equal 1275M + + testCase "Seq.range step works with decimal" <| fun () -> + seq {-3M .. -0.4359698987M .. -50M} + |> Seq.reduce (+) + |> equal -2843.0340746886M + + testCase "Seq.range works with bigint" <| fun () -> + seq{1I..2000I} + |> Seq.reduce (+) + |> equal 2001000I + + testCase "Seq.range step works with bigint" <| fun () -> + seq {1I .. 10000000000000I .. 20000000000000000I} + |> Seq.reduce (+) + |> equal 19990000000000002000I + testCase "Seq.reduce works" <| fun () -> let xs = [1.; 2.] xs |> Seq.reduce (+) @@ -530,8 +550,13 @@ let tests = testCase "Seq.scan works" <| fun () -> let xs = [1.; 2.; 3.; 4.] let ys = xs |> Seq.scan (+) 0. - sumFirstTwo ys - |> equal 1. + sumFirstTwo ys |> equal 1. + + testCase "Seq.scan works with empty input" <| fun () -> + let xs = Seq.empty + let ys = xs |> Seq.scan (+) 3 + Seq.head ys |> equal 3 + Seq.length ys |> equal 1 testCase "Seq.sort works" <| fun () -> let xs = [3.; 4.; 1.; -3.; 2.; 10.] |> List.toSeq @@ -677,6 +702,24 @@ let tests = ys |> Seq.length |> equal 2 ys |> Seq.head |> fst >= 4 |> equal true + testCase "Seq.distinct works on infinite sequences" <| fun () -> + let rec numbersFrom n = + seq { yield n; yield n; yield! numbersFrom (n + 1) } + let xs = + numbersFrom 1 + |> Seq.distinct + |> Seq.take 5 + xs |> Seq.toList |> equal [1; 2; 3; 4; 5] + + testCase "Seq.distinctBy works on infinite sequences" <| fun () -> + let rec numbersFrom n = + seq { yield n; yield n; yield! numbersFrom (n + 1) } + let xs = + numbersFrom 1 + |> Seq.distinctBy (fun x -> x / 5) + |> Seq.take 5 + xs |> Seq.toList |> equal [1; 5; 10; 15; 20] + testCase "Seq.groupBy works" <| fun () -> let xs = [1; 2; 3; 4] let ys = xs |> Seq.groupBy (fun x -> x % 2) @@ -694,6 +737,11 @@ let tests = xs |> Seq.exactlyOne |> equal 1. + testCase "Seq.tryExactlyOne works" <| fun () -> + seq {yield 1.} |> Seq.tryExactlyOne |> equal (Some 1.) + seq {yield 1.; yield 2.} |> Seq.tryExactlyOne |> equal None + Seq.empty |> Seq.tryExactlyOne |> equal None + testCase "Seq.initInfinite works" <| fun () -> Seq.initInfinite (fun i -> 2. * float i) |> Seq.take 10 @@ -717,6 +765,11 @@ let tests = |> String.concat "" |> equal "122334" + testCase "Seq.pairwise works with empty input" <| fun () -> // See #1941 + ([||] : int array) |> Seq.pairwise |> Seq.toArray |> equal [||] + [1] |> Seq.pairwise |> Seq.toList |> equal [] + [1; 2] |> Seq.pairwise |> Seq.toList |> equal [(1, 2)] + testCase "Seq.readonly works" <| fun () -> let xs = [1.; 2.; 3.; 4.] xs |> Seq.readonly @@ -810,4 +863,51 @@ let tests = Seq.windowed 5 nums |> Seq.toArray |> equal [|[| 1.0; 1.5; 2.0; 1.5; 1.0 |]; [| 1.5; 2.0; 1.5; 1.0; 1.5 |]|] Seq.windowed 6 nums |> Seq.toArray |> equal [|[| 1.0; 1.5; 2.0; 1.5; 1.0; 1.5 |]|] Seq.windowed 7 nums |> Seq.isEmpty |> equal true + + testCase "Seq.allPairs works" <| fun () -> + let mutable accX = 0 + let mutable accY = 0 + let xs = seq { accX <- accX + 1; for i = 1 to 4 do yield i } + let ys = seq { accY <- accY + 1; for i = 'a' to 'f' do yield i } + let res = Seq.allPairs xs ys + let res1 = List.ofSeq res + let res2 = List.ofSeq res + let expected = + [(1, 'a'); (1, 'b'); (1, 'c'); (1, 'd'); (1, 'e'); (1, 'f'); (2, 'a'); + (2, 'b'); (2, 'c'); (2, 'd'); (2, 'e'); (2, 'f'); (3, 'a'); (3, 'b'); + (3, 'c'); (3, 'd'); (3, 'e'); (3, 'f'); (4, 'a'); (4, 'b'); (4, 'c'); + (4, 'd'); (4, 'e'); (4, 'f')] + accX |> equal 2 + accY |> equal 1 + equal expected res1 + equal expected res2 + + testCase "Seq.transpose works" <| fun () -> + let seqEqual (expected: seq<'T seq>) (actual: seq<'T seq>) = + (actual |> Seq.map Seq.toArray |> Seq.toArray) + |> equal (expected |> Seq.map Seq.toArray |> Seq.toArray) + // integer seq + Seq.transpose (seq [seq {1..3}; seq {4..6}]) + |> seqEqual [seq [1; 4]; seq [2; 5]; seq [3; 6]] + Seq.transpose (seq [seq {1..3}]) + |> seqEqual [seq [1]; seq [2]; seq [3]] + Seq.transpose (seq [seq [1]; seq [2]]) + |> seqEqual [seq {1..2}] + // string seq + Seq.transpose (seq [seq ["a";"b";"c"]; seq ["d";"e";"f"]]) + |> seqEqual [seq ["a";"d"]; seq ["b";"e"]; seq ["c";"f"]] + // empty seq + Seq.transpose Seq.empty + |> seqEqual Seq.empty + // seq of empty seqs - m x 0 seq transposes to 0 x m (i.e. empty) + Seq.transpose (seq [Seq.empty]) + |> seqEqual Seq.empty + Seq.transpose (seq [Seq.empty; Seq.empty]) + |> seqEqual Seq.empty + // sequences of lists + Seq.transpose [["a";"b"]; ["c";"d"]] + |> seqEqual [seq ["a";"c"]; seq ["b";"d"]] + Seq.transpose (seq { yield ["a";"b"]; yield ["c";"d"] }) + |> seqEqual [seq ["a";"c"]; seq ["b";"d"]] + ] \ No newline at end of file diff --git a/tests/Main/SetTests.fs b/tests/Main/SetTests.fs index 2494eccd85..4e178c07e5 100644 --- a/tests/Main/SetTests.fs +++ b/tests/Main/SetTests.fs @@ -268,37 +268,4 @@ let tests = (Seq.item 2 xs) = (Seq.item 2 zs) |> equal true - // type R = { i: int; s: string } - - // testCase "Sets can be JSON serialized forth and back" <| fun () -> - // let x = [{ i=1; s="1" }; { i=2; s="2" } ] |> set - // #if FABLE_COMPILER - // let json = Fable.Core.JsInterop.toJson x - // let x2 = Fable.Core.JsInterop.ofJson> json - // x2.IsSubsetOf x |> equal true - // (0, x2) ||> Set.fold (fun acc v -> acc + v.i) |> equal 3 - // let x2 = Fable.Core.JsInterop.ofJsonAsType json (x.GetType()) :?> Set - // x2.IsSubsetOf x |> equal true - // (0, x2) ||> Set.fold (fun acc v -> acc + v.i) |> equal 3 - // let json = Fable.Core.JsInterop.toJsonWithTypeInfo x - // let x2 = Fable.Core.JsInterop.ofJsonWithTypeInfo> json - // #else - // let json = Newtonsoft.Json.JsonConvert.SerializeObject x - // let x2 = Newtonsoft.Json.JsonConvert.DeserializeObject> json - // #endif - // x2.IsSubsetOf x |> equal true - // (0, x2) ||> Set.fold (fun acc v -> acc + v.i) - // |> equal 3 - - // testCase "Sets serialized with Json.NET can be deserialized" <| fun () -> - // // let x = ["a", { i=1; s="1" }; "b", { i=2; s="2" } ] |> Map - // // let json = JsonConvert.SerializeObject(x, JsonSerializerSettings(TypeNameHandling=TypeNameHandling.All)) - // let json = """{"$type":"Microsoft.FSharp.Collections.FSharpSet`1[[Fable.Tests.Sets+R, Fable.Tests]], FSharp.Core","$values":[{"$type":"Fable.Tests.Sets+R, Fable.Tests","i":1,"s":"1"},{"$type":"Fable.Tests.Sets+R, Fable.Tests","i":2,"s":"2"}]}""" - // #if FABLE_COMPILER - // let x2 = Fable.Core.JsInterop.ofJsonWithTypeInfo> json - // #else - // let x2 = Newtonsoft.Json.JsonConvert.DeserializeObject> json - // #endif - // (0, x2) ||> Set.fold (fun acc v -> acc + v.i) - // |> equal 3 ] diff --git a/tests/Main/StringTests.fs b/tests/Main/StringTests.fs index dcfa8974d4..2ca8214e83 100644 --- a/tests/Main/StringTests.fs +++ b/tests/Main/StringTests.fs @@ -33,6 +33,30 @@ let tests = // Format + testCase "StringBuilder works" <| fun () -> + let sb = System.Text.StringBuilder() + sb.Append "Hello" |> ignore + sb.AppendLine () |> ignore + sb.AppendLine "World!" |> ignore + let expected = System.Text.StringBuilder() + .AppendFormat("Hello{0}World!{0}", Environment.NewLine) + .ToString() + sb.ToString() |> equal expected + + testCase "StringBuilder.Lengh works" <| fun () -> + let sb = System.Text.StringBuilder() + sb.Append("Hello") |> ignore + // We don't test the AppendLine for Length because depending on the OS + // the result is different. Unix \n VS Windows \r\n + // sb.AppendLine() |> ignore + equal 5 sb.Length + + testCase "StringBuilder.ToString works with index and length" <| fun () -> + let sb = System.Text.StringBuilder() + sb.Append("Hello") |> ignore + sb.AppendLine() |> ignore + equal "ll" (sb.ToString(2, 2)) + testCase "kprintf works" <| fun () -> let f (s:string) = s + "XX" Printf.kprintf f "hello" |> equal "helloXX" @@ -83,6 +107,23 @@ let tests = let printer2 = printer2 "afternoon" printer2 "?" |> equal "Hi Maxime, good afternoon?" + testCase "sprintf with different decimal digits works" <| fun () -> // See #1932 + sprintf "Percent: %.0f%%" 5.0 |> equal "Percent: 5%" + sprintf "Percent: %.2f%%" 5. |> equal "Percent: 5.00%" + sprintf "Percent: %.1f%%" 5.24 |> equal "Percent: 5.2%" + sprintf "Percent: %.2f%%" 5.268 |> equal "Percent: 5.27%" + sprintf "Percent: %f%%" 5.67 |> equal "Percent: 5.670000%" + + testCase "sprintf displays sign correctly" <| fun () -> // See #1937 + sprintf "%i" 1 |> equal "1" + sprintf "%d" 1 |> equal "1" + sprintf "%d" 1L |> equal "1" + sprintf "%.2f" 1. |> equal "1.00" + sprintf "%i" -1 |> equal "-1" + sprintf "%d" -1 |> equal "-1" + sprintf "%d" -1L |> equal "-1" + sprintf "%.2f" -1. |> equal "-1.00" + testCase "Print.sprintf works" <| fun () -> // See #1216 let res = Printf.sprintf "%s" "abc" equal "res: abc" ("res: " + res) @@ -156,6 +197,30 @@ let tests = sprintf "%A" o |> ignore #endif + testCase "sprintf \"%A\" with lists works" <| fun () -> + let xs = ["Hi"; "Hello"; "Hola"] + (sprintf "%A" xs).Replace("\"", "") |> equal "[Hi; Hello; Hola]" + + testCase "sprintf \"%A\" with nested lists works" <| fun () -> + let xs = [["Hi"]; ["Hello"]; ["Hola"]] + (sprintf "%A" xs).Replace("\"", "") |> equal "[[Hi]; [Hello]; [Hola]]" + + testCase "sprintf \"%A\" with sequences works" <| fun () -> + let xs = seq { "Hi"; "Hello"; "Hola" } + (sprintf "%A" xs).Replace("\"", "") |> equal "seq [Hi; Hello; Hola]" + + testCase "Storing result of Seq.tail and printing the result several times works. Related to #1996" <| fun () -> + let tweets = seq { "Hi"; "Hello"; "Hola" } + let tweetsTailR: seq = tweets |> Seq.tail + + let a = sprintf "%A" (tweetsTailR) + let b = sprintf "%A" (tweetsTailR) + + let expected = "seq [Hello; Hola]" + + equal expected (a.Replace("\"", "")) + equal expected (b.Replace("\"", "")) + testCase "sprintf \"%X\" works" <| fun () -> //These should all be the Native JS Versions (except int64 / uint64) //See #1530 for more information. @@ -172,6 +237,18 @@ let tests = sprintf "1L <<< 63: %x" (1L <<< 63) |> equal "1L <<< 63: 8000000000000000" sprintf "1uL <<< 63: %x" (1uL <<< 63) |> equal "1uL <<< 63: 8000000000000000" + testCase "sprintf integers with sign and padding works" <| fun () -> // See #1931 + sprintf "%+04i" 1 |> equal "+001" + sprintf "%+04i" -1 |> equal "-001" + sprintf "%5d" -5 |> equal " -5" + sprintf "%5d" -5L |> equal " -5" + sprintf "%- 4i" 5 |> equal " 5 " + + testCase "String.Format combingin padding and zeroes pattern works" <| fun () -> + String.Format("{0:++0.00++}", -5000.5657) |> equal "-++5000.57++" + String.Format("{0:000.00}foo", 5) |> equal "005.00foo" + String.Format("{0,-8:000.00}foo", 12.456) |> equal "012.46 foo" + testCase "String.Format {0:x} works" <| fun () -> //See above comment on expected values String.Format("255: {0:X}", 255) |> equal "255: FF" @@ -489,6 +566,10 @@ let tests = @"\\\abc///".Trim('\\','/') |> equal "abc" + testCase "String.Trim with special chars works" <| fun () -> + @"()[]{}abc/.?*+-^$|\".Trim(@"()[]{}/.?*+-^$|\".ToCharArray()) + |> equal "abc" + testCase "String.TrimStart works" <| fun () -> "!!--abc ".TrimStart('!','-') |> equal "abc " @@ -524,6 +605,13 @@ let tests = "abcdefg".Substring(2, 2) |> equal "cd" + testCase "String.Substring throws error if startIndex or length are out of bounds" <| fun () -> // See #1955 + let throws f = + try f () |> ignore; false + with _ -> true + throws (fun _ -> "abcdefg".Substring(20)) |> equal true + throws (fun _ -> "abcdefg".Substring(2, 10)) |> equal true + testCase "String.ToUpper works" <| fun () -> "AbC".ToUpper() |> equal "ABC" @@ -596,6 +684,42 @@ let tests = String.Concat(seq { yield "a"; yield "b"; yield "c" }) |> equal "abc" + testCase "System.String.Join with long array works" <| fun () -> + let n = 1_000_000 + let a = Array.init n (fun _i -> "a") + let s = String.Join("", a) + s.Length |> equal n + + testCase "System.String.Join with long seq works" <| fun () -> + let n = 1_000_000 + let a = seq { for i in 1..n -> "a" } + let s = String.Join("", a) + s.Length |> equal n + + testCase "System.String.Concat with long array works" <| fun () -> + let n = 1_000_000 + let a = Array.init n (fun _i -> "a") + let s = String.Concat(a) + s.Length |> equal n + + testCase "System.String.Concat with long seq works" <| fun () -> + let n = 1_000_000 + let a = seq { for i in 1..n -> "a" } + let s = String.Concat(a) + s.Length |> equal n + + testCase "String.concat with long array works" <| fun () -> + let n = 1_000_000 + let a = Array.init n (fun _i -> "a") + let s = String.concat "" a + s.Length |> equal n + + testCase "String.concat with long seq works" <| fun () -> + let n = 1_000_000 + let a = seq { for i in 1..n -> "a" } + let s = String.concat "" a + s.Length |> equal n + testCase "String.Remove works" <| fun () -> "abcd".Remove(2) |> equal "ab" diff --git a/tests/Main/TailCallTests.fs b/tests/Main/TailCallTests.fs index 71bb4a693c..66a73c81d9 100644 --- a/tests/Main/TailCallTests.fs +++ b/tests/Main/TailCallTests.fs @@ -99,6 +99,14 @@ and parseTokens tokens = function | x::xs -> parseTokens tokens xs | [] -> List.rev tokens +type Element = + | Element of action: (unit->unit) * children: Element list + member this.Activate() = + match this with + | Element(action, children) -> + action() + for child in children do child.Activate() + let tests = testList "TailCalls" [ testCase "Recursive functions can be tailcall optimized" <| fun () -> @@ -192,4 +200,52 @@ let tests = then yield i + i + 3 } seq { yield 2; yield! oddprms } |> Seq.length |> equal 23000 + + testCase "Expressiones captured in a closure don't change after tail-call optimizations" <| fun () -> // See #1859 + let mutable accValue = 0 + let el action children = Element(action, children) + + let init () = + [|1 .. 4|] |> Array.map (fun i -> i, false) |> Map.ofArray + + let update msg (model: Map) = + accValue <- accValue + msg + let b = model.[msg] + Map.add msg (not b) model + + let view model dispatch = + let rec looper acc x = + match x with + |(i1,b1)::(i2,b2)::rest -> + let newParent = + el ignore [ + el (fun _ -> + // Force the x argument to be captured + // by the closure + match x with + |(i1,_)::_ -> i1 |> dispatch + | _ -> ()) [] + el (fun _ -> i2 |> dispatch) [] + ] + looper (newParent::acc) rest + |(i,b)::rest -> + let newParent = + el (fun _ -> i |> dispatch) [] + looper (newParent::acc) rest + |[] -> acc + + // Use two looper references to prevent the binding + // beta reduction and force the tail-call optimization + model |> Map.toList |> looper [] |> ignore + model |> Map.toList |> looper [] |> el ignore + + let main init view update = + let mutable model = init() + let dispatch m msg = + model <- update msg m + let el: Element = view model (dispatch model) + el.Activate() + + main init view update + accValue |> equal 10 ] \ No newline at end of file diff --git a/tests/Main/TimeSpanTests.fs b/tests/Main/TimeSpanTests.fs index 786937375d..0c4401da4e 100644 --- a/tests/Main/TimeSpanTests.fs +++ b/tests/Main/TimeSpanTests.fs @@ -14,6 +14,10 @@ let tests = TimeSpan.FromDays(18.).ToString() |> equal "18.00:00:00" TimeSpan.FromMilliseconds(25.).ToString() |> equal "00:00:00.0250000" + testCase "TimeSpan.ToString() works for negative TimeSpan" <| fun () -> + TimeSpan.FromSeconds(-5.).ToString() |> equal "-00:00:05" + TimeSpan.FromDays(-5.23).ToString() |> equal "-5.05:31:12" + testCase "TimeSpan.ToString(\"c\", CultureInfo.InvariantCulture) works" <| fun () -> TimeSpan(0L).ToString("c", CultureInfo.InvariantCulture) |> equal "00:00:00" TimeSpan.FromSeconds(12345.).ToString("c", CultureInfo.InvariantCulture) |> equal "03:25:45" @@ -42,11 +46,13 @@ let tests = let t2 = TimeSpan(3, 3, 3) let t3 = TimeSpan(5, 5, 5, 5) let t4 = TimeSpan(7, 7, 7, 7, 7) + let t5 = TimeSpan(-2,0,0,0) t1.TotalMilliseconds |> equal 2.0 t2.TotalMilliseconds |> equal 10983000.0 t3.TotalMilliseconds |> equal 450305000.0 t4.TotalMilliseconds |> equal 630427007.0 + t5.TotalMilliseconds |> equal -172800000.0 t1.TotalMilliseconds + t2.TotalMilliseconds + t3.TotalMilliseconds + t4.TotalMilliseconds |> equal 1091715009.0 @@ -265,7 +271,7 @@ let tests = // https://github.com/dotnet/dotnet-api-docs/blob/7f6a3882631bc008b858adfadb43cd17bbd55d49/xml/System/TimeSpan.xml#L2772 testCase "TimeSpan 24:0:0 parse fails" <| fun () -> (fun _ -> TimeSpan.Parse("24:0:0")) - |> Util.throwsError "String was not recognized as a valid TimeSpan." + |> Util.throwsError "String '24:0:0' was not recognized as a valid TimeSpan." testCase "TimeSpan 24:0:0 TryParse fails" <| fun () -> let status, _ = TimeSpan.TryParse("24:0:0") @@ -277,47 +283,60 @@ let tests = let expected = TimeSpan(0, 0, 0, 59, 0) equal actual expected +#if FABLE_COMPILER // temporary, TODO: fix test to be backwards compatible testCase "TimeSpan 0:60:0 parse fails" <| fun () -> (fun _ -> TimeSpan.Parse("0:60:0")) #if FABLE_COMPILER - |> Util.throwsError "String was not recognized as a valid TimeSpan." + |> Util.throwsError "String '0:60:0' was not recognized as a valid TimeSpan." #else - |> Util.throwsError "The TimeSpan could not be parsed because at least one of the numeric components is out of range or contains too many digits." + |> Util.throwsError "The TimeSpan string '0:60:0' could not be parsed because at least one of the numeric components is out of range or contains too many digits." +#endif #endif + +#if FABLE_COMPILER // temporary, TODO: fix test to be backwards compatible testCase "TimeSpan 10: parse fails" <| fun () -> (fun _ -> TimeSpan.Parse("10:")) - |> Util.throwsError "String was not recognized as a valid TimeSpan." + |> Util.throwsError "String '10:' was not recognized as a valid TimeSpan." +#endif testCase "TimeSpan 10:0 parse works" <| fun () -> let actual = TimeSpan.Parse("10:0") let expected = TimeSpan(0, 10, 0, 0, 0) equal actual expected +#if FABLE_COMPILER // temporary, TODO: fix test to be backwards compatible testCase "TimeSpan 10:20: parse fails" <| fun () -> (fun _ -> TimeSpan.Parse("10:20:")) - |> Util.throwsError "String was not recognized as a valid TimeSpan." + |> Util.throwsError "String '10:20:' was not recognized as a valid TimeSpan." +#endif testCase "TimeSpan 10:20:0 parse works" <| fun () -> let actual = TimeSpan.Parse("10:20:0") let expected = TimeSpan(0, 10, 20, 0, 0) equal actual expected +#if FABLE_COMPILER // temporary, TODO: fix test to be backwards compatible testCase "TimeSpan .123 parse fails" <| fun () -> (fun _ -> TimeSpan.Parse(".123")) - |> Util.throwsError "String was not recognized as a valid TimeSpan." + |> Util.throwsError "String '.123' was not recognized as a valid TimeSpan." +#endif testCase "TimeSpan 0.12:00 parse works" <| fun () -> let actual = TimeSpan.Parse("0.12:00") let expected = TimeSpan(0, 12, 00, 0, 0) equal actual expected +#if FABLE_COMPILER // temporary, TODO: fix test to be backwards compatible testCase "TimeSpan 10. parse fails" <| fun () -> (fun _ -> TimeSpan.Parse("10.")) - |> Util.throwsError "String was not recognized as a valid TimeSpan." + |> Util.throwsError "String '10.' was not recognized as a valid TimeSpan." +#endif +#if FABLE_COMPILER // temporary, TODO: fix test to be backwards compatible testCase "TimeSpan 10.12 parse fails" <| fun () -> (fun _ -> TimeSpan.Parse("10.12")) - |> Util.throwsError "String was not recognized as a valid TimeSpan." + |> Util.throwsError "String '10.12' was not recognized as a valid TimeSpan." +#endif testCase "TimeSpan 10.12:00 parse works" <| fun () -> let actual = TimeSpan.Parse("10.12:00") @@ -424,4 +443,125 @@ let tests = let expected = TimeSpan(10, 12, 00, 0, 0) equal status true equal actual expected + + testCase "TimeSpan 00:00:00.1 Parse handle correctly the milliseconds" <| fun () -> + let actual = TimeSpan.Parse("00:00:00.1").TotalMilliseconds + let expected = 100. + equal actual expected + + testCase "TimeSpan 00:00:00.12 Parse handle correctly the milliseconds" <| fun () -> + let actual = TimeSpan.Parse("00:00:00.12").TotalMilliseconds + let expected = 120. + equal actual expected + + testCase "TimeSpan 00:00:00.123 Parse handle correctly the milliseconds" <| fun () -> + let actual = TimeSpan.Parse("00:00:00.123").TotalMilliseconds + let expected = 123. + equal actual expected + + testCase "TimeSpan 00:00:00.1234 Parse handle correctly the milliseconds" <| fun () -> + let actual = TimeSpan.Parse("00:00:00.1234").TotalMilliseconds + let expected = 123.4 + equal actual expected + + testCase "TimeSpan 00:00:00.12345 Parse handle correctly the milliseconds" <| fun () -> + let actual = TimeSpan.Parse("00:00:00.12345").TotalMilliseconds + let expected = 123.45 + equal actual expected + + testCase "TimeSpan 00:00:00.123456 Parse handle correctly the milliseconds" <| fun () -> + let actual = TimeSpan.Parse("00:00:00.123456").TotalMilliseconds + let expected = 123.456 + equal actual expected + + testCase "TimeSpan 00:00:00.0034567 Parse handle correctly the milliseconds" <| fun () -> + let actual = TimeSpan.Parse("00:00:00.0034567").TotalMilliseconds + let expected = 3.4567 + equal actual expected + + testCase "TimeSpan Parse work with negative TimeSpan" <| fun () -> + let actual = TimeSpan.Parse("-2:00:00") + equal actual.TotalMilliseconds -7200000.0 + + testCase "TimeSpan 1.23:45:06.789 TotalMilliseconds works" <| fun () -> + let actual = TimeSpan.Parse("1.23:45:06.789").TotalMilliseconds + let expected = 171906789.0 + equal actual expected + + testCase "TimeSpan 1.23:45:06.789 TotalSeconds works" <| fun () -> + let actual = TimeSpan.Parse("1.23:45:06.789").TotalSeconds + let expected = 171906.789 + equal actual expected + + testCase "TimeSpan 1.23:45:06.789 TotalMinutes works" <| fun () -> + let actual = TimeSpan.Parse("1.23:45:06.789").TotalMinutes + let expected = 2865.11315 + equal actual expected + + testCase "TimeSpan 1.23:45:06.789 TotalHours works" <| fun () -> + let actual = TimeSpan.Parse("1.23:45:06.789").TotalHours + let expected = 47.75188583333333 + equal actual expected + + testCase "TimeSpan 1.23:45:06.789 TotalDays works" <| fun () -> + let actual = TimeSpan.Parse("1.23:45:06.789").TotalDays + let expected = 1.9896619097222221 + equal actual expected + + // TODO: This tests fails because of the decimal part of the milliseconds, see #1867 + // testCase "TimeSpan TotalSeconds & friends work" <| fun () -> + // let ts = TimeSpan.FromDays(0.005277777778) + // ts.TotalMilliseconds |> equal 456000.0 + // ts.TotalSeconds |> equal 456. + // ts.TotalMinutes |> equal 7.6 + + testCase "TimeSpan.Milliseconds works with positive TimeSpan" <| fun () -> + let actual = TimeSpan.Parse("1.23:45:06.789").Milliseconds + let expected = 789 + equal actual expected + + testCase "TimeSpan.Milliseconds works with negative TimeSpan" <| fun () -> + let actual = TimeSpan.Parse("-1.23:45:06.78999").Milliseconds + let expected = -789 + equal actual expected + + testCase "TimeSpan.Seconds works with positive TimeSpan" <| fun () -> + let actual = TimeSpan.Parse("1.23:45:06.789").Seconds + let expected = 6 + equal actual expected + + testCase "TimeSpan.Seconds works with negative TimeSpan" <| fun () -> + let actual = TimeSpan.Parse("-1.23:45:06.78999").Seconds + let expected = -6 + equal actual expected + + testCase "TimeSpan.Minutes works with positive TimeSpan" <| fun () -> + let actual = TimeSpan.Parse("1.23:45:06.789").Minutes + let expected = 45 + equal actual expected + + testCase "TimeSpan.Minutes works with negative TimeSpan" <| fun () -> + let actual = TimeSpan.Parse("-1.23:45:06.78999").Minutes + let expected = -45 + equal actual expected + + testCase "TimeSpan.Hours works with positive TimeSpan" <| fun () -> + let actual = TimeSpan.Parse("1.23:45:06.789").Hours + let expected = 23 + equal actual expected + + testCase "TimeSpan.Hours works with negative TimeSpan" <| fun () -> + let actual = TimeSpan.Parse("-1.23:45:06.78999").Hours + let expected = -23 + equal actual expected + + testCase "TimeSpan.Days works with positive TimeSpan" <| fun () -> + let actual = TimeSpan.Parse("1.23:45:06.789").Days + let expected = 1 + equal actual expected + + testCase "TimeSpan.Days works with negative TimeSpan" <| fun () -> + let actual = TimeSpan.Parse("-1.23:45:06.78999").Days + let expected = -1 + equal actual expected ] diff --git a/tests/Main/TypeTests.fs b/tests/Main/TypeTests.fs index 9b35b724c2..a741d5f84c 100644 --- a/tests/Main/TypeTests.fs +++ b/tests/Main/TypeTests.fs @@ -1,4 +1,4 @@ -module Fable.Tests.TypeTests +module Fable.Tests.TypeTests open System open Util.Testing @@ -223,6 +223,11 @@ type ValueType1<'T>(value: 'T) = type ValueType2(i: int, j: int) = member x.Value = i + j +type ValueType3 = + struct + val mutable public X : int + end + [] type StructUnion = Value of string @@ -253,6 +258,41 @@ type TypeWithClassAttribute = val Pos : int new (pos) = { Pos=pos } +// ------------------------------------------------------------- +// Issue #1975: https://github.com/fable-compiler/Fable/issues/1975 +// In previous version of Fable, using type with parameterized units of measure was causing an endless loops in the compiler + +type TestTypeWithParameterizedUnitMeasure<[] 't> = + private | TestTypeWithParameterizedUnitMeasureType of float<'t> + + member this.Value = + match this with + | TestTypeWithParameterizedUnitMeasureType value -> value + +let makeTestTypeWithParameterizedUnitMeasureType (value: float<_>) : TestTypeWithParameterizedUnitMeasure<_> = + TestTypeWithParameterizedUnitMeasureType value + +open FSharp.Data.UnitSystems.SI.UnitSymbols + +type Test_TestTypeWithParameterizedUnitMeasure = { + Field: TestTypeWithParameterizedUnitMeasure +} + +// ------------------------------------------------------------- + +// Tested ported from https://github.com/fable-compiler/Fable/pull/1336/files +type TestTypeWithDefaultValue() = + [] val mutable IntValue: int + [] val mutable StringValue: string + [] val mutable ObjValue: System.Collections.Generic.Dictionary + +type Default1 = int + +type Distinct1 = + // Overloads only distinguished by generic constrain work, see #1908 + static member inline Distinct1 (x: ^``Collection<'T>``, _impl: Default1) = (^``Collection<'T>`` : (static member Distinct1 : _->_) x) : '``Collection<'T>`` + static member inline Distinct1 (_: ^t when ^t : null and ^t : struct, _mthd: Default1) = id //must + let tests = testList "Types" [ testCase "Types can instantiate their parent in the constructor" <| fun () -> @@ -409,6 +449,10 @@ let tests = let g1 = Guid.Empty string g1 |> equal "00000000-0000-0000-0000-000000000000" + testCase "Guid.ToString works" <| fun () -> + let g1 = Guid.Parse "dec42487-c02b-42a6-9a10-0263a5a7fdf1" + string g1 |> equal "dec42487-c02b-42a6-9a10-0263a5a7fdf1" + testCase "lazy works" <| fun () -> let mutable snitch = 0 let lazyVal = @@ -450,57 +494,6 @@ let tests = search "b" |> equal (Some "b") search "d" |> equal None - // testCase "Classes can be JSON serialized forth and back" <| fun () -> - // let x = Serializable(5) - // #if FABLE_COMPILER - // let json = Fable.Core.JsInterop.toJson x - // let x2 = Fable.Core.JsInterop.ofJson json - // string x |> equal "Public: 1 - Private: 5 - Deserialized: false" - // string x2 |> equal "Public: 1 - Private: 0 - Deserialized: true" - // let x2 = Fable.Core.JsInterop.ofJsonAsType json (x.GetType()) :?> Serializable - // string x |> equal "Public: 1 - Private: 5 - Deserialized: false" - // string x2 |> equal "Public: 1 - Private: 0 - Deserialized: true" - // let json = Fable.Core.JsInterop.toJsonWithTypeInfo x - // let x2 = Fable.Core.JsInterop.ofJsonWithTypeInfo json - // #else - // let json = Newtonsoft.Json.JsonConvert.SerializeObject x - // let x2 = Newtonsoft.Json.JsonConvert.DeserializeObject json - // #endif - // string x |> equal "Public: 1 - Private: 5 - Deserialized: false" - // string x2 |> equal "Public: 1 - Private: 0 - Deserialized: true" - - // testCase "Null values can be JSON serialized forth and back" <| fun () -> - // let x: Serializable = null - // #if FABLE_COMPILER - // let json = Fable.Core.JsInterop.toJson x - // let x2 = Fable.Core.JsInterop.ofJsonAsType json (typedefof) - // equal x2 null - // let json = Fable.Core.JsInterop.toJson x - // let x2 = Fable.Core.JsInterop.ofJson json - // equal x2 null - // let json = Fable.Core.JsInterop.toJsonWithTypeInfo x - // let x2 = Fable.Core.JsInterop.ofJsonWithTypeInfo json - // #else - // let json = Newtonsoft.Json.JsonConvert.SerializeObject x - // let x2 = Newtonsoft.Json.JsonConvert.DeserializeObject json - // #endif - // equal x2 null - - // testCase "Classes serialized with Json.NET can be deserialized" <| fun () -> - // // let x = Serializable(5) - // // let json = JsonConvert.SerializeObject(x, JsonSerializerSettings(TypeNameHandling=TypeNameHandling.All)) - // let json = """{"$type":"Fable.Tests.TypeTests+Serializable","PublicValue":1}""" - // #if FABLE_COMPILER - // let x2 = Fable.Core.JsInterop.ofJson json - // string x2 |> equal "Public: 1 - Private: 0 - Deserialized: true" - // let x2 = Fable.Core.JsInterop.ofJsonAsType json typedefof - // string x2 |> equal "Public: 1 - Private: 0 - Deserialized: true" - // let x2 = Fable.Core.JsInterop.ofJsonWithTypeInfo json - // #else - // let x2 = Newtonsoft.Json.JsonConvert.DeserializeObject json - // #endif - // string x2 |> equal "Public: 1 - Private: 0 - Deserialized: true" - testCase "Secondary constructors work" <| fun () -> let s1 = SecondaryCons(3) let s2 = SecondaryCons() @@ -623,6 +616,18 @@ let tests = let p = Point2D(2.) p.Y |> equal 2. + testCase "struct without explicit ctor works" <| fun () -> + let t1 = ValueType3(X=10) + t1.X |> equal 10 + let mutable t2 = ValueType3() + t2.X |> equal 0 + t1 |> notEqual t2 + (compare t1 t2) |> equal 1 + t2.X <- 10 + t1 |> equal t2 + + (compare t1 t2) |> equal 0 + testCase "Custom F# exceptions work" <| fun () -> try MyEx(4,"ERROR") |> raise @@ -666,4 +671,22 @@ let tests = testCase "ClassAttribute works" <| fun () -> // See #573 let t1 = TypeWithClassAttribute(8) t1.Pos |> equal 8 - ] \ No newline at end of file + + testCase "Issue #1975: Compile type with parameterized units of measure as generic" <| fun () -> + let a = makeTestTypeWithParameterizedUnitMeasureType 2. + equal 2. a.Value + + // Test ported from https://github.com/fable-compiler/Fable/pull/1336/files + testCase "default value attributes works" <| fun _ -> + let withDefaultValue = TestTypeWithDefaultValue() + + withDefaultValue.IntValue |> equal Unchecked.defaultof + withDefaultValue.IntValue |> equal 0 + + withDefaultValue.StringValue |> equal Unchecked.defaultof + withDefaultValue.StringValue |> equal null + + withDefaultValue.ObjValue |> equal Unchecked.defaultof> + withDefaultValue.ObjValue |> equal null + + ] diff --git a/tests/Main/UnionTypeTests.fs b/tests/Main/UnionTypeTests.fs index 075c3901b2..aaf9f59a64 100644 --- a/tests/Main/UnionTypeTests.fs +++ b/tests/Main/UnionTypeTests.fs @@ -76,12 +76,6 @@ type R = { #if FABLE_COMPILER open Fable.Core -[] -let jsonParse (json: string) = jsNative - -[] -let jsonStringify (json): string = jsNative - [] #endif type DU = Int of int | Str of string @@ -175,108 +169,6 @@ let tests = Some(5, None) |> test |> equal 0 None |> test |> equal 0 - // TODO - // #if FABLE_COMPILER - // testCase "Pattern matching json parse union cases still works" <| fun () -> - // // Test IntType - // match jsonParse """{"tag":0,"data":1}""" with - // | IntType x -> x - // | _ -> failwith "unexpected" - // |> equal 1 - // // Test StringType - // match jsonParse """{"tag":1,"data":"value1"}""" with - // | StringType x -> x - // | _ -> failwith "unexpected" - // |> equal "value1" - // // Test TupleType - // match jsonParse """{"tag":2,"data":["value1",2]}""" with - // | TupleType(x, y) -> x, y - // | _ -> failwith "unexpected" - // |> fun (x, y) -> - // x |> equal "value1" - // y |> equal 2 - // // Test ObjectType - // match jsonParse """{"tag":3,"data":{"Prop1":"value1","Prop2":2}}""" with - // | ObjectType(x) -> x - // | _ -> failwith "unexpected" - // |> fun x -> - // x.Prop1 |> equal "value1" - // x.Prop2 |> equal 2 - - // testCase "Union cases json stringify is as we expect" <| fun () -> - // ObjectType({Prop1 = "value1"; Prop2 = 2}) - // |> jsonStringify - // |> equal """{"tag":3,"data":{"Prop1":"value1","Prop2":2}}""" - // #endif - - // testCase "Unions can be JSON serialized forth and back" <| fun () -> - // let tree = Branch [|Leaf 1; Leaf 2; Branch [|Leaf 3; Leaf 4|]|] - // let sum1 = tree.Sum() - // #if FABLE_COMPILER - // let json = Fable.Core.JsInterop.toJson tree - // let tree2 = Fable.Core.JsInterop.ofJson json - // let sum2 = tree2.Sum() - // equal true (box tree2 :? Tree) // Type is kept - // equal true (sum1 = sum2) // Prototype methods can be accessed - // let tree2 = Fable.Core.JsInterop.ofJsonAsType json (tree.GetType()) :?> Tree - // let sum2 = tree2.Sum() - // equal true (box tree2 :? Tree) // Type is kept - // equal true (sum1 = sum2) // Prototype methods can be accessed - // let json = Fable.Core.JsInterop.toJsonWithTypeInfo tree - // let tree2 = Fable.Core.JsInterop.ofJsonWithTypeInfo json - // #else - // let json = Newtonsoft.Json.JsonConvert.SerializeObject tree - // let tree2 = Newtonsoft.Json.JsonConvert.DeserializeObject json - // #endif - // let sum2 = tree2.Sum() - // equal true (box tree2 :? Tree) // Type is kept - // equal true (sum1 = sum2) // Prototype methods can be accessed - - // #if !FABLE_COMPILER - // open FSharp.Reflection - // open Newtonsoft.Json - // open Newtonsoft.Json.Linq - - // type UnionTypeInfoConverter() = - // inherit JsonConverter() - // override x.CanConvert t = FSharpType.IsUnion t - // override x.ReadJson(reader, t, _, serializer) = - // let token = JObject() - // for prop in JToken.ReadFrom(reader).Children() do - // if prop.Name <> "$type" then - // token.Add(prop) - // token.ToObject(t) - // override x.WriteJson(writer, v, serializer) = - // let t = v.GetType() - // let typeFulName = t.FullName.Substring(0, t.FullName.LastIndexOf("+")) - // let uci, fields = FSharpValue.GetUnionFields(v, t) - // writer.WriteStartObject() - // writer.WritePropertyName("$type") - // writer.WriteValue(typeFulName) - // writer.WritePropertyName("Case") - // writer.WriteValue(uci.Name) - // writer.WritePropertyName("Fields") - // writer.WriteStartArray() - // for field in fields do writer.WriteValue(field) - // writer.WriteEndArray() - // writer.WriteEndObject() - // #endif - - // testCase "Unions serialized with Json.NET can be deserialized" <| fun () -> - // #if FABLE_COMPILER - // let json = """{"$type":"Fable.Tests.UnionTypes+Tree","Leaf":5}""" - // let x2 = Fable.Core.JsInterop.ofJsonWithTypeInfo json - // #else - // let x = Leaf 5 - // let settings = - // JsonSerializerSettings( - // Converters = [|UnionTypeInfoConverter()|], - // TypeNameHandling = TypeNameHandling.All) - // let json = JsonConvert.SerializeObject(x, settings) - // let x2 = JsonConvert.DeserializeObject(json, settings) - // #endif - // x2.Sum() |> equal 5 - testCase "Types can have Exception fields" <| fun () -> let (MyExUnionCase ex) = try diff --git a/tests/Main/UriTests.fs b/tests/Main/UriTests.fs index bf540d1044..71f406c120 100644 --- a/tests/Main/UriTests.fs +++ b/tests/Main/UriTests.fs @@ -30,7 +30,7 @@ let tests = let uri = Uri("/hello.html", UriKind.Relative) equal false uri.IsAbsoluteUri - testCase "Uri from relative uri string without uri kind should throws" <| fun _ -> + testCase "Uri from relative uri string without uri kind should throws" <| fun _ -> let createInvalidUri () = Uri("hello.html") @@ -58,4 +58,9 @@ let tests = equal "/hello?a=b" newUri.PathAndQuery equal "?a=b" newUri.Query equal "#c" newUri.Fragment + + testCase "Uri.ToString works" <| fun _ -> + let uri = Uri("HTTP://www.test4.com:80/a%20b%20c.html") + uri.ToString() |> equal "http://www.test4.com/a b c.html" + sprintf "%A" uri |> equal "http://www.test4.com/a b c.html" ] diff --git a/tests/Main/Util/Thoth.Json.Decode.fs b/tests/Main/Util/Thoth.Json.Decode.fs index 7799498f38..016f2a55a1 100644 --- a/tests/Main/Util/Thoth.Json.Decode.fs +++ b/tests/Main/Util/Thoth.Json.Decode.fs @@ -13,12 +13,12 @@ module Helpers = let inline isNumber (o: obj) : bool = jsTypeof o = "number" - let inline isArray (o: obj) : bool = JS.Array.isArray(o) + let inline isArray (o: obj) : bool = JS.Constructors.Array.isArray(o) [] let isObject (_ : obj) : bool = jsNative - let inline isNaN (o: obj) : bool = JS.Number.isNaN(!!o) + let inline isNaN (o: obj) : bool = JS.Constructors.Number.isNaN(!!o) [] let isValidIntRange (_: obj) : bool = jsNative @@ -34,7 +34,7 @@ module Helpers = let inline isFunction (o: obj) : bool = jsTypeof o = "function" - let inline objectKeys (o: obj) : string seq = upcast JS.Object.keys(o) + let inline objectKeys (o: obj) : string seq = upcast JS.Constructors.Object.keys(o) type ErrorReason = | BadPrimitive of string * obj diff --git a/tests/Main/Util/Util.fs b/tests/Main/Util/Util.fs index 229d2148fb..afd391762e 100644 --- a/tests/Main/Util/Util.fs +++ b/tests/Main/Util/Util.fs @@ -4,12 +4,16 @@ open System module Testing = #if FABLE_COMPILER + type TestKind = + | TestList of string * TestKind seq + | TestCase of (string*obj) + open Fable.Core open Fable.Core.Testing - let testList (name: string) (tests: (string * obj) seq) = name, tests - let testCase (msg: string) (test: unit->unit) = msg, box test - let testCaseAsync (msg: string) (test: unit->Async) = msg, box(fun () -> test () |> Async.StartAsPromise) + let testList (name: string) (tests: TestKind seq) = TestList( name, tests ) + let testCase (msg: string) (test: unit->unit) = TestCase( msg, box test ) + let testCaseAsync (msg: string) (test: unit->Async) = TestCase( msg, box(fun () -> test () |> Async.StartAsPromise) ) let equal expected actual: unit = Assert.AreEqual(actual, expected) let notEqual expected actual: unit = Assert.NotEqual(actual, expected) diff --git a/tests/splitter.config.js b/tests/splitter.config.js index 7bcd00bf8c..ed4253d1b2 100644 --- a/tests/splitter.config.js +++ b/tests/splitter.config.js @@ -1,19 +1,7 @@ -const path = require("path"); - -module.exports = { - cli: { path: resolve("../src/Fable.Cli") }, - entry: resolve("Main/Fable.Tests.fsproj"), - outDir: resolve("../build/tests"), - fable: { define: defineConstants() }, - babel: { - plugins: ["@babel/plugin-transform-modules-commonjs"], - // presets: [ ["@babel/preset-env", {"modules": false}] ] - }, - // allFiles: true -}; +const resolve = (path) => require("path").join(__dirname, path); function defineConstants() { - var ar = ["DEBUG"]; + var ar = [] // ["DEBUG"]; if (process.env.APPVEYOR) { console.log("Running on APPVEYOR..."); ar.push("APPVEYOR"); @@ -29,6 +17,15 @@ function defineConstants() { return ar; } -function resolve(p) { - return path.join(__dirname, p); -} \ No newline at end of file +module.exports = { + cli: { path: resolve("../src/Fable.Cli") }, + entry: resolve("Main/Fable.Tests.fsproj"), + outDir: resolve("../build/tests"), + fable: { define: defineConstants() }, + babel: { + plugins: ["@babel/plugin-transform-modules-commonjs"], + sourceMaps: true, + // presets: [ ["@babel/preset-env", {"modules": false}] ] + }, + // allFiles: true +};